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