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