4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
11 * This file is free software; you can redistribute it and/or modify it under
12 * the terms of the GNU Lesser General Public License as published by the Free
13 * Software Foundation; either version 3 of the License, or (at your option) any
16 * This file is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this file; if not, see http://www.gnu.org/licenses/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
31 * override the LIST_HEAD macro. */
32 # include <sys/file.h>
40 #include "wimlib/alloca.h"
41 #include "wimlib/assert.h"
42 #include "wimlib/blob_table.h"
43 #include "wimlib/chunk_compressor.h"
44 #include "wimlib/endianness.h"
45 #include "wimlib/error.h"
46 #include "wimlib/file_io.h"
47 #include "wimlib/header.h"
48 #include "wimlib/inode.h"
49 #include "wimlib/integrity.h"
50 #include "wimlib/metadata.h"
51 #include "wimlib/paths.h"
52 #include "wimlib/progress.h"
53 #include "wimlib/resource.h"
54 #include "wimlib/solid.h"
55 #include "wimlib/win32.h" /* win32_rename_replacement() */
56 #include "wimlib/write.h"
57 #include "wimlib/xml.h"
60 /* wimlib internal flags used when writing resources. */
61 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
62 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
63 #define WRITE_RESOURCE_FLAG_SOLID 0x00000004
64 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
65 #define WRITE_RESOURCE_FLAG_SOLID_SORT 0x00000010
68 write_flags_to_resource_flags(int write_flags)
70 int write_resource_flags = 0;
72 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
73 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
75 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
78 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
79 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
81 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
82 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
84 if ((write_flags & (WIMLIB_WRITE_FLAG_SOLID |
85 WIMLIB_WRITE_FLAG_NO_SOLID_SORT)) ==
86 WIMLIB_WRITE_FLAG_SOLID)
87 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID_SORT;
89 return write_resource_flags;
92 struct filter_context {
98 * Determine whether the specified blob should be filtered out from the write.
102 * < 0 : The blob should be hard-filtered; that is, not included in the output
104 * 0 : The blob should not be filtered out.
105 * > 0 : The blob should be soft-filtered; that is, it already exists in the
106 * WIM file and may not need to be written again.
109 blob_filtered(const struct blob_descriptor *blob,
110 const struct filter_context *ctx)
118 write_flags = ctx->write_flags;
121 if (write_flags & WIMLIB_WRITE_FLAG_APPEND &&
122 blob->blob_location == BLOB_IN_WIM &&
123 blob->rdesc->wim == wim)
126 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
127 blob->blob_location == BLOB_IN_WIM &&
128 blob->rdesc->wim != wim)
135 blob_hard_filtered(const struct blob_descriptor *blob,
136 struct filter_context *ctx)
138 return blob_filtered(blob, ctx) < 0;
142 may_soft_filter_blobs(const struct filter_context *ctx)
144 return ctx && (ctx->write_flags & WIMLIB_WRITE_FLAG_APPEND);
148 may_hard_filter_blobs(const struct filter_context *ctx)
150 return ctx && (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS);
154 may_filter_blobs(const struct filter_context *ctx)
156 return (may_soft_filter_blobs(ctx) || may_hard_filter_blobs(ctx));
159 /* Return true if the specified blob is located in a WIM resource which can be
160 * reused in the output WIM file, without being recompressed. */
162 can_raw_copy(const struct blob_descriptor *blob, int write_resource_flags,
163 int out_ctype, u32 out_chunk_size)
165 const struct wim_resource_descriptor *rdesc;
167 /* Recompress everything if requested. */
168 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
171 /* A blob not located in a WIM resource cannot be reused. */
172 if (blob->blob_location != BLOB_IN_WIM)
177 /* 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("Write error");
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 read. */
381 u64 cur_read_blob_offset;
383 /* Uncompressed size of the blob currently being read. */
384 u64 cur_read_blob_size;
386 /* Current uncompressed offset in the blob being written. */
387 u64 cur_write_blob_offset;
389 /* Uncompressed size of resource currently being written. */
390 u64 cur_write_res_size;
392 /* Array that is filled in with compressed chunk sizes as a resource is
396 /* Index of next entry in @chunk_csizes to fill in. */
399 /* Number of entries in @chunk_csizes currently allocated. */
400 size_t num_alloc_chunks;
402 /* Offset in the output file of the start of the chunks of the resource
403 * currently being written. */
404 u64 chunks_start_offset;
407 /* Reserve space for the chunk table and prepare to accumulate the chunk table
410 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
412 u64 expected_num_chunks;
413 u64 expected_num_chunk_entries;
417 /* Calculate the number of chunks and chunk entries that should be
418 * needed for the resource. These normally will be the final values,
419 * but in SOLID mode some of the blobs we're planning to write into the
420 * resource may be duplicates, and therefore discarded, potentially
421 * decreasing the number of chunk entries needed. */
422 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
423 expected_num_chunk_entries = expected_num_chunks;
424 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
425 expected_num_chunk_entries--;
427 /* Make sure the chunk_csizes array is long enough to store the
428 * compressed size of each chunk. */
429 if (expected_num_chunks > ctx->num_alloc_chunks) {
430 u64 new_length = expected_num_chunks + 50;
432 if ((size_t)new_length != new_length) {
433 ERROR("Resource size too large (%"PRIu64" bytes!",
435 return WIMLIB_ERR_NOMEM;
438 FREE(ctx->chunk_csizes);
439 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
440 if (ctx->chunk_csizes == NULL) {
441 ctx->num_alloc_chunks = 0;
442 return WIMLIB_ERR_NOMEM;
444 ctx->num_alloc_chunks = new_length;
447 ctx->chunk_index = 0;
449 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
450 /* Reserve space for the chunk table in the output file. In the
451 * case of solid resources this reserves the upper bound for the
452 * needed space, not necessarily the exact space which will
453 * prove to be needed. At this point, we just use @chunk_csizes
454 * for a buffer of 0's because the actual compressed chunk sizes
456 reserve_size = expected_num_chunk_entries *
457 get_chunk_entry_size(res_expected_size,
458 0 != (ctx->write_resource_flags &
459 WRITE_RESOURCE_FLAG_SOLID));
460 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
461 reserve_size += sizeof(struct alt_chunk_table_header_disk);
462 memset(ctx->chunk_csizes, 0, reserve_size);
463 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
471 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
475 wimlib_assert(res_expected_size != 0);
477 if (ctx->compressor != NULL) {
478 ret = begin_chunk_table(ctx, res_expected_size);
483 /* Output file descriptor is now positioned at the offset at which to
484 * write the first chunk of the resource. */
485 ctx->chunks_start_offset = ctx->out_fd->offset;
486 ctx->cur_write_blob_offset = 0;
487 ctx->cur_write_res_size = res_expected_size;
492 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
493 u64 *res_start_offset_ret, u64 *res_store_size_ret)
495 size_t actual_num_chunks;
496 size_t actual_num_chunk_entries;
497 size_t chunk_entry_size;
500 actual_num_chunks = ctx->chunk_index;
501 actual_num_chunk_entries = actual_num_chunks;
502 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
503 actual_num_chunk_entries--;
505 chunk_entry_size = get_chunk_entry_size(res_actual_size,
506 0 != (ctx->write_resource_flags &
507 WRITE_RESOURCE_FLAG_SOLID));
509 typedef le64 _may_alias_attribute aliased_le64_t;
510 typedef le32 _may_alias_attribute aliased_le32_t;
512 if (chunk_entry_size == 4) {
513 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
515 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
516 for (size_t i = 0; i < actual_num_chunk_entries; i++)
517 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
519 u32 offset = ctx->chunk_csizes[0];
520 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
521 u32 next_size = ctx->chunk_csizes[i + 1];
522 entries[i] = cpu_to_le32(offset);
527 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
529 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
530 for (size_t i = 0; i < actual_num_chunk_entries; i++)
531 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
533 u64 offset = ctx->chunk_csizes[0];
534 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
535 u64 next_size = ctx->chunk_csizes[i + 1];
536 entries[i] = cpu_to_le64(offset);
542 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
543 u64 res_start_offset;
546 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
547 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
550 res_end_offset = ctx->out_fd->offset;
551 res_start_offset = ctx->chunks_start_offset;
553 res_end_offset = ctx->out_fd->offset;
555 u64 chunk_table_offset;
557 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
559 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
560 struct alt_chunk_table_header_disk hdr;
562 hdr.res_usize = cpu_to_le64(res_actual_size);
563 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
564 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
566 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_XPRESS == 1);
567 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZX == 2);
568 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZMS == 3);
570 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
571 chunk_table_offset - sizeof(hdr));
574 res_start_offset = chunk_table_offset - sizeof(hdr);
576 res_start_offset = chunk_table_offset;
579 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
580 chunk_table_size, chunk_table_offset);
585 *res_start_offset_ret = res_start_offset;
586 *res_store_size_ret = res_end_offset - res_start_offset;
591 ERROR_WITH_ERRNO("Write error");
595 /* Finish writing a WIM resource by writing or updating the chunk table (if not
596 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
598 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
602 u64 res_uncompressed_size;
603 u64 res_offset_in_wim;
605 wimlib_assert(ctx->cur_write_blob_offset == ctx->cur_write_res_size ||
606 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
607 res_uncompressed_size = ctx->cur_write_res_size;
609 if (ctx->compressor) {
610 ret = end_chunk_table(ctx, res_uncompressed_size,
611 &res_offset_in_wim, &res_size_in_wim);
615 res_offset_in_wim = ctx->chunks_start_offset;
616 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
618 out_reshdr->uncompressed_size = res_uncompressed_size;
619 out_reshdr->size_in_wim = res_size_in_wim;
620 out_reshdr->offset_in_wim = res_offset_in_wim;
624 /* Call when no more data from the file at @path is needed. */
626 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
628 union wimlib_progress_info info;
630 info.done_with_file.path_to_file = path;
632 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
637 do_done_with_blob(struct blob_descriptor *blob,
638 wimlib_progress_func_t progfunc, void *progctx)
641 struct wim_inode *inode;
645 if (!blob->may_send_done_with_file)
648 inode = blob->file_inode;
650 wimlib_assert(inode != NULL);
651 wimlib_assert(inode->i_num_remaining_streams > 0);
652 if (--inode->i_num_remaining_streams > 0)
655 cookie1 = progress_get_streamless_path(blob->file_on_disk);
656 cookie2 = progress_get_win32_path(blob->file_on_disk);
658 ret = done_with_file(blob->file_on_disk, 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 ctx->cur_read_blob_offset = 0;
687 ctx->cur_read_blob_size = blob->size;
689 /* As an optimization, we allow some blobs to be "unhashed", meaning
690 * their SHA-1 message digests are unknown. This is the case with blobs
691 * that are added by scanning a directory tree with wimlib_add_image(),
692 * for example. Since WIM uses single-instance blobs, we don't know
693 * whether such each such blob really need to written until it is
694 * actually checksummed, unless it has a unique size. In such cases we
695 * read and checksum the blob in this function, thereby advancing ahead
696 * of read_blob_list(), which will still provide the data again to
697 * write_blob_process_chunk(). This is okay because an unhashed blob
698 * cannot be in a WIM resource, which might be costly to decompress. */
699 if (ctx->blob_table != NULL && blob->unhashed && !blob->unique_size) {
701 struct blob_descriptor *new_blob;
703 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
706 if (new_blob != blob) {
707 /* Duplicate blob detected. */
709 if (new_blob->will_be_in_output_wim ||
710 blob_filtered(new_blob, ctx->filter_ctx))
712 /* The duplicate blob is already being included
713 * in the output WIM, or it would be filtered
714 * out if it had been. Skip writing this blob
715 * (and reading it again) entirely, passing its
716 * output reference count to the duplicate blob
717 * in the former case. */
718 ret = do_write_blobs_progress(&ctx->progress_data,
719 blob->size, 1, true);
720 list_del(&blob->write_blobs_list);
721 list_del(&blob->blob_table_list);
722 if (new_blob->will_be_in_output_wim)
723 new_blob->out_refcnt += blob->out_refcnt;
724 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
725 ctx->cur_write_res_size -= blob->size;
727 ret = done_with_blob(blob, ctx);
728 free_blob_descriptor(blob);
731 return BEGIN_BLOB_STATUS_SKIP_BLOB;
733 /* The duplicate blob can validly be written,
734 * but was not marked as such. Discard the
735 * current blob descriptor and use the
736 * duplicate, but actually freeing the current
737 * blob descriptor must wait until
738 * read_blob_list() has finished reading its
740 list_replace(&blob->write_blobs_list,
741 &new_blob->write_blobs_list);
742 list_replace(&blob->blob_table_list,
743 &new_blob->blob_table_list);
744 blob->will_be_in_output_wim = 0;
745 new_blob->out_refcnt = blob->out_refcnt;
746 new_blob->will_be_in_output_wim = 1;
747 new_blob->may_send_done_with_file = 0;
752 list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
756 /* Rewrite a blob that was just written compressed (as a non-solid WIM resource)
757 * as uncompressed instead. */
759 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
762 u64 begin_offset = blob->out_reshdr.offset_in_wim;
763 u64 end_offset = out_fd->offset;
765 if (filedes_seek(out_fd, begin_offset) == -1)
768 ret = extract_blob_to_fd(blob, out_fd);
770 /* Error reading the uncompressed data. */
771 if (out_fd->offset == begin_offset &&
772 filedes_seek(out_fd, end_offset) != -1)
774 /* Nothing was actually written yet, and we successfully
775 * seeked to the end of the compressed resource, so
776 * don't issue a hard error; just keep the compressed
777 * resource instead. */
778 WARNING("Recovered compressed resource of "
779 "size %"PRIu64", continuing on.", blob->size);
785 wimlib_assert(out_fd->offset - begin_offset == blob->size);
787 /* We could ftruncate() the file to 'out_fd->offset' here, but there
788 * isn't much point. Usually we will only be truncating by a few bytes
789 * and will just overwrite the data immediately. */
791 blob->out_reshdr.size_in_wim = blob->size;
792 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
793 WIM_RESHDR_FLAG_SOLID);
797 /* Returns true if the specified blob, which was written as a non-solid
798 * resource, should be truncated from the WIM file and re-written uncompressed.
799 * blob->out_reshdr must be filled in from the initial write of the blob. */
801 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
802 const struct blob_descriptor *blob)
804 /* If the compressed data is smaller than the uncompressed data, prefer
805 * the compressed data. */
806 if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
809 /* If we're not actually writing compressed data, then there's no need
811 if (!ctx->compressor)
814 /* If writing a pipable WIM, everything we write to the output is final
815 * (it might actually be a pipe!). */
816 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
819 /* If the blob that would need to be re-read is located in a solid
820 * resource in another WIM file, then re-reading it would be costly. So
823 * Exception: if the compressed size happens to be *exactly* the same as
824 * the uncompressed size, then the blob *must* be written uncompressed
825 * in order to remain compatible with the Windows Overlay Filesystem
826 * Filter Driver (WOF).
828 * TODO: we are currently assuming that the optimization for
829 * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
830 * this case from being triggered too often. To fully prevent excessive
831 * decompressions in degenerate cases, we really should obtain the
832 * uncompressed data by decompressing the compressed data we wrote to
835 if (blob->blob_location == BLOB_IN_WIM &&
836 blob->size != blob->rdesc->uncompressed_size &&
837 blob->size != blob->out_reshdr.size_in_wim)
844 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
845 struct blob_descriptor *blob)
847 if (!should_rewrite_blob_uncompressed(ctx, blob))
850 /* Regular (non-solid) WIM resources with exactly one chunk and
851 * compressed size equal to uncompressed size are exactly the same as
852 * the corresponding compressed data --- since there must be 0 entries
853 * in the chunk table and the only chunk must be stored uncompressed.
854 * In this case, there's no need to rewrite anything. */
855 if (ctx->chunk_index == 1 &&
856 blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
858 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
862 return write_blob_uncompressed(blob, ctx->out_fd);
865 /* Write the next chunk of (typically compressed) data to the output WIM,
866 * handling the writing of the chunk table. */
868 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
869 size_t csize, size_t usize)
872 struct blob_descriptor *blob;
873 u32 completed_blob_count;
876 blob = list_entry(ctx->blobs_being_compressed.next,
877 struct blob_descriptor, write_blobs_list);
879 if (ctx->cur_write_blob_offset == 0 &&
880 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
882 /* Starting to write a new blob in non-solid mode. */
884 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
885 ret = write_pwm_blob_header(blob, ctx->out_fd,
886 ctx->compressor != NULL);
891 ret = begin_write_resource(ctx, blob->size);
896 if (ctx->compressor != NULL) {
897 /* Record the compresed chunk size. */
898 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
899 ctx->chunk_csizes[ctx->chunk_index++] = csize;
901 /* If writing a pipable WIM, before the chunk data write a chunk
902 * header that provides the compressed chunk size. */
903 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
904 struct pwm_chunk_hdr chunk_hdr = {
905 .compressed_size = cpu_to_le32(csize),
907 ret = full_write(ctx->out_fd, &chunk_hdr,
914 /* Write the chunk data. */
915 ret = full_write(ctx->out_fd, cchunk, csize);
919 ctx->cur_write_blob_offset += usize;
921 completed_size = usize;
922 completed_blob_count = 0;
923 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
924 /* Wrote chunk in solid mode. It may have finished multiple
926 struct blob_descriptor *next_blob;
928 while (blob && ctx->cur_write_blob_offset >= blob->size) {
930 ctx->cur_write_blob_offset -= blob->size;
932 if (ctx->cur_write_blob_offset)
933 next_blob = list_entry(blob->write_blobs_list.next,
934 struct blob_descriptor,
939 ret = done_with_blob(blob, ctx);
942 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
943 completed_blob_count++;
948 /* Wrote chunk in non-solid mode. It may have finished a
950 if (ctx->cur_write_blob_offset == blob->size) {
952 wimlib_assert(ctx->cur_write_blob_offset ==
953 ctx->cur_write_res_size);
955 ret = end_write_resource(ctx, &blob->out_reshdr);
959 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
960 if (ctx->compressor != NULL)
961 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
963 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
967 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
969 ctx->cur_write_blob_offset = 0;
971 ret = done_with_blob(blob, ctx);
974 list_del(&blob->write_blobs_list);
975 completed_blob_count++;
979 return do_write_blobs_progress(&ctx->progress_data, completed_size,
980 completed_blob_count, false);
983 ERROR_WITH_ERRNO("Write error");
988 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
990 /* While we are unable to get a new chunk buffer due to too many chunks
991 * already outstanding, retrieve and write the next compressed chunk. */
992 while (!(ctx->cur_chunk_buf =
993 ctx->compressor->get_chunk_buffer(ctx->compressor)))
1001 bret = ctx->compressor->get_compression_result(ctx->compressor,
1005 wimlib_assert(bret);
1007 ret = write_chunk(ctx, cchunk, csize, usize);
1014 /* Process the next chunk of data to be written to a WIM resource. */
1016 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1018 struct write_blobs_ctx *ctx = _ctx;
1020 const u8 *chunkptr, *chunkend;
1022 wimlib_assert(size != 0);
1024 if (ctx->compressor == NULL) {
1025 /* Write chunk uncompressed. */
1026 ret = write_chunk(ctx, chunk, size, size);
1029 ctx->cur_read_blob_offset += size;
1033 /* Submit the chunk for compression, but take into account that the
1034 * @size the chunk was provided in may not correspond to the
1035 * @out_chunk_size being used for compression. */
1037 chunkend = chunkptr + size;
1039 size_t needed_chunk_size;
1040 size_t bytes_consumed;
1042 if (!ctx->cur_chunk_buf) {
1043 ret = prepare_chunk_buffer(ctx);
1048 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1049 needed_chunk_size = ctx->out_chunk_size;
1051 needed_chunk_size = min(ctx->out_chunk_size,
1052 ctx->cur_chunk_buf_filled +
1053 (ctx->cur_read_blob_size -
1054 ctx->cur_read_blob_offset));
1057 bytes_consumed = min(chunkend - chunkptr,
1058 needed_chunk_size - ctx->cur_chunk_buf_filled);
1060 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1061 chunkptr, bytes_consumed);
1063 chunkptr += bytes_consumed;
1064 ctx->cur_read_blob_offset += bytes_consumed;
1065 ctx->cur_chunk_buf_filled += bytes_consumed;
1067 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1068 ctx->compressor->signal_chunk_filled(ctx->compressor,
1069 ctx->cur_chunk_buf_filled);
1070 ctx->cur_chunk_buf = NULL;
1071 ctx->cur_chunk_buf_filled = 0;
1073 } while (chunkptr != chunkend);
1077 /* Finish processing a blob for writing. It may not have been completely
1078 * written yet, as the chunk_compressor implementation may still have chunks
1079 * buffered or being compressed. */
1081 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1083 struct write_blobs_ctx *ctx = _ctx;
1085 wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
1087 if (!blob->will_be_in_output_wim) {
1088 /* The blob was a duplicate. Now that its data has finished
1089 * being read, it is being discarded in favor of the duplicate
1090 * entry. It therefore is no longer needed, and we can fire the
1091 * DONE_WITH_FILE callback because the file will not be read
1094 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1095 * blobs, since it needs to be possible to re-read the file if
1096 * it does not compress to less than its original size. */
1098 status = done_with_blob(blob, ctx);
1099 free_blob_descriptor(blob);
1100 } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1101 /* The blob was not a duplicate and was previously unhashed.
1102 * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1103 * read_blob_list(), blob->hash is now computed and valid. So
1104 * turn this blob into a "hashed" blob. */
1105 list_del(&blob->unhashed_list);
1106 blob_table_insert(ctx->blob_table, blob);
1113 * Compute statistics about a list of blobs that will be written.
1115 * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1116 * (specified by WIMStruct) are together.
1118 * For compactions, also verify that there are no overlapping resources. This
1119 * really should be checked earlier, but for now it's easiest to check here.
1122 compute_blob_list_stats(struct list_head *blob_list,
1123 struct write_blobs_ctx *ctx)
1125 struct blob_descriptor *blob;
1126 u64 total_bytes = 0;
1128 u64 total_parts = 0;
1129 WIMStruct *prev_wim_part = NULL;
1130 const struct wim_resource_descriptor *prev_rdesc = NULL;
1132 list_for_each_entry(blob, blob_list, write_blobs_list) {
1134 total_bytes += blob->size;
1135 if (blob->blob_location == BLOB_IN_WIM) {
1136 const struct wim_resource_descriptor *rdesc = blob->rdesc;
1137 WIMStruct *wim = rdesc->wim;
1139 if (prev_wim_part != wim) {
1140 prev_wim_part = wim;
1143 if (unlikely(wim->being_compacted) && rdesc != prev_rdesc) {
1144 if (prev_rdesc != NULL &&
1145 rdesc->offset_in_wim <
1146 prev_rdesc->offset_in_wim +
1147 prev_rdesc->size_in_wim)
1149 WARNING("WIM file contains overlapping "
1150 "resources! Compaction is not "
1152 return WIMLIB_ERR_RESOURCE_ORDER;
1158 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1159 ctx->progress_data.progress.write_streams.total_streams = num_blobs;
1160 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1161 ctx->progress_data.progress.write_streams.completed_streams = 0;
1162 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1163 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1164 ctx->progress_data.progress.write_streams.completed_parts = 0;
1165 ctx->progress_data.next_progress = 0;
1169 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1170 * rather than compressed. Delete these blobs from @blob_list and move them to
1171 * @raw_copy_blobs. Return the total uncompressed size of the blobs that need
1172 * to be compressed. */
1174 find_raw_copy_blobs(struct list_head *blob_list, int write_resource_flags,
1175 int out_ctype, u32 out_chunk_size,
1176 struct list_head *raw_copy_blobs)
1178 struct blob_descriptor *blob, *tmp;
1179 u64 num_nonraw_bytes = 0;
1181 INIT_LIST_HEAD(raw_copy_blobs);
1183 /* Initialize temporary raw_copy_ok flag. */
1184 list_for_each_entry(blob, blob_list, write_blobs_list)
1185 if (blob->blob_location == BLOB_IN_WIM)
1186 blob->rdesc->raw_copy_ok = 0;
1188 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1189 if (can_raw_copy(blob, write_resource_flags,
1190 out_ctype, out_chunk_size))
1192 blob->rdesc->raw_copy_ok = 1;
1193 list_move_tail(&blob->write_blobs_list, raw_copy_blobs);
1195 num_nonraw_bytes += blob->size;
1199 return num_nonraw_bytes;
1202 /* Copy a raw compressed resource located in another WIM file to the WIM file
1205 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1206 struct filedes *out_fd)
1208 u64 cur_read_offset;
1209 u64 end_read_offset;
1210 u8 buf[BUFFER_SIZE];
1211 size_t bytes_to_read;
1213 struct filedes *in_fd;
1214 struct blob_descriptor *blob;
1215 u64 out_offset_in_wim;
1217 /* Copy the raw data. */
1218 cur_read_offset = in_rdesc->offset_in_wim;
1219 end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1221 out_offset_in_wim = out_fd->offset;
1223 if (in_rdesc->is_pipable) {
1224 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1225 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1226 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1227 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1229 in_fd = &in_rdesc->wim->in_fd;
1230 wimlib_assert(cur_read_offset != end_read_offset);
1232 if (likely(!in_rdesc->wim->being_compacted) ||
1233 in_rdesc->offset_in_wim > out_fd->offset) {
1235 bytes_to_read = min(sizeof(buf),
1236 end_read_offset - cur_read_offset);
1238 ret = full_pread(in_fd, buf, bytes_to_read,
1243 ret = full_write(out_fd, buf, bytes_to_read);
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 blob_is_in_file(const struct blob_descriptor *blob)
1346 return blob->blob_location == BLOB_IN_FILE_ON_DISK
1348 || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1349 || blob->blob_location == BLOB_WIN32_ENCRYPTED
1355 init_done_with_file_info(struct list_head *blob_list)
1357 struct blob_descriptor *blob;
1359 list_for_each_entry(blob, blob_list, write_blobs_list) {
1360 if (blob_is_in_file(blob)) {
1361 blob->file_inode->i_num_remaining_streams = 0;
1362 blob->may_send_done_with_file = 1;
1364 blob->may_send_done_with_file = 0;
1368 list_for_each_entry(blob, blob_list, write_blobs_list)
1369 if (blob->may_send_done_with_file)
1370 blob->file_inode->i_num_remaining_streams++;
1374 * Write a list of blobs to the output WIM file.
1377 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1378 * by the 'write_blobs_list' member.
1381 * The file descriptor, opened for writing, to which to write the blobs.
1383 * @write_resource_flags
1384 * Flags to modify how the blobs are written:
1386 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1387 * Force compression of all resources, even if they could otherwise
1388 * be re-used by copying the raw data, due to being located in a WIM
1389 * file with compatible compression parameters.
1391 * WRITE_RESOURCE_FLAG_PIPABLE:
1392 * Write the resources in the wimlib-specific pipable format, and
1393 * furthermore do so in such a way that no seeking backwards in
1394 * @out_fd will be performed (so it may be a pipe).
1396 * WRITE_RESOURCE_FLAG_SOLID:
1397 * Combine all the blobs into a single resource rather than writing
1398 * them in separate resources. This flag is only valid if the WIM
1399 * version number has been, or will be, set to WIM_VERSION_SOLID.
1400 * This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1403 * Compression format to use in the output resources, specified as one of
1404 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
1408 * Compression chunk size to use in the output resources. It must be a
1409 * valid chunk size for the specified compression format @out_ctype, unless
1410 * @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1414 * Number of threads to use to compress data. If 0, a default number of
1415 * threads will be chosen. The number of threads still may be decreased
1416 * from the specified value if insufficient memory is detected.
1419 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1420 * must be pointer to the blob table for the WIMStruct on whose behalf the
1421 * blobs are being written. Otherwise, this parameter can be NULL.
1424 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1425 * can be a pointer to a context for blob filtering used to detect whether
1426 * the duplicate blob has been hard-filtered or not. If no blobs are
1427 * hard-filtered or no blobs are unhashed, this parameter can be NULL.
1429 * This function will write the blobs in @blob_list to resources in
1430 * consecutive positions in the output WIM file, or to a single solid resource
1431 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1432 * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1433 * updated to specify its location, size, and flags in the output WIM. In the
1434 * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1435 * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1436 * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1437 * respectively, in the output WIM of the solid resource containing the
1438 * corresponding blob.
1440 * Each of the blobs to write may be in any location supported by the
1441 * resource-handling code (specifically, read_blob_list()), such as the contents
1442 * of external file that has been logically added to the output WIM, or a blob
1443 * in another WIM file that has been imported, or even a blob in the "same" WIM
1444 * file of which a modified copy is being written. In the case that a blob is
1445 * already in a WIM file and uses compatible compression parameters, by default
1446 * this function will re-use the raw data instead of decompressing it, then
1447 * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1448 * specified in @write_resource_flags, this is not done.
1450 * As a further requirement, this function requires that the
1451 * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1452 * as any other blobs not in @blob_list that will be in the output WIM file, but
1453 * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1454 * resource with a blob in @blob_list. Still furthermore, if on-the-fly
1455 * deduplication of blobs is possible, then all blobs in @blob_list must also be
1456 * linked by @blob_table_list along with any other blobs that have
1457 * @will_be_in_output_wim set.
1459 * This function handles on-the-fly deduplication of blobs for which SHA-1
1460 * message digests have not yet been calculated. Such blobs may or may not need
1461 * to be written. If @blob_table is non-NULL, then each blob in @blob_list that
1462 * has @unhashed set but not @unique_size set is checksummed immediately before
1463 * it would otherwise be read for writing in order to determine if it is
1464 * identical to another blob already being written or one that would be filtered
1465 * out of the output WIM using blob_filtered() with the context @filter_ctx.
1466 * Each such duplicate blob will be removed from @blob_list, its reference count
1467 * transfered to the pre-existing duplicate blob, its memory freed, and will not
1468 * be written. Alternatively, if a blob in @blob_list is a duplicate with any
1469 * blob in @blob_table that has not been marked for writing or would not be
1470 * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1471 * taking ownership of the reference count and slot in the @blob_table_list.
1473 * Returns 0 if every blob was either written successfully or did not need to be
1474 * written; otherwise returns a non-zero error code.
1477 write_blob_list(struct list_head *blob_list,
1478 struct filedes *out_fd,
1479 int write_resource_flags,
1482 unsigned num_threads,
1483 struct blob_table *blob_table,
1484 struct filter_context *filter_ctx,
1485 wimlib_progress_func_t progfunc,
1489 struct write_blobs_ctx ctx;
1490 struct list_head raw_copy_blobs;
1491 u64 num_nonraw_bytes;
1493 wimlib_assert((write_resource_flags &
1494 (WRITE_RESOURCE_FLAG_SOLID |
1495 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1496 (WRITE_RESOURCE_FLAG_SOLID |
1497 WRITE_RESOURCE_FLAG_PIPABLE));
1499 validate_blob_list(blob_list);
1501 if (list_empty(blob_list))
1504 /* If needed, set auxiliary information so that we can detect when the
1505 * library has finished using each external file. */
1506 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1507 init_done_with_file_info(blob_list);
1509 memset(&ctx, 0, sizeof(ctx));
1511 ctx.out_fd = out_fd;
1512 ctx.blob_table = blob_table;
1513 ctx.out_ctype = out_ctype;
1514 ctx.out_chunk_size = out_chunk_size;
1515 ctx.write_resource_flags = write_resource_flags;
1516 ctx.filter_ctx = filter_ctx;
1519 * We normally sort the blobs to write by a "sequential" order that is
1520 * optimized for reading. But when using solid compression, we instead
1521 * sort the blobs by file extension and file name (when applicable; and
1522 * we don't do this for blobs from solid resources) so that similar
1523 * files are grouped together, which improves the compression ratio.
1524 * This is somewhat of a hack since a blob does not necessarily
1525 * correspond one-to-one with a filename, nor is there any guarantee
1526 * that two files with similar names or extensions are actually similar
1527 * in content. A potential TODO is to sort the blobs based on some
1528 * measure of similarity of their actual contents.
1531 ret = sort_blob_list_by_sequential_order(blob_list,
1532 offsetof(struct blob_descriptor,
1537 ret = compute_blob_list_stats(blob_list, &ctx);
1541 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1542 ret = sort_blob_list_for_solid_compression(blob_list);
1544 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1547 ctx.progress_data.progfunc = progfunc;
1548 ctx.progress_data.progctx = progctx;
1550 num_nonraw_bytes = find_raw_copy_blobs(blob_list, write_resource_flags,
1551 out_ctype, out_chunk_size,
1554 /* Copy any compressed resources for which the raw data can be reused
1555 * without decompression. */
1556 ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1557 &ctx.progress_data);
1559 if (ret || num_nonraw_bytes == 0)
1560 goto out_destroy_context;
1562 /* Unless uncompressed output was required, allocate a chunk_compressor
1563 * to do compression. There are serial and parallel implementations of
1564 * the chunk_compressor interface. We default to parallel using the
1565 * specified number of threads, unless the upper bound on the number
1566 * bytes needing to be compressed is less than a heuristic value. */
1567 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1569 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1570 if (num_nonraw_bytes > max(2000000, out_chunk_size)) {
1571 ret = new_parallel_chunk_compressor(out_ctype,
1576 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1577 " Falling back to single-threaded compression.",
1578 wimlib_get_error_string(ret));
1583 if (ctx.compressor == NULL) {
1584 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1587 goto out_destroy_context;
1592 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1594 ctx.progress_data.progress.write_streams.num_threads = 1;
1596 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1597 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1599 ret = call_progress(ctx.progress_data.progfunc,
1600 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1601 &ctx.progress_data.progress,
1602 ctx.progress_data.progctx);
1604 goto out_destroy_context;
1606 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1607 ret = begin_write_resource(&ctx, num_nonraw_bytes);
1609 goto out_destroy_context;
1612 /* Read the list of blobs needing to be compressed, using the specified
1613 * callbacks to execute processing of the data. */
1615 struct read_blob_callbacks cbs = {
1616 .begin_blob = write_blob_begin_read,
1617 .consume_chunk = write_blob_process_chunk,
1618 .end_blob = write_blob_end_read,
1622 ret = read_blob_list(blob_list,
1623 offsetof(struct blob_descriptor, write_blobs_list),
1625 BLOB_LIST_ALREADY_SORTED |
1626 VERIFY_BLOB_HASHES |
1627 COMPUTE_MISSING_BLOB_HASHES);
1630 goto out_destroy_context;
1632 ret = finish_remaining_chunks(&ctx);
1634 goto out_destroy_context;
1636 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1637 struct wim_reshdr reshdr;
1638 struct blob_descriptor *blob;
1641 ret = end_write_resource(&ctx, &reshdr);
1643 goto out_destroy_context;
1646 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1647 blob->out_reshdr.size_in_wim = blob->size;
1648 blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1649 WIM_RESHDR_FLAG_SOLID;
1650 blob->out_reshdr.uncompressed_size = 0;
1651 blob->out_reshdr.offset_in_wim = offset_in_res;
1652 blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1653 blob->out_res_size_in_wim = reshdr.size_in_wim;
1654 blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1655 offset_in_res += blob->size;
1657 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1660 out_destroy_context:
1661 FREE(ctx.chunk_csizes);
1663 ctx.compressor->destroy(ctx.compressor);
1669 write_file_data_blobs(WIMStruct *wim,
1670 struct list_head *blob_list,
1672 unsigned num_threads,
1673 struct filter_context *filter_ctx)
1677 int write_resource_flags;
1679 write_resource_flags = write_flags_to_resource_flags(write_flags);
1681 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1682 out_chunk_size = wim->out_solid_chunk_size;
1683 out_ctype = wim->out_solid_compression_type;
1685 out_chunk_size = wim->out_chunk_size;
1686 out_ctype = wim->out_compression_type;
1689 return write_blob_list(blob_list,
1691 write_resource_flags,
1701 /* Write the contents of the specified blob as a WIM resource. */
1703 write_wim_resource(struct blob_descriptor *blob,
1704 struct filedes *out_fd,
1707 int write_resource_flags)
1709 LIST_HEAD(blob_list);
1710 list_add(&blob->write_blobs_list, &blob_list);
1711 blob->will_be_in_output_wim = 1;
1712 return write_blob_list(&blob_list,
1714 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1724 /* Write the contents of the specified buffer as a WIM resource. */
1726 write_wim_resource_from_buffer(const void *buf,
1729 struct filedes *out_fd,
1732 struct wim_reshdr *out_reshdr,
1734 int write_resource_flags)
1737 struct blob_descriptor blob;
1739 if (unlikely(buf_size == 0)) {
1740 zero_reshdr(out_reshdr);
1742 copy_hash(hash_ret, zero_hash);
1746 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1747 sha1_buffer(buf, buf_size, blob.hash);
1749 blob.is_metadata = is_metadata;
1751 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1752 write_resource_flags);
1756 copy_reshdr(out_reshdr, &blob.out_reshdr);
1759 copy_hash(hash_ret, blob.hash);
1763 struct blob_size_table {
1764 struct hlist_head *array;
1770 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1772 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1773 if (tab->array == NULL)
1774 return WIMLIB_ERR_NOMEM;
1775 tab->num_entries = 0;
1776 tab->capacity = capacity;
1781 destroy_blob_size_table(struct blob_size_table *tab)
1787 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1789 struct blob_size_table *tab = _tab;
1791 struct blob_descriptor *same_size_blob;
1793 pos = hash_u64(blob->size) % tab->capacity;
1794 blob->unique_size = 1;
1795 hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1796 if (same_size_blob->size == blob->size) {
1797 blob->unique_size = 0;
1798 same_size_blob->unique_size = 0;
1803 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1808 struct find_blobs_ctx {
1811 struct list_head blob_list;
1812 struct blob_size_table blob_size_tab;
1816 reference_blob_for_write(struct blob_descriptor *blob,
1817 struct list_head *blob_list, u32 nref)
1819 if (!blob->will_be_in_output_wim) {
1820 blob->out_refcnt = 0;
1821 list_add_tail(&blob->write_blobs_list, blob_list);
1822 blob->will_be_in_output_wim = 1;
1824 blob->out_refcnt += nref;
1828 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1830 struct list_head *blob_list = _blob_list;
1831 blob->will_be_in_output_wim = 0;
1832 reference_blob_for_write(blob, blob_list, blob->refcnt);
1837 inode_find_blobs_to_reference(const struct wim_inode *inode,
1838 const struct blob_table *table,
1839 struct list_head *blob_list)
1841 wimlib_assert(inode->i_nlink > 0);
1843 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1844 struct blob_descriptor *blob;
1847 blob = stream_blob(&inode->i_streams[i], table);
1849 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1851 hash = stream_hash(&inode->i_streams[i]);
1852 if (!is_zero_hash(hash))
1853 return blob_not_found_error(inode, hash);
1860 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1862 blob->will_be_in_output_wim = 0;
1867 image_find_blobs_to_reference(WIMStruct *wim)
1869 struct wim_image_metadata *imd;
1870 struct wim_inode *inode;
1871 struct blob_descriptor *blob;
1872 struct list_head *blob_list;
1875 imd = wim_get_current_image_metadata(wim);
1877 image_for_each_unhashed_blob(blob, imd)
1878 blob->will_be_in_output_wim = 0;
1880 blob_list = wim->private;
1881 image_for_each_inode(inode, imd) {
1882 ret = inode_find_blobs_to_reference(inode,
1892 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1895 struct list_head *blob_list_ret)
1899 INIT_LIST_HEAD(blob_list_ret);
1901 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1902 (image == 1 && wim->hdr.image_count == 1)))
1904 /* Fast case: Assume that all blobs are being written and that
1905 * the reference counts are correct. */
1906 struct blob_descriptor *blob;
1907 struct wim_image_metadata *imd;
1910 for_blob_in_table(wim->blob_table,
1911 fully_reference_blob_for_write,
1914 for (i = 0; i < wim->hdr.image_count; i++) {
1915 imd = wim->image_metadata[i];
1916 image_for_each_unhashed_blob(blob, imd)
1917 fully_reference_blob_for_write(blob, blob_list_ret);
1920 /* Slow case: Walk through the images being written and
1921 * determine the blobs referenced. */
1922 for_blob_in_table(wim->blob_table,
1923 do_blob_set_not_in_output_wim, NULL);
1924 wim->private = blob_list_ret;
1925 ret = for_image(wim, image, image_find_blobs_to_reference);
1933 struct insert_other_if_hard_filtered_ctx {
1934 struct blob_size_table *tab;
1935 struct filter_context *filter_ctx;
1939 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1941 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1943 if (!blob->will_be_in_output_wim &&
1944 blob_hard_filtered(blob, ctx->filter_ctx))
1945 blob_size_table_insert(blob, ctx->tab);
1950 determine_blob_size_uniquity(struct list_head *blob_list,
1951 struct blob_table *lt,
1952 struct filter_context *filter_ctx)
1955 struct blob_size_table tab;
1956 struct blob_descriptor *blob;
1958 ret = init_blob_size_table(&tab, 9001);
1962 if (may_hard_filter_blobs(filter_ctx)) {
1963 struct insert_other_if_hard_filtered_ctx ctx = {
1965 .filter_ctx = filter_ctx,
1967 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
1970 list_for_each_entry(blob, blob_list, write_blobs_list)
1971 blob_size_table_insert(blob, &tab);
1973 destroy_blob_size_table(&tab);
1978 filter_blob_list_for_write(struct list_head *blob_list,
1979 struct filter_context *filter_ctx)
1981 struct blob_descriptor *blob, *tmp;
1983 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1984 int status = blob_filtered(blob, filter_ctx);
1991 /* Soft filtered. */
1993 /* Hard filtered. */
1994 blob->will_be_in_output_wim = 0;
1995 list_del(&blob->blob_table_list);
1997 list_del(&blob->write_blobs_list);
2003 * prepare_blob_list_for_write() -
2005 * Prepare the list of blobs to write for writing a WIM containing the specified
2006 * image(s) with the specified write flags.
2009 * The WIMStruct on whose behalf the write is occurring.
2012 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2015 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2017 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
2018 * table of @wim and the per-image lists of unhashed blobs should be taken
2019 * as-is, and image metadata should not be searched for references. This
2020 * does not exclude filtering with APPEND and SKIP_EXTERNAL_WIMS, below.
2022 * APPEND: Blobs already present in @wim shall not be returned in
2025 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
2026 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
2029 * List of blobs, linked by write_blobs_list, that need to be written will
2032 * Note that this function assumes that unhashed blobs will be written; it
2033 * does not take into account that they may become duplicates when actually
2036 * @blob_table_list_ret
2037 * List of blobs, linked by blob_table_list, that need to be included in
2038 * the WIM's blob table will be returned here. This will be a superset of
2039 * the blobs in @blob_list_ret.
2041 * This list will be a proper superset of @blob_list_ret if and only if
2042 * WIMLIB_WRITE_FLAG_APPEND was specified in @write_flags and some of the
2043 * blobs that would otherwise need to be written were already located in
2046 * All blobs in this list will have @out_refcnt set to the number of
2047 * references to the blob in the output WIM. If
2048 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2049 * may be as low as 0.
2052 * A context for queries of blob filter status with blob_filtered() is
2053 * returned in this location.
2055 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2056 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2057 * inserted into @blob_table_list_ret.
2059 * Still furthermore, @unique_size will be set to 1 on all blobs in
2060 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2061 * among all blobs in the blob table of @wim that are ineligible for being
2062 * written due to filtering.
2064 * Returns 0 on success; nonzero on read error, memory allocation error, or
2068 prepare_blob_list_for_write(WIMStruct *wim, int image,
2070 struct list_head *blob_list_ret,
2071 struct list_head *blob_table_list_ret,
2072 struct filter_context *filter_ctx_ret)
2075 struct blob_descriptor *blob;
2077 filter_ctx_ret->write_flags = write_flags;
2078 filter_ctx_ret->wim = wim;
2080 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2083 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2088 INIT_LIST_HEAD(blob_table_list_ret);
2089 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2090 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2092 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2097 if (may_filter_blobs(filter_ctx_ret))
2098 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2104 write_file_data(WIMStruct *wim, int image, int write_flags,
2105 unsigned num_threads,
2106 struct list_head *blob_list_override,
2107 struct list_head *blob_table_list_ret)
2110 struct list_head _blob_list;
2111 struct list_head *blob_list;
2112 struct blob_descriptor *blob;
2113 struct filter_context _filter_ctx;
2114 struct filter_context *filter_ctx;
2116 if (blob_list_override == NULL) {
2117 /* Normal case: prepare blob list from image(s) being written.
2119 blob_list = &_blob_list;
2120 filter_ctx = &_filter_ctx;
2121 ret = prepare_blob_list_for_write(wim, image, write_flags,
2123 blob_table_list_ret,
2128 /* Currently only as a result of wimlib_split() being called:
2129 * use blob list already explicitly provided. Use existing
2130 * reference counts. */
2131 blob_list = blob_list_override;
2133 INIT_LIST_HEAD(blob_table_list_ret);
2134 list_for_each_entry(blob, blob_list, write_blobs_list) {
2135 blob->out_refcnt = blob->refcnt;
2136 blob->will_be_in_output_wim = 1;
2137 blob->unique_size = 0;
2138 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2142 return write_file_data_blobs(wim,
2150 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2155 int write_resource_flags;
2157 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2160 write_resource_flags = write_flags_to_resource_flags(write_flags);
2162 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2164 ret = call_progress(wim->progfunc,
2165 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2166 NULL, wim->progctx);
2170 if (image == WIMLIB_ALL_IMAGES) {
2172 end_image = wim->hdr.image_count;
2174 start_image = image;
2178 for (int i = start_image; i <= end_image; i++) {
2179 struct wim_image_metadata *imd;
2181 imd = wim->image_metadata[i - 1];
2182 /* Build a new metadata resource only if image was modified from
2183 * the original (or was newly added). Otherwise just copy the
2185 if (imd->modified) {
2186 ret = write_metadata_resource(wim, i,
2187 write_resource_flags);
2188 } else if (write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT) {
2189 /* For compactions, existing metadata resources are
2190 * written along with the existing file resources. */
2192 } else if (write_flags & WIMLIB_WRITE_FLAG_APPEND) {
2193 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2196 ret = write_wim_resource(imd->metadata_blob,
2198 wim->out_compression_type,
2199 wim->out_chunk_size,
2200 write_resource_flags);
2206 return call_progress(wim->progfunc,
2207 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2208 NULL, wim->progctx);
2212 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2214 int raw_fd = topen(path, open_flags | O_BINARY, 0644);
2216 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2217 return WIMLIB_ERR_OPEN;
2219 filedes_init(&wim->out_fd, raw_fd);
2224 close_wim_writable(WIMStruct *wim, int write_flags)
2228 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2229 if (filedes_valid(&wim->out_fd))
2230 if (filedes_close(&wim->out_fd))
2231 ret = WIMLIB_ERR_WRITE;
2232 filedes_invalidate(&wim->out_fd);
2237 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2239 const struct blob_descriptor *blob1, *blob2;
2241 blob1 = *(const struct blob_descriptor**)p1;
2242 blob2 = *(const struct blob_descriptor**)p2;
2244 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2245 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2246 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2247 return cmp_u64(blob1->out_res_offset_in_wim,
2248 blob2->out_res_offset_in_wim);
2253 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2256 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2257 blob2->out_reshdr.offset_in_wim);
2261 write_blob_table(WIMStruct *wim, int image, int write_flags,
2262 struct list_head *blob_table_list)
2266 /* Set output resource metadata for blobs already present in WIM. */
2267 if (write_flags & WIMLIB_WRITE_FLAG_APPEND) {
2268 struct blob_descriptor *blob;
2269 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2270 if (blob->blob_location == BLOB_IN_WIM &&
2271 blob->rdesc->wim == wim)
2273 blob_set_out_reshdr_for_reuse(blob);
2278 ret = sort_blob_list(blob_table_list,
2279 offsetof(struct blob_descriptor, blob_table_list),
2280 cmp_blobs_by_out_rdesc);
2284 /* Add entries for metadata resources. */
2285 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2289 if (image == WIMLIB_ALL_IMAGES) {
2291 end_image = wim->hdr.image_count;
2293 start_image = image;
2297 /* Push metadata blob table entries onto the front of the list
2298 * in reverse order, so that they're written in order.
2300 for (int i = end_image; i >= start_image; i--) {
2301 struct blob_descriptor *metadata_blob;
2303 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2304 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2305 metadata_blob->out_refcnt = 1;
2306 list_add(&metadata_blob->blob_table_list, blob_table_list);
2310 return write_blob_table_from_blob_list(blob_table_list,
2312 wim->out_hdr.part_number,
2313 &wim->out_hdr.blob_table_reshdr,
2314 write_flags_to_resource_flags(write_flags));
2318 * Finish writing a WIM file: write the blob table, xml data, and integrity
2319 * table, then overwrite the WIM header.
2321 * The output file descriptor is closed on success, except when writing to a
2322 * user-specified file descriptor (WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR set).
2325 finish_write(WIMStruct *wim, int image, int write_flags,
2326 struct list_head *blob_table_list)
2328 int write_resource_flags;
2329 off_t old_blob_table_end = 0;
2330 struct integrity_table *old_integrity_table = NULL;
2331 off_t new_blob_table_end;
2335 write_resource_flags = write_flags_to_resource_flags(write_flags);
2337 /* In the WIM header, there is room for the resource entry for a
2338 * metadata resource labeled as the "boot metadata". This entry should
2339 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2340 * it should be a copy of the resource entry for the image that is
2341 * marked as bootable. */
2342 if (wim->out_hdr.boot_idx == 0) {
2343 zero_reshdr(&wim->out_hdr.boot_metadata_reshdr);
2345 copy_reshdr(&wim->out_hdr.boot_metadata_reshdr,
2346 &wim->image_metadata[
2347 wim->out_hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2350 /* If appending to a WIM file containing an integrity table, we'd like
2351 * to re-use the information in the old integrity table instead of
2352 * recalculating it. But we might overwrite the old integrity table
2353 * when we expand the XML data. Read it into memory just in case. */
2354 if ((write_flags & (WIMLIB_WRITE_FLAG_APPEND |
2355 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2356 (WIMLIB_WRITE_FLAG_APPEND |
2357 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2358 && wim_has_integrity_table(wim))
2360 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2361 wim->hdr.blob_table_reshdr.size_in_wim;
2362 (void)read_integrity_table(wim,
2363 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2364 &old_integrity_table);
2365 /* If we couldn't read the old integrity table, we can still
2366 * re-calculate the full integrity table ourselves. Hence the
2367 * ignoring of the return value. */
2370 /* Write blob table if needed. */
2371 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
2372 ret = write_blob_table(wim, image, write_flags,
2375 free_integrity_table(old_integrity_table);
2380 /* Write XML data. */
2381 xml_totalbytes = wim->out_fd.offset;
2382 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2383 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2384 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2385 &wim->out_hdr.xml_data_reshdr,
2386 write_resource_flags);
2388 free_integrity_table(old_integrity_table);
2392 /* Write integrity table if needed. */
2393 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2394 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS) {
2395 /* The XML data we wrote may have overwritten part of
2396 * the old integrity table, so while calculating the new
2397 * integrity table we should temporarily update the WIM
2398 * header to remove the integrity table reference. */
2399 struct wim_header checkpoint_hdr;
2400 memcpy(&checkpoint_hdr, &wim->out_hdr, sizeof(struct wim_header));
2401 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2402 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2403 ret = write_wim_header(&checkpoint_hdr, &wim->out_fd, 0);
2405 free_integrity_table(old_integrity_table);
2410 new_blob_table_end = wim->out_hdr.blob_table_reshdr.offset_in_wim +
2411 wim->out_hdr.blob_table_reshdr.size_in_wim;
2413 ret = write_integrity_table(wim,
2416 old_integrity_table);
2417 free_integrity_table(old_integrity_table);
2421 /* No integrity table. */
2422 zero_reshdr(&wim->out_hdr.integrity_table_reshdr);
2425 /* Now that all information in the WIM header has been determined, the
2426 * preliminary header written earlier can be overwritten, the header of
2427 * the existing WIM file can be overwritten, or the final header can be
2428 * written to the end of the pipable WIM. */
2429 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2430 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2431 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2433 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, 0);
2437 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)) {
2438 /* Truncate any data the compaction freed up. */
2439 if (ftruncate(wim->out_fd.fd, wim->out_fd.offset)) {
2440 ERROR_WITH_ERRNO("Failed to truncate the output WIM file");
2441 return WIMLIB_ERR_WRITE;
2445 /* Possibly sync file data to disk before closing. On POSIX systems, it
2446 * is necessary to do this before using rename() to overwrite an
2447 * existing file with a new file. Otherwise, data loss would occur if
2448 * the system is abruptly terminated when the metadata for the rename
2449 * operation has been written to disk, but the new file data has not.
2451 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2452 if (fsync(wim->out_fd.fd)) {
2453 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2454 return WIMLIB_ERR_WRITE;
2458 if (close_wim_writable(wim, write_flags)) {
2459 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2460 return WIMLIB_ERR_WRITE;
2466 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2468 /* Set advisory lock on WIM file (if not already done so) */
2470 lock_wim_for_append(WIMStruct *wim)
2472 if (wim->locked_for_append)
2474 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2475 wim->locked_for_append = 1;
2478 if (errno != EWOULDBLOCK)
2480 return WIMLIB_ERR_ALREADY_LOCKED;
2483 /* Remove advisory lock on WIM file (if present) */
2485 unlock_wim_for_append(WIMStruct *wim)
2487 if (wim->locked_for_append) {
2488 flock(wim->in_fd.fd, LOCK_UN);
2489 wim->locked_for_append = 0;
2495 * write_pipable_wim():
2497 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2498 * capable of being applied from a pipe).
2500 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2501 * images can be applied from them sequentially when the file data is sent over
2502 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2503 * The modifications made to the WIM format for pipable WIMs are:
2505 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2506 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2507 * stops other software from trying to read the file as a normal WIM.
2509 * - The header at the beginning of the file does not contain all the normal
2510 * information; in particular it will have all 0's for the blob table and XML
2511 * data resource entries. This is because this information cannot be
2512 * determined until the blob table and XML data have been written.
2513 * Consequently, wimlib will write the full header at the very end of the
2514 * file. The header at the end, however, is only used when reading the WIM
2515 * from a seekable file (not a pipe).
2517 * - An extra copy of the XML data is placed directly after the header. This
2518 * allows image names and sizes to be determined at an appropriate time when
2519 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2520 * WIM is read from a seekable file (not a pipe).
2522 * - Solid resources are not allowed. Each blob is always stored in its own
2525 * - The format of resources, or blobs, has been modified to allow them to be
2526 * used before the "blob table" has been read. Each blob is prefixed with a
2527 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2528 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2529 * uncompressed blob size, and flags that indicate whether the blob is
2530 * compressed. The data of uncompressed blobs then follows literally, while
2531 * the data of compressed blobs follows in a modified format. Compressed
2532 * blobs do not begin with a chunk table, since the chunk table cannot be
2533 * written until all chunks have been compressed. Instead, each compressed
2534 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2535 * Furthermore, the chunk table is written at the end of the resource instead
2536 * of the start. Note: chunk offsets are given in the chunk table as if the
2537 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2538 * used if the WIM is being read from a seekable file (not a pipe).
2540 * - Metadata blobs always come before non-metadata blobs. (This does not by
2541 * itself constitute an incompatibility with normal WIMs, since this is valid
2544 * - At least up to the end of the blobs, all components must be packed as
2545 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2546 * not by itself consititute an incompatibility with normal WIMs, since this
2547 * is valid in normal WIMs.)
2549 * Note: the blob table, XML data, and header at the end are not used when
2550 * applying from a pipe. They exist to support functionality such as image
2551 * application and export when the WIM is *not* read from a pipe.
2553 * Layout of pipable WIM:
2555 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2556 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2557 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2559 * Layout of normal WIM:
2561 * +--------+-----------------------------+-------------------------+
2562 * | Header | File and metadata resources | Blob table | XML data |
2563 * +--------+-----------------------------+-------------------------+
2565 * An optional integrity table can follow the final XML data in both normal and
2566 * pipable WIMs. However, due to implementation details, wimlib currently can
2567 * only include an integrity table in a pipable WIM when writing it to a
2568 * seekable file (not a pipe).
2570 * Do note that since pipable WIMs are not supported by Microsoft's software,
2571 * wimlib does not create them unless explicitly requested (with
2572 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2573 * characters to identify the file.
2576 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2577 unsigned num_threads,
2578 struct list_head *blob_list_override,
2579 struct list_head *blob_table_list_ret)
2582 struct wim_reshdr xml_reshdr;
2584 WARNING("Creating a pipable WIM, which will "
2586 " with Microsoft's software (WIMGAPI/ImageX/DISM).");
2588 /* At this point, the header at the beginning of the file has already
2591 /* For efficiency, when wimlib adds an image to the WIM with
2592 * wimlib_add_image(), the SHA-1 message digests of files are not
2593 * calculated; instead, they are calculated while the files are being
2594 * written. However, this does not work when writing a pipable WIM,
2595 * since when writing a blob to a pipable WIM, its SHA-1 message digest
2596 * needs to be known before the blob data is written. Therefore, before
2597 * getting much farther, we need to pre-calculate the SHA-1 message
2598 * digests of all blobs that will be written. */
2599 ret = wim_checksum_unhashed_blobs(wim);
2603 /* Write extra copy of the XML data. */
2604 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2605 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2609 /* Write metadata resources for the image(s) being included in the
2611 ret = write_metadata_resources(wim, image, write_flags);
2615 /* Write file data needed for the image(s) being included in the output
2616 * WIM, or file data needed for the split WIM part. */
2617 return write_file_data(wim, image, write_flags,
2618 num_threads, blob_list_override,
2619 blob_table_list_ret);
2621 /* The blob table, XML data, and header at end are handled by
2622 * finish_write(). */
2626 should_default_to_solid_compression(WIMStruct *wim, int write_flags)
2628 return wim->out_hdr.wim_version == WIM_VERSION_SOLID &&
2629 !(write_flags & (WIMLIB_WRITE_FLAG_SOLID |
2630 WIMLIB_WRITE_FLAG_PIPABLE)) &&
2631 wim_has_solid_resources(wim);
2634 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2637 write_wim_part(WIMStruct *wim,
2638 const void *path_or_fd,
2641 unsigned num_threads,
2642 unsigned part_number,
2643 unsigned total_parts,
2644 struct list_head *blob_list_override,
2648 struct list_head blob_table_list;
2650 /* Internally, this is always called with a valid part number and total
2652 wimlib_assert(total_parts >= 1);
2653 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2655 /* A valid image (or all images) must be specified. */
2656 if (image != WIMLIB_ALL_IMAGES &&
2657 (image < 1 || image > wim->hdr.image_count))
2658 return WIMLIB_ERR_INVALID_IMAGE;
2660 /* If we need to write metadata resources, make sure the ::WIMStruct has
2661 * the needed information attached (e.g. is not a resource-only WIM,
2662 * such as a non-first part of a split WIM). */
2663 if (!wim_has_metadata(wim) &&
2664 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2665 return WIMLIB_ERR_METADATA_NOT_FOUND;
2667 /* Check for contradictory flags. */
2668 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2669 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2670 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2671 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2672 return WIMLIB_ERR_INVALID_PARAM;
2674 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2675 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2676 == (WIMLIB_WRITE_FLAG_PIPABLE |
2677 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2678 return WIMLIB_ERR_INVALID_PARAM;
2680 /* Only wimlib_overwrite() accepts UNSAFE_COMPACT. */
2681 if (write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)
2682 return WIMLIB_ERR_INVALID_PARAM;
2684 /* Include an integrity table by default if no preference was given and
2685 * the WIM already had an integrity table. */
2686 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2687 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))) {
2688 if (wim_has_integrity_table(wim))
2689 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2692 /* Write a pipable WIM by default if no preference was given and the WIM
2693 * was already pipable. */
2694 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2695 WIMLIB_WRITE_FLAG_NOT_PIPABLE))) {
2696 if (wim_is_pipable(wim))
2697 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2700 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2701 WIMLIB_WRITE_FLAG_SOLID))
2702 == (WIMLIB_WRITE_FLAG_PIPABLE |
2703 WIMLIB_WRITE_FLAG_SOLID))
2705 ERROR("Solid compression is unsupported in pipable WIMs");
2706 return WIMLIB_ERR_INVALID_PARAM;
2709 /* Start initializing the new file header. */
2710 memset(&wim->out_hdr, 0, sizeof(wim->out_hdr));
2712 /* Set the magic number. */
2713 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2714 wim->out_hdr.magic = PWM_MAGIC;
2716 wim->out_hdr.magic = WIM_MAGIC;
2718 /* Set the version number. */
2719 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2720 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2721 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2723 wim->out_hdr.wim_version = WIM_VERSION_DEFAULT;
2725 /* Default to solid compression if it is valid in the chosen WIM file
2726 * format and the WIMStruct references any solid resources. This is
2727 * useful when exporting an image from a solid WIM. */
2728 if (should_default_to_solid_compression(wim, write_flags))
2729 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2731 /* Set the header flags. */
2732 wim->out_hdr.flags = (wim->hdr.flags & (WIM_HDR_FLAG_RP_FIX |
2733 WIM_HDR_FLAG_READONLY));
2734 if (total_parts != 1)
2735 wim->out_hdr.flags |= WIM_HDR_FLAG_SPANNED;
2736 if (wim->out_compression_type != WIMLIB_COMPRESSION_TYPE_NONE) {
2737 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESSION;
2738 switch (wim->out_compression_type) {
2739 case WIMLIB_COMPRESSION_TYPE_XPRESS:
2740 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_XPRESS;
2742 case WIMLIB_COMPRESSION_TYPE_LZX:
2743 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZX;
2745 case WIMLIB_COMPRESSION_TYPE_LZMS:
2746 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZMS;
2751 /* Set the chunk size. */
2752 wim->out_hdr.chunk_size = wim->out_chunk_size;
2755 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2756 guid = wim->hdr.guid;
2758 copy_guid(wim->out_hdr.guid, guid);
2760 generate_guid(wim->out_hdr.guid);
2762 /* Set the part number and total parts. */
2763 wim->out_hdr.part_number = part_number;
2764 wim->out_hdr.total_parts = total_parts;
2766 /* Set the image count. */
2767 if (image == WIMLIB_ALL_IMAGES)
2768 wim->out_hdr.image_count = wim->hdr.image_count;
2770 wim->out_hdr.image_count = 1;
2772 /* Set the boot index. */
2773 wim->out_hdr.boot_idx = 0;
2774 if (total_parts == 1) {
2775 if (image == WIMLIB_ALL_IMAGES)
2776 wim->out_hdr.boot_idx = wim->hdr.boot_idx;
2777 else if (image == wim->hdr.boot_idx)
2778 wim->out_hdr.boot_idx = 1;
2781 /* Set up the output file descriptor. */
2782 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2783 /* File descriptor was explicitly provided. */
2784 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2785 if (!filedes_is_seekable(&wim->out_fd)) {
2786 /* The file descriptor is a pipe. */
2787 ret = WIMLIB_ERR_INVALID_PARAM;
2788 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2790 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2791 ERROR("Can't include integrity check when "
2792 "writing pipable WIM to pipe!");
2797 /* Filename of WIM to write was provided; open file descriptor
2799 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2800 O_TRUNC | O_CREAT | O_RDWR);
2805 /* Write initial header. This is merely a "dummy" header since it
2806 * doesn't have resource entries filled in yet, so it will be
2807 * overwritten later (unless writing a pipable WIM). */
2808 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2809 wim->out_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2810 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2811 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2815 /* Write file data and metadata resources. */
2816 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2817 /* Default case: create a normal (non-pipable) WIM. */
2818 ret = write_file_data(wim, image, write_flags,
2825 ret = write_metadata_resources(wim, image, write_flags);
2829 /* Non-default case: create pipable WIM. */
2830 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2837 /* Write blob table, XML data, and (optional) integrity table. */
2838 ret = finish_write(wim, image, write_flags, &blob_table_list);
2840 (void)close_wim_writable(wim, write_flags);
2844 /* Write a standalone WIM to a file or file descriptor. */
2846 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2847 int image, int write_flags, unsigned num_threads)
2849 return write_wim_part(wim, path_or_fd, image, write_flags,
2850 num_threads, 1, 1, NULL, NULL);
2853 /* API function documented in wimlib.h */
2855 wimlib_write(WIMStruct *wim, const tchar *path,
2856 int image, int write_flags, unsigned num_threads)
2858 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2859 return WIMLIB_ERR_INVALID_PARAM;
2861 if (path == NULL || path[0] == T('\0'))
2862 return WIMLIB_ERR_INVALID_PARAM;
2864 return write_standalone_wim(wim, path, image, write_flags, num_threads);
2867 /* API function documented in wimlib.h */
2869 wimlib_write_to_fd(WIMStruct *wim, int fd,
2870 int image, int write_flags, unsigned num_threads)
2872 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2873 return WIMLIB_ERR_INVALID_PARAM;
2876 return WIMLIB_ERR_INVALID_PARAM;
2878 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2880 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2884 any_images_modified(WIMStruct *wim)
2886 for (int i = 0; i < wim->hdr.image_count; i++)
2887 if (wim->image_metadata[i]->modified)
2893 check_resource_offset(struct blob_descriptor *blob, void *_wim)
2895 const WIMStruct *wim = _wim;
2896 off_t end_offset = *(const off_t*)wim->private;
2898 if (blob->blob_location == BLOB_IN_WIM &&
2899 blob->rdesc->wim == wim &&
2900 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
2901 return WIMLIB_ERR_RESOURCE_ORDER;
2905 /* Make sure no file or metadata resources are located after the XML data (or
2906 * integrity table if present)--- otherwise we can't safely append to the WIM
2907 * file and we return WIMLIB_ERR_RESOURCE_ORDER. */
2909 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2914 wim->private = &end_offset;
2915 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
2919 for (i = 0; i < wim->hdr.image_count; i++) {
2920 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
2928 * Overwrite a WIM, possibly appending new resources to it.
2930 * A WIM looks like (or is supposed to look like) the following:
2932 * Header (212 bytes)
2933 * Resources for metadata and files (variable size)
2934 * Blob table (variable size)
2935 * XML data (variable size)
2936 * Integrity table (optional) (variable size)
2938 * If we are not adding any new files or metadata, then the blob table is
2939 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2940 * header. This operation is potentially unsafe if the program is abruptly
2941 * terminated while the XML data or integrity table are being overwritten, but
2942 * before the new header has been written. To partially alleviate this problem,
2943 * we write a temporary header after the XML data has been written. This may
2944 * prevent the WIM from becoming corrupted if the program is terminated while
2945 * the integrity table is being calculated (but no guarantees, due to write
2948 * If we are adding new blobs, including new file data as well as any metadata
2949 * for any new images, then the blob table needs to be changed, and those blobs
2950 * need to be written. In this case, we try to perform a safe update of the WIM
2951 * file by writing the blobs *after* the end of the previous WIM, then writing
2952 * the new blob table, XML data, and (optionally) integrity table following the
2953 * new blobs. This will produce a layout like the following:
2955 * Header (212 bytes)
2956 * (OLD) Resources for metadata and files (variable size)
2957 * (OLD) Blob table (variable size)
2958 * (OLD) XML data (variable size)
2959 * (OLD) Integrity table (optional) (variable size)
2960 * (NEW) Resources for metadata and files (variable size)
2961 * (NEW) Blob table (variable size)
2962 * (NEW) XML data (variable size)
2963 * (NEW) Integrity table (optional) (variable size)
2965 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2966 * the header is overwritten to point to the new blob table, XML data, and
2967 * integrity table, to produce the following layout:
2969 * Header (212 bytes)
2970 * Resources for metadata and files (variable size)
2971 * Nothing (variable size)
2972 * Resources for metadata and files (variable size)
2973 * Blob table (variable size)
2974 * XML data (variable size)
2975 * Integrity table (optional) (variable size)
2977 * This function allows an image to be appended to a large WIM very quickly, and
2978 * is crash-safe except in the case of write re-ordering, but the disadvantage
2979 * is that a small hole is left in the WIM where the old blob table, xml data,
2980 * and integrity table were. (These usually only take up a small amount of
2981 * space compared to the blobs, however.)
2983 * Finally, this function also supports "compaction" overwrites as an
2984 * alternative to the normal "append" overwrites described above. In a
2985 * compaction, data is written starting immediately from the end of the header.
2986 * All existing resources are written first, in order by file offset. New
2987 * resources are written afterwards, and at the end any extra data is truncated
2988 * from the file. The advantage of this approach is that is that the WIM file
2989 * ends up fully optimized, without any holes remaining. The main disadavantage
2990 * is that this operation is fundamentally unsafe and cannot be interrupted
2991 * without data corruption. Consequently, compactions are only ever done when
2992 * explicitly requested by the library user with the flag
2993 * WIMLIB_WRITE_FLAG_UNSAFE_COMPACT. (Another disadvantage is that a compaction
2994 * can be much slower than an append.)
2997 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3001 struct list_head blob_list;
3002 struct list_head blob_table_list;
3003 struct filter_context filter_ctx;
3005 /* Include an integrity table by default if no preference was given and
3006 * the WIM already had an integrity table. */
3007 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3008 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3009 if (wim_has_integrity_table(wim))
3010 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3012 /* Start preparing the updated file header. */
3013 memcpy(&wim->out_hdr, &wim->hdr, sizeof(wim->out_hdr));
3015 /* If using solid compression, the version number must be set to
3016 * WIM_VERSION_SOLID. */
3017 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
3018 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
3020 /* Default to solid compression if it is valid in the chosen WIM file
3021 * format and the WIMStruct references any solid resources. This is
3022 * useful when updating a solid WIM. */
3023 if (should_default_to_solid_compression(wim, write_flags))
3024 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
3026 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)) {
3028 /* In-place compaction */
3030 WARNING("The WIM file \"%"TS"\" is being compacted in place.\n"
3031 " Do *not* interrupt the operation, or else "
3032 "the WIM file will be\n"
3033 " corrupted!", wim->filename);
3034 wim->being_compacted = 1;
3035 old_wim_end = WIM_HEADER_DISK_SIZE;
3037 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES,
3038 write_flags, &blob_list,
3039 &blob_table_list, &filter_ctx);
3043 if (wim_has_metadata(wim)) {
3044 /* Add existing metadata resources to be compacted along
3045 * with the file resources. */
3046 for (int i = 0; i < wim->hdr.image_count; i++) {
3047 struct wim_image_metadata *imd = wim->image_metadata[i];
3048 if (!imd->modified) {
3049 fully_reference_blob_for_write(imd->metadata_blob,
3055 u64 old_blob_table_end, old_xml_begin, old_xml_end;
3057 /* Set additional flags for append. */
3058 write_flags |= WIMLIB_WRITE_FLAG_APPEND |
3059 WIMLIB_WRITE_FLAG_STREAMS_OK;
3061 /* Make sure there is no data after the XML data, except
3062 * possibily an integrity table. If this were the case, then
3063 * this data would be overwritten. */
3064 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3065 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3066 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
3067 wim->hdr.blob_table_reshdr.size_in_wim;
3068 if (wim_has_integrity_table(wim) &&
3069 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3070 WARNING("Didn't expect the integrity table to be "
3071 "before the XML data");
3072 ret = WIMLIB_ERR_RESOURCE_ORDER;
3076 if (old_blob_table_end > old_xml_begin) {
3077 WARNING("Didn't expect the blob table to be after "
3079 ret = WIMLIB_ERR_RESOURCE_ORDER;
3082 /* Set @old_wim_end, which indicates the point beyond which we
3083 * don't allow any file and metadata resources to appear without
3084 * returning WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we
3085 * would otherwise overwrite these resources). */
3086 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
3087 /* If no images have been modified and no images have
3088 * been deleted, a new blob table does not need to be
3089 * written. We shall write the new XML data and
3090 * optional integrity table immediately after the blob
3091 * table. Note that this may overwrite an existing
3092 * integrity table. */
3093 old_wim_end = old_blob_table_end;
3094 write_flags |= WIMLIB_WRITE_FLAG_NO_NEW_BLOBS;
3095 } else if (wim_has_integrity_table(wim)) {
3096 /* Old WIM has an integrity table; begin writing new
3097 * blobs after it. */
3098 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3099 wim->hdr.integrity_table_reshdr.size_in_wim;
3101 /* No existing integrity table; begin writing new blobs
3102 * after the old XML data. */
3103 old_wim_end = old_xml_end;
3106 ret = check_resource_offsets(wim, old_wim_end);
3110 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES,
3111 write_flags, &blob_list,
3112 &blob_table_list, &filter_ctx);
3116 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)
3117 wimlib_assert(list_empty(&blob_list));
3120 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3124 ret = lock_wim_for_append(wim);
3128 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3129 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3130 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3131 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3133 ERROR_WITH_ERRNO("Error updating WIM header flags");
3134 goto out_unlock_wim;
3137 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3138 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3139 ret = WIMLIB_ERR_WRITE;
3140 goto out_restore_hdr;
3143 ret = write_file_data_blobs(wim, &blob_list, write_flags,
3144 num_threads, &filter_ctx);
3148 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3152 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3157 unlock_wim_for_append(wim);
3161 if (!(write_flags & (WIMLIB_WRITE_FLAG_NO_NEW_BLOBS |
3162 WIMLIB_WRITE_FLAG_UNSAFE_COMPACT))) {
3163 WARNING("Truncating \"%"TS"\" to its original size "
3164 "(%"PRIu64" bytes)", wim->filename, old_wim_end);
3165 /* Return value of ftruncate() is ignored because this is
3166 * already an error path. */
3167 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3170 (void)write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3172 unlock_wim_for_append(wim);
3174 (void)close_wim_writable(wim, write_flags);
3176 wim->being_compacted = 0;
3181 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3183 size_t wim_name_len;
3186 /* Write the WIM to a temporary file in the same directory as the
3188 wim_name_len = tstrlen(wim->filename);
3189 tchar tmpfile[wim_name_len + 10];
3190 tmemcpy(tmpfile, wim->filename, wim_name_len);
3191 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3192 tmpfile[wim_name_len + 9] = T('\0');
3194 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3196 WIMLIB_WRITE_FLAG_FSYNC |
3197 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3204 if (filedes_valid(&wim->in_fd)) {
3205 filedes_close(&wim->in_fd);
3206 filedes_invalidate(&wim->in_fd);
3209 /* Rename the new WIM file to the original WIM file. Note: on Windows
3210 * this actually calls win32_rename_replacement(), not _wrename(), so
3211 * that removing the existing destination file can be handled. */
3212 ret = trename(tmpfile, wim->filename);
3214 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3215 tmpfile, wim->filename);
3222 return WIMLIB_ERR_RENAME;
3225 union wimlib_progress_info progress;
3226 progress.rename.from = tmpfile;
3227 progress.rename.to = wim->filename;
3228 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3229 &progress, wim->progctx);
3232 /* Determine if the specified WIM file may be updated in-place rather than by
3233 * writing and replacing it with an entirely new file. */
3235 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3237 /* REBUILD flag forces full rebuild. */
3238 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3241 /* Image deletions cause full rebuild by default. */
3242 if (wim->image_deletion_occurred &&
3243 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3246 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3247 * turned into a pipable WIM in-place. */
3248 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3251 /* The default compression type and compression chunk size selected for
3252 * the output WIM must be the same as those currently used for the WIM.
3254 if (wim->compression_type != wim->out_compression_type)
3256 if (wim->chunk_size != wim->out_chunk_size)
3262 /* API function documented in wimlib.h */
3264 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3269 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3270 return WIMLIB_ERR_INVALID_PARAM;
3273 return WIMLIB_ERR_NO_FILENAME;
3275 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)) {
3277 * In UNSAFE_COMPACT mode:
3278 * - RECOMPRESS is forbidden
3279 * - REBUILD is ignored
3280 * - SOFT_DELETE and NO_SOLID_SORT are implied
3282 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
3283 return WIMLIB_ERR_COMPACTION_NOT_POSSIBLE;
3284 write_flags &= ~WIMLIB_WRITE_FLAG_REBUILD;
3285 write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
3286 write_flags |= WIMLIB_WRITE_FLAG_NO_SOLID_SORT;
3289 orig_hdr_flags = wim->hdr.flags;
3290 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3291 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3292 ret = can_modify_wim(wim);
3293 wim->hdr.flags = orig_hdr_flags;
3297 if (can_overwrite_wim_inplace(wim, write_flags)) {
3298 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3299 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3301 WARNING("Falling back to re-building entire WIM");
3303 if (write_flags & WIMLIB_WRITE_FLAG_UNSAFE_COMPACT)
3304 return WIMLIB_ERR_COMPACTION_NOT_POSSIBLE;
3305 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);