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