Add helper functions for passing paths to progress callbacks
[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, 2014, 2015 Eric Biggers
10  *
11  * This file is free software; you can redistribute it and/or modify it under
12  * the terms of the GNU Lesser General Public License as published by the Free
13  * Software Foundation; either version 3 of the License, or (at your option) any
14  * later version.
15  *
16  * This file is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this file; if not, see http://www.gnu.org/licenses/.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
31  * overwrite the LIST_HEAD macro. */
32 #  include <sys/file.h>
33 #endif
34
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <stdlib.h>
38 #include <unistd.h>
39
40 #include "wimlib/alloca.h"
41 #include "wimlib/assert.h"
42 #include "wimlib/blob_table.h"
43 #include "wimlib/chunk_compressor.h"
44 #include "wimlib/endianness.h"
45 #include "wimlib/error.h"
46 #include "wimlib/file_io.h"
47 #include "wimlib/header.h"
48 #include "wimlib/inode.h"
49 #include "wimlib/integrity.h"
50 #include "wimlib/metadata.h"
51 #include "wimlib/paths.h"
52 #include "wimlib/progress.h"
53 #include "wimlib/resource.h"
54 #include "wimlib/solid.h"
55 #include "wimlib/win32.h" /* win32_rename_replacement() */
56 #include "wimlib/write.h"
57 #include "wimlib/xml.h"
58
59
60 /* wimlib internal flags used when writing resources.  */
61 #define WRITE_RESOURCE_FLAG_RECOMPRESS          0x00000001
62 #define WRITE_RESOURCE_FLAG_PIPABLE             0x00000002
63 #define WRITE_RESOURCE_FLAG_SOLID               0x00000004
64 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
65 #define WRITE_RESOURCE_FLAG_SOLID_SORT          0x00000010
66
67 static int
68 write_flags_to_resource_flags(int write_flags)
69 {
70         int write_resource_flags = 0;
71
72         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
73                 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
74
75         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
76                 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
77
78         if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
79                 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
80
81         if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
82                 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
83
84         if ((write_flags & (WIMLIB_WRITE_FLAG_SOLID |
85                             WIMLIB_WRITE_FLAG_NO_SOLID_SORT)) ==
86             WIMLIB_WRITE_FLAG_SOLID)
87                 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID_SORT;
88
89         return write_resource_flags;
90 }
91
92 struct filter_context {
93         int write_flags;
94         WIMStruct *wim;
95 };
96
97 /*
98  * Determine whether the specified blob should be filtered out from the write.
99  *
100  * Return values:
101  *
102  *  < 0 : The blob should be hard-filtered; that is, not included in the output
103  *        WIM file at all.
104  *    0 : The blob should not be filtered out.
105  *  > 0 : The blob should be soft-filtered; that is, it already exists in the
106  *        WIM file and may not need to be written again.
107  */
108 static int
109 blob_filtered(const struct blob_descriptor *blob,
110               const struct filter_context *ctx)
111 {
112         int write_flags;
113         WIMStruct *wim;
114
115         if (ctx == NULL)
116                 return 0;
117
118         write_flags = ctx->write_flags;
119         wim = ctx->wim;
120
121         if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
122             blob->blob_location == BLOB_IN_WIM &&
123             blob->rdesc->wim == wim)
124                 return 1;
125
126         if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
127             blob->blob_location == BLOB_IN_WIM &&
128             blob->rdesc->wim != wim)
129                 return -1;
130
131         return 0;
132 }
133
134 static bool
135 blob_hard_filtered(const struct blob_descriptor *blob,
136                    struct filter_context *ctx)
137 {
138         return blob_filtered(blob, ctx) < 0;
139 }
140
141 static inline int
142 may_soft_filter_blobs(const struct filter_context *ctx)
143 {
144         if (ctx == NULL)
145                 return 0;
146         return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
147 }
148
149 static inline int
150 may_hard_filter_blobs(const struct filter_context *ctx)
151 {
152         if (ctx == NULL)
153                 return 0;
154         return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
155 }
156
157 static inline int
158 may_filter_blobs(const struct filter_context *ctx)
159 {
160         return (may_soft_filter_blobs(ctx) || may_hard_filter_blobs(ctx));
161 }
162
163 /* Return true if the specified resource is compressed and the compressed data
164  * can be reused with the specified output parameters.  */
165 static bool
166 can_raw_copy(const struct blob_descriptor *blob,
167              int write_resource_flags, int out_ctype, u32 out_chunk_size)
168 {
169         const struct wim_resource_descriptor *rdesc;
170
171         if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
172                 return false;
173
174         if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
175                 return false;
176
177         if (blob->blob_location != BLOB_IN_WIM)
178                 return false;
179
180         rdesc = blob->rdesc;
181
182         if (rdesc->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
183                 return false;
184
185         if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
186                 /* Normal compressed resource: Must use same compression type
187                  * and chunk size.  */
188                 return (rdesc->compression_type == out_ctype &&
189                         rdesc->chunk_size == out_chunk_size);
190         }
191
192         if ((rdesc->flags & WIM_RESHDR_FLAG_SOLID) &&
193             (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
194         {
195                 /* Solid resource: Such resources may contain multiple blobs,
196                  * and in general only a subset of them need to be written.  As
197                  * a heuristic, re-use the raw data if more than two-thirds the
198                  * uncompressed size is being written.  */
199
200                 /* Note: solid resources contain a header that specifies the
201                  * compression type and chunk size; therefore we don't need to
202                  * check if they are compatible with @out_ctype and
203                  * @out_chunk_size.  */
204
205                 struct blob_descriptor *res_blob;
206                 u64 write_size = 0;
207
208                 list_for_each_entry(res_blob, &rdesc->blob_list, rdesc_node)
209                         if (res_blob->will_be_in_output_wim)
210                                 write_size += res_blob->size;
211
212                 return (write_size > rdesc->uncompressed_size * 2 / 3);
213         }
214
215         return false;
216 }
217
218 static u32
219 reshdr_flags_for_blob(const struct blob_descriptor *blob)
220 {
221         u32 reshdr_flags = 0;
222         if (blob->is_metadata)
223                 reshdr_flags |= WIM_RESHDR_FLAG_METADATA;
224         return reshdr_flags;
225 }
226
227 static void
228 blob_set_out_reshdr_for_reuse(struct blob_descriptor *blob)
229 {
230         const struct wim_resource_descriptor *rdesc;
231
232         wimlib_assert(blob->blob_location == BLOB_IN_WIM);
233         rdesc = blob->rdesc;
234
235         if (rdesc->flags & WIM_RESHDR_FLAG_SOLID) {
236                 blob->out_reshdr.offset_in_wim = blob->offset_in_res;
237                 blob->out_reshdr.uncompressed_size = 0;
238                 blob->out_reshdr.size_in_wim = blob->size;
239
240                 blob->out_res_offset_in_wim = rdesc->offset_in_wim;
241                 blob->out_res_size_in_wim = rdesc->size_in_wim;
242                 blob->out_res_uncompressed_size = rdesc->uncompressed_size;
243         } else {
244                 blob->out_reshdr.offset_in_wim = rdesc->offset_in_wim;
245                 blob->out_reshdr.uncompressed_size = rdesc->uncompressed_size;
246                 blob->out_reshdr.size_in_wim = rdesc->size_in_wim;
247         }
248         blob->out_reshdr.flags = rdesc->flags;
249 }
250
251
252 /* Write the header for a blob in a pipable WIM.  */
253 static int
254 write_pwm_blob_header(const struct blob_descriptor *blob,
255                       struct filedes *out_fd, bool compressed)
256 {
257         struct pwm_blob_hdr blob_hdr;
258         u32 reshdr_flags;
259         int ret;
260
261         wimlib_assert(!blob->unhashed);
262
263         blob_hdr.magic = cpu_to_le64(PWM_BLOB_MAGIC);
264         blob_hdr.uncompressed_size = cpu_to_le64(blob->size);
265         copy_hash(blob_hdr.hash, blob->hash);
266         reshdr_flags = reshdr_flags_for_blob(blob);
267         if (compressed)
268                 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
269         blob_hdr.flags = cpu_to_le32(reshdr_flags);
270         ret = full_write(out_fd, &blob_hdr, sizeof(blob_hdr));
271         if (ret)
272                 ERROR_WITH_ERRNO("Write error");
273         return ret;
274 }
275
276 struct write_blobs_progress_data {
277         wimlib_progress_func_t progfunc;
278         void *progctx;
279         union wimlib_progress_info progress;
280         u64 next_progress;
281 };
282
283 static int
284 do_write_blobs_progress(struct write_blobs_progress_data *progress_data,
285                         u64 complete_size, u32 complete_count, bool discarded)
286 {
287         union wimlib_progress_info *progress = &progress_data->progress;
288         int ret;
289
290         if (discarded) {
291                 progress->write_streams.total_bytes -= complete_size;
292                 progress->write_streams.total_streams -= complete_count;
293                 if (progress_data->next_progress != ~(u64)0 &&
294                     progress_data->next_progress > progress->write_streams.total_bytes)
295                 {
296                         progress_data->next_progress = progress->write_streams.total_bytes;
297                 }
298         } else {
299                 progress->write_streams.completed_bytes += complete_size;
300                 progress->write_streams.completed_streams += complete_count;
301         }
302
303         if (progress->write_streams.completed_bytes >= progress_data->next_progress) {
304
305                 ret = call_progress(progress_data->progfunc,
306                                     WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
307                                     progress,
308                                     progress_data->progctx);
309                 if (ret)
310                         return ret;
311
312                 set_next_progress(progress->write_streams.completed_bytes,
313                                   progress->write_streams.total_bytes,
314                                   &progress_data->next_progress);
315         }
316         return 0;
317 }
318
319 struct write_blobs_ctx {
320         /* File descriptor to which the blobs are being written.  */
321         struct filedes *out_fd;
322
323         /* Blob table for the WIMStruct on whose behalf the blobs are being
324          * written.  */
325         struct blob_table *blob_table;
326
327         /* Compression format to use.  */
328         int out_ctype;
329
330         /* Maximum uncompressed chunk size in compressed resources to use.  */
331         u32 out_chunk_size;
332
333         /* Flags that affect how the blobs will be written.  */
334         int write_resource_flags;
335
336         /* Data used for issuing WRITE_STREAMS progress.  */
337         struct write_blobs_progress_data progress_data;
338
339         struct filter_context *filter_ctx;
340
341         /* Upper bound on the total number of bytes that need to be compressed.
342          * */
343         u64 num_bytes_to_compress;
344
345         /* Pointer to the chunk_compressor implementation being used for
346          * compressing chunks of data, or NULL if chunks are being written
347          * uncompressed.  */
348         struct chunk_compressor *compressor;
349
350         /* A buffer of size @out_chunk_size that has been loaned out from the
351          * chunk compressor and is currently being filled with the uncompressed
352          * data of the next chunk.  */
353         u8 *cur_chunk_buf;
354
355         /* Number of bytes in @cur_chunk_buf that are currently filled.  */
356         size_t cur_chunk_buf_filled;
357
358         /* List of blobs that currently have chunks being compressed.  */
359         struct list_head blobs_being_compressed;
360
361         /* List of blobs in the solid resource.  Blobs are moved here after
362          * @blobs_being_compressed only when writing a solid resource.  */
363         struct list_head blobs_in_solid_resource;
364
365         /* Current uncompressed offset in the blob being read.  */
366         u64 cur_read_blob_offset;
367
368         /* Uncompressed size of the blob currently being read.  */
369         u64 cur_read_blob_size;
370
371         /* Current uncompressed offset in the blob being written.  */
372         u64 cur_write_blob_offset;
373
374         /* Uncompressed size of resource currently being written.  */
375         u64 cur_write_res_size;
376
377         /* Array that is filled in with compressed chunk sizes as a resource is
378          * being written.  */
379         u64 *chunk_csizes;
380
381         /* Index of next entry in @chunk_csizes to fill in.  */
382         size_t chunk_index;
383
384         /* Number of entries in @chunk_csizes currently allocated.  */
385         size_t num_alloc_chunks;
386
387         /* Offset in the output file of the start of the chunks of the resource
388          * currently being written.  */
389         u64 chunks_start_offset;
390 };
391
392 /* Reserve space for the chunk table and prepare to accumulate the chunk table
393  * in memory.  */
394 static int
395 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
396 {
397         u64 expected_num_chunks;
398         u64 expected_num_chunk_entries;
399         size_t reserve_size;
400         int ret;
401
402         /* Calculate the number of chunks and chunk entries that should be
403          * needed for the resource.  These normally will be the final values,
404          * but in SOLID mode some of the blobs we're planning to write into the
405          * resource may be duplicates, and therefore discarded, potentially
406          * decreasing the number of chunk entries needed.  */
407         expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
408         expected_num_chunk_entries = expected_num_chunks;
409         if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
410                 expected_num_chunk_entries--;
411
412         /* Make sure the chunk_csizes array is long enough to store the
413          * compressed size of each chunk.  */
414         if (expected_num_chunks > ctx->num_alloc_chunks) {
415                 u64 new_length = expected_num_chunks + 50;
416
417                 if ((size_t)new_length != new_length) {
418                         ERROR("Resource size too large (%"PRIu64" bytes!",
419                               res_expected_size);
420                         return WIMLIB_ERR_NOMEM;
421                 }
422
423                 FREE(ctx->chunk_csizes);
424                 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
425                 if (ctx->chunk_csizes == NULL) {
426                         ctx->num_alloc_chunks = 0;
427                         return WIMLIB_ERR_NOMEM;
428                 }
429                 ctx->num_alloc_chunks = new_length;
430         }
431
432         ctx->chunk_index = 0;
433
434         if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
435                 /* Reserve space for the chunk table in the output file.  In the
436                  * case of solid resources this reserves the upper bound for the
437                  * needed space, not necessarily the exact space which will
438                  * prove to be needed.  At this point, we just use @chunk_csizes
439                  * for a buffer of 0's because the actual compressed chunk sizes
440                  * are unknown.  */
441                 reserve_size = expected_num_chunk_entries *
442                                get_chunk_entry_size(res_expected_size,
443                                                     0 != (ctx->write_resource_flags &
444                                                           WRITE_RESOURCE_FLAG_SOLID));
445                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
446                         reserve_size += sizeof(struct alt_chunk_table_header_disk);
447                 memset(ctx->chunk_csizes, 0, reserve_size);
448                 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
449                 if (ret)
450                         return ret;
451         }
452         return 0;
453 }
454
455 static int
456 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
457 {
458         int ret;
459
460         wimlib_assert(res_expected_size != 0);
461
462         if (ctx->compressor != NULL) {
463                 ret = begin_chunk_table(ctx, res_expected_size);
464                 if (ret)
465                         return ret;
466         }
467
468         /* Output file descriptor is now positioned at the offset at which to
469          * write the first chunk of the resource.  */
470         ctx->chunks_start_offset = ctx->out_fd->offset;
471         ctx->cur_write_blob_offset = 0;
472         ctx->cur_write_res_size = res_expected_size;
473         return 0;
474 }
475
476 static int
477 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
478                 u64 *res_start_offset_ret, u64 *res_store_size_ret)
479 {
480         size_t actual_num_chunks;
481         size_t actual_num_chunk_entries;
482         size_t chunk_entry_size;
483         int ret;
484
485         actual_num_chunks = ctx->chunk_index;
486         actual_num_chunk_entries = actual_num_chunks;
487         if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
488                 actual_num_chunk_entries--;
489
490         chunk_entry_size = get_chunk_entry_size(res_actual_size,
491                                                 0 != (ctx->write_resource_flags &
492                                                       WRITE_RESOURCE_FLAG_SOLID));
493
494         typedef le64 _may_alias_attribute aliased_le64_t;
495         typedef le32 _may_alias_attribute aliased_le32_t;
496
497         if (chunk_entry_size == 4) {
498                 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
499
500                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
501                         for (size_t i = 0; i < actual_num_chunk_entries; i++)
502                                 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
503                 } else {
504                         u32 offset = ctx->chunk_csizes[0];
505                         for (size_t i = 0; i < actual_num_chunk_entries; i++) {
506                                 u32 next_size = ctx->chunk_csizes[i + 1];
507                                 entries[i] = cpu_to_le32(offset);
508                                 offset += next_size;
509                         }
510                 }
511         } else {
512                 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
513
514                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
515                         for (size_t i = 0; i < actual_num_chunk_entries; i++)
516                                 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
517                 } else {
518                         u64 offset = ctx->chunk_csizes[0];
519                         for (size_t i = 0; i < actual_num_chunk_entries; i++) {
520                                 u64 next_size = ctx->chunk_csizes[i + 1];
521                                 entries[i] = cpu_to_le64(offset);
522                                 offset += next_size;
523                         }
524                 }
525         }
526
527         size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
528         u64 res_start_offset;
529         u64 res_end_offset;
530
531         if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
532                 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
533                 if (ret)
534                         goto write_error;
535                 res_end_offset = ctx->out_fd->offset;
536                 res_start_offset = ctx->chunks_start_offset;
537         } else {
538                 res_end_offset = ctx->out_fd->offset;
539
540                 u64 chunk_table_offset;
541
542                 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
543
544                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
545                         struct alt_chunk_table_header_disk hdr;
546
547                         hdr.res_usize = cpu_to_le64(res_actual_size);
548                         hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
549                         hdr.compression_format = cpu_to_le32(ctx->out_ctype);
550
551                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
552                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
553                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
554
555                         ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
556                                           chunk_table_offset - sizeof(hdr));
557                         if (ret)
558                                 goto write_error;
559                         res_start_offset = chunk_table_offset - sizeof(hdr);
560                 } else {
561                         res_start_offset = chunk_table_offset;
562                 }
563
564                 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
565                                   chunk_table_size, chunk_table_offset);
566                 if (ret)
567                         goto write_error;
568         }
569
570         *res_start_offset_ret = res_start_offset;
571         *res_store_size_ret = res_end_offset - res_start_offset;
572
573         return 0;
574
575 write_error:
576         ERROR_WITH_ERRNO("Write error");
577         return ret;
578 }
579
580 /* Finish writing a WIM resource by writing or updating the chunk table (if not
581  * writing the data uncompressed) and loading its metadata into @out_reshdr.  */
582 static int
583 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
584 {
585         int ret;
586         u64 res_size_in_wim;
587         u64 res_uncompressed_size;
588         u64 res_offset_in_wim;
589
590         wimlib_assert(ctx->cur_write_blob_offset == ctx->cur_write_res_size ||
591                       (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
592         res_uncompressed_size = ctx->cur_write_res_size;
593
594         if (ctx->compressor) {
595                 ret = end_chunk_table(ctx, res_uncompressed_size,
596                                       &res_offset_in_wim, &res_size_in_wim);
597                 if (ret)
598                         return ret;
599         } else {
600                 res_offset_in_wim = ctx->chunks_start_offset;
601                 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
602         }
603         out_reshdr->uncompressed_size = res_uncompressed_size;
604         out_reshdr->size_in_wim = res_size_in_wim;
605         out_reshdr->offset_in_wim = res_offset_in_wim;
606         return 0;
607 }
608
609 /* Call when no more data from the file at @path is needed.  */
610 static int
611 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
612 {
613         union wimlib_progress_info info;
614
615         info.done_with_file.path_to_file = path;
616
617         return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
618                              &info, progctx);
619 }
620
621 static int
622 do_done_with_blob(struct blob_descriptor *blob,
623                   wimlib_progress_func_t progfunc, void *progctx)
624 {
625         int ret;
626         struct wim_inode *inode;
627         tchar *cookie1;
628         tchar *cookie2;
629
630         if (!blob->may_send_done_with_file)
631                 return 0;
632
633         inode = blob->file_inode;
634
635         wimlib_assert(inode != NULL);
636         wimlib_assert(inode->i_num_remaining_streams > 0);
637         if (--inode->i_num_remaining_streams > 0)
638                 return 0;
639
640         cookie1 = progress_get_streamless_path(blob->file_on_disk);
641         cookie2 = progress_get_win32_path(blob->file_on_disk);
642
643         ret = done_with_file(blob->file_on_disk, progfunc, progctx);
644
645         progress_put_win32_path(cookie2);
646         progress_put_streamless_path(cookie1);
647
648         return ret;
649 }
650
651 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode.  */
652 static inline int
653 done_with_blob(struct blob_descriptor *blob, struct write_blobs_ctx *ctx)
654 {
655         if (likely(!(ctx->write_resource_flags &
656                      WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
657                 return 0;
658         return do_done_with_blob(blob, ctx->progress_data.progfunc,
659                                  ctx->progress_data.progctx);
660 }
661
662 /* Begin processing a blob for writing.  */
663 static int
664 write_blob_begin_read(struct blob_descriptor *blob, void *_ctx)
665 {
666         struct write_blobs_ctx *ctx = _ctx;
667         int ret;
668
669         wimlib_assert(blob->size > 0);
670
671         ctx->cur_read_blob_offset = 0;
672         ctx->cur_read_blob_size = blob->size;
673
674         /* As an optimization, we allow some blobs to be "unhashed", meaning
675          * their SHA-1 message digests are unknown.  This is the case with blobs
676          * that are added by scanning a directory tree with wimlib_add_image(),
677          * for example.  Since WIM uses single-instance blobs, we don't know
678          * whether such each such blob really need to written until it is
679          * actually checksummed, unless it has a unique size.  In such cases we
680          * read and checksum the blob in this function, thereby advancing ahead
681          * of read_blob_list(), which will still provide the data again to
682          * write_blob_process_chunk().  This is okay because an unhashed blob
683          * cannot be in a WIM resource, which might be costly to decompress.  */
684         if (ctx->blob_table != NULL && blob->unhashed && !blob->unique_size) {
685
686                 struct blob_descriptor *new_blob;
687
688                 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
689                 if (ret)
690                         return ret;
691                 if (new_blob != blob) {
692                         /* Duplicate blob detected.  */
693
694                         if (new_blob->will_be_in_output_wim ||
695                             blob_filtered(new_blob, ctx->filter_ctx))
696                         {
697                                 /* The duplicate blob is already being included
698                                  * in the output WIM, or it would be filtered
699                                  * out if it had been.  Skip writing this blob
700                                  * (and reading it again) entirely, passing its
701                                  * output reference count to the duplicate blob
702                                  * in the former case.  */
703                                 ret = do_write_blobs_progress(&ctx->progress_data,
704                                                               blob->size, 1, true);
705                                 list_del(&blob->write_blobs_list);
706                                 list_del(&blob->blob_table_list);
707                                 if (new_blob->will_be_in_output_wim)
708                                         new_blob->out_refcnt += blob->out_refcnt;
709                                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
710                                         ctx->cur_write_res_size -= blob->size;
711                                 if (!ret)
712                                         ret = done_with_blob(blob, ctx);
713                                 free_blob_descriptor(blob);
714                                 if (ret)
715                                         return ret;
716                                 return BEGIN_BLOB_STATUS_SKIP_BLOB;
717                         } else {
718                                 /* The duplicate blob can validly be written,
719                                  * but was not marked as such.  Discard the
720                                  * current blob descriptor and use the
721                                  * duplicate, but actually freeing the current
722                                  * blob descriptor must wait until
723                                  * read_blob_list() has finished reading its
724                                  * data.  */
725                                 list_replace(&blob->write_blobs_list,
726                                              &new_blob->write_blobs_list);
727                                 list_replace(&blob->blob_table_list,
728                                              &new_blob->blob_table_list);
729                                 blob->will_be_in_output_wim = 0;
730                                 new_blob->out_refcnt = blob->out_refcnt;
731                                 new_blob->will_be_in_output_wim = 1;
732                                 new_blob->may_send_done_with_file = 0;
733                                 blob = new_blob;
734                         }
735                 }
736         }
737         list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
738         return 0;
739 }
740
741 /* Rewrite a blob that was just written compressed (as a non-solid WIM resource)
742  * as uncompressed instead.  */
743 static int
744 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
745 {
746         int ret;
747         u64 begin_offset = blob->out_reshdr.offset_in_wim;
748         u64 end_offset = out_fd->offset;
749
750         if (filedes_seek(out_fd, begin_offset) == -1)
751                 return 0;
752
753         ret = extract_blob_to_fd(blob, out_fd);
754         if (ret) {
755                 /* Error reading the uncompressed data.  */
756                 if (out_fd->offset == begin_offset &&
757                     filedes_seek(out_fd, end_offset) != -1)
758                 {
759                         /* Nothing was actually written yet, and we successfully
760                          * seeked to the end of the compressed resource, so
761                          * don't issue a hard error; just keep the compressed
762                          * resource instead.  */
763                         WARNING("Recovered compressed resource of "
764                                 "size %"PRIu64", continuing on.", blob->size);
765                         return 0;
766                 }
767                 return ret;
768         }
769
770         wimlib_assert(out_fd->offset - begin_offset == blob->size);
771
772         if (out_fd->offset < end_offset &&
773             0 != ftruncate(out_fd->fd, out_fd->offset))
774         {
775                 ERROR_WITH_ERRNO("Can't truncate output file to "
776                                  "offset %"PRIu64, out_fd->offset);
777                 return WIMLIB_ERR_WRITE;
778         }
779
780         blob->out_reshdr.size_in_wim = blob->size;
781         blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
782                                     WIM_RESHDR_FLAG_SOLID);
783         return 0;
784 }
785
786 /* Returns true if the specified blob, which was written as a non-solid
787  * resource, should be truncated from the WIM file and re-written uncompressed.
788  * blob->out_reshdr must be filled in from the initial write of the blob.  */
789 static bool
790 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
791                                  const struct blob_descriptor *blob)
792 {
793         /* If the compressed data is smaller than the uncompressed data, prefer
794          * the compressed data.  */
795         if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
796                 return false;
797
798         /* If we're not actually writing compressed data, then there's no need
799          * for re-writing.  */
800         if (!ctx->compressor)
801                 return false;
802
803         /* If writing a pipable WIM, everything we write to the output is final
804          * (it might actually be a pipe!).  */
805         if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
806                 return false;
807
808         /* If the blob that would need to be re-read is located in a solid
809          * resource in another WIM file, then re-reading it would be costly.  So
810          * don't do it.
811          *
812          * Exception: if the compressed size happens to be *exactly* the same as
813          * the uncompressed size, then the blob *must* be written uncompressed
814          * in order to remain compatible with the Windows Overlay Filesystem
815          * Filter Driver (WOF).
816          *
817          * TODO: we are currently assuming that the optimization for
818          * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
819          * this case from being triggered too often.  To fully prevent excessive
820          * decompressions in degenerate cases, we really should obtain the
821          * uncompressed data by decompressing the compressed data we wrote to
822          * the output file.
823          */
824         if (blob->blob_location == BLOB_IN_WIM &&
825             blob->size != blob->rdesc->uncompressed_size &&
826             blob->size != blob->out_reshdr.size_in_wim)
827                 return false;
828
829         return true;
830 }
831
832 static int
833 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
834                                 struct blob_descriptor *blob)
835 {
836         if (!should_rewrite_blob_uncompressed(ctx, blob))
837                 return 0;
838
839         /* Regular (non-solid) WIM resources with exactly one chunk and
840          * compressed size equal to uncompressed size are exactly the same as
841          * the corresponding compressed data --- since there must be 0 entries
842          * in the chunk table and the only chunk must be stored uncompressed.
843          * In this case, there's no need to rewrite anything.  */
844         if (ctx->chunk_index == 1 &&
845             blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
846         {
847                 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
848                 return 0;
849         }
850
851         return write_blob_uncompressed(blob, ctx->out_fd);
852 }
853
854 /* Write the next chunk of (typically compressed) data to the output WIM,
855  * handling the writing of the chunk table.  */
856 static int
857 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
858             size_t csize, size_t usize)
859 {
860         int ret;
861         struct blob_descriptor *blob;
862         u32 completed_blob_count;
863         u32 completed_size;
864
865         blob = list_entry(ctx->blobs_being_compressed.next,
866                           struct blob_descriptor, write_blobs_list);
867
868         if (ctx->cur_write_blob_offset == 0 &&
869             !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
870         {
871                 /* Starting to write a new blob in non-solid mode.  */
872
873                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
874                         ret = write_pwm_blob_header(blob, ctx->out_fd,
875                                                     ctx->compressor != NULL);
876                         if (ret)
877                                 return ret;
878                 }
879
880                 ret = begin_write_resource(ctx, blob->size);
881                 if (ret)
882                         return ret;
883         }
884
885         if (ctx->compressor != NULL) {
886                 /* Record the compresed chunk size.  */
887                 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
888                 ctx->chunk_csizes[ctx->chunk_index++] = csize;
889
890                /* If writing a pipable WIM, before the chunk data write a chunk
891                 * header that provides the compressed chunk size.  */
892                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
893                         struct pwm_chunk_hdr chunk_hdr = {
894                                 .compressed_size = cpu_to_le32(csize),
895                         };
896                         ret = full_write(ctx->out_fd, &chunk_hdr,
897                                          sizeof(chunk_hdr));
898                         if (ret)
899                                 goto write_error;
900                 }
901         }
902
903         /* Write the chunk data.  */
904         ret = full_write(ctx->out_fd, cchunk, csize);
905         if (ret)
906                 goto write_error;
907
908         ctx->cur_write_blob_offset += usize;
909
910         completed_size = usize;
911         completed_blob_count = 0;
912         if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
913                 /* Wrote chunk in solid mode.  It may have finished multiple
914                  * blobs.  */
915                 struct blob_descriptor *next_blob;
916
917                 while (blob && ctx->cur_write_blob_offset >= blob->size) {
918
919                         ctx->cur_write_blob_offset -= blob->size;
920
921                         if (ctx->cur_write_blob_offset)
922                                 next_blob = list_entry(blob->write_blobs_list.next,
923                                                       struct blob_descriptor,
924                                                       write_blobs_list);
925                         else
926                                 next_blob = NULL;
927
928                         ret = done_with_blob(blob, ctx);
929                         if (ret)
930                                 return ret;
931                         list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
932                         completed_blob_count++;
933
934                         blob = next_blob;
935                 }
936         } else {
937                 /* Wrote chunk in non-solid mode.  It may have finished a
938                  * blob.  */
939                 if (ctx->cur_write_blob_offset == blob->size) {
940
941                         wimlib_assert(ctx->cur_write_blob_offset ==
942                                       ctx->cur_write_res_size);
943
944                         ret = end_write_resource(ctx, &blob->out_reshdr);
945                         if (ret)
946                                 return ret;
947
948                         blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
949                         if (ctx->compressor != NULL)
950                                 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
951
952                         ret = maybe_rewrite_blob_uncompressed(ctx, blob);
953                         if (ret)
954                                 return ret;
955
956                         wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
957
958                         ctx->cur_write_blob_offset = 0;
959
960                         ret = done_with_blob(blob, ctx);
961                         if (ret)
962                                 return ret;
963                         list_del(&blob->write_blobs_list);
964                         completed_blob_count++;
965                 }
966         }
967
968         return do_write_blobs_progress(&ctx->progress_data, completed_size,
969                                        completed_blob_count, false);
970
971 write_error:
972         ERROR_WITH_ERRNO("Write error");
973         return ret;
974 }
975
976 static int
977 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
978 {
979         /* While we are unable to get a new chunk buffer due to too many chunks
980          * already outstanding, retrieve and write the next compressed chunk. */
981         while (!(ctx->cur_chunk_buf =
982                  ctx->compressor->get_chunk_buffer(ctx->compressor)))
983         {
984                 const void *cchunk;
985                 u32 csize;
986                 u32 usize;
987                 bool bret;
988                 int ret;
989
990                 bret = ctx->compressor->get_compression_result(ctx->compressor,
991                                                                &cchunk,
992                                                                &csize,
993                                                                &usize);
994                 wimlib_assert(bret);
995
996                 ret = write_chunk(ctx, cchunk, csize, usize);
997                 if (ret)
998                         return ret;
999         }
1000         return 0;
1001 }
1002
1003 /* Process the next chunk of data to be written to a WIM resource.  */
1004 static int
1005 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1006 {
1007         struct write_blobs_ctx *ctx = _ctx;
1008         int ret;
1009         const u8 *chunkptr, *chunkend;
1010
1011         wimlib_assert(size != 0);
1012
1013         if (ctx->compressor == NULL) {
1014                 /* Write chunk uncompressed.  */
1015                  ret = write_chunk(ctx, chunk, size, size);
1016                  if (ret)
1017                          return ret;
1018                  ctx->cur_read_blob_offset += size;
1019                  return 0;
1020         }
1021
1022         /* Submit the chunk for compression, but take into account that the
1023          * @size the chunk was provided in may not correspond to the
1024          * @out_chunk_size being used for compression.  */
1025         chunkptr = chunk;
1026         chunkend = chunkptr + size;
1027         do {
1028                 size_t needed_chunk_size;
1029                 size_t bytes_consumed;
1030
1031                 if (!ctx->cur_chunk_buf) {
1032                         ret = prepare_chunk_buffer(ctx);
1033                         if (ret)
1034                                 return ret;
1035                 }
1036
1037                 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1038                         needed_chunk_size = ctx->out_chunk_size;
1039                 } else {
1040                         needed_chunk_size = min(ctx->out_chunk_size,
1041                                                 ctx->cur_chunk_buf_filled +
1042                                                         (ctx->cur_read_blob_size -
1043                                                          ctx->cur_read_blob_offset));
1044                 }
1045
1046                 bytes_consumed = min(chunkend - chunkptr,
1047                                      needed_chunk_size - ctx->cur_chunk_buf_filled);
1048
1049                 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1050                        chunkptr, bytes_consumed);
1051
1052                 chunkptr += bytes_consumed;
1053                 ctx->cur_read_blob_offset += bytes_consumed;
1054                 ctx->cur_chunk_buf_filled += bytes_consumed;
1055
1056                 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1057                         ctx->compressor->signal_chunk_filled(ctx->compressor,
1058                                                              ctx->cur_chunk_buf_filled);
1059                         ctx->cur_chunk_buf = NULL;
1060                         ctx->cur_chunk_buf_filled = 0;
1061                 }
1062         } while (chunkptr != chunkend);
1063         return 0;
1064 }
1065
1066 /* Finish processing a blob for writing.  It may not have been completely
1067  * written yet, as the chunk_compressor implementation may still have chunks
1068  * buffered or being compressed.  */
1069 static int
1070 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1071 {
1072         struct write_blobs_ctx *ctx = _ctx;
1073
1074         wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
1075
1076         if (!blob->will_be_in_output_wim) {
1077                 /* The blob was a duplicate.  Now that its data has finished
1078                  * being read, it is being discarded in favor of the duplicate
1079                  * entry.  It therefore is no longer needed, and we can fire the
1080                  * DONE_WITH_FILE callback because the file will not be read
1081                  * again.
1082                  *
1083                  * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1084                  * blobs, since it needs to be possible to re-read the file if
1085                  * it does not compress to less than its original size.  */
1086                 if (!status)
1087                         status = done_with_blob(blob, ctx);
1088                 free_blob_descriptor(blob);
1089         } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1090                 /* The blob was not a duplicate and was previously unhashed.
1091                  * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1092                  * read_blob_list(), blob->hash is now computed and valid.  So
1093                  * turn this blob into a "hashed" blob.  */
1094                 list_del(&blob->unhashed_list);
1095                 blob_table_insert(ctx->blob_table, blob);
1096                 blob->unhashed = 0;
1097         }
1098         return status;
1099 }
1100
1101 /* Compute statistics about a list of blobs that will be written.
1102  *
1103  * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1104  * (specified by WIMStruct) are together.  */
1105 static void
1106 compute_blob_list_stats(struct list_head *blob_list,
1107                         struct write_blobs_ctx *ctx)
1108 {
1109         struct blob_descriptor *blob;
1110         u64 total_bytes = 0;
1111         u64 num_blobs = 0;
1112         u64 total_parts = 0;
1113         WIMStruct *prev_wim_part = NULL;
1114
1115         list_for_each_entry(blob, blob_list, write_blobs_list) {
1116                 num_blobs++;
1117                 total_bytes += blob->size;
1118                 if (blob->blob_location == BLOB_IN_WIM) {
1119                         if (prev_wim_part != blob->rdesc->wim) {
1120                                 prev_wim_part = blob->rdesc->wim;
1121                                 total_parts++;
1122                         }
1123                 }
1124         }
1125         ctx->progress_data.progress.write_streams.total_bytes       = total_bytes;
1126         ctx->progress_data.progress.write_streams.total_streams     = num_blobs;
1127         ctx->progress_data.progress.write_streams.completed_bytes   = 0;
1128         ctx->progress_data.progress.write_streams.completed_streams = 0;
1129         ctx->progress_data.progress.write_streams.compression_type  = ctx->out_ctype;
1130         ctx->progress_data.progress.write_streams.total_parts       = total_parts;
1131         ctx->progress_data.progress.write_streams.completed_parts   = 0;
1132         ctx->progress_data.next_progress = 0;
1133 }
1134
1135 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1136  * rather than compressed.  Delete these blobs from @blob_list and move them to
1137  * @raw_copy_blobs.  Return the total uncompressed size of the blobs that need
1138  * to be compressed.  */
1139 static u64
1140 find_raw_copy_blobs(struct list_head *blob_list,
1141                     int write_resource_flags,
1142                     int out_ctype,
1143                     u32 out_chunk_size,
1144                     struct list_head *raw_copy_blobs)
1145 {
1146         struct blob_descriptor *blob, *tmp;
1147         u64 num_bytes_to_compress = 0;
1148
1149         INIT_LIST_HEAD(raw_copy_blobs);
1150
1151         /* Initialize temporary raw_copy_ok flag.  */
1152         list_for_each_entry(blob, blob_list, write_blobs_list)
1153                 if (blob->blob_location == BLOB_IN_WIM)
1154                         blob->rdesc->raw_copy_ok = 0;
1155
1156         list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1157                 if (blob->blob_location == BLOB_IN_WIM &&
1158                     blob->rdesc->raw_copy_ok)
1159                 {
1160                         list_move_tail(&blob->write_blobs_list,
1161                                        raw_copy_blobs);
1162                 } else if (can_raw_copy(blob, write_resource_flags,
1163                                         out_ctype, out_chunk_size))
1164                 {
1165                         blob->rdesc->raw_copy_ok = 1;
1166                         list_move_tail(&blob->write_blobs_list,
1167                                        raw_copy_blobs);
1168                 } else {
1169                         num_bytes_to_compress += blob->size;
1170                 }
1171         }
1172
1173         return num_bytes_to_compress;
1174 }
1175
1176 /* Copy a raw compressed resource located in another WIM file to the WIM file
1177  * being written.  */
1178 static int
1179 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1180                         struct filedes *out_fd)
1181 {
1182         u64 cur_read_offset;
1183         u64 end_read_offset;
1184         u8 buf[BUFFER_SIZE];
1185         size_t bytes_to_read;
1186         int ret;
1187         struct filedes *in_fd;
1188         struct blob_descriptor *blob;
1189         u64 out_offset_in_wim;
1190
1191         /* Copy the raw data.  */
1192         cur_read_offset = in_rdesc->offset_in_wim;
1193         end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1194
1195         out_offset_in_wim = out_fd->offset;
1196
1197         if (in_rdesc->is_pipable) {
1198                 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1199                         return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1200                 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1201                 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1202         }
1203         in_fd = &in_rdesc->wim->in_fd;
1204         wimlib_assert(cur_read_offset != end_read_offset);
1205         do {
1206
1207                 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1208
1209                 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1210                 if (ret)
1211                         return ret;
1212
1213                 ret = full_write(out_fd, buf, bytes_to_read);
1214                 if (ret)
1215                         return ret;
1216
1217                 cur_read_offset += bytes_to_read;
1218
1219         } while (cur_read_offset != end_read_offset);
1220
1221         list_for_each_entry(blob, &in_rdesc->blob_list, rdesc_node) {
1222                 if (blob->will_be_in_output_wim) {
1223                         blob_set_out_reshdr_for_reuse(blob);
1224                         if (in_rdesc->flags & WIM_RESHDR_FLAG_SOLID)
1225                                 blob->out_res_offset_in_wim = out_offset_in_wim;
1226                         else
1227                                 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1228
1229                 }
1230         }
1231         return 0;
1232 }
1233
1234 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1235  * WIM file being written.  */
1236 static int
1237 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1238                          struct filedes *out_fd,
1239                          struct write_blobs_progress_data *progress_data)
1240 {
1241         struct blob_descriptor *blob;
1242         int ret;
1243
1244         list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1245                 blob->rdesc->raw_copy_ok = 1;
1246
1247         list_for_each_entry(blob, raw_copy_blobs, write_blobs_list) {
1248                 if (blob->rdesc->raw_copy_ok) {
1249                         /* Write each solid resource only one time.  */
1250                         ret = write_raw_copy_resource(blob->rdesc, out_fd);
1251                         if (ret)
1252                                 return ret;
1253                         blob->rdesc->raw_copy_ok = 0;
1254                 }
1255                 ret = do_write_blobs_progress(progress_data, blob->size,
1256                                               1, false);
1257                 if (ret)
1258                         return ret;
1259         }
1260         return 0;
1261 }
1262
1263 /* Wait for and write all chunks pending in the compressor.  */
1264 static int
1265 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1266 {
1267         const void *cdata;
1268         u32 csize;
1269         u32 usize;
1270         int ret;
1271
1272         if (ctx->compressor == NULL)
1273                 return 0;
1274
1275         if (ctx->cur_chunk_buf_filled != 0) {
1276                 ctx->compressor->signal_chunk_filled(ctx->compressor,
1277                                                      ctx->cur_chunk_buf_filled);
1278         }
1279
1280         while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1281                                                        &csize, &usize))
1282         {
1283                 ret = write_chunk(ctx, cdata, csize, usize);
1284                 if (ret)
1285                         return ret;
1286         }
1287         return 0;
1288 }
1289
1290 static void
1291 validate_blob_list(struct list_head *blob_list)
1292 {
1293         struct blob_descriptor *blob;
1294
1295         list_for_each_entry(blob, blob_list, write_blobs_list) {
1296                 wimlib_assert(blob->will_be_in_output_wim);
1297                 wimlib_assert(blob->size != 0);
1298         }
1299 }
1300
1301 static inline bool
1302 blob_is_in_file(const struct blob_descriptor *blob)
1303 {
1304         return blob->blob_location == BLOB_IN_FILE_ON_DISK
1305 #ifdef __WIN32__
1306             || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1307             || blob->blob_location == BLOB_WIN32_ENCRYPTED
1308 #endif
1309            ;
1310 }
1311
1312 static void
1313 init_done_with_file_info(struct list_head *blob_list)
1314 {
1315         struct blob_descriptor *blob;
1316
1317         list_for_each_entry(blob, blob_list, write_blobs_list) {
1318                 if (blob_is_in_file(blob)) {
1319                         blob->file_inode->i_num_remaining_streams = 0;
1320                         blob->may_send_done_with_file = 1;
1321                 } else {
1322                         blob->may_send_done_with_file = 0;
1323                 }
1324         }
1325
1326         list_for_each_entry(blob, blob_list, write_blobs_list)
1327                 if (blob->may_send_done_with_file)
1328                         blob->file_inode->i_num_remaining_streams++;
1329 }
1330
1331 /*
1332  * Write a list of blobs to the output WIM file.
1333  *
1334  * @blob_list
1335  *      The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1336  *      by the 'write_blobs_list' member.
1337  *
1338  * @out_fd
1339  *      The file descriptor, opened for writing, to which to write the blobs.
1340  *
1341  * @write_resource_flags
1342  *      Flags to modify how the blobs are written:
1343  *
1344  *      WRITE_RESOURCE_FLAG_RECOMPRESS:
1345  *              Force compression of all resources, even if they could otherwise
1346  *              be re-used by copying the raw data, due to being located in a WIM
1347  *              file with compatible compression parameters.
1348  *
1349  *      WRITE_RESOURCE_FLAG_PIPABLE:
1350  *              Write the resources in the wimlib-specific pipable format, and
1351  *              furthermore do so in such a way that no seeking backwards in
1352  *              @out_fd will be performed (so it may be a pipe).
1353  *
1354  *      WRITE_RESOURCE_FLAG_SOLID:
1355  *              Combine all the blobs into a single resource rather than writing
1356  *              them in separate resources.  This flag is only valid if the WIM
1357  *              version number has been, or will be, set to WIM_VERSION_SOLID.
1358  *              This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1359  *
1360  * @out_ctype
1361  *      Compression format to use in the output resources, specified as one of
1362  *      the WIMLIB_COMPRESSION_TYPE_* constants.  WIMLIB_COMPRESSION_TYPE_NONE
1363  *      is allowed.
1364  *
1365  * @out_chunk_size
1366  *      Compression chunk size to use in the output resources.  It must be a
1367  *      valid chunk size for the specified compression format @out_ctype, unless
1368  *      @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1369  *      is ignored.
1370  *
1371  * @num_threads
1372  *      Number of threads to use to compress data.  If 0, a default number of
1373  *      threads will be chosen.  The number of threads still may be decreased
1374  *      from the specified value if insufficient memory is detected.
1375  *
1376  * @blob_table
1377  *      If on-the-fly deduplication of unhashed blobs is desired, this parameter
1378  *      must be pointer to the blob table for the WIMStruct on whose behalf the
1379  *      blobs are being written.  Otherwise, this parameter can be NULL.
1380  *
1381  * @filter_ctx
1382  *      If on-the-fly deduplication of unhashed blobs is desired, this parameter
1383  *      can be a pointer to a context for blob filtering used to detect whether
1384  *      the duplicate blob has been hard-filtered or not.  If no blobs are
1385  *      hard-filtered or no blobs are unhashed, this parameter can be NULL.
1386  *
1387  * This function will write the blobs in @blob_list to resources in
1388  * consecutive positions in the output WIM file, or to a single solid resource
1389  * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags.  In both
1390  * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1391  * updated to specify its location, size, and flags in the output WIM.  In the
1392  * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1393  * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1394  * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1395  * respectively, in the output WIM of the solid resource containing the
1396  * corresponding blob.
1397  *
1398  * Each of the blobs to write may be in any location supported by the
1399  * resource-handling code (specifically, read_blob_list()), such as the contents
1400  * of external file that has been logically added to the output WIM, or a blob
1401  * in another WIM file that has been imported, or even a blob in the "same" WIM
1402  * file of which a modified copy is being written.  In the case that a blob is
1403  * already in a WIM file and uses compatible compression parameters, by default
1404  * this function will re-use the raw data instead of decompressing it, then
1405  * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1406  * specified in @write_resource_flags, this is not done.
1407  *
1408  * As a further requirement, this function requires that the
1409  * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1410  * as any other blobs not in @blob_list that will be in the output WIM file, but
1411  * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1412  * resource with a blob in @blob_list.  Still furthermore, if on-the-fly
1413  * deduplication of blobs is possible, then all blobs in @blob_list must also be
1414  * linked by @blob_table_list along with any other blobs that have
1415  * @will_be_in_output_wim set.
1416  *
1417  * This function handles on-the-fly deduplication of blobs for which SHA-1
1418  * message digests have not yet been calculated.  Such blobs may or may not need
1419  * to be written.  If @blob_table is non-NULL, then each blob in @blob_list that
1420  * has @unhashed set but not @unique_size set is checksummed immediately before
1421  * it would otherwise be read for writing in order to determine if it is
1422  * identical to another blob already being written or one that would be filtered
1423  * out of the output WIM using blob_filtered() with the context @filter_ctx.
1424  * Each such duplicate blob will be removed from @blob_list, its reference count
1425  * transfered to the pre-existing duplicate blob, its memory freed, and will not
1426  * be written.  Alternatively, if a blob in @blob_list is a duplicate with any
1427  * blob in @blob_table that has not been marked for writing or would not be
1428  * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1429  * taking ownership of the reference count and slot in the @blob_table_list.
1430  *
1431  * Returns 0 if every blob was either written successfully or did not need to be
1432  * written; otherwise returns a non-zero error code.
1433  */
1434 static int
1435 write_blob_list(struct list_head *blob_list,
1436                 struct filedes *out_fd,
1437                 int write_resource_flags,
1438                 int out_ctype,
1439                 u32 out_chunk_size,
1440                 unsigned num_threads,
1441                 struct blob_table *blob_table,
1442                 struct filter_context *filter_ctx,
1443                 wimlib_progress_func_t progfunc,
1444                 void *progctx)
1445 {
1446         int ret;
1447         struct write_blobs_ctx ctx;
1448         struct list_head raw_copy_blobs;
1449
1450         wimlib_assert((write_resource_flags &
1451                        (WRITE_RESOURCE_FLAG_SOLID |
1452                         WRITE_RESOURCE_FLAG_PIPABLE)) !=
1453                                 (WRITE_RESOURCE_FLAG_SOLID |
1454                                  WRITE_RESOURCE_FLAG_PIPABLE));
1455
1456         validate_blob_list(blob_list);
1457
1458         if (list_empty(blob_list))
1459                 return 0;
1460
1461         /* If needed, set auxiliary information so that we can detect when the
1462          * library has finished using each external file.  */
1463         if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1464                 init_done_with_file_info(blob_list);
1465
1466         memset(&ctx, 0, sizeof(ctx));
1467
1468         ctx.out_fd = out_fd;
1469         ctx.blob_table = blob_table;
1470         ctx.out_ctype = out_ctype;
1471         ctx.out_chunk_size = out_chunk_size;
1472         ctx.write_resource_flags = write_resource_flags;
1473         ctx.filter_ctx = filter_ctx;
1474
1475         /*
1476          * We normally sort the blobs to write by a "sequential" order that is
1477          * optimized for reading.  But when using solid compression, we instead
1478          * sort the blobs by file extension and file name (when applicable; and
1479          * we don't do this for blobs from solid resources) so that similar
1480          * files are grouped together, which improves the compression ratio.
1481          * This is somewhat of a hack since a blob does not necessarily
1482          * correspond one-to-one with a filename, nor is there any guarantee
1483          * that two files with similar names or extensions are actually similar
1484          * in content.  A potential TODO is to sort the blobs based on some
1485          * measure of similarity of their actual contents.
1486          */
1487
1488         ret = sort_blob_list_by_sequential_order(blob_list,
1489                                                  offsetof(struct blob_descriptor,
1490                                                           write_blobs_list));
1491         if (ret)
1492                 return ret;
1493
1494         compute_blob_list_stats(blob_list, &ctx);
1495
1496         if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1497                 ret = sort_blob_list_for_solid_compression(blob_list);
1498                 if (unlikely(ret))
1499                         WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1500         }
1501
1502         ctx.progress_data.progfunc = progfunc;
1503         ctx.progress_data.progctx = progctx;
1504
1505         ctx.num_bytes_to_compress = find_raw_copy_blobs(blob_list,
1506                                                         write_resource_flags,
1507                                                         out_ctype,
1508                                                         out_chunk_size,
1509                                                         &raw_copy_blobs);
1510
1511         if (ctx.num_bytes_to_compress == 0)
1512                 goto out_write_raw_copy_resources;
1513
1514         /* Unless uncompressed output was required, allocate a chunk_compressor
1515          * to do compression.  There are serial and parallel implementations of
1516          * the chunk_compressor interface.  We default to parallel using the
1517          * specified number of threads, unless the upper bound on the number
1518          * bytes needing to be compressed is less than a heuristic value.  */
1519         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1520
1521         #ifdef ENABLE_MULTITHREADED_COMPRESSION
1522                 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1523                         ret = new_parallel_chunk_compressor(out_ctype,
1524                                                             out_chunk_size,
1525                                                             num_threads, 0,
1526                                                             &ctx.compressor);
1527                         if (ret > 0) {
1528                                 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1529                                         "          Falling back to single-threaded compression.",
1530                                         wimlib_get_error_string(ret));
1531                         }
1532                 }
1533         #endif
1534
1535                 if (ctx.compressor == NULL) {
1536                         ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1537                                                           &ctx.compressor);
1538                         if (ret)
1539                                 goto out_destroy_context;
1540                 }
1541         }
1542
1543         if (ctx.compressor)
1544                 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1545         else
1546                 ctx.progress_data.progress.write_streams.num_threads = 1;
1547
1548         INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1549         INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1550
1551         ret = call_progress(ctx.progress_data.progfunc,
1552                             WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1553                             &ctx.progress_data.progress,
1554                             ctx.progress_data.progctx);
1555         if (ret)
1556                 goto out_destroy_context;
1557
1558         if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1559                 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1560                 if (ret)
1561                         goto out_destroy_context;
1562         }
1563
1564         /* Read the list of blobs needing to be compressed, using the specified
1565          * callbacks to execute processing of the data.  */
1566
1567         struct read_blob_callbacks cbs = {
1568                 .begin_blob     = write_blob_begin_read,
1569                 .consume_chunk  = write_blob_process_chunk,
1570                 .end_blob       = write_blob_end_read,
1571                 .ctx            = &ctx,
1572         };
1573
1574         ret = read_blob_list(blob_list,
1575                              offsetof(struct blob_descriptor, write_blobs_list),
1576                              &cbs,
1577                              BLOB_LIST_ALREADY_SORTED |
1578                                 VERIFY_BLOB_HASHES |
1579                                 COMPUTE_MISSING_BLOB_HASHES);
1580
1581         if (ret)
1582                 goto out_destroy_context;
1583
1584         ret = finish_remaining_chunks(&ctx);
1585         if (ret)
1586                 goto out_destroy_context;
1587
1588         if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1589                 struct wim_reshdr reshdr;
1590                 struct blob_descriptor *blob;
1591                 u64 offset_in_res;
1592
1593                 ret = end_write_resource(&ctx, &reshdr);
1594                 if (ret)
1595                         goto out_destroy_context;
1596
1597                 offset_in_res = 0;
1598                 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1599                         blob->out_reshdr.size_in_wim = blob->size;
1600                         blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1601                                                  WIM_RESHDR_FLAG_SOLID;
1602                         blob->out_reshdr.uncompressed_size = 0;
1603                         blob->out_reshdr.offset_in_wim = offset_in_res;
1604                         blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1605                         blob->out_res_size_in_wim = reshdr.size_in_wim;
1606                         blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1607                         offset_in_res += blob->size;
1608                 }
1609                 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1610         }
1611
1612 out_write_raw_copy_resources:
1613         /* Copy any compressed resources for which the raw data can be reused
1614          * without decompression.  */
1615         ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1616                                        &ctx.progress_data);
1617
1618 out_destroy_context:
1619         FREE(ctx.chunk_csizes);
1620         if (ctx.compressor)
1621                 ctx.compressor->destroy(ctx.compressor);
1622         return ret;
1623 }
1624
1625
1626 static int
1627 write_file_data_blobs(WIMStruct *wim,
1628                       struct list_head *blob_list,
1629                       int write_flags,
1630                       unsigned num_threads,
1631                       struct filter_context *filter_ctx)
1632 {
1633         int out_ctype;
1634         u32 out_chunk_size;
1635         int write_resource_flags;
1636
1637         write_resource_flags = write_flags_to_resource_flags(write_flags);
1638
1639         if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1640                 out_chunk_size = wim->out_solid_chunk_size;
1641                 out_ctype = wim->out_solid_compression_type;
1642         } else {
1643                 out_chunk_size = wim->out_chunk_size;
1644                 out_ctype = wim->out_compression_type;
1645         }
1646
1647         return write_blob_list(blob_list,
1648                                &wim->out_fd,
1649                                write_resource_flags,
1650                                out_ctype,
1651                                out_chunk_size,
1652                                num_threads,
1653                                wim->blob_table,
1654                                filter_ctx,
1655                                wim->progfunc,
1656                                wim->progctx);
1657 }
1658
1659 /* Write the contents of the specified blob as a WIM resource.  */
1660 static int
1661 write_wim_resource(struct blob_descriptor *blob,
1662                    struct filedes *out_fd,
1663                    int out_ctype,
1664                    u32 out_chunk_size,
1665                    int write_resource_flags)
1666 {
1667         LIST_HEAD(blob_list);
1668         list_add(&blob->write_blobs_list, &blob_list);
1669         blob->will_be_in_output_wim = 1;
1670         return write_blob_list(&blob_list,
1671                                out_fd,
1672                                write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1673                                out_ctype,
1674                                out_chunk_size,
1675                                1,
1676                                NULL,
1677                                NULL,
1678                                NULL,
1679                                NULL);
1680 }
1681
1682 /* Write the contents of the specified buffer as a WIM resource.  */
1683 int
1684 write_wim_resource_from_buffer(const void *buf,
1685                                size_t buf_size,
1686                                bool is_metadata,
1687                                struct filedes *out_fd,
1688                                int out_ctype,
1689                                u32 out_chunk_size,
1690                                struct wim_reshdr *out_reshdr,
1691                                u8 *hash_ret,
1692                                int write_resource_flags)
1693 {
1694         int ret;
1695         struct blob_descriptor blob;
1696
1697         if (unlikely(buf_size == 0)) {
1698                 zero_reshdr(out_reshdr);
1699                 if (hash_ret)
1700                         copy_hash(hash_ret, zero_hash);
1701                 return 0;
1702         }
1703
1704         blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1705         sha1_buffer(buf, buf_size, blob.hash);
1706         blob.unhashed = 0;
1707         blob.is_metadata = is_metadata;
1708
1709         ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1710                                  write_resource_flags);
1711         if (ret)
1712                 return ret;
1713
1714         copy_reshdr(out_reshdr, &blob.out_reshdr);
1715
1716         if (hash_ret)
1717                 copy_hash(hash_ret, blob.hash);
1718         return 0;
1719 }
1720
1721 struct blob_size_table {
1722         struct hlist_head *array;
1723         size_t num_entries;
1724         size_t capacity;
1725 };
1726
1727 static int
1728 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1729 {
1730         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1731         if (tab->array == NULL)
1732                 return WIMLIB_ERR_NOMEM;
1733         tab->num_entries = 0;
1734         tab->capacity = capacity;
1735         return 0;
1736 }
1737
1738 static void
1739 destroy_blob_size_table(struct blob_size_table *tab)
1740 {
1741         FREE(tab->array);
1742 }
1743
1744 static int
1745 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1746 {
1747         struct blob_size_table *tab = _tab;
1748         size_t pos;
1749         struct blob_descriptor *same_size_blob;
1750
1751         pos = hash_u64(blob->size) % tab->capacity;
1752         blob->unique_size = 1;
1753         hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1754                 if (same_size_blob->size == blob->size) {
1755                         blob->unique_size = 0;
1756                         same_size_blob->unique_size = 0;
1757                         break;
1758                 }
1759         }
1760
1761         hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1762         tab->num_entries++;
1763         return 0;
1764 }
1765
1766 struct find_blobs_ctx {
1767         WIMStruct *wim;
1768         int write_flags;
1769         struct list_head blob_list;
1770         struct blob_size_table blob_size_tab;
1771 };
1772
1773 static void
1774 reference_blob_for_write(struct blob_descriptor *blob,
1775                          struct list_head *blob_list, u32 nref)
1776 {
1777         if (!blob->will_be_in_output_wim) {
1778                 blob->out_refcnt = 0;
1779                 list_add_tail(&blob->write_blobs_list, blob_list);
1780                 blob->will_be_in_output_wim = 1;
1781         }
1782         blob->out_refcnt += nref;
1783 }
1784
1785 static int
1786 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1787 {
1788         struct list_head *blob_list = _blob_list;
1789         blob->will_be_in_output_wim = 0;
1790         reference_blob_for_write(blob, blob_list, blob->refcnt);
1791         return 0;
1792 }
1793
1794 static int
1795 inode_find_blobs_to_reference(const struct wim_inode *inode,
1796                               const struct blob_table *table,
1797                               struct list_head *blob_list)
1798 {
1799         wimlib_assert(inode->i_nlink > 0);
1800
1801         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1802                 struct blob_descriptor *blob;
1803                 const u8 *hash;
1804
1805                 blob = stream_blob(&inode->i_streams[i], table);
1806                 if (blob) {
1807                         reference_blob_for_write(blob, blob_list, inode->i_nlink);
1808                 } else {
1809                         hash = stream_hash(&inode->i_streams[i]);
1810                         if (!is_zero_hash(hash))
1811                                 return blob_not_found_error(inode, hash);
1812                 }
1813         }
1814         return 0;
1815 }
1816
1817 static int
1818 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1819 {
1820         blob->will_be_in_output_wim = 0;
1821         return 0;
1822 }
1823
1824 static int
1825 image_find_blobs_to_reference(WIMStruct *wim)
1826 {
1827         struct wim_image_metadata *imd;
1828         struct wim_inode *inode;
1829         struct blob_descriptor *blob;
1830         struct list_head *blob_list;
1831         int ret;
1832
1833         imd = wim_get_current_image_metadata(wim);
1834
1835         image_for_each_unhashed_blob(blob, imd)
1836                 blob->will_be_in_output_wim = 0;
1837
1838         blob_list = wim->private;
1839         image_for_each_inode(inode, imd) {
1840                 ret = inode_find_blobs_to_reference(inode,
1841                                                     wim->blob_table,
1842                                                     blob_list);
1843                 if (ret)
1844                         return ret;
1845         }
1846         return 0;
1847 }
1848
1849 static int
1850 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1851                                                int image,
1852                                                int blobs_ok,
1853                                                struct list_head *blob_list_ret)
1854 {
1855         int ret;
1856
1857         INIT_LIST_HEAD(blob_list_ret);
1858
1859         if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1860                          (image == 1 && wim->hdr.image_count == 1)))
1861         {
1862                 /* Fast case:  Assume that all blobs are being written and that
1863                  * the reference counts are correct.  */
1864                 struct blob_descriptor *blob;
1865                 struct wim_image_metadata *imd;
1866                 unsigned i;
1867
1868                 for_blob_in_table(wim->blob_table,
1869                                   fully_reference_blob_for_write,
1870                                   blob_list_ret);
1871
1872                 for (i = 0; i < wim->hdr.image_count; i++) {
1873                         imd = wim->image_metadata[i];
1874                         image_for_each_unhashed_blob(blob, imd)
1875                                 fully_reference_blob_for_write(blob, blob_list_ret);
1876                 }
1877         } else {
1878                 /* Slow case:  Walk through the images being written and
1879                  * determine the blobs referenced.  */
1880                 for_blob_in_table(wim->blob_table,
1881                                   do_blob_set_not_in_output_wim, NULL);
1882                 wim->private = blob_list_ret;
1883                 ret = for_image(wim, image, image_find_blobs_to_reference);
1884                 if (ret)
1885                         return ret;
1886         }
1887
1888         return 0;
1889 }
1890
1891 struct insert_other_if_hard_filtered_ctx {
1892         struct blob_size_table *tab;
1893         struct filter_context *filter_ctx;
1894 };
1895
1896 static int
1897 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1898 {
1899         struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1900
1901         if (!blob->will_be_in_output_wim &&
1902             blob_hard_filtered(blob, ctx->filter_ctx))
1903                 blob_size_table_insert(blob, ctx->tab);
1904         return 0;
1905 }
1906
1907 static int
1908 determine_blob_size_uniquity(struct list_head *blob_list,
1909                              struct blob_table *lt,
1910                              struct filter_context *filter_ctx)
1911 {
1912         int ret;
1913         struct blob_size_table tab;
1914         struct blob_descriptor *blob;
1915
1916         ret = init_blob_size_table(&tab, 9001);
1917         if (ret)
1918                 return ret;
1919
1920         if (may_hard_filter_blobs(filter_ctx)) {
1921                 struct insert_other_if_hard_filtered_ctx ctx = {
1922                         .tab = &tab,
1923                         .filter_ctx = filter_ctx,
1924                 };
1925                 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
1926         }
1927
1928         list_for_each_entry(blob, blob_list, write_blobs_list)
1929                 blob_size_table_insert(blob, &tab);
1930
1931         destroy_blob_size_table(&tab);
1932         return 0;
1933 }
1934
1935 static void
1936 filter_blob_list_for_write(struct list_head *blob_list,
1937                            struct filter_context *filter_ctx)
1938 {
1939         struct blob_descriptor *blob, *tmp;
1940
1941         list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1942                 int status = blob_filtered(blob, filter_ctx);
1943
1944                 if (status == 0) {
1945                         /* Not filtered.  */
1946                         continue;
1947                 } else {
1948                         if (status > 0) {
1949                                 /* Soft filtered.  */
1950                         } else {
1951                                 /* Hard filtered.  */
1952                                 blob->will_be_in_output_wim = 0;
1953                                 list_del(&blob->blob_table_list);
1954                         }
1955                         list_del(&blob->write_blobs_list);
1956                 }
1957         }
1958 }
1959
1960 /*
1961  * prepare_blob_list_for_write() -
1962  *
1963  * Prepare the list of blobs to write for writing a WIM containing the specified
1964  * image(s) with the specified write flags.
1965  *
1966  * @wim
1967  *      The WIMStruct on whose behalf the write is occurring.
1968  *
1969  * @image
1970  *      Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1971  *
1972  * @write_flags
1973  *      WIMLIB_WRITE_FLAG_* flags for the write operation:
1974  *
1975  *      STREAMS_OK:  For writes of all images, assume that all blobs in the blob
1976  *      table of @wim and the per-image lists of unhashed blobs should be taken
1977  *      as-is, and image metadata should not be searched for references.  This
1978  *      does not exclude filtering with OVERWRITE and SKIP_EXTERNAL_WIMS, below.
1979  *
1980  *      OVERWRITE:  Blobs already present in @wim shall not be returned in
1981  *      @blob_list_ret.
1982  *
1983  *      SKIP_EXTERNAL_WIMS:  Blobs already present in a WIM file, but not @wim,
1984  *      shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
1985  *
1986  * @blob_list_ret
1987  *      List of blobs, linked by write_blobs_list, that need to be written will
1988  *      be returned here.
1989  *
1990  *      Note that this function assumes that unhashed blobs will be written; it
1991  *      does not take into account that they may become duplicates when actually
1992  *      hashed.
1993  *
1994  * @blob_table_list_ret
1995  *      List of blobs, linked by blob_table_list, that need to be included in
1996  *      the WIM's blob table will be returned here.  This will be a superset of
1997  *      the blobs in @blob_list_ret.
1998  *
1999  *      This list will be a proper superset of @blob_list_ret if and only if
2000  *      WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2001  *      the blobs that would otherwise need to be written were already located
2002  *      in the WIM file.
2003  *
2004  *      All blobs in this list will have @out_refcnt set to the number of
2005  *      references to the blob in the output WIM.  If
2006  *      WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2007  *      may be as low as 0.
2008  *
2009  * @filter_ctx_ret
2010  *      A context for queries of blob filter status with blob_filtered() is
2011  *      returned in this location.
2012  *
2013  * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2014  * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2015  * inserted into @blob_table_list_ret.
2016  *
2017  * Still furthermore, @unique_size will be set to 1 on all blobs in
2018  * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2019  * among all blobs in the blob table of @wim that are ineligible for being
2020  * written due to filtering.
2021  *
2022  * Returns 0 on success; nonzero on read error, memory allocation error, or
2023  * otherwise.
2024  */
2025 static int
2026 prepare_blob_list_for_write(WIMStruct *wim, int image,
2027                             int write_flags,
2028                             struct list_head *blob_list_ret,
2029                             struct list_head *blob_table_list_ret,
2030                             struct filter_context *filter_ctx_ret)
2031 {
2032         int ret;
2033         struct blob_descriptor *blob;
2034
2035         filter_ctx_ret->write_flags = write_flags;
2036         filter_ctx_ret->wim = wim;
2037
2038         ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2039                                 wim,
2040                                 image,
2041                                 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2042                                 blob_list_ret);
2043         if (ret)
2044                 return ret;
2045
2046         INIT_LIST_HEAD(blob_table_list_ret);
2047         list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2048                 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2049
2050         ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2051                                            filter_ctx_ret);
2052         if (ret)
2053                 return ret;
2054
2055         if (may_filter_blobs(filter_ctx_ret))
2056                 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2057
2058         return 0;
2059 }
2060
2061 static int
2062 write_file_data(WIMStruct *wim, int image, int write_flags,
2063                 unsigned num_threads,
2064                 struct list_head *blob_list_override,
2065                 struct list_head *blob_table_list_ret)
2066 {
2067         int ret;
2068         struct list_head _blob_list;
2069         struct list_head *blob_list;
2070         struct blob_descriptor *blob;
2071         struct filter_context _filter_ctx;
2072         struct filter_context *filter_ctx;
2073
2074         if (blob_list_override == NULL) {
2075                 /* Normal case: prepare blob list from image(s) being written.
2076                  */
2077                 blob_list = &_blob_list;
2078                 filter_ctx = &_filter_ctx;
2079                 ret = prepare_blob_list_for_write(wim, image, write_flags,
2080                                                   blob_list,
2081                                                   blob_table_list_ret,
2082                                                   filter_ctx);
2083                 if (ret)
2084                         return ret;
2085         } else {
2086                 /* Currently only as a result of wimlib_split() being called:
2087                  * use blob list already explicitly provided.  Use existing
2088                  * reference counts.  */
2089                 blob_list = blob_list_override;
2090                 filter_ctx = NULL;
2091                 INIT_LIST_HEAD(blob_table_list_ret);
2092                 list_for_each_entry(blob, blob_list, write_blobs_list) {
2093                         blob->out_refcnt = blob->refcnt;
2094                         blob->will_be_in_output_wim = 1;
2095                         blob->unique_size = 0;
2096                         list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2097                 }
2098         }
2099
2100         return write_file_data_blobs(wim,
2101                                      blob_list,
2102                                      write_flags,
2103                                      num_threads,
2104                                      filter_ctx);
2105 }
2106
2107 static int
2108 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2109 {
2110         int ret;
2111         int start_image;
2112         int end_image;
2113         int write_resource_flags;
2114
2115         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2116                 return 0;
2117
2118         write_resource_flags = write_flags_to_resource_flags(write_flags);
2119
2120         write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2121
2122         ret = call_progress(wim->progfunc,
2123                             WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2124                             NULL, wim->progctx);
2125         if (ret)
2126                 return ret;
2127
2128         if (image == WIMLIB_ALL_IMAGES) {
2129                 start_image = 1;
2130                 end_image = wim->hdr.image_count;
2131         } else {
2132                 start_image = image;
2133                 end_image = image;
2134         }
2135
2136         for (int i = start_image; i <= end_image; i++) {
2137                 struct wim_image_metadata *imd;
2138
2139                 imd = wim->image_metadata[i - 1];
2140                 /* Build a new metadata resource only if image was modified from
2141                  * the original (or was newly added).  Otherwise just copy the
2142                  * existing one.  */
2143                 if (imd->modified) {
2144                         ret = write_metadata_resource(wim, i,
2145                                                       write_resource_flags);
2146                 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2147                         blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2148                         ret = 0;
2149                 } else {
2150                         ret = write_wim_resource(imd->metadata_blob,
2151                                                  &wim->out_fd,
2152                                                  wim->out_compression_type,
2153                                                  wim->out_chunk_size,
2154                                                  write_resource_flags);
2155                 }
2156                 if (ret)
2157                         return ret;
2158         }
2159
2160         return call_progress(wim->progfunc,
2161                              WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2162                              NULL, wim->progctx);
2163 }
2164
2165 static int
2166 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2167 {
2168         int raw_fd = topen(path, open_flags | O_BINARY, 0644);
2169         if (raw_fd < 0) {
2170                 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2171                 return WIMLIB_ERR_OPEN;
2172         }
2173         filedes_init(&wim->out_fd, raw_fd);
2174         return 0;
2175 }
2176
2177 static int
2178 close_wim_writable(WIMStruct *wim, int write_flags)
2179 {
2180         int ret = 0;
2181
2182         if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2183                 if (filedes_valid(&wim->out_fd))
2184                         if (filedes_close(&wim->out_fd))
2185                                 ret = WIMLIB_ERR_WRITE;
2186         filedes_invalidate(&wim->out_fd);
2187         return ret;
2188 }
2189
2190 static int
2191 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2192 {
2193         const struct blob_descriptor *blob1, *blob2;
2194
2195         blob1 = *(const struct blob_descriptor**)p1;
2196         blob2 = *(const struct blob_descriptor**)p2;
2197
2198         if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2199                 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2200                         if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2201                                 return cmp_u64(blob1->out_res_offset_in_wim,
2202                                                blob2->out_res_offset_in_wim);
2203                 } else {
2204                         return 1;
2205                 }
2206         } else {
2207                 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2208                         return -1;
2209         }
2210         return cmp_u64(blob1->out_reshdr.offset_in_wim,
2211                        blob2->out_reshdr.offset_in_wim);
2212 }
2213
2214 static int
2215 write_blob_table(WIMStruct *wim, int image, int write_flags,
2216                  struct list_head *blob_table_list)
2217 {
2218         int ret;
2219
2220         /* Set output resource metadata for blobs already present in WIM.  */
2221         if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2222                 struct blob_descriptor *blob;
2223                 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2224                         if (blob->blob_location == BLOB_IN_WIM &&
2225                             blob->rdesc->wim == wim)
2226                         {
2227                                 blob_set_out_reshdr_for_reuse(blob);
2228                         }
2229                 }
2230         }
2231
2232         ret = sort_blob_list(blob_table_list,
2233                              offsetof(struct blob_descriptor, blob_table_list),
2234                              cmp_blobs_by_out_rdesc);
2235         if (ret)
2236                 return ret;
2237
2238         /* Add entries for metadata resources.  */
2239         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2240                 int start_image;
2241                 int end_image;
2242
2243                 if (image == WIMLIB_ALL_IMAGES) {
2244                         start_image = 1;
2245                         end_image = wim->hdr.image_count;
2246                 } else {
2247                         start_image = image;
2248                         end_image = image;
2249                 }
2250
2251                 /* Push metadata blob table entries onto the front of the list
2252                  * in reverse order, so that they're written in order.
2253                  */
2254                 for (int i = end_image; i >= start_image; i--) {
2255                         struct blob_descriptor *metadata_blob;
2256
2257                         metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2258                         wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2259                         metadata_blob->out_refcnt = 1;
2260                         list_add(&metadata_blob->blob_table_list, blob_table_list);
2261                 }
2262         }
2263
2264         return write_blob_table_from_blob_list(blob_table_list,
2265                                                &wim->out_fd,
2266                                                wim->out_hdr.part_number,
2267                                                &wim->out_hdr.blob_table_reshdr,
2268                                                write_flags_to_resource_flags(write_flags));
2269 }
2270
2271 /*
2272  * Finish writing a WIM file: write the blob table, xml data, and integrity
2273  * table, then overwrite the WIM header.
2274  *
2275  * The output file descriptor is closed on success, except when writing to a
2276  * user-specified file descriptor (WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR set).
2277  */
2278 static int
2279 finish_write(WIMStruct *wim, int image, int write_flags,
2280              struct list_head *blob_table_list)
2281 {
2282         int write_resource_flags;
2283         off_t old_blob_table_end = 0;
2284         struct integrity_table *old_integrity_table = NULL;
2285         off_t new_blob_table_end;
2286         u64 xml_totalbytes;
2287         int ret;
2288
2289         write_resource_flags = write_flags_to_resource_flags(write_flags);
2290
2291         /* In the WIM header, there is room for the resource entry for a
2292          * metadata resource labeled as the "boot metadata".  This entry should
2293          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
2294          * it should be a copy of the resource entry for the image that is
2295          * marked as bootable.  */
2296         if (wim->out_hdr.boot_idx == 0) {
2297                 zero_reshdr(&wim->out_hdr.boot_metadata_reshdr);
2298         } else {
2299                 copy_reshdr(&wim->out_hdr.boot_metadata_reshdr,
2300                             &wim->image_metadata[
2301                                 wim->out_hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2302         }
2303
2304         /* If overwriting the WIM file containing an integrity table in-place,
2305          * we'd like to re-use the information in the old integrity table
2306          * instead of recalculating it.  But we might overwrite the old
2307          * integrity table when we expand the XML data.  Read it into memory
2308          * just in case.  */
2309         if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2310                             WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2311                 (WIMLIB_WRITE_FLAG_OVERWRITE |
2312                  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2313             && wim_has_integrity_table(wim))
2314         {
2315                 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2316                                      wim->hdr.blob_table_reshdr.size_in_wim;
2317                 (void)read_integrity_table(wim,
2318                                            old_blob_table_end - WIM_HEADER_DISK_SIZE,
2319                                            &old_integrity_table);
2320                 /* If we couldn't read the old integrity table, we can still
2321                  * re-calculate the full integrity table ourselves.  Hence the
2322                  * ignoring of the return value.  */
2323         }
2324
2325         /* Write blob table if needed.  */
2326         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
2327                 ret = write_blob_table(wim, image, write_flags,
2328                                        blob_table_list);
2329                 if (ret) {
2330                         free_integrity_table(old_integrity_table);
2331                         return ret;
2332                 }
2333         }
2334
2335         /* Write XML data.  */
2336         xml_totalbytes = wim->out_fd.offset;
2337         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2338                 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2339         ret = write_wim_xml_data(wim, image, xml_totalbytes,
2340                                  &wim->out_hdr.xml_data_reshdr,
2341                                  write_resource_flags);
2342         if (ret) {
2343                 free_integrity_table(old_integrity_table);
2344                 return ret;
2345         }
2346
2347         /* Write integrity table if needed.  */
2348         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2349                 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS) {
2350                         /* The XML data we wrote may have overwritten part of
2351                          * the old integrity table, so while calculating the new
2352                          * integrity table we should temporarily update the WIM
2353                          * header to remove the integrity table reference.   */
2354                         struct wim_header checkpoint_hdr;
2355                         memcpy(&checkpoint_hdr, &wim->out_hdr, sizeof(struct wim_header));
2356                         zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2357                         checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2358                         ret = write_wim_header(&checkpoint_hdr, &wim->out_fd, 0);
2359                         if (ret) {
2360                                 free_integrity_table(old_integrity_table);
2361                                 return ret;
2362                         }
2363                 }
2364
2365                 new_blob_table_end = wim->out_hdr.blob_table_reshdr.offset_in_wim +
2366                                      wim->out_hdr.blob_table_reshdr.size_in_wim;
2367
2368                 ret = write_integrity_table(wim,
2369                                             new_blob_table_end,
2370                                             old_blob_table_end,
2371                                             old_integrity_table);
2372                 free_integrity_table(old_integrity_table);
2373                 if (ret)
2374                         return ret;
2375         } else {
2376                 /* No integrity table.  */
2377                 zero_reshdr(&wim->out_hdr.integrity_table_reshdr);
2378         }
2379
2380         /* Now that all information in the WIM header has been determined, the
2381          * preliminary header written earlier can be overwritten, the header of
2382          * the existing WIM file can be overwritten, or the final header can be
2383          * written to the end of the pipable WIM.  */
2384         wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2385         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2386                 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2387         else
2388                 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, 0);
2389         if (ret)
2390                 return ret;
2391
2392         /* Possibly sync file data to disk before closing.  On POSIX systems, it
2393          * is necessary to do this before using rename() to overwrite an
2394          * existing file with a new file.  Otherwise, data loss would occur if
2395          * the system is abruptly terminated when the metadata for the rename
2396          * operation has been written to disk, but the new file data has not.
2397          */
2398         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2399                 if (fsync(wim->out_fd.fd)) {
2400                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
2401                         return WIMLIB_ERR_WRITE;
2402                 }
2403         }
2404
2405         if (close_wim_writable(wim, write_flags)) {
2406                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2407                 return WIMLIB_ERR_WRITE;
2408         }
2409
2410         return 0;
2411 }
2412
2413 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2414
2415 /* Set advisory lock on WIM file (if not already done so)  */
2416 int
2417 lock_wim_for_append(WIMStruct *wim)
2418 {
2419         if (wim->locked_for_append)
2420                 return 0;
2421         if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2422                 wim->locked_for_append = 1;
2423                 return 0;
2424         }
2425         if (errno != EWOULDBLOCK)
2426                 return 0;
2427         return WIMLIB_ERR_ALREADY_LOCKED;
2428 }
2429
2430 /* Remove advisory lock on WIM file (if present)  */
2431 void
2432 unlock_wim_for_append(WIMStruct *wim)
2433 {
2434         if (wim->locked_for_append) {
2435                 flock(wim->in_fd.fd, LOCK_UN);
2436                 wim->locked_for_append = 0;
2437         }
2438 }
2439 #endif
2440
2441 /*
2442  * write_pipable_wim():
2443  *
2444  * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2445  * capable of being applied from a pipe).
2446  *
2447  * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2448  * images can be applied from them sequentially when the file data is sent over
2449  * a pipe.  In addition, a pipable WIM can be written sequentially to a pipe.
2450  * The modifications made to the WIM format for pipable WIMs are:
2451  *
2452  * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2453  *   of "MSWIM\0\0\0".  This lets wimlib know that the WIM is pipable and also
2454  *   stops other software from trying to read the file as a normal WIM.
2455  *
2456  * - The header at the beginning of the file does not contain all the normal
2457  *   information; in particular it will have all 0's for the blob table and XML
2458  *   data resource entries.  This is because this information cannot be
2459  *   determined until the blob table and XML data have been written.
2460  *   Consequently, wimlib will write the full header at the very end of the
2461  *   file.  The header at the end, however, is only used when reading the WIM
2462  *   from a seekable file (not a pipe).
2463  *
2464  * - An extra copy of the XML data is placed directly after the header.  This
2465  *   allows image names and sizes to be determined at an appropriate time when
2466  *   reading the WIM from a pipe.  This copy of the XML data is ignored if the
2467  *   WIM is read from a seekable file (not a pipe).
2468  *
2469  * - Solid resources are not allowed.  Each blob is always stored in its own
2470  *   resource.
2471  *
2472  * - The format of resources, or blobs, has been modified to allow them to be
2473  *   used before the "blob table" has been read.  Each blob is prefixed with a
2474  *   `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2475  *   blob_descriptor_disk' that only contains the SHA-1 message digest,
2476  *   uncompressed blob size, and flags that indicate whether the blob is
2477  *   compressed.  The data of uncompressed blobs then follows literally, while
2478  *   the data of compressed blobs follows in a modified format.  Compressed
2479  *   blobs do not begin with a chunk table, since the chunk table cannot be
2480  *   written until all chunks have been compressed.  Instead, each compressed
2481  *   chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2482  *   Furthermore, the chunk table is written at the end of the resource instead
2483  *   of the start.  Note: chunk offsets are given in the chunk table as if the
2484  *   `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2485  *   used if the WIM is being read from a seekable file (not a pipe).
2486  *
2487  * - Metadata blobs always come before non-metadata blobs.  (This does not by
2488  *   itself constitute an incompatibility with normal WIMs, since this is valid
2489  *   in normal WIMs.)
2490  *
2491  * - At least up to the end of the blobs, all components must be packed as
2492  *   tightly as possible; there cannot be any "holes" in the WIM.  (This does
2493  *   not by itself consititute an incompatibility with normal WIMs, since this
2494  *   is valid in normal WIMs.)
2495  *
2496  * Note: the blob table, XML data, and header at the end are not used when
2497  * applying from a pipe.  They exist to support functionality such as image
2498  * application and export when the WIM is *not* read from a pipe.
2499  *
2500  *   Layout of pipable WIM:
2501  *
2502  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2503  * | Header | XML data | Metadata resources | File resources |  Blob table  | XML data  | Header |
2504  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2505  *
2506  *   Layout of normal WIM:
2507  *
2508  * +--------+-----------------------------+-------------------------+
2509  * | Header | File and metadata resources |  Blob table  | XML data |
2510  * +--------+-----------------------------+-------------------------+
2511  *
2512  * An optional integrity table can follow the final XML data in both normal and
2513  * pipable WIMs.  However, due to implementation details, wimlib currently can
2514  * only include an integrity table in a pipable WIM when writing it to a
2515  * seekable file (not a pipe).
2516  *
2517  * Do note that since pipable WIMs are not supported by Microsoft's software,
2518  * wimlib does not create them unless explicitly requested (with
2519  * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2520  * characters to identify the file.
2521  */
2522 static int
2523 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2524                   unsigned num_threads,
2525                   struct list_head *blob_list_override,
2526                   struct list_head *blob_table_list_ret)
2527 {
2528         int ret;
2529         struct wim_reshdr xml_reshdr;
2530
2531         WARNING("Creating a pipable WIM, which will "
2532                 "be incompatible\n"
2533                 "          with Microsoft's software (WIMGAPI/ImageX/DISM).");
2534
2535         /* At this point, the header at the beginning of the file has already
2536          * been written.  */
2537
2538         /* For efficiency, when wimlib adds an image to the WIM with
2539          * wimlib_add_image(), the SHA-1 message digests of files are not
2540          * calculated; instead, they are calculated while the files are being
2541          * written.  However, this does not work when writing a pipable WIM,
2542          * since when writing a blob to a pipable WIM, its SHA-1 message digest
2543          * needs to be known before the blob data is written.  Therefore, before
2544          * getting much farther, we need to pre-calculate the SHA-1 message
2545          * digests of all blobs that will be written.  */
2546         ret = wim_checksum_unhashed_blobs(wim);
2547         if (ret)
2548                 return ret;
2549
2550         /* Write extra copy of the XML data.  */
2551         ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2552                                  &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2553         if (ret)
2554                 return ret;
2555
2556         /* Write metadata resources for the image(s) being included in the
2557          * output WIM.  */
2558         ret = write_metadata_resources(wim, image, write_flags);
2559         if (ret)
2560                 return ret;
2561
2562         /* Write file data needed for the image(s) being included in the output
2563          * WIM, or file data needed for the split WIM part.  */
2564         return write_file_data(wim, image, write_flags,
2565                                num_threads, blob_list_override,
2566                                blob_table_list_ret);
2567
2568         /* The blob table, XML data, and header at end are handled by
2569          * finish_write().  */
2570 }
2571
2572 static bool
2573 should_default_to_solid_compression(WIMStruct *wim, int write_flags)
2574 {
2575         return wim->out_hdr.wim_version == WIM_VERSION_SOLID &&
2576                 !(write_flags & (WIMLIB_WRITE_FLAG_SOLID |
2577                                  WIMLIB_WRITE_FLAG_PIPABLE)) &&
2578                 wim_has_solid_resources(wim);
2579 }
2580
2581 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2582  * descriptor.  */
2583 int
2584 write_wim_part(WIMStruct *wim,
2585                const void *path_or_fd,
2586                int image,
2587                int write_flags,
2588                unsigned num_threads,
2589                unsigned part_number,
2590                unsigned total_parts,
2591                struct list_head *blob_list_override,
2592                const u8 *guid)
2593 {
2594         int ret;
2595         struct list_head blob_table_list;
2596
2597         /* Internally, this is always called with a valid part number and total
2598          * parts.  */
2599         wimlib_assert(total_parts >= 1);
2600         wimlib_assert(part_number >= 1 && part_number <= total_parts);
2601
2602         /* A valid image (or all images) must be specified.  */
2603         if (image != WIMLIB_ALL_IMAGES &&
2604              (image < 1 || image > wim->hdr.image_count))
2605                 return WIMLIB_ERR_INVALID_IMAGE;
2606
2607         /* If we need to write metadata resources, make sure the ::WIMStruct has
2608          * the needed information attached (e.g. is not a resource-only WIM,
2609          * such as a non-first part of a split WIM).  */
2610         if (!wim_has_metadata(wim) &&
2611             !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2612                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2613
2614         /* Check for contradictory flags.  */
2615         if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2616                             WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2617                                 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2618                                     WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2619                 return WIMLIB_ERR_INVALID_PARAM;
2620
2621         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2622                             WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2623                                 == (WIMLIB_WRITE_FLAG_PIPABLE |
2624                                     WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2625                 return WIMLIB_ERR_INVALID_PARAM;
2626
2627         /* Include an integrity table by default if no preference was given and
2628          * the WIM already had an integrity table.  */
2629         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2630                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))) {
2631                 if (wim_has_integrity_table(wim))
2632                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2633         }
2634
2635         /* Write a pipable WIM by default if no preference was given and the WIM
2636          * was already pipable.  */
2637         if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2638                              WIMLIB_WRITE_FLAG_NOT_PIPABLE))) {
2639                 if (wim_is_pipable(wim))
2640                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2641         }
2642
2643         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2644                             WIMLIB_WRITE_FLAG_SOLID))
2645                                     == (WIMLIB_WRITE_FLAG_PIPABLE |
2646                                         WIMLIB_WRITE_FLAG_SOLID))
2647         {
2648                 ERROR("Solid compression is unsupported in pipable WIMs");
2649                 return WIMLIB_ERR_INVALID_PARAM;
2650         }
2651
2652         /* Start initializing the new file header.  */
2653         memset(&wim->out_hdr, 0, sizeof(wim->out_hdr));
2654
2655         /* Set the magic number.  */
2656         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2657                 wim->out_hdr.magic = PWM_MAGIC;
2658         else
2659                 wim->out_hdr.magic = WIM_MAGIC;
2660
2661         /* Set the version number.  */
2662         if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2663             wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2664                 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2665         else
2666                 wim->out_hdr.wim_version = WIM_VERSION_DEFAULT;
2667
2668         /* Default to solid compression if it is valid in the chosen WIM file
2669          * format and the WIMStruct references any solid resources.  This is
2670          * useful when exporting an image from a solid WIM.  */
2671         if (should_default_to_solid_compression(wim, write_flags))
2672                 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2673
2674         /* Set the header flags.  */
2675         wim->out_hdr.flags = (wim->hdr.flags & (WIM_HDR_FLAG_RP_FIX |
2676                                                 WIM_HDR_FLAG_READONLY));
2677         if (total_parts != 1)
2678                 wim->out_hdr.flags |= WIM_HDR_FLAG_SPANNED;
2679         if (wim->out_compression_type != WIMLIB_COMPRESSION_TYPE_NONE) {
2680                 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESSION;
2681                 switch (wim->out_compression_type) {
2682                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
2683                         wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_XPRESS;
2684                         break;
2685                 case WIMLIB_COMPRESSION_TYPE_LZX:
2686                         wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZX;
2687                         break;
2688                 case WIMLIB_COMPRESSION_TYPE_LZMS:
2689                         wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZMS;
2690                         break;
2691                 }
2692         }
2693
2694         /* Set the chunk size.  */
2695         wim->out_hdr.chunk_size = wim->out_chunk_size;
2696
2697         /* Set the GUID.  */
2698         if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2699                 guid = wim->hdr.guid;
2700         if (guid)
2701                 copy_guid(wim->out_hdr.guid, guid);
2702         else
2703                 generate_guid(wim->out_hdr.guid);
2704
2705         /* Set the part number and total parts.  */
2706         wim->out_hdr.part_number = part_number;
2707         wim->out_hdr.total_parts = total_parts;
2708
2709         /* Set the image count.  */
2710         if (image == WIMLIB_ALL_IMAGES)
2711                 wim->out_hdr.image_count = wim->hdr.image_count;
2712         else
2713                 wim->out_hdr.image_count = 1;
2714
2715         /* Set the boot index.  */
2716         wim->out_hdr.boot_idx = 0;
2717         if (total_parts == 1) {
2718                 if (image == WIMLIB_ALL_IMAGES)
2719                         wim->out_hdr.boot_idx = wim->hdr.boot_idx;
2720                 else if (image == wim->hdr.boot_idx)
2721                         wim->out_hdr.boot_idx = 1;
2722         }
2723
2724         /* Set up the output file descriptor.  */
2725         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2726                 /* File descriptor was explicitly provided.  */
2727                 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2728                 if (!filedes_is_seekable(&wim->out_fd)) {
2729                         /* The file descriptor is a pipe.  */
2730                         ret = WIMLIB_ERR_INVALID_PARAM;
2731                         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2732                                 goto out_cleanup;
2733                         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2734                                 ERROR("Can't include integrity check when "
2735                                       "writing pipable WIM to pipe!");
2736                                 goto out_cleanup;
2737                         }
2738                 }
2739         } else {
2740                 /* Filename of WIM to write was provided; open file descriptor
2741                  * to it.  */
2742                 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2743                                         O_TRUNC | O_CREAT | O_RDWR);
2744                 if (ret)
2745                         goto out_cleanup;
2746         }
2747
2748         /* Write initial header.  This is merely a "dummy" header since it
2749          * doesn't have resource entries filled in yet, so it will be
2750          * overwritten later (unless writing a pipable WIM).  */
2751         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2752                 wim->out_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2753         ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2754         wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2755         if (ret)
2756                 goto out_cleanup;
2757
2758         /* Write file data and metadata resources.  */
2759         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2760                 /* Default case: create a normal (non-pipable) WIM.  */
2761                 ret = write_file_data(wim, image, write_flags,
2762                                       num_threads,
2763                                       blob_list_override,
2764                                       &blob_table_list);
2765                 if (ret)
2766                         goto out_cleanup;
2767
2768                 ret = write_metadata_resources(wim, image, write_flags);
2769                 if (ret)
2770                         goto out_cleanup;
2771         } else {
2772                 /* Non-default case: create pipable WIM.  */
2773                 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2774                                         blob_list_override,
2775                                         &blob_table_list);
2776                 if (ret)
2777                         goto out_cleanup;
2778         }
2779
2780         /* Write blob table, XML data, and (optional) integrity table.  */
2781         ret = finish_write(wim, image, write_flags, &blob_table_list);
2782 out_cleanup:
2783         (void)close_wim_writable(wim, write_flags);
2784         return ret;
2785 }
2786
2787 /* Write a standalone WIM to a file or file descriptor.  */
2788 static int
2789 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2790                      int image, int write_flags, unsigned num_threads)
2791 {
2792         return write_wim_part(wim, path_or_fd, image, write_flags,
2793                               num_threads, 1, 1, NULL, NULL);
2794 }
2795
2796 /* API function documented in wimlib.h  */
2797 WIMLIBAPI int
2798 wimlib_write(WIMStruct *wim, const tchar *path,
2799              int image, int write_flags, unsigned num_threads)
2800 {
2801         if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2802                 return WIMLIB_ERR_INVALID_PARAM;
2803
2804         if (path == NULL || path[0] == T('\0'))
2805                 return WIMLIB_ERR_INVALID_PARAM;
2806
2807         return write_standalone_wim(wim, path, image, write_flags, num_threads);
2808 }
2809
2810 /* API function documented in wimlib.h  */
2811 WIMLIBAPI int
2812 wimlib_write_to_fd(WIMStruct *wim, int fd,
2813                    int image, int write_flags, unsigned num_threads)
2814 {
2815         if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2816                 return WIMLIB_ERR_INVALID_PARAM;
2817
2818         if (fd < 0)
2819                 return WIMLIB_ERR_INVALID_PARAM;
2820
2821         write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2822
2823         return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2824 }
2825
2826 static bool
2827 any_images_modified(WIMStruct *wim)
2828 {
2829         for (int i = 0; i < wim->hdr.image_count; i++)
2830                 if (wim->image_metadata[i]->modified)
2831                         return true;
2832         return false;
2833 }
2834
2835 static int
2836 check_resource_offset(struct blob_descriptor *blob, void *_wim)
2837 {
2838         const WIMStruct *wim = _wim;
2839         off_t end_offset = *(const off_t*)wim->private;
2840
2841         if (blob->blob_location == BLOB_IN_WIM &&
2842             blob->rdesc->wim == wim &&
2843             blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
2844                 return WIMLIB_ERR_RESOURCE_ORDER;
2845         return 0;
2846 }
2847
2848 /* Make sure no file or metadata resources are located after the XML data (or
2849  * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2850  * place and we return WIMLIB_ERR_RESOURCE_ORDER.  */
2851 static int
2852 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2853 {
2854         int ret;
2855         unsigned i;
2856
2857         wim->private = &end_offset;
2858         ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
2859         if (ret)
2860                 return ret;
2861
2862         for (i = 0; i < wim->hdr.image_count; i++) {
2863                 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
2864                 if (ret)
2865                         return ret;
2866         }
2867         return 0;
2868 }
2869
2870 /*
2871  * Overwrite a WIM, possibly appending new resources to it.
2872  *
2873  * A WIM looks like (or is supposed to look like) the following:
2874  *
2875  *                   Header (212 bytes)
2876  *                   Resources for metadata and files (variable size)
2877  *                   Blob table (variable size)
2878  *                   XML data (variable size)
2879  *                   Integrity table (optional) (variable size)
2880  *
2881  * If we are not adding any new files or metadata, then the blob table is
2882  * unchanged--- so we only need to overwrite the XML data, integrity table, and
2883  * header.  This operation is potentially unsafe if the program is abruptly
2884  * terminated while the XML data or integrity table are being overwritten, but
2885  * before the new header has been written.  To partially alleviate this problem,
2886  * we write a temporary header after the XML data has been written.  This may
2887  * prevent the WIM from becoming corrupted if the program is terminated while
2888  * the integrity table is being calculated (but no guarantees, due to write
2889  * re-ordering...).
2890  *
2891  * If we are adding new blobs, including new file data as well as any metadata
2892  * for any new images, then the blob table needs to be changed, and those blobs
2893  * need to be written.  In this case, we try to perform a safe update of the WIM
2894  * file by writing the blobs *after* the end of the previous WIM, then writing
2895  * the new blob table, XML data, and (optionally) integrity table following the
2896  * new blobs.  This will produce a layout like the following:
2897  *
2898  *                   Header (212 bytes)
2899  *                   (OLD) Resources for metadata and files (variable size)
2900  *                   (OLD) Blob table (variable size)
2901  *                   (OLD) XML data (variable size)
2902  *                   (OLD) Integrity table (optional) (variable size)
2903  *                   (NEW) Resources for metadata and files (variable size)
2904  *                   (NEW) Blob table (variable size)
2905  *                   (NEW) XML data (variable size)
2906  *                   (NEW) Integrity table (optional) (variable size)
2907  *
2908  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2909  * the header is overwritten to point to the new blob table, XML data, and
2910  * integrity table, to produce the following layout:
2911  *
2912  *                   Header (212 bytes)
2913  *                   Resources for metadata and files (variable size)
2914  *                   Nothing (variable size)
2915  *                   Resources for metadata and files (variable size)
2916  *                   Blob table (variable size)
2917  *                   XML data (variable size)
2918  *                   Integrity table (optional) (variable size)
2919  *
2920  * This method allows an image to be appended to a large WIM very quickly, and
2921  * is crash-safe except in the case of write re-ordering, but the disadvantage
2922  * is that a small hole is left in the WIM where the old blob table, xml data,
2923  * and integrity table were.  (These usually only take up a small amount of
2924  * space compared to the blobs, however.)
2925  */
2926 static int
2927 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
2928 {
2929         int ret;
2930         off_t old_wim_end;
2931         u64 old_blob_table_end, old_xml_begin, old_xml_end;
2932         struct list_head blob_list;
2933         struct list_head blob_table_list;
2934         struct filter_context filter_ctx;
2935
2936         /* Include an integrity table by default if no preference was given and
2937          * the WIM already had an integrity table.  */
2938         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2939                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2940                 if (wim_has_integrity_table(wim))
2941                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2942
2943         /* Start preparing the updated file header.  */
2944         memcpy(&wim->out_hdr, &wim->hdr, sizeof(wim->out_hdr));
2945
2946         /* If using solid compression, the version number must be set to
2947          * WIM_VERSION_SOLID.  */
2948         if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2949                 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2950
2951         /* Default to solid compression if it is valid in the chosen WIM file
2952          * format and the WIMStruct references any solid resources.  This is
2953          * useful when updating a solid WIM.  */
2954         if (should_default_to_solid_compression(wim, write_flags))
2955                 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2956
2957         /* Set additional flags for overwrite.  */
2958         write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2959                        WIMLIB_WRITE_FLAG_STREAMS_OK;
2960
2961         /* Make sure there is no data after the XML data, except possibily an
2962          * integrity table.  If this were the case, then this data would be
2963          * overwritten.  */
2964         old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2965         old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2966         old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2967                              wim->hdr.blob_table_reshdr.size_in_wim;
2968         if (wim_has_integrity_table(wim) &&
2969             wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2970                 WARNING("Didn't expect the integrity table to be before the XML data");
2971                 ret = WIMLIB_ERR_RESOURCE_ORDER;
2972                 goto out;
2973         }
2974
2975         if (old_blob_table_end > old_xml_begin) {
2976                 WARNING("Didn't expect the blob table to be after the XML data");
2977                 ret = WIMLIB_ERR_RESOURCE_ORDER;
2978                 goto out;
2979         }
2980
2981         /* Set @old_wim_end, which indicates the point beyond which we don't
2982          * allow any file and metadata resources to appear without returning
2983          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2984          * overwrite these resources). */
2985         if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
2986                 /* If no images have been modified and no images have been
2987                  * deleted, a new blob table does not need to be written.  We
2988                  * shall write the new XML data and optional integrity table
2989                  * immediately after the blob table.  Note that this may
2990                  * overwrite an existing integrity table. */
2991                 old_wim_end = old_blob_table_end;
2992                 write_flags |= WIMLIB_WRITE_FLAG_NO_NEW_BLOBS;
2993         } else if (wim_has_integrity_table(wim)) {
2994                 /* Old WIM has an integrity table; begin writing new blobs after
2995                  * it. */
2996                 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2997                               wim->hdr.integrity_table_reshdr.size_in_wim;
2998         } else {
2999                 /* No existing integrity table; begin writing new blobs after
3000                  * the old XML data. */
3001                 old_wim_end = old_xml_end;
3002         }
3003
3004         ret = check_resource_offsets(wim, old_wim_end);
3005         if (ret)
3006                 goto out;
3007
3008         ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3009                                           &blob_list, &blob_table_list,
3010                                           &filter_ctx);
3011         if (ret)
3012                 goto out;
3013
3014         if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)
3015                 wimlib_assert(list_empty(&blob_list));
3016
3017         ret = open_wim_writable(wim, wim->filename, O_RDWR);
3018         if (ret)
3019                 goto out;
3020
3021         ret = lock_wim_for_append(wim);
3022         if (ret)
3023                 goto out_close_wim;
3024
3025         /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3026         wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3027         ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3028         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3029         if (ret) {
3030                 ERROR_WITH_ERRNO("Error updating WIM header flags");
3031                 goto out_unlock_wim;
3032         }
3033
3034         if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3035                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3036                 ret = WIMLIB_ERR_WRITE;
3037                 goto out_restore_hdr;
3038         }
3039
3040         ret = write_file_data_blobs(wim, &blob_list, write_flags,
3041                                     num_threads, &filter_ctx);
3042         if (ret)
3043                 goto out_truncate;
3044
3045         ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3046         if (ret)
3047                 goto out_truncate;
3048
3049         ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3050                            &blob_table_list);
3051         if (ret)
3052                 goto out_truncate;
3053
3054         unlock_wim_for_append(wim);
3055         return 0;
3056
3057 out_truncate:
3058         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
3059                 WARNING("Truncating \"%"TS"\" to its original size "
3060                         "(%"PRIu64" bytes)", wim->filename, old_wim_end);
3061                 /* Return value of ftruncate() is ignored because this is
3062                  * already an error path.  */
3063                 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3064         }
3065 out_restore_hdr:
3066         (void)write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3067 out_unlock_wim:
3068         unlock_wim_for_append(wim);
3069 out_close_wim:
3070         (void)close_wim_writable(wim, write_flags);
3071 out:
3072         return ret;
3073 }
3074
3075 static int
3076 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3077 {
3078         size_t wim_name_len;
3079         int ret;
3080
3081         /* Write the WIM to a temporary file in the same directory as the
3082          * original WIM. */
3083         wim_name_len = tstrlen(wim->filename);
3084         tchar tmpfile[wim_name_len + 10];
3085         tmemcpy(tmpfile, wim->filename, wim_name_len);
3086         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3087         tmpfile[wim_name_len + 9] = T('\0');
3088
3089         ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3090                            write_flags |
3091                                 WIMLIB_WRITE_FLAG_FSYNC |
3092                                 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3093                            num_threads);
3094         if (ret) {
3095                 tunlink(tmpfile);
3096                 return ret;
3097         }
3098
3099         if (filedes_valid(&wim->in_fd)) {
3100                 filedes_close(&wim->in_fd);
3101                 filedes_invalidate(&wim->in_fd);
3102         }
3103
3104         /* Rename the new WIM file to the original WIM file.  Note: on Windows
3105          * this actually calls win32_rename_replacement(), not _wrename(), so
3106          * that removing the existing destination file can be handled.  */
3107         ret = trename(tmpfile, wim->filename);
3108         if (ret) {
3109                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3110                                  tmpfile, wim->filename);
3111         #ifdef __WIN32__
3112                 if (ret < 0)
3113         #endif
3114                 {
3115                         tunlink(tmpfile);
3116                 }
3117                 return WIMLIB_ERR_RENAME;
3118         }
3119
3120         union wimlib_progress_info progress;
3121         progress.rename.from = tmpfile;
3122         progress.rename.to = wim->filename;
3123         return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3124                              &progress, wim->progctx);
3125 }
3126
3127 /* Determine if the specified WIM file may be updated by appending in-place
3128  * rather than writing and replacing it with an entirely new file.  */
3129 static bool
3130 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3131 {
3132         /* REBUILD flag forces full rebuild.  */
3133         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3134                 return false;
3135
3136         /* Image deletions cause full rebuild by default.  */
3137         if (wim->image_deletion_occurred &&
3138             !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3139                 return false;
3140
3141         /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3142          * turned into a pipable WIM in-place.  */
3143         if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3144                 return false;
3145
3146         /* The default compression type and compression chunk size selected for
3147          * the output WIM must be the same as those currently used for the WIM.
3148          */
3149         if (wim->compression_type != wim->out_compression_type)
3150                 return false;
3151         if (wim->chunk_size != wim->out_chunk_size)
3152                 return false;
3153
3154         return true;
3155 }
3156
3157 /* API function documented in wimlib.h  */
3158 WIMLIBAPI int
3159 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3160 {
3161         int ret;
3162         u32 orig_hdr_flags;
3163
3164         if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3165                 return WIMLIB_ERR_INVALID_PARAM;
3166
3167         if (!wim->filename)
3168                 return WIMLIB_ERR_NO_FILENAME;
3169
3170         orig_hdr_flags = wim->hdr.flags;
3171         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3172                 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3173         ret = can_modify_wim(wim);
3174         wim->hdr.flags = orig_hdr_flags;
3175         if (ret)
3176                 return ret;
3177
3178         if (can_overwrite_wim_inplace(wim, write_flags)) {
3179                 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3180                 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3181                         return ret;
3182                 WARNING("Falling back to re-building entire WIM");
3183         }
3184         return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);
3185 }