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