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