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