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