4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012-2016 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 /* In the case of an in-place compaction, always reuse resources located
178 * in the WIM being compacted. */
179 if (rdesc->wim->being_compacted)
182 /* Otherwise, only reuse compressed resources. */
183 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
184 !(rdesc->flags & (WIM_RESHDR_FLAG_COMPRESSED |
185 WIM_RESHDR_FLAG_SOLID)))
188 /* When writing a pipable WIM, we can only reuse pipable resources; and
189 * when writing a non-pipable WIM, we can only reuse non-pipable
191 if (rdesc->is_pipable !=
192 !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
195 /* When writing a solid WIM, we can only reuse solid resources; and when
196 * writing a non-solid WIM, we can only reuse non-solid resources. */
197 if (!!(rdesc->flags & WIM_RESHDR_FLAG_SOLID) !=
198 !!(write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
201 /* Note: it is theoretically possible to copy chunks of compressed data
202 * between non-solid, solid, and pipable resources. However, we don't
203 * currently implement this optimization because it would be complex and
204 * would usually go unused. */
206 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
207 /* To re-use a non-solid resource, it must use the desired
208 * compression type and chunk size. */
209 return (rdesc->compression_type == out_ctype &&
210 rdesc->chunk_size == out_chunk_size);
212 /* Solid resource: Such resources may contain multiple blobs,
213 * and in general only a subset of them need to be written. As
214 * a heuristic, re-use the raw data if more than two-thirds the
215 * uncompressed size is being written. */
217 /* Note: solid resources contain a header that specifies the
218 * compression type and chunk size; therefore we don't need to
219 * check if they are compatible with @out_ctype and
220 * @out_chunk_size. */
222 /* Did we already decide to reuse the resource? */
223 if (rdesc->raw_copy_ok)
226 struct blob_descriptor *res_blob;
229 list_for_each_entry(res_blob, &rdesc->blob_list, rdesc_node)
230 if (res_blob->will_be_in_output_wim)
231 write_size += res_blob->size;
233 return (write_size > rdesc->uncompressed_size * 2 / 3);
238 reshdr_flags_for_blob(const struct blob_descriptor *blob)
240 u32 reshdr_flags = 0;
241 if (blob->is_metadata)
242 reshdr_flags |= WIM_RESHDR_FLAG_METADATA;
247 blob_set_out_reshdr_for_reuse(struct blob_descriptor *blob)
249 const struct wim_resource_descriptor *rdesc;
251 wimlib_assert(blob->blob_location == BLOB_IN_WIM);
254 if (rdesc->flags & WIM_RESHDR_FLAG_SOLID) {
255 blob->out_reshdr.offset_in_wim = blob->offset_in_res;
256 blob->out_reshdr.uncompressed_size = 0;
257 blob->out_reshdr.size_in_wim = blob->size;
259 blob->out_res_offset_in_wim = rdesc->offset_in_wim;
260 blob->out_res_size_in_wim = rdesc->size_in_wim;
261 blob->out_res_uncompressed_size = rdesc->uncompressed_size;
263 blob->out_reshdr.offset_in_wim = rdesc->offset_in_wim;
264 blob->out_reshdr.uncompressed_size = rdesc->uncompressed_size;
265 blob->out_reshdr.size_in_wim = rdesc->size_in_wim;
267 blob->out_reshdr.flags = rdesc->flags;
271 /* Write the header for a blob in a pipable WIM. */
273 write_pwm_blob_header(const struct blob_descriptor *blob,
274 struct filedes *out_fd, bool compressed)
276 struct pwm_blob_hdr blob_hdr;
280 wimlib_assert(!blob->unhashed);
282 blob_hdr.magic = cpu_to_le64(PWM_BLOB_MAGIC);
283 blob_hdr.uncompressed_size = cpu_to_le64(blob->size);
284 copy_hash(blob_hdr.hash, blob->hash);
285 reshdr_flags = reshdr_flags_for_blob(blob);
287 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
288 blob_hdr.flags = cpu_to_le32(reshdr_flags);
289 ret = full_write(out_fd, &blob_hdr, sizeof(blob_hdr));
291 ERROR_WITH_ERRNO("Error writing blob header to WIM file");
295 struct write_blobs_progress_data {
296 wimlib_progress_func_t progfunc;
298 union wimlib_progress_info progress;
303 do_write_blobs_progress(struct write_blobs_progress_data *progress_data,
304 u64 complete_size, u32 complete_count, bool discarded)
306 union wimlib_progress_info *progress = &progress_data->progress;
310 progress->write_streams.total_bytes -= complete_size;
311 progress->write_streams.total_streams -= complete_count;
312 if (progress_data->next_progress != ~(u64)0 &&
313 progress_data->next_progress > progress->write_streams.total_bytes)
315 progress_data->next_progress = progress->write_streams.total_bytes;
318 progress->write_streams.completed_bytes += complete_size;
319 progress->write_streams.completed_streams += complete_count;
322 if (progress->write_streams.completed_bytes >= progress_data->next_progress) {
324 ret = call_progress(progress_data->progfunc,
325 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
327 progress_data->progctx);
331 set_next_progress(progress->write_streams.completed_bytes,
332 progress->write_streams.total_bytes,
333 &progress_data->next_progress);
338 struct write_blobs_ctx {
339 /* File descriptor to which the blobs are being written. */
340 struct filedes *out_fd;
342 /* Blob table for the WIMStruct on whose behalf the blobs are being
344 struct blob_table *blob_table;
346 /* Compression format to use. */
349 /* Maximum uncompressed chunk size in compressed resources to use. */
352 /* Flags that affect how the blobs will be written. */
353 int write_resource_flags;
355 /* Data used for issuing WRITE_STREAMS progress. */
356 struct write_blobs_progress_data progress_data;
358 struct filter_context *filter_ctx;
360 /* Pointer to the chunk_compressor implementation being used for
361 * compressing chunks of data, or NULL if chunks are being written
363 struct chunk_compressor *compressor;
365 /* A buffer of size @out_chunk_size that has been loaned out from the
366 * chunk compressor and is currently being filled with the uncompressed
367 * data of the next chunk. */
370 /* Number of bytes in @cur_chunk_buf that are currently filled. */
371 size_t cur_chunk_buf_filled;
373 /* List of blobs that currently have chunks being compressed. */
374 struct list_head blobs_being_compressed;
376 /* List of blobs in the solid resource. Blobs are moved here after
377 * @blobs_being_compressed only when writing a solid resource. */
378 struct list_head blobs_in_solid_resource;
380 /* Current uncompressed offset in the blob being written. */
381 u64 cur_write_blob_offset;
383 /* Uncompressed size of resource currently being written. */
384 u64 cur_write_res_size;
386 /* Array that is filled in with compressed chunk sizes as a resource is
390 /* Index of next entry in @chunk_csizes to fill in. */
393 /* Number of entries in @chunk_csizes currently allocated. */
394 size_t num_alloc_chunks;
396 /* Offset in the output file of the start of the chunks of the resource
397 * currently being written. */
398 u64 chunks_start_offset;
401 /* Reserve space for the chunk table and prepare to accumulate the chunk table
404 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
406 u64 expected_num_chunks;
407 u64 expected_num_chunk_entries;
411 /* Calculate the number of chunks and chunk entries that should be
412 * needed for the resource. These normally will be the final values,
413 * but in SOLID mode some of the blobs we're planning to write into the
414 * resource may be duplicates, and therefore discarded, potentially
415 * decreasing the number of chunk entries needed. */
416 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
417 expected_num_chunk_entries = expected_num_chunks;
418 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
419 expected_num_chunk_entries--;
421 /* Make sure the chunk_csizes array is long enough to store the
422 * compressed size of each chunk. */
423 if (expected_num_chunks > ctx->num_alloc_chunks) {
424 u64 new_length = expected_num_chunks + 50;
426 if ((size_t)new_length != new_length) {
427 ERROR("Resource size too large (%"PRIu64" bytes!",
429 return WIMLIB_ERR_NOMEM;
432 FREE(ctx->chunk_csizes);
433 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
434 if (ctx->chunk_csizes == NULL) {
435 ctx->num_alloc_chunks = 0;
436 return WIMLIB_ERR_NOMEM;
438 ctx->num_alloc_chunks = new_length;
441 ctx->chunk_index = 0;
443 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
444 /* Reserve space for the chunk table in the output file. In the
445 * case of solid resources this reserves the upper bound for the
446 * needed space, not necessarily the exact space which will
447 * prove to be needed. At this point, we just use @chunk_csizes
448 * for a buffer of 0's because the actual compressed chunk sizes
450 reserve_size = expected_num_chunk_entries *
451 get_chunk_entry_size(res_expected_size,
452 0 != (ctx->write_resource_flags &
453 WRITE_RESOURCE_FLAG_SOLID));
454 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
455 reserve_size += sizeof(struct alt_chunk_table_header_disk);
456 memset(ctx->chunk_csizes, 0, reserve_size);
457 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
459 ERROR_WITH_ERRNO("Error reserving space for chunk "
460 "table in WIM file");
468 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
472 wimlib_assert(res_expected_size != 0);
474 if (ctx->compressor != NULL) {
475 ret = begin_chunk_table(ctx, res_expected_size);
480 /* Output file descriptor is now positioned at the offset at which to
481 * write the first chunk of the resource. */
482 ctx->chunks_start_offset = ctx->out_fd->offset;
483 ctx->cur_write_blob_offset = 0;
484 ctx->cur_write_res_size = res_expected_size;
489 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
490 u64 *res_start_offset_ret, u64 *res_store_size_ret)
492 size_t actual_num_chunks;
493 size_t actual_num_chunk_entries;
494 size_t chunk_entry_size;
497 actual_num_chunks = ctx->chunk_index;
498 actual_num_chunk_entries = actual_num_chunks;
499 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
500 actual_num_chunk_entries--;
502 chunk_entry_size = get_chunk_entry_size(res_actual_size,
503 0 != (ctx->write_resource_flags &
504 WRITE_RESOURCE_FLAG_SOLID));
506 typedef le64 _may_alias_attribute aliased_le64_t;
507 typedef le32 _may_alias_attribute aliased_le32_t;
509 if (chunk_entry_size == 4) {
510 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
512 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
513 for (size_t i = 0; i < actual_num_chunk_entries; i++)
514 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
516 u32 offset = ctx->chunk_csizes[0];
517 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
518 u32 next_size = ctx->chunk_csizes[i + 1];
519 entries[i] = cpu_to_le32(offset);
524 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
526 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
527 for (size_t i = 0; i < actual_num_chunk_entries; i++)
528 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
530 u64 offset = ctx->chunk_csizes[0];
531 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
532 u64 next_size = ctx->chunk_csizes[i + 1];
533 entries[i] = cpu_to_le64(offset);
539 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
540 u64 res_start_offset;
543 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
544 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
547 res_end_offset = ctx->out_fd->offset;
548 res_start_offset = ctx->chunks_start_offset;
550 res_end_offset = ctx->out_fd->offset;
552 u64 chunk_table_offset;
554 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
556 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
557 struct alt_chunk_table_header_disk hdr;
559 hdr.res_usize = cpu_to_le64(res_actual_size);
560 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
561 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
563 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_XPRESS == 1);
564 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZX == 2);
565 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZMS == 3);
567 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
568 chunk_table_offset - sizeof(hdr));
571 res_start_offset = chunk_table_offset - sizeof(hdr);
573 res_start_offset = chunk_table_offset;
576 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
577 chunk_table_size, chunk_table_offset);
582 *res_start_offset_ret = res_start_offset;
583 *res_store_size_ret = res_end_offset - res_start_offset;
588 ERROR_WITH_ERRNO("Error writing chunk table to WIM file");
592 /* Finish writing a WIM resource by writing or updating the chunk table (if not
593 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
595 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
599 u64 res_uncompressed_size;
600 u64 res_offset_in_wim;
602 wimlib_assert(ctx->cur_write_blob_offset == ctx->cur_write_res_size ||
603 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
604 res_uncompressed_size = ctx->cur_write_res_size;
606 if (ctx->compressor) {
607 ret = end_chunk_table(ctx, res_uncompressed_size,
608 &res_offset_in_wim, &res_size_in_wim);
612 res_offset_in_wim = ctx->chunks_start_offset;
613 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
615 out_reshdr->uncompressed_size = res_uncompressed_size;
616 out_reshdr->size_in_wim = res_size_in_wim;
617 out_reshdr->offset_in_wim = res_offset_in_wim;
621 /* Call when no more data from the file at @path is needed. */
623 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
625 union wimlib_progress_info info;
627 info.done_with_file.path_to_file = path;
629 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
634 do_done_with_blob(struct blob_descriptor *blob,
635 wimlib_progress_func_t progfunc, void *progctx)
638 struct wim_inode *inode;
643 if (!blob->may_send_done_with_file)
646 inode = blob->file_inode;
648 wimlib_assert(inode != NULL);
649 wimlib_assert(inode->i_num_remaining_streams > 0);
650 if (--inode->i_num_remaining_streams > 0)
653 path = blob_file_path(blob);
655 cookie1 = progress_get_streamless_path(path);
656 cookie2 = progress_get_win32_path(path);
658 ret = done_with_file(path, progfunc, progctx);
660 progress_put_win32_path(cookie2);
661 progress_put_streamless_path(cookie1);
666 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
668 done_with_blob(struct blob_descriptor *blob, struct write_blobs_ctx *ctx)
670 if (likely(!(ctx->write_resource_flags &
671 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
673 return do_done_with_blob(blob, ctx->progress_data.progfunc,
674 ctx->progress_data.progctx);
677 /* Begin processing a blob for writing. */
679 write_blob_begin_read(struct blob_descriptor *blob, void *_ctx)
681 struct write_blobs_ctx *ctx = _ctx;
684 wimlib_assert(blob->size > 0);
686 /* As an optimization, we allow some blobs to be "unhashed", meaning
687 * their SHA-1 message digests are unknown. This is the case with blobs
688 * that are added by scanning a directory tree with wimlib_add_image(),
689 * for example. Since WIM uses single-instance blobs, we don't know
690 * whether such each such blob really need to written until it is
691 * actually checksummed, unless it has a unique size. In such cases we
692 * read and checksum the blob in this function, thereby advancing ahead
693 * of read_blob_list(), which will still provide the data again to
694 * write_blob_process_chunk(). This is okay because an unhashed blob
695 * cannot be in a WIM resource, which might be costly to decompress. */
696 if (ctx->blob_table != NULL && blob->unhashed && !blob->unique_size) {
698 struct blob_descriptor *new_blob;
700 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
703 if (new_blob != blob) {
704 /* Duplicate blob detected. */
706 if (new_blob->will_be_in_output_wim ||
707 blob_filtered(new_blob, ctx->filter_ctx))
709 /* The duplicate blob is already being included
710 * in the output WIM, or it would be filtered
711 * out if it had been. Skip writing this blob
712 * (and reading it again) entirely, passing its
713 * output reference count to the duplicate blob
714 * in the former case. */
715 ret = do_write_blobs_progress(&ctx->progress_data,
716 blob->size, 1, true);
717 list_del(&blob->write_blobs_list);
718 list_del(&blob->blob_table_list);
719 if (new_blob->will_be_in_output_wim)
720 new_blob->out_refcnt += blob->out_refcnt;
721 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
722 ctx->cur_write_res_size -= blob->size;
724 ret = done_with_blob(blob, ctx);
725 free_blob_descriptor(blob);
728 return BEGIN_BLOB_STATUS_SKIP_BLOB;
730 /* The duplicate blob can validly be written,
731 * but was not marked as such. Discard the
732 * current blob descriptor and use the
733 * duplicate, but actually freeing the current
734 * blob descriptor must wait until
735 * read_blob_list() has finished reading its
737 list_replace(&blob->write_blobs_list,
738 &new_blob->write_blobs_list);
739 list_replace(&blob->blob_table_list,
740 &new_blob->blob_table_list);
741 blob->will_be_in_output_wim = 0;
742 new_blob->out_refcnt = blob->out_refcnt;
743 new_blob->will_be_in_output_wim = 1;
744 new_blob->may_send_done_with_file = 0;
749 list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
753 /* Rewrite a blob that was just written compressed (as a non-solid WIM resource)
754 * as uncompressed instead. */
756 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
759 u64 begin_offset = blob->out_reshdr.offset_in_wim;
760 u64 end_offset = out_fd->offset;
762 if (filedes_seek(out_fd, begin_offset) == -1)
765 ret = extract_blob_to_fd(blob, out_fd);
767 /* Error reading the uncompressed data. */
768 if (out_fd->offset == begin_offset &&
769 filedes_seek(out_fd, end_offset) != -1)
771 /* Nothing was actually written yet, and we successfully
772 * seeked to the end of the compressed resource, so
773 * don't issue a hard error; just keep the compressed
774 * resource instead. */
775 WARNING("Recovered compressed resource of "
776 "size %"PRIu64", continuing on.", blob->size);
782 wimlib_assert(out_fd->offset - begin_offset == blob->size);
784 /* We could ftruncate() the file to 'out_fd->offset' here, but there
785 * isn't much point. Usually we will only be truncating by a few bytes
786 * and will just overwrite the data immediately. */
788 blob->out_reshdr.size_in_wim = blob->size;
789 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
790 WIM_RESHDR_FLAG_SOLID);
794 /* Returns true if the specified blob, which was written as a non-solid
795 * resource, should be truncated from the WIM file and re-written uncompressed.
796 * blob->out_reshdr must be filled in from the initial write of the blob. */
798 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
799 const struct blob_descriptor *blob)
801 /* If the compressed data is smaller than the uncompressed data, prefer
802 * the compressed data. */
803 if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
806 /* If we're not actually writing compressed data, then there's no need
808 if (!ctx->compressor)
811 /* If writing a pipable WIM, everything we write to the output is final
812 * (it might actually be a pipe!). */
813 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
816 /* If the blob that would need to be re-read is located in a solid
817 * resource in another WIM file, then re-reading it would be costly. So
820 * Exception: if the compressed size happens to be *exactly* the same as
821 * the uncompressed size, then the blob *must* be written uncompressed
822 * in order to remain compatible with the Windows Overlay Filesystem
823 * filter driver (WOF).
825 * TODO: we are currently assuming that the optimization for
826 * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
827 * this case from being triggered too often. To fully prevent excessive
828 * decompressions in degenerate cases, we really should obtain the
829 * uncompressed data by decompressing the compressed data we wrote to
832 if (blob->blob_location == BLOB_IN_WIM &&
833 blob->size != blob->rdesc->uncompressed_size &&
834 blob->size != blob->out_reshdr.size_in_wim)
841 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
842 struct blob_descriptor *blob)
844 if (!should_rewrite_blob_uncompressed(ctx, blob))
847 /* Regular (non-solid) WIM resources with exactly one chunk and
848 * compressed size equal to uncompressed size are exactly the same as
849 * the corresponding compressed data --- since there must be 0 entries
850 * in the chunk table and the only chunk must be stored uncompressed.
851 * In this case, there's no need to rewrite anything. */
852 if (ctx->chunk_index == 1 &&
853 blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
855 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
859 return write_blob_uncompressed(blob, ctx->out_fd);
862 /* Write the next chunk of (typically compressed) data to the output WIM,
863 * handling the writing of the chunk table. */
865 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
866 size_t csize, size_t usize)
869 struct blob_descriptor *blob;
870 u32 completed_blob_count;
873 blob = list_entry(ctx->blobs_being_compressed.next,
874 struct blob_descriptor, write_blobs_list);
876 if (ctx->cur_write_blob_offset == 0 &&
877 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
879 /* Starting to write a new blob in non-solid mode. */
881 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
882 ret = write_pwm_blob_header(blob, ctx->out_fd,
883 ctx->compressor != NULL);
888 ret = begin_write_resource(ctx, blob->size);
893 if (ctx->compressor != NULL) {
894 /* Record the compresed chunk size. */
895 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
896 ctx->chunk_csizes[ctx->chunk_index++] = csize;
898 /* If writing a pipable WIM, before the chunk data write a chunk
899 * header that provides the compressed chunk size. */
900 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
901 struct pwm_chunk_hdr chunk_hdr = {
902 .compressed_size = cpu_to_le32(csize),
904 ret = full_write(ctx->out_fd, &chunk_hdr,
911 /* Write the chunk data. */
912 ret = full_write(ctx->out_fd, cchunk, csize);
916 ctx->cur_write_blob_offset += usize;
918 completed_size = usize;
919 completed_blob_count = 0;
920 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
921 /* Wrote chunk in solid mode. It may have finished multiple
923 struct blob_descriptor *next_blob;
925 while (blob && ctx->cur_write_blob_offset >= blob->size) {
927 ctx->cur_write_blob_offset -= blob->size;
929 if (ctx->cur_write_blob_offset)
930 next_blob = list_entry(blob->write_blobs_list.next,
931 struct blob_descriptor,
936 ret = done_with_blob(blob, ctx);
939 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
940 completed_blob_count++;
945 /* Wrote chunk in non-solid mode. It may have finished a
947 if (ctx->cur_write_blob_offset == blob->size) {
949 wimlib_assert(ctx->cur_write_blob_offset ==
950 ctx->cur_write_res_size);
952 ret = end_write_resource(ctx, &blob->out_reshdr);
956 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
957 if (ctx->compressor != NULL)
958 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
960 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
964 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
966 ctx->cur_write_blob_offset = 0;
968 ret = done_with_blob(blob, ctx);
971 list_del(&blob->write_blobs_list);
972 completed_blob_count++;
976 return do_write_blobs_progress(&ctx->progress_data, completed_size,
977 completed_blob_count, false);
980 ERROR_WITH_ERRNO("Error writing chunk data to WIM file");
985 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
987 /* While we are unable to get a new chunk buffer due to too many chunks
988 * already outstanding, retrieve and write the next compressed chunk. */
989 while (!(ctx->cur_chunk_buf =
990 ctx->compressor->get_chunk_buffer(ctx->compressor)))
998 bret = ctx->compressor->get_compression_result(ctx->compressor,
1002 wimlib_assert(bret);
1004 ret = write_chunk(ctx, cchunk, csize, usize);
1011 /* Process the next chunk of data to be written to a WIM resource. */
1013 write_blob_process_chunk(const struct blob_descriptor *blob, u64 offset,
1014 const void *chunk, size_t size, void *_ctx)
1016 struct write_blobs_ctx *ctx = _ctx;
1018 const u8 *chunkptr, *chunkend;
1020 wimlib_assert(size != 0);
1022 if (ctx->compressor == NULL) {
1023 /* Write chunk uncompressed. */
1024 ret = write_chunk(ctx, chunk, size, size);
1030 /* Submit the chunk for compression, but take into account that the
1031 * @size the chunk was provided in may not correspond to the
1032 * @out_chunk_size being used for compression. */
1034 chunkend = chunkptr + size;
1036 size_t needed_chunk_size;
1037 size_t bytes_consumed;
1039 if (!ctx->cur_chunk_buf) {
1040 ret = prepare_chunk_buffer(ctx);
1045 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1046 needed_chunk_size = ctx->out_chunk_size;
1048 needed_chunk_size = min(ctx->out_chunk_size,
1049 ctx->cur_chunk_buf_filled +
1050 (blob->size - offset));
1053 bytes_consumed = min(chunkend - chunkptr,
1054 needed_chunk_size - ctx->cur_chunk_buf_filled);
1056 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1057 chunkptr, bytes_consumed);
1059 chunkptr += bytes_consumed;
1060 offset += bytes_consumed;
1061 ctx->cur_chunk_buf_filled += bytes_consumed;
1063 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1064 ctx->compressor->signal_chunk_filled(ctx->compressor,
1065 ctx->cur_chunk_buf_filled);
1066 ctx->cur_chunk_buf = NULL;
1067 ctx->cur_chunk_buf_filled = 0;
1069 } while (chunkptr != chunkend);
1073 /* Finish processing a blob for writing. It may not have been completely
1074 * written yet, as the chunk_compressor implementation may still have chunks
1075 * buffered or being compressed. */
1077 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1079 struct write_blobs_ctx *ctx = _ctx;
1081 if (!blob->will_be_in_output_wim) {
1082 /* The blob was a duplicate. Now that its data has finished
1083 * being read, it is being discarded in favor of the duplicate
1084 * entry. It therefore is no longer needed, and we can fire the
1085 * DONE_WITH_FILE callback because the file will not be read
1088 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1089 * blobs, since it needs to be possible to re-read the file if
1090 * it does not compress to less than its original size. */
1092 status = done_with_blob(blob, ctx);
1093 free_blob_descriptor(blob);
1094 } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1095 /* The blob was not a duplicate and was previously unhashed.
1096 * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1097 * read_blob_list(), blob->hash is now computed and valid. So
1098 * turn this blob into a "hashed" blob. */
1099 list_del(&blob->unhashed_list);
1100 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 * For compactions, also verify that there are no overlapping resources. This
1113 * really should be checked earlier, but for now it's easiest to check here.
1116 compute_blob_list_stats(struct list_head *blob_list,
1117 struct write_blobs_ctx *ctx)
1119 struct blob_descriptor *blob;
1120 u64 total_bytes = 0;
1122 u64 total_parts = 0;
1123 WIMStruct *prev_wim_part = NULL;
1124 const struct wim_resource_descriptor *prev_rdesc = NULL;
1126 list_for_each_entry(blob, blob_list, write_blobs_list) {
1128 total_bytes += blob->size;
1129 if (blob->blob_location == BLOB_IN_WIM) {
1130 const struct wim_resource_descriptor *rdesc = blob->rdesc;
1131 WIMStruct *wim = rdesc->wim;
1133 if (prev_wim_part != wim) {
1134 prev_wim_part = wim;
1137 if (unlikely(wim->being_compacted) && rdesc != prev_rdesc) {
1138 if (prev_rdesc != NULL &&
1139 rdesc->offset_in_wim <
1140 prev_rdesc->offset_in_wim +
1141 prev_rdesc->size_in_wim)
1143 WARNING("WIM file contains overlapping "
1144 "resources! Compaction is not "
1146 return WIMLIB_ERR_RESOURCE_ORDER;
1152 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1153 ctx->progress_data.progress.write_streams.total_streams = num_blobs;
1154 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1155 ctx->progress_data.progress.write_streams.completed_streams = 0;
1156 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1157 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1158 ctx->progress_data.progress.write_streams.completed_parts = 0;
1159 ctx->progress_data.next_progress = 0;
1163 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1164 * rather than compressed. Delete these blobs from @blob_list and move them to
1165 * @raw_copy_blobs. Return the total uncompressed size of the blobs that need
1166 * to be compressed. */
1168 find_raw_copy_blobs(struct list_head *blob_list, int write_resource_flags,
1169 int out_ctype, u32 out_chunk_size,
1170 struct list_head *raw_copy_blobs)
1172 struct blob_descriptor *blob, *tmp;
1173 u64 num_nonraw_bytes = 0;
1175 INIT_LIST_HEAD(raw_copy_blobs);
1177 /* Initialize temporary raw_copy_ok flag. */
1178 list_for_each_entry(blob, blob_list, write_blobs_list)
1179 if (blob->blob_location == BLOB_IN_WIM)
1180 blob->rdesc->raw_copy_ok = 0;
1182 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1183 if (can_raw_copy(blob, write_resource_flags,
1184 out_ctype, out_chunk_size))
1186 blob->rdesc->raw_copy_ok = 1;
1187 list_move_tail(&blob->write_blobs_list, raw_copy_blobs);
1189 num_nonraw_bytes += blob->size;
1193 return num_nonraw_bytes;
1196 /* Copy a raw compressed resource located in another WIM file to the WIM file
1199 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1200 struct filedes *out_fd)
1202 u64 cur_read_offset;
1203 u64 end_read_offset;
1204 u8 buf[BUFFER_SIZE];
1205 size_t bytes_to_read;
1207 struct filedes *in_fd;
1208 struct blob_descriptor *blob;
1209 u64 out_offset_in_wim;
1211 /* Copy the raw data. */
1212 cur_read_offset = in_rdesc->offset_in_wim;
1213 end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1215 out_offset_in_wim = out_fd->offset;
1217 if (in_rdesc->is_pipable) {
1218 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1219 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1220 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1221 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1223 in_fd = &in_rdesc->wim->in_fd;
1224 wimlib_assert(cur_read_offset != end_read_offset);
1226 if (likely(!in_rdesc->wim->being_compacted) ||
1227 in_rdesc->offset_in_wim > out_fd->offset) {
1229 bytes_to_read = min(sizeof(buf),
1230 end_read_offset - cur_read_offset);
1232 ret = full_pread(in_fd, buf, bytes_to_read,
1235 ERROR_WITH_ERRNO("Error reading raw data "
1240 ret = full_write(out_fd, buf, bytes_to_read);
1242 ERROR_WITH_ERRNO("Error writing raw data "
1247 cur_read_offset += bytes_to_read;
1249 } while (cur_read_offset != end_read_offset);
1251 /* Optimization: the WIM file is being compacted and the
1252 * resource being written is already in the desired location.
1253 * Skip over the data instead of re-writing it. */
1255 /* Due the earlier check for overlapping resources, it should
1256 * never be the case that we already overwrote the resource. */
1257 wimlib_assert(!(in_rdesc->offset_in_wim < out_fd->offset));
1259 if (-1 == filedes_seek(out_fd, out_fd->offset + in_rdesc->size_in_wim))
1260 return WIMLIB_ERR_WRITE;
1263 list_for_each_entry(blob, &in_rdesc->blob_list, rdesc_node) {
1264 if (blob->will_be_in_output_wim) {
1265 blob_set_out_reshdr_for_reuse(blob);
1266 if (in_rdesc->flags & WIM_RESHDR_FLAG_SOLID)
1267 blob->out_res_offset_in_wim = out_offset_in_wim;
1269 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1276 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1277 * WIM file being written. */
1279 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1280 struct filedes *out_fd,
1281 struct write_blobs_progress_data *progress_data)
1283 struct blob_descriptor *blob;
1286 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1287 blob->rdesc->raw_copy_ok = 1;
1289 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list) {
1290 if (blob->rdesc->raw_copy_ok) {
1291 /* Write each solid resource only one time. */
1292 ret = write_raw_copy_resource(blob->rdesc, out_fd);
1295 blob->rdesc->raw_copy_ok = 0;
1297 ret = do_write_blobs_progress(progress_data, blob->size,
1305 /* Wait for and write all chunks pending in the compressor. */
1307 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1314 if (ctx->compressor == NULL)
1317 if (ctx->cur_chunk_buf_filled != 0) {
1318 ctx->compressor->signal_chunk_filled(ctx->compressor,
1319 ctx->cur_chunk_buf_filled);
1322 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1325 ret = write_chunk(ctx, cdata, csize, usize);
1333 validate_blob_list(struct list_head *blob_list)
1335 struct blob_descriptor *blob;
1337 list_for_each_entry(blob, blob_list, write_blobs_list) {
1338 wimlib_assert(blob->will_be_in_output_wim);
1339 wimlib_assert(blob->size != 0);
1344 init_done_with_file_info(struct list_head *blob_list)
1346 struct blob_descriptor *blob;
1348 list_for_each_entry(blob, blob_list, write_blobs_list) {
1349 if (blob_is_in_file(blob)) {
1350 blob->file_inode->i_num_remaining_streams = 0;
1351 blob->may_send_done_with_file = 1;
1353 blob->may_send_done_with_file = 0;
1357 list_for_each_entry(blob, blob_list, write_blobs_list)
1358 if (blob->may_send_done_with_file)
1359 blob->file_inode->i_num_remaining_streams++;
1363 * Write a list of blobs to the output WIM file.
1366 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1367 * by the 'write_blobs_list' member.
1370 * The file descriptor, opened for writing, to which to write the blobs.
1372 * @write_resource_flags
1373 * Flags to modify how the blobs are written:
1375 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1376 * Force compression of all resources, even if they could otherwise
1377 * be re-used by copying the raw data, due to being located in a WIM
1378 * file with compatible compression parameters.
1380 * WRITE_RESOURCE_FLAG_PIPABLE:
1381 * Write the resources in the wimlib-specific pipable format, and
1382 * furthermore do so in such a way that no seeking backwards in
1383 * @out_fd will be performed (so it may be a pipe).
1385 * WRITE_RESOURCE_FLAG_SOLID:
1386 * Combine all the blobs into a single resource rather than writing
1387 * them in separate resources. This flag is only valid if the WIM
1388 * version number has been, or will be, set to WIM_VERSION_SOLID.
1389 * This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1392 * Compression format to use in the output resources, specified as one of
1393 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
1397 * Compression chunk size to use in the output resources. It must be a
1398 * valid chunk size for the specified compression format @out_ctype, unless
1399 * @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1403 * Number of threads to use to compress data. If 0, a default number of
1404 * threads will be chosen. The number of threads still may be decreased
1405 * from the specified value if insufficient memory is detected.
1408 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1409 * must be pointer to the blob table for the WIMStruct on whose behalf the
1410 * blobs are being written. Otherwise, this parameter can be NULL.
1413 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1414 * can be a pointer to a context for blob filtering used to detect whether
1415 * the duplicate blob has been hard-filtered or not. If no blobs are
1416 * hard-filtered or no blobs are unhashed, this parameter can be NULL.
1418 * This function will write the blobs in @blob_list to resources in
1419 * consecutive positions in the output WIM file, or to a single solid resource
1420 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1421 * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1422 * updated to specify its location, size, and flags in the output WIM. In the
1423 * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1424 * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1425 * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1426 * respectively, in the output WIM of the solid resource containing the
1427 * corresponding blob.
1429 * Each of the blobs to write may be in any location supported by the
1430 * resource-handling code (specifically, read_blob_list()), such as the contents
1431 * of external file that has been logically added to the output WIM, or a blob
1432 * in another WIM file that has been imported, or even a blob in the "same" WIM
1433 * file of which a modified copy is being written. In the case that a blob is
1434 * already in a WIM file and uses compatible compression parameters, by default
1435 * this function will re-use the raw data instead of decompressing it, then
1436 * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1437 * specified in @write_resource_flags, this is not done.
1439 * As a further requirement, this function requires that the
1440 * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1441 * as any other blobs not in @blob_list that will be in the output WIM file, but
1442 * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1443 * resource with a blob in @blob_list. Still furthermore, if on-the-fly
1444 * deduplication of blobs is possible, then all blobs in @blob_list must also be
1445 * linked by @blob_table_list along with any other blobs that have
1446 * @will_be_in_output_wim set.
1448 * This function handles on-the-fly deduplication of blobs for which SHA-1
1449 * message digests have not yet been calculated. Such blobs may or may not need
1450 * to be written. If @blob_table is non-NULL, then each blob in @blob_list that
1451 * has @unhashed set but not @unique_size set is checksummed immediately before
1452 * it would otherwise be read for writing in order to determine if it is
1453 * identical to another blob already being written or one that would be filtered
1454 * out of the output WIM using blob_filtered() with the context @filter_ctx.
1455 * Each such duplicate blob will be removed from @blob_list, its reference count
1456 * transferred to the pre-existing duplicate blob, its memory freed, and will
1457 * not be written. Alternatively, if a blob in @blob_list is a duplicate with
1458 * any blob in @blob_table that has not been marked for writing or would not be
1459 * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1460 * taking ownership of the reference count and slot in the @blob_table_list.
1462 * Returns 0 if every blob was either written successfully or did not need to be
1463 * written; otherwise returns a non-zero error code.
1466 write_blob_list(struct list_head *blob_list,
1467 struct filedes *out_fd,
1468 int write_resource_flags,
1471 unsigned num_threads,
1472 struct blob_table *blob_table,
1473 struct filter_context *filter_ctx,
1474 wimlib_progress_func_t progfunc,
1478 struct write_blobs_ctx ctx;
1479 struct list_head raw_copy_blobs;
1480 u64 num_nonraw_bytes;
1482 wimlib_assert((write_resource_flags &
1483 (WRITE_RESOURCE_FLAG_SOLID |
1484 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1485 (WRITE_RESOURCE_FLAG_SOLID |
1486 WRITE_RESOURCE_FLAG_PIPABLE));
1488 validate_blob_list(blob_list);
1490 if (list_empty(blob_list))
1493 /* If needed, set auxiliary information so that we can detect when the
1494 * library has finished using each external file. */
1495 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1496 init_done_with_file_info(blob_list);
1498 memset(&ctx, 0, sizeof(ctx));
1500 ctx.out_fd = out_fd;
1501 ctx.blob_table = blob_table;
1502 ctx.out_ctype = out_ctype;
1503 ctx.out_chunk_size = out_chunk_size;
1504 ctx.write_resource_flags = write_resource_flags;
1505 ctx.filter_ctx = filter_ctx;
1508 * We normally sort the blobs to write by a "sequential" order that is
1509 * optimized for reading. But when using solid compression, we instead
1510 * sort the blobs by file extension and file name (when applicable; and
1511 * we don't do this for blobs from solid resources) so that similar
1512 * files are grouped together, which improves the compression ratio.
1513 * This is somewhat of a hack since a blob does not necessarily
1514 * correspond one-to-one with a filename, nor is there any guarantee
1515 * that two files with similar names or extensions are actually similar
1516 * in content. A potential TODO is to sort the blobs based on some
1517 * measure of similarity of their actual contents.
1520 ret = sort_blob_list_by_sequential_order(blob_list,
1521 offsetof(struct blob_descriptor,
1526 ret = compute_blob_list_stats(blob_list, &ctx);
1530 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1531 ret = sort_blob_list_for_solid_compression(blob_list);
1533 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1536 ctx.progress_data.progfunc = progfunc;
1537 ctx.progress_data.progctx = progctx;
1539 num_nonraw_bytes = find_raw_copy_blobs(blob_list, write_resource_flags,
1540 out_ctype, out_chunk_size,
1543 /* Unless no data needs to be compressed, allocate a chunk_compressor to
1544 * do compression. There are serial and parallel implementations of the
1545 * chunk_compressor interface. We default to parallel using the
1546 * specified number of threads, unless the upper bound on the number
1547 * bytes needing to be compressed is less than a heuristic value. */
1548 if (num_nonraw_bytes != 0 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1549 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1550 if (num_nonraw_bytes > max(2000000, out_chunk_size)) {
1551 ret = new_parallel_chunk_compressor(out_ctype,
1556 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1557 " Falling back to single-threaded compression.",
1558 wimlib_get_error_string(ret));
1563 if (ctx.compressor == NULL) {
1564 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1567 goto out_destroy_context;
1572 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1574 ctx.progress_data.progress.write_streams.num_threads = 1;
1576 ret = call_progress(ctx.progress_data.progfunc,
1577 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1578 &ctx.progress_data.progress,
1579 ctx.progress_data.progctx);
1581 goto out_destroy_context;
1583 /* Copy any compressed resources for which the raw data can be reused
1584 * without decompression. */
1585 ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1586 &ctx.progress_data);
1588 if (ret || num_nonraw_bytes == 0)
1589 goto out_destroy_context;
1591 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1593 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1595 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1597 ret = begin_write_resource(&ctx, num_nonraw_bytes);
1599 goto out_destroy_context;
1602 /* Read the list of blobs needing to be compressed, using the specified
1603 * callbacks to execute processing of the data. */
1605 struct read_blob_callbacks cbs = {
1606 .begin_blob = write_blob_begin_read,
1607 .continue_blob = write_blob_process_chunk,
1608 .end_blob = write_blob_end_read,
1612 ret = read_blob_list(blob_list,
1613 offsetof(struct blob_descriptor, write_blobs_list),
1615 BLOB_LIST_ALREADY_SORTED |
1616 VERIFY_BLOB_HASHES |
1617 COMPUTE_MISSING_BLOB_HASHES);
1620 goto out_destroy_context;
1622 ret = finish_remaining_chunks(&ctx);
1624 goto out_destroy_context;
1626 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1627 struct wim_reshdr reshdr;
1628 struct blob_descriptor *blob;
1631 ret = end_write_resource(&ctx, &reshdr);
1633 goto out_destroy_context;
1636 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1637 blob->out_reshdr.size_in_wim = blob->size;
1638 blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1639 WIM_RESHDR_FLAG_SOLID;
1640 blob->out_reshdr.uncompressed_size = 0;
1641 blob->out_reshdr.offset_in_wim = offset_in_res;
1642 blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1643 blob->out_res_size_in_wim = reshdr.size_in_wim;
1644 blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1645 offset_in_res += blob->size;
1647 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1650 out_destroy_context:
1651 FREE(ctx.chunk_csizes);
1653 ctx.compressor->destroy(ctx.compressor);
1659 write_file_data_blobs(WIMStruct *wim,
1660 struct list_head *blob_list,
1662 unsigned num_threads,
1663 struct filter_context *filter_ctx)
1667 int write_resource_flags;
1669 write_resource_flags = write_flags_to_resource_flags(write_flags);
1671 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1672 out_chunk_size = wim->out_solid_chunk_size;
1673 out_ctype = wim->out_solid_compression_type;
1675 out_chunk_size = wim->out_chunk_size;
1676 out_ctype = wim->out_compression_type;
1679 return write_blob_list(blob_list,
1681 write_resource_flags,
1691 /* Write the contents of the specified blob as a WIM resource. */
1693 write_wim_resource(struct blob_descriptor *blob,
1694 struct filedes *out_fd,
1697 int write_resource_flags)
1699 LIST_HEAD(blob_list);
1700 list_add(&blob->write_blobs_list, &blob_list);
1701 blob->will_be_in_output_wim = 1;
1702 return write_blob_list(&blob_list,
1704 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1714 /* Write the contents of the specified buffer as a WIM resource. */
1716 write_wim_resource_from_buffer(const void *buf,
1719 struct filedes *out_fd,
1722 struct wim_reshdr *out_reshdr,
1724 int write_resource_flags)
1727 struct blob_descriptor blob;
1729 if (unlikely(buf_size == 0)) {
1730 zero_reshdr(out_reshdr);
1732 copy_hash(hash_ret, zero_hash);
1736 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1737 sha1_buffer(buf, buf_size, blob.hash);
1739 blob.is_metadata = is_metadata;
1741 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1742 write_resource_flags);
1746 copy_reshdr(out_reshdr, &blob.out_reshdr);
1749 copy_hash(hash_ret, blob.hash);
1753 struct blob_size_table {
1754 struct hlist_head *array;
1760 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1762 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1763 if (tab->array == NULL)
1764 return WIMLIB_ERR_NOMEM;
1765 tab->num_entries = 0;
1766 tab->capacity = capacity;
1771 destroy_blob_size_table(struct blob_size_table *tab)
1777 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1779 struct blob_size_table *tab = _tab;
1781 struct blob_descriptor *same_size_blob;
1783 pos = hash_u64(blob->size) % tab->capacity;
1784 blob->unique_size = 1;
1785 hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1786 if (same_size_blob->size == blob->size) {
1787 blob->unique_size = 0;
1788 same_size_blob->unique_size = 0;
1793 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1798 struct find_blobs_ctx {
1801 struct list_head blob_list;
1802 struct blob_size_table blob_size_tab;
1806 reference_blob_for_write(struct blob_descriptor *blob,
1807 struct list_head *blob_list, u32 nref)
1809 if (!blob->will_be_in_output_wim) {
1810 blob->out_refcnt = 0;
1811 list_add_tail(&blob->write_blobs_list, blob_list);
1812 blob->will_be_in_output_wim = 1;
1814 blob->out_refcnt += nref;
1818 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1820 struct list_head *blob_list = _blob_list;
1821 blob->will_be_in_output_wim = 0;
1822 reference_blob_for_write(blob, blob_list, blob->refcnt);
1827 inode_find_blobs_to_reference(const struct wim_inode *inode,
1828 const struct blob_table *table,
1829 struct list_head *blob_list)
1831 wimlib_assert(inode->i_nlink > 0);
1833 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1834 struct blob_descriptor *blob;
1837 blob = stream_blob(&inode->i_streams[i], table);
1839 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1841 hash = stream_hash(&inode->i_streams[i]);
1842 if (!is_zero_hash(hash))
1843 return blob_not_found_error(inode, hash);
1850 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1852 blob->will_be_in_output_wim = 0;
1857 image_find_blobs_to_reference(WIMStruct *wim)
1859 struct wim_image_metadata *imd;
1860 struct wim_inode *inode;
1861 struct blob_descriptor *blob;
1862 struct list_head *blob_list;
1865 imd = wim_get_current_image_metadata(wim);
1867 image_for_each_unhashed_blob(blob, imd)
1868 blob->will_be_in_output_wim = 0;
1870 blob_list = wim->private;
1871 image_for_each_inode(inode, imd) {
1872 ret = inode_find_blobs_to_reference(inode,
1882 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1885 struct list_head *blob_list_ret)
1889 INIT_LIST_HEAD(blob_list_ret);
1891 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1892 (image == 1 && wim->hdr.image_count == 1)))
1894 /* Fast case: Assume that all blobs are being written and that
1895 * the reference counts are correct. */
1896 struct blob_descriptor *blob;
1897 struct wim_image_metadata *imd;
1900 for_blob_in_table(wim->blob_table,
1901 fully_reference_blob_for_write,
1904 for (i = 0; i < wim->hdr.image_count; i++) {
1905 imd = wim->image_metadata[i];
1906 image_for_each_unhashed_blob(blob, imd)
1907 fully_reference_blob_for_write(blob, blob_list_ret);
1910 /* Slow case: Walk through the images being written and
1911 * determine the blobs referenced. */
1912 for_blob_in_table(wim->blob_table,
1913 do_blob_set_not_in_output_wim, NULL);
1914 wim->private = blob_list_ret;
1915 ret = for_image(wim, image, image_find_blobs_to_reference);
1923 struct insert_other_if_hard_filtered_ctx {
1924 struct blob_size_table *tab;
1925 struct filter_context *filter_ctx;
1929 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1931 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1933 if (!blob->will_be_in_output_wim &&
1934 blob_hard_filtered(blob, ctx->filter_ctx))
1935 blob_size_table_insert(blob, ctx->tab);
1940 determine_blob_size_uniquity(struct list_head *blob_list,
1941 struct blob_table *lt,
1942 struct filter_context *filter_ctx)
1945 struct blob_size_table tab;
1946 struct blob_descriptor *blob;
1948 ret = init_blob_size_table(&tab, 9001);
1952 if (may_hard_filter_blobs(filter_ctx)) {
1953 struct insert_other_if_hard_filtered_ctx ctx = {
1955 .filter_ctx = filter_ctx,
1957 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
1960 list_for_each_entry(blob, blob_list, write_blobs_list)
1961 blob_size_table_insert(blob, &tab);
1963 destroy_blob_size_table(&tab);
1968 filter_blob_list_for_write(struct list_head *blob_list,
1969 struct filter_context *filter_ctx)
1971 struct blob_descriptor *blob, *tmp;
1973 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1974 int status = blob_filtered(blob, filter_ctx);
1981 /* Soft filtered. */
1983 /* Hard filtered. */
1984 blob->will_be_in_output_wim = 0;
1985 list_del(&blob->blob_table_list);
1987 list_del(&blob->write_blobs_list);
1993 * prepare_blob_list_for_write() -
1995 * Prepare the list of blobs to write for writing a WIM containing the specified
1996 * image(s) with the specified write flags.
1999 * The WIMStruct on whose behalf the write is occurring.
2002 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2005 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2007 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
2008 * table of @wim and the per-image lists of unhashed blobs should be taken
2009 * as-is, and image metadata should not be searched for references. This
2010 * does not exclude filtering with APPEND and SKIP_EXTERNAL_WIMS, below.
2012 * APPEND: Blobs already present in @wim shall not be returned in
2015 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
2016 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
2019 * List of blobs, linked by write_blobs_list, that need to be written will
2022 * Note that this function assumes that unhashed blobs will be written; it
2023 * does not take into account that they may become duplicates when actually
2026 * @blob_table_list_ret
2027 * List of blobs, linked by blob_table_list, that need to be included in
2028 * the WIM's blob table will be returned here. This will be a superset of
2029 * the blobs in @blob_list_ret.
2031 * This list will be a proper superset of @blob_list_ret if and only if
2032 * WIMLIB_WRITE_FLAG_APPEND was specified in @write_flags and some of the
2033 * blobs that would otherwise need to be written were already located in
2036 * All blobs in this list will have @out_refcnt set to the number of
2037 * references to the blob in the output WIM. If
2038 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2039 * may be as low as 0.
2042 * A context for queries of blob filter status with blob_filtered() is
2043 * returned in this location.
2045 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2046 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2047 * inserted into @blob_table_list_ret.
2049 * Still furthermore, @unique_size will be set to 1 on all blobs in
2050 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2051 * among all blobs in the blob table of @wim that are ineligible for being
2052 * written due to filtering.
2054 * Returns 0 on success; nonzero on read error, memory allocation error, or
2058 prepare_blob_list_for_write(WIMStruct *wim, int image,
2060 struct list_head *blob_list_ret,
2061 struct list_head *blob_table_list_ret,
2062 struct filter_context *filter_ctx_ret)
2065 struct blob_descriptor *blob;
2067 filter_ctx_ret->write_flags = write_flags;
2068 filter_ctx_ret->wim = wim;
2070 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2073 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2078 INIT_LIST_HEAD(blob_table_list_ret);
2079 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2080 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2082 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2087 if (may_filter_blobs(filter_ctx_ret))
2088 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2094 write_file_data(WIMStruct *wim, int image, int write_flags,
2095 unsigned num_threads,
2096 struct list_head *blob_list_override,
2097 struct list_head *blob_table_list_ret)
2100 struct list_head _blob_list;
2101 struct list_head *blob_list;
2102 struct blob_descriptor *blob;
2103 struct filter_context _filter_ctx;
2104 struct filter_context *filter_ctx;
2106 if (blob_list_override == NULL) {
2107 /* Normal case: prepare blob list from image(s) being written.
2109 blob_list = &_blob_list;
2110 filter_ctx = &_filter_ctx;
2111 ret = prepare_blob_list_for_write(wim, image, write_flags,
2113 blob_table_list_ret,
2118 /* Currently only as a result of wimlib_split() being called:
2119 * use blob list already explicitly provided. Use existing
2120 * reference counts. */
2121 blob_list = blob_list_override;
2123 INIT_LIST_HEAD(blob_table_list_ret);
2124 list_for_each_entry(blob, blob_list, write_blobs_list) {
2125 blob->out_refcnt = blob->refcnt;
2126 blob->will_be_in_output_wim = 1;
2127 blob->unique_size = 0;
2128 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2132 return write_file_data_blobs(wim,
2140 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2145 int write_resource_flags;
2147 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2150 write_resource_flags = write_flags_to_resource_flags(write_flags);
2152 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2154 ret = call_progress(wim->progfunc,
2155 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2156 NULL, wim->progctx);
2160 if (image == WIMLIB_ALL_IMAGES) {
2162 end_image = wim->hdr.image_count;
2164 start_image = image;
2168 for (int i = start_image; i <= end_image; i++) {
2169 struct wim_image_metadata *imd;
2171 imd = wim->image_metadata[i - 1];
2172 if (is_image_dirty(imd)) {
2173 /* The image was modified from the original, or was
2174 * newly added, so we have to build and write a new
2175 * metadata resource. */
2176 ret = write_metadata_resource(wim, i,
2177 write_resource_flags);
2178 } else if (is_image_unchanged_from_wim(imd, wim) &&
2179 (write_flags & (WIMLIB_WRITE_FLAG_UNSAFE_COMPACT |
2180 WIMLIB_WRITE_FLAG_APPEND)))
2182 /* The metadata resource is already in the WIM file.
2183 * For appends, we don't need to write it at all. For
2184 * compactions, we re-write existing metadata resources
2185 * along with the existing file resources, not here. */
2186 if (write_flags & WIMLIB_WRITE_FLAG_APPEND)
2187 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2190 /* The metadata resource is in a WIM file other than the
2191 * one being written to. We need to rewrite it,
2192 * possibly compressed differently; but rebuilding the
2193 * metadata itself isn't necessary. */
2194 ret = write_wim_resource(imd->metadata_blob,
2196 wim->out_compression_type,
2197 wim->out_chunk_size,
2198 write_resource_flags);
2204 return call_progress(wim->progfunc,
2205 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2206 NULL, wim->progctx);
2210 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2212 int raw_fd = topen(path, open_flags | O_BINARY, 0644);
2214 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2215 return WIMLIB_ERR_OPEN;
2217 filedes_init(&wim->out_fd, raw_fd);
2222 close_wim_writable(WIMStruct *wim, int write_flags)
2226 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2227 if (filedes_valid(&wim->out_fd))
2228 if (filedes_close(&wim->out_fd))
2229 ret = WIMLIB_ERR_WRITE;
2230 filedes_invalidate(&wim->out_fd);
2235 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2237 const struct blob_descriptor *blob1, *blob2;
2239 blob1 = *(const struct blob_descriptor**)p1;
2240 blob2 = *(const struct blob_descriptor**)p2;
2242 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2243 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2244 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2245 return cmp_u64(blob1->out_res_offset_in_wim,
2246 blob2->out_res_offset_in_wim);
2251 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2254 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2255 blob2->out_reshdr.offset_in_wim);
2259 write_blob_table(WIMStruct *wim, int image, int write_flags,
2260 struct list_head *blob_table_list)
2264 /* Set output resource metadata for blobs already present in WIM. */
2265 if (write_flags & WIMLIB_WRITE_FLAG_APPEND) {
2266 struct blob_descriptor *blob;
2267 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2268 if (blob->blob_location == BLOB_IN_WIM &&
2269 blob->rdesc->wim == wim)
2271 blob_set_out_reshdr_for_reuse(blob);
2276 ret = sort_blob_list(blob_table_list,
2277 offsetof(struct blob_descriptor, blob_table_list),
2278 cmp_blobs_by_out_rdesc);
2282 /* Add entries for metadata resources. */
2283 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2287 if (image == WIMLIB_ALL_IMAGES) {
2289 end_image = wim->hdr.image_count;
2291 start_image = image;
2295 /* Push metadata blob table entries onto the front of the list
2296 * in reverse order, so that they're written in order.
2298 for (int i = end_image; i >= start_image; i--) {
2299 struct blob_descriptor *metadata_blob;
2301 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2302 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2303 metadata_blob->out_refcnt = 1;
2304 list_add(&metadata_blob->blob_table_list, blob_table_list);
2308 return write_blob_table_from_blob_list(blob_table_list,
2310 wim->out_hdr.part_number,
2311 &wim->out_hdr.blob_table_reshdr,
2312 write_flags_to_resource_flags(write_flags));
2316 * Finish writing a WIM file: write the blob table, xml data, and integrity
2317 * table, then overwrite the WIM header.
2319 * The output file descriptor is closed on success, except when writing to a
2320 * user-specified file descriptor (WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR set).
2323 finish_write(WIMStruct *wim, int image, int write_flags,
2324 struct list_head *blob_table_list)
2326 int write_resource_flags;
2327 off_t old_blob_table_end = 0;
2328 struct integrity_table *old_integrity_table = NULL;
2329 off_t new_blob_table_end;
2333 write_resource_flags = write_flags_to_resource_flags(write_flags);
2335 /* In the WIM header, there is room for the resource entry for a
2336 * metadata resource labeled as the "boot metadata". This entry should
2337 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2338 * it should be a copy of the resource entry for the image that is
2339 * marked as bootable. */
2340 if (wim->out_hdr.boot_idx == 0) {
2341 zero_reshdr(&wim->out_hdr.boot_metadata_reshdr);
2343 copy_reshdr(&wim->out_hdr.boot_metadata_reshdr,
2344 &wim->image_metadata[
2345 wim->out_hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2348 /* If appending to a WIM file containing an integrity table, we'd like
2349 * to re-use the information in the old integrity table instead of
2350 * recalculating it. But we might overwrite the old integrity table
2351 * when we expand the XML data. Read it into memory just in case. */
2352 if ((write_flags & (WIMLIB_WRITE_FLAG_APPEND |
2353 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2354 (WIMLIB_WRITE_FLAG_APPEND |
2355 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2356 && wim_has_integrity_table(wim))
2358 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2359 wim->hdr.blob_table_reshdr.size_in_wim;
2360 (void)read_integrity_table(wim,
2361 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2362 &old_integrity_table);
2363 /* If we couldn't read the old integrity table, we can still
2364 * re-calculate the full integrity table ourselves. Hence the
2365 * ignoring of the return value. */
2368 /* Write blob table if needed. */
2369 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
2370 ret = write_blob_table(wim, image, write_flags,
2376 /* Write XML data. */
2377 xml_totalbytes = wim->out_fd.offset;
2378 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2379 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2380 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2381 &wim->out_hdr.xml_data_reshdr,
2382 write_resource_flags);
2386 /* Write integrity table if needed. */
2387 if ((write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) &&
2388 wim->out_hdr.blob_table_reshdr.offset_in_wim != 0)
2390 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS) {
2391 /* The XML data we wrote may have overwritten part of
2392 * the old integrity table, so while calculating the new
2393 * integrity table we should temporarily update the WIM
2394 * header to remove the integrity table reference. */
2395 struct wim_header checkpoint_hdr;
2396 memcpy(&checkpoint_hdr, &wim->out_hdr, sizeof(struct wim_header));
2397 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2398 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2399 ret = write_wim_header(&checkpoint_hdr, &wim->out_fd, 0);
2404 new_blob_table_end = wim->out_hdr.blob_table_reshdr.offset_in_wim +
2405 wim->out_hdr.blob_table_reshdr.size_in_wim;
2407 ret = write_integrity_table(wim,
2410 old_integrity_table);
2414 /* No integrity table. */
2415 zero_reshdr(&wim->out_hdr.integrity_table_reshdr);
2418 /* Now that all information in the WIM header has been determined, the
2419 * preliminary header written earlier can be overwritten, the header of
2420 * the existing WIM file can be overwritten, or the final header can be
2421 * written to the end of the pipable WIM. */
2422 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2423 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2424 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2426 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, 0);
2430 ret = WIMLIB_ERR_WRITE;
2431 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)) {
2432 /* Truncate any data the compaction freed up. */
2433 if (ftruncate(wim->out_fd.fd, wim->out_fd.offset) &&
2434 errno != EINVAL) /* allow compaction on untruncatable files,
2435 e.g. block devices */
2437 ERROR_WITH_ERRNO("Failed to truncate the output WIM file");
2442 /* Possibly sync file data to disk before closing. On POSIX systems, it
2443 * is necessary to do this before using rename() to overwrite an
2444 * existing file with a new file. Otherwise, data loss would occur if
2445 * the system is abruptly terminated when the metadata for the rename
2446 * operation has been written to disk, but the new file data has not.
2448 ret = WIMLIB_ERR_WRITE;
2449 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2450 if (fsync(wim->out_fd.fd)) {
2451 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2456 ret = WIMLIB_ERR_WRITE;
2457 if (close_wim_writable(wim, write_flags)) {
2458 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2464 free_integrity_table(old_integrity_table);
2468 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2470 /* Set advisory lock on WIM file (if not already done so) */
2472 lock_wim_for_append(WIMStruct *wim)
2474 if (wim->locked_for_append)
2476 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2477 wim->locked_for_append = 1;
2480 if (errno != EWOULDBLOCK)
2482 return WIMLIB_ERR_ALREADY_LOCKED;
2485 /* Remove advisory lock on WIM file (if present) */
2487 unlock_wim_for_append(WIMStruct *wim)
2489 if (wim->locked_for_append) {
2490 flock(wim->in_fd.fd, LOCK_UN);
2491 wim->locked_for_append = 0;
2497 * write_pipable_wim():
2499 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2500 * capable of being applied from a pipe).
2502 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2503 * images can be applied from them sequentially when the file data is sent over
2504 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2505 * The modifications made to the WIM format for pipable WIMs are:
2507 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2508 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2509 * stops other software from trying to read the file as a normal WIM.
2511 * - The header at the beginning of the file does not contain all the normal
2512 * information; in particular it will have all 0's for the blob table and XML
2513 * data resource entries. This is because this information cannot be
2514 * determined until the blob table and XML data have been written.
2515 * Consequently, wimlib will write the full header at the very end of the
2516 * file. The header at the end, however, is only used when reading the WIM
2517 * from a seekable file (not a pipe).
2519 * - An extra copy of the XML data is placed directly after the header. This
2520 * allows image names and sizes to be determined at an appropriate time when
2521 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2522 * WIM is read from a seekable file (not a pipe).
2524 * - Solid resources are not allowed. Each blob is always stored in its own
2527 * - The format of resources, or blobs, has been modified to allow them to be
2528 * used before the "blob table" has been read. Each blob is prefixed with a
2529 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2530 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2531 * uncompressed blob size, and flags that indicate whether the blob is
2532 * compressed. The data of uncompressed blobs then follows literally, while
2533 * the data of compressed blobs follows in a modified format. Compressed
2534 * blobs do not begin with a chunk table, since the chunk table cannot be
2535 * written until all chunks have been compressed. Instead, each compressed
2536 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2537 * Furthermore, the chunk table is written at the end of the resource instead
2538 * of the start. Note: chunk offsets are given in the chunk table as if the
2539 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2540 * used if the WIM is being read from a seekable file (not a pipe).
2542 * - Metadata blobs always come before non-metadata blobs. (This does not by
2543 * itself constitute an incompatibility with normal WIMs, since this is valid
2546 * - At least up to the end of the blobs, all components must be packed as
2547 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2548 * not by itself consititute an incompatibility with normal WIMs, since this
2549 * is valid in normal WIMs.)
2551 * Note: the blob table, XML data, and header at the end are not used when
2552 * applying from a pipe. They exist to support functionality such as image
2553 * application and export when the WIM is *not* read from a pipe.
2555 * Layout of pipable WIM:
2557 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2558 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2559 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2561 * Layout of normal WIM:
2563 * +--------+-----------------------------+-------------------------+
2564 * | Header | File and metadata resources | Blob table | XML data |
2565 * +--------+-----------------------------+-------------------------+
2567 * An optional integrity table can follow the final XML data in both normal and
2568 * pipable WIMs. However, due to implementation details, wimlib currently can
2569 * only include an integrity table in a pipable WIM when writing it to a
2570 * seekable file (not a pipe).
2572 * Do note that since pipable WIMs are not supported by Microsoft's software,
2573 * wimlib does not create them unless explicitly requested (with
2574 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2575 * characters to identify the file.
2578 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2579 unsigned num_threads,
2580 struct list_head *blob_list_override,
2581 struct list_head *blob_table_list_ret)
2584 struct wim_reshdr xml_reshdr;
2586 WARNING("Creating a pipable WIM, which will "
2588 " with Microsoft's software (WIMGAPI/ImageX/DISM).");
2590 /* At this point, the header at the beginning of the file has already
2594 * For efficiency, wimlib normally delays calculating each newly added
2595 * stream's hash until while that stream being written, or just before
2596 * it is written. However, when writing a pipable WIM (potentially to a
2597 * pipe), we first have to write the metadata resources, which contain
2598 * all the hashes. Moreover each blob is prefixed with its hash (struct
2599 * pwm_blob_hdr). Thus, we have to calculate all the hashes before
2602 ret = wim_checksum_unhashed_blobs(wim);
2606 /* Write extra copy of the XML data. */
2607 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2608 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2612 /* Write metadata resources for the image(s) being included in the
2614 ret = write_metadata_resources(wim, image, write_flags);
2618 /* Write file data needed for the image(s) being included in the output
2619 * WIM, or file data needed for the split WIM part. */
2620 return write_file_data(wim, image, write_flags,
2621 num_threads, blob_list_override,
2622 blob_table_list_ret);
2624 /* The blob table, XML data, and header at end are handled by
2625 * finish_write(). */
2629 should_default_to_solid_compression(WIMStruct *wim, int write_flags)
2631 return wim->out_hdr.wim_version == WIM_VERSION_SOLID &&
2632 !(write_flags & (WIMLIB_WRITE_FLAG_SOLID |
2633 WIMLIB_WRITE_FLAG_PIPABLE)) &&
2634 wim_has_solid_resources(wim);
2637 /* Update the images' filecount/bytecount stats (in the XML info) to take into
2638 * account any recent modifications. */
2640 update_image_stats(WIMStruct *wim)
2642 if (!wim_has_metadata(wim))
2644 for (int i = 0; i < wim->hdr.image_count; i++) {
2645 struct wim_image_metadata *imd = wim->image_metadata[i];
2646 if (imd->stats_outdated) {
2647 int ret = xml_update_image_info(wim, i + 1);
2650 imd->stats_outdated = false;
2656 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2659 write_wim_part(WIMStruct *wim,
2660 const void *path_or_fd,
2663 unsigned num_threads,
2664 unsigned part_number,
2665 unsigned total_parts,
2666 struct list_head *blob_list_override,
2670 struct list_head blob_table_list;
2672 /* Internally, this is always called with a valid part number and total
2674 wimlib_assert(total_parts >= 1);
2675 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2677 /* A valid image (or all images) must be specified. */
2678 if (image != WIMLIB_ALL_IMAGES &&
2679 (image < 1 || image > wim->hdr.image_count))
2680 return WIMLIB_ERR_INVALID_IMAGE;
2682 /* If we need to write metadata resources, make sure the ::WIMStruct has
2683 * the needed information attached (e.g. is not a resource-only WIM,
2684 * such as a non-first part of a split WIM). */
2685 if (!wim_has_metadata(wim) &&
2686 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2687 return WIMLIB_ERR_METADATA_NOT_FOUND;
2689 /* Check for contradictory flags. */
2690 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2691 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2692 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2693 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2694 return WIMLIB_ERR_INVALID_PARAM;
2696 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2697 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2698 == (WIMLIB_WRITE_FLAG_PIPABLE |
2699 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2700 return WIMLIB_ERR_INVALID_PARAM;
2702 /* Only wimlib_overwrite() accepts UNSAFE_COMPACT. */
2703 if (write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)
2704 return WIMLIB_ERR_INVALID_PARAM;
2706 /* Include an integrity table by default if no preference was given and
2707 * the WIM already had an integrity table. */
2708 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2709 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))) {
2710 if (wim_has_integrity_table(wim))
2711 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2714 /* Write a pipable WIM by default if no preference was given and the WIM
2715 * was already pipable. */
2716 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2717 WIMLIB_WRITE_FLAG_NOT_PIPABLE))) {
2718 if (wim_is_pipable(wim))
2719 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2722 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2723 WIMLIB_WRITE_FLAG_SOLID))
2724 == (WIMLIB_WRITE_FLAG_PIPABLE |
2725 WIMLIB_WRITE_FLAG_SOLID))
2727 ERROR("Solid compression is unsupported in pipable WIMs");
2728 return WIMLIB_ERR_INVALID_PARAM;
2731 /* Start initializing the new file header. */
2732 memset(&wim->out_hdr, 0, sizeof(wim->out_hdr));
2734 /* Set the magic number. */
2735 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2736 wim->out_hdr.magic = PWM_MAGIC;
2738 wim->out_hdr.magic = WIM_MAGIC;
2740 /* Set the version number. */
2741 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2742 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2743 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2745 wim->out_hdr.wim_version = WIM_VERSION_DEFAULT;
2747 /* Default to solid compression if it is valid in the chosen WIM file
2748 * format and the WIMStruct references any solid resources. This is
2749 * useful when exporting an image from a solid WIM. */
2750 if (should_default_to_solid_compression(wim, write_flags))
2751 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2753 /* Set the header flags. */
2754 wim->out_hdr.flags = (wim->hdr.flags & (WIM_HDR_FLAG_RP_FIX |
2755 WIM_HDR_FLAG_READONLY));
2756 if (total_parts != 1)
2757 wim->out_hdr.flags |= WIM_HDR_FLAG_SPANNED;
2758 if (wim->out_compression_type != WIMLIB_COMPRESSION_TYPE_NONE) {
2759 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESSION;
2760 switch (wim->out_compression_type) {
2761 case WIMLIB_COMPRESSION_TYPE_XPRESS:
2762 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_XPRESS;
2764 case WIMLIB_COMPRESSION_TYPE_LZX:
2765 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZX;
2767 case WIMLIB_COMPRESSION_TYPE_LZMS:
2768 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZMS;
2773 /* Set the chunk size. */
2774 wim->out_hdr.chunk_size = wim->out_chunk_size;
2777 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2778 guid = wim->hdr.guid;
2780 copy_guid(wim->out_hdr.guid, guid);
2782 generate_guid(wim->out_hdr.guid);
2784 /* Set the part number and total parts. */
2785 wim->out_hdr.part_number = part_number;
2786 wim->out_hdr.total_parts = total_parts;
2788 /* Set the image count. */
2789 if (image == WIMLIB_ALL_IMAGES)
2790 wim->out_hdr.image_count = wim->hdr.image_count;
2792 wim->out_hdr.image_count = 1;
2794 /* Set the boot index. */
2795 wim->out_hdr.boot_idx = 0;
2796 if (total_parts == 1) {
2797 if (image == WIMLIB_ALL_IMAGES)
2798 wim->out_hdr.boot_idx = wim->hdr.boot_idx;
2799 else if (image == wim->hdr.boot_idx)
2800 wim->out_hdr.boot_idx = 1;
2803 /* Update image stats if needed. */
2804 ret = update_image_stats(wim);
2808 /* Set up the output file descriptor. */
2809 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2810 /* File descriptor was explicitly provided. */
2811 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2812 if (!filedes_is_seekable(&wim->out_fd)) {
2813 /* The file descriptor is a pipe. */
2814 ret = WIMLIB_ERR_INVALID_PARAM;
2815 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2817 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2818 ERROR("Can't include integrity check when "
2819 "writing pipable WIM to pipe!");
2824 /* Filename of WIM to write was provided; open file descriptor
2826 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2827 O_TRUNC | O_CREAT | O_RDWR);
2832 /* Write initial header. This is merely a "dummy" header since it
2833 * doesn't have resource entries filled in yet, so it will be
2834 * overwritten later (unless writing a pipable WIM). */
2835 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2836 wim->out_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2837 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2838 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2842 /* Write file data and metadata resources. */
2843 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2844 /* Default case: create a normal (non-pipable) WIM. */
2845 ret = write_file_data(wim, image, write_flags,
2852 ret = write_metadata_resources(wim, image, write_flags);
2856 /* Non-default case: create pipable WIM. */
2857 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2864 /* Write blob table, XML data, and (optional) integrity table. */
2865 ret = finish_write(wim, image, write_flags, &blob_table_list);
2867 (void)close_wim_writable(wim, write_flags);
2871 /* Write a standalone WIM to a file or file descriptor. */
2873 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2874 int image, int write_flags, unsigned num_threads)
2876 return write_wim_part(wim, path_or_fd, image, write_flags,
2877 num_threads, 1, 1, NULL, NULL);
2880 /* API function documented in wimlib.h */
2882 wimlib_write(WIMStruct *wim, const tchar *path,
2883 int image, int write_flags, unsigned num_threads)
2885 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2886 return WIMLIB_ERR_INVALID_PARAM;
2888 if (path == NULL || path[0] == T('\0'))
2889 return WIMLIB_ERR_INVALID_PARAM;
2891 return write_standalone_wim(wim, path, image, write_flags, num_threads);
2894 /* API function documented in wimlib.h */
2896 wimlib_write_to_fd(WIMStruct *wim, int fd,
2897 int image, int write_flags, unsigned num_threads)
2899 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2900 return WIMLIB_ERR_INVALID_PARAM;
2903 return WIMLIB_ERR_INVALID_PARAM;
2905 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2907 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2910 /* Have there been any changes to images in the specified WIM, including updates
2911 * as well as deletions and additions of entire images, but excluding changes to
2912 * the XML document? */
2914 any_images_changed(WIMStruct *wim)
2916 if (wim->image_deletion_occurred)
2918 for (int i = 0; i < wim->hdr.image_count; i++)
2919 if (!is_image_unchanged_from_wim(wim->image_metadata[i], wim))
2925 check_resource_offset(struct blob_descriptor *blob, void *_wim)
2927 const WIMStruct *wim = _wim;
2928 off_t end_offset = *(const off_t*)wim->private;
2930 if (blob->blob_location == BLOB_IN_WIM &&
2931 blob->rdesc->wim == wim &&
2932 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
2933 return WIMLIB_ERR_RESOURCE_ORDER;
2937 /* Make sure no file or metadata resources are located after the XML data (or
2938 * integrity table if present)--- otherwise we can't safely append to the WIM
2939 * file and we return WIMLIB_ERR_RESOURCE_ORDER. */
2941 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2946 wim->private = &end_offset;
2947 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
2951 for (i = 0; i < wim->hdr.image_count; i++) {
2952 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
2960 free_blob_if_invalidated(struct blob_descriptor *blob, void *_wim)
2962 const WIMStruct *wim = _wim;
2964 if (!blob->will_be_in_output_wim &&
2965 blob->blob_location == BLOB_IN_WIM && blob->rdesc->wim == wim)
2967 blob_table_unlink(wim->blob_table, blob);
2968 free_blob_descriptor(blob);
2974 * Overwrite a WIM, possibly appending new resources to it.
2976 * A WIM looks like (or is supposed to look like) the following:
2978 * Header (212 bytes)
2979 * Resources for metadata and files (variable size)
2980 * Blob table (variable size)
2981 * XML data (variable size)
2982 * Integrity table (optional) (variable size)
2984 * If we are not adding any new files or metadata, then the blob table is
2985 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2986 * header. This operation is potentially unsafe if the program is abruptly
2987 * terminated while the XML data or integrity table are being overwritten, but
2988 * before the new header has been written. To partially alleviate this problem,
2989 * we write a temporary header after the XML data has been written. This may
2990 * prevent the WIM from becoming corrupted if the program is terminated while
2991 * the integrity table is being calculated (but no guarantees, due to write
2994 * If we are adding new blobs, including new file data as well as any metadata
2995 * for any new images, then the blob table needs to be changed, and those blobs
2996 * need to be written. In this case, we try to perform a safe update of the WIM
2997 * file by writing the blobs *after* the end of the previous WIM, then writing
2998 * the new blob table, XML data, and (optionally) integrity table following the
2999 * new blobs. This will produce a layout like the following:
3001 * Header (212 bytes)
3002 * (OLD) Resources for metadata and files (variable size)
3003 * (OLD) Blob table (variable size)
3004 * (OLD) XML data (variable size)
3005 * (OLD) Integrity table (optional) (variable size)
3006 * (NEW) Resources for metadata and files (variable size)
3007 * (NEW) Blob table (variable size)
3008 * (NEW) XML data (variable size)
3009 * (NEW) Integrity table (optional) (variable size)
3011 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3012 * the header is overwritten to point to the new blob table, XML data, and
3013 * integrity table, to produce the following layout:
3015 * Header (212 bytes)
3016 * Resources for metadata and files (variable size)
3017 * Nothing (variable size)
3018 * Resources for metadata and files (variable size)
3019 * Blob table (variable size)
3020 * XML data (variable size)
3021 * Integrity table (optional) (variable size)
3023 * This function allows an image to be appended to a large WIM very quickly, and
3024 * is crash-safe except in the case of write re-ordering, but the disadvantage
3025 * is that a small hole is left in the WIM where the old blob table, xml data,
3026 * and integrity table were. (These usually only take up a small amount of
3027 * space compared to the blobs, however.)
3029 * Finally, this function also supports "compaction" overwrites as an
3030 * alternative to the normal "append" overwrites described above. In a
3031 * compaction, data is written starting immediately from the end of the header.
3032 * All existing resources are written first, in order by file offset. New
3033 * resources are written afterwards, and at the end any extra data is truncated
3034 * from the file. The advantage of this approach is that is that the WIM file
3035 * ends up fully optimized, without any holes remaining. The main disadavantage
3036 * is that this operation is fundamentally unsafe and cannot be interrupted
3037 * without data corruption. Consequently, compactions are only ever done when
3038 * explicitly requested by the library user with the flag
3039 * WIMLIB_WRITE_FLAG_UNSAFE_COMPACT. (Another disadvantage is that a compaction
3040 * can be much slower than an append.)
3043 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3047 struct list_head blob_list;
3048 struct list_head blob_table_list;
3049 struct filter_context filter_ctx;
3051 /* Include an integrity table by default if no preference was given and
3052 * the WIM already had an integrity table. */
3053 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3054 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3055 if (wim_has_integrity_table(wim))
3056 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3058 /* Start preparing the updated file header. */
3059 memcpy(&wim->out_hdr, &wim->hdr, sizeof(wim->out_hdr));
3061 /* If using solid compression, the version number must be set to
3062 * WIM_VERSION_SOLID. */
3063 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
3064 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
3066 /* Default to solid compression if it is valid in the chosen WIM file
3067 * format and the WIMStruct references any solid resources. This is
3068 * useful when updating a solid WIM. */
3069 if (should_default_to_solid_compression(wim, write_flags))
3070 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
3072 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)) {
3074 /* In-place compaction */
3076 WARNING("The WIM file \"%"TS"\" is being compacted in place.\n"
3077 " Do *not* interrupt the operation, or else "
3078 "the WIM file will be\n"
3079 " corrupted!", wim->filename);
3080 wim->being_compacted = 1;
3081 old_wim_end = WIM_HEADER_DISK_SIZE;
3083 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES,
3084 write_flags, &blob_list,
3085 &blob_table_list, &filter_ctx);
3089 /* Prevent new files from being deduplicated with existing blobs
3090 * in the WIM that we haven't decided to write. Such blobs will
3091 * be overwritten during the compaction. */
3092 for_blob_in_table(wim->blob_table, free_blob_if_invalidated, wim);
3094 if (wim_has_metadata(wim)) {
3095 /* Add existing metadata resources to be compacted along
3096 * with the file resources. */
3097 for (int i = 0; i < wim->hdr.image_count; i++) {
3098 struct wim_image_metadata *imd = wim->image_metadata[i];
3099 if (is_image_unchanged_from_wim(imd, wim)) {
3100 fully_reference_blob_for_write(imd->metadata_blob,
3106 u64 old_blob_table_end, old_xml_begin, old_xml_end;
3108 /* Set additional flags for append. */
3109 write_flags |= WIMLIB_WRITE_FLAG_APPEND |
3110 WIMLIB_WRITE_FLAG_STREAMS_OK;
3112 /* Make sure there is no data after the XML data, except
3113 * possibily an integrity table. If this were the case, then
3114 * this data would be overwritten. */
3115 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3116 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3117 if (wim->hdr.blob_table_reshdr.offset_in_wim == 0)
3118 old_blob_table_end = WIM_HEADER_DISK_SIZE;
3120 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
3121 wim->hdr.blob_table_reshdr.size_in_wim;
3122 if (wim_has_integrity_table(wim) &&
3123 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3124 WARNING("Didn't expect the integrity table to be "
3125 "before the XML data");
3126 ret = WIMLIB_ERR_RESOURCE_ORDER;
3130 if (old_blob_table_end > old_xml_begin) {
3131 WARNING("Didn't expect the blob table to be after "
3133 ret = WIMLIB_ERR_RESOURCE_ORDER;
3136 /* Set @old_wim_end, which indicates the point beyond which we
3137 * don't allow any file and metadata resources to appear without
3138 * returning WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we
3139 * would otherwise overwrite these resources). */
3140 if (!any_images_changed(wim)) {
3141 /* If no images have been modified, added, or deleted,
3142 * then a new blob table does not need to be written.
3143 * We shall write the new XML data and optional
3144 * integrity table immediately after the blob table.
3145 * Note that this may overwrite an existing integrity
3147 old_wim_end = old_blob_table_end;
3148 write_flags |= WIMLIB_WRITE_FLAG_NO_NEW_BLOBS;
3149 } else if (wim_has_integrity_table(wim)) {
3150 /* Old WIM has an integrity table; begin writing new
3151 * blobs after it. */
3152 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3153 wim->hdr.integrity_table_reshdr.size_in_wim;
3155 /* No existing integrity table; begin writing new blobs
3156 * after the old XML data. */
3157 old_wim_end = old_xml_end;
3160 ret = check_resource_offsets(wim, old_wim_end);
3164 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES,
3165 write_flags, &blob_list,
3166 &blob_table_list, &filter_ctx);
3170 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)
3171 wimlib_assert(list_empty(&blob_list));
3174 /* Update image stats if needed. */
3175 ret = update_image_stats(wim);
3179 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3183 ret = lock_wim_for_append(wim);
3187 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3188 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3189 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3190 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3192 ERROR_WITH_ERRNO("Error updating WIM header flags");
3193 goto out_unlock_wim;
3196 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3197 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3198 ret = WIMLIB_ERR_WRITE;
3199 goto out_restore_hdr;
3202 ret = write_file_data_blobs(wim, &blob_list, write_flags,
3203 num_threads, &filter_ctx);
3207 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3211 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3216 unlock_wim_for_append(wim);
3220 if (!(write_flags & (WIMLIB_WRITE_FLAG_NO_NEW_BLOBS |
3221 WIMLIB_WRITE_FLAG_UNSAFE_COMPACT))) {
3222 WARNING("Truncating \"%"TS"\" to its original size "
3223 "(%"PRIu64" bytes)", wim->filename, old_wim_end);
3224 if (ftruncate(wim->out_fd.fd, old_wim_end))
3225 WARNING_WITH_ERRNO("Failed to truncate WIM file!");
3228 (void)write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3230 unlock_wim_for_append(wim);
3232 (void)close_wim_writable(wim, write_flags);
3234 wim->being_compacted = 0;
3239 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3241 size_t wim_name_len;
3244 /* Write the WIM to a temporary file in the same directory as the
3246 wim_name_len = tstrlen(wim->filename);
3247 tchar tmpfile[wim_name_len + 10];
3248 tmemcpy(tmpfile, wim->filename, wim_name_len);
3249 get_random_alnum_chars(tmpfile + wim_name_len, 9);
3250 tmpfile[wim_name_len + 9] = T('\0');
3252 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3254 WIMLIB_WRITE_FLAG_FSYNC |
3255 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3262 if (filedes_valid(&wim->in_fd)) {
3263 filedes_close(&wim->in_fd);
3264 filedes_invalidate(&wim->in_fd);
3267 /* Rename the new WIM file to the original WIM file. Note: on Windows
3268 * this actually calls win32_rename_replacement(), not _wrename(), so
3269 * that removing the existing destination file can be handled. */
3270 ret = trename(tmpfile, wim->filename);
3272 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3273 tmpfile, wim->filename);
3280 return WIMLIB_ERR_RENAME;
3283 union wimlib_progress_info progress;
3284 progress.rename.from = tmpfile;
3285 progress.rename.to = wim->filename;
3286 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3287 &progress, wim->progctx);
3290 /* Determine if the specified WIM file may be updated in-place rather than by
3291 * writing and replacing it with an entirely new file. */
3293 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3295 /* REBUILD flag forces full rebuild. */
3296 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3299 /* Image deletions cause full rebuild by default. */
3300 if (wim->image_deletion_occurred &&
3301 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3304 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3305 * turned into a pipable WIM in-place. */
3306 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3309 /* The default compression type and compression chunk size selected for
3310 * the output WIM must be the same as those currently used for the WIM.
3312 if (wim->compression_type != wim->out_compression_type)
3314 if (wim->chunk_size != wim->out_chunk_size)
3320 /* API function documented in wimlib.h */
3322 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3327 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3328 return WIMLIB_ERR_INVALID_PARAM;
3331 return WIMLIB_ERR_NO_FILENAME;
3333 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)) {
3335 * In UNSAFE_COMPACT mode:
3336 * - RECOMPRESS is forbidden
3337 * - REBUILD is ignored
3338 * - SOFT_DELETE and NO_SOLID_SORT are implied
3340 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
3341 return WIMLIB_ERR_COMPACTION_NOT_POSSIBLE;
3342 write_flags &= ~WIMLIB_WRITE_FLAG_REBUILD;
3343 write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
3344 write_flags |= WIMLIB_WRITE_FLAG_NO_SOLID_SORT;
3347 orig_hdr_flags = wim->hdr.flags;
3348 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3349 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3350 ret = can_modify_wim(wim);
3351 wim->hdr.flags = orig_hdr_flags;
3355 if (can_overwrite_wim_inplace(wim, write_flags)) {
3356 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3357 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3359 WARNING("Falling back to re-building entire WIM");
3361 if (write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)
3362 return WIMLIB_ERR_COMPACTION_NOT_POSSIBLE;
3363 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);