]> wimlib.net Git - wimlib/blob - src/write.c
Use read_stream_list() for extraction
[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                                  &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, ctx, 0);
1484         if (ret)
1485                 return ret;
1486         wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1487         return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1488 }
1489
1490 static int
1491 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1492 {
1493         struct main_writer_thread_ctx *ctx = _ctx;
1494         int ret;
1495
1496         if (lte->size < 1000 ||
1497             !must_compress_stream(lte, ctx->write_resource_flags,
1498                                   ctx->out_ctype, ctx->out_chunk_size))
1499         {
1500                 /* Stream is too small or isn't being compressed.  Process it by
1501                  * the main thread when we have a chance.  We can't necessarily
1502                  * process it right here, as the main thread could be in the
1503                  * middle of writing a different stream.  */
1504                 list_add_tail(&lte->write_streams_list, &ctx->serial_streams);
1505                 lte->deferred = 1;
1506                 ret = 0;
1507         } else {
1508                 ret = submit_stream_for_compression(lte, ctx);
1509         }
1510         lte->no_progress = 1;
1511         return ret;
1512 }
1513
1514 static long
1515 get_default_num_threads(void)
1516 {
1517 #ifdef __WIN32__
1518         return win32_get_number_of_processors();
1519 #else
1520         return sysconf(_SC_NPROCESSORS_ONLN);
1521 #endif
1522 }
1523
1524 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1525  * parameter and will perform compression using that many threads.  Falls
1526  * back to write_stream_list_serial() on certain errors, such as a failure to
1527  * create the number of threads requested.
1528  *
1529  * High level description of the algorithm for writing compressed streams in
1530  * parallel:  We perform compression on chunks rather than on full files.  The
1531  * currently executing thread becomes the main thread and is entirely in charge
1532  * of reading the data to compress (which may be in any location understood by
1533  * the resource code--- such as in an external file being captured, or in
1534  * another WIM file from which an image is being exported) and actually writing
1535  * the compressed data to the output file.  Additional threads are "compressor
1536  * threads" and all execute the compressor_thread_proc, where they repeatedly
1537  * retrieve buffers of data from the main thread, compress them, and hand them
1538  * back to the main thread.
1539  *
1540  * Certain streams, such as streams that do not need to be compressed (e.g.
1541  * input compression type same as output compression type) or streams of very
1542  * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1543  * handled entirely by the main thread at an appropriate time.
1544  *
1545  * At any given point in time, multiple streams may be having chunks compressed
1546  * concurrently.  The stream that the main thread is currently *reading* may be
1547  * later in the list that the stream that the main thread is currently
1548  * *writing*.  */
1549 static int
1550 write_stream_list_parallel(struct list_head *stream_list,
1551                            struct wim_lookup_table *lookup_table,
1552                            struct filedes *out_fd,
1553                            int out_ctype,
1554                            u32 out_chunk_size,
1555                            struct wimlib_lzx_context **comp_ctx,
1556                            int write_resource_flags,
1557                            struct write_streams_progress_data *progress_data,
1558                            unsigned num_threads)
1559 {
1560         int ret;
1561         struct shared_queue res_to_compress_queue;
1562         struct shared_queue compressed_res_queue;
1563         pthread_t *compressor_threads = NULL;
1564         union wimlib_progress_info *progress = &progress_data->progress;
1565         unsigned num_started_threads;
1566         bool can_retry = true;
1567
1568         if (num_threads == 0) {
1569                 long nthreads = get_default_num_threads();
1570                 if (nthreads < 1 || nthreads > UINT_MAX) {
1571                         WARNING("Could not determine number of processors! Assuming 1");
1572                         goto out_serial_quiet;
1573                 } else if (nthreads == 1) {
1574                         goto out_serial_quiet;
1575                 } else {
1576                         num_threads = nthreads;
1577                 }
1578         }
1579
1580         DEBUG("Writing stream list of size %"PRIu64" "
1581               "(parallel version, num_threads=%u)",
1582               progress->write_streams.total_streams, num_threads);
1583
1584         progress->write_streams.num_threads = num_threads;
1585
1586         static const size_t MESSAGES_PER_THREAD = 2;
1587         size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1588
1589         DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1590
1591         ret = shared_queue_init(&res_to_compress_queue, queue_size);
1592         if (ret)
1593                 goto out_serial;
1594
1595         ret = shared_queue_init(&compressed_res_queue, queue_size);
1596         if (ret)
1597                 goto out_destroy_res_to_compress_queue;
1598
1599         struct compressor_thread_params *params;
1600
1601         params = CALLOC(num_threads, sizeof(params[0]));
1602         if (params == NULL) {
1603                 ret = WIMLIB_ERR_NOMEM;
1604                 goto out_destroy_compressed_res_queue;
1605         }
1606
1607         for (unsigned i = 0; i < num_threads; i++) {
1608                 params[i].res_to_compress_queue = &res_to_compress_queue;
1609                 params[i].compressed_res_queue = &compressed_res_queue;
1610                 params[i].out_ctype = out_ctype;
1611                 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1612                         ret = wimlib_lzx_alloc_context(out_chunk_size,
1613                                                        NULL, &params[i].comp_ctx);
1614                         if (ret)
1615                                 goto out_free_params;
1616                 }
1617         }
1618
1619         compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1620         if (compressor_threads == NULL) {
1621                 ret = WIMLIB_ERR_NOMEM;
1622                 goto out_free_params;
1623         }
1624
1625         for (unsigned i = 0; i < num_threads; i++) {
1626                 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1627                 ret = pthread_create(&compressor_threads[i], NULL,
1628                                      compressor_thread_proc, &params[i]);
1629                 if (ret) {
1630                         errno = ret;
1631                         ret = -1;
1632                         ERROR_WITH_ERRNO("Failed to create compressor "
1633                                          "thread %u of %u",
1634                                          i + 1, num_threads);
1635                         num_started_threads = i;
1636                         goto out_join;
1637                 }
1638         }
1639         num_started_threads = num_threads;
1640
1641         if (progress_data->progress_func) {
1642                 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1643                                              progress);
1644         }
1645
1646         struct main_writer_thread_ctx ctx;
1647
1648         memset(&ctx, 0, sizeof(ctx));
1649
1650         ctx.stream_list           = stream_list;
1651         ctx.lookup_table          = lookup_table;
1652         ctx.out_fd                = out_fd;
1653         ctx.out_ctype             = out_ctype;
1654         ctx.out_chunk_size        = out_chunk_size;
1655         ctx.comp_ctx              = comp_ctx;
1656         ctx.res_to_compress_queue = &res_to_compress_queue;
1657         ctx.compressed_res_queue  = &compressed_res_queue;
1658         ctx.num_messages          = queue_size;
1659         ctx.write_resource_flags  = write_resource_flags;
1660         ctx.progress_data         = progress_data;
1661         ret = main_writer_thread_init_ctx(&ctx);
1662         if (ret)
1663                 goto out_join;
1664
1665         can_retry = false;
1666         ret = do_write_stream_list(stream_list, lookup_table,
1667                                    main_thread_process_next_stream,
1668                                    &ctx, progress_data);
1669         if (ret)
1670                 goto out_destroy_ctx;
1671
1672         /* The main thread has finished reading all streams that are going to be
1673          * compressed in parallel, and it now needs to wait for all remaining
1674          * chunks to be compressed so that the remaining streams can actually be
1675          * written to the output file.  Furthermore, any remaining streams that
1676          * had processing deferred to the main thread need to be handled.  These
1677          * tasks are done by the main_writer_thread_finish() function.  */
1678         ret = main_writer_thread_finish(&ctx);
1679 out_destroy_ctx:
1680         main_writer_thread_destroy_ctx(&ctx);
1681 out_join:
1682         for (unsigned i = 0; i < num_started_threads; i++)
1683                 shared_queue_put(&res_to_compress_queue, NULL);
1684
1685         for (unsigned i = 0; i < num_started_threads; i++) {
1686                 if (pthread_join(compressor_threads[i], NULL)) {
1687                         WARNING_WITH_ERRNO("Failed to join compressor "
1688                                            "thread %u of %u",
1689                                            i + 1, num_threads);
1690                 }
1691         }
1692         FREE(compressor_threads);
1693 out_free_params:
1694         for (unsigned i = 0; i < num_threads; i++)
1695                 wimlib_lzx_free_context(params[i].comp_ctx);
1696         FREE(params);
1697 out_destroy_compressed_res_queue:
1698         shared_queue_destroy(&compressed_res_queue);
1699 out_destroy_res_to_compress_queue:
1700         shared_queue_destroy(&res_to_compress_queue);
1701         if (!can_retry || (ret >= 0 && ret != WIMLIB_ERR_NOMEM))
1702                 return ret;
1703 out_serial:
1704         WARNING("Falling back to single-threaded compression");
1705 out_serial_quiet:
1706         return write_stream_list_serial(stream_list,
1707                                         lookup_table,
1708                                         out_fd,
1709                                         out_ctype,
1710                                         out_chunk_size,
1711                                         comp_ctx,
1712                                         write_resource_flags,
1713                                         progress_data);
1714
1715 }
1716 #endif
1717
1718 /* Write a list of streams to a WIM (@out_fd) using the compression type
1719  * @out_ctype, chunk size @out_chunk_size, and up to @num_threads compressor
1720  * threads.  */
1721 static int
1722 write_stream_list(struct list_head *stream_list,
1723                   struct wim_lookup_table *lookup_table,
1724                   struct filedes *out_fd, int out_ctype,
1725                   u32 out_chunk_size,
1726                   struct wimlib_lzx_context **comp_ctx,
1727                   int write_flags,
1728                   unsigned num_threads, wimlib_progress_func_t progress_func)
1729 {
1730         int ret;
1731         int write_resource_flags;
1732         u64 total_bytes;
1733         u64 total_compression_bytes;
1734         unsigned total_parts;
1735         WIMStruct *prev_wim_part;
1736         size_t num_streams;
1737         struct wim_lookup_table_entry *lte;
1738         struct write_streams_progress_data progress_data;
1739
1740         if (list_empty(stream_list)) {
1741                 DEBUG("No streams to write.");
1742                 return 0;
1743         }
1744
1745         write_resource_flags = write_flags_to_resource_flags(write_flags);
1746
1747         DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1748               out_fd->offset, write_resource_flags);
1749
1750         /* Sort the stream list into a good order for reading.  */
1751         ret = sort_stream_list_by_sequential_order(stream_list,
1752                                                    offsetof(struct wim_lookup_table_entry,
1753                                                             write_streams_list));
1754         if (ret)
1755                 return ret;
1756
1757         /* Calculate the total size of the streams to be written.  Note: this
1758          * will be the uncompressed size, as we may not know the compressed size
1759          * yet, and also this will assume that every unhashed stream will be
1760          * written (which will not necessarily be the case).  */
1761         total_bytes = 0;
1762         total_compression_bytes = 0;
1763         num_streams = 0;
1764         total_parts = 0;
1765         prev_wim_part = NULL;
1766         list_for_each_entry(lte, stream_list, write_streams_list) {
1767                 num_streams++;
1768                 total_bytes += lte->size;
1769                 if (must_compress_stream(lte, write_resource_flags,
1770                                          out_ctype, out_chunk_size))
1771                         total_compression_bytes += lte->size;
1772                 if (lte->resource_location == RESOURCE_IN_WIM) {
1773                         if (prev_wim_part != lte->rspec->wim) {
1774                                 prev_wim_part = lte->rspec->wim;
1775                                 total_parts++;
1776                         }
1777                 }
1778         }
1779
1780         memset(&progress_data, 0, sizeof(progress_data));
1781         progress_data.progress_func = progress_func;
1782
1783         progress_data.progress.write_streams.total_bytes       = total_bytes;
1784         progress_data.progress.write_streams.total_streams     = num_streams;
1785         progress_data.progress.write_streams.completed_bytes   = 0;
1786         progress_data.progress.write_streams.completed_streams = 0;
1787         progress_data.progress.write_streams.num_threads       = num_threads;
1788         progress_data.progress.write_streams.compression_type  = out_ctype;
1789         progress_data.progress.write_streams.total_parts       = total_parts;
1790         progress_data.progress.write_streams.completed_parts   = 0;
1791
1792         progress_data.next_progress = 0;
1793         progress_data.prev_wim_part = NULL;
1794
1795 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1796         if (total_compression_bytes >= 2000000 && num_threads != 1)
1797                 ret = write_stream_list_parallel(stream_list,
1798                                                  lookup_table,
1799                                                  out_fd,
1800                                                  out_ctype,
1801                                                  out_chunk_size,
1802                                                  comp_ctx,
1803                                                  write_resource_flags,
1804                                                  &progress_data,
1805                                                  num_threads);
1806         else
1807 #endif
1808                 ret = write_stream_list_serial(stream_list,
1809                                                lookup_table,
1810                                                out_fd,
1811                                                out_ctype,
1812                                                out_chunk_size,
1813                                                comp_ctx,
1814                                                write_resource_flags,
1815                                                &progress_data);
1816         if (ret == 0)
1817                 DEBUG("Successfully wrote stream list.");
1818         else
1819                 DEBUG("Failed to write stream list (ret=%d).", ret);
1820         return ret;
1821 }
1822
1823 struct stream_size_table {
1824         struct hlist_head *array;
1825         size_t num_entries;
1826         size_t capacity;
1827 };
1828
1829 static int
1830 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1831 {
1832         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1833         if (!tab->array)
1834                 return WIMLIB_ERR_NOMEM;
1835         tab->num_entries = 0;
1836         tab->capacity = capacity;
1837         return 0;
1838 }
1839
1840 static void
1841 destroy_stream_size_table(struct stream_size_table *tab)
1842 {
1843         FREE(tab->array);
1844 }
1845
1846 static int
1847 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1848 {
1849         struct stream_size_table *tab = _tab;
1850         size_t pos;
1851         struct wim_lookup_table_entry *same_size_lte;
1852         struct hlist_node *tmp;
1853
1854         pos = hash_u64(lte->size) % tab->capacity;
1855         lte->unique_size = 1;
1856         hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1857                 if (same_size_lte->size == lte->size) {
1858                         lte->unique_size = 0;
1859                         same_size_lte->unique_size = 0;
1860                         break;
1861                 }
1862         }
1863
1864         hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
1865         tab->num_entries++;
1866         return 0;
1867 }
1868
1869 struct find_streams_ctx {
1870         WIMStruct *wim;
1871         int write_flags;
1872         struct list_head stream_list;
1873         struct stream_size_table stream_size_tab;
1874 };
1875
1876 static void
1877 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1878                                 struct find_streams_ctx *ctx,
1879                                 unsigned nref)
1880 {
1881         if (lte->out_refcnt == 0) {
1882                 stream_size_table_insert(lte, &ctx->stream_size_tab);
1883                 list_add_tail(&lte->write_streams_list, &ctx->stream_list);
1884         }
1885         lte->out_refcnt += nref;
1886 }
1887
1888 static int
1889 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1890                                         void *_ctx)
1891 {
1892         struct find_streams_ctx *ctx = _ctx;
1893         lte->out_refcnt = 0;
1894         lte_reference_for_logical_write(lte, ctx,
1895                                         (lte->refcnt ? lte->refcnt : 1));
1896         return 0;
1897 }
1898
1899 static int
1900 inode_find_streams_to_write(struct wim_inode *inode,
1901                             struct wim_lookup_table *table,
1902                             struct find_streams_ctx *ctx)
1903 {
1904         struct wim_lookup_table_entry *lte;
1905         unsigned i;
1906
1907         for (i = 0; i <= inode->i_num_ads; i++) {
1908                 lte = inode_stream_lte(inode, i, table);
1909                 if (lte)
1910                         lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1911                 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1912                         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1913         }
1914         return 0;
1915 }
1916
1917 static int
1918 image_find_streams_to_write(WIMStruct *wim)
1919 {
1920         struct find_streams_ctx *ctx;
1921         struct wim_image_metadata *imd;
1922         struct wim_inode *inode;
1923         struct wim_lookup_table_entry *lte;
1924         int ret;
1925
1926         ctx = wim->private;
1927         imd = wim_get_current_image_metadata(wim);
1928
1929         image_for_each_unhashed_stream(lte, imd)
1930                 lte->out_refcnt = 0;
1931
1932         /* Go through this image's inodes to find any streams that have not been
1933          * found yet. */
1934         image_for_each_inode(inode, imd) {
1935                 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1936                 if (ret)
1937                         return ret;
1938         }
1939         return 0;
1940 }
1941
1942 /*
1943  * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1944  * the "logical write" of the WIM, meaning all streams that are referenced at
1945  * least once by dentries in the the image(s) being written.  'out_refcnt' on
1946  * each stream being included in the logical write is set to the number of
1947  * references from dentries in the image(s).  Furthermore, 'unique_size' on each
1948  * stream being included in the logical write is set to indicate whether that
1949  * stream has a unique size relative to the streams being included in the
1950  * logical write.  Still furthermore, 'part_number' on each stream being
1951  * included in the logical write is set to the part number given in the
1952  * in-memory header of @p wim.
1953  *
1954  * This is considered a "logical write" because it does not take into account
1955  * filtering out streams already present in the WIM (in the case of an in place
1956  * overwrite) or present in other WIMs (in case of creating delta WIM).
1957  */
1958 static int
1959 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1960                             struct find_streams_ctx *ctx)
1961 {
1962         int ret;
1963
1964         if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1965                            (image == 1 && wim->hdr.image_count == 1)))
1966         {
1967                 /* Fast case:  Assume that all streams are being written and
1968                  * that the reference counts are correct.  */
1969                 struct wim_lookup_table_entry *lte;
1970                 struct wim_image_metadata *imd;
1971                 unsigned i;
1972
1973                 for_lookup_table_entry(wim->lookup_table,
1974                                        do_lte_full_reference_for_logical_write, ctx);
1975                 for (i = 0; i < wim->hdr.image_count; i++) {
1976                         imd = wim->image_metadata[i];
1977                         image_for_each_unhashed_stream(lte, imd)
1978                                 do_lte_full_reference_for_logical_write(lte, ctx);
1979                 }
1980         } else {
1981                 /* Slow case:  Walk through the images being written and
1982                  * determine the streams referenced.  */
1983                 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1984                 wim->private = ctx;
1985                 ret = for_image(wim, image, image_find_streams_to_write);
1986                 if (ret)
1987                         return ret;
1988         }
1989
1990         return 0;
1991 }
1992
1993 static int
1994 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1995 {
1996         struct find_streams_ctx *ctx = _ctx;
1997         u16 filtered = 0;
1998
1999         /* Calculate and set lte->filtered.  */
2000         if (lte->resource_location == RESOURCE_IN_WIM) {
2001                 if (lte->rspec->wim == ctx->wim &&
2002                     (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
2003                         filtered |= FILTERED_SAME_WIM;
2004                 if (lte->rspec->wim != ctx->wim &&
2005                     (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
2006                         filtered |= FILTERED_EXTERNAL_WIM;
2007         }
2008         lte->filtered = filtered;
2009
2010         /* Filtered streams get inserted into the stream size table too, unless
2011          * they already were.  This is because streams that are checksummed
2012          * on-the-fly during the write should not be written if they are
2013          * duplicates of filtered stream.  */
2014         if (lte->filtered && lte->out_refcnt == 0)
2015                 stream_size_table_insert(lte, &ctx->stream_size_tab);
2016         return 0;
2017 }
2018
2019 static int
2020 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
2021 {
2022         lte->filtered = 0;
2023         return 0;
2024 }
2025
2026 /* Given the list of streams to include in a logical write of a WIM, handle
2027  * filtering out streams already present in the WIM or already present in
2028  * external WIMs, depending on the write flags provided.  */
2029 static void
2030 handle_stream_filtering(struct find_streams_ctx *ctx)
2031 {
2032         struct wim_lookup_table_entry *lte, *tmp;
2033
2034         if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2035                                   WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2036         {
2037                 for_lookup_table_entry(ctx->wim->lookup_table,
2038                                        mark_stream_not_filtered, ctx);
2039                 return;
2040         }
2041
2042         for_lookup_table_entry(ctx->wim->lookup_table,
2043                                process_filtered_stream, ctx);
2044
2045         /* Streams in logical write list that were filtered can be removed.  */
2046         list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2047                                  write_streams_list)
2048                 if (lte->filtered)
2049                         list_del(&lte->write_streams_list);
2050 }
2051
2052 /* Prepares list of streams to write for the specified WIM image(s).  This wraps
2053  * around prepare_logical_stream_list() to handle filtering out streams already
2054  * present in the WIM or already present in external WIMs, depending on the
2055  * write flags provided.
2056  *
2057  * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2058  *
2059  * - 'out_refcnt' is set to the number of references found for the logical write.
2060  *    This will be nonzero on all streams in the list returned by this function,
2061  *    but will also be nonzero on streams not in the list that were included in
2062  *    the logical write list, but filtered out from the returned list.
2063  * - 'filtered' is set to nonzero if the stream was filtered.  Filtered streams
2064  *   are not included in the list of streams returned by this function.
2065  * - 'unique_size' is set if the stream has a unique size among all streams in
2066  *   the logical write plus any filtered streams in the entire WIM that could
2067  *   potentially turn out to have the same checksum as a yet-to-be-checksummed
2068  *   stream being written.
2069  */
2070 static int
2071 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2072                     struct list_head *stream_list)
2073 {
2074         int ret;
2075         bool streams_ok;
2076         struct find_streams_ctx ctx;
2077
2078         INIT_LIST_HEAD(&ctx.stream_list);
2079         ret = init_stream_size_table(&ctx.stream_size_tab,
2080                                      wim->lookup_table->capacity);
2081         if (ret)
2082                 return ret;
2083         ctx.write_flags = write_flags;
2084         ctx.wim = wim;
2085
2086         streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2087
2088         ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2089         if (ret)
2090                 goto out_destroy_table;
2091
2092         handle_stream_filtering(&ctx);
2093         list_transfer(&ctx.stream_list, stream_list);
2094         ret = 0;
2095 out_destroy_table:
2096         destroy_stream_size_table(&ctx.stream_size_tab);
2097         return ret;
2098 }
2099
2100 static int
2101 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2102                   unsigned num_threads,
2103                   wimlib_progress_func_t progress_func,
2104                   struct list_head *stream_list_override)
2105 {
2106         int ret;
2107         struct list_head _stream_list;
2108         struct list_head *stream_list;
2109         struct wim_lookup_table_entry *lte;
2110
2111         if (stream_list_override == NULL) {
2112                 /* Normal case: prepare stream list from image(s) being written.
2113                  */
2114                 stream_list = &_stream_list;
2115                 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2116                 if (ret)
2117                         return ret;
2118         } else {
2119                 /* Currently only as a result of wimlib_split() being called:
2120                  * use stream list already explicitly provided.  Use existing
2121                  * reference counts.  */
2122                 stream_list = stream_list_override;
2123                 list_for_each_entry(lte, stream_list, write_streams_list)
2124                         lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2125         }
2126
2127         return write_stream_list(stream_list,
2128                                  wim->lookup_table,
2129                                  &wim->out_fd,
2130                                  wim->out_compression_type,
2131                                  wim->out_chunk_size,
2132                                  &wim->lzx_context,
2133                                  write_flags,
2134                                  num_threads,
2135                                  progress_func);
2136 }
2137
2138 static int
2139 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2140                              wimlib_progress_func_t progress_func)
2141 {
2142         int ret;
2143         int start_image;
2144         int end_image;
2145         int write_resource_flags;
2146
2147         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2148                 DEBUG("Not writing any metadata resources.");
2149                 return 0;
2150         }
2151
2152         write_resource_flags = write_flags_to_resource_flags(write_flags);
2153
2154         DEBUG("Writing metadata resources (offset=%"PRIu64")",
2155               wim->out_fd.offset);
2156
2157         if (progress_func)
2158                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2159
2160         if (image == WIMLIB_ALL_IMAGES) {
2161                 start_image = 1;
2162                 end_image = wim->hdr.image_count;
2163         } else {
2164                 start_image = image;
2165                 end_image = image;
2166         }
2167
2168         for (int i = start_image; i <= end_image; i++) {
2169                 struct wim_image_metadata *imd;
2170
2171                 imd = wim->image_metadata[i - 1];
2172                 /* Build a new metadata resource only if image was modified from
2173                  * the original (or was newly added).  Otherwise just copy the
2174                  * existing one.  */
2175                 if (imd->modified) {
2176                         DEBUG("Image %u was modified; building and writing new "
2177                               "metadata resource", i);
2178                         ret = write_metadata_resource(wim, i,
2179                                                       write_resource_flags);
2180                 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2181                         DEBUG("Image %u was not modified; re-using existing "
2182                               "metadata resource.", i);
2183                         wim_res_spec_to_hdr(imd->metadata_lte->rspec,
2184                                             &imd->metadata_lte->out_reshdr);
2185                         ret = 0;
2186                 } else {
2187                         DEBUG("Image %u was not modified; copying existing "
2188                               "metadata resource.", i);
2189                         ret = write_wim_resource(imd->metadata_lte,
2190                                                  &wim->out_fd,
2191                                                  wim->out_compression_type,
2192                                                  wim->out_chunk_size,
2193                                                  &imd->metadata_lte->out_reshdr,
2194                                                  write_resource_flags,
2195                                                  &wim->lzx_context);
2196                 }
2197                 if (ret)
2198                         return ret;
2199         }
2200         if (progress_func)
2201                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2202         return 0;
2203 }
2204
2205 static int
2206 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2207 {
2208         int raw_fd;
2209         DEBUG("Opening \"%"TS"\" for writing.", path);
2210
2211         raw_fd = topen(path, open_flags | O_BINARY, 0644);
2212         if (raw_fd < 0) {
2213                 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2214                 return WIMLIB_ERR_OPEN;
2215         }
2216         filedes_init(&wim->out_fd, raw_fd);
2217         return 0;
2218 }
2219
2220 static int
2221 close_wim_writable(WIMStruct *wim, int write_flags)
2222 {
2223         int ret = 0;
2224
2225         if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2226                 DEBUG("Closing WIM file.");
2227                 if (filedes_valid(&wim->out_fd))
2228                         if (filedes_close(&wim->out_fd))
2229                                 ret = WIMLIB_ERR_WRITE;
2230         }
2231         filedes_invalidate(&wim->out_fd);
2232         return ret;
2233 }
2234
2235 /*
2236  * finish_write():
2237  *
2238  * Finish writing a WIM file: write the lookup table, xml data, and integrity
2239  * table, then overwrite the WIM header.  By default, closes the WIM file
2240  * descriptor (@wim->out_fd) if successful.
2241  *
2242  * write_flags is a bitwise OR of the following:
2243  *
2244  *      (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2245  *              Include an integrity table.
2246  *
2247  *      (public) WIMLIB_WRITE_FLAG_FSYNC:
2248  *              fsync() the output file before closing it.
2249  *
2250  *      (public) WIMLIB_WRITE_FLAG_PIPABLE:
2251  *              Writing a pipable WIM, possibly to a pipe; include pipable WIM
2252  *              stream headers before the lookup table and XML data, and also
2253  *              write the WIM header at the end instead of seeking to the
2254  *              beginning.  Can't be combined with
2255  *              WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2256  *
2257  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2258  *              Don't write the lookup table.
2259  *
2260  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2261  *              When (if) writing the integrity table, re-use entries from the
2262  *              existing integrity table, if possible.
2263  *
2264  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2265  *              After writing the XML data but before writing the integrity
2266  *              table, write a temporary WIM header and flush the stream so that
2267  *              the WIM is less likely to become corrupted upon abrupt program
2268  *              termination.
2269  *      (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2270  *              Instead of overwriting the WIM header at the beginning of the
2271  *              file, simply append it to the end of the file.  (Used when
2272  *              writing to pipe.)
2273  *      (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2274  *              Do not close the file descriptor @wim->out_fd on either success
2275  *              on failure.
2276  *      (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2277  *              Use the existing <TOTALBYTES> stored in the in-memory XML
2278  *              information, rather than setting it to the offset of the XML
2279  *              data being written.
2280  */
2281 static int
2282 finish_write(WIMStruct *wim, int image, int write_flags,
2283              wimlib_progress_func_t progress_func,
2284              struct list_head *stream_list_override)
2285 {
2286         int ret;
2287         off_t hdr_offset;
2288         int write_resource_flags;
2289         off_t old_lookup_table_end;
2290         off_t new_lookup_table_end;
2291         u64 xml_totalbytes;
2292
2293         DEBUG("image=%d, write_flags=%08x", image, write_flags);
2294
2295         write_resource_flags = write_flags_to_resource_flags(write_flags);
2296
2297         /* In the WIM header, there is room for the resource entry for a
2298          * metadata resource labeled as the "boot metadata".  This entry should
2299          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
2300          * it should be a copy of the resource entry for the image that is
2301          * marked as bootable.  This is not well documented...  */
2302         if (wim->hdr.boot_idx == 0) {
2303                 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2304         } else {
2305                 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2306                             &wim->image_metadata[wim->hdr.boot_idx- 1
2307                                         ]->metadata_lte->out_reshdr);
2308         }
2309
2310         /* Write lookup table.  (Save old position first.)  */
2311         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2312                                wim->hdr.lookup_table_reshdr.size_in_wim;
2313         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2314                 ret = write_wim_lookup_table(wim, image, write_flags,
2315                                              &wim->hdr.lookup_table_reshdr,
2316                                              stream_list_override);
2317                 if (ret)
2318                         return ret;
2319         }
2320
2321         /* Write XML data.  */
2322         xml_totalbytes = wim->out_fd.offset;
2323         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2324                 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2325         ret = write_wim_xml_data(wim, image, xml_totalbytes,
2326                                  &wim->hdr.xml_data_reshdr,
2327                                  write_resource_flags);
2328         if (ret)
2329                 return ret;
2330
2331         /* Write integrity table (optional).  */
2332         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2333                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2334                         struct wim_header checkpoint_hdr;
2335                         memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2336                         zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2337                         checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2338                         ret = write_wim_header_at_offset(&checkpoint_hdr,
2339                                                          &wim->out_fd, 0);
2340                         if (ret)
2341                                 return ret;
2342                 }
2343
2344                 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2345                         old_lookup_table_end = 0;
2346
2347                 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2348                                        wim->hdr.lookup_table_reshdr.size_in_wim;
2349
2350                 ret = write_integrity_table(wim,
2351                                             new_lookup_table_end,
2352                                             old_lookup_table_end,
2353                                             progress_func);
2354                 if (ret)
2355                         return ret;
2356         } else {
2357                 /* No integrity table.  */
2358                 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2359         }
2360
2361         /* Now that all information in the WIM header has been determined, the
2362          * preliminary header written earlier can be overwritten, the header of
2363          * the existing WIM file can be overwritten, or the final header can be
2364          * written to the end of the pipable WIM.  */
2365         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2366         hdr_offset = 0;
2367         if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2368                 hdr_offset = wim->out_fd.offset;
2369         DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2370         ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2371         if (ret)
2372                 return ret;
2373
2374         /* Possibly sync file data to disk before closing.  On POSIX systems, it
2375          * is necessary to do this before using rename() to overwrite an
2376          * existing file with a new file.  Otherwise, data loss would occur if
2377          * the system is abruptly terminated when the metadata for the rename
2378          * operation has been written to disk, but the new file data has not.
2379          */
2380         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2381                 DEBUG("Syncing WIM file.");
2382                 if (fsync(wim->out_fd.fd)) {
2383                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
2384                         return WIMLIB_ERR_WRITE;
2385                 }
2386         }
2387
2388         if (close_wim_writable(wim, write_flags)) {
2389                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2390                 return WIMLIB_ERR_WRITE;
2391         }
2392
2393         return 0;
2394 }
2395
2396 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2397 int
2398 lock_wim(WIMStruct *wim, int fd)
2399 {
2400         int ret = 0;
2401         if (fd != -1 && !wim->wim_locked) {
2402                 ret = flock(fd, LOCK_EX | LOCK_NB);
2403                 if (ret != 0) {
2404                         if (errno == EWOULDBLOCK) {
2405                                 ERROR("`%"TS"' is already being modified or has been "
2406                                       "mounted read-write\n"
2407                                       "        by another process!", wim->filename);
2408                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
2409                         } else {
2410                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2411                                                    wim->filename);
2412                                 ret = 0;
2413                         }
2414                 } else {
2415                         wim->wim_locked = 1;
2416                 }
2417         }
2418         return ret;
2419 }
2420 #endif
2421
2422 /*
2423  * write_pipable_wim():
2424  *
2425  * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2426  * capable of being applied from a pipe).
2427  *
2428  * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2429  * images can be applied from them sequentially when the file data is sent over
2430  * a pipe.  In addition, a pipable WIM can be written sequentially to a pipe.
2431  * The modifications made to the WIM format for pipable WIMs are:
2432  *
2433  * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2434  *   of "MSWIM\0\0\0".  This lets wimlib know that the WIM is pipable and also
2435  *   stops other software from trying to read the file as a normal WIM.
2436  *
2437  * - The header at the beginning of the file does not contain all the normal
2438  *   information; in particular it will have all 0's for the lookup table and
2439  *   XML data resource entries.  This is because this information cannot be
2440  *   determined until the lookup table and XML data have been written.
2441  *   Consequently, wimlib will write the full header at the very end of the
2442  *   file.  The header at the end, however, is only used when reading the WIM
2443  *   from a seekable file (not a pipe).
2444  *
2445  * - An extra copy of the XML data is placed directly after the header.  This
2446  *   allows image names and sizes to be determined at an appropriate time when
2447  *   reading the WIM from a pipe.  This copy of the XML data is ignored if the
2448  *   WIM is read from a seekable file (not a pipe).
2449  *
2450  * - The format of resources, or streams, has been modified to allow them to be
2451  *   used before the "lookup table" has been read.  Each stream is prefixed with
2452  *   a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2453  *   wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2454  *   uncompressed stream size, and flags that indicate whether the stream is
2455  *   compressed.  The data of uncompressed streams then follows literally, while
2456  *   the data of compressed streams follows in a modified format.  Compressed
2457  *   streams do not begin with a chunk table, since the chunk table cannot be
2458  *   written until all chunks have been compressed.  Instead, each compressed
2459  *   chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2460  *   Furthermore, the chunk table is written at the end of the resource instead
2461  *   of the start.  Note: chunk offsets are given in the chunk table as if the
2462  *   `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2463  *   used if the WIM is being read from a seekable file (not a pipe).
2464  *
2465  * - Metadata resources always come before other file resources (streams).
2466  *   (This does not by itself constitute an incompatibility with normal WIMs,
2467  *   since this is valid in normal WIMs.)
2468  *
2469  * - At least up to the end of the file resources, all components must be packed
2470  *   as tightly as possible; there cannot be any "holes" in the WIM.  (This does
2471  *   not by itself consititute an incompatibility with normal WIMs, since this
2472  *   is valid in normal WIMs.)
2473  *
2474  * Note: the lookup table, XML data, and header at the end are not used when
2475  * applying from a pipe.  They exist to support functionality such as image
2476  * application and export when the WIM is *not* read from a pipe.
2477  *
2478  *   Layout of pipable WIM:
2479  *
2480  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2481  * | Header | XML data | Metadata resources | File resources | Lookup table | XML data  | Header |
2482  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2483  *
2484  *   Layout of normal WIM:
2485  *
2486  * +--------+-----------------------------+-------------------------+
2487  * | Header | File and metadata resources | Lookup table | XML data |
2488  * +--------+-----------------------------+-------------------------+
2489  *
2490  * An optional integrity table can follow the final XML data in both normal and
2491  * pipable WIMs.  However, due to implementation details, wimlib currently can
2492  * only include an integrity table in a pipable WIM when writing it to a
2493  * seekable file (not a pipe).
2494  *
2495  * Do note that since pipable WIMs are not supported by Microsoft's software,
2496  * wimlib does not create them unless explicitly requested (with
2497  * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2498  * characters to identify the file.
2499  */
2500 static int
2501 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2502                   unsigned num_threads, wimlib_progress_func_t progress_func,
2503                   struct list_head *stream_list_override)
2504 {
2505         int ret;
2506         struct wim_reshdr xml_reshdr;
2507
2508         WARNING("Creating a pipable WIM, which will "
2509                 "be incompatible\n"
2510                 "          with Microsoft's software (wimgapi/imagex/Dism).");
2511
2512         /* At this point, the header at the beginning of the file has already
2513          * been written.  */
2514
2515         /* For efficiency, when wimlib adds an image to the WIM with
2516          * wimlib_add_image(), the SHA1 message digests of files is not
2517          * calculated; instead, they are calculated while the files are being
2518          * written.  However, this does not work when writing a pipable WIM,
2519          * since when writing a stream to a pipable WIM, its SHA1 message digest
2520          * needs to be known before the stream data is written.  Therefore,
2521          * before getting much farther, we need to pre-calculate the SHA1
2522          * message digests of all streams that will be written.  */
2523         ret = wim_checksum_unhashed_streams(wim);
2524         if (ret)
2525                 return ret;
2526
2527         /* Write extra copy of the XML data.  */
2528         ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2529                                  &xml_reshdr,
2530                                  WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2531         if (ret)
2532                 return ret;
2533
2534         /* Write metadata resources for the image(s) being included in the
2535          * output WIM.  */
2536         ret = write_wim_metadata_resources(wim, image, write_flags,
2537                                            progress_func);
2538         if (ret)
2539                 return ret;
2540
2541         /* Write streams needed for the image(s) being included in the output
2542          * WIM, or streams needed for the split WIM part.  */
2543         return write_wim_streams(wim, image, write_flags, num_threads,
2544                                  progress_func, stream_list_override);
2545
2546         /* The lookup table, XML data, and header at end are handled by
2547          * finish_write().  */
2548 }
2549
2550 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2551  * descriptor.  */
2552 int
2553 write_wim_part(WIMStruct *wim,
2554                const void *path_or_fd,
2555                int image,
2556                int write_flags,
2557                unsigned num_threads,
2558                wimlib_progress_func_t progress_func,
2559                unsigned part_number,
2560                unsigned total_parts,
2561                struct list_head *stream_list_override,
2562                const u8 *guid)
2563 {
2564         int ret;
2565         struct wim_header hdr_save;
2566         struct list_head lt_stream_list_override;
2567
2568         if (total_parts == 1)
2569                 DEBUG("Writing standalone WIM.");
2570         else
2571                 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2572         if (image == WIMLIB_ALL_IMAGES)
2573                 DEBUG("Including all images.");
2574         else
2575                 DEBUG("Including image %d only.", image);
2576         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2577                 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2578         else
2579                 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2580         DEBUG("Write flags: 0x%08x", write_flags);
2581         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2582                 DEBUG("\tCHECK_INTEGRITY");
2583         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2584                 DEBUG("\tREBUILD");
2585         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2586                 DEBUG("\tRECOMPRESS");
2587         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2588                 DEBUG("\tFSYNC");
2589         if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2590                 DEBUG("\tFSYNC");
2591         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2592                 DEBUG("\tIGNORE_READONLY_FLAG");
2593         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2594                 DEBUG("\tPIPABLE");
2595         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2596                 DEBUG("\tFILE_DESCRIPTOR");
2597         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2598                 DEBUG("\tNO_METADATA");
2599         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2600                 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2601         if (num_threads == 0)
2602                 DEBUG("Number of threads: autodetect");
2603         else
2604                 DEBUG("Number of threads: %u", num_threads);
2605         DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2606         DEBUG("Stream list:       %s", (stream_list_override ? "specified" : "autodetect"));
2607         DEBUG("GUID:              %s", ((guid || wim->guid_set_explicitly) ?
2608                                         "specified" : "generate new"));
2609
2610         /* Internally, this is always called with a valid part number and total
2611          * parts.  */
2612         wimlib_assert(total_parts >= 1);
2613         wimlib_assert(part_number >= 1 && part_number <= total_parts);
2614
2615         /* A valid image (or all images) must be specified.  */
2616         if (image != WIMLIB_ALL_IMAGES &&
2617              (image < 1 || image > wim->hdr.image_count))
2618                 return WIMLIB_ERR_INVALID_IMAGE;
2619
2620         /* If we need to write metadata resources, make sure the ::WIMStruct has
2621          * the needed information attached (e.g. is not a resource-only WIM,
2622          * such as a non-first part of a split WIM).  */
2623         if (!wim_has_metadata(wim) &&
2624             !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2625                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2626
2627         /* Check for contradictory flags.  */
2628         if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2629                             WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2630                                 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2631                                     WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2632                 return WIMLIB_ERR_INVALID_PARAM;
2633
2634         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2635                             WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2636                                 == (WIMLIB_WRITE_FLAG_PIPABLE |
2637                                     WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2638                 return WIMLIB_ERR_INVALID_PARAM;
2639
2640         /* Save previous header, then start initializing the new one.  */
2641         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2642
2643         /* Set default integrity and pipable flags.  */
2644         if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2645                              WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2646                 if (wim_is_pipable(wim))
2647                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2648
2649         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2650                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2651                 if (wim_has_integrity_table(wim))
2652                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2653
2654         /* Set appropriate magic number.  */
2655         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2656                 wim->hdr.magic = PWM_MAGIC;
2657         else
2658                 wim->hdr.magic = WIM_MAGIC;
2659
2660         /* Clear header flags that will be set automatically.  */
2661         wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY          |
2662                             WIM_HDR_FLAG_RESOURCE_ONLY          |
2663                             WIM_HDR_FLAG_SPANNED                |
2664                             WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2665
2666         /* Set SPANNED header flag if writing part of a split WIM.  */
2667         if (total_parts != 1)
2668                 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2669
2670         /* Set part number and total parts of split WIM.  This will be 1 and 1
2671          * if the WIM is standalone.  */
2672         wim->hdr.part_number = part_number;
2673         wim->hdr.total_parts = total_parts;
2674
2675         /* Set compression type if different.  */
2676         if (wim->compression_type != wim->out_compression_type) {
2677                 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2678                 wimlib_assert(ret == 0);
2679         }
2680
2681         /* Set chunk size if different.  */
2682         wim->hdr.chunk_size = wim->out_chunk_size;
2683
2684         /* Use GUID if specified; otherwise generate a new one.  */
2685         if (guid)
2686                 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2687         else if (!wim->guid_set_explicitly)
2688                 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2689
2690         /* Clear references to resources that have not been written yet.  */
2691         zero_reshdr(&wim->hdr.lookup_table_reshdr);
2692         zero_reshdr(&wim->hdr.xml_data_reshdr);
2693         zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2694         zero_reshdr(&wim->hdr.integrity_table_reshdr);
2695
2696         /* Set image count and boot index correctly for single image writes.  */
2697         if (image != WIMLIB_ALL_IMAGES) {
2698                 wim->hdr.image_count = 1;
2699                 if (wim->hdr.boot_idx == image)
2700                         wim->hdr.boot_idx = 1;
2701                 else
2702                         wim->hdr.boot_idx = 0;
2703         }
2704
2705         /* Split WIMs can't be bootable.  */
2706         if (total_parts != 1)
2707                 wim->hdr.boot_idx = 0;
2708
2709         /* Initialize output file descriptor.  */
2710         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2711                 /* File descriptor was explicitly provided.  Return error if
2712                  * file descriptor is not seekable, unless writing a pipable WIM
2713                  * was requested.  */
2714                 wim->out_fd.fd = *(const int*)path_or_fd;
2715                 wim->out_fd.offset = 0;
2716                 if (!filedes_is_seekable(&wim->out_fd)) {
2717                         ret = WIMLIB_ERR_INVALID_PARAM;
2718                         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2719                                 goto out_restore_hdr;
2720                         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2721                                 ERROR("Can't include integrity check when "
2722                                       "writing pipable WIM to pipe!");
2723                                 goto out_restore_hdr;
2724                         }
2725                 }
2726
2727         } else {
2728                 /* Filename of WIM to write was provided; open file descriptor
2729                  * to it.  */
2730                 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2731                                         O_TRUNC | O_CREAT | O_RDWR);
2732                 if (ret)
2733                         goto out_restore_hdr;
2734         }
2735
2736         /* Write initial header.  This is merely a "dummy" header since it
2737          * doesn't have all the information yet, so it will be overwritten later
2738          * (unless writing a pipable WIM).  */
2739         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2740                 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2741         ret = write_wim_header(&wim->hdr, &wim->out_fd);
2742         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2743         if (ret)
2744                 goto out_restore_hdr;
2745
2746         if (stream_list_override) {
2747                 struct wim_lookup_table_entry *lte;
2748                 INIT_LIST_HEAD(&lt_stream_list_override);
2749                 list_for_each_entry(lte, stream_list_override,
2750                                     write_streams_list)
2751                 {
2752                         list_add_tail(&lte->lookup_table_list,
2753                                       &lt_stream_list_override);
2754                 }
2755         }
2756
2757         /* Write metadata resources and streams.  */
2758         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2759                 /* Default case: create a normal (non-pipable) WIM.  */
2760                 ret = write_wim_streams(wim, image, write_flags, num_threads,
2761                                         progress_func, stream_list_override);
2762                 if (ret)
2763                         goto out_restore_hdr;
2764
2765                 ret = write_wim_metadata_resources(wim, image, write_flags,
2766                                                    progress_func);
2767                 if (ret)
2768                         goto out_restore_hdr;
2769         } else {
2770                 /* Non-default case: create pipable WIM.  */
2771                 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2772                                         progress_func, stream_list_override);
2773                 if (ret)
2774                         goto out_restore_hdr;
2775                 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2776         }
2777
2778         if (stream_list_override)
2779                 stream_list_override = &lt_stream_list_override;
2780
2781         /* Write lookup table, XML data, and (optional) integrity table.  */
2782         ret = finish_write(wim, image, write_flags, progress_func,
2783                            stream_list_override);
2784 out_restore_hdr:
2785         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2786         (void)close_wim_writable(wim, write_flags);
2787         DEBUG("ret=%d", ret);
2788         return ret;
2789 }
2790
2791 /* Write a standalone WIM to a file or file descriptor.  */
2792 static int
2793 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2794                      int image, int write_flags, unsigned num_threads,
2795                      wimlib_progress_func_t progress_func)
2796 {
2797         return write_wim_part(wim, path_or_fd, image, write_flags,
2798                               num_threads, progress_func, 1, 1, NULL, NULL);
2799 }
2800
2801 /* API function documented in wimlib.h  */
2802 WIMLIBAPI int
2803 wimlib_write(WIMStruct *wim, const tchar *path,
2804              int image, int write_flags, unsigned num_threads,
2805              wimlib_progress_func_t progress_func)
2806 {
2807         if (!path)
2808                 return WIMLIB_ERR_INVALID_PARAM;
2809
2810         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2811
2812         return write_standalone_wim(wim, path, image, write_flags,
2813                                     num_threads, progress_func);
2814 }
2815
2816 /* API function documented in wimlib.h  */
2817 WIMLIBAPI int
2818 wimlib_write_to_fd(WIMStruct *wim, int fd,
2819                    int image, int write_flags, unsigned num_threads,
2820                    wimlib_progress_func_t progress_func)
2821 {
2822         if (fd < 0)
2823                 return WIMLIB_ERR_INVALID_PARAM;
2824
2825         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2826         write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2827
2828         return write_standalone_wim(wim, &fd, image, write_flags,
2829                                     num_threads, progress_func);
2830 }
2831
2832 static bool
2833 any_images_modified(WIMStruct *wim)
2834 {
2835         for (int i = 0; i < wim->hdr.image_count; i++)
2836                 if (wim->image_metadata[i]->modified)
2837                         return true;
2838         return false;
2839 }
2840
2841 static int
2842 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2843 {
2844         const WIMStruct *wim = _wim;
2845         off_t end_offset = *(const off_t*)wim->private;
2846
2847         if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2848             lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2849                 return WIMLIB_ERR_RESOURCE_ORDER;
2850         return 0;
2851 }
2852
2853 /* Make sure no file or metadata resources are located after the XML data (or
2854  * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2855  * place and we return WIMLIB_ERR_RESOURCE_ORDER.  */
2856 static int
2857 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2858 {
2859         int ret;
2860         unsigned i;
2861
2862         wim->private = &end_offset;
2863         ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2864         if (ret)
2865                 return ret;
2866
2867         for (i = 0; i < wim->hdr.image_count; i++) {
2868                 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2869                 if (ret)
2870                         return ret;
2871         }
2872         return 0;
2873 }
2874
2875 /*
2876  * Overwrite a WIM, possibly appending streams to it.
2877  *
2878  * A WIM looks like (or is supposed to look like) the following:
2879  *
2880  *                   Header (212 bytes)
2881  *                   Streams and metadata resources (variable size)
2882  *                   Lookup table (variable size)
2883  *                   XML data (variable size)
2884  *                   Integrity table (optional) (variable size)
2885  *
2886  * If we are not adding any streams or metadata resources, the lookup table is
2887  * unchanged--- so we only need to overwrite the XML data, integrity table, and
2888  * header.  This operation is potentially unsafe if the program is abruptly
2889  * terminated while the XML data or integrity table are being overwritten, but
2890  * before the new header has been written.  To partially alleviate this problem,
2891  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2892  * finish_write() to cause a temporary WIM header to be written after the XML
2893  * data has been written.  This may prevent the WIM from becoming corrupted if
2894  * the program is terminated while the integrity table is being calculated (but
2895  * no guarantees, due to write re-ordering...).
2896  *
2897  * If we are adding new streams or images (metadata resources), the lookup table
2898  * needs to be changed, and those streams need to be written.  In this case, we
2899  * try to perform a safe update of the WIM file by writing the streams *after*
2900  * the end of the previous WIM, then writing the new lookup table, XML data, and
2901  * (optionally) integrity table following the new streams.  This will produce a
2902  * layout like the following:
2903  *
2904  *                   Header (212 bytes)
2905  *                   (OLD) Streams and metadata resources (variable size)
2906  *                   (OLD) Lookup table (variable size)
2907  *                   (OLD) XML data (variable size)
2908  *                   (OLD) Integrity table (optional) (variable size)
2909  *                   (NEW) Streams and metadata resources (variable size)
2910  *                   (NEW) Lookup table (variable size)
2911  *                   (NEW) XML data (variable size)
2912  *                   (NEW) Integrity table (optional) (variable size)
2913  *
2914  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2915  * the header is overwritten to point to the new lookup table, XML data, and
2916  * integrity table, to produce the following layout:
2917  *
2918  *                   Header (212 bytes)
2919  *                   Streams and metadata resources (variable size)
2920  *                   Nothing (variable size)
2921  *                   More Streams and metadata resources (variable size)
2922  *                   Lookup table (variable size)
2923  *                   XML data (variable size)
2924  *                   Integrity table (optional) (variable size)
2925  *
2926  * This method allows an image to be appended to a large WIM very quickly, and
2927  * is is crash-safe except in the case of write re-ordering, but the
2928  * disadvantage is that a small hole is left in the WIM where the old lookup
2929  * table, xml data, and integrity table were.  (These usually only take up a
2930  * small amount of space compared to the streams, however.)
2931  */
2932 static int
2933 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2934                       unsigned num_threads,
2935                       wimlib_progress_func_t progress_func)
2936 {
2937         int ret;
2938         struct list_head stream_list;
2939         off_t old_wim_end;
2940         u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2941         struct wim_header hdr_save;
2942
2943         DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2944
2945         /* Set default integrity flag.  */
2946         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2947                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2948                 if (wim_has_integrity_table(wim))
2949                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2950
2951         /* Set additional flags for overwrite.  */
2952         write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2953                        WIMLIB_WRITE_FLAG_STREAMS_OK;
2954
2955         /* Make sure that the integrity table (if present) is after the XML
2956          * data, and that there are no stream resources, metadata resources, or
2957          * lookup tables after the XML data.  Otherwise, these data would be
2958          * overwritten. */
2959         old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2960         old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2961         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2962                                wim->hdr.lookup_table_reshdr.size_in_wim;
2963         if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2964             wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2965                 WARNING("Didn't expect the integrity table to be before the XML data");
2966                 return WIMLIB_ERR_RESOURCE_ORDER;
2967         }
2968
2969         if (old_lookup_table_end > old_xml_begin) {
2970                 WARNING("Didn't expect the lookup table to be after the XML data");
2971                 return WIMLIB_ERR_RESOURCE_ORDER;
2972         }
2973
2974         /* Set @old_wim_end, which indicates the point beyond which we don't
2975          * allow any file and metadata resources to appear without returning
2976          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2977          * overwrite these resources). */
2978         if (!wim->deletion_occurred && !any_images_modified(wim)) {
2979                 /* If no images have been modified and no images have been
2980                  * deleted, a new lookup table does not need to be written.  We
2981                  * shall write the new XML data and optional integrity table
2982                  * immediately after the lookup table.  Note that this may
2983                  * overwrite an existing integrity table. */
2984                 DEBUG("Skipping writing lookup table "
2985                       "(no images modified or deleted)");
2986                 old_wim_end = old_lookup_table_end;
2987                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2988                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2989         } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2990                 /* Old WIM has an integrity table; begin writing new streams
2991                  * after it. */
2992                 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2993                               wim->hdr.integrity_table_reshdr.size_in_wim;
2994         } else {
2995                 /* No existing integrity table; begin writing new streams after
2996                  * the old XML data. */
2997                 old_wim_end = old_xml_end;
2998         }
2999
3000         ret = check_resource_offsets(wim, old_wim_end);
3001         if (ret)
3002                 return ret;
3003
3004         ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
3005                                   &stream_list);
3006         if (ret)
3007                 return ret;
3008
3009         ret = open_wim_writable(wim, wim->filename, O_RDWR);
3010         if (ret)
3011                 return ret;
3012
3013         ret = lock_wim(wim, wim->out_fd.fd);
3014         if (ret)
3015                 goto out_close_wim;
3016
3017         /* Save original header so it can be restored in case of error  */
3018         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3019
3020         /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3021         wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3022         ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3023         if (ret) {
3024                 ERROR_WITH_ERRNO("Error updating WIM header flags");
3025                 goto out_restore_memory_hdr;
3026         }
3027
3028         if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3029                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3030                 ret = WIMLIB_ERR_WRITE;
3031                 goto out_restore_physical_hdr;
3032         }
3033
3034         ret = write_stream_list(&stream_list,
3035                                 wim->lookup_table,
3036                                 &wim->out_fd,
3037                                 wim->compression_type,
3038                                 wim->chunk_size,
3039                                 &wim->lzx_context,
3040                                 write_flags,
3041                                 num_threads,
3042                                 progress_func);
3043         if (ret)
3044                 goto out_truncate;
3045
3046         ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3047                                            write_flags, progress_func);
3048         if (ret)
3049                 goto out_truncate;
3050
3051         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3052         ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3053                            progress_func, NULL);
3054         if (ret)
3055                 goto out_truncate;
3056
3057         goto out_unlock_wim;
3058
3059 out_truncate:
3060         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3061                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3062                         wim->filename, old_wim_end);
3063                 /* Return value of ftruncate() is ignored because this is
3064                  * already an error path.  */
3065                 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3066         }
3067 out_restore_physical_hdr:
3068         (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3069 out_restore_memory_hdr:
3070         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3071 out_close_wim:
3072         (void)close_wim_writable(wim, write_flags);
3073 out_unlock_wim:
3074         wim->wim_locked = 0;
3075         return ret;
3076 }
3077
3078 static int
3079 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3080                           unsigned num_threads,
3081                           wimlib_progress_func_t progress_func)
3082 {
3083         size_t wim_name_len;
3084         int ret;
3085
3086         DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3087
3088         /* Write the WIM to a temporary file in the same directory as the
3089          * original WIM. */
3090         wim_name_len = tstrlen(wim->filename);
3091         tchar tmpfile[wim_name_len + 10];
3092         tmemcpy(tmpfile, wim->filename, wim_name_len);
3093         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3094         tmpfile[wim_name_len + 9] = T('\0');
3095
3096         ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3097                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3098                            num_threads, progress_func);
3099         if (ret) {
3100                 tunlink(tmpfile);
3101                 return ret;
3102         }
3103
3104         close_wim(wim);
3105
3106         /* Rename the new WIM file to the original WIM file.  Note: on Windows
3107          * this actually calls win32_rename_replacement(), not _wrename(), so
3108          * that removing the existing destination file can be handled.  */
3109         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3110         ret = trename(tmpfile, wim->filename);
3111         if (ret) {
3112                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3113                                  tmpfile, wim->filename);
3114         #ifdef __WIN32__
3115                 if (ret < 0)
3116         #endif
3117                 {
3118                         tunlink(tmpfile);
3119                 }
3120                 return WIMLIB_ERR_RENAME;
3121         }
3122
3123         if (progress_func) {
3124                 union wimlib_progress_info progress;
3125                 progress.rename.from = tmpfile;
3126                 progress.rename.to = wim->filename;
3127                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3128         }
3129         return 0;
3130 }
3131
3132 /* API function documented in wimlib.h  */
3133 WIMLIBAPI int
3134 wimlib_overwrite(WIMStruct *wim, int write_flags,
3135                  unsigned num_threads,
3136                  wimlib_progress_func_t progress_func)
3137 {
3138         int ret;
3139         u32 orig_hdr_flags;
3140
3141         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3142
3143         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3144                 return WIMLIB_ERR_INVALID_PARAM;
3145
3146         if (!wim->filename)
3147                 return WIMLIB_ERR_NO_FILENAME;
3148
3149         orig_hdr_flags = wim->hdr.flags;
3150         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3151                 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3152         ret = can_modify_wim(wim);
3153         wim->hdr.flags = orig_hdr_flags;
3154         if (ret)
3155                 return ret;
3156
3157         if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3158             && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3159                                 WIMLIB_WRITE_FLAG_PIPABLE))
3160             && !(wim_is_pipable(wim))
3161             && wim->compression_type == wim->out_compression_type
3162             && wim->chunk_size == wim->out_chunk_size)
3163         {
3164                 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3165                                             progress_func);
3166                 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3167                         return ret;
3168                 WARNING("Falling back to re-building entire WIM");
3169         }
3170         return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,
3171                                          progress_func);
3172 }