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