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 * override 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"
55 #include "wimlib/win32.h" /* win32_rename_replacement() */
56 #include "wimlib/write.h"
57 #include "wimlib/xml.h"
60 /* wimlib internal flags used when writing resources. */
61 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
62 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
63 #define WRITE_RESOURCE_FLAG_SOLID 0x00000004
64 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
65 #define WRITE_RESOURCE_FLAG_SOLID_SORT 0x00000010
68 write_flags_to_resource_flags(int write_flags)
70 int write_resource_flags = 0;
72 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
73 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
75 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
78 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
79 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
81 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
82 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
84 if ((write_flags & (WIMLIB_WRITE_FLAG_SOLID |
85 WIMLIB_WRITE_FLAG_NO_SOLID_SORT)) ==
86 WIMLIB_WRITE_FLAG_SOLID)
87 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID_SORT;
89 return write_resource_flags;
92 struct filter_context {
98 * Determine whether the specified blob should be filtered out from the write.
102 * < 0 : The blob should be hard-filtered; that is, not included in the output
104 * 0 : The blob should not be filtered out.
105 * > 0 : The blob should be soft-filtered; that is, it already exists in the
106 * WIM file and may not need to be written again.
109 blob_filtered(const struct blob_descriptor *blob,
110 const struct filter_context *ctx)
118 write_flags = ctx->write_flags;
121 if (write_flags & WIMLIB_WRITE_FLAG_APPEND &&
122 blob->blob_location == BLOB_IN_WIM &&
123 blob->rdesc->wim == wim)
126 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
127 blob->blob_location == BLOB_IN_WIM &&
128 blob->rdesc->wim != wim)
135 blob_hard_filtered(const struct blob_descriptor *blob,
136 struct filter_context *ctx)
138 return blob_filtered(blob, ctx) < 0;
142 may_soft_filter_blobs(const struct filter_context *ctx)
144 return ctx && (ctx->write_flags & WIMLIB_WRITE_FLAG_APPEND);
148 may_hard_filter_blobs(const struct filter_context *ctx)
150 return ctx && (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS);
154 may_filter_blobs(const struct filter_context *ctx)
156 return (may_soft_filter_blobs(ctx) || may_hard_filter_blobs(ctx));
159 /* Return true if the specified blob is located in a WIM resource which can be
160 * reused in the output WIM file, without being recompressed. */
162 can_raw_copy(const struct blob_descriptor *blob, int write_resource_flags,
163 int out_ctype, u32 out_chunk_size)
165 const struct wim_resource_descriptor *rdesc;
167 /* Recompress everything if requested. */
168 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
171 /* A blob not located in a WIM resource cannot be reused. */
172 if (blob->blob_location != BLOB_IN_WIM)
177 /* Only reuse compressed resources. */
178 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
179 !(rdesc->flags & (WIM_RESHDR_FLAG_COMPRESSED |
180 WIM_RESHDR_FLAG_SOLID)))
183 /* When writing a pipable WIM, we can only reuse pipable resources; and
184 * when writing a non-pipable WIM, we can only reuse non-pipable
186 if (rdesc->is_pipable !=
187 !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
190 /* When writing a solid WIM, we can only reuse solid resources; and when
191 * writing a non-solid WIM, we can only reuse non-solid resources. */
192 if (!!(rdesc->flags & WIM_RESHDR_FLAG_SOLID) !=
193 !!(write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
196 /* Note: it is theoretically possible to copy chunks of compressed data
197 * between non-solid, solid, and pipable resources. However, we don't
198 * currently implement this optimization because it would be complex and
199 * would usually go unused. */
201 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
202 /* To re-use a non-solid resource, it must use the desired
203 * compression type and chunk size. */
204 return (rdesc->compression_type == out_ctype &&
205 rdesc->chunk_size == out_chunk_size);
207 /* Solid resource: Such resources may contain multiple blobs,
208 * and in general only a subset of them need to be written. As
209 * a heuristic, re-use the raw data if more than two-thirds the
210 * uncompressed size is being written. */
212 /* Note: solid resources contain a header that specifies the
213 * compression type and chunk size; therefore we don't need to
214 * check if they are compatible with @out_ctype and
215 * @out_chunk_size. */
217 /* Did we already decide to reuse the resource? */
218 if (rdesc->raw_copy_ok)
221 struct blob_descriptor *res_blob;
224 list_for_each_entry(res_blob, &rdesc->blob_list, rdesc_node)
225 if (res_blob->will_be_in_output_wim)
226 write_size += res_blob->size;
228 return (write_size > rdesc->uncompressed_size * 2 / 3);
233 reshdr_flags_for_blob(const struct blob_descriptor *blob)
235 u32 reshdr_flags = 0;
236 if (blob->is_metadata)
237 reshdr_flags |= WIM_RESHDR_FLAG_METADATA;
242 blob_set_out_reshdr_for_reuse(struct blob_descriptor *blob)
244 const struct wim_resource_descriptor *rdesc;
246 wimlib_assert(blob->blob_location == BLOB_IN_WIM);
249 if (rdesc->flags & WIM_RESHDR_FLAG_SOLID) {
250 blob->out_reshdr.offset_in_wim = blob->offset_in_res;
251 blob->out_reshdr.uncompressed_size = 0;
252 blob->out_reshdr.size_in_wim = blob->size;
254 blob->out_res_offset_in_wim = rdesc->offset_in_wim;
255 blob->out_res_size_in_wim = rdesc->size_in_wim;
256 blob->out_res_uncompressed_size = rdesc->uncompressed_size;
258 blob->out_reshdr.offset_in_wim = rdesc->offset_in_wim;
259 blob->out_reshdr.uncompressed_size = rdesc->uncompressed_size;
260 blob->out_reshdr.size_in_wim = rdesc->size_in_wim;
262 blob->out_reshdr.flags = rdesc->flags;
266 /* Write the header for a blob in a pipable WIM. */
268 write_pwm_blob_header(const struct blob_descriptor *blob,
269 struct filedes *out_fd, bool compressed)
271 struct pwm_blob_hdr blob_hdr;
275 wimlib_assert(!blob->unhashed);
277 blob_hdr.magic = cpu_to_le64(PWM_BLOB_MAGIC);
278 blob_hdr.uncompressed_size = cpu_to_le64(blob->size);
279 copy_hash(blob_hdr.hash, blob->hash);
280 reshdr_flags = reshdr_flags_for_blob(blob);
282 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
283 blob_hdr.flags = cpu_to_le32(reshdr_flags);
284 ret = full_write(out_fd, &blob_hdr, sizeof(blob_hdr));
286 ERROR_WITH_ERRNO("Write error");
290 struct write_blobs_progress_data {
291 wimlib_progress_func_t progfunc;
293 union wimlib_progress_info progress;
298 do_write_blobs_progress(struct write_blobs_progress_data *progress_data,
299 u64 complete_size, u32 complete_count, bool discarded)
301 union wimlib_progress_info *progress = &progress_data->progress;
305 progress->write_streams.total_bytes -= complete_size;
306 progress->write_streams.total_streams -= complete_count;
307 if (progress_data->next_progress != ~(u64)0 &&
308 progress_data->next_progress > progress->write_streams.total_bytes)
310 progress_data->next_progress = progress->write_streams.total_bytes;
313 progress->write_streams.completed_bytes += complete_size;
314 progress->write_streams.completed_streams += complete_count;
317 if (progress->write_streams.completed_bytes >= progress_data->next_progress) {
319 ret = call_progress(progress_data->progfunc,
320 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
322 progress_data->progctx);
326 set_next_progress(progress->write_streams.completed_bytes,
327 progress->write_streams.total_bytes,
328 &progress_data->next_progress);
333 struct write_blobs_ctx {
334 /* File descriptor to which the blobs are being written. */
335 struct filedes *out_fd;
337 /* Blob table for the WIMStruct on whose behalf the blobs are being
339 struct blob_table *blob_table;
341 /* Compression format to use. */
344 /* Maximum uncompressed chunk size in compressed resources to use. */
347 /* Flags that affect how the blobs will be written. */
348 int write_resource_flags;
350 /* Data used for issuing WRITE_STREAMS progress. */
351 struct write_blobs_progress_data progress_data;
353 struct filter_context *filter_ctx;
355 /* Pointer to the chunk_compressor implementation being used for
356 * compressing chunks of data, or NULL if chunks are being written
358 struct chunk_compressor *compressor;
360 /* A buffer of size @out_chunk_size that has been loaned out from the
361 * chunk compressor and is currently being filled with the uncompressed
362 * data of the next chunk. */
365 /* Number of bytes in @cur_chunk_buf that are currently filled. */
366 size_t cur_chunk_buf_filled;
368 /* List of blobs that currently have chunks being compressed. */
369 struct list_head blobs_being_compressed;
371 /* List of blobs in the solid resource. Blobs are moved here after
372 * @blobs_being_compressed only when writing a solid resource. */
373 struct list_head blobs_in_solid_resource;
375 /* Current uncompressed offset in the blob being read. */
376 u64 cur_read_blob_offset;
378 /* Uncompressed size of the blob currently being read. */
379 u64 cur_read_blob_size;
381 /* Current uncompressed offset in the blob being written. */
382 u64 cur_write_blob_offset;
384 /* Uncompressed size of resource currently being written. */
385 u64 cur_write_res_size;
387 /* Array that is filled in with compressed chunk sizes as a resource is
391 /* Index of next entry in @chunk_csizes to fill in. */
394 /* Number of entries in @chunk_csizes currently allocated. */
395 size_t num_alloc_chunks;
397 /* Offset in the output file of the start of the chunks of the resource
398 * currently being written. */
399 u64 chunks_start_offset;
402 /* Reserve space for the chunk table and prepare to accumulate the chunk table
405 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
407 u64 expected_num_chunks;
408 u64 expected_num_chunk_entries;
412 /* Calculate the number of chunks and chunk entries that should be
413 * needed for the resource. These normally will be the final values,
414 * but in SOLID mode some of the blobs we're planning to write into the
415 * resource may be duplicates, and therefore discarded, potentially
416 * decreasing the number of chunk entries needed. */
417 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
418 expected_num_chunk_entries = expected_num_chunks;
419 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
420 expected_num_chunk_entries--;
422 /* Make sure the chunk_csizes array is long enough to store the
423 * compressed size of each chunk. */
424 if (expected_num_chunks > ctx->num_alloc_chunks) {
425 u64 new_length = expected_num_chunks + 50;
427 if ((size_t)new_length != new_length) {
428 ERROR("Resource size too large (%"PRIu64" bytes!",
430 return WIMLIB_ERR_NOMEM;
433 FREE(ctx->chunk_csizes);
434 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
435 if (ctx->chunk_csizes == NULL) {
436 ctx->num_alloc_chunks = 0;
437 return WIMLIB_ERR_NOMEM;
439 ctx->num_alloc_chunks = new_length;
442 ctx->chunk_index = 0;
444 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
445 /* Reserve space for the chunk table in the output file. In the
446 * case of solid resources this reserves the upper bound for the
447 * needed space, not necessarily the exact space which will
448 * prove to be needed. At this point, we just use @chunk_csizes
449 * for a buffer of 0's because the actual compressed chunk sizes
451 reserve_size = expected_num_chunk_entries *
452 get_chunk_entry_size(res_expected_size,
453 0 != (ctx->write_resource_flags &
454 WRITE_RESOURCE_FLAG_SOLID));
455 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
456 reserve_size += sizeof(struct alt_chunk_table_header_disk);
457 memset(ctx->chunk_csizes, 0, reserve_size);
458 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
466 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
470 wimlib_assert(res_expected_size != 0);
472 if (ctx->compressor != NULL) {
473 ret = begin_chunk_table(ctx, res_expected_size);
478 /* Output file descriptor is now positioned at the offset at which to
479 * write the first chunk of the resource. */
480 ctx->chunks_start_offset = ctx->out_fd->offset;
481 ctx->cur_write_blob_offset = 0;
482 ctx->cur_write_res_size = res_expected_size;
487 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
488 u64 *res_start_offset_ret, u64 *res_store_size_ret)
490 size_t actual_num_chunks;
491 size_t actual_num_chunk_entries;
492 size_t chunk_entry_size;
495 actual_num_chunks = ctx->chunk_index;
496 actual_num_chunk_entries = actual_num_chunks;
497 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
498 actual_num_chunk_entries--;
500 chunk_entry_size = get_chunk_entry_size(res_actual_size,
501 0 != (ctx->write_resource_flags &
502 WRITE_RESOURCE_FLAG_SOLID));
504 typedef le64 _may_alias_attribute aliased_le64_t;
505 typedef le32 _may_alias_attribute aliased_le32_t;
507 if (chunk_entry_size == 4) {
508 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
510 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
511 for (size_t i = 0; i < actual_num_chunk_entries; i++)
512 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
514 u32 offset = ctx->chunk_csizes[0];
515 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
516 u32 next_size = ctx->chunk_csizes[i + 1];
517 entries[i] = cpu_to_le32(offset);
522 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
524 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
525 for (size_t i = 0; i < actual_num_chunk_entries; i++)
526 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
528 u64 offset = ctx->chunk_csizes[0];
529 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
530 u64 next_size = ctx->chunk_csizes[i + 1];
531 entries[i] = cpu_to_le64(offset);
537 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
538 u64 res_start_offset;
541 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
542 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
545 res_end_offset = ctx->out_fd->offset;
546 res_start_offset = ctx->chunks_start_offset;
548 res_end_offset = ctx->out_fd->offset;
550 u64 chunk_table_offset;
552 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
554 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
555 struct alt_chunk_table_header_disk hdr;
557 hdr.res_usize = cpu_to_le64(res_actual_size);
558 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
559 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
561 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_XPRESS == 1);
562 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZX == 2);
563 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZMS == 3);
565 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
566 chunk_table_offset - sizeof(hdr));
569 res_start_offset = chunk_table_offset - sizeof(hdr);
571 res_start_offset = chunk_table_offset;
574 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
575 chunk_table_size, chunk_table_offset);
580 *res_start_offset_ret = res_start_offset;
581 *res_store_size_ret = res_end_offset - res_start_offset;
586 ERROR_WITH_ERRNO("Write error");
590 /* Finish writing a WIM resource by writing or updating the chunk table (if not
591 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
593 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
597 u64 res_uncompressed_size;
598 u64 res_offset_in_wim;
600 wimlib_assert(ctx->cur_write_blob_offset == ctx->cur_write_res_size ||
601 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
602 res_uncompressed_size = ctx->cur_write_res_size;
604 if (ctx->compressor) {
605 ret = end_chunk_table(ctx, res_uncompressed_size,
606 &res_offset_in_wim, &res_size_in_wim);
610 res_offset_in_wim = ctx->chunks_start_offset;
611 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
613 out_reshdr->uncompressed_size = res_uncompressed_size;
614 out_reshdr->size_in_wim = res_size_in_wim;
615 out_reshdr->offset_in_wim = res_offset_in_wim;
619 /* Call when no more data from the file at @path is needed. */
621 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
623 union wimlib_progress_info info;
625 info.done_with_file.path_to_file = path;
627 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
632 do_done_with_blob(struct blob_descriptor *blob,
633 wimlib_progress_func_t progfunc, void *progctx)
636 struct wim_inode *inode;
640 if (!blob->may_send_done_with_file)
643 inode = blob->file_inode;
645 wimlib_assert(inode != NULL);
646 wimlib_assert(inode->i_num_remaining_streams > 0);
647 if (--inode->i_num_remaining_streams > 0)
650 cookie1 = progress_get_streamless_path(blob->file_on_disk);
651 cookie2 = progress_get_win32_path(blob->file_on_disk);
653 ret = done_with_file(blob->file_on_disk, progfunc, progctx);
655 progress_put_win32_path(cookie2);
656 progress_put_streamless_path(cookie1);
661 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
663 done_with_blob(struct blob_descriptor *blob, struct write_blobs_ctx *ctx)
665 if (likely(!(ctx->write_resource_flags &
666 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
668 return do_done_with_blob(blob, ctx->progress_data.progfunc,
669 ctx->progress_data.progctx);
672 /* Begin processing a blob for writing. */
674 write_blob_begin_read(struct blob_descriptor *blob, void *_ctx)
676 struct write_blobs_ctx *ctx = _ctx;
679 wimlib_assert(blob->size > 0);
681 ctx->cur_read_blob_offset = 0;
682 ctx->cur_read_blob_size = blob->size;
684 /* As an optimization, we allow some blobs to be "unhashed", meaning
685 * their SHA-1 message digests are unknown. This is the case with blobs
686 * that are added by scanning a directory tree with wimlib_add_image(),
687 * for example. Since WIM uses single-instance blobs, we don't know
688 * whether such each such blob really need to written until it is
689 * actually checksummed, unless it has a unique size. In such cases we
690 * read and checksum the blob in this function, thereby advancing ahead
691 * of read_blob_list(), which will still provide the data again to
692 * write_blob_process_chunk(). This is okay because an unhashed blob
693 * cannot be in a WIM resource, which might be costly to decompress. */
694 if (ctx->blob_table != NULL && blob->unhashed && !blob->unique_size) {
696 struct blob_descriptor *new_blob;
698 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
701 if (new_blob != blob) {
702 /* Duplicate blob detected. */
704 if (new_blob->will_be_in_output_wim ||
705 blob_filtered(new_blob, ctx->filter_ctx))
707 /* The duplicate blob is already being included
708 * in the output WIM, or it would be filtered
709 * out if it had been. Skip writing this blob
710 * (and reading it again) entirely, passing its
711 * output reference count to the duplicate blob
712 * in the former case. */
713 ret = do_write_blobs_progress(&ctx->progress_data,
714 blob->size, 1, true);
715 list_del(&blob->write_blobs_list);
716 list_del(&blob->blob_table_list);
717 if (new_blob->will_be_in_output_wim)
718 new_blob->out_refcnt += blob->out_refcnt;
719 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
720 ctx->cur_write_res_size -= blob->size;
722 ret = done_with_blob(blob, ctx);
723 free_blob_descriptor(blob);
726 return BEGIN_BLOB_STATUS_SKIP_BLOB;
728 /* The duplicate blob can validly be written,
729 * but was not marked as such. Discard the
730 * current blob descriptor and use the
731 * duplicate, but actually freeing the current
732 * blob descriptor must wait until
733 * read_blob_list() has finished reading its
735 list_replace(&blob->write_blobs_list,
736 &new_blob->write_blobs_list);
737 list_replace(&blob->blob_table_list,
738 &new_blob->blob_table_list);
739 blob->will_be_in_output_wim = 0;
740 new_blob->out_refcnt = blob->out_refcnt;
741 new_blob->will_be_in_output_wim = 1;
742 new_blob->may_send_done_with_file = 0;
747 list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
751 /* Rewrite a blob that was just written compressed (as a non-solid WIM resource)
752 * as uncompressed instead. */
754 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
757 u64 begin_offset = blob->out_reshdr.offset_in_wim;
758 u64 end_offset = out_fd->offset;
760 if (filedes_seek(out_fd, begin_offset) == -1)
763 ret = extract_blob_to_fd(blob, out_fd);
765 /* Error reading the uncompressed data. */
766 if (out_fd->offset == begin_offset &&
767 filedes_seek(out_fd, end_offset) != -1)
769 /* Nothing was actually written yet, and we successfully
770 * seeked to the end of the compressed resource, so
771 * don't issue a hard error; just keep the compressed
772 * resource instead. */
773 WARNING("Recovered compressed resource of "
774 "size %"PRIu64", continuing on.", blob->size);
780 wimlib_assert(out_fd->offset - begin_offset == blob->size);
782 /* We could ftruncate() the file to 'out_fd->offset' here, but there
783 * isn't much point. Usually we will only be truncating by a few bytes
784 * and will just overwrite the data immediately. */
786 blob->out_reshdr.size_in_wim = blob->size;
787 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
788 WIM_RESHDR_FLAG_SOLID);
792 /* Returns true if the specified blob, which was written as a non-solid
793 * resource, should be truncated from the WIM file and re-written uncompressed.
794 * blob->out_reshdr must be filled in from the initial write of the blob. */
796 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
797 const struct blob_descriptor *blob)
799 /* If the compressed data is smaller than the uncompressed data, prefer
800 * the compressed data. */
801 if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
804 /* If we're not actually writing compressed data, then there's no need
806 if (!ctx->compressor)
809 /* If writing a pipable WIM, everything we write to the output is final
810 * (it might actually be a pipe!). */
811 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
814 /* If the blob that would need to be re-read is located in a solid
815 * resource in another WIM file, then re-reading it would be costly. So
818 * Exception: if the compressed size happens to be *exactly* the same as
819 * the uncompressed size, then the blob *must* be written uncompressed
820 * in order to remain compatible with the Windows Overlay Filesystem
821 * Filter Driver (WOF).
823 * TODO: we are currently assuming that the optimization for
824 * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
825 * this case from being triggered too often. To fully prevent excessive
826 * decompressions in degenerate cases, we really should obtain the
827 * uncompressed data by decompressing the compressed data we wrote to
830 if (blob->blob_location == BLOB_IN_WIM &&
831 blob->size != blob->rdesc->uncompressed_size &&
832 blob->size != blob->out_reshdr.size_in_wim)
839 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
840 struct blob_descriptor *blob)
842 if (!should_rewrite_blob_uncompressed(ctx, blob))
845 /* Regular (non-solid) WIM resources with exactly one chunk and
846 * compressed size equal to uncompressed size are exactly the same as
847 * the corresponding compressed data --- since there must be 0 entries
848 * in the chunk table and the only chunk must be stored uncompressed.
849 * In this case, there's no need to rewrite anything. */
850 if (ctx->chunk_index == 1 &&
851 blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
853 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
857 return write_blob_uncompressed(blob, ctx->out_fd);
860 /* Write the next chunk of (typically compressed) data to the output WIM,
861 * handling the writing of the chunk table. */
863 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
864 size_t csize, size_t usize)
867 struct blob_descriptor *blob;
868 u32 completed_blob_count;
871 blob = list_entry(ctx->blobs_being_compressed.next,
872 struct blob_descriptor, write_blobs_list);
874 if (ctx->cur_write_blob_offset == 0 &&
875 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
877 /* Starting to write a new blob in non-solid mode. */
879 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
880 ret = write_pwm_blob_header(blob, ctx->out_fd,
881 ctx->compressor != NULL);
886 ret = begin_write_resource(ctx, blob->size);
891 if (ctx->compressor != NULL) {
892 /* Record the compresed chunk size. */
893 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
894 ctx->chunk_csizes[ctx->chunk_index++] = csize;
896 /* If writing a pipable WIM, before the chunk data write a chunk
897 * header that provides the compressed chunk size. */
898 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
899 struct pwm_chunk_hdr chunk_hdr = {
900 .compressed_size = cpu_to_le32(csize),
902 ret = full_write(ctx->out_fd, &chunk_hdr,
909 /* Write the chunk data. */
910 ret = full_write(ctx->out_fd, cchunk, csize);
914 ctx->cur_write_blob_offset += usize;
916 completed_size = usize;
917 completed_blob_count = 0;
918 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
919 /* Wrote chunk in solid mode. It may have finished multiple
921 struct blob_descriptor *next_blob;
923 while (blob && ctx->cur_write_blob_offset >= blob->size) {
925 ctx->cur_write_blob_offset -= blob->size;
927 if (ctx->cur_write_blob_offset)
928 next_blob = list_entry(blob->write_blobs_list.next,
929 struct blob_descriptor,
934 ret = done_with_blob(blob, ctx);
937 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
938 completed_blob_count++;
943 /* Wrote chunk in non-solid mode. It may have finished a
945 if (ctx->cur_write_blob_offset == blob->size) {
947 wimlib_assert(ctx->cur_write_blob_offset ==
948 ctx->cur_write_res_size);
950 ret = end_write_resource(ctx, &blob->out_reshdr);
954 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
955 if (ctx->compressor != NULL)
956 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
958 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
962 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
964 ctx->cur_write_blob_offset = 0;
966 ret = done_with_blob(blob, ctx);
969 list_del(&blob->write_blobs_list);
970 completed_blob_count++;
974 return do_write_blobs_progress(&ctx->progress_data, completed_size,
975 completed_blob_count, false);
978 ERROR_WITH_ERRNO("Write error");
983 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
985 /* While we are unable to get a new chunk buffer due to too many chunks
986 * already outstanding, retrieve and write the next compressed chunk. */
987 while (!(ctx->cur_chunk_buf =
988 ctx->compressor->get_chunk_buffer(ctx->compressor)))
996 bret = ctx->compressor->get_compression_result(ctx->compressor,
1000 wimlib_assert(bret);
1002 ret = write_chunk(ctx, cchunk, csize, usize);
1009 /* Process the next chunk of data to be written to a WIM resource. */
1011 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1013 struct write_blobs_ctx *ctx = _ctx;
1015 const u8 *chunkptr, *chunkend;
1017 wimlib_assert(size != 0);
1019 if (ctx->compressor == NULL) {
1020 /* Write chunk uncompressed. */
1021 ret = write_chunk(ctx, chunk, size, size);
1024 ctx->cur_read_blob_offset += size;
1028 /* Submit the chunk for compression, but take into account that the
1029 * @size the chunk was provided in may not correspond to the
1030 * @out_chunk_size being used for compression. */
1032 chunkend = chunkptr + size;
1034 size_t needed_chunk_size;
1035 size_t bytes_consumed;
1037 if (!ctx->cur_chunk_buf) {
1038 ret = prepare_chunk_buffer(ctx);
1043 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1044 needed_chunk_size = ctx->out_chunk_size;
1046 needed_chunk_size = min(ctx->out_chunk_size,
1047 ctx->cur_chunk_buf_filled +
1048 (ctx->cur_read_blob_size -
1049 ctx->cur_read_blob_offset));
1052 bytes_consumed = min(chunkend - chunkptr,
1053 needed_chunk_size - ctx->cur_chunk_buf_filled);
1055 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1056 chunkptr, bytes_consumed);
1058 chunkptr += bytes_consumed;
1059 ctx->cur_read_blob_offset += bytes_consumed;
1060 ctx->cur_chunk_buf_filled += bytes_consumed;
1062 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1063 ctx->compressor->signal_chunk_filled(ctx->compressor,
1064 ctx->cur_chunk_buf_filled);
1065 ctx->cur_chunk_buf = NULL;
1066 ctx->cur_chunk_buf_filled = 0;
1068 } while (chunkptr != chunkend);
1072 /* Finish processing a blob for writing. It may not have been completely
1073 * written yet, as the chunk_compressor implementation may still have chunks
1074 * buffered or being compressed. */
1076 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1078 struct write_blobs_ctx *ctx = _ctx;
1080 wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
1082 if (!blob->will_be_in_output_wim) {
1083 /* The blob was a duplicate. Now that its data has finished
1084 * being read, it is being discarded in favor of the duplicate
1085 * entry. It therefore is no longer needed, and we can fire the
1086 * DONE_WITH_FILE callback because the file will not be read
1089 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1090 * blobs, since it needs to be possible to re-read the file if
1091 * it does not compress to less than its original size. */
1093 status = done_with_blob(blob, ctx);
1094 free_blob_descriptor(blob);
1095 } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1096 /* The blob was not a duplicate and was previously unhashed.
1097 * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1098 * read_blob_list(), blob->hash is now computed and valid. So
1099 * turn this blob into a "hashed" blob. */
1100 list_del(&blob->unhashed_list);
1101 blob_table_insert(ctx->blob_table, blob);
1107 /* Compute statistics about a list of blobs that will be written.
1109 * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1110 * (specified by WIMStruct) are together. */
1112 compute_blob_list_stats(struct list_head *blob_list,
1113 struct write_blobs_ctx *ctx)
1115 struct blob_descriptor *blob;
1116 u64 total_bytes = 0;
1118 u64 total_parts = 0;
1119 WIMStruct *prev_wim_part = NULL;
1121 list_for_each_entry(blob, blob_list, write_blobs_list) {
1123 total_bytes += blob->size;
1124 if (blob->blob_location == BLOB_IN_WIM) {
1125 if (prev_wim_part != blob->rdesc->wim) {
1126 prev_wim_part = blob->rdesc->wim;
1131 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1132 ctx->progress_data.progress.write_streams.total_streams = num_blobs;
1133 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1134 ctx->progress_data.progress.write_streams.completed_streams = 0;
1135 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1136 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1137 ctx->progress_data.progress.write_streams.completed_parts = 0;
1138 ctx->progress_data.next_progress = 0;
1141 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1142 * rather than compressed. Delete these blobs from @blob_list and move them to
1143 * @raw_copy_blobs. Return the total uncompressed size of the blobs that need
1144 * to be compressed. */
1146 find_raw_copy_blobs(struct list_head *blob_list, int write_resource_flags,
1147 int out_ctype, u32 out_chunk_size,
1148 struct list_head *raw_copy_blobs)
1150 struct blob_descriptor *blob, *tmp;
1151 u64 num_nonraw_bytes = 0;
1153 INIT_LIST_HEAD(raw_copy_blobs);
1155 /* Initialize temporary raw_copy_ok flag. */
1156 list_for_each_entry(blob, blob_list, write_blobs_list)
1157 if (blob->blob_location == BLOB_IN_WIM)
1158 blob->rdesc->raw_copy_ok = 0;
1160 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1161 if (can_raw_copy(blob, write_resource_flags,
1162 out_ctype, out_chunk_size))
1164 blob->rdesc->raw_copy_ok = 1;
1165 list_move_tail(&blob->write_blobs_list, raw_copy_blobs);
1167 num_nonraw_bytes += blob->size;
1171 return num_nonraw_bytes;
1174 /* Copy a raw compressed resource located in another WIM file to the WIM file
1177 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1178 struct filedes *out_fd)
1180 u64 cur_read_offset;
1181 u64 end_read_offset;
1182 u8 buf[BUFFER_SIZE];
1183 size_t bytes_to_read;
1185 struct filedes *in_fd;
1186 struct blob_descriptor *blob;
1187 u64 out_offset_in_wim;
1189 /* Copy the raw data. */
1190 cur_read_offset = in_rdesc->offset_in_wim;
1191 end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1193 out_offset_in_wim = out_fd->offset;
1195 if (in_rdesc->is_pipable) {
1196 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1197 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1198 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1199 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1201 in_fd = &in_rdesc->wim->in_fd;
1202 wimlib_assert(cur_read_offset != end_read_offset);
1205 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1207 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1211 ret = full_write(out_fd, buf, bytes_to_read);
1215 cur_read_offset += bytes_to_read;
1217 } while (cur_read_offset != end_read_offset);
1219 list_for_each_entry(blob, &in_rdesc->blob_list, rdesc_node) {
1220 if (blob->will_be_in_output_wim) {
1221 blob_set_out_reshdr_for_reuse(blob);
1222 if (in_rdesc->flags & WIM_RESHDR_FLAG_SOLID)
1223 blob->out_res_offset_in_wim = out_offset_in_wim;
1225 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1232 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1233 * WIM file being written. */
1235 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1236 struct filedes *out_fd,
1237 struct write_blobs_progress_data *progress_data)
1239 struct blob_descriptor *blob;
1242 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1243 blob->rdesc->raw_copy_ok = 1;
1245 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list) {
1246 if (blob->rdesc->raw_copy_ok) {
1247 /* Write each solid resource only one time. */
1248 ret = write_raw_copy_resource(blob->rdesc, out_fd);
1251 blob->rdesc->raw_copy_ok = 0;
1253 ret = do_write_blobs_progress(progress_data, blob->size,
1261 /* Wait for and write all chunks pending in the compressor. */
1263 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1270 if (ctx->compressor == NULL)
1273 if (ctx->cur_chunk_buf_filled != 0) {
1274 ctx->compressor->signal_chunk_filled(ctx->compressor,
1275 ctx->cur_chunk_buf_filled);
1278 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1281 ret = write_chunk(ctx, cdata, csize, usize);
1289 validate_blob_list(struct list_head *blob_list)
1291 struct blob_descriptor *blob;
1293 list_for_each_entry(blob, blob_list, write_blobs_list) {
1294 wimlib_assert(blob->will_be_in_output_wim);
1295 wimlib_assert(blob->size != 0);
1300 blob_is_in_file(const struct blob_descriptor *blob)
1302 return blob->blob_location == BLOB_IN_FILE_ON_DISK
1304 || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1305 || blob->blob_location == BLOB_WIN32_ENCRYPTED
1311 init_done_with_file_info(struct list_head *blob_list)
1313 struct blob_descriptor *blob;
1315 list_for_each_entry(blob, blob_list, write_blobs_list) {
1316 if (blob_is_in_file(blob)) {
1317 blob->file_inode->i_num_remaining_streams = 0;
1318 blob->may_send_done_with_file = 1;
1320 blob->may_send_done_with_file = 0;
1324 list_for_each_entry(blob, blob_list, write_blobs_list)
1325 if (blob->may_send_done_with_file)
1326 blob->file_inode->i_num_remaining_streams++;
1330 * Write a list of blobs to the output WIM file.
1333 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1334 * by the 'write_blobs_list' member.
1337 * The file descriptor, opened for writing, to which to write the blobs.
1339 * @write_resource_flags
1340 * Flags to modify how the blobs are written:
1342 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1343 * Force compression of all resources, even if they could otherwise
1344 * be re-used by copying the raw data, due to being located in a WIM
1345 * file with compatible compression parameters.
1347 * WRITE_RESOURCE_FLAG_PIPABLE:
1348 * Write the resources in the wimlib-specific pipable format, and
1349 * furthermore do so in such a way that no seeking backwards in
1350 * @out_fd will be performed (so it may be a pipe).
1352 * WRITE_RESOURCE_FLAG_SOLID:
1353 * Combine all the blobs into a single resource rather than writing
1354 * them in separate resources. This flag is only valid if the WIM
1355 * version number has been, or will be, set to WIM_VERSION_SOLID.
1356 * This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1359 * Compression format to use in the output resources, specified as one of
1360 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
1364 * Compression chunk size to use in the output resources. It must be a
1365 * valid chunk size for the specified compression format @out_ctype, unless
1366 * @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1370 * Number of threads to use to compress data. If 0, a default number of
1371 * threads will be chosen. The number of threads still may be decreased
1372 * from the specified value if insufficient memory is detected.
1375 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1376 * must be pointer to the blob table for the WIMStruct on whose behalf the
1377 * blobs are being written. Otherwise, this parameter can be NULL.
1380 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1381 * can be a pointer to a context for blob filtering used to detect whether
1382 * the duplicate blob has been hard-filtered or not. If no blobs are
1383 * hard-filtered or no blobs are unhashed, this parameter can be NULL.
1385 * This function will write the blobs in @blob_list to resources in
1386 * consecutive positions in the output WIM file, or to a single solid resource
1387 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1388 * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1389 * updated to specify its location, size, and flags in the output WIM. In the
1390 * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1391 * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1392 * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1393 * respectively, in the output WIM of the solid resource containing the
1394 * corresponding blob.
1396 * Each of the blobs to write may be in any location supported by the
1397 * resource-handling code (specifically, read_blob_list()), such as the contents
1398 * of external file that has been logically added to the output WIM, or a blob
1399 * in another WIM file that has been imported, or even a blob in the "same" WIM
1400 * file of which a modified copy is being written. In the case that a blob is
1401 * already in a WIM file and uses compatible compression parameters, by default
1402 * this function will re-use the raw data instead of decompressing it, then
1403 * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1404 * specified in @write_resource_flags, this is not done.
1406 * As a further requirement, this function requires that the
1407 * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1408 * as any other blobs not in @blob_list that will be in the output WIM file, but
1409 * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1410 * resource with a blob in @blob_list. Still furthermore, if on-the-fly
1411 * deduplication of blobs is possible, then all blobs in @blob_list must also be
1412 * linked by @blob_table_list along with any other blobs that have
1413 * @will_be_in_output_wim set.
1415 * This function handles on-the-fly deduplication of blobs for which SHA-1
1416 * message digests have not yet been calculated. Such blobs may or may not need
1417 * to be written. If @blob_table is non-NULL, then each blob in @blob_list that
1418 * has @unhashed set but not @unique_size set is checksummed immediately before
1419 * it would otherwise be read for writing in order to determine if it is
1420 * identical to another blob already being written or one that would be filtered
1421 * out of the output WIM using blob_filtered() with the context @filter_ctx.
1422 * Each such duplicate blob will be removed from @blob_list, its reference count
1423 * transfered to the pre-existing duplicate blob, its memory freed, and will not
1424 * be written. Alternatively, if a blob in @blob_list is a duplicate with any
1425 * blob in @blob_table that has not been marked for writing or would not be
1426 * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1427 * taking ownership of the reference count and slot in the @blob_table_list.
1429 * Returns 0 if every blob was either written successfully or did not need to be
1430 * written; otherwise returns a non-zero error code.
1433 write_blob_list(struct list_head *blob_list,
1434 struct filedes *out_fd,
1435 int write_resource_flags,
1438 unsigned num_threads,
1439 struct blob_table *blob_table,
1440 struct filter_context *filter_ctx,
1441 wimlib_progress_func_t progfunc,
1445 struct write_blobs_ctx ctx;
1446 struct list_head raw_copy_blobs;
1447 u64 num_nonraw_bytes;
1449 wimlib_assert((write_resource_flags &
1450 (WRITE_RESOURCE_FLAG_SOLID |
1451 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1452 (WRITE_RESOURCE_FLAG_SOLID |
1453 WRITE_RESOURCE_FLAG_PIPABLE));
1455 validate_blob_list(blob_list);
1457 if (list_empty(blob_list))
1460 /* If needed, set auxiliary information so that we can detect when the
1461 * library has finished using each external file. */
1462 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1463 init_done_with_file_info(blob_list);
1465 memset(&ctx, 0, sizeof(ctx));
1467 ctx.out_fd = out_fd;
1468 ctx.blob_table = blob_table;
1469 ctx.out_ctype = out_ctype;
1470 ctx.out_chunk_size = out_chunk_size;
1471 ctx.write_resource_flags = write_resource_flags;
1472 ctx.filter_ctx = filter_ctx;
1475 * We normally sort the blobs to write by a "sequential" order that is
1476 * optimized for reading. But when using solid compression, we instead
1477 * sort the blobs by file extension and file name (when applicable; and
1478 * we don't do this for blobs from solid resources) so that similar
1479 * files are grouped together, which improves the compression ratio.
1480 * This is somewhat of a hack since a blob does not necessarily
1481 * correspond one-to-one with a filename, nor is there any guarantee
1482 * that two files with similar names or extensions are actually similar
1483 * in content. A potential TODO is to sort the blobs based on some
1484 * measure of similarity of their actual contents.
1487 ret = sort_blob_list_by_sequential_order(blob_list,
1488 offsetof(struct blob_descriptor,
1493 compute_blob_list_stats(blob_list, &ctx);
1495 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1496 ret = sort_blob_list_for_solid_compression(blob_list);
1498 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1501 ctx.progress_data.progfunc = progfunc;
1502 ctx.progress_data.progctx = progctx;
1504 num_nonraw_bytes = find_raw_copy_blobs(blob_list, write_resource_flags,
1505 out_ctype, out_chunk_size,
1508 /* Copy any compressed resources for which the raw data can be reused
1509 * without decompression. */
1510 ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1511 &ctx.progress_data);
1513 if (ret || num_nonraw_bytes == 0)
1514 goto out_destroy_context;
1516 /* Unless uncompressed output was required, allocate a chunk_compressor
1517 * to do compression. There are serial and parallel implementations of
1518 * the chunk_compressor interface. We default to parallel using the
1519 * specified number of threads, unless the upper bound on the number
1520 * bytes needing to be compressed is less than a heuristic value. */
1521 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1523 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1524 if (num_nonraw_bytes > max(2000000, out_chunk_size)) {
1525 ret = new_parallel_chunk_compressor(out_ctype,
1530 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1531 " Falling back to single-threaded compression.",
1532 wimlib_get_error_string(ret));
1537 if (ctx.compressor == NULL) {
1538 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1541 goto out_destroy_context;
1546 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1548 ctx.progress_data.progress.write_streams.num_threads = 1;
1550 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1551 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1553 ret = call_progress(ctx.progress_data.progfunc,
1554 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1555 &ctx.progress_data.progress,
1556 ctx.progress_data.progctx);
1558 goto out_destroy_context;
1560 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1561 ret = begin_write_resource(&ctx, num_nonraw_bytes);
1563 goto out_destroy_context;
1566 /* Read the list of blobs needing to be compressed, using the specified
1567 * callbacks to execute processing of the data. */
1569 struct read_blob_callbacks cbs = {
1570 .begin_blob = write_blob_begin_read,
1571 .consume_chunk = write_blob_process_chunk,
1572 .end_blob = write_blob_end_read,
1576 ret = read_blob_list(blob_list,
1577 offsetof(struct blob_descriptor, write_blobs_list),
1579 BLOB_LIST_ALREADY_SORTED |
1580 VERIFY_BLOB_HASHES |
1581 COMPUTE_MISSING_BLOB_HASHES);
1584 goto out_destroy_context;
1586 ret = finish_remaining_chunks(&ctx);
1588 goto out_destroy_context;
1590 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1591 struct wim_reshdr reshdr;
1592 struct blob_descriptor *blob;
1595 ret = end_write_resource(&ctx, &reshdr);
1597 goto out_destroy_context;
1600 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1601 blob->out_reshdr.size_in_wim = blob->size;
1602 blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1603 WIM_RESHDR_FLAG_SOLID;
1604 blob->out_reshdr.uncompressed_size = 0;
1605 blob->out_reshdr.offset_in_wim = offset_in_res;
1606 blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1607 blob->out_res_size_in_wim = reshdr.size_in_wim;
1608 blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1609 offset_in_res += blob->size;
1611 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1614 out_destroy_context:
1615 FREE(ctx.chunk_csizes);
1617 ctx.compressor->destroy(ctx.compressor);
1623 write_file_data_blobs(WIMStruct *wim,
1624 struct list_head *blob_list,
1626 unsigned num_threads,
1627 struct filter_context *filter_ctx)
1631 int write_resource_flags;
1633 write_resource_flags = write_flags_to_resource_flags(write_flags);
1635 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1636 out_chunk_size = wim->out_solid_chunk_size;
1637 out_ctype = wim->out_solid_compression_type;
1639 out_chunk_size = wim->out_chunk_size;
1640 out_ctype = wim->out_compression_type;
1643 return write_blob_list(blob_list,
1645 write_resource_flags,
1655 /* Write the contents of the specified blob as a WIM resource. */
1657 write_wim_resource(struct blob_descriptor *blob,
1658 struct filedes *out_fd,
1661 int write_resource_flags)
1663 LIST_HEAD(blob_list);
1664 list_add(&blob->write_blobs_list, &blob_list);
1665 blob->will_be_in_output_wim = 1;
1666 return write_blob_list(&blob_list,
1668 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1678 /* Write the contents of the specified buffer as a WIM resource. */
1680 write_wim_resource_from_buffer(const void *buf,
1683 struct filedes *out_fd,
1686 struct wim_reshdr *out_reshdr,
1688 int write_resource_flags)
1691 struct blob_descriptor blob;
1693 if (unlikely(buf_size == 0)) {
1694 zero_reshdr(out_reshdr);
1696 copy_hash(hash_ret, zero_hash);
1700 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1701 sha1_buffer(buf, buf_size, blob.hash);
1703 blob.is_metadata = is_metadata;
1705 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1706 write_resource_flags);
1710 copy_reshdr(out_reshdr, &blob.out_reshdr);
1713 copy_hash(hash_ret, blob.hash);
1717 struct blob_size_table {
1718 struct hlist_head *array;
1724 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1726 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1727 if (tab->array == NULL)
1728 return WIMLIB_ERR_NOMEM;
1729 tab->num_entries = 0;
1730 tab->capacity = capacity;
1735 destroy_blob_size_table(struct blob_size_table *tab)
1741 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1743 struct blob_size_table *tab = _tab;
1745 struct blob_descriptor *same_size_blob;
1747 pos = hash_u64(blob->size) % tab->capacity;
1748 blob->unique_size = 1;
1749 hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1750 if (same_size_blob->size == blob->size) {
1751 blob->unique_size = 0;
1752 same_size_blob->unique_size = 0;
1757 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1762 struct find_blobs_ctx {
1765 struct list_head blob_list;
1766 struct blob_size_table blob_size_tab;
1770 reference_blob_for_write(struct blob_descriptor *blob,
1771 struct list_head *blob_list, u32 nref)
1773 if (!blob->will_be_in_output_wim) {
1774 blob->out_refcnt = 0;
1775 list_add_tail(&blob->write_blobs_list, blob_list);
1776 blob->will_be_in_output_wim = 1;
1778 blob->out_refcnt += nref;
1782 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1784 struct list_head *blob_list = _blob_list;
1785 blob->will_be_in_output_wim = 0;
1786 reference_blob_for_write(blob, blob_list, blob->refcnt);
1791 inode_find_blobs_to_reference(const struct wim_inode *inode,
1792 const struct blob_table *table,
1793 struct list_head *blob_list)
1795 wimlib_assert(inode->i_nlink > 0);
1797 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1798 struct blob_descriptor *blob;
1801 blob = stream_blob(&inode->i_streams[i], table);
1803 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1805 hash = stream_hash(&inode->i_streams[i]);
1806 if (!is_zero_hash(hash))
1807 return blob_not_found_error(inode, hash);
1814 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1816 blob->will_be_in_output_wim = 0;
1821 image_find_blobs_to_reference(WIMStruct *wim)
1823 struct wim_image_metadata *imd;
1824 struct wim_inode *inode;
1825 struct blob_descriptor *blob;
1826 struct list_head *blob_list;
1829 imd = wim_get_current_image_metadata(wim);
1831 image_for_each_unhashed_blob(blob, imd)
1832 blob->will_be_in_output_wim = 0;
1834 blob_list = wim->private;
1835 image_for_each_inode(inode, imd) {
1836 ret = inode_find_blobs_to_reference(inode,
1846 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1849 struct list_head *blob_list_ret)
1853 INIT_LIST_HEAD(blob_list_ret);
1855 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1856 (image == 1 && wim->hdr.image_count == 1)))
1858 /* Fast case: Assume that all blobs are being written and that
1859 * the reference counts are correct. */
1860 struct blob_descriptor *blob;
1861 struct wim_image_metadata *imd;
1864 for_blob_in_table(wim->blob_table,
1865 fully_reference_blob_for_write,
1868 for (i = 0; i < wim->hdr.image_count; i++) {
1869 imd = wim->image_metadata[i];
1870 image_for_each_unhashed_blob(blob, imd)
1871 fully_reference_blob_for_write(blob, blob_list_ret);
1874 /* Slow case: Walk through the images being written and
1875 * determine the blobs referenced. */
1876 for_blob_in_table(wim->blob_table,
1877 do_blob_set_not_in_output_wim, NULL);
1878 wim->private = blob_list_ret;
1879 ret = for_image(wim, image, image_find_blobs_to_reference);
1887 struct insert_other_if_hard_filtered_ctx {
1888 struct blob_size_table *tab;
1889 struct filter_context *filter_ctx;
1893 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1895 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1897 if (!blob->will_be_in_output_wim &&
1898 blob_hard_filtered(blob, ctx->filter_ctx))
1899 blob_size_table_insert(blob, ctx->tab);
1904 determine_blob_size_uniquity(struct list_head *blob_list,
1905 struct blob_table *lt,
1906 struct filter_context *filter_ctx)
1909 struct blob_size_table tab;
1910 struct blob_descriptor *blob;
1912 ret = init_blob_size_table(&tab, 9001);
1916 if (may_hard_filter_blobs(filter_ctx)) {
1917 struct insert_other_if_hard_filtered_ctx ctx = {
1919 .filter_ctx = filter_ctx,
1921 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
1924 list_for_each_entry(blob, blob_list, write_blobs_list)
1925 blob_size_table_insert(blob, &tab);
1927 destroy_blob_size_table(&tab);
1932 filter_blob_list_for_write(struct list_head *blob_list,
1933 struct filter_context *filter_ctx)
1935 struct blob_descriptor *blob, *tmp;
1937 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1938 int status = blob_filtered(blob, filter_ctx);
1945 /* Soft filtered. */
1947 /* Hard filtered. */
1948 blob->will_be_in_output_wim = 0;
1949 list_del(&blob->blob_table_list);
1951 list_del(&blob->write_blobs_list);
1957 * prepare_blob_list_for_write() -
1959 * Prepare the list of blobs to write for writing a WIM containing the specified
1960 * image(s) with the specified write flags.
1963 * The WIMStruct on whose behalf the write is occurring.
1966 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1969 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1971 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
1972 * table of @wim and the per-image lists of unhashed blobs should be taken
1973 * as-is, and image metadata should not be searched for references. This
1974 * does not exclude filtering with APPEND and SKIP_EXTERNAL_WIMS, below.
1976 * APPEND: Blobs already present in @wim shall not be returned in
1979 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
1980 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
1983 * List of blobs, linked by write_blobs_list, that need to be written will
1986 * Note that this function assumes that unhashed blobs will be written; it
1987 * does not take into account that they may become duplicates when actually
1990 * @blob_table_list_ret
1991 * List of blobs, linked by blob_table_list, that need to be included in
1992 * the WIM's blob table will be returned here. This will be a superset of
1993 * the blobs in @blob_list_ret.
1995 * This list will be a proper superset of @blob_list_ret if and only if
1996 * WIMLIB_WRITE_FLAG_APPEND was specified in @write_flags and some of the
1997 * blobs that would otherwise need to be written were already located in
2000 * All blobs in this list will have @out_refcnt set to the number of
2001 * references to the blob in the output WIM. If
2002 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2003 * may be as low as 0.
2006 * A context for queries of blob filter status with blob_filtered() is
2007 * returned in this location.
2009 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2010 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2011 * inserted into @blob_table_list_ret.
2013 * Still furthermore, @unique_size will be set to 1 on all blobs in
2014 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2015 * among all blobs in the blob table of @wim that are ineligible for being
2016 * written due to filtering.
2018 * Returns 0 on success; nonzero on read error, memory allocation error, or
2022 prepare_blob_list_for_write(WIMStruct *wim, int image,
2024 struct list_head *blob_list_ret,
2025 struct list_head *blob_table_list_ret,
2026 struct filter_context *filter_ctx_ret)
2029 struct blob_descriptor *blob;
2031 filter_ctx_ret->write_flags = write_flags;
2032 filter_ctx_ret->wim = wim;
2034 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2037 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2042 INIT_LIST_HEAD(blob_table_list_ret);
2043 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2044 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2046 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2051 if (may_filter_blobs(filter_ctx_ret))
2052 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2058 write_file_data(WIMStruct *wim, int image, int write_flags,
2059 unsigned num_threads,
2060 struct list_head *blob_list_override,
2061 struct list_head *blob_table_list_ret)
2064 struct list_head _blob_list;
2065 struct list_head *blob_list;
2066 struct blob_descriptor *blob;
2067 struct filter_context _filter_ctx;
2068 struct filter_context *filter_ctx;
2070 if (blob_list_override == NULL) {
2071 /* Normal case: prepare blob list from image(s) being written.
2073 blob_list = &_blob_list;
2074 filter_ctx = &_filter_ctx;
2075 ret = prepare_blob_list_for_write(wim, image, write_flags,
2077 blob_table_list_ret,
2082 /* Currently only as a result of wimlib_split() being called:
2083 * use blob list already explicitly provided. Use existing
2084 * reference counts. */
2085 blob_list = blob_list_override;
2087 INIT_LIST_HEAD(blob_table_list_ret);
2088 list_for_each_entry(blob, blob_list, write_blobs_list) {
2089 blob->out_refcnt = blob->refcnt;
2090 blob->will_be_in_output_wim = 1;
2091 blob->unique_size = 0;
2092 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2096 return write_file_data_blobs(wim,
2104 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2109 int write_resource_flags;
2111 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2114 write_resource_flags = write_flags_to_resource_flags(write_flags);
2116 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2118 ret = call_progress(wim->progfunc,
2119 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2120 NULL, wim->progctx);
2124 if (image == WIMLIB_ALL_IMAGES) {
2126 end_image = wim->hdr.image_count;
2128 start_image = image;
2132 for (int i = start_image; i <= end_image; i++) {
2133 struct wim_image_metadata *imd;
2135 imd = wim->image_metadata[i - 1];
2136 /* Build a new metadata resource only if image was modified from
2137 * the original (or was newly added). Otherwise just copy the
2139 if (imd->modified) {
2140 ret = write_metadata_resource(wim, i,
2141 write_resource_flags);
2142 } else if (write_flags & WIMLIB_WRITE_FLAG_APPEND) {
2143 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2146 ret = write_wim_resource(imd->metadata_blob,
2148 wim->out_compression_type,
2149 wim->out_chunk_size,
2150 write_resource_flags);
2156 return call_progress(wim->progfunc,
2157 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2158 NULL, wim->progctx);
2162 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2164 int raw_fd = topen(path, open_flags | O_BINARY, 0644);
2166 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2167 return WIMLIB_ERR_OPEN;
2169 filedes_init(&wim->out_fd, raw_fd);
2174 close_wim_writable(WIMStruct *wim, int write_flags)
2178 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2179 if (filedes_valid(&wim->out_fd))
2180 if (filedes_close(&wim->out_fd))
2181 ret = WIMLIB_ERR_WRITE;
2182 filedes_invalidate(&wim->out_fd);
2187 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2189 const struct blob_descriptor *blob1, *blob2;
2191 blob1 = *(const struct blob_descriptor**)p1;
2192 blob2 = *(const struct blob_descriptor**)p2;
2194 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2195 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2196 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2197 return cmp_u64(blob1->out_res_offset_in_wim,
2198 blob2->out_res_offset_in_wim);
2203 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2206 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2207 blob2->out_reshdr.offset_in_wim);
2211 write_blob_table(WIMStruct *wim, int image, int write_flags,
2212 struct list_head *blob_table_list)
2216 /* Set output resource metadata for blobs already present in WIM. */
2217 if (write_flags & WIMLIB_WRITE_FLAG_APPEND) {
2218 struct blob_descriptor *blob;
2219 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2220 if (blob->blob_location == BLOB_IN_WIM &&
2221 blob->rdesc->wim == wim)
2223 blob_set_out_reshdr_for_reuse(blob);
2228 ret = sort_blob_list(blob_table_list,
2229 offsetof(struct blob_descriptor, blob_table_list),
2230 cmp_blobs_by_out_rdesc);
2234 /* Add entries for metadata resources. */
2235 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2239 if (image == WIMLIB_ALL_IMAGES) {
2241 end_image = wim->hdr.image_count;
2243 start_image = image;
2247 /* Push metadata blob table entries onto the front of the list
2248 * in reverse order, so that they're written in order.
2250 for (int i = end_image; i >= start_image; i--) {
2251 struct blob_descriptor *metadata_blob;
2253 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2254 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2255 metadata_blob->out_refcnt = 1;
2256 list_add(&metadata_blob->blob_table_list, blob_table_list);
2260 return write_blob_table_from_blob_list(blob_table_list,
2262 wim->out_hdr.part_number,
2263 &wim->out_hdr.blob_table_reshdr,
2264 write_flags_to_resource_flags(write_flags));
2268 * Finish writing a WIM file: write the blob table, xml data, and integrity
2269 * table, then overwrite the WIM header.
2271 * The output file descriptor is closed on success, except when writing to a
2272 * user-specified file descriptor (WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR set).
2275 finish_write(WIMStruct *wim, int image, int write_flags,
2276 struct list_head *blob_table_list)
2278 int write_resource_flags;
2279 off_t old_blob_table_end = 0;
2280 struct integrity_table *old_integrity_table = NULL;
2281 off_t new_blob_table_end;
2285 write_resource_flags = write_flags_to_resource_flags(write_flags);
2287 /* In the WIM header, there is room for the resource entry for a
2288 * metadata resource labeled as the "boot metadata". This entry should
2289 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2290 * it should be a copy of the resource entry for the image that is
2291 * marked as bootable. */
2292 if (wim->out_hdr.boot_idx == 0) {
2293 zero_reshdr(&wim->out_hdr.boot_metadata_reshdr);
2295 copy_reshdr(&wim->out_hdr.boot_metadata_reshdr,
2296 &wim->image_metadata[
2297 wim->out_hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2300 /* If appending to a WIM file containing an integrity table, we'd like
2301 * to re-use the information in the old integrity table instead of
2302 * recalculating it. But we might overwrite the old integrity table
2303 * when we expand the XML data. Read it into memory just in case. */
2304 if ((write_flags & (WIMLIB_WRITE_FLAG_APPEND |
2305 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2306 (WIMLIB_WRITE_FLAG_APPEND |
2307 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2308 && wim_has_integrity_table(wim))
2310 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2311 wim->hdr.blob_table_reshdr.size_in_wim;
2312 (void)read_integrity_table(wim,
2313 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2314 &old_integrity_table);
2315 /* If we couldn't read the old integrity table, we can still
2316 * re-calculate the full integrity table ourselves. Hence the
2317 * ignoring of the return value. */
2320 /* Write blob table if needed. */
2321 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
2322 ret = write_blob_table(wim, image, write_flags,
2325 free_integrity_table(old_integrity_table);
2330 /* Write XML data. */
2331 xml_totalbytes = wim->out_fd.offset;
2332 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2333 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2334 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2335 &wim->out_hdr.xml_data_reshdr,
2336 write_resource_flags);
2338 free_integrity_table(old_integrity_table);
2342 /* Write integrity table if needed. */
2343 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2344 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS) {
2345 /* The XML data we wrote may have overwritten part of
2346 * the old integrity table, so while calculating the new
2347 * integrity table we should temporarily update the WIM
2348 * header to remove the integrity table reference. */
2349 struct wim_header checkpoint_hdr;
2350 memcpy(&checkpoint_hdr, &wim->out_hdr, sizeof(struct wim_header));
2351 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2352 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2353 ret = write_wim_header(&checkpoint_hdr, &wim->out_fd, 0);
2355 free_integrity_table(old_integrity_table);
2360 new_blob_table_end = wim->out_hdr.blob_table_reshdr.offset_in_wim +
2361 wim->out_hdr.blob_table_reshdr.size_in_wim;
2363 ret = write_integrity_table(wim,
2366 old_integrity_table);
2367 free_integrity_table(old_integrity_table);
2371 /* No integrity table. */
2372 zero_reshdr(&wim->out_hdr.integrity_table_reshdr);
2375 /* Now that all information in the WIM header has been determined, the
2376 * preliminary header written earlier can be overwritten, the header of
2377 * the existing WIM file can be overwritten, or the final header can be
2378 * written to the end of the pipable WIM. */
2379 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2380 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2381 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2383 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, 0);
2387 /* Possibly sync file data to disk before closing. On POSIX systems, it
2388 * is necessary to do this before using rename() to overwrite an
2389 * existing file with a new file. Otherwise, data loss would occur if
2390 * the system is abruptly terminated when the metadata for the rename
2391 * operation has been written to disk, but the new file data has not.
2393 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2394 if (fsync(wim->out_fd.fd)) {
2395 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2396 return WIMLIB_ERR_WRITE;
2400 if (close_wim_writable(wim, write_flags)) {
2401 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2402 return WIMLIB_ERR_WRITE;
2408 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2410 /* Set advisory lock on WIM file (if not already done so) */
2412 lock_wim_for_append(WIMStruct *wim)
2414 if (wim->locked_for_append)
2416 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2417 wim->locked_for_append = 1;
2420 if (errno != EWOULDBLOCK)
2422 return WIMLIB_ERR_ALREADY_LOCKED;
2425 /* Remove advisory lock on WIM file (if present) */
2427 unlock_wim_for_append(WIMStruct *wim)
2429 if (wim->locked_for_append) {
2430 flock(wim->in_fd.fd, LOCK_UN);
2431 wim->locked_for_append = 0;
2437 * write_pipable_wim():
2439 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2440 * capable of being applied from a pipe).
2442 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2443 * images can be applied from them sequentially when the file data is sent over
2444 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2445 * The modifications made to the WIM format for pipable WIMs are:
2447 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2448 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2449 * stops other software from trying to read the file as a normal WIM.
2451 * - The header at the beginning of the file does not contain all the normal
2452 * information; in particular it will have all 0's for the blob table and XML
2453 * data resource entries. This is because this information cannot be
2454 * determined until the blob table and XML data have been written.
2455 * Consequently, wimlib will write the full header at the very end of the
2456 * file. The header at the end, however, is only used when reading the WIM
2457 * from a seekable file (not a pipe).
2459 * - An extra copy of the XML data is placed directly after the header. This
2460 * allows image names and sizes to be determined at an appropriate time when
2461 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2462 * WIM is read from a seekable file (not a pipe).
2464 * - Solid resources are not allowed. Each blob is always stored in its own
2467 * - The format of resources, or blobs, has been modified to allow them to be
2468 * used before the "blob table" has been read. Each blob is prefixed with a
2469 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2470 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2471 * uncompressed blob size, and flags that indicate whether the blob is
2472 * compressed. The data of uncompressed blobs then follows literally, while
2473 * the data of compressed blobs follows in a modified format. Compressed
2474 * blobs do not begin with a chunk table, since the chunk table cannot be
2475 * written until all chunks have been compressed. Instead, each compressed
2476 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2477 * Furthermore, the chunk table is written at the end of the resource instead
2478 * of the start. Note: chunk offsets are given in the chunk table as if the
2479 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2480 * used if the WIM is being read from a seekable file (not a pipe).
2482 * - Metadata blobs always come before non-metadata blobs. (This does not by
2483 * itself constitute an incompatibility with normal WIMs, since this is valid
2486 * - At least up to the end of the blobs, all components must be packed as
2487 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2488 * not by itself consititute an incompatibility with normal WIMs, since this
2489 * is valid in normal WIMs.)
2491 * Note: the blob table, XML data, and header at the end are not used when
2492 * applying from a pipe. They exist to support functionality such as image
2493 * application and export when the WIM is *not* read from a pipe.
2495 * Layout of pipable WIM:
2497 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2498 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2499 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2501 * Layout of normal WIM:
2503 * +--------+-----------------------------+-------------------------+
2504 * | Header | File and metadata resources | Blob table | XML data |
2505 * +--------+-----------------------------+-------------------------+
2507 * An optional integrity table can follow the final XML data in both normal and
2508 * pipable WIMs. However, due to implementation details, wimlib currently can
2509 * only include an integrity table in a pipable WIM when writing it to a
2510 * seekable file (not a pipe).
2512 * Do note that since pipable WIMs are not supported by Microsoft's software,
2513 * wimlib does not create them unless explicitly requested (with
2514 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2515 * characters to identify the file.
2518 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2519 unsigned num_threads,
2520 struct list_head *blob_list_override,
2521 struct list_head *blob_table_list_ret)
2524 struct wim_reshdr xml_reshdr;
2526 WARNING("Creating a pipable WIM, which will "
2528 " with Microsoft's software (WIMGAPI/ImageX/DISM).");
2530 /* At this point, the header at the beginning of the file has already
2533 /* For efficiency, when wimlib adds an image to the WIM with
2534 * wimlib_add_image(), the SHA-1 message digests of files are not
2535 * calculated; instead, they are calculated while the files are being
2536 * written. However, this does not work when writing a pipable WIM,
2537 * since when writing a blob to a pipable WIM, its SHA-1 message digest
2538 * needs to be known before the blob data is written. Therefore, before
2539 * getting much farther, we need to pre-calculate the SHA-1 message
2540 * digests of all blobs that will be written. */
2541 ret = wim_checksum_unhashed_blobs(wim);
2545 /* Write extra copy of the XML data. */
2546 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2547 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2551 /* Write metadata resources for the image(s) being included in the
2553 ret = write_metadata_resources(wim, image, write_flags);
2557 /* Write file data needed for the image(s) being included in the output
2558 * WIM, or file data needed for the split WIM part. */
2559 return write_file_data(wim, image, write_flags,
2560 num_threads, blob_list_override,
2561 blob_table_list_ret);
2563 /* The blob table, XML data, and header at end are handled by
2564 * finish_write(). */
2568 should_default_to_solid_compression(WIMStruct *wim, int write_flags)
2570 return wim->out_hdr.wim_version == WIM_VERSION_SOLID &&
2571 !(write_flags & (WIMLIB_WRITE_FLAG_SOLID |
2572 WIMLIB_WRITE_FLAG_PIPABLE)) &&
2573 wim_has_solid_resources(wim);
2576 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2579 write_wim_part(WIMStruct *wim,
2580 const void *path_or_fd,
2583 unsigned num_threads,
2584 unsigned part_number,
2585 unsigned total_parts,
2586 struct list_head *blob_list_override,
2590 struct list_head blob_table_list;
2592 /* Internally, this is always called with a valid part number and total
2594 wimlib_assert(total_parts >= 1);
2595 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2597 /* A valid image (or all images) must be specified. */
2598 if (image != WIMLIB_ALL_IMAGES &&
2599 (image < 1 || image > wim->hdr.image_count))
2600 return WIMLIB_ERR_INVALID_IMAGE;
2602 /* If we need to write metadata resources, make sure the ::WIMStruct has
2603 * the needed information attached (e.g. is not a resource-only WIM,
2604 * such as a non-first part of a split WIM). */
2605 if (!wim_has_metadata(wim) &&
2606 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2607 return WIMLIB_ERR_METADATA_NOT_FOUND;
2609 /* Check for contradictory flags. */
2610 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2611 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2612 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2613 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2614 return WIMLIB_ERR_INVALID_PARAM;
2616 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2617 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2618 == (WIMLIB_WRITE_FLAG_PIPABLE |
2619 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2620 return WIMLIB_ERR_INVALID_PARAM;
2622 /* Include an integrity table by default if no preference was given and
2623 * the WIM already had an integrity table. */
2624 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2625 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))) {
2626 if (wim_has_integrity_table(wim))
2627 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2630 /* Write a pipable WIM by default if no preference was given and the WIM
2631 * was already pipable. */
2632 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2633 WIMLIB_WRITE_FLAG_NOT_PIPABLE))) {
2634 if (wim_is_pipable(wim))
2635 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2638 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2639 WIMLIB_WRITE_FLAG_SOLID))
2640 == (WIMLIB_WRITE_FLAG_PIPABLE |
2641 WIMLIB_WRITE_FLAG_SOLID))
2643 ERROR("Solid compression is unsupported in pipable WIMs");
2644 return WIMLIB_ERR_INVALID_PARAM;
2647 /* Start initializing the new file header. */
2648 memset(&wim->out_hdr, 0, sizeof(wim->out_hdr));
2650 /* Set the magic number. */
2651 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2652 wim->out_hdr.magic = PWM_MAGIC;
2654 wim->out_hdr.magic = WIM_MAGIC;
2656 /* Set the version number. */
2657 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2658 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2659 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2661 wim->out_hdr.wim_version = WIM_VERSION_DEFAULT;
2663 /* Default to solid compression if it is valid in the chosen WIM file
2664 * format and the WIMStruct references any solid resources. This is
2665 * useful when exporting an image from a solid WIM. */
2666 if (should_default_to_solid_compression(wim, write_flags))
2667 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2669 /* Set the header flags. */
2670 wim->out_hdr.flags = (wim->hdr.flags & (WIM_HDR_FLAG_RP_FIX |
2671 WIM_HDR_FLAG_READONLY));
2672 if (total_parts != 1)
2673 wim->out_hdr.flags |= WIM_HDR_FLAG_SPANNED;
2674 if (wim->out_compression_type != WIMLIB_COMPRESSION_TYPE_NONE) {
2675 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESSION;
2676 switch (wim->out_compression_type) {
2677 case WIMLIB_COMPRESSION_TYPE_XPRESS:
2678 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_XPRESS;
2680 case WIMLIB_COMPRESSION_TYPE_LZX:
2681 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZX;
2683 case WIMLIB_COMPRESSION_TYPE_LZMS:
2684 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZMS;
2689 /* Set the chunk size. */
2690 wim->out_hdr.chunk_size = wim->out_chunk_size;
2693 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2694 guid = wim->hdr.guid;
2696 copy_guid(wim->out_hdr.guid, guid);
2698 generate_guid(wim->out_hdr.guid);
2700 /* Set the part number and total parts. */
2701 wim->out_hdr.part_number = part_number;
2702 wim->out_hdr.total_parts = total_parts;
2704 /* Set the image count. */
2705 if (image == WIMLIB_ALL_IMAGES)
2706 wim->out_hdr.image_count = wim->hdr.image_count;
2708 wim->out_hdr.image_count = 1;
2710 /* Set the boot index. */
2711 wim->out_hdr.boot_idx = 0;
2712 if (total_parts == 1) {
2713 if (image == WIMLIB_ALL_IMAGES)
2714 wim->out_hdr.boot_idx = wim->hdr.boot_idx;
2715 else if (image == wim->hdr.boot_idx)
2716 wim->out_hdr.boot_idx = 1;
2719 /* Set up the output file descriptor. */
2720 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2721 /* File descriptor was explicitly provided. */
2722 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2723 if (!filedes_is_seekable(&wim->out_fd)) {
2724 /* The file descriptor is a pipe. */
2725 ret = WIMLIB_ERR_INVALID_PARAM;
2726 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2728 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2729 ERROR("Can't include integrity check when "
2730 "writing pipable WIM to pipe!");
2735 /* Filename of WIM to write was provided; open file descriptor
2737 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2738 O_TRUNC | O_CREAT | O_RDWR);
2743 /* Write initial header. This is merely a "dummy" header since it
2744 * doesn't have resource entries filled in yet, so it will be
2745 * overwritten later (unless writing a pipable WIM). */
2746 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2747 wim->out_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2748 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2749 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2753 /* Write file data and metadata resources. */
2754 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2755 /* Default case: create a normal (non-pipable) WIM. */
2756 ret = write_file_data(wim, image, write_flags,
2763 ret = write_metadata_resources(wim, image, write_flags);
2767 /* Non-default case: create pipable WIM. */
2768 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2775 /* Write blob table, XML data, and (optional) integrity table. */
2776 ret = finish_write(wim, image, write_flags, &blob_table_list);
2778 (void)close_wim_writable(wim, write_flags);
2782 /* Write a standalone WIM to a file or file descriptor. */
2784 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2785 int image, int write_flags, unsigned num_threads)
2787 return write_wim_part(wim, path_or_fd, image, write_flags,
2788 num_threads, 1, 1, NULL, NULL);
2791 /* API function documented in wimlib.h */
2793 wimlib_write(WIMStruct *wim, const tchar *path,
2794 int image, int write_flags, unsigned num_threads)
2796 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2797 return WIMLIB_ERR_INVALID_PARAM;
2799 if (path == NULL || path[0] == T('\0'))
2800 return WIMLIB_ERR_INVALID_PARAM;
2802 return write_standalone_wim(wim, path, image, write_flags, num_threads);
2805 /* API function documented in wimlib.h */
2807 wimlib_write_to_fd(WIMStruct *wim, int fd,
2808 int image, int write_flags, unsigned num_threads)
2810 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2811 return WIMLIB_ERR_INVALID_PARAM;
2814 return WIMLIB_ERR_INVALID_PARAM;
2816 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2818 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2822 any_images_modified(WIMStruct *wim)
2824 for (int i = 0; i < wim->hdr.image_count; i++)
2825 if (wim->image_metadata[i]->modified)
2831 check_resource_offset(struct blob_descriptor *blob, void *_wim)
2833 const WIMStruct *wim = _wim;
2834 off_t end_offset = *(const off_t*)wim->private;
2836 if (blob->blob_location == BLOB_IN_WIM &&
2837 blob->rdesc->wim == wim &&
2838 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
2839 return WIMLIB_ERR_RESOURCE_ORDER;
2843 /* Make sure no file or metadata resources are located after the XML data (or
2844 * integrity table if present)--- otherwise we can't safely append to the WIM
2845 * file and we return WIMLIB_ERR_RESOURCE_ORDER. */
2847 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2852 wim->private = &end_offset;
2853 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
2857 for (i = 0; i < wim->hdr.image_count; i++) {
2858 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
2866 * Overwrite a WIM, possibly appending new resources to it.
2868 * A WIM looks like (or is supposed to look like) the following:
2870 * Header (212 bytes)
2871 * Resources for metadata and files (variable size)
2872 * Blob table (variable size)
2873 * XML data (variable size)
2874 * Integrity table (optional) (variable size)
2876 * If we are not adding any new files or metadata, then the blob table is
2877 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2878 * header. This operation is potentially unsafe if the program is abruptly
2879 * terminated while the XML data or integrity table are being overwritten, but
2880 * before the new header has been written. To partially alleviate this problem,
2881 * we write a temporary header after the XML data has been written. This may
2882 * prevent the WIM from becoming corrupted if the program is terminated while
2883 * the integrity table is being calculated (but no guarantees, due to write
2886 * If we are adding new blobs, including new file data as well as any metadata
2887 * for any new images, then the blob table needs to be changed, and those blobs
2888 * need to be written. In this case, we try to perform a safe update of the WIM
2889 * file by writing the blobs *after* the end of the previous WIM, then writing
2890 * the new blob table, XML data, and (optionally) integrity table following the
2891 * new blobs. This will produce a layout like the following:
2893 * Header (212 bytes)
2894 * (OLD) Resources for metadata and files (variable size)
2895 * (OLD) Blob table (variable size)
2896 * (OLD) XML data (variable size)
2897 * (OLD) Integrity table (optional) (variable size)
2898 * (NEW) Resources for metadata and files (variable size)
2899 * (NEW) Blob table (variable size)
2900 * (NEW) XML data (variable size)
2901 * (NEW) Integrity table (optional) (variable size)
2903 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2904 * the header is overwritten to point to the new blob table, XML data, and
2905 * integrity table, to produce the following layout:
2907 * Header (212 bytes)
2908 * Resources for metadata and files (variable size)
2909 * Nothing (variable size)
2910 * Resources for metadata and files (variable size)
2911 * Blob table (variable size)
2912 * XML data (variable size)
2913 * Integrity table (optional) (variable size)
2915 * This function allows an image to be appended to a large WIM very quickly, and
2916 * is crash-safe except in the case of write re-ordering, but the disadvantage
2917 * is that a small hole is left in the WIM where the old blob table, xml data,
2918 * and integrity table were. (These usually only take up a small amount of
2919 * space compared to the blobs, however.)
2922 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
2926 u64 old_blob_table_end, old_xml_begin, old_xml_end;
2927 struct list_head blob_list;
2928 struct list_head blob_table_list;
2929 struct filter_context filter_ctx;
2931 /* Include an integrity table by default if no preference was given and
2932 * the WIM already had an integrity table. */
2933 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2934 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2935 if (wim_has_integrity_table(wim))
2936 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2938 /* Start preparing the updated file header. */
2939 memcpy(&wim->out_hdr, &wim->hdr, sizeof(wim->out_hdr));
2941 /* If using solid compression, the version number must be set to
2942 * WIM_VERSION_SOLID. */
2943 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2944 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2946 /* Default to solid compression if it is valid in the chosen WIM file
2947 * format and the WIMStruct references any solid resources. This is
2948 * useful when updating a solid WIM. */
2949 if (should_default_to_solid_compression(wim, write_flags))
2950 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2952 /* Set additional flags for overwrite. */
2953 write_flags |= WIMLIB_WRITE_FLAG_APPEND |
2954 WIMLIB_WRITE_FLAG_STREAMS_OK;
2956 /* Make sure there is no data after the XML data, except possibily an
2957 * integrity table. If this were the case, then this data would be
2959 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2960 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2961 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2962 wim->hdr.blob_table_reshdr.size_in_wim;
2963 if (wim_has_integrity_table(wim) &&
2964 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2965 WARNING("Didn't expect the integrity table to be before the XML data");
2966 ret = WIMLIB_ERR_RESOURCE_ORDER;
2970 if (old_blob_table_end > old_xml_begin) {
2971 WARNING("Didn't expect the blob table to be after the XML data");
2972 ret = WIMLIB_ERR_RESOURCE_ORDER;
2976 /* Set @old_wim_end, which indicates the point beyond which we don't
2977 * allow any file and metadata resources to appear without returning
2978 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2979 * overwrite these resources). */
2980 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
2981 /* If no images have been modified and no images have been
2982 * deleted, a new blob table does not need to be written. We
2983 * shall write the new XML data and optional integrity table
2984 * immediately after the blob table. Note that this may
2985 * overwrite an existing integrity table. */
2986 old_wim_end = old_blob_table_end;
2987 write_flags |= WIMLIB_WRITE_FLAG_NO_NEW_BLOBS;
2988 } else if (wim_has_integrity_table(wim)) {
2989 /* Old WIM has an integrity table; begin writing new blobs after
2991 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2992 wim->hdr.integrity_table_reshdr.size_in_wim;
2994 /* No existing integrity table; begin writing new blobs after
2995 * the old XML data. */
2996 old_wim_end = old_xml_end;
2999 ret = check_resource_offsets(wim, old_wim_end);
3003 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3004 &blob_list, &blob_table_list,
3009 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)
3010 wimlib_assert(list_empty(&blob_list));
3012 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3016 ret = lock_wim_for_append(wim);
3020 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3021 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3022 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3023 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3025 ERROR_WITH_ERRNO("Error updating WIM header flags");
3026 goto out_unlock_wim;
3029 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3030 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3031 ret = WIMLIB_ERR_WRITE;
3032 goto out_restore_hdr;
3035 ret = write_file_data_blobs(wim, &blob_list, write_flags,
3036 num_threads, &filter_ctx);
3040 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3044 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3049 unlock_wim_for_append(wim);
3053 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
3054 WARNING("Truncating \"%"TS"\" to its original size "
3055 "(%"PRIu64" bytes)", wim->filename, old_wim_end);
3056 /* Return value of ftruncate() is ignored because this is
3057 * already an error path. */
3058 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3061 (void)write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3063 unlock_wim_for_append(wim);
3065 (void)close_wim_writable(wim, write_flags);
3071 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3073 size_t wim_name_len;
3076 /* Write the WIM to a temporary file in the same directory as the
3078 wim_name_len = tstrlen(wim->filename);
3079 tchar tmpfile[wim_name_len + 10];
3080 tmemcpy(tmpfile, wim->filename, wim_name_len);
3081 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3082 tmpfile[wim_name_len + 9] = T('\0');
3084 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3086 WIMLIB_WRITE_FLAG_FSYNC |
3087 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3094 if (filedes_valid(&wim->in_fd)) {
3095 filedes_close(&wim->in_fd);
3096 filedes_invalidate(&wim->in_fd);
3099 /* Rename the new WIM file to the original WIM file. Note: on Windows
3100 * this actually calls win32_rename_replacement(), not _wrename(), so
3101 * that removing the existing destination file can be handled. */
3102 ret = trename(tmpfile, wim->filename);
3104 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3105 tmpfile, wim->filename);
3112 return WIMLIB_ERR_RENAME;
3115 union wimlib_progress_info progress;
3116 progress.rename.from = tmpfile;
3117 progress.rename.to = wim->filename;
3118 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3119 &progress, wim->progctx);
3122 /* Determine if the specified WIM file may be updated in-place rather than by
3123 * writing and replacing it with an entirely new file. */
3125 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3127 /* REBUILD flag forces full rebuild. */
3128 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3131 /* Image deletions cause full rebuild by default. */
3132 if (wim->image_deletion_occurred &&
3133 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3136 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3137 * turned into a pipable WIM in-place. */
3138 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3141 /* The default compression type and compression chunk size selected for
3142 * the output WIM must be the same as those currently used for the WIM.
3144 if (wim->compression_type != wim->out_compression_type)
3146 if (wim->chunk_size != wim->out_chunk_size)
3152 /* API function documented in wimlib.h */
3154 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3159 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3160 return WIMLIB_ERR_INVALID_PARAM;
3163 return WIMLIB_ERR_NO_FILENAME;
3165 orig_hdr_flags = wim->hdr.flags;
3166 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3167 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3168 ret = can_modify_wim(wim);
3169 wim->hdr.flags = orig_hdr_flags;
3173 if (can_overwrite_wim_inplace(wim, write_flags)) {
3174 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3175 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3177 WARNING("Falling back to re-building entire WIM");
3179 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);