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