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