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