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