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