9965f5c06bf2d21f853bb6d1bfedda0cbf3d98a3
[wimlib] / src / write.c
1 /*
2  * write.c
3  *
4  * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5  * compressed file resources, etc.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #include "config.h"
28
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "list.h" so that "list.h" can
31  * overwrite the LIST_HEAD macro. */
32 #  include <sys/file.h>
33 #endif
34
35 #ifdef __WIN32__
36 #  include "win32.h"
37 #endif
38
39 #include "list.h"
40 #include "wimlib_internal.h"
41 #include "buffer_io.h"
42 #include "dentry.h"
43 #include "lookup_table.h"
44 #include "xml.h"
45
46 #ifdef ENABLE_MULTITHREADED_COMPRESSION
47 #  include <pthread.h>
48 #endif
49
50 #include <unistd.h>
51 #include <errno.h>
52
53 #ifdef WITH_NTFS_3G
54 #  include <time.h>
55 #  include <ntfs-3g/attrib.h>
56 #  include <ntfs-3g/inode.h>
57 #  include <ntfs-3g/dir.h>
58 #endif
59
60 #ifdef HAVE_ALLOCA_H
61 #  include <alloca.h>
62 #else
63 #  include <stdlib.h>
64 #endif
65
66 #include <limits.h>
67
68 #include <sys/uio.h> /* writev() */
69
70 /* Chunk table that's located at the beginning of each compressed resource in
71  * the WIM.  (This is not the on-disk format; the on-disk format just has an
72  * array of offsets.) */
73 struct chunk_table {
74         off_t file_offset;
75         u64 num_chunks;
76         u64 original_resource_size;
77         u64 bytes_per_chunk_entry;
78         u64 table_disk_size;
79         u64 cur_offset;
80         u64 *cur_offset_p;
81         u64 offsets[0];
82 };
83
84 /*
85  * Allocates and initializes a chunk table, and reserves space for it in the
86  * output file.
87  */
88 static int
89 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
90                              int out_fd,
91                              off_t file_offset,
92                              struct chunk_table **chunk_tab_ret)
93 {
94         u64 size = wim_resource_size(lte);
95         u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
96         size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
97         struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
98
99         DEBUG("Begin chunk table for stream with size %"PRIu64, size);
100
101         if (!chunk_tab) {
102                 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
103                       "resource", size);
104                 return WIMLIB_ERR_NOMEM;
105         }
106         chunk_tab->file_offset = file_offset;
107         chunk_tab->num_chunks = num_chunks;
108         chunk_tab->original_resource_size = size;
109         chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
110         chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
111                                      (num_chunks - 1);
112         chunk_tab->cur_offset = 0;
113         chunk_tab->cur_offset_p = chunk_tab->offsets;
114
115         if (full_write(out_fd, chunk_tab,
116                        chunk_tab->table_disk_size) != chunk_tab->table_disk_size)
117         {
118                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
119                                  "file resource");
120                 FREE(chunk_tab);
121                 return WIMLIB_ERR_WRITE;
122         }
123         *chunk_tab_ret = chunk_tab;
124         return 0;
125 }
126
127 /*
128  * compress_func_t- Pointer to a function to compresses a chunk
129  *                  of a WIM resource.  This may be either
130  *                  wimlib_xpress_compress() (xpress-compress.c) or
131  *                  wimlib_lzx_compress() (lzx-compress.c).
132  *
133  * @chunk:        Uncompressed data of the chunk.
134  * @chunk_size:   Size of the uncompressed chunk, in bytes.
135  * @out:          Pointer to output buffer of size at least (@chunk_size - 1) bytes.
136  *
137  * Returns the size of the compressed data written to @out in bytes, or 0 if the
138  * data could not be compressed to (@chunk_size - 1) bytes or fewer.
139  *
140  * As a special requirement, the compression code is optimized for the WIM
141  * format and therefore requires (@chunk_size <= 32768).
142  *
143  * As another special requirement, the compression code will read up to 8 bytes
144  * off the end of the @chunk array for performance reasons.  The values of these
145  * bytes will not affect the output of the compression, but the calling code
146  * must make sure that the buffer holding the uncompressed chunk is actually at
147  * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
148  * mapped memory that will not cause a memory access violation if accessed.
149  */
150 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
151                                     void *out);
152
153 static compress_func_t
154 get_compress_func(int out_ctype)
155 {
156         if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
157                 return wimlib_lzx_compress;
158         else
159                 return wimlib_xpress_compress;
160 }
161
162 /*
163  * Writes a chunk of a WIM resource to an output file.
164  *
165  * @chunk:        Uncompressed data of the chunk.
166  * @chunk_size:   Size of the chunk (<= WIM_CHUNK_SIZE)
167  * @out_fd:       FILE descriptor to write the chunk to.
168  * @compress:     Compression function to use (NULL if writing uncompressed
169  *                      data).
170  * @chunk_tab:    Pointer to chunk table being created.  It is updated with the
171  *                      offset of the chunk we write.
172  *
173  * Returns 0 on success; nonzero on failure.
174  */
175 static int
176 write_wim_resource_chunk(const void * restrict chunk,
177                          unsigned chunk_size,
178                          filedes_t out_fd,
179                          compress_func_t compress,
180                          struct chunk_table * restrict chunk_tab)
181 {
182         const void *out_chunk;
183         unsigned out_chunk_size;
184         if (compress) {
185                 void *compressed_chunk = alloca(chunk_size);
186
187                 out_chunk_size = (*compress)(chunk, chunk_size, compressed_chunk);
188                 if (out_chunk_size) {
189                         /* Write compressed */
190                         out_chunk = compressed_chunk;
191                 } else {
192                         /* Write uncompressed */
193                         out_chunk = chunk;
194                         out_chunk_size = chunk_size;
195                 }
196                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
197                 chunk_tab->cur_offset += out_chunk_size;
198         } else {
199                 /* Write uncompressed */
200                 out_chunk = chunk;
201                 out_chunk_size = chunk_size;
202         }
203         if (full_write(out_fd, out_chunk, out_chunk_size) != out_chunk_size) {
204                 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
205                 return WIMLIB_ERR_WRITE;
206         }
207         return 0;
208 }
209
210 /*
211  * Finishes a WIM chunk table and writes it to the output file at the correct
212  * offset.
213  *
214  * The final size of the full compressed resource is returned in the
215  * @compressed_size_p.
216  */
217 static int
218 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
219                               filedes_t out_fd, u64 *compressed_size_p)
220 {
221         size_t bytes_written;
222
223         if (chunk_tab->bytes_per_chunk_entry == 8) {
224                 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
225         } else {
226                 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
227                         ((u32*)chunk_tab->offsets)[i] =
228                                 cpu_to_le32(chunk_tab->offsets[i]);
229         }
230         bytes_written = full_pwrite(out_fd,
231                                     (u8*)chunk_tab->offsets + chunk_tab->bytes_per_chunk_entry,
232                                     chunk_tab->table_disk_size,
233                                     chunk_tab->file_offset);
234         if (bytes_written != chunk_tab->table_disk_size) {
235                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
236                                  "file resource");
237                 return WIMLIB_ERR_WRITE;
238         }
239         *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
240         return 0;
241 }
242
243 static int
244 seek_and_truncate(filedes_t out_fd, off_t offset)
245 {
246         if (lseek(out_fd, offset, SEEK_SET) == -1 ||
247             ftruncate(out_fd, offset))
248         {
249                 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
250                 return WIMLIB_ERR_WRITE;
251         } else {
252                 return 0;
253         }
254 }
255
256 static int
257 finalize_and_check_sha1(SHA_CTX * restrict sha_ctx,
258                         struct wim_lookup_table_entry * restrict lte)
259 {
260         u8 md[SHA1_HASH_SIZE];
261         sha1_final(md, sha_ctx);
262         if (lte->unhashed) {
263                 copy_hash(lte->hash, md);
264         } else if (!hashes_equal(md, lte->hash)) {
265                 ERROR("WIM resource has incorrect hash!");
266                 if (lte_filename_valid(lte)) {
267                         ERROR("We were reading it from \"%"TS"\"; maybe "
268                               "it changed while we were reading it.",
269                               lte->file_on_disk);
270                 }
271                 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
272         }
273         return 0;
274 }
275
276
277 struct write_resource_ctx {
278         compress_func_t compress;
279         struct chunk_table *chunk_tab;
280         filedes_t out_fd;
281         SHA_CTX sha_ctx;
282         bool doing_sha;
283 };
284
285 static int
286 write_resource_cb(const void *restrict chunk, size_t chunk_size,
287                   void *restrict _ctx)
288 {
289         struct write_resource_ctx *ctx = _ctx;
290
291         if (ctx->doing_sha)
292                 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
293         return write_wim_resource_chunk(chunk, chunk_size,
294                                         ctx->out_fd, ctx->compress,
295                                         ctx->chunk_tab);
296 }
297
298 /*
299  * Write a resource to an output WIM.
300  *
301  * @lte:  Lookup table entry for the resource, which could be in another WIM,
302  *        in an external file, or in another location.
303  *
304  * @out_fp:  File descriptor opened to the output WIM.
305  *
306  * @out_ctype:  One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
307  *              which compression algorithm to use.
308  *
309  * @out_res_entry:  On success, this is filled in with the offset, flags,
310  *                  compressed size, and uncompressed size of the resource
311  *                  in the output WIM.
312  *
313  * @flags:  WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
314  *          even if it could otherwise be copied directly from the input.
315  *
316  * Additional notes:  The SHA1 message digest of the uncompressed data is
317  * calculated (except when doing a raw copy --- see below).  If the @unhashed
318  * flag is set on the lookup table entry, this message digest is simply copied
319  * to it; otherwise, the message digest is compared with the existing one, and
320  * the function will fail if they do not match.
321  */
322 int
323 write_wim_resource(struct wim_lookup_table_entry *lte,
324                    filedes_t out_fd, int out_ctype,
325                    struct resource_entry *out_res_entry,
326                    int flags)
327 {
328         struct write_resource_ctx write_ctx;
329         u64 read_size;
330         u64 new_size;
331         off_t offset;
332         int ret;
333
334         flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
335
336         /* Get current position in output WIM */
337         offset = filedes_offset(out_fd);
338         if (offset == -1) {
339                 ERROR_WITH_ERRNO("Can't get position in output WIM");
340                 return WIMLIB_ERR_WRITE;
341         }
342
343         /* If we are not forcing the data to be recompressed, and the input
344          * resource is located in a WIM with the same compression type as that
345          * desired other than no compression, we can simply copy the compressed
346          * data without recompressing it.  This also means we must skip
347          * calculating the SHA1, as we never will see the uncompressed data. */
348         if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
349             lte->resource_location == RESOURCE_IN_WIM &&
350             out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
351             wimlib_get_compression_type(lte->wim) == out_ctype)
352         {
353                 flags |= WIMLIB_RESOURCE_FLAG_RAW;
354                 write_ctx.doing_sha = false;
355                 read_size = lte->resource_entry.size;
356         } else {
357                 write_ctx.doing_sha = true;
358                 sha1_init(&write_ctx.sha_ctx);
359                 read_size = lte->resource_entry.original_size;
360         }
361
362         /* Initialize the chunk table and set the compression function if
363          * compressing the resource. */
364         if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
365             (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
366                 write_ctx.compress = NULL;
367                 write_ctx.chunk_tab = NULL;
368         } else {
369                 write_ctx.compress = get_compress_func(out_ctype);
370                 ret = begin_wim_resource_chunk_tab(lte, out_fd,
371                                                    offset,
372                                                    &write_ctx.chunk_tab);
373                 if (ret)
374                         return ret;
375         }
376
377         /* Write the entire resource by reading the entire resource and feeding
378          * the data through the write_resource_cb function. */
379         write_ctx.out_fd = out_fd;
380 try_write_again:
381         ret = read_resource_prefix(lte, read_size,
382                                    write_resource_cb, &write_ctx, flags);
383         if (ret)
384                 goto out_free_chunk_tab;
385
386         /* Verify SHA1 message digest of the resource, or set the hash for the
387          * first time. */
388         if (write_ctx.doing_sha) {
389                 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
390                 if (ret)
391                         goto out_free_chunk_tab;
392         }
393
394         out_res_entry->flags = lte->resource_entry.flags;
395         out_res_entry->original_size = wim_resource_size(lte);
396         out_res_entry->offset = offset;
397         if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
398                 /* Doing a raw write:  The new compressed size is the same as
399                  * the compressed size in the other WIM. */
400                 new_size = lte->resource_entry.size;
401         } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
402                 /* Using WIMLIB_COMPRESSION_TYPE_NONE:  The new compressed size
403                  * is the original size. */
404                 new_size = lte->resource_entry.original_size;
405                 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
406         } else {
407                 /* Using a different compression type:  Call
408                  * finish_wim_resource_chunk_tab() and it will provide the new
409                  * compressed size. */
410                 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fd,
411                                                     &new_size);
412                 if (ret)
413                         goto out_free_chunk_tab;
414                 if (new_size >= wim_resource_size(lte)) {
415                         /* Oops!  We compressed the resource to larger than the original
416                          * size.  Write the resource uncompressed instead. */
417                         DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
418                               "writing uncompressed instead",
419                               wim_resource_size(lte), new_size);
420                         ret = seek_and_truncate(out_fd, offset);
421                         if (ret)
422                                 goto out_free_chunk_tab;
423                         write_ctx.compress = NULL;
424                         write_ctx.doing_sha = false;
425                         out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
426                         goto try_write_again;
427                 }
428                 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
429         }
430         out_res_entry->size = new_size;
431         ret = 0;
432 out_free_chunk_tab:
433         FREE(write_ctx.chunk_tab);
434         return ret;
435 }
436
437 #ifdef ENABLE_MULTITHREADED_COMPRESSION
438
439 /* Blocking shared queue (solves the producer-consumer problem) */
440 struct shared_queue {
441         unsigned size;
442         unsigned front;
443         unsigned back;
444         unsigned filled_slots;
445         void **array;
446         pthread_mutex_t lock;
447         pthread_cond_t msg_avail_cond;
448         pthread_cond_t space_avail_cond;
449 };
450
451 static int
452 shared_queue_init(struct shared_queue *q, unsigned size)
453 {
454         wimlib_assert(size != 0);
455         q->array = CALLOC(sizeof(q->array[0]), size);
456         if (!q->array)
457                 goto err;
458         q->filled_slots = 0;
459         q->front = 0;
460         q->back = size - 1;
461         q->size = size;
462         if (pthread_mutex_init(&q->lock, NULL)) {
463                 ERROR_WITH_ERRNO("Failed to initialize mutex");
464                 goto err;
465         }
466         if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
467                 ERROR_WITH_ERRNO("Failed to initialize condition variable");
468                 goto err_destroy_lock;
469         }
470         if (pthread_cond_init(&q->space_avail_cond, NULL)) {
471                 ERROR_WITH_ERRNO("Failed to initialize condition variable");
472                 goto err_destroy_msg_avail_cond;
473         }
474         return 0;
475 err_destroy_msg_avail_cond:
476         pthread_cond_destroy(&q->msg_avail_cond);
477 err_destroy_lock:
478         pthread_mutex_destroy(&q->lock);
479 err:
480         return WIMLIB_ERR_NOMEM;
481 }
482
483 static void
484 shared_queue_destroy(struct shared_queue *q)
485 {
486         FREE(q->array);
487         pthread_mutex_destroy(&q->lock);
488         pthread_cond_destroy(&q->msg_avail_cond);
489         pthread_cond_destroy(&q->space_avail_cond);
490 }
491
492 static void
493 shared_queue_put(struct shared_queue *q, void *obj)
494 {
495         pthread_mutex_lock(&q->lock);
496         while (q->filled_slots == q->size)
497                 pthread_cond_wait(&q->space_avail_cond, &q->lock);
498
499         q->back = (q->back + 1) % q->size;
500         q->array[q->back] = obj;
501         q->filled_slots++;
502
503         pthread_cond_broadcast(&q->msg_avail_cond);
504         pthread_mutex_unlock(&q->lock);
505 }
506
507 static void *
508 shared_queue_get(struct shared_queue *q)
509 {
510         void *obj;
511
512         pthread_mutex_lock(&q->lock);
513         while (q->filled_slots == 0)
514                 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
515
516         obj = q->array[q->front];
517         q->array[q->front] = NULL;
518         q->front = (q->front + 1) % q->size;
519         q->filled_slots--;
520
521         pthread_cond_broadcast(&q->space_avail_cond);
522         pthread_mutex_unlock(&q->lock);
523         return obj;
524 }
525
526 struct compressor_thread_params {
527         struct shared_queue *res_to_compress_queue;
528         struct shared_queue *compressed_res_queue;
529         compress_func_t compress;
530 };
531
532 #define MAX_CHUNKS_PER_MSG 2
533
534 struct message {
535         struct wim_lookup_table_entry *lte;
536         u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
537         u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
538         unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
539         struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
540         size_t total_out_bytes;
541         unsigned num_chunks;
542         struct list_head list;
543         bool complete;
544         u64 begin_chunk;
545 };
546
547 static void
548 compress_chunks(struct message *msg, compress_func_t compress)
549 {
550         msg->total_out_bytes = 0;
551         for (unsigned i = 0; i < msg->num_chunks; i++) {
552                 unsigned len = compress(msg->uncompressed_chunks[i],
553                                         msg->uncompressed_chunk_sizes[i],
554                                         msg->compressed_chunks[i]);
555                 void *out_chunk;
556                 unsigned out_len;
557                 if (len) {
558                         /* To be written compressed */
559                         out_chunk = msg->compressed_chunks[i];
560                         out_len = len;
561                 } else {
562                         /* To be written uncompressed */
563                         out_chunk = msg->uncompressed_chunks[i];
564                         out_len = msg->uncompressed_chunk_sizes[i];
565                 }
566                 msg->out_chunks[i].iov_base = out_chunk;
567                 msg->out_chunks[i].iov_len = out_len;
568                 msg->total_out_bytes += out_len;
569         }
570 }
571
572 /* Compressor thread routine.  This is a lot simpler than the main thread
573  * routine: just repeatedly get a group of chunks from the
574  * res_to_compress_queue, compress them, and put them in the
575  * compressed_res_queue.  A NULL pointer indicates that the thread should stop.
576  * */
577 static void *
578 compressor_thread_proc(void *arg)
579 {
580         struct compressor_thread_params *params = arg;
581         struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
582         struct shared_queue *compressed_res_queue = params->compressed_res_queue;
583         compress_func_t compress = params->compress;
584         struct message *msg;
585
586         DEBUG("Compressor thread ready");
587         while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
588                 compress_chunks(msg, compress);
589                 shared_queue_put(compressed_res_queue, msg);
590         }
591         DEBUG("Compressor thread terminating");
592         return NULL;
593 }
594 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
595
596 static void
597 do_write_streams_progress(union wimlib_progress_info *progress,
598                           wimlib_progress_func_t progress_func,
599                           uint64_t size_added)
600 {
601         progress->write_streams.completed_bytes += size_added;
602         progress->write_streams.completed_streams++;
603         if (progress_func &&
604             progress->write_streams.completed_bytes >= progress->write_streams._private)
605         {
606                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
607                               progress);
608                 if (progress->write_streams._private == progress->write_streams.total_bytes) {
609                         progress->write_streams._private = ~0;
610                 } else {
611                         progress->write_streams._private =
612                                 min(progress->write_streams.total_bytes,
613                                     progress->write_streams.completed_bytes +
614                                         progress->write_streams.total_bytes / 100);
615                 }
616         }
617 }
618
619 struct serial_write_stream_ctx {
620         filedes_t out_fd;
621         int out_ctype;
622         int write_resource_flags;
623 };
624
625 static int
626 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
627 {
628         struct serial_write_stream_ctx *ctx = _ctx;
629         return write_wim_resource(lte, ctx->out_fd,
630                                   ctx->out_ctype, &lte->output_resource_entry,
631                                   ctx->write_resource_flags);
632 }
633
634 /* Write a list of streams, taking into account that some streams may be
635  * duplicates that are checksummed and discarded on the fly, and also delegating
636  * the actual writing of a stream to a function @write_stream_cb, which is
637  * passed the context @write_stream_ctx. */
638 static int
639 do_write_stream_list(struct list_head *stream_list,
640                      struct wim_lookup_table *lookup_table,
641                      int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
642                      void *write_stream_ctx,
643                      wimlib_progress_func_t progress_func,
644                      union wimlib_progress_info *progress)
645 {
646         int ret = 0;
647         struct wim_lookup_table_entry *lte;
648
649         /* For each stream in @stream_list ... */
650         while (!list_empty(stream_list)) {
651                 lte = container_of(stream_list->next,
652                                    struct wim_lookup_table_entry,
653                                    write_streams_list);
654                 list_del(&lte->write_streams_list);
655                 if (lte->unhashed && !lte->unique_size) {
656                         /* Unhashed stream that shares a size with some other
657                          * stream in the WIM we are writing.  The stream must be
658                          * checksummed to know if we need to write it or not. */
659                         struct wim_lookup_table_entry *tmp;
660                         u32 orig_refcnt = lte->out_refcnt;
661
662                         ret = hash_unhashed_stream(lte, lookup_table, &tmp);
663                         if (ret)
664                                 break;
665                         if (tmp != lte) {
666                                 lte = tmp;
667                                 /* We found a duplicate stream. */
668                                 if (orig_refcnt != tmp->out_refcnt) {
669                                         /* We have already written, or are going
670                                          * to write, the duplicate stream.  So
671                                          * just skip to the next stream. */
672                                         DEBUG("Discarding duplicate stream of length %"PRIu64,
673                                               wim_resource_size(lte));
674                                         lte->no_progress = 0;
675                                         goto skip_to_progress;
676                                 }
677                         }
678                 }
679
680                 /* Here, @lte is either a hashed stream or an unhashed stream
681                  * with a unique size.  In either case we know that the stream
682                  * has to be written.  In either case the SHA1 message digest
683                  * will be calculated over the stream while writing it; however,
684                  * in the former case this is done merely to check the data,
685                  * while in the latter case this is done because we do not have
686                  * the SHA1 message digest yet.  */
687                 wimlib_assert(lte->out_refcnt != 0);
688                 lte->deferred = 0;
689                 lte->no_progress = 0;
690                 ret = (*write_stream_cb)(lte, write_stream_ctx);
691                 if (ret)
692                         break;
693                 /* In parallel mode, some streams are deferred for later,
694                  * serialized processing; ignore them here. */
695                 if (lte->deferred)
696                         continue;
697                 if (lte->unhashed) {
698                         list_del(&lte->unhashed_list);
699                         lookup_table_insert(lookup_table, lte);
700                         lte->unhashed = 0;
701                 }
702         skip_to_progress:
703                 if (!lte->no_progress) {
704                         do_write_streams_progress(progress,
705                                                   progress_func,
706                                                   wim_resource_size(lte));
707                 }
708         }
709         return ret;
710 }
711
712 static int
713 do_write_stream_list_serial(struct list_head *stream_list,
714                             struct wim_lookup_table *lookup_table,
715                             filedes_t out_fd,
716                             int out_ctype,
717                             int write_resource_flags,
718                             wimlib_progress_func_t progress_func,
719                             union wimlib_progress_info *progress)
720 {
721         struct serial_write_stream_ctx ctx = {
722                 .out_fd = out_fd,
723                 .out_ctype = out_ctype,
724                 .write_resource_flags = write_resource_flags,
725         };
726         return do_write_stream_list(stream_list,
727                                     lookup_table,
728                                     serial_write_stream,
729                                     &ctx,
730                                     progress_func,
731                                     progress);
732 }
733
734 static inline int
735 write_flags_to_resource_flags(int write_flags)
736 {
737         int resource_flags = 0;
738
739         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
740                 resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
741         return resource_flags;
742 }
743
744 static int
745 write_stream_list_serial(struct list_head *stream_list,
746                          struct wim_lookup_table *lookup_table,
747                          filedes_t out_fd,
748                          int out_ctype,
749                          int write_resource_flags,
750                          wimlib_progress_func_t progress_func,
751                          union wimlib_progress_info *progress)
752 {
753         DEBUG("Writing stream list (serial version)");
754         progress->write_streams.num_threads = 1;
755         if (progress_func)
756                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
757         return do_write_stream_list_serial(stream_list,
758                                            lookup_table,
759                                            out_fd,
760                                            out_ctype,
761                                            write_resource_flags,
762                                            progress_func,
763                                            progress);
764 }
765
766 #ifdef ENABLE_MULTITHREADED_COMPRESSION
767 static int
768 write_wim_chunks(struct message *msg, filedes_t out_fd,
769                  struct chunk_table *chunk_tab)
770 {
771         ssize_t bytes_remaining = msg->total_out_bytes;
772         struct iovec *vecs = msg->out_chunks;
773         unsigned nvecs = msg->num_chunks;
774         int ret;
775
776         wimlib_assert(nvecs != 0);
777         wimlib_assert(msg->total_out_bytes != 0);
778
779         for (unsigned i = 0; i < msg->num_chunks; i++) {
780                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
781                 chunk_tab->cur_offset += vecs[i].iov_len;
782         }
783         for (;;) {
784                 ssize_t bytes_written;
785
786                 bytes_written = writev(out_fd, vecs, nvecs);
787                 if (bytes_written <= 0) {
788                         if (bytes_written < 0 && errno == EINTR)
789                                 continue;
790                         else if (bytes_written == 0)
791                                 errno = EIO;
792                         ERROR_WITH_ERRNO("Failed to write WIM chunks");
793                         ret = WIMLIB_ERR_WRITE;
794                         break;
795                 }
796                 bytes_remaining -= bytes_written;
797                 if (bytes_remaining <= 0) {
798                         ret = 0;
799                         break;
800                 }
801                 while (bytes_written >= 0) {
802                         wimlib_assert(nvecs != 0);
803                         if (bytes_written >= vecs[0].iov_len) {
804                                 vecs++;
805                                 nvecs--;
806                                 bytes_written -= vecs[0].iov_len;
807                         } else {
808                                 vecs[0].iov_base += bytes_written;
809                                 vecs[0].iov_len -= bytes_written;
810                                 bytes_written = 0;
811                         }
812                 }
813         }
814         return ret;
815 }
816
817 struct main_writer_thread_ctx {
818         struct list_head *stream_list;
819         struct wim_lookup_table *lookup_table;
820         filedes_t out_fd;
821         int out_ctype;
822         int write_resource_flags;
823         struct shared_queue *res_to_compress_queue;
824         struct shared_queue *compressed_res_queue;
825         size_t num_messages;
826         wimlib_progress_func_t progress_func;
827         union wimlib_progress_info *progress;
828
829         struct list_head available_msgs;
830         struct list_head outstanding_streams;
831         struct list_head serial_streams;
832         size_t num_outstanding_messages;
833
834         SHA_CTX next_sha_ctx;
835         u64 next_chunk;
836         u64 next_num_chunks;
837         struct wim_lookup_table_entry *next_lte;
838
839         struct message *msgs;
840         struct message *next_msg;
841         struct chunk_table *cur_chunk_tab;
842 };
843
844 static int
845 init_message(struct message *msg)
846 {
847         for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
848                 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
849                 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
850                 if (msg->compressed_chunks[i] == NULL ||
851                     msg->uncompressed_chunks[i] == NULL)
852                         return WIMLIB_ERR_NOMEM;
853         }
854         return 0;
855 }
856
857 static void
858 destroy_message(struct message *msg)
859 {
860         for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
861                 FREE(msg->compressed_chunks[i]);
862                 FREE(msg->uncompressed_chunks[i]);
863         }
864 }
865
866 static void
867 free_messages(struct message *msgs, size_t num_messages)
868 {
869         if (msgs) {
870                 for (size_t i = 0; i < num_messages; i++)
871                         destroy_message(&msgs[i]);
872                 FREE(msgs);
873         }
874 }
875
876 static struct message *
877 allocate_messages(size_t num_messages)
878 {
879         struct message *msgs;
880
881         msgs = CALLOC(num_messages, sizeof(struct message));
882         if (!msgs)
883                 return NULL;
884         for (size_t i = 0; i < num_messages; i++) {
885                 if (init_message(&msgs[i])) {
886                         free_messages(msgs, num_messages);
887                         return NULL;
888                 }
889         }
890         return msgs;
891 }
892
893 static void
894 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
895 {
896         while (ctx->num_outstanding_messages--)
897                 shared_queue_get(ctx->compressed_res_queue);
898         free_messages(ctx->msgs, ctx->num_messages);
899         FREE(ctx->cur_chunk_tab);
900 }
901
902 static int
903 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
904 {
905         /* Pre-allocate all the buffers that will be needed to do the chunk
906          * compression. */
907         ctx->msgs = allocate_messages(ctx->num_messages);
908         if (!ctx->msgs)
909                 return WIMLIB_ERR_NOMEM;
910
911         /* Initially, all the messages are available to use. */
912         INIT_LIST_HEAD(&ctx->available_msgs);
913         for (size_t i = 0; i < ctx->num_messages; i++)
914                 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
915
916         /* outstanding_streams is the list of streams that currently have had
917          * chunks sent off for compression.
918          *
919          * The first stream in outstanding_streams is the stream that is
920          * currently being written.
921          *
922          * The last stream in outstanding_streams is the stream that is
923          * currently being read and having chunks fed to the compressor threads.
924          * */
925         INIT_LIST_HEAD(&ctx->outstanding_streams);
926         ctx->num_outstanding_messages = 0;
927
928         ctx->next_msg = NULL;
929
930         /* Resources that don't need any chunks compressed are added to this
931          * list and written directly by the main thread. */
932         INIT_LIST_HEAD(&ctx->serial_streams);
933
934         ctx->cur_chunk_tab = NULL;
935
936         return 0;
937 }
938
939 static int
940 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
941 {
942         struct message *msg;
943         struct wim_lookup_table_entry *cur_lte;
944         int ret;
945
946         wimlib_assert(!list_empty(&ctx->outstanding_streams));
947         wimlib_assert(ctx->num_outstanding_messages != 0);
948
949         cur_lte = container_of(ctx->outstanding_streams.next,
950                                struct wim_lookup_table_entry,
951                                being_compressed_list);
952
953         /* Get the next message from the queue and process it.
954          * The message will contain 1 or more data chunks that have been
955          * compressed. */
956         msg = shared_queue_get(ctx->compressed_res_queue);
957         msg->complete = true;
958         --ctx->num_outstanding_messages;
959
960         /* Is this the next chunk in the current resource?  If it's not
961          * (i.e., an earlier chunk in a same or different resource
962          * hasn't been compressed yet), do nothing, and keep this
963          * message around until all earlier chunks are received.
964          *
965          * Otherwise, write all the chunks we can. */
966         while (cur_lte != NULL &&
967                !list_empty(&cur_lte->msg_list)
968                && (msg = container_of(cur_lte->msg_list.next,
969                                       struct message,
970                                       list))->complete)
971         {
972                 list_move(&msg->list, &ctx->available_msgs);
973                 if (msg->begin_chunk == 0) {
974                         /* This is the first set of chunks.  Leave space
975                          * for the chunk table in the output file. */
976                         off_t cur_offset = filedes_offset(ctx->out_fd);
977                         if (cur_offset == -1)
978                                 return WIMLIB_ERR_WRITE;
979                         ret = begin_wim_resource_chunk_tab(cur_lte,
980                                                            ctx->out_fd,
981                                                            cur_offset,
982                                                            &ctx->cur_chunk_tab);
983                         if (ret)
984                                 return ret;
985                 }
986
987                 /* Write the compressed chunks from the message. */
988                 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab);
989                 if (ret)
990                         return ret;
991
992                 /* Was this the last chunk of the stream?  If so, finish
993                  * it. */
994                 if (list_empty(&cur_lte->msg_list) &&
995                     msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
996                 {
997                         u64 res_csize;
998                         off_t offset;
999
1000                         ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1001                                                             ctx->out_fd,
1002                                                             &res_csize);
1003                         if (ret)
1004                                 return ret;
1005
1006                         list_del(&cur_lte->being_compressed_list);
1007
1008                         /* Grab the offset of this stream in the output file
1009                          * from the chunk table before we free it. */
1010                         offset = ctx->cur_chunk_tab->file_offset;
1011
1012                         FREE(ctx->cur_chunk_tab);
1013                         ctx->cur_chunk_tab = NULL;
1014
1015                         if (res_csize >= wim_resource_size(cur_lte)) {
1016                                 /* Oops!  We compressed the resource to
1017                                  * larger than the original size.  Write
1018                                  * the resource uncompressed instead. */
1019                                 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1020                                       "writing uncompressed instead",
1021                                       wim_resource_size(cur_lte), res_csize);
1022                                 ret = seek_and_truncate(ctx->out_fd, offset);
1023                                 if (ret)
1024                                         return ret;
1025                                 ret = write_wim_resource(cur_lte,
1026                                                          ctx->out_fd,
1027                                                          WIMLIB_COMPRESSION_TYPE_NONE,
1028                                                          &cur_lte->output_resource_entry,
1029                                                          ctx->write_resource_flags);
1030                                 if (ret)
1031                                         return ret;
1032                         } else {
1033                                 cur_lte->output_resource_entry.size =
1034                                         res_csize;
1035
1036                                 cur_lte->output_resource_entry.original_size =
1037                                         cur_lte->resource_entry.original_size;
1038
1039                                 cur_lte->output_resource_entry.offset =
1040                                         offset;
1041
1042                                 cur_lte->output_resource_entry.flags =
1043                                         cur_lte->resource_entry.flags |
1044                                                 WIM_RESHDR_FLAG_COMPRESSED;
1045                         }
1046
1047                         do_write_streams_progress(ctx->progress,
1048                                                   ctx->progress_func,
1049                                                   wim_resource_size(cur_lte));
1050
1051                         /* Since we just finished writing a stream, write any
1052                          * streams that have been added to the serial_streams
1053                          * list for direct writing by the main thread (e.g.
1054                          * resources that don't need to be compressed because
1055                          * the desired compression type is the same as the
1056                          * previous compression type). */
1057                         if (!list_empty(&ctx->serial_streams)) {
1058                                 ret = do_write_stream_list_serial(&ctx->serial_streams,
1059                                                                   ctx->lookup_table,
1060                                                                   ctx->out_fd,
1061                                                                   ctx->out_ctype,
1062                                                                   ctx->write_resource_flags,
1063                                                                   ctx->progress_func,
1064                                                                   ctx->progress);
1065                                 if (ret)
1066                                         return ret;
1067                         }
1068
1069                         /* Advance to the next stream to write. */
1070                         if (list_empty(&ctx->outstanding_streams)) {
1071                                 cur_lte = NULL;
1072                         } else {
1073                                 cur_lte = container_of(ctx->outstanding_streams.next,
1074                                                        struct wim_lookup_table_entry,
1075                                                        being_compressed_list);
1076                         }
1077                 }
1078         }
1079         return 0;
1080 }
1081
1082 /* Called when the main thread has read a new chunk of data. */
1083 static int
1084 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1085 {
1086         struct main_writer_thread_ctx *ctx = _ctx;
1087         int ret;
1088         struct message *next_msg;
1089         u64 next_chunk_in_msg;
1090
1091         /* Update SHA1 message digest for the stream currently being read by the
1092          * main thread. */
1093         sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1094
1095         /* We send chunks of data to the compressor chunks in batches which we
1096          * refer to as "messages".  @next_msg is the message that is currently
1097          * being prepared to send off.  If it is NULL, that indicates that we
1098          * need to start a new message. */
1099         next_msg = ctx->next_msg;
1100         if (!next_msg) {
1101                 /* We need to start a new message.  First check to see if there
1102                  * is a message available in the list of available messages.  If
1103                  * so, we can just take one.  If not, all the messages (there is
1104                  * a fixed number of them, proportional to the number of
1105                  * threads) have been sent off to the compressor threads, so we
1106                  * receive messages from the compressor threads containing
1107                  * compressed chunks of data.
1108                  *
1109                  * We may need to receive multiple messages before one is
1110                  * actually available to use because messages received that are
1111                  * *not* for the very next set of chunks to compress must be
1112                  * buffered until it's time to write those chunks. */
1113                 while (list_empty(&ctx->available_msgs)) {
1114                         ret = receive_compressed_chunks(ctx);
1115                         if (ret)
1116                                 return ret;
1117                 }
1118
1119                 next_msg = container_of(ctx->available_msgs.next,
1120                                         struct message, list);
1121                 list_del(&next_msg->list);
1122                 next_msg->complete = false;
1123                 next_msg->begin_chunk = ctx->next_chunk;
1124                 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1125                                            ctx->next_num_chunks - ctx->next_chunk);
1126                 ctx->next_msg = next_msg;
1127         }
1128
1129         /* Fill in the next chunk to compress */
1130         next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1131
1132         next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1133         memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1134                chunk, chunk_size);
1135         ctx->next_chunk++;
1136         if (++next_chunk_in_msg == next_msg->num_chunks) {
1137                 /* Send off an array of chunks to compress */
1138                 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1139                 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1140                 ++ctx->num_outstanding_messages;
1141                 ctx->next_msg = NULL;
1142         }
1143         return 0;
1144 }
1145
1146 static int
1147 main_writer_thread_finish(void *_ctx)
1148 {
1149         struct main_writer_thread_ctx *ctx = _ctx;
1150         int ret;
1151         while (ctx->num_outstanding_messages != 0) {
1152                 ret = receive_compressed_chunks(ctx);
1153                 if (ret)
1154                         return ret;
1155         }
1156         wimlib_assert(list_empty(&ctx->outstanding_streams));
1157         return do_write_stream_list_serial(&ctx->serial_streams,
1158                                            ctx->lookup_table,
1159                                            ctx->out_fd,
1160                                            ctx->out_ctype,
1161                                            ctx->write_resource_flags,
1162                                            ctx->progress_func,
1163                                            ctx->progress);
1164 }
1165
1166 static int
1167 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1168                               struct main_writer_thread_ctx *ctx)
1169 {
1170         int ret;
1171
1172         /* Read the entire stream @lte, feeding its data chunks to the
1173          * compressor threads.  Also SHA1-sum the stream; this is required in
1174          * the case that @lte is unhashed, and a nice additional verification
1175          * when @lte is already hashed. */
1176         sha1_init(&ctx->next_sha_ctx);
1177         ctx->next_chunk = 0;
1178         ctx->next_num_chunks = wim_resource_chunks(lte);
1179         ctx->next_lte = lte;
1180         INIT_LIST_HEAD(&lte->msg_list);
1181         list_add_tail(&lte->being_compressed_list, &ctx->outstanding_streams);
1182         ret = read_resource_prefix(lte, wim_resource_size(lte),
1183                                    main_writer_thread_cb, ctx, 0);
1184         if (ret == 0) {
1185                 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1186                 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1187         }
1188         return ret;
1189 }
1190
1191 static int
1192 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1193 {
1194         struct main_writer_thread_ctx *ctx = _ctx;
1195         int ret;
1196
1197         if (wim_resource_size(lte) < 1000 ||
1198             ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1199             (lte->resource_location == RESOURCE_IN_WIM &&
1200              !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1201              wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
1202         {
1203                 /* Stream is too small or isn't being compressed.  Process it by
1204                  * the main thread when we have a chance.  We can't necessarily
1205                  * process it right here, as the main thread could be in the
1206                  * middle of writing a different stream. */
1207                 list_add_tail(&lte->write_streams_list, &ctx->serial_streams);
1208                 lte->deferred = 1;
1209                 ret = 0;
1210         } else {
1211                 ret = submit_stream_for_compression(lte, ctx);
1212         }
1213         lte->no_progress = 1;
1214         return ret;
1215 }
1216
1217 static long
1218 get_default_num_threads()
1219 {
1220 #ifdef __WIN32__
1221         return win32_get_number_of_processors();
1222 #else
1223         return sysconf(_SC_NPROCESSORS_ONLN);
1224 #endif
1225 }
1226
1227 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1228  * parameter and will perform compression using that many threads.  Falls
1229  * back to write_stream_list_serial() on certain errors, such as a failure to
1230  * create the number of threads requested.
1231  *
1232  * High level description of the algorithm for writing compressed streams in
1233  * parallel:  We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1234  * rather than on full files.  The currently executing thread becomes the main
1235  * thread and is entirely in charge of reading the data to compress (which may
1236  * be in any location understood by the resource code--- such as in an external
1237  * file being captured, or in another WIM file from which an image is being
1238  * exported) and actually writing the compressed data to the output file.
1239  * Additional threads are "compressor threads" and all execute the
1240  * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1241  * the main thread, compress them, and hand them back to the main thread.
1242  *
1243  * Certain streams, such as streams that do not need to be compressed (e.g.
1244  * input compression type same as output compression type) or streams of very
1245  * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1246  * handled entirely by the main thread at an appropriate time.
1247  *
1248  * At any given point in time, multiple streams may be having chunks compressed
1249  * concurrently.  The stream that the main thread is currently *reading* may be
1250  * later in the list that the stream that the main thread is currently
1251  * *writing*.
1252  */
1253 static int
1254 write_stream_list_parallel(struct list_head *stream_list,
1255                            struct wim_lookup_table *lookup_table,
1256                            filedes_t out_fd,
1257                            int out_ctype,
1258                            int write_resource_flags,
1259                            wimlib_progress_func_t progress_func,
1260                            union wimlib_progress_info *progress,
1261                            unsigned num_threads)
1262 {
1263         int ret;
1264         struct shared_queue res_to_compress_queue;
1265         struct shared_queue compressed_res_queue;
1266         pthread_t *compressor_threads = NULL;
1267
1268         if (num_threads == 0) {
1269                 long nthreads = get_default_num_threads();
1270                 if (nthreads < 1 || nthreads > UINT_MAX) {
1271                         WARNING("Could not determine number of processors! Assuming 1");
1272                         goto out_serial;
1273                 } else if (nthreads == 1) {
1274                         goto out_serial_quiet;
1275                 } else {
1276                         num_threads = nthreads;
1277                 }
1278         }
1279
1280         DEBUG("Writing stream list (parallel version, num_threads=%u)",
1281               num_threads);
1282
1283         progress->write_streams.num_threads = num_threads;
1284
1285         static const size_t MESSAGES_PER_THREAD = 2;
1286         size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1287
1288         DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1289
1290         ret = shared_queue_init(&res_to_compress_queue, queue_size);
1291         if (ret)
1292                 goto out_serial;
1293
1294         ret = shared_queue_init(&compressed_res_queue, queue_size);
1295         if (ret)
1296                 goto out_destroy_res_to_compress_queue;
1297
1298         struct compressor_thread_params params;
1299         params.res_to_compress_queue = &res_to_compress_queue;
1300         params.compressed_res_queue = &compressed_res_queue;
1301         params.compress = get_compress_func(out_ctype);
1302
1303         compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1304         if (!compressor_threads) {
1305                 ret = WIMLIB_ERR_NOMEM;
1306                 goto out_destroy_compressed_res_queue;
1307         }
1308
1309         for (unsigned i = 0; i < num_threads; i++) {
1310                 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1311                 ret = pthread_create(&compressor_threads[i], NULL,
1312                                      compressor_thread_proc, &params);
1313                 if (ret != 0) {
1314                         ret = -1;
1315                         ERROR_WITH_ERRNO("Failed to create compressor "
1316                                          "thread %u of %u",
1317                                          i + 1, num_threads);
1318                         num_threads = i;
1319                         goto out_join;
1320                 }
1321         }
1322
1323         if (progress_func)
1324                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1325
1326         struct main_writer_thread_ctx ctx;
1327         ctx.stream_list           = stream_list;
1328         ctx.lookup_table          = lookup_table;
1329         ctx.out_fd                = out_fd;
1330         ctx.out_ctype             = out_ctype;
1331         ctx.res_to_compress_queue = &res_to_compress_queue;
1332         ctx.compressed_res_queue  = &compressed_res_queue;
1333         ctx.num_messages          = queue_size;
1334         ctx.write_resource_flags  = write_resource_flags;
1335         ctx.progress_func         = progress_func;
1336         ctx.progress              = progress;
1337         ret = main_writer_thread_init_ctx(&ctx);
1338         if (ret)
1339                 goto out_join;
1340         ret = do_write_stream_list(stream_list, lookup_table,
1341                                    main_thread_process_next_stream,
1342                                    &ctx, progress_func, progress);
1343         if (ret)
1344                 goto out_destroy_ctx;
1345
1346         /* The main thread has finished reading all streams that are going to be
1347          * compressed in parallel, and it now needs to wait for all remaining
1348          * chunks to be compressed so that the remaining streams can actually be
1349          * written to the output file.  Furthermore, any remaining streams that
1350          * had processing deferred to the main thread need to be handled.  These
1351          * tasks are done by the main_writer_thread_finish() function. */
1352         ret = main_writer_thread_finish(&ctx);
1353 out_destroy_ctx:
1354         main_writer_thread_destroy_ctx(&ctx);
1355 out_join:
1356         for (unsigned i = 0; i < num_threads; i++)
1357                 shared_queue_put(&res_to_compress_queue, NULL);
1358
1359         for (unsigned i = 0; i < num_threads; i++) {
1360                 if (pthread_join(compressor_threads[i], NULL)) {
1361                         WARNING_WITH_ERRNO("Failed to join compressor "
1362                                            "thread %u of %u",
1363                                            i + 1, num_threads);
1364                 }
1365         }
1366         FREE(compressor_threads);
1367 out_destroy_compressed_res_queue:
1368         shared_queue_destroy(&compressed_res_queue);
1369 out_destroy_res_to_compress_queue:
1370         shared_queue_destroy(&res_to_compress_queue);
1371         if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1372                 return ret;
1373 out_serial:
1374         WARNING("Falling back to single-threaded compression");
1375 out_serial_quiet:
1376         return write_stream_list_serial(stream_list,
1377                                         lookup_table,
1378                                         out_fd,
1379                                         out_ctype,
1380                                         write_resource_flags,
1381                                         progress_func,
1382                                         progress);
1383
1384 }
1385 #endif
1386
1387 /*
1388  * Write a list of streams to a WIM (@out_fd) using the compression type
1389  * @out_ctype and up to @num_threads compressor threads.
1390  */
1391 static int
1392 write_stream_list(struct list_head *stream_list,
1393                   struct wim_lookup_table *lookup_table,
1394                   filedes_t out_fd, int out_ctype, int write_flags,
1395                   unsigned num_threads, wimlib_progress_func_t progress_func)
1396 {
1397         struct wim_lookup_table_entry *lte;
1398         size_t num_streams = 0;
1399         u64 total_bytes = 0;
1400         u64 total_compression_bytes = 0;
1401         union wimlib_progress_info progress;
1402         int ret;
1403         int write_resource_flags;
1404
1405         if (list_empty(stream_list))
1406                 return 0;
1407
1408         write_resource_flags = write_flags_to_resource_flags(write_flags);
1409
1410         /* Calculate the total size of the streams to be written.  Note: this
1411          * will be the uncompressed size, as we may not know the compressed size
1412          * yet, and also this will assume that every unhashed stream will be
1413          * written (which will not necessarily be the case). */
1414         list_for_each_entry(lte, stream_list, write_streams_list) {
1415                 num_streams++;
1416                 total_bytes += wim_resource_size(lte);
1417                 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1418                        && (wim_resource_compression_type(lte) != out_ctype ||
1419                            (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1420                 {
1421                         total_compression_bytes += wim_resource_size(lte);
1422                 }
1423         }
1424         progress.write_streams.total_bytes       = total_bytes;
1425         progress.write_streams.total_streams     = num_streams;
1426         progress.write_streams.completed_bytes   = 0;
1427         progress.write_streams.completed_streams = 0;
1428         progress.write_streams.num_threads       = num_threads;
1429         progress.write_streams.compression_type  = out_ctype;
1430         progress.write_streams._private          = 0;
1431
1432 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1433         if (total_compression_bytes >= 1000000 && num_threads != 1)
1434                 ret = write_stream_list_parallel(stream_list,
1435                                                  lookup_table,
1436                                                  out_fd,
1437                                                  out_ctype,
1438                                                  write_resource_flags,
1439                                                  progress_func,
1440                                                  &progress,
1441                                                  num_threads);
1442         else
1443 #endif
1444                 ret = write_stream_list_serial(stream_list,
1445                                                lookup_table,
1446                                                out_fd,
1447                                                out_ctype,
1448                                                write_resource_flags,
1449                                                progress_func,
1450                                                &progress);
1451         return ret;
1452 }
1453
1454 struct stream_size_table {
1455         struct hlist_head *array;
1456         size_t num_entries;
1457         size_t capacity;
1458 };
1459
1460 static int
1461 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1462 {
1463         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1464         if (!tab->array)
1465                 return WIMLIB_ERR_NOMEM;
1466         tab->num_entries = 0;
1467         tab->capacity = capacity;
1468         return 0;
1469 }
1470
1471 static void
1472 destroy_stream_size_table(struct stream_size_table *tab)
1473 {
1474         FREE(tab->array);
1475 }
1476
1477 static int
1478 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1479 {
1480         struct stream_size_table *tab = _tab;
1481         size_t pos;
1482         struct wim_lookup_table_entry *same_size_lte;
1483         struct hlist_node *tmp;
1484
1485         pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1486         lte->unique_size = 1;
1487         hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1488                 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1489                         lte->unique_size = 0;
1490                         same_size_lte->unique_size = 0;
1491                         break;
1492                 }
1493         }
1494
1495         hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
1496         tab->num_entries++;
1497         return 0;
1498 }
1499
1500
1501 struct lte_overwrite_prepare_args {
1502         WIMStruct *wim;
1503         off_t end_offset;
1504         struct list_head stream_list;
1505         struct stream_size_table stream_size_tab;
1506 };
1507
1508 /* First phase of preparing streams for an in-place overwrite.  This is called
1509  * on all streams, both hashed and unhashed, except the metadata resources. */
1510 static int
1511 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1512 {
1513         struct lte_overwrite_prepare_args *args = _args;
1514
1515         wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1516         if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1517                 list_add_tail(&lte->write_streams_list, &args->stream_list);
1518         lte->out_refcnt = lte->refcnt;
1519         stream_size_table_insert(lte, &args->stream_size_tab);
1520         return 0;
1521 }
1522
1523 /* Second phase of preparing streams for an in-place overwrite.  This is called
1524  * on existing metadata resources and hashed streams, but not unhashed streams.
1525  *
1526  * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1527  * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1528  * the latter uses lte->hash_list_2, while the former expects to set
1529  * lte->output_resource_entry. */
1530 static int
1531 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1532 {
1533         struct lte_overwrite_prepare_args *args = _args;
1534
1535         if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1536                 /* We can't do an in place overwrite on the WIM if there are
1537                  * streams after the XML data. */
1538                 if (lte->resource_entry.offset +
1539                     lte->resource_entry.size > args->end_offset)
1540                 {
1541                 #ifdef ENABLE_ERROR_MESSAGES
1542                         ERROR("The following resource is after the XML data:");
1543                         print_lookup_table_entry(lte, stderr);
1544                 #endif
1545                         return WIMLIB_ERR_RESOURCE_ORDER;
1546                 }
1547                 copy_resource_entry(&lte->output_resource_entry,
1548                                     &lte->resource_entry);
1549         }
1550         return 0;
1551 }
1552
1553 /* Given a WIM that we are going to overwrite in place with zero or more
1554  * additional streams added, construct a list the list of new unique streams
1555  * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1556  * streams that need to be added but may be identical to other hashed or
1557  * unhashed streams.  These unhashed streams are checksummed while the streams
1558  * are being written.  To aid this process, the member @unique_size is set to 1
1559  * on streams that have a unique size and therefore must be written.
1560  *
1561  * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1562  * indicate the number of times the stream is referenced in only the streams
1563  * that are being written; this may still be adjusted later when unhashed
1564  * streams are being resolved.
1565  */
1566 static int
1567 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1568                               struct list_head *stream_list)
1569 {
1570         int ret;
1571         struct lte_overwrite_prepare_args args;
1572         unsigned i;
1573
1574         args.wim = wim;
1575         args.end_offset = end_offset;
1576         ret = init_stream_size_table(&args.stream_size_tab,
1577                                      wim->lookup_table->capacity);
1578         if (ret)
1579                 return ret;
1580
1581         INIT_LIST_HEAD(&args.stream_list);
1582         for (i = 0; i < wim->hdr.image_count; i++) {
1583                 struct wim_image_metadata *imd;
1584                 struct wim_lookup_table_entry *lte;
1585
1586                 imd = wim->image_metadata[i];
1587                 image_for_each_unhashed_stream(lte, imd)
1588                         lte_overwrite_prepare(lte, &args);
1589         }
1590         for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1591         list_transfer(&args.stream_list, stream_list);
1592
1593         for (i = 0; i < wim->hdr.image_count; i++) {
1594                 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1595                                               &args);
1596                 if (ret)
1597                         goto out_destroy_stream_size_table;
1598         }
1599         ret = for_lookup_table_entry(wim->lookup_table,
1600                                      lte_overwrite_prepare_2, &args);
1601 out_destroy_stream_size_table:
1602         destroy_stream_size_table(&args.stream_size_tab);
1603         return ret;
1604 }
1605
1606
1607 struct find_streams_ctx {
1608         struct list_head stream_list;
1609         struct stream_size_table stream_size_tab;
1610 };
1611
1612 static void
1613 inode_find_streams_to_write(struct wim_inode *inode,
1614                             struct wim_lookup_table *table,
1615                             struct list_head *stream_list,
1616                             struct stream_size_table *tab)
1617 {
1618         struct wim_lookup_table_entry *lte;
1619         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1620                 lte = inode_stream_lte(inode, i, table);
1621                 if (lte) {
1622                         if (lte->out_refcnt == 0) {
1623                                 if (lte->unhashed)
1624                                         stream_size_table_insert(lte, tab);
1625                                 list_add_tail(&lte->write_streams_list, stream_list);
1626                         }
1627                         lte->out_refcnt += inode->i_nlink;
1628                 }
1629         }
1630 }
1631
1632 static int
1633 image_find_streams_to_write(WIMStruct *w)
1634 {
1635         struct find_streams_ctx *ctx;
1636         struct wim_image_metadata *imd;
1637         struct wim_inode *inode;
1638         struct wim_lookup_table_entry *lte;
1639
1640         ctx = w->private;
1641         imd = wim_get_current_image_metadata(w);
1642
1643         image_for_each_unhashed_stream(lte, imd)
1644                 lte->out_refcnt = 0;
1645
1646         /* Go through this image's inodes to find any streams that have not been
1647          * found yet. */
1648         image_for_each_inode(inode, imd) {
1649                 inode_find_streams_to_write(inode, w->lookup_table,
1650                                             &ctx->stream_list,
1651                                             &ctx->stream_size_tab);
1652         }
1653         return 0;
1654 }
1655
1656 /* Given a WIM that from which one or all of the images is being written, build
1657  * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1658  * written, plus any unhashed streams that need to be written but may be
1659  * identical to other hashed or unhashed streams being written.  These unhashed
1660  * streams are checksummed while the streams are being written.  To aid this
1661  * process, the member @unique_size is set to 1 on streams that have a unique
1662  * size and therefore must be written.
1663  *
1664  * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1665  * indicate the number of times the stream is referenced in only the streams
1666  * that are being written; this may still be adjusted later when unhashed
1667  * streams are being resolved.
1668  */
1669 static int
1670 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1671 {
1672         int ret;
1673         struct find_streams_ctx ctx;
1674
1675         for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1676         ret = init_stream_size_table(&ctx.stream_size_tab,
1677                                      wim->lookup_table->capacity);
1678         if (ret)
1679                 return ret;
1680         for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1681                                &ctx.stream_size_tab);
1682         INIT_LIST_HEAD(&ctx.stream_list);
1683         wim->private = &ctx;
1684         ret = for_image(wim, image, image_find_streams_to_write);
1685         destroy_stream_size_table(&ctx.stream_size_tab);
1686         if (ret == 0)
1687                 list_transfer(&ctx.stream_list, stream_list);
1688         return ret;
1689 }
1690
1691 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1692  */
1693 static int
1694 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1695                   unsigned num_threads,
1696                   wimlib_progress_func_t progress_func)
1697 {
1698         int ret;
1699         struct list_head stream_list;
1700
1701         ret = prepare_stream_list(wim, image, &stream_list);
1702         if (ret)
1703                 return ret;
1704         return write_stream_list(&stream_list,
1705                                  wim->lookup_table,
1706                                  wim->out_fd,
1707                                  wimlib_get_compression_type(wim),
1708                                  write_flags,
1709                                  num_threads,
1710                                  progress_func);
1711 }
1712
1713 /*
1714  * Finish writing a WIM file: write the lookup table, xml data, and integrity
1715  * table (optional), then overwrite the WIM header.
1716  *
1717  * write_flags is a bitwise OR of the following:
1718  *
1719  *      (public)  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1720  *              Include an integrity table.
1721  *
1722  *      (public)  WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1723  *              Show progress information when (if) writing the integrity table.
1724  *
1725  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1726  *              Don't write the lookup table.
1727  *
1728  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1729  *              When (if) writing the integrity table, re-use entries from the
1730  *              existing integrity table, if possible.
1731  *
1732  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1733  *              After writing the XML data but before writing the integrity
1734  *              table, write a temporary WIM header and flush the stream so that
1735  *              the WIM is less likely to become corrupted upon abrupt program
1736  *              termination.
1737  *
1738  *      (private) WIMLIB_WRITE_FLAG_FSYNC:
1739  *              fsync() the output file before closing it.
1740  *
1741  */
1742 int
1743 finish_write(WIMStruct *w, int image, int write_flags,
1744              wimlib_progress_func_t progress_func)
1745 {
1746         int ret;
1747         struct wim_header hdr;
1748
1749         /* @hdr will be the header for the new WIM.  First copy all the data
1750          * from the header in the WIMStruct; then set all the fields that may
1751          * have changed, including the resource entries, boot index, and image
1752          * count.  */
1753         memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1754
1755         /* Set image count and boot index correctly for single image writes */
1756         if (image != WIMLIB_ALL_IMAGES) {
1757                 hdr.image_count = 1;
1758                 if (hdr.boot_idx == image)
1759                         hdr.boot_idx = 1;
1760                 else
1761                         hdr.boot_idx = 0;
1762         }
1763
1764         /* In the WIM header, there is room for the resource entry for a
1765          * metadata resource labeled as the "boot metadata".  This entry should
1766          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
1767          * it should be a copy of the resource entry for the image that is
1768          * marked as bootable.  This is not well documented...  */
1769         if (hdr.boot_idx == 0) {
1770                 zero_resource_entry(&hdr.boot_metadata_res_entry);
1771         } else {
1772                 copy_resource_entry(&hdr.boot_metadata_res_entry,
1773                             &w->image_metadata[ hdr.boot_idx- 1
1774                                         ]->metadata_lte->output_resource_entry);
1775         }
1776
1777         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1778                 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1779                 if (ret)
1780                         goto out_close_wim;
1781         }
1782
1783         ret = write_xml_data(w->wim_info, image, w->out_fd,
1784                              (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1785                               wim_info_get_total_bytes(w->wim_info) : 0,
1786                              &hdr.xml_res_entry);
1787         if (ret)
1788                 goto out_close_wim;
1789
1790         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1791                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1792                         struct wim_header checkpoint_hdr;
1793                         memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1794                         zero_resource_entry(&checkpoint_hdr.integrity);
1795                         ret = write_header(&checkpoint_hdr, w->out_fd);
1796                         if (ret)
1797                                 goto out_close_wim;
1798                 }
1799
1800                 off_t old_lookup_table_end;
1801                 off_t new_lookup_table_end;
1802                 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1803                         old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1804                                                w->hdr.lookup_table_res_entry.size;
1805                 } else {
1806                         old_lookup_table_end = 0;
1807                 }
1808                 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1809                                        hdr.lookup_table_res_entry.size;
1810
1811                 ret = write_integrity_table(w->out_fd,
1812                                             &hdr.integrity,
1813                                             new_lookup_table_end,
1814                                             old_lookup_table_end,
1815                                             progress_func);
1816                 if (ret)
1817                         goto out_close_wim;
1818         } else {
1819                 zero_resource_entry(&hdr.integrity);
1820         }
1821
1822         ret = write_header(&hdr, w->out_fd);
1823         if (ret)
1824                 goto out_close_wim;
1825
1826         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1827                 if (fsync(w->out_fd)) {
1828                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
1829                         ret = WIMLIB_ERR_WRITE;
1830                 }
1831         }
1832 out_close_wim:
1833         if (close(w->out_fd)) {
1834                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1835                 if (ret == 0)
1836                         ret = WIMLIB_ERR_WRITE;
1837         }
1838         w->out_fd = INVALID_FILEDES;
1839         return ret;
1840 }
1841
1842 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1843 int
1844 lock_wim(WIMStruct *w, filedes_t fd)
1845 {
1846         int ret = 0;
1847         if (fd != INVALID_FILEDES && !w->wim_locked) {
1848                 ret = flock(fd, LOCK_EX | LOCK_NB);
1849                 if (ret != 0) {
1850                         if (errno == EWOULDBLOCK) {
1851                                 ERROR("`%"TS"' is already being modified or has been "
1852                                       "mounted read-write\n"
1853                                       "        by another process!", w->filename);
1854                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
1855                         } else {
1856                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1857                                                    w->filename);
1858                                 ret = 0;
1859                         }
1860                 } else {
1861                         w->wim_locked = 1;
1862                 }
1863         }
1864         return ret;
1865 }
1866 #endif
1867
1868 static int
1869 open_wim_writable(WIMStruct *w, const tchar *path, int open_flags)
1870 {
1871         wimlib_assert(w->out_fd == INVALID_FILEDES);
1872         w->out_fd = open(path, open_flags, 0644);
1873         if (w->out_fd == INVALID_FILEDES) {
1874                 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1875                 return WIMLIB_ERR_OPEN;
1876         }
1877         return 0;
1878 }
1879
1880
1881 void
1882 close_wim_writable(WIMStruct *w)
1883 {
1884         if (w->out_fd != INVALID_FILEDES) {
1885                 if (close(w->out_fd))
1886                         WARNING_WITH_ERRNO("Failed to close output WIM");
1887                 w->out_fd = INVALID_FILEDES;
1888         }
1889 }
1890
1891 /* Open file stream and write dummy header for WIM. */
1892 int
1893 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1894 {
1895         int ret;
1896         int open_flags = O_TRUNC | O_CREAT;
1897         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1898                 open_flags |= O_RDWR;
1899         else
1900                 open_flags |= O_WRONLY;
1901         ret = open_wim_writable(w, path, open_flags);
1902         if (ret)
1903                 return ret;
1904         /* Write dummy header. It will be overwritten later. */
1905         ret = write_header(&w->hdr, w->out_fd);
1906         if (ret)
1907                 return ret;
1908         if (lseek(w->out_fd, 0, SEEK_END) == -1) {
1909                 ERROR_WITH_ERRNO("Failed to seek to end of WIM");
1910                 return WIMLIB_ERR_WRITE;
1911         }
1912         return 0;
1913 }
1914
1915 /* Writes a stand-alone WIM to a file.  */
1916 WIMLIBAPI int
1917 wimlib_write(WIMStruct *w, const tchar *path,
1918              int image, int write_flags, unsigned num_threads,
1919              wimlib_progress_func_t progress_func)
1920 {
1921         int ret;
1922
1923         if (!path)
1924                 return WIMLIB_ERR_INVALID_PARAM;
1925
1926         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1927
1928         if (image != WIMLIB_ALL_IMAGES &&
1929              (image < 1 || image > w->hdr.image_count))
1930                 return WIMLIB_ERR_INVALID_IMAGE;
1931
1932         if (w->hdr.total_parts != 1) {
1933                 ERROR("Cannot call wimlib_write() on part of a split WIM");
1934                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1935         }
1936
1937         ret = begin_write(w, path, write_flags);
1938         if (ret)
1939                 goto out_close_wim;
1940
1941         ret = write_wim_streams(w, image, write_flags, num_threads,
1942                                 progress_func);
1943         if (ret)
1944                 goto out_close_wim;
1945
1946         if (progress_func)
1947                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1948
1949         ret = for_image(w, image, write_metadata_resource);
1950         if (ret)
1951                 goto out_close_wim;
1952
1953         if (progress_func)
1954                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1955
1956         ret = finish_write(w, image, write_flags, progress_func);
1957         /* finish_write() closed the WIM for us */
1958         goto out;
1959 out_close_wim:
1960         close_wim_writable(w);
1961 out:
1962         DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1963         return ret;
1964 }
1965
1966 static bool
1967 any_images_modified(WIMStruct *w)
1968 {
1969         for (int i = 0; i < w->hdr.image_count; i++)
1970                 if (w->image_metadata[i]->modified)
1971                         return true;
1972         return false;
1973 }
1974
1975 /*
1976  * Overwrite a WIM, possibly appending streams to it.
1977  *
1978  * A WIM looks like (or is supposed to look like) the following:
1979  *
1980  *                   Header (212 bytes)
1981  *                   Streams and metadata resources (variable size)
1982  *                   Lookup table (variable size)
1983  *                   XML data (variable size)
1984  *                   Integrity table (optional) (variable size)
1985  *
1986  * If we are not adding any streams or metadata resources, the lookup table is
1987  * unchanged--- so we only need to overwrite the XML data, integrity table, and
1988  * header.  This operation is potentially unsafe if the program is abruptly
1989  * terminated while the XML data or integrity table are being overwritten, but
1990  * before the new header has been written.  To partially alleviate this problem,
1991  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1992  * finish_write() to cause a temporary WIM header to be written after the XML
1993  * data has been written.  This may prevent the WIM from becoming corrupted if
1994  * the program is terminated while the integrity table is being calculated (but
1995  * no guarantees, due to write re-ordering...).
1996  *
1997  * If we are adding new streams or images (metadata resources), the lookup table
1998  * needs to be changed, and those streams need to be written.  In this case, we
1999  * try to perform a safe update of the WIM file by writing the streams *after*
2000  * the end of the previous WIM, then writing the new lookup table, XML data, and
2001  * (optionally) integrity table following the new streams.  This will produce a
2002  * layout like the following:
2003  *
2004  *                   Header (212 bytes)
2005  *                   (OLD) Streams and metadata resources (variable size)
2006  *                   (OLD) Lookup table (variable size)
2007  *                   (OLD) XML data (variable size)
2008  *                   (OLD) Integrity table (optional) (variable size)
2009  *                   (NEW) Streams and metadata resources (variable size)
2010  *                   (NEW) Lookup table (variable size)
2011  *                   (NEW) XML data (variable size)
2012  *                   (NEW) Integrity table (optional) (variable size)
2013  *
2014  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2015  * the header is overwritten to point to the new lookup table, XML data, and
2016  * integrity table, to produce the following layout:
2017  *
2018  *                   Header (212 bytes)
2019  *                   Streams and metadata resources (variable size)
2020  *                   Nothing (variable size)
2021  *                   More Streams and metadata resources (variable size)
2022  *                   Lookup table (variable size)
2023  *                   XML data (variable size)
2024  *                   Integrity table (optional) (variable size)
2025  *
2026  * This method allows an image to be appended to a large WIM very quickly, and
2027  * is is crash-safe except in the case of write re-ordering, but the
2028  * disadvantage is that a small hole is left in the WIM where the old lookup
2029  * table, xml data, and integrity table were.  (These usually only take up a
2030  * small amount of space compared to the streams, however.)
2031  */
2032 static int
2033 overwrite_wim_inplace(WIMStruct *w, int write_flags,
2034                       unsigned num_threads,
2035                       wimlib_progress_func_t progress_func)
2036 {
2037         int ret;
2038         struct list_head stream_list;
2039         off_t old_wim_end;
2040         u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2041         int open_flags;
2042
2043         DEBUG("Overwriting `%"TS"' in-place", w->filename);
2044
2045         /* Make sure that the integrity table (if present) is after the XML
2046          * data, and that there are no stream resources, metadata resources, or
2047          * lookup tables after the XML data.  Otherwise, these data would be
2048          * overwritten. */
2049         old_xml_begin = w->hdr.xml_res_entry.offset;
2050         old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
2051         old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
2052                                w->hdr.lookup_table_res_entry.size;
2053         if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
2054                 ERROR("Didn't expect the integrity table to be before the XML data");
2055                 return WIMLIB_ERR_RESOURCE_ORDER;
2056         }
2057
2058         if (old_lookup_table_end > old_xml_begin) {
2059                 ERROR("Didn't expect the lookup table to be after the XML data");
2060                 return WIMLIB_ERR_RESOURCE_ORDER;
2061         }
2062
2063         /* Set @old_wim_end, which indicates the point beyond which we don't
2064          * allow any file and metadata resources to appear without returning
2065          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2066          * overwrite these resources). */
2067         if (!w->deletion_occurred && !any_images_modified(w)) {
2068                 /* If no images have been modified and no images have been
2069                  * deleted, a new lookup table does not need to be written.  We
2070                  * shall write the new XML data and optional integrity table
2071                  * immediately after the lookup table.  Note that this may
2072                  * overwrite an existing integrity table. */
2073                 DEBUG("Skipping writing lookup table "
2074                       "(no images modified or deleted)");
2075                 old_wim_end = old_lookup_table_end;
2076                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2077                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2078         } else if (w->hdr.integrity.offset) {
2079                 /* Old WIM has an integrity table; begin writing new streams
2080                  * after it. */
2081                 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2082         } else {
2083                 /* No existing integrity table; begin writing new streams after
2084                  * the old XML data. */
2085                 old_wim_end = old_xml_end;
2086         }
2087
2088         ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2089         if (ret)
2090                 return ret;
2091
2092         open_flags = 0;
2093         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2094                 open_flags |= O_RDWR;
2095         else
2096                 open_flags |= O_WRONLY;
2097         ret = open_wim_writable(w, w->filename, open_flags);
2098         if (ret)
2099                 return ret;
2100
2101         ret = lock_wim(w, w->out_fd);
2102         if (ret) {
2103                 close_wim_writable(w);
2104                 return ret;
2105         }
2106
2107         if (lseek(w->out_fd, old_wim_end, SEEK_SET) == -1) {
2108                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2109                 close_wim_writable(w);
2110                 w->wim_locked = 0;
2111                 return WIMLIB_ERR_WRITE;
2112         }
2113
2114         DEBUG("Writing newly added streams (offset = %"PRIu64")",
2115               old_wim_end);
2116         ret = write_stream_list(&stream_list,
2117                                 w->lookup_table,
2118                                 w->out_fd,
2119                                 wimlib_get_compression_type(w),
2120                                 write_flags,
2121                                 num_threads,
2122                                 progress_func);
2123         if (ret)
2124                 goto out_truncate;
2125
2126         for (int i = 0; i < w->hdr.image_count; i++) {
2127                 if (w->image_metadata[i]->modified) {
2128                         select_wim_image(w, i + 1);
2129                         ret = write_metadata_resource(w);
2130                         if (ret)
2131                                 goto out_truncate;
2132                 }
2133         }
2134         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2135         ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2136                            progress_func);
2137 out_truncate:
2138         close_wim_writable(w);
2139         if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2140                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2141                         w->filename, old_wim_end);
2142                 /* Return value of truncate() is ignored because this is already
2143                  * an error path. */
2144                 (void)ttruncate(w->filename, old_wim_end);
2145         }
2146         w->wim_locked = 0;
2147         return ret;
2148 }
2149
2150 static int
2151 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2152                           unsigned num_threads,
2153                           wimlib_progress_func_t progress_func)
2154 {
2155         size_t wim_name_len;
2156         int ret;
2157
2158         DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2159
2160         /* Write the WIM to a temporary file in the same directory as the
2161          * original WIM. */
2162         wim_name_len = tstrlen(w->filename);
2163         tchar tmpfile[wim_name_len + 10];
2164         tmemcpy(tmpfile, w->filename, wim_name_len);
2165         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2166         tmpfile[wim_name_len + 9] = T('\0');
2167
2168         ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2169                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2170                            num_threads, progress_func);
2171         if (ret) {
2172                 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2173                 goto out_unlink;
2174         }
2175
2176         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2177
2178 #ifdef __WIN32__
2179         /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2180          * specified to CreateFile().  The WIM was opened with fopen(), which
2181          * didn't provided this flag to CreateFile, so the handle must be closed
2182          * before executing the rename(). */
2183         if (w->fp != NULL) {
2184                 fclose(w->fp);
2185                 w->fp = NULL;
2186         }
2187 #endif
2188
2189         /* Rename the new file to the old file .*/
2190         if (trename(tmpfile, w->filename) != 0) {
2191                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2192                                  tmpfile, w->filename);
2193                 ret = WIMLIB_ERR_RENAME;
2194                 goto out_unlink;
2195         }
2196
2197         if (progress_func) {
2198                 union wimlib_progress_info progress;
2199                 progress.rename.from = tmpfile;
2200                 progress.rename.to = w->filename;
2201                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2202         }
2203         goto out;
2204 out_unlink:
2205         /* Remove temporary file. */
2206         if (tunlink(tmpfile) != 0)
2207                 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2208 out:
2209         return ret;
2210 }
2211
2212 /*
2213  * Writes a WIM file to the original file that it was read from, overwriting it.
2214  */
2215 WIMLIBAPI int
2216 wimlib_overwrite(WIMStruct *w, int write_flags,
2217                  unsigned num_threads,
2218                  wimlib_progress_func_t progress_func)
2219 {
2220         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2221
2222         if (!w->filename)
2223                 return WIMLIB_ERR_NO_FILENAME;
2224
2225         if (w->hdr.total_parts != 1) {
2226                 ERROR("Cannot modify a split WIM");
2227                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2228         }
2229
2230         if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2231             && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2232         {
2233                 int ret;
2234                 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2235                                             progress_func);
2236                 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2237                         WARNING("Falling back to re-building entire WIM");
2238                 else
2239                         return ret;
2240         }
2241         return overwrite_wim_via_tmpfile(w, write_flags, num_threads,
2242                                          progress_func);
2243 }