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