Merge LZX compressor updates
[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 <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <stdlib.h>
60 #include <unistd.h>
61
62 #ifdef HAVE_ALLOCA_H
63 #  include <alloca.h>
64 #endif
65
66
67 #ifndef __WIN32__
68 #  include <sys/uio.h> /* for `struct iovec' */
69 #endif
70
71 static unsigned
72 compress_chunk(const void * uncompressed_data,
73                unsigned uncompressed_len,
74                void *compressed_data,
75                int out_ctype,
76                struct wimlib_lzx_context *comp_ctx)
77 {
78         switch (out_ctype) {
79         case WIMLIB_COMPRESSION_TYPE_XPRESS:
80                 return wimlib_xpress_compress(uncompressed_data,
81                                               uncompressed_len,
82                                               compressed_data);
83         case WIMLIB_COMPRESSION_TYPE_LZX:
84                 return wimlib_lzx_compress2(uncompressed_data,
85                                             uncompressed_len,
86                                             compressed_data,
87                                             comp_ctx);
88         default:
89                 wimlib_assert(0);
90                 return 0;
91         }
92 }
93
94 /* Chunk table that's located at the beginning of each compressed resource in
95  * the WIM.  (This is not the on-disk format; the on-disk format just has an
96  * array of offsets.) */
97 struct chunk_table {
98         u64 original_resource_size;
99         u64 num_chunks;
100         u64 table_disk_size;
101         unsigned bytes_per_chunk_entry;
102         void *cur_offset_p;
103         union {
104                 u32 cur_offset_u32;
105                 u64 cur_offset_u64;
106         };
107         /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
108          * integers, including the first offset of 0, which will not be written.
109          * */
110         u8 offsets[] _aligned_attribute(8);
111 };
112
113 /* Allocate and initializes a chunk table, then reserve space for it in the
114  * output file unless writing a pipable resource.  */
115 static int
116 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
117                              struct filedes *out_fd,
118                              struct chunk_table **chunk_tab_ret,
119                              int resource_flags)
120 {
121         u64 size;
122         u64 num_chunks;
123         unsigned bytes_per_chunk_entry;
124         size_t alloc_size;
125         struct chunk_table *chunk_tab;
126         int ret;
127
128         size = wim_resource_size(lte);
129         num_chunks = wim_resource_chunks(lte);
130         bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
131         alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
132         chunk_tab = CALLOC(1, alloc_size);
133
134         if (!chunk_tab) {
135                 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
136                       "resource", size);
137                 return WIMLIB_ERR_NOMEM;
138         }
139         chunk_tab->num_chunks = num_chunks;
140         chunk_tab->original_resource_size = size;
141         chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
142         chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
143                                      (num_chunks - 1);
144         chunk_tab->cur_offset_p = chunk_tab->offsets;
145
146         /* We don't know the correct offsets yet; so just write zeroes to
147          * reserve space for the table, so we can go back to it later after
148          * we've written the compressed chunks following it.
149          *
150          * Special case: if writing a pipable WIM, compressed resources are in a
151          * modified format (see comment above write_pipable_wim()) and do not
152          * have a chunk table at the beginning, so don't reserve any space for
153          * one.  */
154         if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
155                 ret = full_write(out_fd, chunk_tab->offsets,
156                                  chunk_tab->table_disk_size);
157                 if (ret) {
158                         ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
159                                          "file resource");
160                         FREE(chunk_tab);
161                         return ret;
162                 }
163         }
164         *chunk_tab_ret = chunk_tab;
165         return 0;
166 }
167
168 /* Add the offset for the next chunk to the chunk table being constructed for a
169  * compressed stream. */
170 static void
171 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
172 {
173         if (chunk_tab->bytes_per_chunk_entry == 4) {
174                 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
175                 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
176                 chunk_tab->cur_offset_u32 += out_chunk_size;
177         } else {
178                 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
179                 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
180                 chunk_tab->cur_offset_u64 += out_chunk_size;
181         }
182 }
183
184 /* Finishes a WIM chunk table and writes it to the output file at the correct
185  * offset.  */
186 static int
187 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
188                               struct filedes *out_fd,
189                               off_t res_start_offset,
190                               int write_resource_flags)
191 {
192         int ret;
193
194         if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
195                 ret = full_write(out_fd,
196                                  chunk_tab->offsets +
197                                          chunk_tab->bytes_per_chunk_entry,
198                                  chunk_tab->table_disk_size);
199         } else {
200                 ret  = full_pwrite(out_fd,
201                                    chunk_tab->offsets +
202                                            chunk_tab->bytes_per_chunk_entry,
203                                    chunk_tab->table_disk_size,
204                                    res_start_offset);
205         }
206         if (ret) {
207                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
208                                  "file resource");
209         }
210         return ret;
211 }
212
213 /* Write the header for a stream in a pipable WIM.
214  */
215 static int
216 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
217                         struct filedes *out_fd,
218                         int additional_reshdr_flags)
219 {
220         struct pwm_stream_hdr stream_hdr;
221         u32 reshdr_flags;
222         int ret;
223
224         stream_hdr.magic = PWM_STREAM_MAGIC;
225         stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
226         if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
227                 zero_out_hash(stream_hdr.hash);
228         } else {
229                 wimlib_assert(!lte->unhashed);
230                 copy_hash(stream_hdr.hash, lte->hash);
231         }
232
233         reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
234         reshdr_flags |= additional_reshdr_flags;
235         stream_hdr.flags = cpu_to_le32(reshdr_flags);
236         ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
237         if (ret)
238                 ERROR_WITH_ERRNO("Error writing stream header");
239         return ret;
240 }
241
242 static int
243 seek_and_truncate(struct filedes *out_fd, off_t offset)
244 {
245         if (filedes_seek(out_fd, offset) == -1 ||
246             ftruncate(out_fd->fd, offset))
247         {
248                 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
249                 return WIMLIB_ERR_WRITE;
250         }
251         return 0;
252 }
253
254 static int
255 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
256 {
257         u8 md[SHA1_HASH_SIZE];
258
259         sha1_final(md, sha_ctx);
260         if (lte->unhashed) {
261                 copy_hash(lte->hash, md);
262         } else if (!hashes_equal(md, lte->hash)) {
263                 ERROR("WIM resource has incorrect hash!");
264                 if (lte_filename_valid(lte)) {
265                         ERROR("We were reading it from \"%"TS"\"; maybe "
266                               "it changed while we were reading it.",
267                               lte->file_on_disk);
268                 }
269                 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
270         }
271         return 0;
272 }
273
274 struct write_resource_ctx {
275         int out_ctype;
276         struct wimlib_lzx_context *comp_ctx;
277         struct chunk_table *chunk_tab;
278         struct filedes *out_fd;
279         SHA_CTX sha_ctx;
280         bool doing_sha;
281         int resource_flags;
282 };
283
284 static int
285 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
286 {
287         struct write_resource_ctx *ctx = _ctx;
288         const void *out_chunk;
289         unsigned out_chunk_size;
290         int ret;
291
292         if (ctx->doing_sha)
293                 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
294
295         out_chunk = chunk;
296         out_chunk_size = chunk_size;
297         if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
298                 void *compressed_chunk;
299                 unsigned compressed_size;
300
301                 /* Compress the chunk.  */
302                 compressed_chunk = alloca(chunk_size);
303
304                 compressed_size = compress_chunk(chunk, chunk_size,
305                                                  compressed_chunk,
306                                                  ctx->out_ctype,
307                                                  ctx->comp_ctx);
308                 /* Use compressed data if compression to less than input size
309                  * was successful.  */
310                 if (compressed_size) {
311                         out_chunk = compressed_chunk;
312                         out_chunk_size = compressed_size;
313                 }
314         }
315
316         if (ctx->chunk_tab) {
317                 /* Update chunk table accounting.  */
318                 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
319
320                 /* If writing compressed chunks to a pipable WIM, before the
321                  * chunk data write a chunk header that provides the compressed
322                  * chunk size.  */
323                 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
324                         struct pwm_chunk_hdr chunk_hdr = {
325                                 .compressed_size = cpu_to_le32(out_chunk_size),
326                         };
327                         ret = full_write(ctx->out_fd, &chunk_hdr,
328                                          sizeof(chunk_hdr));
329                         if (ret)
330                                 goto error;
331                 }
332         }
333
334         /* Write the chunk data.  */
335         ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
336         if (ret)
337                 goto error;
338         return 0;
339
340 error:
341         ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
342         return ret;
343 }
344
345 /*
346  * write_wim_resource()-
347  *
348  * Write a resource to an output WIM.
349  *
350  * @lte:
351  *      Lookup table entry for the resource, which could be in another WIM, in
352  *      an external file, or in another location.
353  *
354  * @out_fd:
355  *      File descriptor opened to the output WIM.
356  *
357  * @out_ctype:
358  *      One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
359  *      compression algorithm to use.
360  *
361  * @out_res_entry:
362  *      On success, this is filled in with the offset, flags, compressed size,
363  *      and uncompressed size of the resource in the output WIM.
364  *
365  * @resource_flags:
366  *      * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
367  *        if it could otherwise be copied directly from the input;
368  *      * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
369  *        (and the output file descriptor may be a pipe).
370  *
371  * @comp_ctx:
372  *      Location of LZX compression context pointer, which will be allocated or
373  *      updated if needed.  (Initialize to NULL.)
374  *
375  * Additional notes:  The SHA1 message digest of the uncompressed data is
376  * calculated (except when doing a raw copy --- see below).  If the @unhashed
377  * flag is set on the lookup table entry, this message digest is simply copied
378  * to it; otherwise, the message digest is compared with the existing one, and
379  * the function will fail if they do not match.
380  */
381 int
382 write_wim_resource(struct wim_lookup_table_entry *lte,
383                    struct filedes *out_fd, int out_ctype,
384                    struct resource_entry *out_res_entry,
385                    int resource_flags,
386                    struct wimlib_lzx_context **comp_ctx)
387 {
388         struct write_resource_ctx write_ctx;
389         off_t res_start_offset;
390         u64 read_size;
391         int ret;
392
393         /* Mask out any irrelevant flags, since this function also uses this
394          * variable to store WIMLIB_READ_RESOURCE flags.  */
395         resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
396
397         /* Get current position in output WIM.  */
398         res_start_offset = out_fd->offset;
399
400         /* If we are not forcing the data to be recompressed, and the input
401          * resource is located in a WIM with the same compression type as that
402          * desired other than no compression, we can simply copy the compressed
403          * data without recompressing it.  This also means we must skip
404          * calculating the SHA1, as we never will see the uncompressed data.  */
405         if (lte->resource_location == RESOURCE_IN_WIM &&
406             out_ctype == wim_resource_compression_type(lte) &&
407             out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
408             !(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS))
409         {
410                 /* Normally we can request a RAW_FULL read, but if we're reading
411                  * from a pipable resource and writing a non-pipable resource or
412                  * vice versa, then a RAW_CHUNKS read needs to be requested so
413                  * that the written resource can be appropriately formatted.
414                  * However, in neither case is any actual decompression needed.
415                  */
416                 if (lte->is_pipable == !!(resource_flags &
417                                           WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
418                         resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
419                 else
420                         resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
421                 write_ctx.doing_sha = false;
422                 read_size = lte->resource_entry.size;
423         } else {
424                 write_ctx.doing_sha = true;
425                 sha1_init(&write_ctx.sha_ctx);
426                 read_size = lte->resource_entry.original_size;
427         }
428
429
430         /* If the output resource is to be compressed, initialize the chunk
431          * table and set the function to use for chunk compression.  Exceptions:
432          * no compression function is needed if doing a raw copy; also, no chunk
433          * table is needed if doing a *full* (not per-chunk) raw copy.  */
434         write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
435         write_ctx.chunk_tab = NULL;
436         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
437                 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
438                         write_ctx.out_ctype = out_ctype;
439                         if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
440                                 ret = wimlib_lzx_alloc_context(NULL, comp_ctx);
441                                 if (ret)
442                                         goto out;
443                         }
444                         write_ctx.comp_ctx = *comp_ctx;
445                 }
446                 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
447                         ret = begin_wim_resource_chunk_tab(lte, out_fd,
448                                                            &write_ctx.chunk_tab,
449                                                            resource_flags);
450                         if (ret)
451                                 goto out;
452                 }
453         }
454
455         /* If writing a pipable resource, write the stream header and update
456          * @res_start_offset to be the end of the stream header.  */
457         if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
458                 int reshdr_flags = 0;
459                 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
460                         reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
461                 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
462                 if (ret)
463                         goto out_free_chunk_tab;
464                 res_start_offset = out_fd->offset;
465         }
466
467         /* Write the entire resource by reading the entire resource and feeding
468          * the data through the write_resource_cb function. */
469         write_ctx.out_fd = out_fd;
470         write_ctx.resource_flags = resource_flags;
471 try_write_again:
472         ret = read_resource_prefix(lte, read_size,
473                                    write_resource_cb, &write_ctx, resource_flags);
474         if (ret)
475                 goto out_free_chunk_tab;
476
477         /* Verify SHA1 message digest of the resource, or set the hash for the
478          * first time. */
479         if (write_ctx.doing_sha) {
480                 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
481                 if (ret)
482                         goto out_free_chunk_tab;
483         }
484
485         /* Write chunk table if needed.  */
486         if (write_ctx.chunk_tab) {
487                 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
488                                                     out_fd,
489                                                     res_start_offset,
490                                                     resource_flags);
491                 if (ret)
492                         goto out_free_chunk_tab;
493         }
494
495         /* Fill in out_res_entry with information about the newly written
496          * resource.  */
497         out_res_entry->size          = out_fd->offset - res_start_offset;
498         out_res_entry->flags         = lte->resource_entry.flags;
499         if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
500                 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
501         else
502                 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
503         out_res_entry->offset        = res_start_offset;
504         out_res_entry->original_size = wim_resource_size(lte);
505
506         /* Check for resources compressed to greater than their original size
507          * and write them uncompressed instead.  (But never do this if writing
508          * to a pipe, and don't bother if we did a raw copy.)  */
509         if (out_res_entry->size > out_res_entry->original_size &&
510             !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
511                                 WIMLIB_READ_RESOURCE_FLAG_RAW)))
512         {
513                 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
514                       "writing uncompressed instead",
515                       out_res_entry->original_size, out_res_entry->size);
516                 ret = seek_and_truncate(out_fd, res_start_offset);
517                 if (ret)
518                         goto out_free_chunk_tab;
519                 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
520                 FREE(write_ctx.chunk_tab);
521                 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
522                 write_ctx.chunk_tab = NULL;
523                 write_ctx.doing_sha = false;
524                 goto try_write_again;
525         }
526         if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
527                 DEBUG("Copied raw compressed data "
528                       "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
529                       out_res_entry->original_size, out_res_entry->size,
530                       out_res_entry->offset, out_res_entry->flags);
531         } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
532                 DEBUG("Wrote compressed resource "
533                       "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
534                       out_res_entry->original_size, out_res_entry->size,
535                       out_res_entry->offset, out_res_entry->flags);
536         } else {
537                 DEBUG("Wrote uncompressed resource "
538                       "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
539                       out_res_entry->original_size,
540                       out_res_entry->offset, out_res_entry->flags);
541         }
542         ret = 0;
543 out_free_chunk_tab:
544         FREE(write_ctx.chunk_tab);
545 out:
546         return ret;
547 }
548
549 /* Like write_wim_resource(), but the resource is specified by a buffer of
550  * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
551  * the buffer to @hash_ret.  */
552 int
553 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
554                                int reshdr_flags, struct filedes *out_fd,
555                                int out_ctype,
556                                struct resource_entry *out_res_entry,
557                                u8 *hash_ret, int write_resource_flags,
558                                struct wimlib_lzx_context **comp_ctx)
559 {
560         /* Set up a temporary lookup table entry to provide to
561          * write_wim_resource(). */
562         struct wim_lookup_table_entry lte;
563         int ret;
564
565         lte.resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
566         lte.attached_buffer              = (void*)buf;
567         lte.resource_entry.original_size = buf_size;
568         lte.resource_entry.flags         = reshdr_flags;
569
570         if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
571                 sha1_buffer(buf, buf_size, lte.hash);
572                 lte.unhashed = 0;
573         } else {
574                 lte.unhashed = 1;
575         }
576
577         ret = write_wim_resource(&lte, out_fd, out_ctype, out_res_entry,
578                                  write_resource_flags, comp_ctx);
579         if (ret)
580                 return ret;
581         if (hash_ret)
582                 copy_hash(hash_ret, lte.hash);
583         return 0;
584 }
585
586
587 #ifdef ENABLE_MULTITHREADED_COMPRESSION
588
589 /* Blocking shared queue (solves the producer-consumer problem) */
590 struct shared_queue {
591         unsigned size;
592         unsigned front;
593         unsigned back;
594         unsigned filled_slots;
595         void **array;
596         pthread_mutex_t lock;
597         pthread_cond_t msg_avail_cond;
598         pthread_cond_t space_avail_cond;
599 };
600
601 static int
602 shared_queue_init(struct shared_queue *q, unsigned size)
603 {
604         wimlib_assert(size != 0);
605         q->array = CALLOC(sizeof(q->array[0]), size);
606         if (!q->array)
607                 goto err;
608         q->filled_slots = 0;
609         q->front = 0;
610         q->back = size - 1;
611         q->size = size;
612         if (pthread_mutex_init(&q->lock, NULL)) {
613                 ERROR_WITH_ERRNO("Failed to initialize mutex");
614                 goto err;
615         }
616         if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
617                 ERROR_WITH_ERRNO("Failed to initialize condition variable");
618                 goto err_destroy_lock;
619         }
620         if (pthread_cond_init(&q->space_avail_cond, NULL)) {
621                 ERROR_WITH_ERRNO("Failed to initialize condition variable");
622                 goto err_destroy_msg_avail_cond;
623         }
624         return 0;
625 err_destroy_msg_avail_cond:
626         pthread_cond_destroy(&q->msg_avail_cond);
627 err_destroy_lock:
628         pthread_mutex_destroy(&q->lock);
629 err:
630         return WIMLIB_ERR_NOMEM;
631 }
632
633 static void
634 shared_queue_destroy(struct shared_queue *q)
635 {
636         FREE(q->array);
637         pthread_mutex_destroy(&q->lock);
638         pthread_cond_destroy(&q->msg_avail_cond);
639         pthread_cond_destroy(&q->space_avail_cond);
640 }
641
642 static void
643 shared_queue_put(struct shared_queue *q, void *obj)
644 {
645         pthread_mutex_lock(&q->lock);
646         while (q->filled_slots == q->size)
647                 pthread_cond_wait(&q->space_avail_cond, &q->lock);
648
649         q->back = (q->back + 1) % q->size;
650         q->array[q->back] = obj;
651         q->filled_slots++;
652
653         pthread_cond_broadcast(&q->msg_avail_cond);
654         pthread_mutex_unlock(&q->lock);
655 }
656
657 static void *
658 shared_queue_get(struct shared_queue *q)
659 {
660         void *obj;
661
662         pthread_mutex_lock(&q->lock);
663         while (q->filled_slots == 0)
664                 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
665
666         obj = q->array[q->front];
667         q->array[q->front] = NULL;
668         q->front = (q->front + 1) % q->size;
669         q->filled_slots--;
670
671         pthread_cond_broadcast(&q->space_avail_cond);
672         pthread_mutex_unlock(&q->lock);
673         return obj;
674 }
675
676 struct compressor_thread_params {
677         struct shared_queue *res_to_compress_queue;
678         struct shared_queue *compressed_res_queue;
679         int out_ctype;
680         struct wimlib_lzx_context *comp_ctx;
681 };
682
683 #define MAX_CHUNKS_PER_MSG 2
684
685 struct message {
686         struct wim_lookup_table_entry *lte;
687         u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
688         u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
689         unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
690         struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
691         unsigned num_chunks;
692         struct list_head list;
693         bool complete;
694         u64 begin_chunk;
695 };
696
697 static void
698 compress_chunks(struct message *msg, int out_ctype,
699                 struct wimlib_lzx_context *comp_ctx)
700 {
701         for (unsigned i = 0; i < msg->num_chunks; i++) {
702                 unsigned len;
703
704                 len = compress_chunk(msg->uncompressed_chunks[i],
705                                      msg->uncompressed_chunk_sizes[i],
706                                      msg->compressed_chunks[i],
707                                      out_ctype,
708                                      comp_ctx);
709
710                 void *out_chunk;
711                 unsigned out_len;
712                 if (len) {
713                         /* To be written compressed */
714                         out_chunk = msg->compressed_chunks[i];
715                         out_len = len;
716                 } else {
717                         /* To be written uncompressed */
718                         out_chunk = msg->uncompressed_chunks[i];
719                         out_len = msg->uncompressed_chunk_sizes[i];
720                 }
721                 msg->out_chunks[i].iov_base = out_chunk;
722                 msg->out_chunks[i].iov_len = out_len;
723         }
724 }
725
726 /* Compressor thread routine.  This is a lot simpler than the main thread
727  * routine: just repeatedly get a group of chunks from the
728  * res_to_compress_queue, compress them, and put them in the
729  * compressed_res_queue.  A NULL pointer indicates that the thread should stop.
730  * */
731 static void *
732 compressor_thread_proc(void *arg)
733 {
734         struct compressor_thread_params *params = arg;
735         struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
736         struct shared_queue *compressed_res_queue = params->compressed_res_queue;
737         struct message *msg;
738
739         DEBUG("Compressor thread ready");
740         while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
741                 compress_chunks(msg, params->out_ctype, params->comp_ctx);
742                 shared_queue_put(compressed_res_queue, msg);
743         }
744         DEBUG("Compressor thread terminating");
745         return NULL;
746 }
747 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
748
749 struct write_streams_progress_data {
750         wimlib_progress_func_t progress_func;
751         union wimlib_progress_info progress;
752         uint64_t next_progress;
753         WIMStruct *prev_wim_part;
754 };
755
756 static void
757 do_write_streams_progress(struct write_streams_progress_data *progress_data,
758                           struct wim_lookup_table_entry *lte,
759                           bool stream_discarded)
760 {
761         union wimlib_progress_info *progress = &progress_data->progress;
762         bool new_wim_part;
763
764         if (stream_discarded) {
765                 progress->write_streams.total_bytes -= wim_resource_size(lte);
766                 if (progress_data->next_progress != ~(uint64_t)0 &&
767                     progress_data->next_progress > progress->write_streams.total_bytes)
768                 {
769                         progress_data->next_progress = progress->write_streams.total_bytes;
770                 }
771         } else {
772                 progress->write_streams.completed_bytes += wim_resource_size(lte);
773         }
774         new_wim_part = false;
775         if (lte->resource_location == RESOURCE_IN_WIM &&
776             lte->wim != progress_data->prev_wim_part)
777         {
778                 if (progress_data->prev_wim_part) {
779                         new_wim_part = true;
780                         progress->write_streams.completed_parts++;
781                 }
782                 progress_data->prev_wim_part = lte->wim;
783         }
784         progress->write_streams.completed_streams++;
785         if (progress_data->progress_func
786             && (progress->write_streams.completed_bytes >= progress_data->next_progress
787                 || new_wim_part))
788         {
789                 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
790                                              progress);
791                 if (progress_data->next_progress == progress->write_streams.total_bytes) {
792                         progress_data->next_progress = ~(uint64_t)0;
793                 } else {
794                         progress_data->next_progress =
795                                 min(progress->write_streams.total_bytes,
796                                     progress->write_streams.completed_bytes +
797                                         progress->write_streams.total_bytes / 100);
798                 }
799         }
800 }
801
802 struct serial_write_stream_ctx {
803         struct filedes *out_fd;
804         int out_ctype;
805         struct wimlib_lzx_context **comp_ctx;
806         int write_resource_flags;
807 };
808
809 static int
810 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
811 {
812         struct serial_write_stream_ctx *ctx = _ctx;
813         return write_wim_resource(lte, ctx->out_fd,
814                                   ctx->out_ctype, &lte->output_resource_entry,
815                                   ctx->write_resource_flags,
816                                   ctx->comp_ctx);
817 }
818
819
820 /* Write a list of streams, taking into account that some streams may be
821  * duplicates that are checksummed and discarded on the fly, and also delegating
822  * the actual writing of a stream to a function @write_stream_cb, which is
823  * passed the context @write_stream_ctx. */
824 static int
825 do_write_stream_list(struct list_head *stream_list,
826                      struct wim_lookup_table *lookup_table,
827                      int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
828                      void *write_stream_ctx,
829                      struct write_streams_progress_data *progress_data)
830 {
831         int ret = 0;
832         struct wim_lookup_table_entry *lte;
833         bool stream_discarded;
834
835         /* For each stream in @stream_list ... */
836         while (!list_empty(stream_list)) {
837                 stream_discarded = false;
838                 lte = container_of(stream_list->next,
839                                    struct wim_lookup_table_entry,
840                                    write_streams_list);
841                 list_del(&lte->write_streams_list);
842                 if (lte->unhashed && !lte->unique_size) {
843                         /* Unhashed stream that shares a size with some other
844                          * stream in the WIM we are writing.  The stream must be
845                          * checksummed to know if we need to write it or not. */
846                         struct wim_lookup_table_entry *tmp;
847                         u32 orig_out_refcnt = lte->out_refcnt;
848
849                         ret = hash_unhashed_stream(lte, lookup_table, &tmp);
850                         if (ret)
851                                 break;
852                         if (tmp != lte) {
853                                 /* We found a duplicate stream.  'lte' was
854                                  * freed, so replace it with the duplicate.  */
855                                 lte = tmp;
856
857                                 /* 'out_refcnt' was transferred to the
858                                  * duplicate, and we can detect if the duplicate
859                                  * stream was already referenced for writing by
860                                  * checking if its 'out_refcnt' is higher than
861                                  * that of the original stream.  In such cases,
862                                  * the current stream can be discarded.  We can
863                                  * also discard the current stream if it was
864                                  * previously marked as filtered (e.g. already
865                                  * present in the WIM being written).  */
866                                 if (lte->out_refcnt > orig_out_refcnt ||
867                                     lte->filtered) {
868                                         DEBUG("Discarding duplicate stream of "
869                                               "length %"PRIu64,
870                                               wim_resource_size(lte));
871                                         lte->no_progress = 0;
872                                         stream_discarded = true;
873                                         goto skip_to_progress;
874                                 }
875                         }
876                 }
877
878                 /* Here, @lte is either a hashed stream or an unhashed stream
879                  * with a unique size.  In either case we know that the stream
880                  * has to be written.  In either case the SHA1 message digest
881                  * will be calculated over the stream while writing it; however,
882                  * in the former case this is done merely to check the data,
883                  * while in the latter case this is done because we do not have
884                  * the SHA1 message digest yet.  */
885                 wimlib_assert(lte->out_refcnt != 0);
886                 lte->deferred = 0;
887                 lte->no_progress = 0;
888                 ret = (*write_stream_cb)(lte, write_stream_ctx);
889                 if (ret)
890                         break;
891                 /* In parallel mode, some streams are deferred for later,
892                  * serialized processing; ignore them here. */
893                 if (lte->deferred)
894                         continue;
895                 if (lte->unhashed) {
896                         list_del(&lte->unhashed_list);
897                         lookup_table_insert(lookup_table, lte);
898                         lte->unhashed = 0;
899                 }
900         skip_to_progress:
901                 if (!lte->no_progress) {
902                         do_write_streams_progress(progress_data,
903                                                   lte, stream_discarded);
904                 }
905         }
906         return ret;
907 }
908
909 static int
910 do_write_stream_list_serial(struct list_head *stream_list,
911                             struct wim_lookup_table *lookup_table,
912                             struct filedes *out_fd,
913                             int out_ctype,
914                             struct wimlib_lzx_context **comp_ctx,
915                             int write_resource_flags,
916                             struct write_streams_progress_data *progress_data)
917 {
918         struct serial_write_stream_ctx ctx = {
919                 .out_fd = out_fd,
920                 .out_ctype = out_ctype,
921                 .write_resource_flags = write_resource_flags,
922                 .comp_ctx = comp_ctx,
923         };
924         return do_write_stream_list(stream_list,
925                                     lookup_table,
926                                     serial_write_stream,
927                                     &ctx,
928                                     progress_data);
929 }
930
931 static inline int
932 write_flags_to_resource_flags(int write_flags)
933 {
934         int resource_flags = 0;
935
936         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
937                 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
938         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
939                 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
940         return resource_flags;
941 }
942
943 static int
944 write_stream_list_serial(struct list_head *stream_list,
945                          struct wim_lookup_table *lookup_table,
946                          struct filedes *out_fd,
947                          int out_ctype,
948                          struct wimlib_lzx_context **comp_ctx,
949                          int write_resource_flags,
950                          struct write_streams_progress_data *progress_data)
951 {
952         union wimlib_progress_info *progress = &progress_data->progress;
953         DEBUG("Writing stream list of size %"PRIu64" (serial version)",
954               progress->write_streams.total_streams);
955         progress->write_streams.num_threads = 1;
956         if (progress_data->progress_func) {
957                 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
958                                              progress);
959         }
960         return do_write_stream_list_serial(stream_list,
961                                            lookup_table,
962                                            out_fd,
963                                            out_ctype,
964                                            comp_ctx,
965                                            write_resource_flags,
966                                            progress_data);
967 }
968
969 #ifdef ENABLE_MULTITHREADED_COMPRESSION
970 static int
971 write_wim_chunks(struct message *msg, struct filedes *out_fd,
972                  struct chunk_table *chunk_tab,
973                  int write_resource_flags)
974 {
975         struct iovec *vecs;
976         struct pwm_chunk_hdr *chunk_hdrs;
977         unsigned nvecs;
978         int ret;
979
980         for (unsigned i = 0; i < msg->num_chunks; i++)
981                 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
982
983         if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
984                 nvecs = msg->num_chunks;
985                 vecs = msg->out_chunks;
986         } else {
987                 /* Special case:  If writing a compressed resource to a pipable
988                  * WIM, prefix each compressed chunk with a header that gives
989                  * its compressed size.  */
990                 nvecs = msg->num_chunks * 2;
991                 vecs = alloca(nvecs * sizeof(vecs[0]));
992                 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
993
994                 for (unsigned i = 0; i < msg->num_chunks; i++) {
995                         chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
996                         vecs[i * 2].iov_base = &chunk_hdrs[i];
997                         vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
998                         vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
999                         vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1000                 }
1001         }
1002         ret = full_writev(out_fd, vecs, nvecs);
1003         if (ret)
1004                 ERROR_WITH_ERRNO("Failed to write WIM chunks");
1005         return ret;
1006 }
1007
1008 struct main_writer_thread_ctx {
1009         struct list_head *stream_list;
1010         struct wim_lookup_table *lookup_table;
1011         struct filedes *out_fd;
1012         off_t res_start_offset;
1013         int out_ctype;
1014         struct wimlib_lzx_context **comp_ctx;
1015         int write_resource_flags;
1016         struct shared_queue *res_to_compress_queue;
1017         struct shared_queue *compressed_res_queue;
1018         size_t num_messages;
1019         struct write_streams_progress_data *progress_data;
1020
1021         struct list_head available_msgs;
1022         struct list_head outstanding_streams;
1023         struct list_head serial_streams;
1024         size_t num_outstanding_messages;
1025
1026         SHA_CTX next_sha_ctx;
1027         u64 next_chunk;
1028         u64 next_num_chunks;
1029         struct wim_lookup_table_entry *next_lte;
1030
1031         struct message *msgs;
1032         struct message *next_msg;
1033         struct chunk_table *cur_chunk_tab;
1034 };
1035
1036 static int
1037 init_message(struct message *msg)
1038 {
1039         for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1040                 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1041                 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1042                 if (msg->compressed_chunks[i] == NULL ||
1043                     msg->uncompressed_chunks[i] == NULL)
1044                         return WIMLIB_ERR_NOMEM;
1045         }
1046         return 0;
1047 }
1048
1049 static void
1050 destroy_message(struct message *msg)
1051 {
1052         for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1053                 FREE(msg->compressed_chunks[i]);
1054                 FREE(msg->uncompressed_chunks[i]);
1055         }
1056 }
1057
1058 static void
1059 free_messages(struct message *msgs, size_t num_messages)
1060 {
1061         if (msgs) {
1062                 for (size_t i = 0; i < num_messages; i++)
1063                         destroy_message(&msgs[i]);
1064                 FREE(msgs);
1065         }
1066 }
1067
1068 static struct message *
1069 allocate_messages(size_t num_messages)
1070 {
1071         struct message *msgs;
1072
1073         msgs = CALLOC(num_messages, sizeof(struct message));
1074         if (!msgs)
1075                 return NULL;
1076         for (size_t i = 0; i < num_messages; i++) {
1077                 if (init_message(&msgs[i])) {
1078                         free_messages(msgs, num_messages);
1079                         return NULL;
1080                 }
1081         }
1082         return msgs;
1083 }
1084
1085 static void
1086 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1087 {
1088         while (ctx->num_outstanding_messages--)
1089                 shared_queue_get(ctx->compressed_res_queue);
1090         free_messages(ctx->msgs, ctx->num_messages);
1091         FREE(ctx->cur_chunk_tab);
1092 }
1093
1094 static int
1095 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1096 {
1097         /* Pre-allocate all the buffers that will be needed to do the chunk
1098          * compression. */
1099         ctx->msgs = allocate_messages(ctx->num_messages);
1100         if (!ctx->msgs)
1101                 return WIMLIB_ERR_NOMEM;
1102
1103         /* Initially, all the messages are available to use. */
1104         INIT_LIST_HEAD(&ctx->available_msgs);
1105         for (size_t i = 0; i < ctx->num_messages; i++)
1106                 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1107
1108         /* outstanding_streams is the list of streams that currently have had
1109          * chunks sent off for compression.
1110          *
1111          * The first stream in outstanding_streams is the stream that is
1112          * currently being written.
1113          *
1114          * The last stream in outstanding_streams is the stream that is
1115          * currently being read and having chunks fed to the compressor threads.
1116          * */
1117         INIT_LIST_HEAD(&ctx->outstanding_streams);
1118         ctx->num_outstanding_messages = 0;
1119
1120         ctx->next_msg = NULL;
1121
1122         /* Resources that don't need any chunks compressed are added to this
1123          * list and written directly by the main thread. */
1124         INIT_LIST_HEAD(&ctx->serial_streams);
1125
1126         ctx->cur_chunk_tab = NULL;
1127
1128         return 0;
1129 }
1130
1131 static int
1132 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1133 {
1134         struct message *msg;
1135         struct wim_lookup_table_entry *cur_lte;
1136         int ret;
1137
1138         wimlib_assert(!list_empty(&ctx->outstanding_streams));
1139         wimlib_assert(ctx->num_outstanding_messages != 0);
1140
1141         cur_lte = container_of(ctx->outstanding_streams.next,
1142                                struct wim_lookup_table_entry,
1143                                being_compressed_list);
1144
1145         /* Get the next message from the queue and process it.
1146          * The message will contain 1 or more data chunks that have been
1147          * compressed. */
1148         msg = shared_queue_get(ctx->compressed_res_queue);
1149         msg->complete = true;
1150         --ctx->num_outstanding_messages;
1151
1152         /* Is this the next chunk in the current resource?  If it's not
1153          * (i.e., an earlier chunk in a same or different resource
1154          * hasn't been compressed yet), do nothing, and keep this
1155          * message around until all earlier chunks are received.
1156          *
1157          * Otherwise, write all the chunks we can. */
1158         while (cur_lte != NULL &&
1159                !list_empty(&cur_lte->msg_list)
1160                && (msg = container_of(cur_lte->msg_list.next,
1161                                       struct message,
1162                                       list))->complete)
1163         {
1164                 list_move(&msg->list, &ctx->available_msgs);
1165                 if (msg->begin_chunk == 0) {
1166                         /* First set of chunks.  */
1167
1168                         /* Write pipable WIM stream header if needed.  */
1169                         if (ctx->write_resource_flags &
1170                             WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1171                         {
1172                                 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1173                                                               WIM_RESHDR_FLAG_COMPRESSED);
1174                                 if (ret)
1175                                         return ret;
1176                         }
1177
1178                         /* Save current offset.  */
1179                         ctx->res_start_offset = ctx->out_fd->offset;
1180
1181                         /* Begin building the chunk table, and leave space for
1182                          * it if needed.  */
1183                         ret = begin_wim_resource_chunk_tab(cur_lte,
1184                                                            ctx->out_fd,
1185                                                            &ctx->cur_chunk_tab,
1186                                                            ctx->write_resource_flags);
1187                         if (ret)
1188                                 return ret;
1189
1190                 }
1191
1192                 /* Write the compressed chunks from the message. */
1193                 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1194                                        ctx->write_resource_flags);
1195                 if (ret)
1196                         return ret;
1197
1198                 /* Was this the last chunk of the stream?  If so, finish
1199                  * it. */
1200                 if (list_empty(&cur_lte->msg_list) &&
1201                     msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1202                 {
1203                         u64 res_csize;
1204
1205                         ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1206                                                             ctx->out_fd,
1207                                                             ctx->res_start_offset,
1208                                                             ctx->write_resource_flags);
1209                         if (ret)
1210                                 return ret;
1211
1212                         list_del(&cur_lte->being_compressed_list);
1213
1214                         res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1215
1216                         FREE(ctx->cur_chunk_tab);
1217                         ctx->cur_chunk_tab = NULL;
1218
1219                         /* Check for resources compressed to greater than or
1220                          * equal to their original size and write them
1221                          * uncompressed instead.  (But never do this if writing
1222                          * to a pipe.)  */
1223                         if (res_csize >= wim_resource_size(cur_lte) &&
1224                             !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1225                         {
1226                                 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1227                                       "writing uncompressed instead",
1228                                       wim_resource_size(cur_lte), res_csize);
1229                                 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1230                                 if (ret)
1231                                         return ret;
1232                                 ret = write_wim_resource(cur_lte,
1233                                                          ctx->out_fd,
1234                                                          WIMLIB_COMPRESSION_TYPE_NONE,
1235                                                          &cur_lte->output_resource_entry,
1236                                                          ctx->write_resource_flags,
1237                                                          ctx->comp_ctx);
1238                                 if (ret)
1239                                         return ret;
1240                         } else {
1241                                 cur_lte->output_resource_entry.size =
1242                                         res_csize;
1243
1244                                 cur_lte->output_resource_entry.original_size =
1245                                         cur_lte->resource_entry.original_size;
1246
1247                                 cur_lte->output_resource_entry.offset =
1248                                         ctx->res_start_offset;
1249
1250                                 cur_lte->output_resource_entry.flags =
1251                                         cur_lte->resource_entry.flags |
1252                                                 WIM_RESHDR_FLAG_COMPRESSED;
1253
1254                                 DEBUG("Wrote compressed resource "
1255                                       "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1256                                       cur_lte->output_resource_entry.original_size,
1257                                       cur_lte->output_resource_entry.size,
1258                                       cur_lte->output_resource_entry.offset,
1259                                       cur_lte->output_resource_entry.flags);
1260                         }
1261
1262                         do_write_streams_progress(ctx->progress_data,
1263                                                   cur_lte, false);
1264
1265                         /* Since we just finished writing a stream, write any
1266                          * streams that have been added to the serial_streams
1267                          * list for direct writing by the main thread (e.g.
1268                          * resources that don't need to be compressed because
1269                          * the desired compression type is the same as the
1270                          * previous compression type). */
1271                         if (!list_empty(&ctx->serial_streams)) {
1272                                 ret = do_write_stream_list_serial(&ctx->serial_streams,
1273                                                                   ctx->lookup_table,
1274                                                                   ctx->out_fd,
1275                                                                   ctx->out_ctype,
1276                                                                   ctx->comp_ctx,
1277                                                                   ctx->write_resource_flags,
1278                                                                   ctx->progress_data);
1279                                 if (ret)
1280                                         return ret;
1281                         }
1282
1283                         /* Advance to the next stream to write. */
1284                         if (list_empty(&ctx->outstanding_streams)) {
1285                                 cur_lte = NULL;
1286                         } else {
1287                                 cur_lte = container_of(ctx->outstanding_streams.next,
1288                                                        struct wim_lookup_table_entry,
1289                                                        being_compressed_list);
1290                         }
1291                 }
1292         }
1293         return 0;
1294 }
1295
1296 /* Called when the main thread has read a new chunk of data. */
1297 static int
1298 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1299 {
1300         struct main_writer_thread_ctx *ctx = _ctx;
1301         int ret;
1302         struct message *next_msg;
1303         u64 next_chunk_in_msg;
1304
1305         /* Update SHA1 message digest for the stream currently being read by the
1306          * main thread. */
1307         sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1308
1309         /* We send chunks of data to the compressor chunks in batches which we
1310          * refer to as "messages".  @next_msg is the message that is currently
1311          * being prepared to send off.  If it is NULL, that indicates that we
1312          * need to start a new message. */
1313         next_msg = ctx->next_msg;
1314         if (!next_msg) {
1315                 /* We need to start a new message.  First check to see if there
1316                  * is a message available in the list of available messages.  If
1317                  * so, we can just take one.  If not, all the messages (there is
1318                  * a fixed number of them, proportional to the number of
1319                  * threads) have been sent off to the compressor threads, so we
1320                  * receive messages from the compressor threads containing
1321                  * compressed chunks of data.
1322                  *
1323                  * We may need to receive multiple messages before one is
1324                  * actually available to use because messages received that are
1325                  * *not* for the very next set of chunks to compress must be
1326                  * buffered until it's time to write those chunks. */
1327                 while (list_empty(&ctx->available_msgs)) {
1328                         ret = receive_compressed_chunks(ctx);
1329                         if (ret)
1330                                 return ret;
1331                 }
1332
1333                 next_msg = container_of(ctx->available_msgs.next,
1334                                         struct message, list);
1335                 list_del(&next_msg->list);
1336                 next_msg->complete = false;
1337                 next_msg->begin_chunk = ctx->next_chunk;
1338                 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1339                                            ctx->next_num_chunks - ctx->next_chunk);
1340                 ctx->next_msg = next_msg;
1341         }
1342
1343         /* Fill in the next chunk to compress */
1344         next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1345
1346         next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1347         memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1348                chunk, chunk_size);
1349         ctx->next_chunk++;
1350         if (++next_chunk_in_msg == next_msg->num_chunks) {
1351                 /* Send off an array of chunks to compress */
1352                 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1353                 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1354                 ++ctx->num_outstanding_messages;
1355                 ctx->next_msg = NULL;
1356         }
1357         return 0;
1358 }
1359
1360 static int
1361 main_writer_thread_finish(void *_ctx)
1362 {
1363         struct main_writer_thread_ctx *ctx = _ctx;
1364         int ret;
1365         while (ctx->num_outstanding_messages != 0) {
1366                 ret = receive_compressed_chunks(ctx);
1367                 if (ret)
1368                         return ret;
1369         }
1370         wimlib_assert(list_empty(&ctx->outstanding_streams));
1371         return do_write_stream_list_serial(&ctx->serial_streams,
1372                                            ctx->lookup_table,
1373                                            ctx->out_fd,
1374                                            ctx->out_ctype,
1375                                            ctx->comp_ctx,
1376                                            ctx->write_resource_flags,
1377                                            ctx->progress_data);
1378 }
1379
1380 static int
1381 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1382                               struct main_writer_thread_ctx *ctx)
1383 {
1384         int ret;
1385
1386         /* Read the entire stream @lte, feeding its data chunks to the
1387          * compressor threads.  Also SHA1-sum the stream; this is required in
1388          * the case that @lte is unhashed, and a nice additional verification
1389          * when @lte is already hashed. */
1390         sha1_init(&ctx->next_sha_ctx);
1391         ctx->next_chunk = 0;
1392         ctx->next_num_chunks = wim_resource_chunks(lte);
1393         ctx->next_lte = lte;
1394         INIT_LIST_HEAD(&lte->msg_list);
1395         list_add_tail(&lte->being_compressed_list, &ctx->outstanding_streams);
1396         ret = read_resource_prefix(lte, wim_resource_size(lte),
1397                                    main_writer_thread_cb, ctx, 0);
1398         if (ret)
1399                 return ret;
1400         wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1401         return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1402 }
1403
1404 static int
1405 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1406 {
1407         struct main_writer_thread_ctx *ctx = _ctx;
1408         int ret;
1409
1410         if (wim_resource_size(lte) < 1000 ||
1411             ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1412             (lte->resource_location == RESOURCE_IN_WIM &&
1413              !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS) &&
1414              lte->wim->compression_type == ctx->out_ctype))
1415         {
1416                 /* Stream is too small or isn't being compressed.  Process it by
1417                  * the main thread when we have a chance.  We can't necessarily
1418                  * process it right here, as the main thread could be in the
1419                  * middle of writing a different stream. */
1420                 list_add_tail(&lte->write_streams_list, &ctx->serial_streams);
1421                 lte->deferred = 1;
1422                 ret = 0;
1423         } else {
1424                 ret = submit_stream_for_compression(lte, ctx);
1425         }
1426         lte->no_progress = 1;
1427         return ret;
1428 }
1429
1430 static long
1431 get_default_num_threads(void)
1432 {
1433 #ifdef __WIN32__
1434         return win32_get_number_of_processors();
1435 #else
1436         return sysconf(_SC_NPROCESSORS_ONLN);
1437 #endif
1438 }
1439
1440 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1441  * parameter and will perform compression using that many threads.  Falls
1442  * back to write_stream_list_serial() on certain errors, such as a failure to
1443  * create the number of threads requested.
1444  *
1445  * High level description of the algorithm for writing compressed streams in
1446  * parallel:  We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1447  * rather than on full files.  The currently executing thread becomes the main
1448  * thread and is entirely in charge of reading the data to compress (which may
1449  * be in any location understood by the resource code--- such as in an external
1450  * file being captured, or in another WIM file from which an image is being
1451  * exported) and actually writing the compressed data to the output file.
1452  * Additional threads are "compressor threads" and all execute the
1453  * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1454  * the main thread, compress them, and hand them back to the main thread.
1455  *
1456  * Certain streams, such as streams that do not need to be compressed (e.g.
1457  * input compression type same as output compression type) or streams of very
1458  * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1459  * handled entirely by the main thread at an appropriate time.
1460  *
1461  * At any given point in time, multiple streams may be having chunks compressed
1462  * concurrently.  The stream that the main thread is currently *reading* may be
1463  * later in the list that the stream that the main thread is currently
1464  * *writing*.
1465  */
1466 static int
1467 write_stream_list_parallel(struct list_head *stream_list,
1468                            struct wim_lookup_table *lookup_table,
1469                            struct filedes *out_fd,
1470                            int out_ctype,
1471                            struct wimlib_lzx_context **comp_ctx,
1472                            int write_resource_flags,
1473                            struct write_streams_progress_data *progress_data,
1474                            unsigned num_threads)
1475 {
1476         int ret;
1477         struct shared_queue res_to_compress_queue;
1478         struct shared_queue compressed_res_queue;
1479         pthread_t *compressor_threads = NULL;
1480         union wimlib_progress_info *progress = &progress_data->progress;
1481
1482         if (num_threads == 0) {
1483                 long nthreads = get_default_num_threads();
1484                 if (nthreads < 1 || nthreads > UINT_MAX) {
1485                         WARNING("Could not determine number of processors! Assuming 1");
1486                         goto out_serial;
1487                 } else if (nthreads == 1) {
1488                         goto out_serial_quiet;
1489                 } else {
1490                         num_threads = nthreads;
1491                 }
1492         }
1493
1494         DEBUG("Writing stream list of size %"PRIu64" "
1495               "(parallel version, num_threads=%u)",
1496               progress->write_streams.total_streams, num_threads);
1497
1498         progress->write_streams.num_threads = num_threads;
1499
1500         static const size_t MESSAGES_PER_THREAD = 2;
1501         size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1502
1503         DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1504
1505         ret = shared_queue_init(&res_to_compress_queue, queue_size);
1506         if (ret)
1507                 goto out_serial;
1508
1509         ret = shared_queue_init(&compressed_res_queue, queue_size);
1510         if (ret)
1511                 goto out_destroy_res_to_compress_queue;
1512
1513         struct compressor_thread_params *params;
1514
1515         params = CALLOC(num_threads, sizeof(params[0]));
1516         if (params == NULL) {
1517                 ret = WIMLIB_ERR_NOMEM;
1518                 goto out_destroy_compressed_res_queue;
1519         }
1520
1521         for (unsigned i = 0; i < num_threads; i++) {
1522                 params[i].res_to_compress_queue = &res_to_compress_queue;
1523                 params[i].compressed_res_queue = &compressed_res_queue;
1524                 params[i].out_ctype = out_ctype;
1525                 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1526                         ret = wimlib_lzx_alloc_context(NULL, &params[i].comp_ctx);
1527                         if (ret)
1528                                 goto out_free_params;
1529                 }
1530         }
1531
1532         compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1533         if (!compressor_threads) {
1534                 ret = WIMLIB_ERR_NOMEM;
1535                 goto out_free_params;
1536         }
1537
1538         for (unsigned i = 0; i < num_threads; i++) {
1539                 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1540                 ret = pthread_create(&compressor_threads[i], NULL,
1541                                      compressor_thread_proc, &params[i]);
1542                 if (ret != 0) {
1543                         ret = -1;
1544                         ERROR_WITH_ERRNO("Failed to create compressor "
1545                                          "thread %u of %u",
1546                                          i + 1, num_threads);
1547                         num_threads = i;
1548                         goto out_join;
1549                 }
1550         }
1551
1552         if (progress_data->progress_func) {
1553                 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1554                                              progress);
1555         }
1556
1557         struct main_writer_thread_ctx ctx;
1558         ctx.stream_list           = stream_list;
1559         ctx.lookup_table          = lookup_table;
1560         ctx.out_fd                = out_fd;
1561         ctx.out_ctype             = out_ctype;
1562         ctx.comp_ctx              = comp_ctx;
1563         ctx.res_to_compress_queue = &res_to_compress_queue;
1564         ctx.compressed_res_queue  = &compressed_res_queue;
1565         ctx.num_messages          = queue_size;
1566         ctx.write_resource_flags  = write_resource_flags;
1567         ctx.progress_data         = progress_data;
1568         ret = main_writer_thread_init_ctx(&ctx);
1569         if (ret)
1570                 goto out_join;
1571         ret = do_write_stream_list(stream_list, lookup_table,
1572                                    main_thread_process_next_stream,
1573                                    &ctx, progress_data);
1574         if (ret)
1575                 goto out_destroy_ctx;
1576
1577         /* The main thread has finished reading all streams that are going to be
1578          * compressed in parallel, and it now needs to wait for all remaining
1579          * chunks to be compressed so that the remaining streams can actually be
1580          * written to the output file.  Furthermore, any remaining streams that
1581          * had processing deferred to the main thread need to be handled.  These
1582          * tasks are done by the main_writer_thread_finish() function. */
1583         ret = main_writer_thread_finish(&ctx);
1584 out_destroy_ctx:
1585         main_writer_thread_destroy_ctx(&ctx);
1586 out_join:
1587         for (unsigned i = 0; i < num_threads; i++)
1588                 shared_queue_put(&res_to_compress_queue, NULL);
1589
1590         for (unsigned i = 0; i < num_threads; i++) {
1591                 if (pthread_join(compressor_threads[i], NULL)) {
1592                         WARNING_WITH_ERRNO("Failed to join compressor "
1593                                            "thread %u of %u",
1594                                            i + 1, num_threads);
1595                 }
1596         }
1597         FREE(compressor_threads);
1598 out_free_params:
1599         for (unsigned i = 0; i < num_threads; i++)
1600                 wimlib_lzx_free_context(params[i].comp_ctx);
1601         FREE(params);
1602 out_destroy_compressed_res_queue:
1603         shared_queue_destroy(&compressed_res_queue);
1604 out_destroy_res_to_compress_queue:
1605         shared_queue_destroy(&res_to_compress_queue);
1606         if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1607                 return ret;
1608 out_serial:
1609         WARNING("Falling back to single-threaded compression");
1610 out_serial_quiet:
1611         return write_stream_list_serial(stream_list,
1612                                         lookup_table,
1613                                         out_fd,
1614                                         out_ctype,
1615                                         comp_ctx,
1616                                         write_resource_flags,
1617                                         progress_data);
1618
1619 }
1620 #endif
1621
1622 /*
1623  * Write a list of streams to a WIM (@out_fd) using the compression type
1624  * @out_ctype and up to @num_threads compressor threads.
1625  */
1626 static int
1627 write_stream_list(struct list_head *stream_list,
1628                   struct wim_lookup_table *lookup_table,
1629                   struct filedes *out_fd, int out_ctype,
1630                   struct wimlib_lzx_context **comp_ctx,
1631                   int write_flags,
1632                   unsigned num_threads, wimlib_progress_func_t progress_func)
1633 {
1634         struct wim_lookup_table_entry *lte;
1635         size_t num_streams = 0;
1636         u64 total_bytes = 0;
1637         u64 total_compression_bytes = 0;
1638         struct write_streams_progress_data progress_data;
1639         int ret;
1640         int write_resource_flags;
1641         unsigned total_parts = 0;
1642         WIMStruct *prev_wim_part = NULL;
1643
1644         if (list_empty(stream_list)) {
1645                 DEBUG("No streams to write.");
1646                 return 0;
1647         }
1648
1649         write_resource_flags = write_flags_to_resource_flags(write_flags);
1650
1651         DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1652               out_fd->offset, write_resource_flags);
1653
1654         sort_stream_list_by_sequential_order(stream_list,
1655                                              offsetof(struct wim_lookup_table_entry,
1656                                                       write_streams_list));
1657
1658         /* Calculate the total size of the streams to be written.  Note: this
1659          * will be the uncompressed size, as we may not know the compressed size
1660          * yet, and also this will assume that every unhashed stream will be
1661          * written (which will not necessarily be the case). */
1662         list_for_each_entry(lte, stream_list, write_streams_list) {
1663                 num_streams++;
1664                 total_bytes += wim_resource_size(lte);
1665                 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1666                        && (wim_resource_compression_type(lte) != out_ctype ||
1667                            (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)))
1668                 {
1669                         total_compression_bytes += wim_resource_size(lte);
1670                 }
1671                 if (lte->resource_location == RESOURCE_IN_WIM) {
1672                         if (prev_wim_part != lte->wim) {
1673                                 prev_wim_part = lte->wim;
1674                                 total_parts++;
1675                         }
1676                 }
1677         }
1678
1679         memset(&progress_data, 0, sizeof(progress_data));
1680         progress_data.progress_func = progress_func;
1681
1682         progress_data.progress.write_streams.total_bytes       = total_bytes;
1683         progress_data.progress.write_streams.total_streams     = num_streams;
1684         progress_data.progress.write_streams.completed_bytes   = 0;
1685         progress_data.progress.write_streams.completed_streams = 0;
1686         progress_data.progress.write_streams.num_threads       = num_threads;
1687         progress_data.progress.write_streams.compression_type  = out_ctype;
1688         progress_data.progress.write_streams.total_parts       = total_parts;
1689         progress_data.progress.write_streams.completed_parts   = 0;
1690
1691         progress_data.next_progress = 0;
1692         progress_data.prev_wim_part = NULL;
1693
1694 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1695         if (total_compression_bytes >= 2000000 && num_threads != 1)
1696                 ret = write_stream_list_parallel(stream_list,
1697                                                  lookup_table,
1698                                                  out_fd,
1699                                                  out_ctype,
1700                                                  comp_ctx,
1701                                                  write_resource_flags,
1702                                                  &progress_data,
1703                                                  num_threads);
1704         else
1705 #endif
1706                 ret = write_stream_list_serial(stream_list,
1707                                                lookup_table,
1708                                                out_fd,
1709                                                out_ctype,
1710                                                comp_ctx,
1711                                                write_resource_flags,
1712                                                &progress_data);
1713         if (ret == 0)
1714                 DEBUG("Successfully wrote stream list.");
1715         else
1716                 DEBUG("Failed to write stream list.");
1717         return ret;
1718 }
1719
1720 struct stream_size_table {
1721         struct hlist_head *array;
1722         size_t num_entries;
1723         size_t capacity;
1724 };
1725
1726 static int
1727 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1728 {
1729         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1730         if (!tab->array)
1731                 return WIMLIB_ERR_NOMEM;
1732         tab->num_entries = 0;
1733         tab->capacity = capacity;
1734         return 0;
1735 }
1736
1737 static void
1738 destroy_stream_size_table(struct stream_size_table *tab)
1739 {
1740         FREE(tab->array);
1741 }
1742
1743 static int
1744 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1745 {
1746         struct stream_size_table *tab = _tab;
1747         size_t pos;
1748         struct wim_lookup_table_entry *same_size_lte;
1749         struct hlist_node *tmp;
1750
1751         pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1752         lte->unique_size = 1;
1753         hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1754                 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1755                         lte->unique_size = 0;
1756                         same_size_lte->unique_size = 0;
1757                         break;
1758                 }
1759         }
1760
1761         hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
1762         tab->num_entries++;
1763         return 0;
1764 }
1765
1766 struct find_streams_ctx {
1767         WIMStruct *wim;
1768         int write_flags;
1769         struct list_head stream_list;
1770         struct stream_size_table stream_size_tab;
1771 };
1772
1773 static void
1774 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1775                                 struct find_streams_ctx *ctx,
1776                                 unsigned nref)
1777 {
1778         if (lte->out_refcnt == 0) {
1779                 stream_size_table_insert(lte, &ctx->stream_size_tab);
1780                 list_add_tail(&lte->write_streams_list, &ctx->stream_list);
1781         }
1782         lte->out_refcnt += nref;
1783 }
1784
1785 static int
1786 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1787                                         void *_ctx)
1788 {
1789         struct find_streams_ctx *ctx = _ctx;
1790         lte->out_refcnt = 0;
1791         lte_reference_for_logical_write(lte, ctx,
1792                                         (lte->refcnt ? lte->refcnt : 1));
1793         return 0;
1794 }
1795
1796 static int
1797 inode_find_streams_to_write(struct wim_inode *inode,
1798                             struct wim_lookup_table *table,
1799                             struct find_streams_ctx *ctx)
1800 {
1801         struct wim_lookup_table_entry *lte;
1802         unsigned i;
1803
1804         for (i = 0; i <= inode->i_num_ads; i++) {
1805                 lte = inode_stream_lte(inode, i, table);
1806                 if (lte)
1807                         lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1808                 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1809                         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1810         }
1811         return 0;
1812 }
1813
1814 static int
1815 image_find_streams_to_write(WIMStruct *wim)
1816 {
1817         struct find_streams_ctx *ctx;
1818         struct wim_image_metadata *imd;
1819         struct wim_inode *inode;
1820         struct wim_lookup_table_entry *lte;
1821         int ret;
1822
1823         ctx = wim->private;
1824         imd = wim_get_current_image_metadata(wim);
1825
1826         image_for_each_unhashed_stream(lte, imd)
1827                 lte->out_refcnt = 0;
1828
1829         /* Go through this image's inodes to find any streams that have not been
1830          * found yet. */
1831         image_for_each_inode(inode, imd) {
1832                 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1833                 if (ret)
1834                         return ret;
1835         }
1836         return 0;
1837 }
1838
1839 /*
1840  * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1841  * the "logical write" of the WIM, meaning all streams that are referenced at
1842  * least once by dentries in the the image(s) being written.  'out_refcnt' on
1843  * each stream being included in the logical write is set to the number of
1844  * references from dentries in the image(s).  Furthermore, 'unique_size' on each
1845  * stream being included in the logical write is set to indicate whether that
1846  * stream has a unique size relative to the streams being included in the
1847  * logical write.  Still furthermore, 'part_number' on each stream being
1848  * included in the logical write is set to the part number given in the
1849  * in-memory header of @p wim.
1850  *
1851  * This is considered a "logical write" because it does not take into account
1852  * filtering out streams already present in the WIM (in the case of an in place
1853  * overwrite) or present in other WIMs (in case of creating delta WIM).
1854  */
1855 static int
1856 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1857                             struct find_streams_ctx *ctx)
1858 {
1859         int ret;
1860         struct wim_lookup_table_entry *lte;
1861
1862         if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1863                            (image == 1 && wim->hdr.image_count == 1)))
1864         {
1865                 /* Fast case:  Assume that all streams are being written and
1866                  * that the reference counts are correct.  */
1867                 struct wim_lookup_table_entry *lte;
1868                 struct wim_image_metadata *imd;
1869                 unsigned i;
1870
1871                 for_lookup_table_entry(wim->lookup_table,
1872                                        do_lte_full_reference_for_logical_write, ctx);
1873                 for (i = 0; i < wim->hdr.image_count; i++) {
1874                         imd = wim->image_metadata[i];
1875                         image_for_each_unhashed_stream(lte, imd)
1876                                 do_lte_full_reference_for_logical_write(lte, ctx);
1877                 }
1878         } else {
1879                 /* Slow case:  Walk through the images being written and
1880                  * determine the streams referenced.  */
1881                 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1882                 wim->private = ctx;
1883                 ret = for_image(wim, image, image_find_streams_to_write);
1884                 if (ret)
1885                         return ret;
1886         }
1887
1888         list_for_each_entry(lte, &ctx->stream_list, write_streams_list)
1889                 lte->part_number = wim->hdr.part_number;
1890         return 0;
1891 }
1892
1893 static int
1894 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1895 {
1896         struct find_streams_ctx *ctx = _ctx;
1897         u16 filtered = 0;
1898
1899         /* Calculate and set lte->filtered.  */
1900         if (lte->resource_location == RESOURCE_IN_WIM) {
1901                 if (lte->wim == ctx->wim &&
1902                     (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1903                         filtered |= FILTERED_SAME_WIM;
1904                 if (lte->wim != ctx->wim &&
1905                     (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1906                         filtered |= FILTERED_EXTERNAL_WIM;
1907         }
1908         lte->filtered = filtered;
1909
1910         /* Filtered streams get inserted into the stream size table too, unless
1911          * they already were.  This is because streams that are checksummed
1912          * on-the-fly during the write should not be written if they are
1913          * duplicates of filtered stream.  */
1914         if (lte->filtered && lte->out_refcnt == 0)
1915                 stream_size_table_insert(lte, &ctx->stream_size_tab);
1916         return 0;
1917 }
1918
1919 static int
1920 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
1921 {
1922         lte->filtered = 0;
1923         return 0;
1924 }
1925
1926 /* Given the list of streams to include in a logical write of a WIM, handle
1927  * filtering out streams already present in the WIM or already present in
1928  * external WIMs, depending on the write flags provided.  */
1929 static void
1930 handle_stream_filtering(struct find_streams_ctx *ctx)
1931 {
1932         struct wim_lookup_table_entry *lte, *tmp;
1933
1934         if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
1935                                   WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
1936         {
1937                 for_lookup_table_entry(ctx->wim->lookup_table,
1938                                        mark_stream_not_filtered, ctx);
1939                 return;
1940         }
1941
1942         for_lookup_table_entry(ctx->wim->lookup_table,
1943                                process_filtered_stream, ctx);
1944
1945         /* Streams in logical write list that were filtered can be removed.  */
1946         list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
1947                                  write_streams_list)
1948                 if (lte->filtered)
1949                         list_del(&lte->write_streams_list);
1950 }
1951
1952 /* Prepares list of streams to write for the specified WIM image(s).  This wraps
1953  * around prepare_logical_stream_list() to handle filtering out streams already
1954  * present in the WIM or already present in external WIMs, depending on the
1955  * write flags provided.
1956  *
1957  * Note: some additional data is stored in each `struct wim_lookup_table_entry':
1958  *
1959  * - 'out_refcnt' is set to the number of references found for the logical write.
1960  *    This will be nonzero on all streams in the list returned by this function,
1961  *    but will also be nonzero on streams not in the list that were included in
1962  *    the logical write list, but filtered out from the returned list.
1963  * - 'filtered' is set to nonzero if the stream was filtered.  Filtered streams
1964  *   are not included in the list of streams returned by this function.
1965  * - 'unique_size' is set if the stream has a unique size among all streams in
1966  *   the logical write plus any filtered streams in the entire WIM that could
1967  *   potentially turn out to have the same checksum as a yet-to-be-checksummed
1968  *   stream being written.
1969  */
1970 static int
1971 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
1972                     struct list_head *stream_list)
1973 {
1974         int ret;
1975         bool streams_ok;
1976         struct find_streams_ctx ctx;
1977
1978         INIT_LIST_HEAD(&ctx.stream_list);
1979         ret = init_stream_size_table(&ctx.stream_size_tab,
1980                                      wim->lookup_table->capacity);
1981         if (ret)
1982                 return ret;
1983         ctx.write_flags = write_flags;
1984         ctx.wim = wim;
1985
1986         streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
1987
1988         ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
1989         if (ret)
1990                 goto out_destroy_table;
1991
1992         handle_stream_filtering(&ctx);
1993         list_transfer(&ctx.stream_list, stream_list);
1994         ret = 0;
1995 out_destroy_table:
1996         destroy_stream_size_table(&ctx.stream_size_tab);
1997         return ret;
1998 }
1999
2000 static int
2001 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2002                   unsigned num_threads,
2003                   wimlib_progress_func_t progress_func,
2004                   struct list_head *stream_list_override)
2005 {
2006         int ret;
2007         struct list_head _stream_list;
2008         struct list_head *stream_list;
2009         struct wim_lookup_table_entry *lte;
2010
2011         if (stream_list_override == NULL) {
2012                 /* Normal case: prepare stream list from image(s) being written.
2013                  */
2014                 stream_list = &_stream_list;
2015                 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2016                 if (ret)
2017                         return ret;
2018         } else {
2019                 /* Currently only as a result of wimlib_split() being called:
2020                  * use stream list already explicitly provided.  Use existing
2021                  * reference counts.  */
2022                 stream_list = stream_list_override;
2023                 list_for_each_entry(lte, stream_list, write_streams_list) {
2024                         lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2025                         lte->part_number = wim->hdr.part_number;
2026                 }
2027         }
2028
2029         return write_stream_list(stream_list,
2030                                  wim->lookup_table,
2031                                  &wim->out_fd,
2032                                  wim->compression_type,
2033                                  &wim->lzx_context,
2034                                  write_flags,
2035                                  num_threads,
2036                                  progress_func);
2037 }
2038
2039 static int
2040 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2041                              wimlib_progress_func_t progress_func)
2042 {
2043         int ret;
2044         int start_image;
2045         int end_image;
2046         int write_resource_flags;
2047
2048         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2049                 DEBUG("Not writing any metadata resources.");
2050                 return 0;
2051         }
2052
2053         write_resource_flags = write_flags_to_resource_flags(write_flags);
2054
2055         DEBUG("Writing metadata resources (offset=%"PRIu64")",
2056               wim->out_fd.offset);
2057
2058         if (progress_func)
2059                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2060
2061         if (image == WIMLIB_ALL_IMAGES) {
2062                 start_image = 1;
2063                 end_image = wim->hdr.image_count;
2064         } else {
2065                 start_image = image;
2066                 end_image = image;
2067         }
2068
2069         for (int i = start_image; i <= end_image; i++) {
2070                 struct wim_image_metadata *imd;
2071
2072                 imd = wim->image_metadata[i - 1];
2073                 /* Build a new metadata resource only if image was modified from
2074                  * the original (or was newly added).  Otherwise just copy the
2075                  * existing one.  */
2076                 if (imd->modified) {
2077                         DEBUG("Image %u was modified; building and writing new "
2078                               "metadata resource", i);
2079                         ret = write_metadata_resource(wim, i,
2080                                                       write_resource_flags);
2081                 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2082                         DEBUG("Image %u was not modified; re-using existing "
2083                               "metadata resource.", i);
2084                         copy_resource_entry(&imd->metadata_lte->output_resource_entry,
2085                                             &imd->metadata_lte->resource_entry);
2086                         ret = 0;
2087                 } else {
2088                         DEBUG("Image %u was not modified; copying existing "
2089                               "metadata resource.", i);
2090                         ret = write_wim_resource(imd->metadata_lte,
2091                                                  &wim->out_fd,
2092                                                  wim->compression_type,
2093                                                  &imd->metadata_lte->output_resource_entry,
2094                                                  write_resource_flags,
2095                                                  &wim->lzx_context);
2096                 }
2097                 if (ret)
2098                         return ret;
2099         }
2100         if (progress_func)
2101                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2102         return 0;
2103 }
2104
2105 static int
2106 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2107 {
2108         int raw_fd;
2109         DEBUG("Opening \"%"TS"\" for writing.", path);
2110
2111         raw_fd = topen(path, open_flags | O_BINARY, 0644);
2112         if (raw_fd < 0) {
2113                 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2114                 return WIMLIB_ERR_OPEN;
2115         }
2116         filedes_init(&wim->out_fd, raw_fd);
2117         return 0;
2118 }
2119
2120 static int
2121 close_wim_writable(WIMStruct *wim, int write_flags)
2122 {
2123         int ret = 0;
2124
2125         if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2126                 DEBUG("Closing WIM file.");
2127                 if (filedes_valid(&wim->out_fd))
2128                         if (filedes_close(&wim->out_fd))
2129                                 ret = WIMLIB_ERR_WRITE;
2130         }
2131         filedes_invalidate(&wim->out_fd);
2132         return ret;
2133 }
2134
2135 /*
2136  * finish_write():
2137  *
2138  * Finish writing a WIM file: write the lookup table, xml data, and integrity
2139  * table, then overwrite the WIM header.  By default, closes the WIM file
2140  * descriptor (@wim->out_fd) if successful.
2141  *
2142  * write_flags is a bitwise OR of the following:
2143  *
2144  *      (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2145  *              Include an integrity table.
2146  *
2147  *      (public) WIMLIB_WRITE_FLAG_FSYNC:
2148  *              fsync() the output file before closing it.
2149  *
2150  *      (public) WIMLIB_WRITE_FLAG_PIPABLE:
2151  *              Writing a pipable WIM, possibly to a pipe; include pipable WIM
2152  *              stream headers before the lookup table and XML data, and also
2153  *              write the WIM header at the end instead of seeking to the
2154  *              beginning.  Can't be combined with
2155  *              WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2156  *
2157  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2158  *              Don't write the lookup table.
2159  *
2160  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2161  *              When (if) writing the integrity table, re-use entries from the
2162  *              existing integrity table, if possible.
2163  *
2164  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2165  *              After writing the XML data but before writing the integrity
2166  *              table, write a temporary WIM header and flush the stream so that
2167  *              the WIM is less likely to become corrupted upon abrupt program
2168  *              termination.
2169  *      (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2170  *              Instead of overwriting the WIM header at the beginning of the
2171  *              file, simply append it to the end of the file.  (Used when
2172  *              writing to pipe.)
2173  *      (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2174  *              Do not close the file descriptor @wim->out_fd on either success
2175  *              on failure.
2176  *      (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2177  *              Use the existing <TOTALBYTES> stored in the in-memory XML
2178  *              information, rather than setting it to the offset of the XML
2179  *              data being written.
2180  */
2181 static int
2182 finish_write(WIMStruct *wim, int image, int write_flags,
2183              wimlib_progress_func_t progress_func,
2184              struct list_head *stream_list_override)
2185 {
2186         int ret;
2187         off_t hdr_offset;
2188         int write_resource_flags;
2189         off_t old_lookup_table_end;
2190         off_t new_lookup_table_end;
2191         u64 xml_totalbytes;
2192
2193         DEBUG("image=%d, write_flags=%08x", image, write_flags);
2194
2195         write_resource_flags = write_flags_to_resource_flags(write_flags);
2196
2197         /* In the WIM header, there is room for the resource entry for a
2198          * metadata resource labeled as the "boot metadata".  This entry should
2199          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
2200          * it should be a copy of the resource entry for the image that is
2201          * marked as bootable.  This is not well documented...  */
2202         if (wim->hdr.boot_idx == 0) {
2203                 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2204         } else {
2205                 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2206                             &wim->image_metadata[wim->hdr.boot_idx- 1
2207                                         ]->metadata_lte->output_resource_entry);
2208         }
2209
2210         /* Write lookup table.  (Save old position first.)  */
2211         old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2212                                wim->hdr.lookup_table_res_entry.size;
2213         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2214                 ret = write_wim_lookup_table(wim, image, write_flags,
2215                                              &wim->hdr.lookup_table_res_entry,
2216                                              stream_list_override);
2217                 if (ret)
2218                         return ret;
2219         }
2220
2221         /* Write XML data.  */
2222         xml_totalbytes = wim->out_fd.offset;
2223         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2224                 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2225         ret = write_wim_xml_data(wim, image, xml_totalbytes,
2226                                  &wim->hdr.xml_res_entry,
2227                                  write_resource_flags);
2228         if (ret)
2229                 return ret;
2230
2231         /* Write integrity table (optional).  */
2232         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2233                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2234                         struct wim_header checkpoint_hdr;
2235                         memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2236                         zero_resource_entry(&checkpoint_hdr.integrity);
2237                         checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2238                         ret = write_wim_header_at_offset(&checkpoint_hdr,
2239                                                          &wim->out_fd, 0);
2240                         if (ret)
2241                                 return ret;
2242                 }
2243
2244                 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2245                         old_lookup_table_end = 0;
2246
2247                 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2248                                        wim->hdr.lookup_table_res_entry.size;
2249
2250                 ret = write_integrity_table(wim,
2251                                             new_lookup_table_end,
2252                                             old_lookup_table_end,
2253                                             progress_func);
2254                 if (ret)
2255                         return ret;
2256         } else {
2257                 /* No integrity table.  */
2258                 zero_resource_entry(&wim->hdr.integrity);
2259         }
2260
2261         /* Now that all information in the WIM header has been determined, the
2262          * preliminary header written earlier can be overwritten, the header of
2263          * the existing WIM file can be overwritten, or the final header can be
2264          * written to the end of the pipable WIM.  */
2265         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2266         hdr_offset = 0;
2267         if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2268                 hdr_offset = wim->out_fd.offset;
2269         DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2270         ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2271         if (ret)
2272                 return ret;
2273
2274         /* Possibly sync file data to disk before closing.  On POSIX systems, it
2275          * is necessary to do this before using rename() to overwrite an
2276          * existing file with a new file.  Otherwise, data loss would occur if
2277          * the system is abruptly terminated when the metadata for the rename
2278          * operation has been written to disk, but the new file data has not.
2279          */
2280         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2281                 DEBUG("Syncing WIM file.");
2282                 if (fsync(wim->out_fd.fd)) {
2283                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
2284                         return WIMLIB_ERR_WRITE;
2285                 }
2286         }
2287
2288         if (close_wim_writable(wim, write_flags)) {
2289                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2290                 return WIMLIB_ERR_WRITE;
2291         }
2292
2293         return 0;
2294 }
2295
2296 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2297 int
2298 lock_wim(WIMStruct *wim, int fd)
2299 {
2300         int ret = 0;
2301         if (fd != -1 && !wim->wim_locked) {
2302                 ret = flock(fd, LOCK_EX | LOCK_NB);
2303                 if (ret != 0) {
2304                         if (errno == EWOULDBLOCK) {
2305                                 ERROR("`%"TS"' is already being modified or has been "
2306                                       "mounted read-write\n"
2307                                       "        by another process!", wim->filename);
2308                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
2309                         } else {
2310                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2311                                                    wim->filename);
2312                                 ret = 0;
2313                         }
2314                 } else {
2315                         wim->wim_locked = 1;
2316                 }
2317         }
2318         return ret;
2319 }
2320 #endif
2321
2322 /*
2323  * write_pipable_wim():
2324  *
2325  * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2326  * capable of being applied from a pipe).
2327  *
2328  * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2329  * images can be applied from them sequentially when the file data is sent over
2330  * a pipe.  In addition, a pipable WIM can be written sequentially to a pipe.
2331  * The modifications made to the WIM format for pipable WIMs are:
2332  *
2333  * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2334  *   of "MSWIM\0\0\0".  This lets wimlib know that the WIM is pipable and also
2335  *   stops other software from trying to read the file as a normal WIM.
2336  *
2337  * - The header at the beginning of the file does not contain all the normal
2338  *   information; in particular it will have all 0's for the lookup table and
2339  *   XML data resource entries.  This is because this information cannot be
2340  *   determined until the lookup table and XML data have been written.
2341  *   Consequently, wimlib will write the full header at the very end of the
2342  *   file.  The header at the end, however, is only used when reading the WIM
2343  *   from a seekable file (not a pipe).
2344  *
2345  * - An extra copy of the XML data is placed directly after the header.  This
2346  *   allows image names and sizes to be determined at an appropriate time when
2347  *   reading the WIM from a pipe.  This copy of the XML data is ignored if the
2348  *   WIM is read from a seekable file (not a pipe).
2349  *
2350  * - The format of resources, or streams, has been modified to allow them to be
2351  *   used before the "lookup table" has been read.  Each stream is prefixed with
2352  *   a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2353  *   wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2354  *   uncompressed stream size, and flags that indicate whether the stream is
2355  *   compressed.  The data of uncompressed streams then follows literally, while
2356  *   the data of compressed streams follows in a modified format.  Compressed
2357  *   streams do not begin with a chunk table, since the chunk table cannot be
2358  *   written until all chunks have been compressed.  Instead, each compressed
2359  *   chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2360  *   Furthermore, the chunk table is written at the end of the resource instead
2361  *   of the start.  Note: chunk offsets are given in the chunk table as if the
2362  *   `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2363  *   used if the WIM is being read from a seekable file (not a pipe).
2364  *
2365  * - Metadata resources always come before other file resources (streams).
2366  *   (This does not by itself constitute an incompatibility with normal WIMs,
2367  *   since this is valid in normal WIMs.)
2368  *
2369  * - At least up to the end of the file resources, all components must be packed
2370  *   as tightly as possible; there cannot be any "holes" in the WIM.  (This does
2371  *   not by itself consititute an incompatibility with normal WIMs, since this
2372  *   is valid in normal WIMs.)
2373  *
2374  * Note: the lookup table, XML data, and header at the end are not used when
2375  * applying from a pipe.  They exist to support functionality such as image
2376  * application and export when the WIM is *not* read from a pipe.
2377  *
2378  *   Layout of pipable WIM:
2379  *
2380  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2381  * | Header | XML data | Metadata resources | File resources | Lookup table | XML data  | Header |
2382  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2383  *
2384  *   Layout of normal WIM:
2385  *
2386  * +--------+-----------------------------+-------------------------+
2387  * | Header | File and metadata resources | Lookup table | XML data |
2388  * +--------+-----------------------------+-------------------------+
2389  *
2390  * An optional integrity table can follow the final XML data in both normal and
2391  * pipable WIMs.  However, due to implementation details, wimlib currently can
2392  * only include an integrity table in a pipable WIM when writing it to a
2393  * seekable file (not a pipe).
2394  *
2395  * Do note that since pipable WIMs are not supported by Microsoft's software,
2396  * wimlib does not create them unless explicitly requested (with
2397  * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2398  * characters to identify the file.
2399  */
2400 static int
2401 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2402                   unsigned num_threads, wimlib_progress_func_t progress_func,
2403                   struct list_head *stream_list_override)
2404 {
2405         int ret;
2406         struct resource_entry xml_res_entry;
2407
2408         WARNING("Creating a pipable WIM, which will "
2409                 "be incompatible\n"
2410                 "          with Microsoft's software (wimgapi/imagex/Dism).");
2411
2412         /* At this point, the header at the beginning of the file has already
2413          * been written.  */
2414
2415         /* For efficiency, when wimlib adds an image to the WIM with
2416          * wimlib_add_image(), the SHA1 message digests of files is not
2417          * calculated; instead, they are calculated while the files are being
2418          * written.  However, this does not work when writing a pipable WIM,
2419          * since when writing a stream to a pipable WIM, its SHA1 message digest
2420          * needs to be known before the stream data is written.  Therefore,
2421          * before getting much farther, we need to pre-calculate the SHA1
2422          * message digests of all streams that will be written.  */
2423         ret = wim_checksum_unhashed_streams(wim);
2424         if (ret)
2425                 return ret;
2426
2427         /* Write extra copy of the XML data.  */
2428         ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2429                                  &xml_res_entry,
2430                                  WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2431         if (ret)
2432                 return ret;
2433
2434         /* Write metadata resources for the image(s) being included in the
2435          * output WIM.  */
2436         ret = write_wim_metadata_resources(wim, image, write_flags,
2437                                            progress_func);
2438         if (ret)
2439                 return ret;
2440
2441         /* Write streams needed for the image(s) being included in the output
2442          * WIM, or streams needed for the split WIM part.  */
2443         return write_wim_streams(wim, image, write_flags, num_threads,
2444                                  progress_func, stream_list_override);
2445
2446         /* The lookup table, XML data, and header at end are handled by
2447          * finish_write().  */
2448 }
2449
2450 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2451  * descriptor.  */
2452 int
2453 write_wim_part(WIMStruct *wim,
2454                const void *path_or_fd,
2455                int image,
2456                int write_flags,
2457                unsigned num_threads,
2458                wimlib_progress_func_t progress_func,
2459                unsigned part_number,
2460                unsigned total_parts,
2461                struct list_head *stream_list_override,
2462                const u8 *guid)
2463 {
2464         int ret;
2465         struct wim_header hdr_save;
2466         struct list_head lt_stream_list_override;
2467
2468         if (total_parts == 1)
2469                 DEBUG("Writing standalone WIM.");
2470         else
2471                 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2472         if (image == WIMLIB_ALL_IMAGES)
2473                 DEBUG("Including all images.");
2474         else
2475                 DEBUG("Including image %d only.", image);
2476         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2477                 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2478         else
2479                 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2480         DEBUG("Write flags: 0x%08x", write_flags);
2481         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2482                 DEBUG("\tCHECK_INTEGRITY");
2483         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2484                 DEBUG("\tREBUILD");
2485         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2486                 DEBUG("\tRECOMPRESS");
2487         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2488                 DEBUG("\tFSYNC");
2489         if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2490                 DEBUG("\tFSYNC");
2491         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2492                 DEBUG("\tIGNORE_READONLY_FLAG");
2493         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2494                 DEBUG("\tPIPABLE");
2495         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2496                 DEBUG("\tFILE_DESCRIPTOR");
2497         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2498                 DEBUG("\tNO_METADATA");
2499         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2500                 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2501         if (num_threads == 0)
2502                 DEBUG("Number of threads: autodetect");
2503         else
2504                 DEBUG("Number of threads: %u", num_threads);
2505         DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2506         DEBUG("Stream list:       %s", (stream_list_override ? "specified" : "autodetect"));
2507         DEBUG("GUID:              %s", ((guid || wim->guid_set_explicitly) ?
2508                                         "specified" : "generate new"));
2509
2510         /* Internally, this is always called with a valid part number and total
2511          * parts.  */
2512         wimlib_assert(total_parts >= 1);
2513         wimlib_assert(part_number >= 1 && part_number <= total_parts);
2514
2515         /* A valid image (or all images) must be specified.  */
2516         if (image != WIMLIB_ALL_IMAGES &&
2517              (image < 1 || image > wim->hdr.image_count))
2518                 return WIMLIB_ERR_INVALID_IMAGE;
2519
2520         /* If we need to write metadata resources, make sure the ::WIMStruct has
2521          * the needed information attached (e.g. is not a resource-only WIM,
2522          * such as a non-first part of a split WIM).  */
2523         if (!wim_has_metadata(wim) &&
2524             !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2525                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2526
2527         /* Check for contradictory flags.  */
2528         if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2529                             WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2530                                 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2531                                     WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2532                 return WIMLIB_ERR_INVALID_PARAM;
2533
2534         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2535                             WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2536                                 == (WIMLIB_WRITE_FLAG_PIPABLE |
2537                                     WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2538                 return WIMLIB_ERR_INVALID_PARAM;
2539
2540         /* Save previous header, then start initializing the new one.  */
2541         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2542
2543         /* Set default integrity and pipable flags.  */
2544         if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2545                              WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2546                 if (wim_is_pipable(wim))
2547                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2548
2549         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2550                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2551                 if (wim_has_integrity_table(wim))
2552                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2553
2554         /* Set appropriate magic number.  */
2555         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2556                 wim->hdr.magic = PWM_MAGIC;
2557         else
2558                 wim->hdr.magic = WIM_MAGIC;
2559
2560         /* Clear header flags that will be set automatically.  */
2561         wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY          |
2562                             WIM_HDR_FLAG_RESOURCE_ONLY          |
2563                             WIM_HDR_FLAG_SPANNED                |
2564                             WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2565
2566         /* Set SPANNED header flag if writing part of a split WIM.  */
2567         if (total_parts != 1)
2568                 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2569
2570         /* Set part number and total parts of split WIM.  This will be 1 and 1
2571          * if the WIM is standalone.  */
2572         wim->hdr.part_number = part_number;
2573         wim->hdr.total_parts = total_parts;
2574
2575         /* Use GUID if specified; otherwise generate a new one.  */
2576         if (guid)
2577                 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2578         else if (!wim->guid_set_explicitly)
2579                 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2580
2581         /* Clear references to resources that have not been written yet.  */
2582         zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2583         zero_resource_entry(&wim->hdr.xml_res_entry);
2584         zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2585         zero_resource_entry(&wim->hdr.integrity);
2586
2587         /* Set image count and boot index correctly for single image writes.  */
2588         if (image != WIMLIB_ALL_IMAGES) {
2589                 wim->hdr.image_count = 1;
2590                 if (wim->hdr.boot_idx == image)
2591                         wim->hdr.boot_idx = 1;
2592                 else
2593                         wim->hdr.boot_idx = 0;
2594         }
2595
2596         /* Split WIMs can't be bootable.  */
2597         if (total_parts != 1)
2598                 wim->hdr.boot_idx = 0;
2599
2600         /* Initialize output file descriptor.  */
2601         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2602                 /* File descriptor was explicitly provided.  Return error if
2603                  * file descriptor is not seekable, unless writing a pipable WIM
2604                  * was requested.  */
2605                 wim->out_fd.fd = *(const int*)path_or_fd;
2606                 wim->out_fd.offset = 0;
2607                 if (!filedes_is_seekable(&wim->out_fd)) {
2608                         ret = WIMLIB_ERR_INVALID_PARAM;
2609                         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2610                                 goto out_restore_hdr;
2611                         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2612                                 ERROR("Can't include integrity check when "
2613                                       "writing pipable WIM to pipe!");
2614                                 goto out_restore_hdr;
2615                         }
2616                 }
2617
2618         } else {
2619                 /* Filename of WIM to write was provided; open file descriptor
2620                  * to it.  */
2621                 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2622                                         O_TRUNC | O_CREAT | O_RDWR);
2623                 if (ret)
2624                         goto out_restore_hdr;
2625         }
2626
2627         /* Write initial header.  This is merely a "dummy" header since it
2628          * doesn't have all the information yet, so it will be overwritten later
2629          * (unless writing a pipable WIM).  */
2630         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2631                 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2632         ret = write_wim_header(&wim->hdr, &wim->out_fd);
2633         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2634         if (ret)
2635                 goto out_restore_hdr;
2636
2637         if (stream_list_override) {
2638                 struct wim_lookup_table_entry *lte;
2639                 INIT_LIST_HEAD(&lt_stream_list_override);
2640                 list_for_each_entry(lte, stream_list_override,
2641                                     write_streams_list)
2642                 {
2643                         list_add_tail(&lte->lookup_table_list,
2644                                       &lt_stream_list_override);
2645                 }
2646         }
2647
2648         /* Write metadata resources and streams.  */
2649         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2650                 /* Default case: create a normal (non-pipable) WIM.  */
2651                 ret = write_wim_streams(wim, image, write_flags, num_threads,
2652                                         progress_func, stream_list_override);
2653                 if (ret)
2654                         goto out_restore_hdr;
2655
2656                 ret = write_wim_metadata_resources(wim, image, write_flags,
2657                                                    progress_func);
2658                 if (ret)
2659                         goto out_restore_hdr;
2660         } else {
2661                 /* Non-default case: create pipable WIM.  */
2662                 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2663                                         progress_func, stream_list_override);
2664                 if (ret)
2665                         goto out_restore_hdr;
2666                 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2667         }
2668
2669         if (stream_list_override)
2670                 stream_list_override = &lt_stream_list_override;
2671
2672         /* Write lookup table, XML data, and (optional) integrity table.  */
2673         ret = finish_write(wim, image, write_flags, progress_func,
2674                            stream_list_override);
2675 out_restore_hdr:
2676         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2677         (void)close_wim_writable(wim, write_flags);
2678         DEBUG("ret=%d", ret);
2679         return ret;
2680 }
2681
2682 /* Write a standalone WIM to a file or file descriptor.  */
2683 static int
2684 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2685                      int image, int write_flags, unsigned num_threads,
2686                      wimlib_progress_func_t progress_func)
2687 {
2688         return write_wim_part(wim, path_or_fd, image, write_flags,
2689                               num_threads, progress_func, 1, 1, NULL, NULL);
2690 }
2691
2692 /* API function documented in wimlib.h  */
2693 WIMLIBAPI int
2694 wimlib_write(WIMStruct *wim, const tchar *path,
2695              int image, int write_flags, unsigned num_threads,
2696              wimlib_progress_func_t progress_func)
2697 {
2698         if (!path)
2699                 return WIMLIB_ERR_INVALID_PARAM;
2700
2701         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2702
2703         return write_standalone_wim(wim, path, image, write_flags,
2704                                     num_threads, progress_func);
2705 }
2706
2707 /* API function documented in wimlib.h  */
2708 WIMLIBAPI int
2709 wimlib_write_to_fd(WIMStruct *wim, int fd,
2710                    int image, int write_flags, unsigned num_threads,
2711                    wimlib_progress_func_t progress_func)
2712 {
2713         if (fd < 0)
2714                 return WIMLIB_ERR_INVALID_PARAM;
2715
2716         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2717         write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2718
2719         return write_standalone_wim(wim, &fd, image, write_flags,
2720                                     num_threads, progress_func);
2721 }
2722
2723 static bool
2724 any_images_modified(WIMStruct *wim)
2725 {
2726         for (int i = 0; i < wim->hdr.image_count; i++)
2727                 if (wim->image_metadata[i]->modified)
2728                         return true;
2729         return false;
2730 }
2731
2732 static int
2733 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2734 {
2735         const WIMStruct *wim = _wim;
2736         off_t end_offset = *(const off_t*)wim->private;
2737
2738         if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == wim &&
2739             lte->resource_entry.offset + lte->resource_entry.size > end_offset)
2740                 return WIMLIB_ERR_RESOURCE_ORDER;
2741         return 0;
2742 }
2743
2744 /* Make sure no file or metadata resources are located after the XML data (or
2745  * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2746  * place and we return WIMLIB_ERR_RESOURCE_ORDER.  */
2747 static int
2748 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2749 {
2750         int ret;
2751         unsigned i;
2752
2753         wim->private = &end_offset;
2754         ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2755         if (ret)
2756                 return ret;
2757
2758         for (i = 0; i < wim->hdr.image_count; i++) {
2759                 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2760                 if (ret)
2761                         return ret;
2762         }
2763         return 0;
2764 }
2765
2766 /*
2767  * Overwrite a WIM, possibly appending streams to it.
2768  *
2769  * A WIM looks like (or is supposed to look like) the following:
2770  *
2771  *                   Header (212 bytes)
2772  *                   Streams and metadata resources (variable size)
2773  *                   Lookup table (variable size)
2774  *                   XML data (variable size)
2775  *                   Integrity table (optional) (variable size)
2776  *
2777  * If we are not adding any streams or metadata resources, the lookup table is
2778  * unchanged--- so we only need to overwrite the XML data, integrity table, and
2779  * header.  This operation is potentially unsafe if the program is abruptly
2780  * terminated while the XML data or integrity table are being overwritten, but
2781  * before the new header has been written.  To partially alleviate this problem,
2782  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2783  * finish_write() to cause a temporary WIM header to be written after the XML
2784  * data has been written.  This may prevent the WIM from becoming corrupted if
2785  * the program is terminated while the integrity table is being calculated (but
2786  * no guarantees, due to write re-ordering...).
2787  *
2788  * If we are adding new streams or images (metadata resources), the lookup table
2789  * needs to be changed, and those streams need to be written.  In this case, we
2790  * try to perform a safe update of the WIM file by writing the streams *after*
2791  * the end of the previous WIM, then writing the new lookup table, XML data, and
2792  * (optionally) integrity table following the new streams.  This will produce a
2793  * layout like the following:
2794  *
2795  *                   Header (212 bytes)
2796  *                   (OLD) Streams and metadata resources (variable size)
2797  *                   (OLD) Lookup table (variable size)
2798  *                   (OLD) XML data (variable size)
2799  *                   (OLD) Integrity table (optional) (variable size)
2800  *                   (NEW) Streams and metadata resources (variable size)
2801  *                   (NEW) Lookup table (variable size)
2802  *                   (NEW) XML data (variable size)
2803  *                   (NEW) Integrity table (optional) (variable size)
2804  *
2805  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2806  * the header is overwritten to point to the new lookup table, XML data, and
2807  * integrity table, to produce the following layout:
2808  *
2809  *                   Header (212 bytes)
2810  *                   Streams and metadata resources (variable size)
2811  *                   Nothing (variable size)
2812  *                   More Streams and metadata resources (variable size)
2813  *                   Lookup table (variable size)
2814  *                   XML data (variable size)
2815  *                   Integrity table (optional) (variable size)
2816  *
2817  * This method allows an image to be appended to a large WIM very quickly, and
2818  * is is crash-safe except in the case of write re-ordering, but the
2819  * disadvantage is that a small hole is left in the WIM where the old lookup
2820  * table, xml data, and integrity table were.  (These usually only take up a
2821  * small amount of space compared to the streams, however.)
2822  */
2823 static int
2824 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2825                       unsigned num_threads,
2826                       wimlib_progress_func_t progress_func)
2827 {
2828         int ret;
2829         struct list_head stream_list;
2830         off_t old_wim_end;
2831         u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2832         struct wim_header hdr_save;
2833
2834         DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2835
2836         /* Set default integrity flag.  */
2837         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2838                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2839                 if (wim_has_integrity_table(wim))
2840                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2841
2842         /* Set additional flags for overwrite.  */
2843         write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2844                        WIMLIB_WRITE_FLAG_STREAMS_OK;
2845
2846         /* Make sure that the integrity table (if present) is after the XML
2847          * data, and that there are no stream resources, metadata resources, or
2848          * lookup tables after the XML data.  Otherwise, these data would be
2849          * overwritten. */
2850         old_xml_begin = wim->hdr.xml_res_entry.offset;
2851         old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2852         old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2853                                wim->hdr.lookup_table_res_entry.size;
2854         if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2855                 WARNING("Didn't expect the integrity table to be before the XML data");
2856                 return WIMLIB_ERR_RESOURCE_ORDER;
2857         }
2858
2859         if (old_lookup_table_end > old_xml_begin) {
2860                 WARNING("Didn't expect the lookup table to be after the XML data");
2861                 return WIMLIB_ERR_RESOURCE_ORDER;
2862         }
2863
2864         /* Set @old_wim_end, which indicates the point beyond which we don't
2865          * allow any file and metadata resources to appear without returning
2866          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2867          * overwrite these resources). */
2868         if (!wim->deletion_occurred && !any_images_modified(wim)) {
2869                 /* If no images have been modified and no images have been
2870                  * deleted, a new lookup table does not need to be written.  We
2871                  * shall write the new XML data and optional integrity table
2872                  * immediately after the lookup table.  Note that this may
2873                  * overwrite an existing integrity table. */
2874                 DEBUG("Skipping writing lookup table "
2875                       "(no images modified or deleted)");
2876                 old_wim_end = old_lookup_table_end;
2877                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2878                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2879         } else if (wim->hdr.integrity.offset) {
2880                 /* Old WIM has an integrity table; begin writing new streams
2881                  * after it. */
2882                 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2883         } else {
2884                 /* No existing integrity table; begin writing new streams after
2885                  * the old XML data. */
2886                 old_wim_end = old_xml_end;
2887         }
2888
2889         ret = check_resource_offsets(wim, old_wim_end);
2890         if (ret)
2891                 return ret;
2892
2893         ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2894                                   &stream_list);
2895         if (ret)
2896                 return ret;
2897
2898         ret = open_wim_writable(wim, wim->filename, O_RDWR);
2899         if (ret)
2900                 return ret;
2901
2902         ret = lock_wim(wim, wim->out_fd.fd);
2903         if (ret)
2904                 goto out_close_wim;
2905
2906         /* Save original header so it can be restored in case of error  */
2907         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2908
2909         /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2910         wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2911         ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2912         if (ret) {
2913                 ERROR_WITH_ERRNO("Error updating WIM header flags");
2914                 goto out_restore_memory_hdr;
2915         }
2916
2917         if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2918                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2919                 ret = WIMLIB_ERR_WRITE;
2920                 goto out_restore_physical_hdr;
2921         }
2922
2923         ret = write_stream_list(&stream_list,
2924                                 wim->lookup_table,
2925                                 &wim->out_fd,
2926                                 wim->compression_type,
2927                                 &wim->lzx_context,
2928                                 write_flags,
2929                                 num_threads,
2930                                 progress_func);
2931         if (ret)
2932                 goto out_truncate;
2933
2934         ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2935                                            write_flags, progress_func);
2936         if (ret)
2937                 goto out_truncate;
2938
2939         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2940         ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2941                            progress_func, NULL);
2942         if (ret)
2943                 goto out_truncate;
2944
2945         goto out_unlock_wim;
2946
2947 out_truncate:
2948         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2949                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2950                         wim->filename, old_wim_end);
2951                 /* Return value of ftruncate() is ignored because this is
2952                  * already an error path.  */
2953                 (void)ftruncate(wim->out_fd.fd, old_wim_end);
2954         }
2955 out_restore_physical_hdr:
2956         (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
2957 out_restore_memory_hdr:
2958         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2959 out_close_wim:
2960         (void)close_wim_writable(wim, write_flags);
2961 out_unlock_wim:
2962         wim->wim_locked = 0;
2963         return ret;
2964 }
2965
2966 static int
2967 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2968                           unsigned num_threads,
2969                           wimlib_progress_func_t progress_func)
2970 {
2971         size_t wim_name_len;
2972         int ret;
2973
2974         DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2975
2976         /* Write the WIM to a temporary file in the same directory as the
2977          * original WIM. */
2978         wim_name_len = tstrlen(wim->filename);
2979         tchar tmpfile[wim_name_len + 10];
2980         tmemcpy(tmpfile, wim->filename, wim_name_len);
2981         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2982         tmpfile[wim_name_len + 9] = T('\0');
2983
2984         ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2985                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2986                            num_threads, progress_func);
2987         if (ret) {
2988                 tunlink(tmpfile);
2989                 return ret;
2990         }
2991
2992         close_wim(wim);
2993
2994         /* Rename the new WIM file to the original WIM file.  Note: on Windows
2995          * this actually calls win32_rename_replacement(), not _wrename(), so
2996          * that removing the existing destination file can be handled.  */
2997         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
2998         ret = trename(tmpfile, wim->filename);
2999         if (ret) {
3000                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3001                                  tmpfile, wim->filename);
3002         #ifdef __WIN32__
3003                 if (ret < 0)
3004         #endif
3005                 {
3006                         tunlink(tmpfile);
3007                 }
3008                 return WIMLIB_ERR_RENAME;
3009         }
3010
3011         if (progress_func) {
3012                 union wimlib_progress_info progress;
3013                 progress.rename.from = tmpfile;
3014                 progress.rename.to = wim->filename;
3015                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3016         }
3017         return 0;
3018 }
3019
3020 /* API function documented in wimlib.h  */
3021 WIMLIBAPI int
3022 wimlib_overwrite(WIMStruct *wim, int write_flags,
3023                  unsigned num_threads,
3024                  wimlib_progress_func_t progress_func)
3025 {
3026         int ret;
3027         u32 orig_hdr_flags;
3028
3029         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3030
3031         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3032                 return WIMLIB_ERR_INVALID_PARAM;
3033
3034         if (!wim->filename)
3035                 return WIMLIB_ERR_NO_FILENAME;
3036
3037         orig_hdr_flags = wim->hdr.flags;
3038         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3039                 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3040         ret = can_modify_wim(wim);
3041         wim->hdr.flags = orig_hdr_flags;
3042         if (ret)
3043                 return ret;
3044
3045         if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3046             && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3047                                 WIMLIB_WRITE_FLAG_PIPABLE))
3048             && !(wim_is_pipable(wim)))
3049         {
3050                 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3051                                             progress_func);
3052                 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3053                         return ret;
3054                 WARNING("Falling back to re-building entire WIM");
3055         }
3056         return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,
3057                                          progress_func);
3058 }