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