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 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_XPRESS == 1);
552 STATIC_ASSERT(WIMLIB_COMPRESSION_TYPE_LZX == 2);
553 STATIC_ASSERT(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 /* We could ftruncate() the file to 'out_fd->offset' here, but there
773 * isn't much point. Usually we will only be truncating by a few bytes
774 * and will just overwrite the data immediately. */
776 blob->out_reshdr.size_in_wim = blob->size;
777 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
778 WIM_RESHDR_FLAG_SOLID);
782 /* Returns true if the specified blob, which was written as a non-solid
783 * resource, should be truncated from the WIM file and re-written uncompressed.
784 * blob->out_reshdr must be filled in from the initial write of the blob. */
786 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
787 const struct blob_descriptor *blob)
789 /* If the compressed data is smaller than the uncompressed data, prefer
790 * the compressed data. */
791 if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
794 /* If we're not actually writing compressed data, then there's no need
796 if (!ctx->compressor)
799 /* If writing a pipable WIM, everything we write to the output is final
800 * (it might actually be a pipe!). */
801 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
804 /* If the blob that would need to be re-read is located in a solid
805 * resource in another WIM file, then re-reading it would be costly. So
808 * Exception: if the compressed size happens to be *exactly* the same as
809 * the uncompressed size, then the blob *must* be written uncompressed
810 * in order to remain compatible with the Windows Overlay Filesystem
811 * Filter Driver (WOF).
813 * TODO: we are currently assuming that the optimization for
814 * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
815 * this case from being triggered too often. To fully prevent excessive
816 * decompressions in degenerate cases, we really should obtain the
817 * uncompressed data by decompressing the compressed data we wrote to
820 if (blob->blob_location == BLOB_IN_WIM &&
821 blob->size != blob->rdesc->uncompressed_size &&
822 blob->size != blob->out_reshdr.size_in_wim)
829 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
830 struct blob_descriptor *blob)
832 if (!should_rewrite_blob_uncompressed(ctx, blob))
835 /* Regular (non-solid) WIM resources with exactly one chunk and
836 * compressed size equal to uncompressed size are exactly the same as
837 * the corresponding compressed data --- since there must be 0 entries
838 * in the chunk table and the only chunk must be stored uncompressed.
839 * In this case, there's no need to rewrite anything. */
840 if (ctx->chunk_index == 1 &&
841 blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
843 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
847 return write_blob_uncompressed(blob, ctx->out_fd);
850 /* Write the next chunk of (typically compressed) data to the output WIM,
851 * handling the writing of the chunk table. */
853 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
854 size_t csize, size_t usize)
857 struct blob_descriptor *blob;
858 u32 completed_blob_count;
861 blob = list_entry(ctx->blobs_being_compressed.next,
862 struct blob_descriptor, write_blobs_list);
864 if (ctx->cur_write_blob_offset == 0 &&
865 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
867 /* Starting to write a new blob in non-solid mode. */
869 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
870 ret = write_pwm_blob_header(blob, ctx->out_fd,
871 ctx->compressor != NULL);
876 ret = begin_write_resource(ctx, blob->size);
881 if (ctx->compressor != NULL) {
882 /* Record the compresed chunk size. */
883 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
884 ctx->chunk_csizes[ctx->chunk_index++] = csize;
886 /* If writing a pipable WIM, before the chunk data write a chunk
887 * header that provides the compressed chunk size. */
888 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
889 struct pwm_chunk_hdr chunk_hdr = {
890 .compressed_size = cpu_to_le32(csize),
892 ret = full_write(ctx->out_fd, &chunk_hdr,
899 /* Write the chunk data. */
900 ret = full_write(ctx->out_fd, cchunk, csize);
904 ctx->cur_write_blob_offset += usize;
906 completed_size = usize;
907 completed_blob_count = 0;
908 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
909 /* Wrote chunk in solid mode. It may have finished multiple
911 struct blob_descriptor *next_blob;
913 while (blob && ctx->cur_write_blob_offset >= blob->size) {
915 ctx->cur_write_blob_offset -= blob->size;
917 if (ctx->cur_write_blob_offset)
918 next_blob = list_entry(blob->write_blobs_list.next,
919 struct blob_descriptor,
924 ret = done_with_blob(blob, ctx);
927 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
928 completed_blob_count++;
933 /* Wrote chunk in non-solid mode. It may have finished a
935 if (ctx->cur_write_blob_offset == blob->size) {
937 wimlib_assert(ctx->cur_write_blob_offset ==
938 ctx->cur_write_res_size);
940 ret = end_write_resource(ctx, &blob->out_reshdr);
944 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
945 if (ctx->compressor != NULL)
946 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
948 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
952 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
954 ctx->cur_write_blob_offset = 0;
956 ret = done_with_blob(blob, ctx);
959 list_del(&blob->write_blobs_list);
960 completed_blob_count++;
964 return do_write_blobs_progress(&ctx->progress_data, completed_size,
965 completed_blob_count, false);
968 ERROR_WITH_ERRNO("Write error");
973 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
975 /* While we are unable to get a new chunk buffer due to too many chunks
976 * already outstanding, retrieve and write the next compressed chunk. */
977 while (!(ctx->cur_chunk_buf =
978 ctx->compressor->get_chunk_buffer(ctx->compressor)))
986 bret = ctx->compressor->get_compression_result(ctx->compressor,
992 ret = write_chunk(ctx, cchunk, csize, usize);
999 /* Process the next chunk of data to be written to a WIM resource. */
1001 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1003 struct write_blobs_ctx *ctx = _ctx;
1005 const u8 *chunkptr, *chunkend;
1007 wimlib_assert(size != 0);
1009 if (ctx->compressor == NULL) {
1010 /* Write chunk uncompressed. */
1011 ret = write_chunk(ctx, chunk, size, size);
1014 ctx->cur_read_blob_offset += size;
1018 /* Submit the chunk for compression, but take into account that the
1019 * @size the chunk was provided in may not correspond to the
1020 * @out_chunk_size being used for compression. */
1022 chunkend = chunkptr + size;
1024 size_t needed_chunk_size;
1025 size_t bytes_consumed;
1027 if (!ctx->cur_chunk_buf) {
1028 ret = prepare_chunk_buffer(ctx);
1033 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1034 needed_chunk_size = ctx->out_chunk_size;
1036 needed_chunk_size = min(ctx->out_chunk_size,
1037 ctx->cur_chunk_buf_filled +
1038 (ctx->cur_read_blob_size -
1039 ctx->cur_read_blob_offset));
1042 bytes_consumed = min(chunkend - chunkptr,
1043 needed_chunk_size - ctx->cur_chunk_buf_filled);
1045 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1046 chunkptr, bytes_consumed);
1048 chunkptr += bytes_consumed;
1049 ctx->cur_read_blob_offset += bytes_consumed;
1050 ctx->cur_chunk_buf_filled += bytes_consumed;
1052 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1053 ctx->compressor->signal_chunk_filled(ctx->compressor,
1054 ctx->cur_chunk_buf_filled);
1055 ctx->cur_chunk_buf = NULL;
1056 ctx->cur_chunk_buf_filled = 0;
1058 } while (chunkptr != chunkend);
1062 /* Finish processing a blob for writing. It may not have been completely
1063 * written yet, as the chunk_compressor implementation may still have chunks
1064 * buffered or being compressed. */
1066 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1068 struct write_blobs_ctx *ctx = _ctx;
1070 wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
1072 if (!blob->will_be_in_output_wim) {
1073 /* The blob was a duplicate. Now that its data has finished
1074 * being read, it is being discarded in favor of the duplicate
1075 * entry. It therefore is no longer needed, and we can fire the
1076 * DONE_WITH_FILE callback because the file will not be read
1079 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1080 * blobs, since it needs to be possible to re-read the file if
1081 * it does not compress to less than its original size. */
1083 status = done_with_blob(blob, ctx);
1084 free_blob_descriptor(blob);
1085 } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1086 /* The blob was not a duplicate and was previously unhashed.
1087 * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1088 * read_blob_list(), blob->hash is now computed and valid. So
1089 * turn this blob into a "hashed" blob. */
1090 list_del(&blob->unhashed_list);
1091 blob_table_insert(ctx->blob_table, blob);
1097 /* Compute statistics about a list of blobs that will be written.
1099 * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1100 * (specified by WIMStruct) are together. */
1102 compute_blob_list_stats(struct list_head *blob_list,
1103 struct write_blobs_ctx *ctx)
1105 struct blob_descriptor *blob;
1106 u64 total_bytes = 0;
1108 u64 total_parts = 0;
1109 WIMStruct *prev_wim_part = NULL;
1111 list_for_each_entry(blob, blob_list, write_blobs_list) {
1113 total_bytes += blob->size;
1114 if (blob->blob_location == BLOB_IN_WIM) {
1115 if (prev_wim_part != blob->rdesc->wim) {
1116 prev_wim_part = blob->rdesc->wim;
1121 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1122 ctx->progress_data.progress.write_streams.total_streams = num_blobs;
1123 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1124 ctx->progress_data.progress.write_streams.completed_streams = 0;
1125 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1126 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1127 ctx->progress_data.progress.write_streams.completed_parts = 0;
1128 ctx->progress_data.next_progress = 0;
1131 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1132 * rather than compressed. Delete these blobs from @blob_list and move them to
1133 * @raw_copy_blobs. Return the total uncompressed size of the blobs that need
1134 * to be compressed. */
1136 find_raw_copy_blobs(struct list_head *blob_list,
1137 int write_resource_flags,
1140 struct list_head *raw_copy_blobs)
1142 struct blob_descriptor *blob, *tmp;
1143 u64 num_bytes_to_compress = 0;
1145 INIT_LIST_HEAD(raw_copy_blobs);
1147 /* Initialize temporary raw_copy_ok flag. */
1148 list_for_each_entry(blob, blob_list, write_blobs_list)
1149 if (blob->blob_location == BLOB_IN_WIM)
1150 blob->rdesc->raw_copy_ok = 0;
1152 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1153 if (blob->blob_location == BLOB_IN_WIM &&
1154 blob->rdesc->raw_copy_ok)
1156 list_move_tail(&blob->write_blobs_list,
1158 } else if (can_raw_copy(blob, write_resource_flags,
1159 out_ctype, out_chunk_size))
1161 blob->rdesc->raw_copy_ok = 1;
1162 list_move_tail(&blob->write_blobs_list,
1165 num_bytes_to_compress += blob->size;
1169 return num_bytes_to_compress;
1172 /* Copy a raw compressed resource located in another WIM file to the WIM file
1175 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1176 struct filedes *out_fd)
1178 u64 cur_read_offset;
1179 u64 end_read_offset;
1180 u8 buf[BUFFER_SIZE];
1181 size_t bytes_to_read;
1183 struct filedes *in_fd;
1184 struct blob_descriptor *blob;
1185 u64 out_offset_in_wim;
1187 /* Copy the raw data. */
1188 cur_read_offset = in_rdesc->offset_in_wim;
1189 end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1191 out_offset_in_wim = out_fd->offset;
1193 if (in_rdesc->is_pipable) {
1194 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1195 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1196 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1197 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1199 in_fd = &in_rdesc->wim->in_fd;
1200 wimlib_assert(cur_read_offset != end_read_offset);
1203 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1205 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1209 ret = full_write(out_fd, buf, bytes_to_read);
1213 cur_read_offset += bytes_to_read;
1215 } while (cur_read_offset != end_read_offset);
1217 list_for_each_entry(blob, &in_rdesc->blob_list, rdesc_node) {
1218 if (blob->will_be_in_output_wim) {
1219 blob_set_out_reshdr_for_reuse(blob);
1220 if (in_rdesc->flags & WIM_RESHDR_FLAG_SOLID)
1221 blob->out_res_offset_in_wim = out_offset_in_wim;
1223 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1230 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1231 * WIM file being written. */
1233 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1234 struct filedes *out_fd,
1235 struct write_blobs_progress_data *progress_data)
1237 struct blob_descriptor *blob;
1240 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1241 blob->rdesc->raw_copy_ok = 1;
1243 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list) {
1244 if (blob->rdesc->raw_copy_ok) {
1245 /* Write each solid resource only one time. */
1246 ret = write_raw_copy_resource(blob->rdesc, out_fd);
1249 blob->rdesc->raw_copy_ok = 0;
1251 ret = do_write_blobs_progress(progress_data, blob->size,
1259 /* Wait for and write all chunks pending in the compressor. */
1261 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1268 if (ctx->compressor == NULL)
1271 if (ctx->cur_chunk_buf_filled != 0) {
1272 ctx->compressor->signal_chunk_filled(ctx->compressor,
1273 ctx->cur_chunk_buf_filled);
1276 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1279 ret = write_chunk(ctx, cdata, csize, usize);
1287 validate_blob_list(struct list_head *blob_list)
1289 struct blob_descriptor *blob;
1291 list_for_each_entry(blob, blob_list, write_blobs_list) {
1292 wimlib_assert(blob->will_be_in_output_wim);
1293 wimlib_assert(blob->size != 0);
1298 blob_is_in_file(const struct blob_descriptor *blob)
1300 return blob->blob_location == BLOB_IN_FILE_ON_DISK
1302 || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1303 || blob->blob_location == BLOB_WIN32_ENCRYPTED
1309 init_done_with_file_info(struct list_head *blob_list)
1311 struct blob_descriptor *blob;
1313 list_for_each_entry(blob, blob_list, write_blobs_list) {
1314 if (blob_is_in_file(blob)) {
1315 blob->file_inode->i_num_remaining_streams = 0;
1316 blob->may_send_done_with_file = 1;
1318 blob->may_send_done_with_file = 0;
1322 list_for_each_entry(blob, blob_list, write_blobs_list)
1323 if (blob->may_send_done_with_file)
1324 blob->file_inode->i_num_remaining_streams++;
1328 * Write a list of blobs to the output WIM file.
1331 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1332 * by the 'write_blobs_list' member.
1335 * The file descriptor, opened for writing, to which to write the blobs.
1337 * @write_resource_flags
1338 * Flags to modify how the blobs are written:
1340 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1341 * Force compression of all resources, even if they could otherwise
1342 * be re-used by copying the raw data, due to being located in a WIM
1343 * file with compatible compression parameters.
1345 * WRITE_RESOURCE_FLAG_PIPABLE:
1346 * Write the resources in the wimlib-specific pipable format, and
1347 * furthermore do so in such a way that no seeking backwards in
1348 * @out_fd will be performed (so it may be a pipe).
1350 * WRITE_RESOURCE_FLAG_SOLID:
1351 * Combine all the blobs into a single resource rather than writing
1352 * them in separate resources. This flag is only valid if the WIM
1353 * version number has been, or will be, set to WIM_VERSION_SOLID.
1354 * This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1357 * Compression format to use in the output resources, specified as one of
1358 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
1362 * Compression chunk size to use in the output resources. It must be a
1363 * valid chunk size for the specified compression format @out_ctype, unless
1364 * @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1368 * Number of threads to use to compress data. If 0, a default number of
1369 * threads will be chosen. The number of threads still may be decreased
1370 * from the specified value if insufficient memory is detected.
1373 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1374 * must be pointer to the blob table for the WIMStruct on whose behalf the
1375 * blobs are being written. Otherwise, this parameter can be NULL.
1378 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1379 * can be a pointer to a context for blob filtering used to detect whether
1380 * the duplicate blob has been hard-filtered or not. If no blobs are
1381 * hard-filtered or no blobs are unhashed, this parameter can be NULL.
1383 * This function will write the blobs in @blob_list to resources in
1384 * consecutive positions in the output WIM file, or to a single solid resource
1385 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1386 * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1387 * updated to specify its location, size, and flags in the output WIM. In the
1388 * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1389 * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1390 * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1391 * respectively, in the output WIM of the solid resource containing the
1392 * corresponding blob.
1394 * Each of the blobs to write may be in any location supported by the
1395 * resource-handling code (specifically, read_blob_list()), such as the contents
1396 * of external file that has been logically added to the output WIM, or a blob
1397 * in another WIM file that has been imported, or even a blob in the "same" WIM
1398 * file of which a modified copy is being written. In the case that a blob is
1399 * already in a WIM file and uses compatible compression parameters, by default
1400 * this function will re-use the raw data instead of decompressing it, then
1401 * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1402 * specified in @write_resource_flags, this is not done.
1404 * As a further requirement, this function requires that the
1405 * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1406 * as any other blobs not in @blob_list that will be in the output WIM file, but
1407 * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1408 * resource with a blob in @blob_list. Still furthermore, if on-the-fly
1409 * deduplication of blobs is possible, then all blobs in @blob_list must also be
1410 * linked by @blob_table_list along with any other blobs that have
1411 * @will_be_in_output_wim set.
1413 * This function handles on-the-fly deduplication of blobs for which SHA-1
1414 * message digests have not yet been calculated. Such blobs may or may not need
1415 * to be written. If @blob_table is non-NULL, then each blob in @blob_list that
1416 * has @unhashed set but not @unique_size set is checksummed immediately before
1417 * it would otherwise be read for writing in order to determine if it is
1418 * identical to another blob already being written or one that would be filtered
1419 * out of the output WIM using blob_filtered() with the context @filter_ctx.
1420 * Each such duplicate blob will be removed from @blob_list, its reference count
1421 * transfered to the pre-existing duplicate blob, its memory freed, and will not
1422 * be written. Alternatively, if a blob in @blob_list is a duplicate with any
1423 * blob in @blob_table that has not been marked for writing or would not be
1424 * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1425 * taking ownership of the reference count and slot in the @blob_table_list.
1427 * Returns 0 if every blob was either written successfully or did not need to be
1428 * written; otherwise returns a non-zero error code.
1431 write_blob_list(struct list_head *blob_list,
1432 struct filedes *out_fd,
1433 int write_resource_flags,
1436 unsigned num_threads,
1437 struct blob_table *blob_table,
1438 struct filter_context *filter_ctx,
1439 wimlib_progress_func_t progfunc,
1443 struct write_blobs_ctx ctx;
1444 struct list_head raw_copy_blobs;
1446 wimlib_assert((write_resource_flags &
1447 (WRITE_RESOURCE_FLAG_SOLID |
1448 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1449 (WRITE_RESOURCE_FLAG_SOLID |
1450 WRITE_RESOURCE_FLAG_PIPABLE));
1452 validate_blob_list(blob_list);
1454 if (list_empty(blob_list))
1457 /* If needed, set auxiliary information so that we can detect when the
1458 * library has finished using each external file. */
1459 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1460 init_done_with_file_info(blob_list);
1462 memset(&ctx, 0, sizeof(ctx));
1464 ctx.out_fd = out_fd;
1465 ctx.blob_table = blob_table;
1466 ctx.out_ctype = out_ctype;
1467 ctx.out_chunk_size = out_chunk_size;
1468 ctx.write_resource_flags = write_resource_flags;
1469 ctx.filter_ctx = filter_ctx;
1472 * We normally sort the blobs to write by a "sequential" order that is
1473 * optimized for reading. But when using solid compression, we instead
1474 * sort the blobs by file extension and file name (when applicable; and
1475 * we don't do this for blobs from solid resources) so that similar
1476 * files are grouped together, which improves the compression ratio.
1477 * This is somewhat of a hack since a blob does not necessarily
1478 * correspond one-to-one with a filename, nor is there any guarantee
1479 * that two files with similar names or extensions are actually similar
1480 * in content. A potential TODO is to sort the blobs based on some
1481 * measure of similarity of their actual contents.
1484 ret = sort_blob_list_by_sequential_order(blob_list,
1485 offsetof(struct blob_descriptor,
1490 compute_blob_list_stats(blob_list, &ctx);
1492 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1493 ret = sort_blob_list_for_solid_compression(blob_list);
1495 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1498 ctx.progress_data.progfunc = progfunc;
1499 ctx.progress_data.progctx = progctx;
1501 ctx.num_bytes_to_compress = find_raw_copy_blobs(blob_list,
1502 write_resource_flags,
1507 if (ctx.num_bytes_to_compress == 0)
1508 goto out_write_raw_copy_resources;
1510 /* Unless uncompressed output was required, allocate a chunk_compressor
1511 * to do compression. There are serial and parallel implementations of
1512 * the chunk_compressor interface. We default to parallel using the
1513 * specified number of threads, unless the upper bound on the number
1514 * bytes needing to be compressed is less than a heuristic value. */
1515 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1517 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1518 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1519 ret = new_parallel_chunk_compressor(out_ctype,
1524 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1525 " Falling back to single-threaded compression.",
1526 wimlib_get_error_string(ret));
1531 if (ctx.compressor == NULL) {
1532 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1535 goto out_destroy_context;
1540 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1542 ctx.progress_data.progress.write_streams.num_threads = 1;
1544 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1545 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1547 ret = call_progress(ctx.progress_data.progfunc,
1548 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1549 &ctx.progress_data.progress,
1550 ctx.progress_data.progctx);
1552 goto out_destroy_context;
1554 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1555 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1557 goto out_destroy_context;
1560 /* Read the list of blobs needing to be compressed, using the specified
1561 * callbacks to execute processing of the data. */
1563 struct read_blob_callbacks cbs = {
1564 .begin_blob = write_blob_begin_read,
1565 .consume_chunk = write_blob_process_chunk,
1566 .end_blob = write_blob_end_read,
1570 ret = read_blob_list(blob_list,
1571 offsetof(struct blob_descriptor, write_blobs_list),
1573 BLOB_LIST_ALREADY_SORTED |
1574 VERIFY_BLOB_HASHES |
1575 COMPUTE_MISSING_BLOB_HASHES);
1578 goto out_destroy_context;
1580 ret = finish_remaining_chunks(&ctx);
1582 goto out_destroy_context;
1584 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1585 struct wim_reshdr reshdr;
1586 struct blob_descriptor *blob;
1589 ret = end_write_resource(&ctx, &reshdr);
1591 goto out_destroy_context;
1594 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1595 blob->out_reshdr.size_in_wim = blob->size;
1596 blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1597 WIM_RESHDR_FLAG_SOLID;
1598 blob->out_reshdr.uncompressed_size = 0;
1599 blob->out_reshdr.offset_in_wim = offset_in_res;
1600 blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1601 blob->out_res_size_in_wim = reshdr.size_in_wim;
1602 blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1603 offset_in_res += blob->size;
1605 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1608 out_write_raw_copy_resources:
1609 /* Copy any compressed resources for which the raw data can be reused
1610 * without decompression. */
1611 ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1612 &ctx.progress_data);
1614 out_destroy_context:
1615 FREE(ctx.chunk_csizes);
1617 ctx.compressor->destroy(ctx.compressor);
1623 write_file_data_blobs(WIMStruct *wim,
1624 struct list_head *blob_list,
1626 unsigned num_threads,
1627 struct filter_context *filter_ctx)
1631 int write_resource_flags;
1633 write_resource_flags = write_flags_to_resource_flags(write_flags);
1635 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1636 out_chunk_size = wim->out_solid_chunk_size;
1637 out_ctype = wim->out_solid_compression_type;
1639 out_chunk_size = wim->out_chunk_size;
1640 out_ctype = wim->out_compression_type;
1643 return write_blob_list(blob_list,
1645 write_resource_flags,
1655 /* Write the contents of the specified blob as a WIM resource. */
1657 write_wim_resource(struct blob_descriptor *blob,
1658 struct filedes *out_fd,
1661 int write_resource_flags)
1663 LIST_HEAD(blob_list);
1664 list_add(&blob->write_blobs_list, &blob_list);
1665 blob->will_be_in_output_wim = 1;
1666 return write_blob_list(&blob_list,
1668 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1678 /* Write the contents of the specified buffer as a WIM resource. */
1680 write_wim_resource_from_buffer(const void *buf,
1683 struct filedes *out_fd,
1686 struct wim_reshdr *out_reshdr,
1688 int write_resource_flags)
1691 struct blob_descriptor blob;
1693 if (unlikely(buf_size == 0)) {
1694 zero_reshdr(out_reshdr);
1696 copy_hash(hash_ret, zero_hash);
1700 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1701 sha1_buffer(buf, buf_size, blob.hash);
1703 blob.is_metadata = is_metadata;
1705 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1706 write_resource_flags);
1710 copy_reshdr(out_reshdr, &blob.out_reshdr);
1713 copy_hash(hash_ret, blob.hash);
1717 struct blob_size_table {
1718 struct hlist_head *array;
1724 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1726 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1727 if (tab->array == NULL)
1728 return WIMLIB_ERR_NOMEM;
1729 tab->num_entries = 0;
1730 tab->capacity = capacity;
1735 destroy_blob_size_table(struct blob_size_table *tab)
1741 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1743 struct blob_size_table *tab = _tab;
1745 struct blob_descriptor *same_size_blob;
1747 pos = hash_u64(blob->size) % tab->capacity;
1748 blob->unique_size = 1;
1749 hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1750 if (same_size_blob->size == blob->size) {
1751 blob->unique_size = 0;
1752 same_size_blob->unique_size = 0;
1757 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1762 struct find_blobs_ctx {
1765 struct list_head blob_list;
1766 struct blob_size_table blob_size_tab;
1770 reference_blob_for_write(struct blob_descriptor *blob,
1771 struct list_head *blob_list, u32 nref)
1773 if (!blob->will_be_in_output_wim) {
1774 blob->out_refcnt = 0;
1775 list_add_tail(&blob->write_blobs_list, blob_list);
1776 blob->will_be_in_output_wim = 1;
1778 blob->out_refcnt += nref;
1782 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1784 struct list_head *blob_list = _blob_list;
1785 blob->will_be_in_output_wim = 0;
1786 reference_blob_for_write(blob, blob_list, blob->refcnt);
1791 inode_find_blobs_to_reference(const struct wim_inode *inode,
1792 const struct blob_table *table,
1793 struct list_head *blob_list)
1795 wimlib_assert(inode->i_nlink > 0);
1797 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1798 struct blob_descriptor *blob;
1801 blob = stream_blob(&inode->i_streams[i], table);
1803 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1805 hash = stream_hash(&inode->i_streams[i]);
1806 if (!is_zero_hash(hash))
1807 return blob_not_found_error(inode, hash);
1814 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1816 blob->will_be_in_output_wim = 0;
1821 image_find_blobs_to_reference(WIMStruct *wim)
1823 struct wim_image_metadata *imd;
1824 struct wim_inode *inode;
1825 struct blob_descriptor *blob;
1826 struct list_head *blob_list;
1829 imd = wim_get_current_image_metadata(wim);
1831 image_for_each_unhashed_blob(blob, imd)
1832 blob->will_be_in_output_wim = 0;
1834 blob_list = wim->private;
1835 image_for_each_inode(inode, imd) {
1836 ret = inode_find_blobs_to_reference(inode,
1846 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1849 struct list_head *blob_list_ret)
1853 INIT_LIST_HEAD(blob_list_ret);
1855 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1856 (image == 1 && wim->hdr.image_count == 1)))
1858 /* Fast case: Assume that all blobs are being written and that
1859 * the reference counts are correct. */
1860 struct blob_descriptor *blob;
1861 struct wim_image_metadata *imd;
1864 for_blob_in_table(wim->blob_table,
1865 fully_reference_blob_for_write,
1868 for (i = 0; i < wim->hdr.image_count; i++) {
1869 imd = wim->image_metadata[i];
1870 image_for_each_unhashed_blob(blob, imd)
1871 fully_reference_blob_for_write(blob, blob_list_ret);
1874 /* Slow case: Walk through the images being written and
1875 * determine the blobs referenced. */
1876 for_blob_in_table(wim->blob_table,
1877 do_blob_set_not_in_output_wim, NULL);
1878 wim->private = blob_list_ret;
1879 ret = for_image(wim, image, image_find_blobs_to_reference);
1887 struct insert_other_if_hard_filtered_ctx {
1888 struct blob_size_table *tab;
1889 struct filter_context *filter_ctx;
1893 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1895 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1897 if (!blob->will_be_in_output_wim &&
1898 blob_hard_filtered(blob, ctx->filter_ctx))
1899 blob_size_table_insert(blob, ctx->tab);
1904 determine_blob_size_uniquity(struct list_head *blob_list,
1905 struct blob_table *lt,
1906 struct filter_context *filter_ctx)
1909 struct blob_size_table tab;
1910 struct blob_descriptor *blob;
1912 ret = init_blob_size_table(&tab, 9001);
1916 if (may_hard_filter_blobs(filter_ctx)) {
1917 struct insert_other_if_hard_filtered_ctx ctx = {
1919 .filter_ctx = filter_ctx,
1921 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
1924 list_for_each_entry(blob, blob_list, write_blobs_list)
1925 blob_size_table_insert(blob, &tab);
1927 destroy_blob_size_table(&tab);
1932 filter_blob_list_for_write(struct list_head *blob_list,
1933 struct filter_context *filter_ctx)
1935 struct blob_descriptor *blob, *tmp;
1937 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1938 int status = blob_filtered(blob, filter_ctx);
1945 /* Soft filtered. */
1947 /* Hard filtered. */
1948 blob->will_be_in_output_wim = 0;
1949 list_del(&blob->blob_table_list);
1951 list_del(&blob->write_blobs_list);
1957 * prepare_blob_list_for_write() -
1959 * Prepare the list of blobs to write for writing a WIM containing the specified
1960 * image(s) with the specified write flags.
1963 * The WIMStruct on whose behalf the write is occurring.
1966 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1969 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1971 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
1972 * table of @wim and the per-image lists of unhashed blobs should be taken
1973 * as-is, and image metadata should not be searched for references. This
1974 * does not exclude filtering with OVERWRITE and SKIP_EXTERNAL_WIMS, below.
1976 * OVERWRITE: Blobs already present in @wim shall not be returned in
1979 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
1980 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
1983 * List of blobs, linked by write_blobs_list, that need to be written will
1986 * Note that this function assumes that unhashed blobs will be written; it
1987 * does not take into account that they may become duplicates when actually
1990 * @blob_table_list_ret
1991 * List of blobs, linked by blob_table_list, that need to be included in
1992 * the WIM's blob table will be returned here. This will be a superset of
1993 * the blobs in @blob_list_ret.
1995 * This list will be a proper superset of @blob_list_ret if and only if
1996 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1997 * the blobs that would otherwise need to be written were already located
2000 * All blobs in this list will have @out_refcnt set to the number of
2001 * references to the blob in the output WIM. If
2002 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2003 * may be as low as 0.
2006 * A context for queries of blob filter status with blob_filtered() is
2007 * returned in this location.
2009 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2010 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2011 * inserted into @blob_table_list_ret.
2013 * Still furthermore, @unique_size will be set to 1 on all blobs in
2014 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2015 * among all blobs in the blob table of @wim that are ineligible for being
2016 * written due to filtering.
2018 * Returns 0 on success; nonzero on read error, memory allocation error, or
2022 prepare_blob_list_for_write(WIMStruct *wim, int image,
2024 struct list_head *blob_list_ret,
2025 struct list_head *blob_table_list_ret,
2026 struct filter_context *filter_ctx_ret)
2029 struct blob_descriptor *blob;
2031 filter_ctx_ret->write_flags = write_flags;
2032 filter_ctx_ret->wim = wim;
2034 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2037 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2042 INIT_LIST_HEAD(blob_table_list_ret);
2043 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2044 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2046 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2051 if (may_filter_blobs(filter_ctx_ret))
2052 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2058 write_file_data(WIMStruct *wim, int image, int write_flags,
2059 unsigned num_threads,
2060 struct list_head *blob_list_override,
2061 struct list_head *blob_table_list_ret)
2064 struct list_head _blob_list;
2065 struct list_head *blob_list;
2066 struct blob_descriptor *blob;
2067 struct filter_context _filter_ctx;
2068 struct filter_context *filter_ctx;
2070 if (blob_list_override == NULL) {
2071 /* Normal case: prepare blob list from image(s) being written.
2073 blob_list = &_blob_list;
2074 filter_ctx = &_filter_ctx;
2075 ret = prepare_blob_list_for_write(wim, image, write_flags,
2077 blob_table_list_ret,
2082 /* Currently only as a result of wimlib_split() being called:
2083 * use blob list already explicitly provided. Use existing
2084 * reference counts. */
2085 blob_list = blob_list_override;
2087 INIT_LIST_HEAD(blob_table_list_ret);
2088 list_for_each_entry(blob, blob_list, write_blobs_list) {
2089 blob->out_refcnt = blob->refcnt;
2090 blob->will_be_in_output_wim = 1;
2091 blob->unique_size = 0;
2092 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2096 return write_file_data_blobs(wim,
2104 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2109 int write_resource_flags;
2111 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2114 write_resource_flags = write_flags_to_resource_flags(write_flags);
2116 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2118 ret = call_progress(wim->progfunc,
2119 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2120 NULL, wim->progctx);
2124 if (image == WIMLIB_ALL_IMAGES) {
2126 end_image = wim->hdr.image_count;
2128 start_image = image;
2132 for (int i = start_image; i <= end_image; i++) {
2133 struct wim_image_metadata *imd;
2135 imd = wim->image_metadata[i - 1];
2136 /* Build a new metadata resource only if image was modified from
2137 * the original (or was newly added). Otherwise just copy the
2139 if (imd->modified) {
2140 ret = write_metadata_resource(wim, i,
2141 write_resource_flags);
2142 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2143 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2146 ret = write_wim_resource(imd->metadata_blob,
2148 wim->out_compression_type,
2149 wim->out_chunk_size,
2150 write_resource_flags);
2156 return call_progress(wim->progfunc,
2157 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2158 NULL, wim->progctx);
2162 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2164 int raw_fd = topen(path, open_flags | O_BINARY, 0644);
2166 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2167 return WIMLIB_ERR_OPEN;
2169 filedes_init(&wim->out_fd, raw_fd);
2174 close_wim_writable(WIMStruct *wim, int write_flags)
2178 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2179 if (filedes_valid(&wim->out_fd))
2180 if (filedes_close(&wim->out_fd))
2181 ret = WIMLIB_ERR_WRITE;
2182 filedes_invalidate(&wim->out_fd);
2187 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2189 const struct blob_descriptor *blob1, *blob2;
2191 blob1 = *(const struct blob_descriptor**)p1;
2192 blob2 = *(const struct blob_descriptor**)p2;
2194 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2195 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2196 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2197 return cmp_u64(blob1->out_res_offset_in_wim,
2198 blob2->out_res_offset_in_wim);
2203 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2206 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2207 blob2->out_reshdr.offset_in_wim);
2211 write_blob_table(WIMStruct *wim, int image, int write_flags,
2212 struct list_head *blob_table_list)
2216 /* Set output resource metadata for blobs already present in WIM. */
2217 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2218 struct blob_descriptor *blob;
2219 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2220 if (blob->blob_location == BLOB_IN_WIM &&
2221 blob->rdesc->wim == wim)
2223 blob_set_out_reshdr_for_reuse(blob);
2228 ret = sort_blob_list(blob_table_list,
2229 offsetof(struct blob_descriptor, blob_table_list),
2230 cmp_blobs_by_out_rdesc);
2234 /* Add entries for metadata resources. */
2235 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2239 if (image == WIMLIB_ALL_IMAGES) {
2241 end_image = wim->hdr.image_count;
2243 start_image = image;
2247 /* Push metadata blob table entries onto the front of the list
2248 * in reverse order, so that they're written in order.
2250 for (int i = end_image; i >= start_image; i--) {
2251 struct blob_descriptor *metadata_blob;
2253 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2254 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2255 metadata_blob->out_refcnt = 1;
2256 list_add(&metadata_blob->blob_table_list, blob_table_list);
2260 return write_blob_table_from_blob_list(blob_table_list,
2262 wim->out_hdr.part_number,
2263 &wim->out_hdr.blob_table_reshdr,
2264 write_flags_to_resource_flags(write_flags));
2268 * Finish writing a WIM file: write the blob table, xml data, and integrity
2269 * table, then overwrite the WIM header.
2271 * The output file descriptor is closed on success, except when writing to a
2272 * user-specified file descriptor (WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR set).
2275 finish_write(WIMStruct *wim, int image, int write_flags,
2276 struct list_head *blob_table_list)
2278 int write_resource_flags;
2279 off_t old_blob_table_end = 0;
2280 struct integrity_table *old_integrity_table = NULL;
2281 off_t new_blob_table_end;
2285 write_resource_flags = write_flags_to_resource_flags(write_flags);
2287 /* In the WIM header, there is room for the resource entry for a
2288 * metadata resource labeled as the "boot metadata". This entry should
2289 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2290 * it should be a copy of the resource entry for the image that is
2291 * marked as bootable. */
2292 if (wim->out_hdr.boot_idx == 0) {
2293 zero_reshdr(&wim->out_hdr.boot_metadata_reshdr);
2295 copy_reshdr(&wim->out_hdr.boot_metadata_reshdr,
2296 &wim->image_metadata[
2297 wim->out_hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2300 /* If overwriting the WIM file containing an integrity table in-place,
2301 * we'd like to re-use the information in the old integrity table
2302 * instead of recalculating it. But we might overwrite the old
2303 * integrity table when we expand the XML data. Read it into memory
2305 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2306 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2307 (WIMLIB_WRITE_FLAG_OVERWRITE |
2308 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2309 && wim_has_integrity_table(wim))
2311 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2312 wim->hdr.blob_table_reshdr.size_in_wim;
2313 (void)read_integrity_table(wim,
2314 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2315 &old_integrity_table);
2316 /* If we couldn't read the old integrity table, we can still
2317 * re-calculate the full integrity table ourselves. Hence the
2318 * ignoring of the return value. */
2321 /* Write blob table if needed. */
2322 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
2323 ret = write_blob_table(wim, image, write_flags,
2326 free_integrity_table(old_integrity_table);
2331 /* Write XML data. */
2332 xml_totalbytes = wim->out_fd.offset;
2333 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2334 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2335 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2336 &wim->out_hdr.xml_data_reshdr,
2337 write_resource_flags);
2339 free_integrity_table(old_integrity_table);
2343 /* Write integrity table if needed. */
2344 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2345 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS) {
2346 /* The XML data we wrote may have overwritten part of
2347 * the old integrity table, so while calculating the new
2348 * integrity table we should temporarily update the WIM
2349 * header to remove the integrity table reference. */
2350 struct wim_header checkpoint_hdr;
2351 memcpy(&checkpoint_hdr, &wim->out_hdr, sizeof(struct wim_header));
2352 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2353 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2354 ret = write_wim_header(&checkpoint_hdr, &wim->out_fd, 0);
2356 free_integrity_table(old_integrity_table);
2361 new_blob_table_end = wim->out_hdr.blob_table_reshdr.offset_in_wim +
2362 wim->out_hdr.blob_table_reshdr.size_in_wim;
2364 ret = write_integrity_table(wim,
2367 old_integrity_table);
2368 free_integrity_table(old_integrity_table);
2372 /* No integrity table. */
2373 zero_reshdr(&wim->out_hdr.integrity_table_reshdr);
2376 /* Now that all information in the WIM header has been determined, the
2377 * preliminary header written earlier can be overwritten, the header of
2378 * the existing WIM file can be overwritten, or the final header can be
2379 * written to the end of the pipable WIM. */
2380 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2381 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2382 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2384 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, 0);
2388 /* Possibly sync file data to disk before closing. On POSIX systems, it
2389 * is necessary to do this before using rename() to overwrite an
2390 * existing file with a new file. Otherwise, data loss would occur if
2391 * the system is abruptly terminated when the metadata for the rename
2392 * operation has been written to disk, but the new file data has not.
2394 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2395 if (fsync(wim->out_fd.fd)) {
2396 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2397 return WIMLIB_ERR_WRITE;
2401 if (close_wim_writable(wim, write_flags)) {
2402 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2403 return WIMLIB_ERR_WRITE;
2409 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2411 /* Set advisory lock on WIM file (if not already done so) */
2413 lock_wim_for_append(WIMStruct *wim)
2415 if (wim->locked_for_append)
2417 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2418 wim->locked_for_append = 1;
2421 if (errno != EWOULDBLOCK)
2423 return WIMLIB_ERR_ALREADY_LOCKED;
2426 /* Remove advisory lock on WIM file (if present) */
2428 unlock_wim_for_append(WIMStruct *wim)
2430 if (wim->locked_for_append) {
2431 flock(wim->in_fd.fd, LOCK_UN);
2432 wim->locked_for_append = 0;
2438 * write_pipable_wim():
2440 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2441 * capable of being applied from a pipe).
2443 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2444 * images can be applied from them sequentially when the file data is sent over
2445 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2446 * The modifications made to the WIM format for pipable WIMs are:
2448 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2449 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2450 * stops other software from trying to read the file as a normal WIM.
2452 * - The header at the beginning of the file does not contain all the normal
2453 * information; in particular it will have all 0's for the blob table and XML
2454 * data resource entries. This is because this information cannot be
2455 * determined until the blob table and XML data have been written.
2456 * Consequently, wimlib will write the full header at the very end of the
2457 * file. The header at the end, however, is only used when reading the WIM
2458 * from a seekable file (not a pipe).
2460 * - An extra copy of the XML data is placed directly after the header. This
2461 * allows image names and sizes to be determined at an appropriate time when
2462 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2463 * WIM is read from a seekable file (not a pipe).
2465 * - Solid resources are not allowed. Each blob is always stored in its own
2468 * - The format of resources, or blobs, has been modified to allow them to be
2469 * used before the "blob table" has been read. Each blob is prefixed with a
2470 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2471 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2472 * uncompressed blob size, and flags that indicate whether the blob is
2473 * compressed. The data of uncompressed blobs then follows literally, while
2474 * the data of compressed blobs follows in a modified format. Compressed
2475 * blobs do not begin with a chunk table, since the chunk table cannot be
2476 * written until all chunks have been compressed. Instead, each compressed
2477 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2478 * Furthermore, the chunk table is written at the end of the resource instead
2479 * of the start. Note: chunk offsets are given in the chunk table as if the
2480 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2481 * used if the WIM is being read from a seekable file (not a pipe).
2483 * - Metadata blobs always come before non-metadata blobs. (This does not by
2484 * itself constitute an incompatibility with normal WIMs, since this is valid
2487 * - At least up to the end of the blobs, all components must be packed as
2488 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2489 * not by itself consititute an incompatibility with normal WIMs, since this
2490 * is valid in normal WIMs.)
2492 * Note: the blob table, XML data, and header at the end are not used when
2493 * applying from a pipe. They exist to support functionality such as image
2494 * application and export when the WIM is *not* read from a pipe.
2496 * Layout of pipable WIM:
2498 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2499 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2500 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2502 * Layout of normal WIM:
2504 * +--------+-----------------------------+-------------------------+
2505 * | Header | File and metadata resources | Blob table | XML data |
2506 * +--------+-----------------------------+-------------------------+
2508 * An optional integrity table can follow the final XML data in both normal and
2509 * pipable WIMs. However, due to implementation details, wimlib currently can
2510 * only include an integrity table in a pipable WIM when writing it to a
2511 * seekable file (not a pipe).
2513 * Do note that since pipable WIMs are not supported by Microsoft's software,
2514 * wimlib does not create them unless explicitly requested (with
2515 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2516 * characters to identify the file.
2519 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2520 unsigned num_threads,
2521 struct list_head *blob_list_override,
2522 struct list_head *blob_table_list_ret)
2525 struct wim_reshdr xml_reshdr;
2527 WARNING("Creating a pipable WIM, which will "
2529 " with Microsoft's software (WIMGAPI/ImageX/DISM).");
2531 /* At this point, the header at the beginning of the file has already
2534 /* For efficiency, when wimlib adds an image to the WIM with
2535 * wimlib_add_image(), the SHA-1 message digests of files are not
2536 * calculated; instead, they are calculated while the files are being
2537 * written. However, this does not work when writing a pipable WIM,
2538 * since when writing a blob to a pipable WIM, its SHA-1 message digest
2539 * needs to be known before the blob data is written. Therefore, before
2540 * getting much farther, we need to pre-calculate the SHA-1 message
2541 * digests of all blobs that will be written. */
2542 ret = wim_checksum_unhashed_blobs(wim);
2546 /* Write extra copy of the XML data. */
2547 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2548 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2552 /* Write metadata resources for the image(s) being included in the
2554 ret = write_metadata_resources(wim, image, write_flags);
2558 /* Write file data needed for the image(s) being included in the output
2559 * WIM, or file data needed for the split WIM part. */
2560 return write_file_data(wim, image, write_flags,
2561 num_threads, blob_list_override,
2562 blob_table_list_ret);
2564 /* The blob table, XML data, and header at end are handled by
2565 * finish_write(). */
2569 should_default_to_solid_compression(WIMStruct *wim, int write_flags)
2571 return wim->out_hdr.wim_version == WIM_VERSION_SOLID &&
2572 !(write_flags & (WIMLIB_WRITE_FLAG_SOLID |
2573 WIMLIB_WRITE_FLAG_PIPABLE)) &&
2574 wim_has_solid_resources(wim);
2577 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2580 write_wim_part(WIMStruct *wim,
2581 const void *path_or_fd,
2584 unsigned num_threads,
2585 unsigned part_number,
2586 unsigned total_parts,
2587 struct list_head *blob_list_override,
2591 struct list_head blob_table_list;
2593 /* Internally, this is always called with a valid part number and total
2595 wimlib_assert(total_parts >= 1);
2596 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2598 /* A valid image (or all images) must be specified. */
2599 if (image != WIMLIB_ALL_IMAGES &&
2600 (image < 1 || image > wim->hdr.image_count))
2601 return WIMLIB_ERR_INVALID_IMAGE;
2603 /* If we need to write metadata resources, make sure the ::WIMStruct has
2604 * the needed information attached (e.g. is not a resource-only WIM,
2605 * such as a non-first part of a split WIM). */
2606 if (!wim_has_metadata(wim) &&
2607 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2608 return WIMLIB_ERR_METADATA_NOT_FOUND;
2610 /* Check for contradictory flags. */
2611 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2612 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2613 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2614 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2615 return WIMLIB_ERR_INVALID_PARAM;
2617 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2618 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2619 == (WIMLIB_WRITE_FLAG_PIPABLE |
2620 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2621 return WIMLIB_ERR_INVALID_PARAM;
2623 /* Include an integrity table by default if no preference was given and
2624 * the WIM already had an integrity table. */
2625 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2626 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))) {
2627 if (wim_has_integrity_table(wim))
2628 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2631 /* Write a pipable WIM by default if no preference was given and the WIM
2632 * was already pipable. */
2633 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2634 WIMLIB_WRITE_FLAG_NOT_PIPABLE))) {
2635 if (wim_is_pipable(wim))
2636 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2639 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2640 WIMLIB_WRITE_FLAG_SOLID))
2641 == (WIMLIB_WRITE_FLAG_PIPABLE |
2642 WIMLIB_WRITE_FLAG_SOLID))
2644 ERROR("Solid compression is unsupported in pipable WIMs");
2645 return WIMLIB_ERR_INVALID_PARAM;
2648 /* Start initializing the new file header. */
2649 memset(&wim->out_hdr, 0, sizeof(wim->out_hdr));
2651 /* Set the magic number. */
2652 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2653 wim->out_hdr.magic = PWM_MAGIC;
2655 wim->out_hdr.magic = WIM_MAGIC;
2657 /* Set the version number. */
2658 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2659 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2660 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2662 wim->out_hdr.wim_version = WIM_VERSION_DEFAULT;
2664 /* Default to solid compression if it is valid in the chosen WIM file
2665 * format and the WIMStruct references any solid resources. This is
2666 * useful when exporting an image from a solid WIM. */
2667 if (should_default_to_solid_compression(wim, write_flags))
2668 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2670 /* Set the header flags. */
2671 wim->out_hdr.flags = (wim->hdr.flags & (WIM_HDR_FLAG_RP_FIX |
2672 WIM_HDR_FLAG_READONLY));
2673 if (total_parts != 1)
2674 wim->out_hdr.flags |= WIM_HDR_FLAG_SPANNED;
2675 if (wim->out_compression_type != WIMLIB_COMPRESSION_TYPE_NONE) {
2676 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESSION;
2677 switch (wim->out_compression_type) {
2678 case WIMLIB_COMPRESSION_TYPE_XPRESS:
2679 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_XPRESS;
2681 case WIMLIB_COMPRESSION_TYPE_LZX:
2682 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZX;
2684 case WIMLIB_COMPRESSION_TYPE_LZMS:
2685 wim->out_hdr.flags |= WIM_HDR_FLAG_COMPRESS_LZMS;
2690 /* Set the chunk size. */
2691 wim->out_hdr.chunk_size = wim->out_chunk_size;
2694 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2695 guid = wim->hdr.guid;
2697 copy_guid(wim->out_hdr.guid, guid);
2699 generate_guid(wim->out_hdr.guid);
2701 /* Set the part number and total parts. */
2702 wim->out_hdr.part_number = part_number;
2703 wim->out_hdr.total_parts = total_parts;
2705 /* Set the image count. */
2706 if (image == WIMLIB_ALL_IMAGES)
2707 wim->out_hdr.image_count = wim->hdr.image_count;
2709 wim->out_hdr.image_count = 1;
2711 /* Set the boot index. */
2712 wim->out_hdr.boot_idx = 0;
2713 if (total_parts == 1) {
2714 if (image == WIMLIB_ALL_IMAGES)
2715 wim->out_hdr.boot_idx = wim->hdr.boot_idx;
2716 else if (image == wim->hdr.boot_idx)
2717 wim->out_hdr.boot_idx = 1;
2720 /* Set up the output file descriptor. */
2721 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2722 /* File descriptor was explicitly provided. */
2723 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2724 if (!filedes_is_seekable(&wim->out_fd)) {
2725 /* The file descriptor is a pipe. */
2726 ret = WIMLIB_ERR_INVALID_PARAM;
2727 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2729 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2730 ERROR("Can't include integrity check when "
2731 "writing pipable WIM to pipe!");
2736 /* Filename of WIM to write was provided; open file descriptor
2738 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2739 O_TRUNC | O_CREAT | O_RDWR);
2744 /* Write initial header. This is merely a "dummy" header since it
2745 * doesn't have resource entries filled in yet, so it will be
2746 * overwritten later (unless writing a pipable WIM). */
2747 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2748 wim->out_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2749 ret = write_wim_header(&wim->out_hdr, &wim->out_fd, wim->out_fd.offset);
2750 wim->out_hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2754 /* Write file data and metadata resources. */
2755 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2756 /* Default case: create a normal (non-pipable) WIM. */
2757 ret = write_file_data(wim, image, write_flags,
2764 ret = write_metadata_resources(wim, image, write_flags);
2768 /* Non-default case: create pipable WIM. */
2769 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2776 /* Write blob table, XML data, and (optional) integrity table. */
2777 ret = finish_write(wim, image, write_flags, &blob_table_list);
2779 (void)close_wim_writable(wim, write_flags);
2783 /* Write a standalone WIM to a file or file descriptor. */
2785 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2786 int image, int write_flags, unsigned num_threads)
2788 return write_wim_part(wim, path_or_fd, image, write_flags,
2789 num_threads, 1, 1, NULL, NULL);
2792 /* API function documented in wimlib.h */
2794 wimlib_write(WIMStruct *wim, const tchar *path,
2795 int image, int write_flags, unsigned num_threads)
2797 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2798 return WIMLIB_ERR_INVALID_PARAM;
2800 if (path == NULL || path[0] == T('\0'))
2801 return WIMLIB_ERR_INVALID_PARAM;
2803 return write_standalone_wim(wim, path, image, write_flags, num_threads);
2806 /* API function documented in wimlib.h */
2808 wimlib_write_to_fd(WIMStruct *wim, int fd,
2809 int image, int write_flags, unsigned num_threads)
2811 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2812 return WIMLIB_ERR_INVALID_PARAM;
2815 return WIMLIB_ERR_INVALID_PARAM;
2817 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2819 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2823 any_images_modified(WIMStruct *wim)
2825 for (int i = 0; i < wim->hdr.image_count; i++)
2826 if (wim->image_metadata[i]->modified)
2832 check_resource_offset(struct blob_descriptor *blob, void *_wim)
2834 const WIMStruct *wim = _wim;
2835 off_t end_offset = *(const off_t*)wim->private;
2837 if (blob->blob_location == BLOB_IN_WIM &&
2838 blob->rdesc->wim == wim &&
2839 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
2840 return WIMLIB_ERR_RESOURCE_ORDER;
2844 /* Make sure no file or metadata resources are located after the XML data (or
2845 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2846 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2848 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2853 wim->private = &end_offset;
2854 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
2858 for (i = 0; i < wim->hdr.image_count; i++) {
2859 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
2867 * Overwrite a WIM, possibly appending new resources to it.
2869 * A WIM looks like (or is supposed to look like) the following:
2871 * Header (212 bytes)
2872 * Resources for metadata and files (variable size)
2873 * Blob table (variable size)
2874 * XML data (variable size)
2875 * Integrity table (optional) (variable size)
2877 * If we are not adding any new files or metadata, then the blob table is
2878 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2879 * header. This operation is potentially unsafe if the program is abruptly
2880 * terminated while the XML data or integrity table are being overwritten, but
2881 * before the new header has been written. To partially alleviate this problem,
2882 * we write a temporary header after the XML data has been written. This may
2883 * prevent the WIM from becoming corrupted if the program is terminated while
2884 * the integrity table is being calculated (but no guarantees, due to write
2887 * If we are adding new blobs, including new file data as well as any metadata
2888 * for any new images, then the blob table needs to be changed, and those blobs
2889 * need to be written. In this case, we try to perform a safe update of the WIM
2890 * file by writing the blobs *after* the end of the previous WIM, then writing
2891 * the new blob table, XML data, and (optionally) integrity table following the
2892 * new blobs. This will produce a layout like the following:
2894 * Header (212 bytes)
2895 * (OLD) Resources for metadata and files (variable size)
2896 * (OLD) Blob table (variable size)
2897 * (OLD) XML data (variable size)
2898 * (OLD) Integrity table (optional) (variable size)
2899 * (NEW) Resources for metadata and files (variable size)
2900 * (NEW) Blob table (variable size)
2901 * (NEW) XML data (variable size)
2902 * (NEW) Integrity table (optional) (variable size)
2904 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2905 * the header is overwritten to point to the new blob table, XML data, and
2906 * integrity table, to produce the following layout:
2908 * Header (212 bytes)
2909 * Resources for metadata and files (variable size)
2910 * Nothing (variable size)
2911 * Resources for metadata and files (variable size)
2912 * Blob table (variable size)
2913 * XML data (variable size)
2914 * Integrity table (optional) (variable size)
2916 * This method allows an image to be appended to a large WIM very quickly, and
2917 * is crash-safe except in the case of write re-ordering, but the disadvantage
2918 * is that a small hole is left in the WIM where the old blob table, xml data,
2919 * and integrity table were. (These usually only take up a small amount of
2920 * space compared to the blobs, however.)
2923 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
2927 u64 old_blob_table_end, old_xml_begin, old_xml_end;
2928 struct list_head blob_list;
2929 struct list_head blob_table_list;
2930 struct filter_context filter_ctx;
2932 /* Include an integrity table by default if no preference was given and
2933 * the WIM already had an integrity table. */
2934 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2935 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2936 if (wim_has_integrity_table(wim))
2937 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2939 /* Start preparing the updated file header. */
2940 memcpy(&wim->out_hdr, &wim->hdr, sizeof(wim->out_hdr));
2942 /* If using solid compression, the version number must be set to
2943 * WIM_VERSION_SOLID. */
2944 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2945 wim->out_hdr.wim_version = WIM_VERSION_SOLID;
2947 /* Default to solid compression if it is valid in the chosen WIM file
2948 * format and the WIMStruct references any solid resources. This is
2949 * useful when updating a solid WIM. */
2950 if (should_default_to_solid_compression(wim, write_flags))
2951 write_flags |= WIMLIB_WRITE_FLAG_SOLID;
2953 /* Set additional flags for overwrite. */
2954 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2955 WIMLIB_WRITE_FLAG_STREAMS_OK;
2957 /* Make sure there is no data after the XML data, except possibily an
2958 * integrity table. If this were the case, then this data would be
2960 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2961 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2962 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2963 wim->hdr.blob_table_reshdr.size_in_wim;
2964 if (wim_has_integrity_table(wim) &&
2965 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2966 WARNING("Didn't expect the integrity table to be before the XML data");
2967 ret = WIMLIB_ERR_RESOURCE_ORDER;
2971 if (old_blob_table_end > old_xml_begin) {
2972 WARNING("Didn't expect the blob table to be after the XML data");
2973 ret = WIMLIB_ERR_RESOURCE_ORDER;
2977 /* Set @old_wim_end, which indicates the point beyond which we don't
2978 * allow any file and metadata resources to appear without returning
2979 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2980 * overwrite these resources). */
2981 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
2982 /* If no images have been modified and no images have been
2983 * deleted, a new blob table does not need to be written. We
2984 * shall write the new XML data and optional integrity table
2985 * immediately after the blob table. Note that this may
2986 * overwrite an existing integrity table. */
2987 old_wim_end = old_blob_table_end;
2988 write_flags |= WIMLIB_WRITE_FLAG_NO_NEW_BLOBS;
2989 } else if (wim_has_integrity_table(wim)) {
2990 /* Old WIM has an integrity table; begin writing new blobs after
2992 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2993 wim->hdr.integrity_table_reshdr.size_in_wim;
2995 /* No existing integrity table; begin writing new blobs after
2996 * the old XML data. */
2997 old_wim_end = old_xml_end;
3000 ret = check_resource_offsets(wim, old_wim_end);
3004 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3005 &blob_list, &blob_table_list,
3010 if (write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)
3011 wimlib_assert(list_empty(&blob_list));
3013 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3017 ret = lock_wim_for_append(wim);
3021 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3022 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3023 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3024 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3026 ERROR_WITH_ERRNO("Error updating WIM header flags");
3027 goto out_unlock_wim;
3030 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3031 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3032 ret = WIMLIB_ERR_WRITE;
3033 goto out_restore_hdr;
3036 ret = write_file_data_blobs(wim, &blob_list, write_flags,
3037 num_threads, &filter_ctx);
3041 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3045 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3050 unlock_wim_for_append(wim);
3054 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_NEW_BLOBS)) {
3055 WARNING("Truncating \"%"TS"\" to its original size "
3056 "(%"PRIu64" bytes)", wim->filename, old_wim_end);
3057 /* Return value of ftruncate() is ignored because this is
3058 * already an error path. */
3059 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3062 (void)write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3064 unlock_wim_for_append(wim);
3066 (void)close_wim_writable(wim, write_flags);
3072 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3074 size_t wim_name_len;
3077 /* Write the WIM to a temporary file in the same directory as the
3079 wim_name_len = tstrlen(wim->filename);
3080 tchar tmpfile[wim_name_len + 10];
3081 tmemcpy(tmpfile, wim->filename, wim_name_len);
3082 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3083 tmpfile[wim_name_len + 9] = T('\0');
3085 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3087 WIMLIB_WRITE_FLAG_FSYNC |
3088 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3095 if (filedes_valid(&wim->in_fd)) {
3096 filedes_close(&wim->in_fd);
3097 filedes_invalidate(&wim->in_fd);
3100 /* Rename the new WIM file to the original WIM file. Note: on Windows
3101 * this actually calls win32_rename_replacement(), not _wrename(), so
3102 * that removing the existing destination file can be handled. */
3103 ret = trename(tmpfile, wim->filename);
3105 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3106 tmpfile, wim->filename);
3113 return WIMLIB_ERR_RENAME;
3116 union wimlib_progress_info progress;
3117 progress.rename.from = tmpfile;
3118 progress.rename.to = wim->filename;
3119 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3120 &progress, wim->progctx);
3123 /* Determine if the specified WIM file may be updated by appending in-place
3124 * rather than writing and replacing it with an entirely new file. */
3126 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3128 /* REBUILD flag forces full rebuild. */
3129 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3132 /* Image deletions cause full rebuild by default. */
3133 if (wim->image_deletion_occurred &&
3134 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3137 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3138 * turned into a pipable WIM in-place. */
3139 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3142 /* The default compression type and compression chunk size selected for
3143 * the output WIM must be the same as those currently used for the WIM.
3145 if (wim->compression_type != wim->out_compression_type)
3147 if (wim->chunk_size != wim->out_chunk_size)
3153 /* API function documented in wimlib.h */
3155 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3160 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3161 return WIMLIB_ERR_INVALID_PARAM;
3164 return WIMLIB_ERR_NO_FILENAME;
3166 orig_hdr_flags = wim->hdr.flags;
3167 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3168 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3169 ret = can_modify_wim(wim);
3170 wim->hdr.flags = orig_hdr_flags;
3174 if (can_overwrite_wim_inplace(wim, write_flags)) {
3175 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3176 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3178 WARNING("Falling back to re-building entire WIM");
3180 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);