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