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