4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
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
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
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/.
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>
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"
56 # include "wimlib/win32.h" /* win32_rename_replacement() */
58 #include "wimlib/write.h"
59 #include "wimlib/xml.h"
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
70 write_flags_to_resource_flags(int write_flags)
72 int write_resource_flags = 0;
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;
89 struct filter_context {
95 * Determine whether the specified blob should be filtered out from the write.
99 * < 0 : The blob should be hard-filtered; that is, not included in the output
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.
106 blob_filtered(const struct blob_descriptor *blob,
107 const struct filter_context *ctx)
115 write_flags = ctx->write_flags;
118 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
119 blob->blob_location == BLOB_IN_WIM &&
120 blob->rdesc->wim == wim)
123 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
124 blob->blob_location == BLOB_IN_WIM &&
125 blob->rdesc->wim != wim)
132 blob_hard_filtered(const struct blob_descriptor *blob,
133 struct filter_context *ctx)
135 return blob_filtered(blob, ctx) < 0;
139 may_soft_filter_blobs(const struct filter_context *ctx)
143 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
147 may_hard_filter_blobs(const struct filter_context *ctx)
151 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
155 may_filter_blobs(const struct filter_context *ctx)
157 return (may_soft_filter_blobs(ctx) || may_hard_filter_blobs(ctx));
160 /* Return true if the specified resource is compressed and the compressed data
161 * can be reused with the specified output parameters. */
163 can_raw_copy(const struct blob_descriptor *blob,
164 int write_resource_flags, int out_ctype, u32 out_chunk_size)
166 const struct wim_resource_descriptor *rdesc;
168 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
171 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
174 if (blob->blob_location != BLOB_IN_WIM)
179 if (rdesc->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
182 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
183 /* Normal compressed resource: Must use same compression type
185 return (rdesc->compression_type == out_ctype &&
186 rdesc->chunk_size == out_chunk_size);
189 if ((rdesc->flags & WIM_RESHDR_FLAG_SOLID) &&
190 (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
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. */
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. */
202 struct blob_descriptor *res_blob;
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;
209 return (write_size > rdesc->uncompressed_size * 2 / 3);
216 reshdr_flags_for_blob(const struct blob_descriptor *blob)
218 u32 reshdr_flags = 0;
219 if (blob->is_metadata)
220 reshdr_flags |= WIM_RESHDR_FLAG_METADATA;
225 blob_set_out_reshdr_for_reuse(struct blob_descriptor *blob)
227 const struct wim_resource_descriptor *rdesc;
229 wimlib_assert(blob->blob_location == BLOB_IN_WIM);
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;
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;
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;
245 blob->out_reshdr.flags = rdesc->flags;
249 /* Write the header for a blob in a pipable WIM. */
251 write_pwm_blob_header(const struct blob_descriptor *blob,
252 struct filedes *out_fd, bool compressed)
254 struct pwm_blob_hdr blob_hdr;
258 wimlib_assert(!blob->unhashed);
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);
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));
269 ERROR_WITH_ERRNO("Write error");
273 struct write_blobs_progress_data {
274 wimlib_progress_func_t progfunc;
276 union wimlib_progress_info progress;
277 uint64_t next_progress;
281 do_write_blobs_progress(struct write_blobs_progress_data *progress_data,
282 u64 complete_size, u32 complete_count, bool discarded)
284 union wimlib_progress_info *progress = &progress_data->progress;
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)
293 progress_data->next_progress = progress->write_streams.total_bytes;
296 progress->write_streams.completed_bytes += complete_size;
297 progress->write_streams.completed_streams += complete_count;
300 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
302 ret = call_progress(progress_data->progfunc,
303 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
305 progress_data->progctx);
309 if (progress_data->next_progress == progress->write_streams.total_bytes) {
310 progress_data->next_progress = ~(uint64_t)0;
312 /* Handle rate-limiting of messages */
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;
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;
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;
339 struct write_blobs_ctx {
340 /* File descriptor to which the blobs are being written. */
341 struct filedes *out_fd;
343 /* Blob table for the WIMStruct on whose behalf the blobs are being
345 struct blob_table *blob_table;
347 /* Compression format to use. */
350 /* Maximum uncompressed chunk size in compressed resources to use. */
353 /* Flags that affect how the blobs will be written. */
354 int write_resource_flags;
356 /* Data used for issuing WRITE_STREAMS progress. */
357 struct write_blobs_progress_data progress_data;
359 struct filter_context *filter_ctx;
361 /* Upper bound on the total number of bytes that need to be compressed.
363 u64 num_bytes_to_compress;
365 /* Pointer to the chunk_compressor implementation being used for
366 * compressing chunks of data, or NULL if chunks are being written
368 struct chunk_compressor *compressor;
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. */
375 /* Number of bytes in @cur_chunk_buf that are currently filled. */
376 size_t cur_chunk_buf_filled;
378 /* List of blobs that currently have chunks being compressed. */
379 struct list_head blobs_being_compressed;
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;
385 /* Current uncompressed offset in the blob being read. */
386 u64 cur_read_blob_offset;
388 /* Uncompressed size of the blob currently being read. */
389 u64 cur_read_blob_size;
391 /* Current uncompressed offset in the blob being written. */
392 u64 cur_write_blob_offset;
394 /* Uncompressed size of resource currently being written. */
395 u64 cur_write_res_size;
397 /* Array that is filled in with compressed chunk sizes as a resource is
401 /* Index of next entry in @chunk_csizes to fill in. */
404 /* Number of entries in @chunk_csizes currently allocated. */
405 size_t num_alloc_chunks;
407 /* Offset in the output file of the start of the chunks of the resource
408 * currently being written. */
409 u64 chunks_start_offset;
412 /* Reserve space for the chunk table and prepare to accumulate the chunk table
415 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
417 u64 expected_num_chunks;
418 u64 expected_num_chunk_entries;
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--;
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;
437 if ((size_t)new_length != new_length) {
438 ERROR("Resource size too large (%"PRIu64" bytes!",
440 return WIMLIB_ERR_NOMEM;
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;
449 ctx->num_alloc_chunks = new_length;
452 ctx->chunk_index = 0;
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
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);
476 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
480 wimlib_assert(res_expected_size != 0);
482 if (ctx->compressor != NULL) {
483 ret = begin_chunk_table(ctx, res_expected_size);
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;
497 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
498 u64 *res_start_offset_ret, u64 *res_store_size_ret)
500 size_t actual_num_chunks;
501 size_t actual_num_chunk_entries;
502 size_t chunk_entry_size;
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--;
510 chunk_entry_size = get_chunk_entry_size(res_actual_size,
511 0 != (ctx->write_resource_flags &
512 WRITE_RESOURCE_FLAG_SOLID));
514 typedef le64 _may_alias_attribute aliased_le64_t;
515 typedef le32 _may_alias_attribute aliased_le32_t;
517 if (chunk_entry_size == 4) {
518 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
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]);
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);
532 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
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]);
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);
547 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
548 u64 res_start_offset;
551 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
552 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
555 res_end_offset = ctx->out_fd->offset;
556 res_start_offset = ctx->chunks_start_offset;
558 res_end_offset = ctx->out_fd->offset;
560 u64 chunk_table_offset;
562 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
564 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
565 struct alt_chunk_table_header_disk hdr;
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);
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);
575 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
576 chunk_table_offset - sizeof(hdr));
579 res_start_offset = chunk_table_offset - sizeof(hdr);
581 res_start_offset = chunk_table_offset;
584 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
585 chunk_table_size, chunk_table_offset);
590 *res_start_offset_ret = res_start_offset;
591 *res_store_size_ret = res_end_offset - res_start_offset;
596 ERROR_WITH_ERRNO("Write error");
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. */
603 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
607 u64 res_uncompressed_size;
608 u64 res_offset_in_wim;
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;
614 if (ctx->compressor) {
615 ret = end_chunk_table(ctx, res_uncompressed_size,
616 &res_offset_in_wim, &res_size_in_wim);
620 res_offset_in_wim = ctx->chunks_start_offset;
621 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
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);
631 /* Call when no more data from the file at @path is needed. */
633 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
635 union wimlib_progress_info info;
637 info.done_with_file.path_to_file = path;
639 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
644 do_done_with_blob(struct blob_descriptor *blob,
645 wimlib_progress_func_t progfunc, void *progctx)
648 struct wim_inode *inode;
650 if (!blob->may_send_done_with_file)
653 inode = blob->file_inode;
655 wimlib_assert(inode != NULL);
656 wimlib_assert(inode->num_remaining_streams > 0);
657 if (--inode->num_remaining_streams > 0)
661 /* XXX: This logic really should be somewhere else. */
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;
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':');
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'\\';
684 ret = done_with_file(blob->file_on_disk, progfunc, progctx);
690 *p_question_mark = L'?';
695 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
697 done_with_blob(struct blob_descriptor *blob, struct write_blobs_ctx *ctx)
699 if (likely(!(ctx->write_resource_flags &
700 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
702 return do_done_with_blob(blob, ctx->progress_data.progfunc,
703 ctx->progress_data.progctx);
706 /* Begin processing a blob for writing. */
708 write_blob_begin_read(struct blob_descriptor *blob, void *_ctx)
710 struct write_blobs_ctx *ctx = _ctx;
713 wimlib_assert(blob->size > 0);
715 ctx->cur_read_blob_offset = 0;
716 ctx->cur_read_blob_size = blob->size;
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) {
730 struct blob_descriptor *new_blob;
732 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
735 if (new_blob != blob) {
736 /* Duplicate blob detected. */
738 if (new_blob->will_be_in_output_wim ||
739 blob_filtered(new_blob, ctx->filter_ctx))
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;
758 ret = done_with_blob(blob, ctx);
759 free_blob_descriptor(blob);
762 return BEGIN_BLOB_STATUS_SKIP_BLOB;
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
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;
785 list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
789 /* Rewrite a blob that was just written compressed as uncompressed instead.
792 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
795 u64 begin_offset = blob->out_reshdr.offset_in_wim;
796 u64 end_offset = out_fd->offset;
798 if (filedes_seek(out_fd, begin_offset) == -1)
801 ret = extract_full_blob_to_fd(blob, out_fd);
803 /* Error reading the uncompressed data. */
804 if (out_fd->offset == begin_offset &&
805 filedes_seek(out_fd, end_offset) != -1)
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);
818 wimlib_assert(out_fd->offset - begin_offset == blob->size);
820 if (out_fd->offset < end_offset &&
821 0 != ftruncate(out_fd->fd, out_fd->offset))
823 ERROR_WITH_ERRNO("Can't truncate output file to "
824 "offset %"PRIu64, out_fd->offset);
825 return WIMLIB_ERR_WRITE;
828 blob->out_reshdr.size_in_wim = blob->size;
829 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
830 WIM_RESHDR_FLAG_SOLID);
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. */
838 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
839 const struct blob_descriptor *blob)
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)
846 /* If we're not actually writing compressed data, then there's no need
848 if (!ctx->compressor)
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)
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
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).
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
872 if (blob->blob_location == BLOB_IN_WIM &&
873 blob->size != blob->rdesc->uncompressed_size &&
874 blob->size != blob->out_reshdr.size_in_wim)
881 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
882 struct blob_descriptor *blob)
884 if (!should_rewrite_blob_uncompressed(ctx, blob))
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)
895 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
899 return write_blob_uncompressed(blob, ctx->out_fd);
902 /* Write the next chunk of (typically compressed) data to the output WIM,
903 * handling the writing of the chunk table. */
905 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
906 size_t csize, size_t usize)
909 struct blob_descriptor *blob;
910 u32 completed_blob_count;
913 blob = list_entry(ctx->blobs_being_compressed.next,
914 struct blob_descriptor, write_blobs_list);
916 if (ctx->cur_write_blob_offset == 0 &&
917 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
919 /* Starting to write a new blob in non-solid mode. */
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);
930 ret = begin_write_resource(ctx, blob->size);
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;
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),
946 ret = full_write(ctx->out_fd, &chunk_hdr,
953 /* Write the chunk data. */
954 ret = full_write(ctx->out_fd, cchunk, csize);
958 ctx->cur_write_blob_offset += usize;
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
965 struct blob_descriptor *next_blob;
967 while (blob && ctx->cur_write_blob_offset >= blob->size) {
969 ctx->cur_write_blob_offset -= blob->size;
971 if (ctx->cur_write_blob_offset)
972 next_blob = list_entry(blob->write_blobs_list.next,
973 struct blob_descriptor,
978 ret = done_with_blob(blob, ctx);
981 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
982 completed_blob_count++;
987 /* Wrote chunk in non-solid mode. It may have finished a
989 if (ctx->cur_write_blob_offset == blob->size) {
991 wimlib_assert(ctx->cur_write_blob_offset ==
992 ctx->cur_write_res_size);
994 ret = end_write_resource(ctx, &blob->out_reshdr);
998 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
999 if (ctx->compressor != NULL)
1000 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
1002 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
1006 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
1008 ctx->cur_write_blob_offset = 0;
1010 ret = done_with_blob(blob, ctx);
1013 list_del(&blob->write_blobs_list);
1014 completed_blob_count++;
1018 return do_write_blobs_progress(&ctx->progress_data, completed_size,
1019 completed_blob_count, false);
1022 ERROR_WITH_ERRNO("Write error");
1027 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
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)))
1040 bret = ctx->compressor->get_compression_result(ctx->compressor,
1044 wimlib_assert(bret);
1046 ret = write_chunk(ctx, cchunk, csize, usize);
1053 /* Process the next chunk of data to be written to a WIM resource. */
1055 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1057 struct write_blobs_ctx *ctx = _ctx;
1059 const u8 *chunkptr, *chunkend;
1061 wimlib_assert(size != 0);
1063 if (ctx->compressor == NULL) {
1064 /* Write chunk uncompressed. */
1065 ret = write_chunk(ctx, chunk, size, size);
1068 ctx->cur_read_blob_offset += size;
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. */
1076 chunkend = chunkptr + size;
1078 size_t needed_chunk_size;
1079 size_t bytes_consumed;
1081 if (!ctx->cur_chunk_buf) {
1082 ret = prepare_chunk_buffer(ctx);
1087 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1088 needed_chunk_size = ctx->out_chunk_size;
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));
1096 bytes_consumed = min(chunkend - chunkptr,
1097 needed_chunk_size - ctx->cur_chunk_buf_filled);
1099 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1100 chunkptr, bytes_consumed);
1102 chunkptr += bytes_consumed;
1103 ctx->cur_read_blob_offset += bytes_consumed;
1104 ctx->cur_chunk_buf_filled += bytes_consumed;
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;
1112 } while (chunkptr != chunkend);
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. */
1120 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1122 struct write_blobs_ctx *ctx = _ctx;
1124 wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
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
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. */
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);
1151 /* Compute statistics about a list of blobs that will be written.
1153 * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1154 * (specified by WIMStruct) are together. */
1156 compute_blob_list_stats(struct list_head *blob_list,
1157 struct write_blobs_ctx *ctx)
1159 struct blob_descriptor *blob;
1160 u64 total_bytes = 0;
1162 u64 total_parts = 0;
1163 WIMStruct *prev_wim_part = NULL;
1165 list_for_each_entry(blob, blob_list, write_blobs_list) {
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;
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;
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. */
1190 find_raw_copy_blobs(struct list_head *blob_list,
1191 int write_resource_flags,
1194 struct list_head *raw_copy_blobs)
1196 struct blob_descriptor *blob, *tmp;
1197 u64 num_bytes_to_compress = 0;
1199 INIT_LIST_HEAD(raw_copy_blobs);
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;
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)
1210 list_move_tail(&blob->write_blobs_list,
1212 } else if (can_raw_copy(blob, write_resource_flags,
1213 out_ctype, out_chunk_size))
1215 blob->rdesc->raw_copy_ok = 1;
1216 list_move_tail(&blob->write_blobs_list,
1219 num_bytes_to_compress += blob->size;
1223 return num_bytes_to_compress;
1226 /* Copy a raw compressed resource located in another WIM file to the WIM file
1229 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1230 struct filedes *out_fd)
1232 u64 cur_read_offset;
1233 u64 end_read_offset;
1234 u8 buf[BUFFER_SIZE];
1235 size_t bytes_to_read;
1237 struct filedes *in_fd;
1238 struct blob_descriptor *blob;
1239 u64 out_offset_in_wim;
1241 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1242 "uncompressed_size=%"PRIu64")",
1243 in_rdesc->size_in_wim, in_rdesc->uncompressed_size);
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;
1249 out_offset_in_wim = out_fd->offset;
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);
1257 in_fd = &in_rdesc->wim->in_fd;
1258 wimlib_assert(cur_read_offset != end_read_offset);
1261 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1263 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1267 ret = full_write(out_fd, buf, bytes_to_read);
1271 cur_read_offset += bytes_to_read;
1273 } while (cur_read_offset != end_read_offset);
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;
1281 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1288 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1289 * WIM file being written. */
1291 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1292 struct filedes *out_fd,
1293 struct write_blobs_progress_data *progress_data)
1295 struct blob_descriptor *blob;
1298 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1299 blob->rdesc->raw_copy_ok = 1;
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);
1307 blob->rdesc->raw_copy_ok = 0;
1309 ret = do_write_blobs_progress(progress_data, blob->size,
1317 /* Wait for and write all chunks pending in the compressor. */
1319 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1326 if (ctx->compressor == NULL)
1329 if (ctx->cur_chunk_buf_filled != 0) {
1330 ctx->compressor->signal_chunk_filled(ctx->compressor,
1331 ctx->cur_chunk_buf_filled);
1334 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1337 ret = write_chunk(ctx, cdata, csize, usize);
1345 remove_empty_blobs(struct list_head *blob_list)
1347 struct blob_descriptor *blob, *tmp;
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);
1362 blob_is_in_file(const struct blob_descriptor *blob)
1364 return blob->blob_location == BLOB_IN_FILE_ON_DISK
1366 || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1367 || blob->blob_location == BLOB_WIN32_ENCRYPTED
1373 init_done_with_file_info(struct list_head *blob_list)
1375 struct blob_descriptor *blob;
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;
1382 blob->may_send_done_with_file = 0;
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++;
1392 * Write a list of blobs to the output WIM file.
1395 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1396 * by the 'write_blobs_list' member.
1399 * The file descriptor, opened for writing, to which to write the blobs.
1401 * @write_resource_flags
1402 * Flags to modify how the blobs are written:
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.
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).
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.
1421 * Compression format to use in the output resources, specified as one of
1422 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
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
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.
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.
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.
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.
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.
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.
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.
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.
1495 write_blob_list(struct list_head *blob_list,
1496 struct filedes *out_fd,
1497 int write_resource_flags,
1500 unsigned num_threads,
1501 struct blob_table *blob_table,
1502 struct filter_context *filter_ctx,
1503 wimlib_progress_func_t progfunc,
1507 struct write_blobs_ctx ctx;
1508 struct list_head raw_copy_blobs;
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));
1516 remove_empty_blobs(blob_list);
1518 if (list_empty(blob_list)) {
1519 DEBUG("No blobs to write.");
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);
1528 memset(&ctx, 0, sizeof(ctx));
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;
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.
1550 ret = sort_blob_list_by_sequential_order(blob_list,
1551 offsetof(struct blob_descriptor,
1556 compute_blob_list_stats(blob_list, &ctx);
1558 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1559 ret = sort_blob_list_for_solid_compression(blob_list);
1561 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1564 ctx.progress_data.progfunc = progfunc;
1565 ctx.progress_data.progctx = progctx;
1567 ctx.num_bytes_to_compress = find_raw_copy_blobs(blob_list,
1568 write_resource_flags,
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);
1582 if (ctx.num_bytes_to_compress == 0) {
1583 DEBUG("No compression needed; skipping to raw copy!");
1584 goto out_write_raw_copy_resources;
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) {
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,
1601 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1602 " Falling back to single-threaded compression.",
1603 wimlib_get_error_string(ret));
1608 if (ctx.compressor == NULL) {
1609 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1612 goto out_destroy_context;
1617 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1619 ctx.progress_data.progress.write_streams.num_threads = 1;
1621 DEBUG("Actually using %u threads",
1622 ctx.progress_data.progress.write_streams.num_threads);
1624 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1625 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1627 ret = call_progress(ctx.progress_data.progfunc,
1628 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1629 &ctx.progress_data.progress,
1630 ctx.progress_data.progctx);
1632 goto out_destroy_context;
1634 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1635 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1637 goto out_destroy_context;
1640 /* Read the list of blobs needing to be compressed, using the specified
1641 * callbacks to execute processing of the data. */
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,
1652 ret = read_blob_list(blob_list,
1653 offsetof(struct blob_descriptor, write_blobs_list),
1655 BLOB_LIST_ALREADY_SORTED |
1656 VERIFY_BLOB_HASHES |
1657 COMPUTE_MISSING_BLOB_HASHES);
1660 goto out_destroy_context;
1662 ret = finish_remaining_chunks(&ctx);
1664 goto out_destroy_context;
1666 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1667 struct wim_reshdr reshdr;
1668 struct blob_descriptor *blob;
1671 ret = end_write_resource(&ctx, &reshdr);
1673 goto out_destroy_context;
1675 DEBUG("Ending solid resource: %lu %lu %lu.",
1676 reshdr.offset_in_wim,
1678 reshdr.uncompressed_size);
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;
1692 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
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);
1701 out_destroy_context:
1702 FREE(ctx.chunk_csizes);
1704 ctx.compressor->destroy(ctx.compressor);
1705 DEBUG("Done (ret=%d)", ret);
1711 wim_write_blob_list(WIMStruct *wim,
1712 struct list_head *blob_list,
1714 unsigned num_threads,
1715 struct filter_context *filter_ctx)
1719 int write_resource_flags;
1721 write_resource_flags = write_flags_to_resource_flags(write_flags);
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))
1730 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
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;
1737 out_chunk_size = wim->out_chunk_size;
1738 out_ctype = wim->out_compression_type;
1741 return write_blob_list(blob_list,
1743 write_resource_flags,
1753 /* Write the contents of the specified blob as a WIM resource. */
1755 write_wim_resource(struct blob_descriptor *blob,
1756 struct filedes *out_fd,
1759 int write_resource_flags)
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,
1766 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1776 /* Write the contents of the specified buffer as a WIM resource. */
1778 write_wim_resource_from_buffer(const void *buf,
1781 struct filedes *out_fd,
1784 struct wim_reshdr *out_reshdr,
1786 int write_resource_flags)
1789 struct blob_descriptor blob;
1791 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1792 sha1_buffer(buf, buf_size, blob.hash);
1794 blob.is_metadata = is_metadata;
1796 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1797 write_resource_flags);
1801 copy_reshdr(out_reshdr, &blob.out_reshdr);
1804 copy_hash(hash_ret, blob.hash);
1808 struct blob_size_table {
1809 struct hlist_head *array;
1815 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
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;
1826 destroy_blob_size_table(struct blob_size_table *tab)
1832 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1834 struct blob_size_table *tab = _tab;
1836 struct blob_descriptor *same_size_blob;
1837 struct hlist_node *tmp;
1839 pos = hash_u64(blob->size) % tab->capacity;
1840 blob->unique_size = 1;
1841 hlist_for_each_entry(same_size_blob, tmp, &tab->array[pos], hash_list_2) {
1842 if (same_size_blob->size == blob->size) {
1843 blob->unique_size = 0;
1844 same_size_blob->unique_size = 0;
1849 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1854 struct find_blobs_ctx {
1857 struct list_head blob_list;
1858 struct blob_size_table blob_size_tab;
1862 reference_blob_for_write(struct blob_descriptor *blob,
1863 struct list_head *blob_list, u32 nref)
1865 if (!blob->will_be_in_output_wim) {
1866 blob->out_refcnt = 0;
1867 list_add_tail(&blob->write_blobs_list, blob_list);
1868 blob->will_be_in_output_wim = 1;
1870 blob->out_refcnt += nref;
1874 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1876 struct list_head *blob_list = _blob_list;
1877 blob->will_be_in_output_wim = 0;
1878 reference_blob_for_write(blob, blob_list, blob->refcnt);
1883 inode_find_blobs_to_reference(const struct wim_inode *inode,
1884 const struct blob_table *table,
1885 struct list_head *blob_list)
1887 wimlib_assert(inode->i_nlink > 0);
1889 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1890 struct blob_descriptor *blob;
1892 blob = stream_blob(&inode->i_streams[i], table);
1894 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1895 else if (!is_zero_hash(stream_hash(&inode->i_streams[i])))
1896 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1902 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1904 blob->will_be_in_output_wim = 0;
1909 image_find_blobs_to_reference(WIMStruct *wim)
1911 struct wim_image_metadata *imd;
1912 struct wim_inode *inode;
1913 struct blob_descriptor *blob;
1914 struct list_head *blob_list;
1917 imd = wim_get_current_image_metadata(wim);
1919 image_for_each_unhashed_blob(blob, imd)
1920 blob->will_be_in_output_wim = 0;
1922 blob_list = wim->private;
1923 image_for_each_inode(inode, imd) {
1924 ret = inode_find_blobs_to_reference(inode,
1934 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1937 struct list_head *blob_list_ret)
1941 INIT_LIST_HEAD(blob_list_ret);
1943 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1944 (image == 1 && wim->hdr.image_count == 1)))
1946 /* Fast case: Assume that all blobs are being written and that
1947 * the reference counts are correct. */
1948 struct blob_descriptor *blob;
1949 struct wim_image_metadata *imd;
1952 for_blob_in_table(wim->blob_table,
1953 fully_reference_blob_for_write,
1956 for (i = 0; i < wim->hdr.image_count; i++) {
1957 imd = wim->image_metadata[i];
1958 image_for_each_unhashed_blob(blob, imd)
1959 fully_reference_blob_for_write(blob, blob_list_ret);
1962 /* Slow case: Walk through the images being written and
1963 * determine the blobs referenced. */
1964 for_blob_in_table(wim->blob_table,
1965 do_blob_set_not_in_output_wim, NULL);
1966 wim->private = blob_list_ret;
1967 ret = for_image(wim, image, image_find_blobs_to_reference);
1975 struct insert_other_if_hard_filtered_ctx {
1976 struct blob_size_table *tab;
1977 struct filter_context *filter_ctx;
1981 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1983 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1985 if (!blob->will_be_in_output_wim &&
1986 blob_hard_filtered(blob, ctx->filter_ctx))
1987 blob_size_table_insert(blob, ctx->tab);
1992 determine_blob_size_uniquity(struct list_head *blob_list,
1993 struct blob_table *lt,
1994 struct filter_context *filter_ctx)
1997 struct blob_size_table tab;
1998 struct blob_descriptor *blob;
2000 ret = init_blob_size_table(&tab, 9001);
2004 if (may_hard_filter_blobs(filter_ctx)) {
2005 struct insert_other_if_hard_filtered_ctx ctx = {
2007 .filter_ctx = filter_ctx,
2009 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
2012 list_for_each_entry(blob, blob_list, write_blobs_list)
2013 blob_size_table_insert(blob, &tab);
2015 destroy_blob_size_table(&tab);
2020 filter_blob_list_for_write(struct list_head *blob_list,
2021 struct filter_context *filter_ctx)
2023 struct blob_descriptor *blob, *tmp;
2025 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
2026 int status = blob_filtered(blob, filter_ctx);
2033 /* Soft filtered. */
2035 /* Hard filtered. */
2036 blob->will_be_in_output_wim = 0;
2037 list_del(&blob->blob_table_list);
2039 list_del(&blob->write_blobs_list);
2045 * prepare_blob_list_for_write() -
2047 * Prepare the list of blobs to write for writing a WIM containing the specified
2048 * image(s) with the specified write flags.
2051 * The WIMStruct on whose behalf the write is occurring.
2054 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2057 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2059 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
2060 * table of @wim and the per-image lists of unhashed blobs should be taken
2061 * as-is, and image metadata should not be searched for references. This
2062 * does not exclude filtering with OVERWRITE and SKIP_EXTERNAL_WIMS, below.
2064 * OVERWRITE: Blobs already present in @wim shall not be returned in
2067 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
2068 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
2071 * List of blobs, linked by write_blobs_list, that need to be written will
2074 * Note that this function assumes that unhashed blobs will be written; it
2075 * does not take into account that they may become duplicates when actually
2078 * @blob_table_list_ret
2079 * List of blobs, linked by blob_table_list, that need to be included in
2080 * the WIM's blob table will be returned here. This will be a superset of
2081 * the blobs in @blob_list_ret.
2083 * This list will be a proper superset of @blob_list_ret if and only if
2084 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2085 * the blobs that would otherwise need to be written were already located
2088 * All blobs in this list will have @out_refcnt set to the number of
2089 * references to the blob in the output WIM. If
2090 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2091 * may be as low as 0.
2094 * A context for queries of blob filter status with blob_filtered() is
2095 * returned in this location.
2097 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2098 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2099 * inserted into @blob_table_list_ret.
2101 * Still furthermore, @unique_size will be set to 1 on all blobs in
2102 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2103 * among all blobs in the blob table of @wim that are ineligible for being
2104 * written due to filtering.
2106 * Returns 0 on success; nonzero on read error, memory allocation error, or
2110 prepare_blob_list_for_write(WIMStruct *wim, int image,
2112 struct list_head *blob_list_ret,
2113 struct list_head *blob_table_list_ret,
2114 struct filter_context *filter_ctx_ret)
2117 struct blob_descriptor *blob;
2119 filter_ctx_ret->write_flags = write_flags;
2120 filter_ctx_ret->wim = wim;
2122 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2125 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2130 INIT_LIST_HEAD(blob_table_list_ret);
2131 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2132 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2134 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2139 if (may_filter_blobs(filter_ctx_ret))
2140 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2146 write_file_blobs(WIMStruct *wim, int image, int write_flags,
2147 unsigned num_threads,
2148 struct list_head *blob_list_override,
2149 struct list_head *blob_table_list_ret)
2152 struct list_head _blob_list;
2153 struct list_head *blob_list;
2154 struct blob_descriptor *blob;
2155 struct filter_context _filter_ctx;
2156 struct filter_context *filter_ctx;
2158 if (blob_list_override == NULL) {
2159 /* Normal case: prepare blob list from image(s) being written.
2161 blob_list = &_blob_list;
2162 filter_ctx = &_filter_ctx;
2163 ret = prepare_blob_list_for_write(wim, image, write_flags,
2165 blob_table_list_ret,
2170 /* Currently only as a result of wimlib_split() being called:
2171 * use blob list already explicitly provided. Use existing
2172 * reference counts. */
2173 blob_list = blob_list_override;
2175 INIT_LIST_HEAD(blob_table_list_ret);
2176 list_for_each_entry(blob, blob_list, write_blobs_list) {
2177 blob->out_refcnt = blob->refcnt;
2178 blob->will_be_in_output_wim = 1;
2179 blob->unique_size = 0;
2180 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2184 return wim_write_blob_list(wim,
2192 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2197 int write_resource_flags;
2199 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2200 DEBUG("Not writing any metadata resources.");
2204 write_resource_flags = write_flags_to_resource_flags(write_flags);
2206 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2208 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2209 wim->out_fd.offset);
2211 ret = call_progress(wim->progfunc,
2212 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2213 NULL, wim->progctx);
2217 if (image == WIMLIB_ALL_IMAGES) {
2219 end_image = wim->hdr.image_count;
2221 start_image = image;
2225 for (int i = start_image; i <= end_image; i++) {
2226 struct wim_image_metadata *imd;
2228 imd = wim->image_metadata[i - 1];
2229 /* Build a new metadata resource only if image was modified from
2230 * the original (or was newly added). Otherwise just copy the
2232 if (imd->modified) {
2233 DEBUG("Image %u was modified; building and writing new "
2234 "metadata resource", i);
2235 ret = write_metadata_resource(wim, i,
2236 write_resource_flags);
2237 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2238 DEBUG("Image %u was not modified; re-using existing "
2239 "metadata resource.", i);
2240 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2243 DEBUG("Image %u was not modified; copying existing "
2244 "metadata resource.", i);
2245 ret = write_wim_resource(imd->metadata_blob,
2247 wim->out_compression_type,
2248 wim->out_chunk_size,
2249 write_resource_flags);
2255 return call_progress(wim->progfunc,
2256 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2257 NULL, wim->progctx);
2261 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2264 DEBUG("Opening \"%"TS"\" for writing.", path);
2266 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2268 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2269 return WIMLIB_ERR_OPEN;
2271 filedes_init(&wim->out_fd, raw_fd);
2276 close_wim_writable(WIMStruct *wim, int write_flags)
2280 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2281 DEBUG("Closing WIM file.");
2282 if (filedes_valid(&wim->out_fd))
2283 if (filedes_close(&wim->out_fd))
2284 ret = WIMLIB_ERR_WRITE;
2286 filedes_invalidate(&wim->out_fd);
2291 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2293 const struct blob_descriptor *blob1, *blob2;
2295 blob1 = *(const struct blob_descriptor**)p1;
2296 blob2 = *(const struct blob_descriptor**)p2;
2298 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2299 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2300 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2301 return cmp_u64(blob1->out_res_offset_in_wim,
2302 blob2->out_res_offset_in_wim);
2307 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2310 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2311 blob2->out_reshdr.offset_in_wim);
2315 write_blob_table(WIMStruct *wim, int image, int write_flags,
2316 struct wim_reshdr *out_reshdr,
2317 struct list_head *blob_table_list)
2321 /* Set output resource metadata for blobs already present in WIM. */
2322 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2323 struct blob_descriptor *blob;
2324 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2325 if (blob->blob_location == BLOB_IN_WIM &&
2326 blob->rdesc->wim == wim)
2328 blob_set_out_reshdr_for_reuse(blob);
2333 ret = sort_blob_list(blob_table_list,
2334 offsetof(struct blob_descriptor, blob_table_list),
2335 cmp_blobs_by_out_rdesc);
2339 /* Add entries for metadata resources. */
2340 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2344 if (image == WIMLIB_ALL_IMAGES) {
2346 end_image = wim->hdr.image_count;
2348 start_image = image;
2352 /* Push metadata blob table entries onto the front of the list
2353 * in reverse order, so that they're written in order.
2355 for (int i = end_image; i >= start_image; i--) {
2356 struct blob_descriptor *metadata_blob;
2358 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2359 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2360 metadata_blob->out_refcnt = 1;
2361 list_add(&metadata_blob->blob_table_list, blob_table_list);
2365 return write_blob_table_from_blob_list(blob_table_list,
2367 wim->hdr.part_number,
2369 write_flags_to_resource_flags(write_flags));
2375 * Finish writing a WIM file: write the blob table, xml data, and integrity
2376 * table, then overwrite the WIM header. By default, closes the WIM file
2377 * descriptor (@wim->out_fd) if successful.
2379 * write_flags is a bitwise OR of the following:
2381 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2382 * Include an integrity table.
2384 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2385 * fsync() the output file before closing it.
2387 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2388 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2389 * blob headers before the blob table and XML data, and also write
2390 * the WIM header at the end instead of seeking to the beginning.
2391 * Can't be combined with WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2393 * (private) WIMLIB_WRITE_FLAG_NO_BLOB_TABLE:
2394 * Don't write the blob table.
2396 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2397 * After writing the XML data but before writing the integrity
2398 * table, write a temporary WIM header and flush the file
2399 * descriptor so that the WIM is less likely to become corrupted
2400 * upon abrupt program termination.
2401 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2402 * Instead of overwriting the WIM header at the beginning of the
2403 * file, simply append it to the end of the file. (Used when
2405 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2406 * Do not close the file descriptor @wim->out_fd on either success
2408 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2409 * Use the existing <TOTALBYTES> stored in the in-memory XML
2410 * information, rather than setting it to the offset of the XML
2411 * data being written.
2412 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2413 * The existing WIM file is being updated in-place. The entries
2414 * from its integrity table may be re-used.
2417 finish_write(WIMStruct *wim, int image, int write_flags,
2418 struct list_head *blob_table_list)
2422 int write_resource_flags;
2423 off_t old_blob_table_end = 0;
2424 off_t new_blob_table_end;
2426 struct integrity_table *old_integrity_table = NULL;
2428 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2430 write_resource_flags = write_flags_to_resource_flags(write_flags);
2432 /* In the WIM header, there is room for the resource entry for a
2433 * metadata resource labeled as the "boot metadata". This entry should
2434 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2435 * it should be a copy of the resource entry for the image that is
2436 * marked as bootable. This is not well documented... */
2437 if (wim->hdr.boot_idx == 0) {
2438 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2440 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2441 &wim->image_metadata[
2442 wim->hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2445 /* If overwriting the WIM file containing an integrity table in-place,
2446 * we'd like to re-use the information in the old integrity table
2447 * instead of recalculating it. But we might overwrite the old
2448 * integrity table when we expand the XML data. Read it into memory
2450 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2451 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2452 (WIMLIB_WRITE_FLAG_OVERWRITE |
2453 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2454 && wim_has_integrity_table(wim))
2456 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2457 wim->hdr.blob_table_reshdr.size_in_wim;
2458 (void)read_integrity_table(wim,
2459 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2460 &old_integrity_table);
2461 /* If we couldn't read the old integrity table, we can still
2462 * re-calculate the full integrity table ourselves. Hence the
2463 * ignoring of the return value. */
2466 /* Write blob table. */
2467 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_BLOB_TABLE)) {
2468 ret = write_blob_table(wim, image, write_flags,
2469 &wim->hdr.blob_table_reshdr,
2472 free_integrity_table(old_integrity_table);
2477 /* Write XML data. */
2478 xml_totalbytes = wim->out_fd.offset;
2479 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2480 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2481 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2482 &wim->hdr.xml_data_reshdr,
2483 write_resource_flags);
2485 free_integrity_table(old_integrity_table);
2489 /* Write integrity table (optional). */
2490 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2491 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2492 struct wim_header checkpoint_hdr;
2493 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2494 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2495 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2496 ret = write_wim_header_at_offset(&checkpoint_hdr,
2499 free_integrity_table(old_integrity_table);
2504 new_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2505 wim->hdr.blob_table_reshdr.size_in_wim;
2507 ret = write_integrity_table(wim,
2510 old_integrity_table);
2511 free_integrity_table(old_integrity_table);
2515 /* No integrity table. */
2516 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2519 /* Now that all information in the WIM header has been determined, the
2520 * preliminary header written earlier can be overwritten, the header of
2521 * the existing WIM file can be overwritten, or the final header can be
2522 * written to the end of the pipable WIM. */
2523 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2525 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2526 hdr_offset = wim->out_fd.offset;
2527 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2528 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2532 /* Possibly sync file data to disk before closing. On POSIX systems, it
2533 * is necessary to do this before using rename() to overwrite an
2534 * existing file with a new file. Otherwise, data loss would occur if
2535 * the system is abruptly terminated when the metadata for the rename
2536 * operation has been written to disk, but the new file data has not.
2538 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2539 DEBUG("Syncing WIM file.");
2540 if (fsync(wim->out_fd.fd)) {
2541 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2542 return WIMLIB_ERR_WRITE;
2546 if (close_wim_writable(wim, write_flags)) {
2547 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2548 return WIMLIB_ERR_WRITE;
2554 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2556 /* Set advisory lock on WIM file (if not already done so) */
2558 lock_wim_for_append(WIMStruct *wim)
2560 if (wim->locked_for_append)
2562 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2563 wim->locked_for_append = 1;
2566 if (errno != EWOULDBLOCK)
2568 return WIMLIB_ERR_ALREADY_LOCKED;
2571 /* Remove advisory lock on WIM file (if present) */
2573 unlock_wim_for_append(WIMStruct *wim)
2575 if (wim->locked_for_append) {
2576 flock(wim->in_fd.fd, LOCK_UN);
2577 wim->locked_for_append = 0;
2583 * write_pipable_wim():
2585 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2586 * capable of being applied from a pipe).
2588 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2589 * images can be applied from them sequentially when the file data is sent over
2590 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2591 * The modifications made to the WIM format for pipable WIMs are:
2593 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2594 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2595 * stops other software from trying to read the file as a normal WIM.
2597 * - The header at the beginning of the file does not contain all the normal
2598 * information; in particular it will have all 0's for the blob table and XML
2599 * data resource entries. This is because this information cannot be
2600 * determined until the blob table and XML data have been written.
2601 * Consequently, wimlib will write the full header at the very end of the
2602 * file. The header at the end, however, is only used when reading the WIM
2603 * from a seekable file (not a pipe).
2605 * - An extra copy of the XML data is placed directly after the header. This
2606 * allows image names and sizes to be determined at an appropriate time when
2607 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2608 * WIM is read from a seekable file (not a pipe).
2610 * - The format of resources, or blobs, has been modified to allow them to be
2611 * used before the "blob table" has been read. Each blob is prefixed with a
2612 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2613 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2614 * uncompressed blob size, and flags that indicate whether the blob is
2615 * compressed. The data of uncompressed blobs then follows literally, while
2616 * the data of compressed blobs follows in a modified format. Compressed
2617 * blobs do not begin with a chunk table, since the chunk table cannot be
2618 * written until all chunks have been compressed. Instead, each compressed
2619 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2620 * Furthermore, the chunk table is written at the end of the resource instead
2621 * of the start. Note: chunk offsets are given in the chunk table as if the
2622 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2623 * used if the WIM is being read from a seekable file (not a pipe).
2625 * - Metadata blobs always come before non-metadata blobs. (This does not by
2626 * itself constitute an incompatibility with normal WIMs, since this is valid
2629 * - At least up to the end of the blobs, all components must be packed as
2630 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2631 * not by itself consititute an incompatibility with normal WIMs, since this
2632 * is valid in normal WIMs.)
2634 * Note: the blob table, XML data, and header at the end are not used when
2635 * applying from a pipe. They exist to support functionality such as image
2636 * application and export when the WIM is *not* read from a pipe.
2638 * Layout of pipable WIM:
2640 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2641 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2642 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2644 * Layout of normal WIM:
2646 * +--------+-----------------------------+-------------------------+
2647 * | Header | File and metadata resources | Blob table | XML data |
2648 * +--------+-----------------------------+-------------------------+
2650 * An optional integrity table can follow the final XML data in both normal and
2651 * pipable WIMs. However, due to implementation details, wimlib currently can
2652 * only include an integrity table in a pipable WIM when writing it to a
2653 * seekable file (not a pipe).
2655 * Do note that since pipable WIMs are not supported by Microsoft's software,
2656 * wimlib does not create them unless explicitly requested (with
2657 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2658 * characters to identify the file.
2661 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2662 unsigned num_threads,
2663 struct list_head *blob_list_override,
2664 struct list_head *blob_table_list_ret)
2667 struct wim_reshdr xml_reshdr;
2669 WARNING("Creating a pipable WIM, which will "
2671 " with Microsoft's software (wimgapi/imagex/Dism).");
2673 /* At this point, the header at the beginning of the file has already
2676 /* For efficiency, when wimlib adds an image to the WIM with
2677 * wimlib_add_image(), the SHA-1 message digests of files is not
2678 * calculated; instead, they are calculated while the files are being
2679 * written. However, this does not work when writing a pipable WIM,
2680 * since when writing a blob to a pipable WIM, its SHA-1 message digest
2681 * needs to be known before the blob data is written. Therefore, before
2682 * getting much farther, we need to pre-calculate the SHA-1 message
2683 * digests of all blobs that will be written. */
2684 ret = wim_checksum_unhashed_blobs(wim);
2688 /* Write extra copy of the XML data. */
2689 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2690 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2694 /* Write metadata resources for the image(s) being included in the
2696 ret = write_metadata_resources(wim, image, write_flags);
2700 /* Write blobs needed for the image(s) being included in the output WIM,
2701 * or blobs needed for the split WIM part. */
2702 return write_file_blobs(wim, image, write_flags,
2703 num_threads, blob_list_override,
2704 blob_table_list_ret);
2706 /* The blob table, XML data, and header at end are handled by
2707 * finish_write(). */
2710 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2713 write_wim_part(WIMStruct *wim,
2714 const void *path_or_fd,
2717 unsigned num_threads,
2718 unsigned part_number,
2719 unsigned total_parts,
2720 struct list_head *blob_list_override,
2724 struct wim_header hdr_save;
2725 struct list_head blob_table_list;
2727 if (total_parts == 1)
2728 DEBUG("Writing standalone WIM.");
2730 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2731 if (image == WIMLIB_ALL_IMAGES)
2732 DEBUG("Including all images.");
2734 DEBUG("Including image %d only.", image);
2735 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2736 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2738 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2739 DEBUG("Write flags: 0x%08x", write_flags);
2741 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2742 DEBUG("\tCHECK_INTEGRITY");
2744 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2745 DEBUG("\tNO_CHECK_INTEGRITY");
2747 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2750 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2751 DEBUG("\tNOT_PIPABLE");
2753 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2754 DEBUG("\tRECOMPRESS");
2756 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2759 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2762 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2763 DEBUG("\tSOFT_DELETE");
2765 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2766 DEBUG("\tIGNORE_READONLY_FLAG");
2768 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2769 DEBUG("\tSKIP_EXTERNAL_WIMS");
2771 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2772 DEBUG("\tSTREAMS_OK");
2774 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2775 DEBUG("\tRETAIN_GUID");
2777 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2780 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2781 DEBUG("\tFILE_DESCRIPTOR");
2783 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2784 DEBUG("\tNO_METADATA");
2786 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2787 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2789 if (num_threads == 0)
2790 DEBUG("Number of threads: autodetect");
2792 DEBUG("Number of threads: %u", num_threads);
2793 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2794 DEBUG("Blob list: %s", (blob_list_override ? "specified" : "autodetect"));
2795 DEBUG("GUID: %s", (write_flags &
2796 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2797 : guid ? "explicit" : "generate new");
2799 /* Internally, this is always called with a valid part number and total
2801 wimlib_assert(total_parts >= 1);
2802 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2804 /* A valid image (or all images) must be specified. */
2805 if (image != WIMLIB_ALL_IMAGES &&
2806 (image < 1 || image > wim->hdr.image_count))
2807 return WIMLIB_ERR_INVALID_IMAGE;
2809 /* If we need to write metadata resources, make sure the ::WIMStruct has
2810 * the needed information attached (e.g. is not a resource-only WIM,
2811 * such as a non-first part of a split WIM). */
2812 if (!wim_has_metadata(wim) &&
2813 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2814 return WIMLIB_ERR_METADATA_NOT_FOUND;
2816 /* Check for contradictory flags. */
2817 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2818 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2819 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2820 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2821 return WIMLIB_ERR_INVALID_PARAM;
2823 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2824 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2825 == (WIMLIB_WRITE_FLAG_PIPABLE |
2826 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2827 return WIMLIB_ERR_INVALID_PARAM;
2829 /* Save previous header, then start initializing the new one. */
2830 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2832 /* Set default integrity, pipable, and solid flags. */
2833 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2834 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2835 if (wim_is_pipable(wim)) {
2836 DEBUG("WIM is pipable; default to PIPABLE.");
2837 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2840 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2841 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2842 if (wim_has_integrity_table(wim)) {
2843 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2844 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2847 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2848 WIMLIB_WRITE_FLAG_SOLID))
2849 == (WIMLIB_WRITE_FLAG_PIPABLE |
2850 WIMLIB_WRITE_FLAG_SOLID))
2852 ERROR("Cannot specify both PIPABLE and SOLID!");
2853 return WIMLIB_ERR_INVALID_PARAM;
2856 /* Set appropriate magic number. */
2857 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2858 wim->hdr.magic = PWM_MAGIC;
2860 wim->hdr.magic = WIM_MAGIC;
2862 /* Set appropriate version number. */
2863 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2864 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2865 wim->hdr.wim_version = WIM_VERSION_SOLID;
2867 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2869 /* Clear header flags that will be set automatically. */
2870 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2871 WIM_HDR_FLAG_RESOURCE_ONLY |
2872 WIM_HDR_FLAG_SPANNED |
2873 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2875 /* Set SPANNED header flag if writing part of a split WIM. */
2876 if (total_parts != 1)
2877 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2879 /* Set part number and total parts of split WIM. This will be 1 and 1
2880 * if the WIM is standalone. */
2881 wim->hdr.part_number = part_number;
2882 wim->hdr.total_parts = total_parts;
2884 /* Set compression type if different. */
2885 if (wim->compression_type != wim->out_compression_type) {
2886 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2887 wimlib_assert(ret == 0);
2890 /* Set chunk size if different. */
2891 wim->hdr.chunk_size = wim->out_chunk_size;
2894 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2896 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2898 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2901 /* Clear references to resources that have not been written yet. */
2902 zero_reshdr(&wim->hdr.blob_table_reshdr);
2903 zero_reshdr(&wim->hdr.xml_data_reshdr);
2904 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2905 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2907 /* Set image count and boot index correctly for single image writes. */
2908 if (image != WIMLIB_ALL_IMAGES) {
2909 wim->hdr.image_count = 1;
2910 if (wim->hdr.boot_idx == image)
2911 wim->hdr.boot_idx = 1;
2913 wim->hdr.boot_idx = 0;
2916 /* Split WIMs can't be bootable. */
2917 if (total_parts != 1)
2918 wim->hdr.boot_idx = 0;
2920 /* Initialize output file descriptor. */
2921 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2922 /* File descriptor was explicitly provided. Return error if
2923 * file descriptor is not seekable, unless writing a pipable WIM
2925 wim->out_fd.fd = *(const int*)path_or_fd;
2926 wim->out_fd.offset = 0;
2927 if (!filedes_is_seekable(&wim->out_fd)) {
2928 ret = WIMLIB_ERR_INVALID_PARAM;
2929 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2930 goto out_restore_hdr;
2931 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2932 ERROR("Can't include integrity check when "
2933 "writing pipable WIM to pipe!");
2934 goto out_restore_hdr;
2939 /* Filename of WIM to write was provided; open file descriptor
2941 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2942 O_TRUNC | O_CREAT | O_RDWR);
2944 goto out_restore_hdr;
2947 /* Write initial header. This is merely a "dummy" header since it
2948 * doesn't have all the information yet, so it will be overwritten later
2949 * (unless writing a pipable WIM). */
2950 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2951 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2952 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2953 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2955 goto out_restore_hdr;
2957 /* Write file blobs and metadata resources. */
2958 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2959 /* Default case: create a normal (non-pipable) WIM. */
2960 ret = write_file_blobs(wim, image, write_flags,
2965 goto out_restore_hdr;
2967 ret = write_metadata_resources(wim, image, write_flags);
2969 goto out_restore_hdr;
2971 /* Non-default case: create pipable WIM. */
2972 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2976 goto out_restore_hdr;
2977 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2981 /* Write blob table, XML data, and (optional) integrity table. */
2982 ret = finish_write(wim, image, write_flags, &blob_table_list);
2984 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2985 (void)close_wim_writable(wim, write_flags);
2986 DEBUG("ret=%d", ret);
2990 /* Write a standalone WIM to a file or file descriptor. */
2992 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2993 int image, int write_flags, unsigned num_threads)
2995 return write_wim_part(wim, path_or_fd, image, write_flags,
2996 num_threads, 1, 1, NULL, NULL);
2999 /* API function documented in wimlib.h */
3001 wimlib_write(WIMStruct *wim, const tchar *path,
3002 int image, int write_flags, unsigned num_threads)
3004 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3005 return WIMLIB_ERR_INVALID_PARAM;
3007 if (path == NULL || path[0] == T('\0'))
3008 return WIMLIB_ERR_INVALID_PARAM;
3010 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3013 /* API function documented in wimlib.h */
3015 wimlib_write_to_fd(WIMStruct *wim, int fd,
3016 int image, int write_flags, unsigned num_threads)
3018 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3019 return WIMLIB_ERR_INVALID_PARAM;
3022 return WIMLIB_ERR_INVALID_PARAM;
3024 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3026 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3030 any_images_modified(WIMStruct *wim)
3032 for (int i = 0; i < wim->hdr.image_count; i++)
3033 if (wim->image_metadata[i]->modified)
3039 check_resource_offset(struct blob_descriptor *blob, void *_wim)
3041 const WIMStruct *wim = _wim;
3042 off_t end_offset = *(const off_t*)wim->private;
3044 if (blob->blob_location == BLOB_IN_WIM &&
3045 blob->rdesc->wim == wim &&
3046 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
3047 return WIMLIB_ERR_RESOURCE_ORDER;
3051 /* Make sure no file or metadata resources are located after the XML data (or
3052 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3053 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3055 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3060 wim->private = &end_offset;
3061 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
3065 for (i = 0; i < wim->hdr.image_count; i++) {
3066 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
3074 * Overwrite a WIM, possibly appending new resources to it.
3076 * A WIM looks like (or is supposed to look like) the following:
3078 * Header (212 bytes)
3079 * Resources for metadata and files (variable size)
3080 * Blob table (variable size)
3081 * XML data (variable size)
3082 * Integrity table (optional) (variable size)
3084 * If we are not adding any new files or metadata, then the blob table is
3085 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3086 * header. This operation is potentially unsafe if the program is abruptly
3087 * terminated while the XML data or integrity table are being overwritten, but
3088 * before the new header has been written. To partially alleviate this problem,
3089 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3090 * finish_write() to cause a temporary WIM header to be written after the XML
3091 * data has been written. This may prevent the WIM from becoming corrupted if
3092 * the program is terminated while the integrity table is being calculated (but
3093 * no guarantees, due to write re-ordering...).
3095 * If we are adding new blobs, including new file data as well as any metadata
3096 * for any new images, then the blob table needs to be changed, and those blobs
3097 * need to be written. In this case, we try to perform a safe update of the WIM
3098 * file by writing the blobs *after* the end of the previous WIM, then writing
3099 * the new blob table, XML data, and (optionally) integrity table following the
3100 * new blobs. This will produce a layout like the following:
3102 * Header (212 bytes)
3103 * (OLD) Resources for metadata and files (variable size)
3104 * (OLD) Blob table (variable size)
3105 * (OLD) XML data (variable size)
3106 * (OLD) Integrity table (optional) (variable size)
3107 * (NEW) Resources for metadata and files (variable size)
3108 * (NEW) Blob table (variable size)
3109 * (NEW) XML data (variable size)
3110 * (NEW) Integrity table (optional) (variable size)
3112 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3113 * the header is overwritten to point to the new blob table, XML data, and
3114 * integrity table, to produce the following layout:
3116 * Header (212 bytes)
3117 * Resources for metadata and files (variable size)
3118 * Nothing (variable size)
3119 * Resources for metadata and files (variable size)
3120 * Blob table (variable size)
3121 * XML data (variable size)
3122 * Integrity table (optional) (variable size)
3124 * This method allows an image to be appended to a large WIM very quickly, and
3125 * is crash-safe except in the case of write re-ordering, but the disadvantage
3126 * is that a small hole is left in the WIM where the old blob table, xml data,
3127 * and integrity table were. (These usually only take up a small amount of
3128 * space compared to the blobs, however.)
3131 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3135 u64 old_blob_table_end, old_xml_begin, old_xml_end;
3136 struct wim_header hdr_save;
3137 struct list_head blob_list;
3138 struct list_head blob_table_list;
3139 struct filter_context filter_ctx;
3141 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3143 /* Save original header so it can be restored in case of error */
3144 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3146 /* Set default integrity flag. */
3147 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3148 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3149 if (wim_has_integrity_table(wim))
3150 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3152 /* Set WIM version if writing solid resources. */
3153 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
3154 wim->hdr.wim_version = WIM_VERSION_SOLID;
3156 /* Set additional flags for overwrite. */
3157 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3158 WIMLIB_WRITE_FLAG_STREAMS_OK;
3160 /* Make sure there is no data after the XML data, except possibily an
3161 * integrity table. If this were the case, then this data would be
3163 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3164 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3165 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
3166 wim->hdr.blob_table_reshdr.size_in_wim;
3167 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3168 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3169 WARNING("Didn't expect the integrity table to be before the XML data");
3170 ret = WIMLIB_ERR_RESOURCE_ORDER;
3171 goto out_restore_memory_hdr;
3174 if (old_blob_table_end > old_xml_begin) {
3175 WARNING("Didn't expect the blob table to be after the XML data");
3176 ret = WIMLIB_ERR_RESOURCE_ORDER;
3177 goto out_restore_memory_hdr;
3180 /* Set @old_wim_end, which indicates the point beyond which we don't
3181 * allow any file and metadata resources to appear without returning
3182 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3183 * overwrite these resources). */
3184 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
3185 /* If no images have been modified and no images have been
3186 * deleted, a new blob table does not need to be written. We
3187 * shall write the new XML data and optional integrity table
3188 * immediately after the blob table. Note that this may
3189 * overwrite an existing integrity table. */
3190 DEBUG("Skipping writing blob table "
3191 "(no images modified or deleted)");
3192 old_wim_end = old_blob_table_end;
3193 write_flags |= WIMLIB_WRITE_FLAG_NO_BLOB_TABLE |
3194 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3195 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3196 /* Old WIM has an integrity table; begin writing new blobs after
3198 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3199 wim->hdr.integrity_table_reshdr.size_in_wim;
3201 /* No existing integrity table; begin writing new blobs after
3202 * the old XML data. */
3203 old_wim_end = old_xml_end;
3206 ret = check_resource_offsets(wim, old_wim_end);
3208 goto out_restore_memory_hdr;
3210 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3211 &blob_list, &blob_table_list,
3214 goto out_restore_memory_hdr;
3216 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3218 goto out_restore_memory_hdr;
3220 ret = lock_wim_for_append(wim);
3224 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3225 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3226 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3228 ERROR_WITH_ERRNO("Error updating WIM header flags");
3229 goto out_unlock_wim;
3232 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3233 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3234 ret = WIMLIB_ERR_WRITE;
3235 goto out_restore_physical_hdr;
3238 ret = wim_write_blob_list(wim, &blob_list, write_flags,
3239 num_threads, &filter_ctx);
3243 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3247 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3252 unlock_wim_for_append(wim);
3256 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_BLOB_TABLE)) {
3257 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3258 wim->filename, old_wim_end);
3259 /* Return value of ftruncate() is ignored because this is
3260 * already an error path. */
3261 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3263 out_restore_physical_hdr:
3264 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3266 unlock_wim_for_append(wim);
3268 (void)close_wim_writable(wim, write_flags);
3269 out_restore_memory_hdr:
3270 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3275 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3277 size_t wim_name_len;
3280 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3282 /* Write the WIM to a temporary file in the same directory as the
3284 wim_name_len = tstrlen(wim->filename);
3285 tchar tmpfile[wim_name_len + 10];
3286 tmemcpy(tmpfile, wim->filename, wim_name_len);
3287 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3288 tmpfile[wim_name_len + 9] = T('\0');
3290 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3292 WIMLIB_WRITE_FLAG_FSYNC |
3293 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3300 if (filedes_valid(&wim->in_fd)) {
3301 filedes_close(&wim->in_fd);
3302 filedes_invalidate(&wim->in_fd);
3305 /* Rename the new WIM file to the original WIM file. Note: on Windows
3306 * this actually calls win32_rename_replacement(), not _wrename(), so
3307 * that removing the existing destination file can be handled. */
3308 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3309 ret = trename(tmpfile, wim->filename);
3311 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3312 tmpfile, wim->filename);
3319 return WIMLIB_ERR_RENAME;
3322 union wimlib_progress_info progress;
3323 progress.rename.from = tmpfile;
3324 progress.rename.to = wim->filename;
3325 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3326 &progress, wim->progctx);
3329 /* Determine if the specified WIM file may be updated by appending in-place
3330 * rather than writing and replacing it with an entirely new file. */
3332 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3334 /* REBUILD flag forces full rebuild. */
3335 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3338 /* Image deletions cause full rebuild by default. */
3339 if (wim->image_deletion_occurred &&
3340 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3343 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3344 * turned into a pipable WIM in-place. */
3345 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3348 /* The default compression type and compression chunk size selected for
3349 * the output WIM must be the same as those currently used for the WIM.
3351 if (wim->compression_type != wim->out_compression_type)
3353 if (wim->chunk_size != wim->out_chunk_size)
3359 /* API function documented in wimlib.h */
3361 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3366 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3367 return WIMLIB_ERR_INVALID_PARAM;
3370 return WIMLIB_ERR_NO_FILENAME;
3372 orig_hdr_flags = wim->hdr.flags;
3373 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3374 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3375 ret = can_modify_wim(wim);
3376 wim->hdr.flags = orig_hdr_flags;
3380 if (can_overwrite_wim_inplace(wim, write_flags)) {
3381 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3382 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3384 WARNING("Falling back to re-building entire WIM");
3386 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);