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