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