4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
11 * This file is free software; you can redistribute it and/or modify it under
12 * the terms of the GNU Lesser General Public License as published by the Free
13 * Software Foundation; either version 3 of the License, or (at your option) any
16 * This file is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this file; if not, see http://www.gnu.org/licenses/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
31 * overwrite the LIST_HEAD macro. */
32 # include <sys/file.h>
40 #include "wimlib/alloca.h"
41 #include "wimlib/assert.h"
42 #include "wimlib/blob_table.h"
43 #include "wimlib/chunk_compressor.h"
44 #include "wimlib/endianness.h"
45 #include "wimlib/error.h"
46 #include "wimlib/file_io.h"
47 #include "wimlib/header.h"
48 #include "wimlib/inode.h"
49 #include "wimlib/integrity.h"
50 #include "wimlib/metadata.h"
51 #include "wimlib/paths.h"
52 #include "wimlib/progress.h"
53 #include "wimlib/resource.h"
54 #include "wimlib/solid.h"
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_OVERWRITE &&
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)
146 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
150 may_hard_filter_blobs(const struct filter_context *ctx)
154 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
158 may_filter_blobs(const struct filter_context *ctx)
160 return (may_soft_filter_blobs(ctx) || may_hard_filter_blobs(ctx));
163 /* Return true if the specified resource is compressed and the compressed data
164 * can be reused with the specified output parameters. */
166 can_raw_copy(const struct blob_descriptor *blob,
167 int write_resource_flags, int out_ctype, u32 out_chunk_size)
169 const struct wim_resource_descriptor *rdesc;
171 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
174 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
177 if (blob->blob_location != BLOB_IN_WIM)
182 if (rdesc->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
185 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
186 /* Normal compressed resource: Must use same compression type
188 return (rdesc->compression_type == out_ctype &&
189 rdesc->chunk_size == out_chunk_size);
192 if ((rdesc->flags & WIM_RESHDR_FLAG_SOLID) &&
193 (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
195 /* Solid resource: Such resources may contain multiple blobs,
196 * and in general only a subset of them need to be written. As
197 * a heuristic, re-use the raw data if more than two-thirds the
198 * uncompressed size is being written. */
200 /* Note: solid resources contain a header that specifies the
201 * compression type and chunk size; therefore we don't need to
202 * check if they are compatible with @out_ctype and
203 * @out_chunk_size. */
205 struct blob_descriptor *res_blob;
208 list_for_each_entry(res_blob, &rdesc->blob_list, rdesc_node)
209 if (res_blob->will_be_in_output_wim)
210 write_size += res_blob->size;
212 return (write_size > rdesc->uncompressed_size * 2 / 3);
219 reshdr_flags_for_blob(const struct blob_descriptor *blob)
221 u32 reshdr_flags = 0;
222 if (blob->is_metadata)
223 reshdr_flags |= WIM_RESHDR_FLAG_METADATA;
228 blob_set_out_reshdr_for_reuse(struct blob_descriptor *blob)
230 const struct wim_resource_descriptor *rdesc;
232 wimlib_assert(blob->blob_location == BLOB_IN_WIM);
235 if (rdesc->flags & WIM_RESHDR_FLAG_SOLID) {
236 blob->out_reshdr.offset_in_wim = blob->offset_in_res;
237 blob->out_reshdr.uncompressed_size = 0;
238 blob->out_reshdr.size_in_wim = blob->size;
240 blob->out_res_offset_in_wim = rdesc->offset_in_wim;
241 blob->out_res_size_in_wim = rdesc->size_in_wim;
242 blob->out_res_uncompressed_size = rdesc->uncompressed_size;
244 blob->out_reshdr.offset_in_wim = rdesc->offset_in_wim;
245 blob->out_reshdr.uncompressed_size = rdesc->uncompressed_size;
246 blob->out_reshdr.size_in_wim = rdesc->size_in_wim;
248 blob->out_reshdr.flags = rdesc->flags;
252 /* Write the header for a blob in a pipable WIM. */
254 write_pwm_blob_header(const struct blob_descriptor *blob,
255 struct filedes *out_fd, bool compressed)
257 struct pwm_blob_hdr blob_hdr;
261 wimlib_assert(!blob->unhashed);
263 blob_hdr.magic = cpu_to_le64(PWM_BLOB_MAGIC);
264 blob_hdr.uncompressed_size = cpu_to_le64(blob->size);
265 copy_hash(blob_hdr.hash, blob->hash);
266 reshdr_flags = reshdr_flags_for_blob(blob);
268 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
269 blob_hdr.flags = cpu_to_le32(reshdr_flags);
270 ret = full_write(out_fd, &blob_hdr, sizeof(blob_hdr));
272 ERROR_WITH_ERRNO("Write error");
276 struct write_blobs_progress_data {
277 wimlib_progress_func_t progfunc;
279 union wimlib_progress_info progress;
284 do_write_blobs_progress(struct write_blobs_progress_data *progress_data,
285 u64 complete_size, u32 complete_count, bool discarded)
287 union wimlib_progress_info *progress = &progress_data->progress;
291 progress->write_streams.total_bytes -= complete_size;
292 progress->write_streams.total_streams -= complete_count;
293 if (progress_data->next_progress != ~(u64)0 &&
294 progress_data->next_progress > progress->write_streams.total_bytes)
296 progress_data->next_progress = progress->write_streams.total_bytes;
299 progress->write_streams.completed_bytes += complete_size;
300 progress->write_streams.completed_streams += complete_count;
303 if (progress->write_streams.completed_bytes >= progress_data->next_progress) {
305 ret = call_progress(progress_data->progfunc,
306 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
308 progress_data->progctx);
312 set_next_progress(progress->write_streams.completed_bytes,
313 progress->write_streams.total_bytes,
314 &progress_data->next_progress);
319 struct write_blobs_ctx {
320 /* File descriptor to which the blobs are being written. */
321 struct filedes *out_fd;
323 /* Blob table for the WIMStruct on whose behalf the blobs are being
325 struct blob_table *blob_table;
327 /* Compression format to use. */
330 /* Maximum uncompressed chunk size in compressed resources to use. */
333 /* Flags that affect how the blobs will be written. */
334 int write_resource_flags;
336 /* Data used for issuing WRITE_STREAMS progress. */
337 struct write_blobs_progress_data progress_data;
339 struct filter_context *filter_ctx;
341 /* Upper bound on the total number of bytes that need to be compressed.
343 u64 num_bytes_to_compress;
345 /* Pointer to the chunk_compressor implementation being used for
346 * compressing chunks of data, or NULL if chunks are being written
348 struct chunk_compressor *compressor;
350 /* A buffer of size @out_chunk_size that has been loaned out from the
351 * chunk compressor and is currently being filled with the uncompressed
352 * data of the next chunk. */
355 /* Number of bytes in @cur_chunk_buf that are currently filled. */
356 size_t cur_chunk_buf_filled;
358 /* List of blobs that currently have chunks being compressed. */
359 struct list_head blobs_being_compressed;
361 /* List of blobs in the solid resource. Blobs are moved here after
362 * @blobs_being_compressed only when writing a solid resource. */
363 struct list_head blobs_in_solid_resource;
365 /* Current uncompressed offset in the blob being read. */
366 u64 cur_read_blob_offset;
368 /* Uncompressed size of the blob currently being read. */
369 u64 cur_read_blob_size;
371 /* Current uncompressed offset in the blob being written. */
372 u64 cur_write_blob_offset;
374 /* Uncompressed size of resource currently being written. */
375 u64 cur_write_res_size;
377 /* Array that is filled in with compressed chunk sizes as a resource is
381 /* Index of next entry in @chunk_csizes to fill in. */
384 /* Number of entries in @chunk_csizes currently allocated. */
385 size_t num_alloc_chunks;
387 /* Offset in the output file of the start of the chunks of the resource
388 * currently being written. */
389 u64 chunks_start_offset;
392 /* Reserve space for the chunk table and prepare to accumulate the chunk table
395 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
397 u64 expected_num_chunks;
398 u64 expected_num_chunk_entries;
402 /* Calculate the number of chunks and chunk entries that should be
403 * needed for the resource. These normally will be the final values,
404 * but in SOLID mode some of the blobs we're planning to write into the
405 * resource may be duplicates, and therefore discarded, potentially
406 * decreasing the number of chunk entries needed. */
407 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
408 expected_num_chunk_entries = expected_num_chunks;
409 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
410 expected_num_chunk_entries--;
412 /* Make sure the chunk_csizes array is long enough to store the
413 * compressed size of each chunk. */
414 if (expected_num_chunks > ctx->num_alloc_chunks) {
415 u64 new_length = expected_num_chunks + 50;
417 if ((size_t)new_length != new_length) {
418 ERROR("Resource size too large (%"PRIu64" bytes!",
420 return WIMLIB_ERR_NOMEM;
423 FREE(ctx->chunk_csizes);
424 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
425 if (ctx->chunk_csizes == NULL) {
426 ctx->num_alloc_chunks = 0;
427 return WIMLIB_ERR_NOMEM;
429 ctx->num_alloc_chunks = new_length;
432 ctx->chunk_index = 0;
434 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
435 /* Reserve space for the chunk table in the output file. In the
436 * case of solid resources this reserves the upper bound for the
437 * needed space, not necessarily the exact space which will
438 * prove to be needed. At this point, we just use @chunk_csizes
439 * for a buffer of 0's because the actual compressed chunk sizes
441 reserve_size = expected_num_chunk_entries *
442 get_chunk_entry_size(res_expected_size,
443 0 != (ctx->write_resource_flags &
444 WRITE_RESOURCE_FLAG_SOLID));
445 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
446 reserve_size += sizeof(struct alt_chunk_table_header_disk);
447 memset(ctx->chunk_csizes, 0, reserve_size);
448 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
456 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
460 wimlib_assert(res_expected_size != 0);
462 if (ctx->compressor != NULL) {
463 ret = begin_chunk_table(ctx, res_expected_size);
468 /* Output file descriptor is now positioned at the offset at which to
469 * write the first chunk of the resource. */
470 ctx->chunks_start_offset = ctx->out_fd->offset;
471 ctx->cur_write_blob_offset = 0;
472 ctx->cur_write_res_size = res_expected_size;
477 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
478 u64 *res_start_offset_ret, u64 *res_store_size_ret)
480 size_t actual_num_chunks;
481 size_t actual_num_chunk_entries;
482 size_t chunk_entry_size;
485 actual_num_chunks = ctx->chunk_index;
486 actual_num_chunk_entries = actual_num_chunks;
487 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
488 actual_num_chunk_entries--;
490 chunk_entry_size = get_chunk_entry_size(res_actual_size,
491 0 != (ctx->write_resource_flags &
492 WRITE_RESOURCE_FLAG_SOLID));
494 typedef le64 _may_alias_attribute aliased_le64_t;
495 typedef le32 _may_alias_attribute aliased_le32_t;
497 if (chunk_entry_size == 4) {
498 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
500 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
501 for (size_t i = 0; i < actual_num_chunk_entries; i++)
502 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
504 u32 offset = ctx->chunk_csizes[0];
505 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
506 u32 next_size = ctx->chunk_csizes[i + 1];
507 entries[i] = cpu_to_le32(offset);
512 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
514 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
515 for (size_t i = 0; i < actual_num_chunk_entries; i++)
516 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
518 u64 offset = ctx->chunk_csizes[0];
519 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
520 u64 next_size = ctx->chunk_csizes[i + 1];
521 entries[i] = cpu_to_le64(offset);
527 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
528 u64 res_start_offset;
531 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
532 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
535 res_end_offset = ctx->out_fd->offset;
536 res_start_offset = ctx->chunks_start_offset;
538 res_end_offset = ctx->out_fd->offset;
540 u64 chunk_table_offset;
542 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
544 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
545 struct alt_chunk_table_header_disk hdr;
547 hdr.res_usize = cpu_to_le64(res_actual_size);
548 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
549 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
551 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
552 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
553 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
555 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
556 chunk_table_offset - sizeof(hdr));
559 res_start_offset = chunk_table_offset - sizeof(hdr);
561 res_start_offset = chunk_table_offset;
564 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
565 chunk_table_size, chunk_table_offset);
570 *res_start_offset_ret = res_start_offset;
571 *res_store_size_ret = res_end_offset - res_start_offset;
576 ERROR_WITH_ERRNO("Write error");
580 /* Finish writing a WIM resource by writing or updating the chunk table (if not
581 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
583 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
587 u64 res_uncompressed_size;
588 u64 res_offset_in_wim;
590 wimlib_assert(ctx->cur_write_blob_offset == ctx->cur_write_res_size ||
591 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
592 res_uncompressed_size = ctx->cur_write_res_size;
594 if (ctx->compressor) {
595 ret = end_chunk_table(ctx, res_uncompressed_size,
596 &res_offset_in_wim, &res_size_in_wim);
600 res_offset_in_wim = ctx->chunks_start_offset;
601 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
603 out_reshdr->uncompressed_size = res_uncompressed_size;
604 out_reshdr->size_in_wim = res_size_in_wim;
605 out_reshdr->offset_in_wim = res_offset_in_wim;
609 /* Call when no more data from the file at @path is needed. */
611 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
613 union wimlib_progress_info info;
615 info.done_with_file.path_to_file = path;
617 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
622 do_done_with_blob(struct blob_descriptor *blob,
623 wimlib_progress_func_t progfunc, void *progctx)
626 struct wim_inode *inode;
630 if (!blob->may_send_done_with_file)
633 inode = blob->file_inode;
635 wimlib_assert(inode != NULL);
636 wimlib_assert(inode->i_num_remaining_streams > 0);
637 if (--inode->i_num_remaining_streams > 0)
640 cookie1 = progress_get_streamless_path(blob->file_on_disk);
641 cookie2 = progress_get_win32_path(blob->file_on_disk);
643 ret = done_with_file(blob->file_on_disk, progfunc, progctx);
645 progress_put_win32_path(cookie2);
646 progress_put_streamless_path(cookie1);
651 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
653 done_with_blob(struct blob_descriptor *blob, struct write_blobs_ctx *ctx)
655 if (likely(!(ctx->write_resource_flags &
656 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
658 return do_done_with_blob(blob, ctx->progress_data.progfunc,
659 ctx->progress_data.progctx);
662 /* Begin processing a blob for writing. */
664 write_blob_begin_read(struct blob_descriptor *blob, void *_ctx)
666 struct write_blobs_ctx *ctx = _ctx;
669 wimlib_assert(blob->size > 0);
671 ctx->cur_read_blob_offset = 0;
672 ctx->cur_read_blob_size = blob->size;
674 /* As an optimization, we allow some blobs to be "unhashed", meaning
675 * their SHA-1 message digests are unknown. This is the case with blobs
676 * that are added by scanning a directory tree with wimlib_add_image(),
677 * for example. Since WIM uses single-instance blobs, we don't know
678 * whether such each such blob really need to written until it is
679 * actually checksummed, unless it has a unique size. In such cases we
680 * read and checksum the blob in this function, thereby advancing ahead
681 * of read_blob_list(), which will still provide the data again to
682 * write_blob_process_chunk(). This is okay because an unhashed blob
683 * cannot be in a WIM resource, which might be costly to decompress. */
684 if (ctx->blob_table != NULL && blob->unhashed && !blob->unique_size) {
686 struct blob_descriptor *new_blob;
688 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
691 if (new_blob != blob) {
692 /* Duplicate blob detected. */
694 if (new_blob->will_be_in_output_wim ||
695 blob_filtered(new_blob, ctx->filter_ctx))
697 /* The duplicate blob is already being included
698 * in the output WIM, or it would be filtered
699 * out if it had been. Skip writing this blob
700 * (and reading it again) entirely, passing its
701 * output reference count to the duplicate blob
702 * in the former case. */
703 ret = do_write_blobs_progress(&ctx->progress_data,
704 blob->size, 1, true);
705 list_del(&blob->write_blobs_list);
706 list_del(&blob->blob_table_list);
707 if (new_blob->will_be_in_output_wim)
708 new_blob->out_refcnt += blob->out_refcnt;
709 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
710 ctx->cur_write_res_size -= blob->size;
712 ret = done_with_blob(blob, ctx);
713 free_blob_descriptor(blob);
716 return BEGIN_BLOB_STATUS_SKIP_BLOB;
718 /* The duplicate blob can validly be written,
719 * but was not marked as such. Discard the
720 * current blob descriptor and use the
721 * duplicate, but actually freeing the current
722 * blob descriptor must wait until
723 * read_blob_list() has finished reading its
725 list_replace(&blob->write_blobs_list,
726 &new_blob->write_blobs_list);
727 list_replace(&blob->blob_table_list,
728 &new_blob->blob_table_list);
729 blob->will_be_in_output_wim = 0;
730 new_blob->out_refcnt = blob->out_refcnt;
731 new_blob->will_be_in_output_wim = 1;
732 new_blob->may_send_done_with_file = 0;
737 list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
741 /* Rewrite a blob that was just written compressed (as a non-solid WIM resource)
742 * as uncompressed instead. */
744 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
747 u64 begin_offset = blob->out_reshdr.offset_in_wim;
748 u64 end_offset = out_fd->offset;
750 if (filedes_seek(out_fd, begin_offset) == -1)
753 ret = extract_blob_to_fd(blob, out_fd);
755 /* Error reading the uncompressed data. */
756 if (out_fd->offset == begin_offset &&
757 filedes_seek(out_fd, end_offset) != -1)
759 /* Nothing was actually written yet, and we successfully
760 * seeked to the end of the compressed resource, so
761 * don't issue a hard error; just keep the compressed
762 * resource instead. */
763 WARNING("Recovered compressed resource of "
764 "size %"PRIu64", continuing on.", blob->size);
770 wimlib_assert(out_fd->offset - begin_offset == blob->size);
772 if (out_fd->offset < end_offset &&
773 0 != ftruncate(out_fd->fd, out_fd->offset))
775 ERROR_WITH_ERRNO("Can't truncate output file to "
776 "offset %"PRIu64, out_fd->offset);
777 return WIMLIB_ERR_WRITE;
780 blob->out_reshdr.size_in_wim = blob->size;
781 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
782 WIM_RESHDR_FLAG_SOLID);
786 /* Returns true if the specified blob, which was written as a non-solid
787 * resource, should be truncated from the WIM file and re-written uncompressed.
788 * blob->out_reshdr must be filled in from the initial write of the blob. */
790 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
791 const struct blob_descriptor *blob)
793 /* If the compressed data is smaller than the uncompressed data, prefer
794 * the compressed data. */
795 if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
798 /* If we're not actually writing compressed data, then there's no need
800 if (!ctx->compressor)
803 /* If writing a pipable WIM, everything we write to the output is final
804 * (it might actually be a pipe!). */
805 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
808 /* If the blob that would need to be re-read is located in a solid
809 * resource in another WIM file, then re-reading it would be costly. So
812 * Exception: if the compressed size happens to be *exactly* the same as
813 * the uncompressed size, then the blob *must* be written uncompressed
814 * in order to remain compatible with the Windows Overlay Filesystem
815 * Filter Driver (WOF).
817 * TODO: we are currently assuming that the optimization for
818 * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
819 * this case from being triggered too often. To fully prevent excessive
820 * decompressions in degenerate cases, we really should obtain the
821 * uncompressed data by decompressing the compressed data we wrote to
824 if (blob->blob_location == BLOB_IN_WIM &&
825 blob->size != blob->rdesc->uncompressed_size &&
826 blob->size != blob->out_reshdr.size_in_wim)
833 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
834 struct blob_descriptor *blob)
836 if (!should_rewrite_blob_uncompressed(ctx, blob))
839 /* Regular (non-solid) WIM resources with exactly one chunk and
840 * compressed size equal to uncompressed size are exactly the same as
841 * the corresponding compressed data --- since there must be 0 entries
842 * in the chunk table and the only chunk must be stored uncompressed.
843 * In this case, there's no need to rewrite anything. */
844 if (ctx->chunk_index == 1 &&
845 blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
847 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
851 return write_blob_uncompressed(blob, ctx->out_fd);
854 /* Write the next chunk of (typically compressed) data to the output WIM,
855 * handling the writing of the chunk table. */
857 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
858 size_t csize, size_t usize)
861 struct blob_descriptor *blob;
862 u32 completed_blob_count;
865 blob = list_entry(ctx->blobs_being_compressed.next,
866 struct blob_descriptor, write_blobs_list);
868 if (ctx->cur_write_blob_offset == 0 &&
869 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
871 /* Starting to write a new blob in non-solid mode. */
873 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
874 ret = write_pwm_blob_header(blob, ctx->out_fd,
875 ctx->compressor != NULL);
880 ret = begin_write_resource(ctx, blob->size);
885 if (ctx->compressor != NULL) {
886 /* Record the compresed chunk size. */
887 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
888 ctx->chunk_csizes[ctx->chunk_index++] = csize;
890 /* If writing a pipable WIM, before the chunk data write a chunk
891 * header that provides the compressed chunk size. */
892 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
893 struct pwm_chunk_hdr chunk_hdr = {
894 .compressed_size = cpu_to_le32(csize),
896 ret = full_write(ctx->out_fd, &chunk_hdr,
903 /* Write the chunk data. */
904 ret = full_write(ctx->out_fd, cchunk, csize);
908 ctx->cur_write_blob_offset += usize;
910 completed_size = usize;
911 completed_blob_count = 0;
912 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
913 /* Wrote chunk in solid mode. It may have finished multiple
915 struct blob_descriptor *next_blob;
917 while (blob && ctx->cur_write_blob_offset >= blob->size) {
919 ctx->cur_write_blob_offset -= blob->size;
921 if (ctx->cur_write_blob_offset)
922 next_blob = list_entry(blob->write_blobs_list.next,
923 struct blob_descriptor,
928 ret = done_with_blob(blob, ctx);
931 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
932 completed_blob_count++;
937 /* Wrote chunk in non-solid mode. It may have finished a
939 if (ctx->cur_write_blob_offset == blob->size) {
941 wimlib_assert(ctx->cur_write_blob_offset ==
942 ctx->cur_write_res_size);
944 ret = end_write_resource(ctx, &blob->out_reshdr);
948 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
949 if (ctx->compressor != NULL)
950 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
952 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
956 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
958 ctx->cur_write_blob_offset = 0;
960 ret = done_with_blob(blob, ctx);
963 list_del(&blob->write_blobs_list);
964 completed_blob_count++;
968 return do_write_blobs_progress(&ctx->progress_data, completed_size,
969 completed_blob_count, false);
972 ERROR_WITH_ERRNO("Write error");
977 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
979 /* While we are unable to get a new chunk buffer due to too many chunks
980 * already outstanding, retrieve and write the next compressed chunk. */
981 while (!(ctx->cur_chunk_buf =
982 ctx->compressor->get_chunk_buffer(ctx->compressor)))
990 bret = ctx->compressor->get_compression_result(ctx->compressor,
996 ret = write_chunk(ctx, cchunk, csize, usize);
1003 /* Process the next chunk of data to be written to a WIM resource. */
1005 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1007 struct write_blobs_ctx *ctx = _ctx;
1009 const u8 *chunkptr, *chunkend;
1011 wimlib_assert(size != 0);
1013 if (ctx->compressor == NULL) {
1014 /* Write chunk uncompressed. */
1015 ret = write_chunk(ctx, chunk, size, size);
1018 ctx->cur_read_blob_offset += size;
1022 /* Submit the chunk for compression, but take into account that the
1023 * @size the chunk was provided in may not correspond to the
1024 * @out_chunk_size being used for compression. */
1026 chunkend = chunkptr + size;
1028 size_t needed_chunk_size;
1029 size_t bytes_consumed;
1031 if (!ctx->cur_chunk_buf) {
1032 ret = prepare_chunk_buffer(ctx);
1037 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1038 needed_chunk_size = ctx->out_chunk_size;
1040 needed_chunk_size = min(ctx->out_chunk_size,
1041 ctx->cur_chunk_buf_filled +
1042 (ctx->cur_read_blob_size -
1043 ctx->cur_read_blob_offset));
1046 bytes_consumed = min(chunkend - chunkptr,
1047 needed_chunk_size - ctx->cur_chunk_buf_filled);
1049 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1050 chunkptr, bytes_consumed);
1052 chunkptr += bytes_consumed;
1053 ctx->cur_read_blob_offset += bytes_consumed;
1054 ctx->cur_chunk_buf_filled += bytes_consumed;
1056 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1057 ctx->compressor->signal_chunk_filled(ctx->compressor,
1058 ctx->cur_chunk_buf_filled);
1059 ctx->cur_chunk_buf = NULL;
1060 ctx->cur_chunk_buf_filled = 0;
1062 } while (chunkptr != chunkend);
1066 /* Finish processing a blob for writing. It may not have been completely
1067 * written yet, as the chunk_compressor implementation may still have chunks
1068 * buffered or being compressed. */
1070 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1072 struct write_blobs_ctx *ctx = _ctx;
1074 wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
1076 if (!blob->will_be_in_output_wim) {
1077 /* The blob was a duplicate. Now that its data has finished
1078 * being read, it is being discarded in favor of the duplicate
1079 * entry. It therefore is no longer needed, and we can fire the
1080 * DONE_WITH_FILE callback because the file will not be read
1083 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1084 * blobs, since it needs to be possible to re-read the file if
1085 * it does not compress to less than its original size. */
1087 status = done_with_blob(blob, ctx);
1088 free_blob_descriptor(blob);
1089 } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1090 /* The blob was not a duplicate and was previously unhashed.
1091 * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1092 * read_blob_list(), blob->hash is now computed and valid. So
1093 * turn this blob into a "hashed" blob. */
1094 list_del(&blob->unhashed_list);
1095 blob_table_insert(ctx->blob_table, blob);
1101 /* Compute statistics about a list of blobs that will be written.
1103 * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1104 * (specified by WIMStruct) are together. */
1106 compute_blob_list_stats(struct list_head *blob_list,
1107 struct write_blobs_ctx *ctx)
1109 struct blob_descriptor *blob;
1110 u64 total_bytes = 0;
1112 u64 total_parts = 0;
1113 WIMStruct *prev_wim_part = NULL;
1115 list_for_each_entry(blob, blob_list, write_blobs_list) {
1117 total_bytes += blob->size;
1118 if (blob->blob_location == BLOB_IN_WIM) {
1119 if (prev_wim_part != blob->rdesc->wim) {
1120 prev_wim_part = blob->rdesc->wim;
1125 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1126 ctx->progress_data.progress.write_streams.total_streams = num_blobs;
1127 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1128 ctx->progress_data.progress.write_streams.completed_streams = 0;
1129 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1130 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1131 ctx->progress_data.progress.write_streams.completed_parts = 0;
1132 ctx->progress_data.next_progress = 0;
1135 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1136 * rather than compressed. Delete these blobs from @blob_list and move them to
1137 * @raw_copy_blobs. Return the total uncompressed size of the blobs that need
1138 * to be compressed. */
1140 find_raw_copy_blobs(struct list_head *blob_list,
1141 int write_resource_flags,
1144 struct list_head *raw_copy_blobs)
1146 struct blob_descriptor *blob, *tmp;
1147 u64 num_bytes_to_compress = 0;
1149 INIT_LIST_HEAD(raw_copy_blobs);
1151 /* Initialize temporary raw_copy_ok flag. */
1152 list_for_each_entry(blob, blob_list, write_blobs_list)
1153 if (blob->blob_location == BLOB_IN_WIM)
1154 blob->rdesc->raw_copy_ok = 0;
1156 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1157 if (blob->blob_location == BLOB_IN_WIM &&
1158 blob->rdesc->raw_copy_ok)
1160 list_move_tail(&blob->write_blobs_list,
1162 } else if (can_raw_copy(blob, write_resource_flags,
1163 out_ctype, out_chunk_size))
1165 blob->rdesc->raw_copy_ok = 1;
1166 list_move_tail(&blob->write_blobs_list,
1169 num_bytes_to_compress += blob->size;
1173 return num_bytes_to_compress;
1176 /* Copy a raw compressed resource located in another WIM file to the WIM file
1179 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1180 struct filedes *out_fd)
1182 u64 cur_read_offset;
1183 u64 end_read_offset;
1184 u8 buf[BUFFER_SIZE];
1185 size_t bytes_to_read;
1187 struct filedes *in_fd;
1188 struct blob_descriptor *blob;
1189 u64 out_offset_in_wim;
1191 /* Copy the raw data. */
1192 cur_read_offset = in_rdesc->offset_in_wim;
1193 end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1195 out_offset_in_wim = out_fd->offset;
1197 if (in_rdesc->is_pipable) {
1198 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1199 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1200 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1201 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1203 in_fd = &in_rdesc->wim->in_fd;
1204 wimlib_assert(cur_read_offset != end_read_offset);
1207 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1209 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1213 ret = full_write(out_fd, buf, bytes_to_read);
1217 cur_read_offset += bytes_to_read;
1219 } while (cur_read_offset != end_read_offset);
1221 list_for_each_entry(blob, &in_rdesc->blob_list, rdesc_node) {
1222 if (blob->will_be_in_output_wim) {
1223 blob_set_out_reshdr_for_reuse(blob);
1224 if (in_rdesc->flags & WIM_RESHDR_FLAG_SOLID)
1225 blob->out_res_offset_in_wim = out_offset_in_wim;
1227 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1234 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1235 * WIM file being written. */
1237 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1238 struct filedes *out_fd,
1239 struct write_blobs_progress_data *progress_data)
1241 struct blob_descriptor *blob;
1244 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1245 blob->rdesc->raw_copy_ok = 1;
1247 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list) {
1248 if (blob->rdesc->raw_copy_ok) {
1249 /* Write each solid resource only one time. */
1250 ret = write_raw_copy_resource(blob->rdesc, out_fd);
1253 blob->rdesc->raw_copy_ok = 0;
1255 ret = do_write_blobs_progress(progress_data, blob->size,
1263 /* Wait for and write all chunks pending in the compressor. */
1265 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1272 if (ctx->compressor == NULL)
1275 if (ctx->cur_chunk_buf_filled != 0) {
1276 ctx->compressor->signal_chunk_filled(ctx->compressor,
1277 ctx->cur_chunk_buf_filled);
1280 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1283 ret = write_chunk(ctx, cdata, csize, usize);
1291 validate_blob_list(struct list_head *blob_list)
1293 struct blob_descriptor *blob;
1295 list_for_each_entry(blob, blob_list, write_blobs_list) {
1296 wimlib_assert(blob->will_be_in_output_wim);
1297 wimlib_assert(blob->size != 0);
1302 blob_is_in_file(const struct blob_descriptor *blob)
1304 return blob->blob_location == BLOB_IN_FILE_ON_DISK
1306 || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1307 || blob->blob_location == BLOB_WIN32_ENCRYPTED
1313 init_done_with_file_info(struct list_head *blob_list)
1315 struct blob_descriptor *blob;
1317 list_for_each_entry(blob, blob_list, write_blobs_list) {
1318 if (blob_is_in_file(blob)) {
1319 blob->file_inode->i_num_remaining_streams = 0;
1320 blob->may_send_done_with_file = 1;
1322 blob->may_send_done_with_file = 0;
1326 list_for_each_entry(blob, blob_list, write_blobs_list)
1327 if (blob->may_send_done_with_file)
1328 blob->file_inode->i_num_remaining_streams++;
1332 * Write a list of blobs to the output WIM file.
1335 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1336 * by the 'write_blobs_list' member.
1339 * The file descriptor, opened for writing, to which to write the blobs.
1341 * @write_resource_flags
1342 * Flags to modify how the blobs are written:
1344 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1345 * Force compression of all resources, even if they could otherwise
1346 * be re-used by copying the raw data, due to being located in a WIM
1347 * file with compatible compression parameters.
1349 * WRITE_RESOURCE_FLAG_PIPABLE:
1350 * Write the resources in the wimlib-specific pipable format, and
1351 * furthermore do so in such a way that no seeking backwards in
1352 * @out_fd will be performed (so it may be a pipe).
1354 * WRITE_RESOURCE_FLAG_SOLID:
1355 * Combine all the blobs into a single resource rather than writing
1356 * them in separate resources. This flag is only valid if the WIM
1357 * version number has been, or will be, set to WIM_VERSION_SOLID.
1358 * This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1361 * Compression format to use in the output resources, specified as one of
1362 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
1366 * Compression chunk size to use in the output resources. It must be a
1367 * valid chunk size for the specified compression format @out_ctype, unless
1368 * @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1372 * Number of threads to use to compress data. If 0, a default number of
1373 * threads will be chosen. The number of threads still may be decreased
1374 * from the specified value if insufficient memory is detected.
1377 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1378 * must be pointer to the blob table for the WIMStruct on whose behalf the
1379 * blobs are being written. Otherwise, this parameter can be NULL.
1382 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1383 * can be a pointer to a context for blob filtering used to detect whether
1384 * the duplicate blob has been hard-filtered or not. If no blobs are
1385 * hard-filtered or no blobs are unhashed, this parameter can be NULL.
1387 * This function will write the blobs in @blob_list to resources in
1388 * consecutive positions in the output WIM file, or to a single solid resource
1389 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1390 * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1391 * updated to specify its location, size, and flags in the output WIM. In the
1392 * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1393 * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1394 * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1395 * respectively, in the output WIM of the solid resource containing the
1396 * corresponding blob.
1398 * Each of the blobs to write may be in any location supported by the
1399 * resource-handling code (specifically, read_blob_list()), such as the contents
1400 * of external file that has been logically added to the output WIM, or a blob
1401 * in another WIM file that has been imported, or even a blob in the "same" WIM
1402 * file of which a modified copy is being written. In the case that a blob is
1403 * already in a WIM file and uses compatible compression parameters, by default
1404 * this function will re-use the raw data instead of decompressing it, then
1405 * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1406 * specified in @write_resource_flags, this is not done.
1408 * As a further requirement, this function requires that the
1409 * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1410 * as any other blobs not in @blob_list that will be in the output WIM file, but
1411 * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1412 * resource with a blob in @blob_list. Still furthermore, if on-the-fly
1413 * deduplication of blobs is possible, then all blobs in @blob_list must also be
1414 * linked by @blob_table_list along with any other blobs that have
1415 * @will_be_in_output_wim set.
1417 * This function handles on-the-fly deduplication of blobs for which SHA-1
1418 * message digests have not yet been calculated. Such blobs may or may not need
1419 * to be written. If @blob_table is non-NULL, then each blob in @blob_list that
1420 * has @unhashed set but not @unique_size set is checksummed immediately before
1421 * it would otherwise be read for writing in order to determine if it is
1422 * identical to another blob already being written or one that would be filtered
1423 * out of the output WIM using blob_filtered() with the context @filter_ctx.
1424 * Each such duplicate blob will be removed from @blob_list, its reference count
1425 * transfered to the pre-existing duplicate blob, its memory freed, and will not
1426 * be written. Alternatively, if a blob in @blob_list is a duplicate with any
1427 * blob in @blob_table that has not been marked for writing or would not be
1428 * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1429 * taking ownership of the reference count and slot in the @blob_table_list.
1431 * Returns 0 if every blob was either written successfully or did not need to be
1432 * written; otherwise returns a non-zero error code.
1435 write_blob_list(struct list_head *blob_list,
1436 struct filedes *out_fd,
1437 int write_resource_flags,
1440 unsigned num_threads,
1441 struct blob_table *blob_table,
1442 struct filter_context *filter_ctx,
1443 wimlib_progress_func_t progfunc,
1447 struct write_blobs_ctx ctx;
1448 struct list_head raw_copy_blobs;
1450 wimlib_assert((write_resource_flags &
1451 (WRITE_RESOURCE_FLAG_SOLID |
1452 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1453 (WRITE_RESOURCE_FLAG_SOLID |
1454 WRITE_RESOURCE_FLAG_PIPABLE));
1456 validate_blob_list(blob_list);
1458 if (list_empty(blob_list))
1461 /* If needed, set auxiliary information so that we can detect when the
1462 * library has finished using each external file. */
1463 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1464 init_done_with_file_info(blob_list);
1466 memset(&ctx, 0, sizeof(ctx));
1468 ctx.out_fd = out_fd;
1469 ctx.blob_table = blob_table;
1470 ctx.out_ctype = out_ctype;
1471 ctx.out_chunk_size = out_chunk_size;
1472 ctx.write_resource_flags = write_resource_flags;
1473 ctx.filter_ctx = filter_ctx;
1476 * We normally sort the blobs to write by a "sequential" order that is
1477 * optimized for reading. But when using solid compression, we instead
1478 * sort the blobs by file extension and file name (when applicable; and
1479 * we don't do this for blobs from solid resources) so that similar
1480 * files are grouped together, which improves the compression ratio.
1481 * This is somewhat of a hack since a blob does not necessarily
1482 * correspond one-to-one with a filename, nor is there any guarantee
1483 * that two files with similar names or extensions are actually similar
1484 * in content. A potential TODO is to sort the blobs based on some
1485 * measure of similarity of their actual contents.
1488 ret = sort_blob_list_by_sequential_order(blob_list,
1489 offsetof(struct blob_descriptor,
1494 compute_blob_list_stats(blob_list, &ctx);
1496 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1497 ret = sort_blob_list_for_solid_compression(blob_list);
1499 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1502 ctx.progress_data.progfunc = progfunc;
1503 ctx.progress_data.progctx = progctx;
1505 ctx.num_bytes_to_compress = find_raw_copy_blobs(blob_list,
1506 write_resource_flags,
1511 if (ctx.num_bytes_to_compress == 0)
1512 goto out_write_raw_copy_resources;
1514 /* Unless uncompressed output was required, allocate a chunk_compressor
1515 * to do compression. There are serial and parallel implementations of
1516 * the chunk_compressor interface. We default to parallel using the
1517 * specified number of threads, unless the upper bound on the number
1518 * bytes needing to be compressed is less than a heuristic value. */
1519 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1521 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1522 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1523 ret = new_parallel_chunk_compressor(out_ctype,
1528 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1529 " Falling back to single-threaded compression.",
1530 wimlib_get_error_string(ret));
1535 if (ctx.compressor == NULL) {
1536 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1539 goto out_destroy_context;
1544 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1546 ctx.progress_data.progress.write_streams.num_threads = 1;
1548 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1549 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1551 ret = call_progress(ctx.progress_data.progfunc,
1552 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1553 &ctx.progress_data.progress,
1554 ctx.progress_data.progctx);
1556 goto out_destroy_context;
1558 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1559 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1561 goto out_destroy_context;
1564 /* Read the list of blobs needing to be compressed, using the specified
1565 * callbacks to execute processing of the data. */
1567 struct read_blob_callbacks cbs = {
1568 .begin_blob = write_blob_begin_read,
1569 .consume_chunk = write_blob_process_chunk,
1570 .end_blob = write_blob_end_read,
1574 ret = read_blob_list(blob_list,
1575 offsetof(struct blob_descriptor, write_blobs_list),
1577 BLOB_LIST_ALREADY_SORTED |
1578 VERIFY_BLOB_HASHES |
1579 COMPUTE_MISSING_BLOB_HASHES);
1582 goto out_destroy_context;
1584 ret = finish_remaining_chunks(&ctx);
1586 goto out_destroy_context;
1588 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1589 struct wim_reshdr reshdr;
1590 struct blob_descriptor *blob;
1593 ret = end_write_resource(&ctx, &reshdr);
1595 goto out_destroy_context;
1598 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1599 blob->out_reshdr.size_in_wim = blob->size;
1600 blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1601 WIM_RESHDR_FLAG_SOLID;
1602 blob->out_reshdr.uncompressed_size = 0;
1603 blob->out_reshdr.offset_in_wim = offset_in_res;
1604 blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1605 blob->out_res_size_in_wim = reshdr.size_in_wim;
1606 blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1607 offset_in_res += blob->size;
1609 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1612 out_write_raw_copy_resources:
1613 /* Copy any compressed resources for which the raw data can be reused
1614 * without decompression. */
1615 ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1616 &ctx.progress_data);
1618 out_destroy_context:
1619 FREE(ctx.chunk_csizes);
1621 ctx.compressor->destroy(ctx.compressor);
1627 write_file_data_blobs(WIMStruct *wim,
1628 struct list_head *blob_list,
1630 unsigned num_threads,
1631 struct filter_context *filter_ctx)
1635 int write_resource_flags;
1637 write_resource_flags = write_flags_to_resource_flags(write_flags);
1639 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1640 out_chunk_size = wim->out_solid_chunk_size;
1641 out_ctype = wim->out_solid_compression_type;
1643 out_chunk_size = wim->out_chunk_size;
1644 out_ctype = wim->out_compression_type;
1647 return write_blob_list(blob_list,
1649 write_resource_flags,
1659 /* Write the contents of the specified blob as a WIM resource. */
1661 write_wim_resource(struct blob_descriptor *blob,
1662 struct filedes *out_fd,
1665 int write_resource_flags)
1667 LIST_HEAD(blob_list);
1668 list_add(&blob->write_blobs_list, &blob_list);
1669 blob->will_be_in_output_wim = 1;
1670 return write_blob_list(&blob_list,
1672 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1682 /* Write the contents of the specified buffer as a WIM resource. */
1684 write_wim_resource_from_buffer(const void *buf,
1687 struct filedes *out_fd,
1690 struct wim_reshdr *out_reshdr,
1692 int write_resource_flags)
1695 struct blob_descriptor blob;
1697 if (unlikely(buf_size == 0)) {
1698 zero_reshdr(out_reshdr);
1700 copy_hash(hash_ret, zero_hash);
1704 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1705 sha1_buffer(buf, buf_size, blob.hash);
1707 blob.is_metadata = is_metadata;
1709 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1710 write_resource_flags);
1714 copy_reshdr(out_reshdr, &blob.out_reshdr);
1717 copy_hash(hash_ret, blob.hash);
1721 struct blob_size_table {
1722 struct hlist_head *array;
1728 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1730 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1731 if (tab->array == NULL)
1732 return WIMLIB_ERR_NOMEM;
1733 tab->num_entries = 0;
1734 tab->capacity = capacity;
1739 destroy_blob_size_table(struct blob_size_table *tab)
1745 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1747 struct blob_size_table *tab = _tab;
1749 struct blob_descriptor *same_size_blob;
1751 pos = hash_u64(blob->size) % tab->capacity;
1752 blob->unique_size = 1;
1753 hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1754 if (same_size_blob->size == blob->size) {
1755 blob->unique_size = 0;
1756 same_size_blob->unique_size = 0;
1761 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1766 struct find_blobs_ctx {
1769 struct list_head blob_list;
1770 struct blob_size_table blob_size_tab;
1774 reference_blob_for_write(struct blob_descriptor *blob,
1775 struct list_head *blob_list, u32 nref)
1777 if (!blob->will_be_in_output_wim) {
1778 blob->out_refcnt = 0;
1779 list_add_tail(&blob->write_blobs_list, blob_list);
1780 blob->will_be_in_output_wim = 1;
1782 blob->out_refcnt += nref;
1786 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1788 struct list_head *blob_list = _blob_list;
1789 blob->will_be_in_output_wim = 0;
1790 reference_blob_for_write(blob, blob_list, blob->refcnt);
1795 inode_find_blobs_to_reference(const struct wim_inode *inode,
1796 const struct blob_table *table,
1797 struct list_head *blob_list)
1799 wimlib_assert(inode->i_nlink > 0);
1801 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1802 struct blob_descriptor *blob;
1805 blob = stream_blob(&inode->i_streams[i], table);
1807 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1809 hash = stream_hash(&inode->i_streams[i]);
1810 if (!is_zero_hash(hash))
1811 return blob_not_found_error(inode, hash);
1818 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1820 blob->will_be_in_output_wim = 0;
1825 image_find_blobs_to_reference(WIMStruct *wim)
1827 struct wim_image_metadata *imd;
1828 struct wim_inode *inode;
1829 struct blob_descriptor *blob;
1830 struct list_head *blob_list;
1833 imd = wim_get_current_image_metadata(wim);
1835 image_for_each_unhashed_blob(blob, imd)
1836 blob->will_be_in_output_wim = 0;
1838 blob_list = wim->private;
1839 image_for_each_inode(inode, imd) {
1840 ret = inode_find_blobs_to_reference(inode,
1850 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1853 struct list_head *blob_list_ret)
1857 INIT_LIST_HEAD(blob_list_ret);
1859 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1860 (image == 1 && wim->hdr.image_count == 1)))
1862 /* Fast case: Assume that all blobs are being written and that
1863 * the reference counts are correct. */
1864 struct blob_descriptor *blob;
1865 struct wim_image_metadata *imd;
1868 for_blob_in_table(wim->blob_table,
1869 fully_reference_blob_for_write,
1872 for (i = 0; i < wim->hdr.image_count; i++) {
1873 imd = wim->image_metadata[i];
1874 image_for_each_unhashed_blob(blob, imd)
1875 fully_reference_blob_for_write(blob, blob_list_ret);
1878 /* Slow case: Walk through the images being written and
1879 * determine the blobs referenced. */
1880 for_blob_in_table(wim->blob_table,
1881 do_blob_set_not_in_output_wim, NULL);
1882 wim->private = blob_list_ret;
1883 ret = for_image(wim, image, image_find_blobs_to_reference);
1891 struct insert_other_if_hard_filtered_ctx {
1892 struct blob_size_table *tab;
1893 struct filter_context *filter_ctx;
1897 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1899 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1901 if (!blob->will_be_in_output_wim &&
1902 blob_hard_filtered(blob, ctx->filter_ctx))
1903 blob_size_table_insert(blob, ctx->tab);
1908 determine_blob_size_uniquity(struct list_head *blob_list,
1909 struct blob_table *lt,
1910 struct filter_context *filter_ctx)
1913 struct blob_size_table tab;
1914 struct blob_descriptor *blob;
1916 ret = init_blob_size_table(&tab, 9001);
1920 if (may_hard_filter_blobs(filter_ctx)) {
1921 struct insert_other_if_hard_filtered_ctx ctx = {
1923 .filter_ctx = filter_ctx,
1925 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
1928 list_for_each_entry(blob, blob_list, write_blobs_list)
1929 blob_size_table_insert(blob, &tab);
1931 destroy_blob_size_table(&tab);
1936 filter_blob_list_for_write(struct list_head *blob_list,
1937 struct filter_context *filter_ctx)
1939 struct blob_descriptor *blob, *tmp;
1941 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1942 int status = blob_filtered(blob, filter_ctx);
1949 /* Soft filtered. */
1951 /* Hard filtered. */
1952 blob->will_be_in_output_wim = 0;
1953 list_del(&blob->blob_table_list);
1955 list_del(&blob->write_blobs_list);
1961 * prepare_blob_list_for_write() -
1963 * Prepare the list of blobs to write for writing a WIM containing the specified
1964 * image(s) with the specified write flags.
1967 * The WIMStruct on whose behalf the write is occurring.
1970 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1973 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1975 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
1976 * table of @wim and the per-image lists of unhashed blobs should be taken
1977 * as-is, and image metadata should not be searched for references. This
1978 * does not exclude filtering with OVERWRITE and SKIP_EXTERNAL_WIMS, below.
1980 * OVERWRITE: Blobs already present in @wim shall not be returned in
1983 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
1984 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
1987 * List of blobs, linked by write_blobs_list, that need to be written will
1990 * Note that this function assumes that unhashed blobs will be written; it
1991 * does not take into account that they may become duplicates when actually
1994 * @blob_table_list_ret
1995 * List of blobs, linked by blob_table_list, that need to be included in
1996 * the WIM's blob table will be returned here. This will be a superset of
1997 * the blobs in @blob_list_ret.
1999 * This list will be a proper superset of @blob_list_ret if and only if
2000 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2001 * the blobs that would otherwise need to be written were already located
2004 * All blobs in this list will have @out_refcnt set to the number of
2005 * references to the blob in the output WIM. If
2006 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2007 * may be as low as 0.
2010 * A context for queries of blob filter status with blob_filtered() is
2011 * returned in this location.
2013 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2014 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2015 * inserted into @blob_table_list_ret.
2017 * Still furthermore, @unique_size will be set to 1 on all blobs in
2018 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2019 * among all blobs in the blob table of @wim that are ineligible for being
2020 * written due to filtering.
2022 * Returns 0 on success; nonzero on read error, memory allocation error, or
2026 prepare_blob_list_for_write(WIMStruct *wim, int image,
2028 struct list_head *blob_list_ret,
2029 struct list_head *blob_table_list_ret,
2030 struct filter_context *filter_ctx_ret)
2033 struct blob_descriptor *blob;
2035 filter_ctx_ret->write_flags = write_flags;
2036 filter_ctx_ret->wim = wim;
2038 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2041 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2046 INIT_LIST_HEAD(blob_table_list_ret);
2047 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2048 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2050 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2055 if (may_filter_blobs(filter_ctx_ret))
2056 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2062 write_file_data(WIMStruct *wim, int image, int write_flags,
2063 unsigned num_threads,
2064 struct list_head *blob_list_override,
2065 struct list_head *blob_table_list_ret)
2068 struct list_head _blob_list;
2069 struct list_head *blob_list;
2070 struct blob_descriptor *blob;
2071 struct filter_context _filter_ctx;
2072 struct filter_context *filter_ctx;
2074 if (blob_list_override == NULL) {
2075 /* Normal case: prepare blob list from image(s) being written.
2077 blob_list = &_blob_list;
2078 filter_ctx = &_filter_ctx;
2079 ret = prepare_blob_list_for_write(wim, image, write_flags,
2081 blob_table_list_ret,
2086 /* Currently only as a result of wimlib_split() being called:
2087 * use blob list already explicitly provided. Use existing
2088 * reference counts. */
2089 blob_list = blob_list_override;
2091 INIT_LIST_HEAD(blob_table_list_ret);
2092 list_for_each_entry(blob, blob_list, write_blobs_list) {
2093 blob->out_refcnt = blob->refcnt;
2094 blob->will_be_in_output_wim = 1;
2095 blob->unique_size = 0;
2096 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2100 return write_file_data_blobs(wim,
2108 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2113 int write_resource_flags;
2115 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2118 write_resource_flags = write_flags_to_resource_flags(write_flags);
2120 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2122 ret = call_progress(wim->progfunc,
2123 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2124 NULL, wim->progctx);
2128 if (image == WIMLIB_ALL_IMAGES) {
2130 end_image = wim->hdr.image_count;
2132 start_image = image;
2136 for (int i = start_image; i <= end_image; i++) {
2137 struct wim_image_metadata *imd;
2139 imd = wim->image_metadata[i - 1];
2140 /* Build a new metadata resource only if image was modified from
2141 * the original (or was newly added). Otherwise just copy the
2143 if (imd->modified) {
2144 ret = write_metadata_resource(wim, i,
2145 write_resource_flags);
2146 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2147 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2150 ret = write_wim_resource(imd->metadata_blob,
2152 wim->out_compression_type,
2153 wim->out_chunk_size,
2154 write_resource_flags);
2160 return call_progress(wim->progfunc,
2161 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2162 NULL, wim->progctx);
2166 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2168 int raw_fd = topen(path, open_flags | O_BINARY, 0644);
2170 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2171 return WIMLIB_ERR_OPEN;
2173 filedes_init(&wim->out_fd, raw_fd);
2178 close_wim_writable(WIMStruct *wim, int write_flags)
2182 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2183 if (filedes_valid(&wim->out_fd))
2184 if (filedes_close(&wim->out_fd))
2185 ret = WIMLIB_ERR_WRITE;
2186 filedes_invalidate(&wim->out_fd);
2191 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2193 const struct blob_descriptor *blob1, *blob2;
2195 blob1 = *(const struct blob_descriptor**)p1;
2196 blob2 = *(const struct blob_descriptor**)p2;
2198 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2199 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2200 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2201 return cmp_u64(blob1->out_res_offset_in_wim,
2202 blob2->out_res_offset_in_wim);
2207 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2210 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2211 blob2->out_reshdr.offset_in_wim);
2215 write_blob_table(WIMStruct *wim, int image, int write_flags,
2216 struct list_head *blob_table_list)
2220 /* Set output resource metadata for blobs already present in WIM. */
2221 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2222 struct blob_descriptor *blob;
2223 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2224 if (blob->blob_location == BLOB_IN_WIM &&
2225 blob->rdesc->wim == wim)
2227 blob_set_out_reshdr_for_reuse(blob);
2232 ret = sort_blob_list(blob_table_list,
2233 offsetof(struct blob_descriptor, blob_table_list),
2234 cmp_blobs_by_out_rdesc);
2238 /* Add entries for metadata resources. */
2239 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2243 if (image == WIMLIB_ALL_IMAGES) {
2245 end_image = wim->hdr.image_count;
2247 start_image = image;
2251 /* Push metadata blob table entries onto the front of the list
2252 * in reverse order, so that they're written in order.
2254 for (int i = end_image; i >= start_image; i--) {
2255 struct blob_descriptor *metadata_blob;
2257 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2258 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2259 metadata_blob->out_refcnt = 1;
2260 list_add(&metadata_blob->blob_table_list, blob_table_list);
2264 return write_blob_table_from_blob_list(blob_table_list,
2266 wim->out_hdr.part_number,
2267 &wim->out_hdr.blob_table_reshdr,
2268 write_flags_to_resource_flags(write_flags));
2272 * Finish writing a WIM file: write the blob table, xml data, and integrity
2273 * table, then overwrite the WIM header.
2275 * The output file descriptor is closed on success, except when writing to a
2276 * user-specified file descriptor (WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR set).
2279 finish_write(WIMStruct *wim, int image, int write_flags,
2280 struct list_head *blob_table_list)
2282 int write_resource_flags;
2283 off_t old_blob_table_end = 0;
2284 struct integrity_table *old_integrity_table = NULL;
2285 off_t new_blob_table_end;
2289 write_resource_flags = write_flags_to_resource_flags(write_flags);
2291 /* In the WIM header, there is room for the resource entry for a
2292 * metadata resource labeled as the "boot metadata". This entry should
2293 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2294 * it should be a copy of the resource entry for the image that is
2295 * marked as bootable. */
2296 if (wim->out_hdr.boot_idx == 0) {
2297 zero_reshdr(&wim->out_hdr.boot_metadata_reshdr);
2299 copy_reshdr(&wim->out_hdr.boot_metadata_reshdr,
2300 &wim->image_metadata[
2301 wim->out_hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2304 /* If overwriting the WIM file containing an integrity table in-place,
2305 * we'd like to re-use the information in the old integrity table
2306 * instead of recalculating it. But we might overwrite the old
2307 * integrity table when we expand the XML data. Read it into memory
2309 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2310 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2311 (WIMLIB_WRITE_FLAG_OVERWRITE |
2312 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2313 && wim_has_integrity_table(wim))
2315 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2316 wim->hdr.blob_table_reshdr.size_in_wim;
2317 (void)read_integrity_table(wim,
2318 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2319 &old_integrity_table);
2320 /* If we couldn't read the old integrity table, we can still
2321 * re-calculate the full integrity table ourselves. Hence the
2322 * ignoring of the return value. */
2325 /* Write blob table if needed. */
2326 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
2327 ret = write_blob_table(wim, image, write_flags,
2330 free_integrity_table(old_integrity_table);
2335 /* Write XML data. */
2336 xml_totalbytes = wim->out_fd.offset;
2337 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2338 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2339 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2340 &wim->out_hdr.xml_data_reshdr,
2341 write_resource_flags);
2343 free_integrity_table(old_integrity_table);
2347 /* Write integrity table if needed. */
2348 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2349 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS) {
2350 /* The XML data we wrote may have overwritten part of
2351 * the old integrity table, so while calculating the new
2352 * integrity table we should temporarily update the WIM
2353 * header to remove the integrity table reference. */
2354 struct wim_header checkpoint_hdr;
2355 memcpy(&checkpoint_hdr, &wim->out_hdr, sizeof(struct wim_header));
2356 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2357 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2358 ret = write_wim_header(&checkpoint_hdr, &wim->out_fd, 0);
2360 free_integrity_table(old_integrity_table);
2365 new_blob_table_end = wim->out_hdr.blob_table_reshdr.offset_in_wim +
2366 wim->out_hdr.blob_table_reshdr.size_in_wim;
2368 ret = write_integrity_table(wim,
2371 old_integrity_table);
2372 free_integrity_table(old_integrity_table);
2376 /* No integrity table. */
2377 zero_reshdr(&wim->out_hdr.integrity_table_reshdr);
2380 /* Now that all information in the WIM header has been determined, the
2381 * preliminary header written earlier can be overwritten, the header of
2382 * the existing WIM file can be overwritten, or the final header can be
2383 * written to the end of the pipable WIM. */
2384 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2385 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2386 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2388 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, 0);
2392 /* Possibly sync file data to disk before closing. On POSIX systems, it
2393 * is necessary to do this before using rename() to overwrite an
2394 * existing file with a new file. Otherwise, data loss would occur if
2395 * the system is abruptly terminated when the metadata for the rename
2396 * operation has been written to disk, but the new file data has not.
2398 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2399 if (fsync(wim->out_fd.fd)) {
2400 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2401 return WIMLIB_ERR_WRITE;
2405 if (close_wim_writable(wim, write_flags)) {
2406 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2407 return WIMLIB_ERR_WRITE;
2413 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2415 /* Set advisory lock on WIM file (if not already done so) */
2417 lock_wim_for_append(WIMStruct *wim)
2419 if (wim->locked_for_append)
2421 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2422 wim->locked_for_append = 1;
2425 if (errno != EWOULDBLOCK)
2427 return WIMLIB_ERR_ALREADY_LOCKED;
2430 /* Remove advisory lock on WIM file (if present) */
2432 unlock_wim_for_append(WIMStruct *wim)
2434 if (wim->locked_for_append) {
2435 flock(wim->in_fd.fd, LOCK_UN);
2436 wim->locked_for_append = 0;
2442 * write_pipable_wim():
2444 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2445 * capable of being applied from a pipe).
2447 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2448 * images can be applied from them sequentially when the file data is sent over
2449 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2450 * The modifications made to the WIM format for pipable WIMs are:
2452 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2453 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2454 * stops other software from trying to read the file as a normal WIM.
2456 * - The header at the beginning of the file does not contain all the normal
2457 * information; in particular it will have all 0's for the blob table and XML
2458 * data resource entries. This is because this information cannot be
2459 * determined until the blob table and XML data have been written.
2460 * Consequently, wimlib will write the full header at the very end of the
2461 * file. The header at the end, however, is only used when reading the WIM
2462 * from a seekable file (not a pipe).
2464 * - An extra copy of the XML data is placed directly after the header. This
2465 * allows image names and sizes to be determined at an appropriate time when
2466 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2467 * WIM is read from a seekable file (not a pipe).
2469 * - Solid resources are not allowed. Each blob is always stored in its own
2472 * - The format of resources, or blobs, has been modified to allow them to be
2473 * used before the "blob table" has been read. Each blob is prefixed with a
2474 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2475 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2476 * uncompressed blob size, and flags that indicate whether the blob is
2477 * compressed. The data of uncompressed blobs then follows literally, while
2478 * the data of compressed blobs follows in a modified format. Compressed
2479 * blobs do not begin with a chunk table, since the chunk table cannot be
2480 * written until all chunks have been compressed. Instead, each compressed
2481 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2482 * Furthermore, the chunk table is written at the end of the resource instead
2483 * of the start. Note: chunk offsets are given in the chunk table as if the
2484 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2485 * used if the WIM is being read from a seekable file (not a pipe).
2487 * - Metadata blobs always come before non-metadata blobs. (This does not by
2488 * itself constitute an incompatibility with normal WIMs, since this is valid
2491 * - At least up to the end of the blobs, all components must be packed as
2492 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2493 * not by itself consititute an incompatibility with normal WIMs, since this
2494 * is valid in normal WIMs.)
2496 * Note: the blob table, XML data, and header at the end are not used when
2497 * applying from a pipe. They exist to support functionality such as image
2498 * application and export when the WIM is *not* read from a pipe.
2500 * Layout of pipable WIM:
2502 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2503 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2504 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2506 * Layout of normal WIM:
2508 * +--------+-----------------------------+-------------------------+
2509 * | Header | File and metadata resources | Blob table | XML data |
2510 * +--------+-----------------------------+-------------------------+
2512 * An optional integrity table can follow the final XML data in both normal and
2513 * pipable WIMs. However, due to implementation details, wimlib currently can
2514 * only include an integrity table in a pipable WIM when writing it to a
2515 * seekable file (not a pipe).
2517 * Do note that since pipable WIMs are not supported by Microsoft's software,
2518 * wimlib does not create them unless explicitly requested (with
2519 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2520 * characters to identify the file.
2523 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2524 unsigned num_threads,
2525 struct list_head *blob_list_override,
2526 struct list_head *blob_table_list_ret)
2529 struct wim_reshdr xml_reshdr;
2531 WARNING("Creating a pipable WIM, which will "
2533 " with Microsoft's software (WIMGAPI/ImageX/DISM).");
2535 /* At this point, the header at the beginning of the file has already
2538 /* For efficiency, when wimlib adds an image to the WIM with
2539 * wimlib_add_image(), the SHA-1 message digests of files are not
2540 * calculated; instead, they are calculated while the files are being
2541 * written. However, this does not work when writing a pipable WIM,
2542 * since when writing a blob to a pipable WIM, its SHA-1 message digest
2543 * needs to be known before the blob data is written. Therefore, before
2544 * getting much farther, we need to pre-calculate the SHA-1 message
2545 * digests of all blobs that will be written. */
2546 ret = wim_checksum_unhashed_blobs(wim);
2550 /* Write extra copy of the XML data. */
2551 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2552 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2556 /* Write metadata resources for the image(s) being included in the
2558 ret = write_metadata_resources(wim, image, write_flags);
2562 /* Write file data needed for the image(s) being included in the output
2563 * WIM, or file data needed for the split WIM part. */
2564 return write_file_data(wim, image, write_flags,
2565 num_threads, blob_list_override,
2566 blob_table_list_ret);
2568 /* The blob table, XML data, and header at end are handled by
2569 * finish_write(). */
2573 should_default_to_solid_compression(WIMStruct *wim, int write_flags)
2575 return wim->out_hdr.wim_version == WIM_VERSION_SOLID &&
2576 !(write_flags & (WIMLIB_WRITE_FLAG_SOLID |
2577 WIMLIB_WRITE_FLAG_PIPABLE)) &&
2578 wim_has_solid_resources(wim);
2581 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2584 write_wim_part(WIMStruct *wim,
2585 const void *path_or_fd,
2588 unsigned num_threads,
2589 unsigned part_number,
2590 unsigned total_parts,
2591 struct list_head *blob_list_override,
2595 struct list_head blob_table_list;
2597 /* Internally, this is always called with a valid part number and total
2599 wimlib_assert(total_parts >= 1);
2600 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2602 /* A valid image (or all images) must be specified. */
2603 if (image != WIMLIB_ALL_IMAGES &&
2604 (image < 1 || image > wim->hdr.image_count))
2605 return WIMLIB_ERR_INVALID_IMAGE;
2607 /* If we need to write metadata resources, make sure the ::WIMStruct has
2608 * the needed information attached (e.g. is not a resource-only WIM,
2609 * such as a non-first part of a split WIM). */
2610 if (!wim_has_metadata(wim) &&
2611 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2612 return WIMLIB_ERR_METADATA_NOT_FOUND;
2614 /* Check for contradictory flags. */
2615 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2616 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2617 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2618 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2619 return WIMLIB_ERR_INVALID_PARAM;
2621 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2622 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2623 == (WIMLIB_WRITE_FLAG_PIPABLE |
2624 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2625 return WIMLIB_ERR_INVALID_PARAM;
2627 /* Include an integrity table by default if no preference was given and
2628 * the WIM already had an integrity table. */
2629 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2630 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))) {
2631 if (wim_has_integrity_table(wim))
2632 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2635 /* Write a pipable WIM by default if no preference was given and the WIM
2636 * was already pipable. */
2637 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2638 WIMLIB_WRITE_FLAG_NOT_PIPABLE))) {
2639 if (wim_is_pipable(wim))
2640 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2643 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2644 WIMLIB_WRITE_FLAG_SOLID))
2645 == (WIMLIB_WRITE_FLAG_PIPABLE |
2646 WIMLIB_WRITE_FLAG_SOLID))
2648 ERROR("Solid compression is unsupported in pipable WIMs");
2649 return WIMLIB_ERR_INVALID_PARAM;
2652 /* Start initializing the new file header. */
2653 memset(&wim->out_hdr, 0, sizeof(wim->out_hdr));
2655 /* Set the magic number. */
2656 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2657 wim->out_hdr.magic = PWM_MAGIC;
2659 wim->out_hdr.magic = WIM_MAGIC;
2661 /* Set the version number. */
2662 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2663 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2664 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2666 wim->out_hdr.wim_version = WIM_VERSION_DEFAULT;
2668 /* Default to solid compression if it is valid in the chosen WIM file
2669 * format and the WIMStruct references any solid resources. This is
2670 * useful when exporting an image from a solid WIM. */
2671 if (should_default_to_solid_compression(wim, write_flags))
2672 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2674 /* Set the header flags. */
2675 wim->out_hdr.flags = (wim->hdr.flags & (WIM_HDR_FLAG_RP_FIX |
2676 WIM_HDR_FLAG_READONLY));
2677 if (total_parts != 1)
2678 wim->out_hdr.flags |= WIM_HDR_FLAG_SPANNED;
2679 if (wim->out_compression_type != WIMLIB_COMPRESSION_TYPE_NONE) {
2680 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESSION;
2681 switch (wim->out_compression_type) {
2682 case WIMLIB_COMPRESSION_TYPE_XPRESS:
2683 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_XPRESS;
2685 case WIMLIB_COMPRESSION_TYPE_LZX:
2686 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZX;
2688 case WIMLIB_COMPRESSION_TYPE_LZMS:
2689 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZMS;
2694 /* Set the chunk size. */
2695 wim->out_hdr.chunk_size = wim->out_chunk_size;
2698 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2699 guid = wim->hdr.guid;
2701 copy_guid(wim->out_hdr.guid, guid);
2703 generate_guid(wim->out_hdr.guid);
2705 /* Set the part number and total parts. */
2706 wim->out_hdr.part_number = part_number;
2707 wim->out_hdr.total_parts = total_parts;
2709 /* Set the image count. */
2710 if (image == WIMLIB_ALL_IMAGES)
2711 wim->out_hdr.image_count = wim->hdr.image_count;
2713 wim->out_hdr.image_count = 1;
2715 /* Set the boot index. */
2716 wim->out_hdr.boot_idx = 0;
2717 if (total_parts == 1) {
2718 if (image == WIMLIB_ALL_IMAGES)
2719 wim->out_hdr.boot_idx = wim->hdr.boot_idx;
2720 else if (image == wim->hdr.boot_idx)
2721 wim->out_hdr.boot_idx = 1;
2724 /* Set up the output file descriptor. */
2725 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2726 /* File descriptor was explicitly provided. */
2727 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2728 if (!filedes_is_seekable(&wim->out_fd)) {
2729 /* The file descriptor is a pipe. */
2730 ret = WIMLIB_ERR_INVALID_PARAM;
2731 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2733 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2734 ERROR("Can't include integrity check when "
2735 "writing pipable WIM to pipe!");
2740 /* Filename of WIM to write was provided; open file descriptor
2742 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2743 O_TRUNC | O_CREAT | O_RDWR);
2748 /* Write initial header. This is merely a "dummy" header since it
2749 * doesn't have resource entries filled in yet, so it will be
2750 * overwritten later (unless writing a pipable WIM). */
2751 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2752 wim->out_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2753 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2754 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2758 /* Write file data and metadata resources. */
2759 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2760 /* Default case: create a normal (non-pipable) WIM. */
2761 ret = write_file_data(wim, image, write_flags,
2768 ret = write_metadata_resources(wim, image, write_flags);
2772 /* Non-default case: create pipable WIM. */
2773 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2780 /* Write blob table, XML data, and (optional) integrity table. */
2781 ret = finish_write(wim, image, write_flags, &blob_table_list);
2783 (void)close_wim_writable(wim, write_flags);
2787 /* Write a standalone WIM to a file or file descriptor. */
2789 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2790 int image, int write_flags, unsigned num_threads)
2792 return write_wim_part(wim, path_or_fd, image, write_flags,
2793 num_threads, 1, 1, NULL, NULL);
2796 /* API function documented in wimlib.h */
2798 wimlib_write(WIMStruct *wim, const tchar *path,
2799 int image, int write_flags, unsigned num_threads)
2801 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2802 return WIMLIB_ERR_INVALID_PARAM;
2804 if (path == NULL || path[0] == T('\0'))
2805 return WIMLIB_ERR_INVALID_PARAM;
2807 return write_standalone_wim(wim, path, image, write_flags, num_threads);
2810 /* API function documented in wimlib.h */
2812 wimlib_write_to_fd(WIMStruct *wim, int fd,
2813 int image, int write_flags, unsigned num_threads)
2815 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2816 return WIMLIB_ERR_INVALID_PARAM;
2819 return WIMLIB_ERR_INVALID_PARAM;
2821 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2823 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2827 any_images_modified(WIMStruct *wim)
2829 for (int i = 0; i < wim->hdr.image_count; i++)
2830 if (wim->image_metadata[i]->modified)
2836 check_resource_offset(struct blob_descriptor *blob, void *_wim)
2838 const WIMStruct *wim = _wim;
2839 off_t end_offset = *(const off_t*)wim->private;
2841 if (blob->blob_location == BLOB_IN_WIM &&
2842 blob->rdesc->wim == wim &&
2843 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
2844 return WIMLIB_ERR_RESOURCE_ORDER;
2848 /* Make sure no file or metadata resources are located after the XML data (or
2849 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2850 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2852 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2857 wim->private = &end_offset;
2858 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
2862 for (i = 0; i < wim->hdr.image_count; i++) {
2863 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
2871 * Overwrite a WIM, possibly appending new resources to it.
2873 * A WIM looks like (or is supposed to look like) the following:
2875 * Header (212 bytes)
2876 * Resources for metadata and files (variable size)
2877 * Blob table (variable size)
2878 * XML data (variable size)
2879 * Integrity table (optional) (variable size)
2881 * If we are not adding any new files or metadata, then the blob table is
2882 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2883 * header. This operation is potentially unsafe if the program is abruptly
2884 * terminated while the XML data or integrity table are being overwritten, but
2885 * before the new header has been written. To partially alleviate this problem,
2886 * we write a temporary header after the XML data has been written. This may
2887 * prevent the WIM from becoming corrupted if the program is terminated while
2888 * the integrity table is being calculated (but no guarantees, due to write
2891 * If we are adding new blobs, including new file data as well as any metadata
2892 * for any new images, then the blob table needs to be changed, and those blobs
2893 * need to be written. In this case, we try to perform a safe update of the WIM
2894 * file by writing the blobs *after* the end of the previous WIM, then writing
2895 * the new blob table, XML data, and (optionally) integrity table following the
2896 * new blobs. This will produce a layout like the following:
2898 * Header (212 bytes)
2899 * (OLD) Resources for metadata and files (variable size)
2900 * (OLD) Blob table (variable size)
2901 * (OLD) XML data (variable size)
2902 * (OLD) Integrity table (optional) (variable size)
2903 * (NEW) Resources for metadata and files (variable size)
2904 * (NEW) Blob table (variable size)
2905 * (NEW) XML data (variable size)
2906 * (NEW) Integrity table (optional) (variable size)
2908 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2909 * the header is overwritten to point to the new blob table, XML data, and
2910 * integrity table, to produce the following layout:
2912 * Header (212 bytes)
2913 * Resources for metadata and files (variable size)
2914 * Nothing (variable size)
2915 * Resources for metadata and files (variable size)
2916 * Blob table (variable size)
2917 * XML data (variable size)
2918 * Integrity table (optional) (variable size)
2920 * This method allows an image to be appended to a large WIM very quickly, and
2921 * is crash-safe except in the case of write re-ordering, but the disadvantage
2922 * is that a small hole is left in the WIM where the old blob table, xml data,
2923 * and integrity table were. (These usually only take up a small amount of
2924 * space compared to the blobs, however.)
2927 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
2931 u64 old_blob_table_end, old_xml_begin, old_xml_end;
2932 struct list_head blob_list;
2933 struct list_head blob_table_list;
2934 struct filter_context filter_ctx;
2936 /* Include an integrity table by default if no preference was given and
2937 * the WIM already had an integrity table. */
2938 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2939 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2940 if (wim_has_integrity_table(wim))
2941 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2943 /* Start preparing the updated file header. */
2944 memcpy(&wim->out_hdr, &wim->hdr, sizeof(wim->out_hdr));
2946 /* If using solid compression, the version number must be set to
2947 * WIM_VERSION_SOLID. */
2948 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2949 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2951 /* Default to solid compression if it is valid in the chosen WIM file
2952 * format and the WIMStruct references any solid resources. This is
2953 * useful when updating a solid WIM. */
2954 if (should_default_to_solid_compression(wim, write_flags))
2955 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2957 /* Set additional flags for overwrite. */
2958 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2959 WIMLIB_WRITE_FLAG_STREAMS_OK;
2961 /* Make sure there is no data after the XML data, except possibily an
2962 * integrity table. If this were the case, then this data would be
2964 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2965 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2966 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2967 wim->hdr.blob_table_reshdr.size_in_wim;
2968 if (wim_has_integrity_table(wim) &&
2969 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2970 WARNING("Didn't expect the integrity table to be before the XML data");
2971 ret = WIMLIB_ERR_RESOURCE_ORDER;
2975 if (old_blob_table_end > old_xml_begin) {
2976 WARNING("Didn't expect the blob table to be after the XML data");
2977 ret = WIMLIB_ERR_RESOURCE_ORDER;
2981 /* Set @old_wim_end, which indicates the point beyond which we don't
2982 * allow any file and metadata resources to appear without returning
2983 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2984 * overwrite these resources). */
2985 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
2986 /* If no images have been modified and no images have been
2987 * deleted, a new blob table does not need to be written. We
2988 * shall write the new XML data and optional integrity table
2989 * immediately after the blob table. Note that this may
2990 * overwrite an existing integrity table. */
2991 old_wim_end = old_blob_table_end;
2992 write_flags |= WIMLIB_WRITE_FLAG_NO_NEW_BLOBS;
2993 } else if (wim_has_integrity_table(wim)) {
2994 /* Old WIM has an integrity table; begin writing new blobs after
2996 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2997 wim->hdr.integrity_table_reshdr.size_in_wim;
2999 /* No existing integrity table; begin writing new blobs after
3000 * the old XML data. */
3001 old_wim_end = old_xml_end;
3004 ret = check_resource_offsets(wim, old_wim_end);
3008 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3009 &blob_list, &blob_table_list,
3014 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)
3015 wimlib_assert(list_empty(&blob_list));
3017 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3021 ret = lock_wim_for_append(wim);
3025 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3026 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3027 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3028 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3030 ERROR_WITH_ERRNO("Error updating WIM header flags");
3031 goto out_unlock_wim;
3034 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3035 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3036 ret = WIMLIB_ERR_WRITE;
3037 goto out_restore_hdr;
3040 ret = write_file_data_blobs(wim, &blob_list, write_flags,
3041 num_threads, &filter_ctx);
3045 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3049 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3054 unlock_wim_for_append(wim);
3058 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
3059 WARNING("Truncating \"%"TS"\" to its original size "
3060 "(%"PRIu64" bytes)", wim->filename, old_wim_end);
3061 /* Return value of ftruncate() is ignored because this is
3062 * already an error path. */
3063 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3066 (void)write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3068 unlock_wim_for_append(wim);
3070 (void)close_wim_writable(wim, write_flags);
3076 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3078 size_t wim_name_len;
3081 /* Write the WIM to a temporary file in the same directory as the
3083 wim_name_len = tstrlen(wim->filename);
3084 tchar tmpfile[wim_name_len + 10];
3085 tmemcpy(tmpfile, wim->filename, wim_name_len);
3086 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3087 tmpfile[wim_name_len + 9] = T('\0');
3089 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3091 WIMLIB_WRITE_FLAG_FSYNC |
3092 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3099 if (filedes_valid(&wim->in_fd)) {
3100 filedes_close(&wim->in_fd);
3101 filedes_invalidate(&wim->in_fd);
3104 /* Rename the new WIM file to the original WIM file. Note: on Windows
3105 * this actually calls win32_rename_replacement(), not _wrename(), so
3106 * that removing the existing destination file can be handled. */
3107 ret = trename(tmpfile, wim->filename);
3109 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3110 tmpfile, wim->filename);
3117 return WIMLIB_ERR_RENAME;
3120 union wimlib_progress_info progress;
3121 progress.rename.from = tmpfile;
3122 progress.rename.to = wim->filename;
3123 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3124 &progress, wim->progctx);
3127 /* Determine if the specified WIM file may be updated by appending in-place
3128 * rather than writing and replacing it with an entirely new file. */
3130 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3132 /* REBUILD flag forces full rebuild. */
3133 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3136 /* Image deletions cause full rebuild by default. */
3137 if (wim->image_deletion_occurred &&
3138 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3141 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3142 * turned into a pipable WIM in-place. */
3143 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3146 /* The default compression type and compression chunk size selected for
3147 * the output WIM must be the same as those currently used for the WIM.
3149 if (wim->compression_type != wim->out_compression_type)
3151 if (wim->chunk_size != wim->out_chunk_size)
3157 /* API function documented in wimlib.h */
3159 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3164 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3165 return WIMLIB_ERR_INVALID_PARAM;
3168 return WIMLIB_ERR_NO_FILENAME;
3170 orig_hdr_flags = wim->hdr.flags;
3171 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3172 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3173 ret = can_modify_wim(wim);
3174 wim->hdr.flags = orig_hdr_flags;
3178 if (can_overwrite_wim_inplace(wim, write_flags)) {
3179 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3180 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3182 WARNING("Falling back to re-building entire WIM");
3184 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);