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