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