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