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