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