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"
56 # include "wimlib/win32.h" /* win32_rename_replacement() */
58 #include "wimlib/write.h"
59 #include "wimlib/xml.h"
62 /* wimlib internal flags used when writing resources. */
63 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
64 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
65 #define WRITE_RESOURCE_FLAG_SOLID 0x00000004
66 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
67 #define WRITE_RESOURCE_FLAG_SOLID_SORT 0x00000010
70 write_flags_to_resource_flags(int write_flags)
72 int write_resource_flags = 0;
74 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
75 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
77 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
78 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
80 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
81 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
83 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
84 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
86 if ((write_flags & (WIMLIB_WRITE_FLAG_SOLID |
87 WIMLIB_WRITE_FLAG_NO_SOLID_SORT)) ==
88 WIMLIB_WRITE_FLAG_SOLID)
89 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID_SORT;
91 return write_resource_flags;
94 struct filter_context {
100 * Determine whether the specified blob should be filtered out from the write.
104 * < 0 : The blob should be hard-filtered; that is, not included in the output
106 * 0 : The blob should not be filtered out.
107 * > 0 : The blob should be soft-filtered; that is, it already exists in the
108 * WIM file and may not need to be written again.
111 blob_filtered(const struct blob_descriptor *blob,
112 const struct filter_context *ctx)
120 write_flags = ctx->write_flags;
123 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
124 blob->blob_location == BLOB_IN_WIM &&
125 blob->rdesc->wim == wim)
128 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
129 blob->blob_location == BLOB_IN_WIM &&
130 blob->rdesc->wim != wim)
137 blob_hard_filtered(const struct blob_descriptor *blob,
138 struct filter_context *ctx)
140 return blob_filtered(blob, ctx) < 0;
144 may_soft_filter_blobs(const struct filter_context *ctx)
148 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
152 may_hard_filter_blobs(const struct filter_context *ctx)
156 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
160 may_filter_blobs(const struct filter_context *ctx)
162 return (may_soft_filter_blobs(ctx) || may_hard_filter_blobs(ctx));
165 /* Return true if the specified resource is compressed and the compressed data
166 * can be reused with the specified output parameters. */
168 can_raw_copy(const struct blob_descriptor *blob,
169 int write_resource_flags, int out_ctype, u32 out_chunk_size)
171 const struct wim_resource_descriptor *rdesc;
173 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
176 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
179 if (blob->blob_location != BLOB_IN_WIM)
184 if (rdesc->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
187 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
188 /* Normal compressed resource: Must use same compression type
190 return (rdesc->compression_type == out_ctype &&
191 rdesc->chunk_size == out_chunk_size);
194 if ((rdesc->flags & WIM_RESHDR_FLAG_SOLID) &&
195 (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
197 /* Solid resource: Such resources may contain multiple blobs,
198 * and in general only a subset of them need to be written. As
199 * a heuristic, re-use the raw data if more than two-thirds the
200 * uncompressed size is being written. */
202 /* Note: solid resources contain a header that specifies the
203 * compression type and chunk size; therefore we don't need to
204 * check if they are compatible with @out_ctype and
205 * @out_chunk_size. */
207 struct blob_descriptor *res_blob;
210 list_for_each_entry(res_blob, &rdesc->blob_list, rdesc_node)
211 if (res_blob->will_be_in_output_wim)
212 write_size += res_blob->size;
214 return (write_size > rdesc->uncompressed_size * 2 / 3);
221 reshdr_flags_for_blob(const struct blob_descriptor *blob)
223 u32 reshdr_flags = 0;
224 if (blob->is_metadata)
225 reshdr_flags |= WIM_RESHDR_FLAG_METADATA;
230 blob_set_out_reshdr_for_reuse(struct blob_descriptor *blob)
232 const struct wim_resource_descriptor *rdesc;
234 wimlib_assert(blob->blob_location == BLOB_IN_WIM);
237 if (rdesc->flags & WIM_RESHDR_FLAG_SOLID) {
238 blob->out_reshdr.offset_in_wim = blob->offset_in_res;
239 blob->out_reshdr.uncompressed_size = 0;
240 blob->out_reshdr.size_in_wim = blob->size;
242 blob->out_res_offset_in_wim = rdesc->offset_in_wim;
243 blob->out_res_size_in_wim = rdesc->size_in_wim;
244 blob->out_res_uncompressed_size = rdesc->uncompressed_size;
246 blob->out_reshdr.offset_in_wim = rdesc->offset_in_wim;
247 blob->out_reshdr.uncompressed_size = rdesc->uncompressed_size;
248 blob->out_reshdr.size_in_wim = rdesc->size_in_wim;
250 blob->out_reshdr.flags = rdesc->flags;
254 /* Write the header for a blob in a pipable WIM. */
256 write_pwm_blob_header(const struct blob_descriptor *blob,
257 struct filedes *out_fd, bool compressed)
259 struct pwm_blob_hdr blob_hdr;
263 wimlib_assert(!blob->unhashed);
265 blob_hdr.magic = cpu_to_le64(PWM_BLOB_MAGIC);
266 blob_hdr.uncompressed_size = cpu_to_le64(blob->size);
267 copy_hash(blob_hdr.hash, blob->hash);
268 reshdr_flags = reshdr_flags_for_blob(blob);
270 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
271 blob_hdr.flags = cpu_to_le32(reshdr_flags);
272 ret = full_write(out_fd, &blob_hdr, sizeof(blob_hdr));
274 ERROR_WITH_ERRNO("Write error");
278 struct write_blobs_progress_data {
279 wimlib_progress_func_t progfunc;
281 union wimlib_progress_info progress;
282 uint64_t next_progress;
286 do_write_blobs_progress(struct write_blobs_progress_data *progress_data,
287 u64 complete_size, u32 complete_count, bool discarded)
289 union wimlib_progress_info *progress = &progress_data->progress;
293 progress->write_streams.total_bytes -= complete_size;
294 progress->write_streams.total_streams -= complete_count;
295 if (progress_data->next_progress != ~(uint64_t)0 &&
296 progress_data->next_progress > progress->write_streams.total_bytes)
298 progress_data->next_progress = progress->write_streams.total_bytes;
301 progress->write_streams.completed_bytes += complete_size;
302 progress->write_streams.completed_streams += complete_count;
305 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
307 ret = call_progress(progress_data->progfunc,
308 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
310 progress_data->progctx);
314 if (progress_data->next_progress == progress->write_streams.total_bytes) {
315 progress_data->next_progress = ~(uint64_t)0;
317 /* Handle rate-limiting of messages */
319 /* Send new message as soon as another 1/128 of the
320 * total has been written. (Arbitrary number.) */
321 progress_data->next_progress =
322 progress->write_streams.completed_bytes +
323 progress->write_streams.total_bytes / 128;
325 /* ... Unless that would be more than 5000000 bytes, in
326 * which case send the next after the next 5000000
327 * bytes. (Another arbitrary number.) */
328 if (progress->write_streams.completed_bytes + 5000000 <
329 progress_data->next_progress)
330 progress_data->next_progress =
331 progress->write_streams.completed_bytes + 5000000;
333 /* ... But always send a message as soon as we're
334 * completely done. */
335 if (progress->write_streams.total_bytes <
336 progress_data->next_progress)
337 progress_data->next_progress =
338 progress->write_streams.total_bytes;
344 struct write_blobs_ctx {
345 /* File descriptor to which the blobs are being written. */
346 struct filedes *out_fd;
348 /* Blob table for the WIMStruct on whose behalf the blobs are being
350 struct blob_table *blob_table;
352 /* Compression format to use. */
355 /* Maximum uncompressed chunk size in compressed resources to use. */
358 /* Flags that affect how the blobs will be written. */
359 int write_resource_flags;
361 /* Data used for issuing WRITE_STREAMS progress. */
362 struct write_blobs_progress_data progress_data;
364 struct filter_context *filter_ctx;
366 /* Upper bound on the total number of bytes that need to be compressed.
368 u64 num_bytes_to_compress;
370 /* Pointer to the chunk_compressor implementation being used for
371 * compressing chunks of data, or NULL if chunks are being written
373 struct chunk_compressor *compressor;
375 /* A buffer of size @out_chunk_size that has been loaned out from the
376 * chunk compressor and is currently being filled with the uncompressed
377 * data of the next chunk. */
380 /* Number of bytes in @cur_chunk_buf that are currently filled. */
381 size_t cur_chunk_buf_filled;
383 /* List of blobs that currently have chunks being compressed. */
384 struct list_head blobs_being_compressed;
386 /* List of blobs in the solid resource. Blobs are moved here after
387 * @blobs_being_compressed only when writing a solid resource. */
388 struct list_head blobs_in_solid_resource;
390 /* Current uncompressed offset in the blob being read. */
391 u64 cur_read_blob_offset;
393 /* Uncompressed size of the blob currently being read. */
394 u64 cur_read_blob_size;
396 /* Current uncompressed offset in the blob being written. */
397 u64 cur_write_blob_offset;
399 /* Uncompressed size of resource currently being written. */
400 u64 cur_write_res_size;
402 /* Array that is filled in with compressed chunk sizes as a resource is
406 /* Index of next entry in @chunk_csizes to fill in. */
409 /* Number of entries in @chunk_csizes currently allocated. */
410 size_t num_alloc_chunks;
412 /* Offset in the output file of the start of the chunks of the resource
413 * currently being written. */
414 u64 chunks_start_offset;
417 /* Reserve space for the chunk table and prepare to accumulate the chunk table
420 begin_chunk_table(struct write_blobs_ctx *ctx, u64 res_expected_size)
422 u64 expected_num_chunks;
423 u64 expected_num_chunk_entries;
427 /* Calculate the number of chunks and chunk entries that should be
428 * needed for the resource. These normally will be the final values,
429 * but in SOLID mode some of the blobs we're planning to write into the
430 * resource may be duplicates, and therefore discarded, potentially
431 * decreasing the number of chunk entries needed. */
432 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
433 expected_num_chunk_entries = expected_num_chunks;
434 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
435 expected_num_chunk_entries--;
437 /* Make sure the chunk_csizes array is long enough to store the
438 * compressed size of each chunk. */
439 if (expected_num_chunks > ctx->num_alloc_chunks) {
440 u64 new_length = expected_num_chunks + 50;
442 if ((size_t)new_length != new_length) {
443 ERROR("Resource size too large (%"PRIu64" bytes!",
445 return WIMLIB_ERR_NOMEM;
448 FREE(ctx->chunk_csizes);
449 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
450 if (ctx->chunk_csizes == NULL) {
451 ctx->num_alloc_chunks = 0;
452 return WIMLIB_ERR_NOMEM;
454 ctx->num_alloc_chunks = new_length;
457 ctx->chunk_index = 0;
459 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
460 /* Reserve space for the chunk table in the output file. In the
461 * case of solid resources this reserves the upper bound for the
462 * needed space, not necessarily the exact space which will
463 * prove to be needed. At this point, we just use @chunk_csizes
464 * for a buffer of 0's because the actual compressed chunk sizes
466 reserve_size = expected_num_chunk_entries *
467 get_chunk_entry_size(res_expected_size,
468 0 != (ctx->write_resource_flags &
469 WRITE_RESOURCE_FLAG_SOLID));
470 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
471 reserve_size += sizeof(struct alt_chunk_table_header_disk);
472 memset(ctx->chunk_csizes, 0, reserve_size);
473 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
481 begin_write_resource(struct write_blobs_ctx *ctx, u64 res_expected_size)
485 wimlib_assert(res_expected_size != 0);
487 if (ctx->compressor != NULL) {
488 ret = begin_chunk_table(ctx, res_expected_size);
493 /* Output file descriptor is now positioned at the offset at which to
494 * write the first chunk of the resource. */
495 ctx->chunks_start_offset = ctx->out_fd->offset;
496 ctx->cur_write_blob_offset = 0;
497 ctx->cur_write_res_size = res_expected_size;
502 end_chunk_table(struct write_blobs_ctx *ctx, u64 res_actual_size,
503 u64 *res_start_offset_ret, u64 *res_store_size_ret)
505 size_t actual_num_chunks;
506 size_t actual_num_chunk_entries;
507 size_t chunk_entry_size;
510 actual_num_chunks = ctx->chunk_index;
511 actual_num_chunk_entries = actual_num_chunks;
512 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
513 actual_num_chunk_entries--;
515 chunk_entry_size = get_chunk_entry_size(res_actual_size,
516 0 != (ctx->write_resource_flags &
517 WRITE_RESOURCE_FLAG_SOLID));
519 typedef le64 _may_alias_attribute aliased_le64_t;
520 typedef le32 _may_alias_attribute aliased_le32_t;
522 if (chunk_entry_size == 4) {
523 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
525 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
526 for (size_t i = 0; i < actual_num_chunk_entries; i++)
527 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
529 u32 offset = ctx->chunk_csizes[0];
530 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
531 u32 next_size = ctx->chunk_csizes[i + 1];
532 entries[i] = cpu_to_le32(offset);
537 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
539 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
540 for (size_t i = 0; i < actual_num_chunk_entries; i++)
541 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
543 u64 offset = ctx->chunk_csizes[0];
544 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
545 u64 next_size = ctx->chunk_csizes[i + 1];
546 entries[i] = cpu_to_le64(offset);
552 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
553 u64 res_start_offset;
556 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
557 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
560 res_end_offset = ctx->out_fd->offset;
561 res_start_offset = ctx->chunks_start_offset;
563 res_end_offset = ctx->out_fd->offset;
565 u64 chunk_table_offset;
567 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
569 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
570 struct alt_chunk_table_header_disk hdr;
572 hdr.res_usize = cpu_to_le64(res_actual_size);
573 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
574 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
576 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
577 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
578 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
580 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
581 chunk_table_offset - sizeof(hdr));
584 res_start_offset = chunk_table_offset - sizeof(hdr);
586 res_start_offset = chunk_table_offset;
589 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
590 chunk_table_size, chunk_table_offset);
595 *res_start_offset_ret = res_start_offset;
596 *res_store_size_ret = res_end_offset - res_start_offset;
601 ERROR_WITH_ERRNO("Write error");
605 /* Finish writing a WIM resource by writing or updating the chunk table (if not
606 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
608 end_write_resource(struct write_blobs_ctx *ctx, struct wim_reshdr *out_reshdr)
612 u64 res_uncompressed_size;
613 u64 res_offset_in_wim;
615 wimlib_assert(ctx->cur_write_blob_offset == ctx->cur_write_res_size ||
616 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
617 res_uncompressed_size = ctx->cur_write_res_size;
619 if (ctx->compressor) {
620 ret = end_chunk_table(ctx, res_uncompressed_size,
621 &res_offset_in_wim, &res_size_in_wim);
625 res_offset_in_wim = ctx->chunks_start_offset;
626 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
628 out_reshdr->uncompressed_size = res_uncompressed_size;
629 out_reshdr->size_in_wim = res_size_in_wim;
630 out_reshdr->offset_in_wim = res_offset_in_wim;
631 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
632 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
636 /* Call when no more data from the file at @path is needed. */
638 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
640 union wimlib_progress_info info;
642 info.done_with_file.path_to_file = path;
644 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
649 do_done_with_blob(struct blob_descriptor *blob,
650 wimlib_progress_func_t progfunc, void *progctx)
653 struct wim_inode *inode;
655 if (!blob->may_send_done_with_file)
658 inode = blob->file_inode;
660 wimlib_assert(inode != NULL);
661 wimlib_assert(inode->num_remaining_streams > 0);
662 if (--inode->num_remaining_streams > 0)
666 /* XXX: This logic really should be somewhere else. */
668 /* We want the path to the file, but blob->file_on_disk might actually
669 * refer to a named data stream. Temporarily strip the named data
670 * stream from the path. */
671 wchar_t *p_colon = NULL;
672 wchar_t *p_question_mark = NULL;
673 const wchar_t *p_stream_name;
675 p_stream_name = path_stream_name(blob->file_on_disk);
676 if (unlikely(p_stream_name)) {
677 p_colon = (wchar_t *)(p_stream_name - 1);
678 wimlib_assert(*p_colon == L':');
682 /* We also should use a fake Win32 path instead of a NT path */
683 if (!wcsncmp(blob->file_on_disk, L"\\??\\", 4)) {
684 p_question_mark = &blob->file_on_disk[1];
685 *p_question_mark = L'\\';
689 ret = done_with_file(blob->file_on_disk, progfunc, progctx);
695 *p_question_mark = L'?';
700 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
702 done_with_blob(struct blob_descriptor *blob, struct write_blobs_ctx *ctx)
704 if (likely(!(ctx->write_resource_flags &
705 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
707 return do_done_with_blob(blob, ctx->progress_data.progfunc,
708 ctx->progress_data.progctx);
711 /* Begin processing a blob for writing. */
713 write_blob_begin_read(struct blob_descriptor *blob, void *_ctx)
715 struct write_blobs_ctx *ctx = _ctx;
718 wimlib_assert(blob->size > 0);
720 ctx->cur_read_blob_offset = 0;
721 ctx->cur_read_blob_size = blob->size;
723 /* As an optimization, we allow some blobs to be "unhashed", meaning
724 * their SHA-1 message digests are unknown. This is the case with blobs
725 * that are added by scanning a directory tree with wimlib_add_image(),
726 * for example. Since WIM uses single-instance blobs, we don't know
727 * whether such each such blob really need to written until it is
728 * actually checksummed, unless it has a unique size. In such cases we
729 * read and checksum the blob in this function, thereby advancing ahead
730 * of read_blob_list(), which will still provide the data again to
731 * write_blob_process_chunk(). This is okay because an unhashed blob
732 * cannot be in a WIM resource, which might be costly to decompress. */
733 if (ctx->blob_table != NULL && blob->unhashed && !blob->unique_size) {
735 struct blob_descriptor *new_blob;
737 ret = hash_unhashed_blob(blob, ctx->blob_table, &new_blob);
740 if (new_blob != blob) {
741 /* Duplicate blob detected. */
743 if (new_blob->will_be_in_output_wim ||
744 blob_filtered(new_blob, ctx->filter_ctx))
746 /* The duplicate blob is already being included
747 * in the output WIM, or it would be filtered
748 * out if it had been. Skip writing this blob
749 * (and reading it again) entirely, passing its
750 * output reference count to the duplicate blob
751 * in the former case. */
752 DEBUG("Discarding duplicate blob of "
753 "length %"PRIu64, blob->size);
754 ret = do_write_blobs_progress(&ctx->progress_data,
755 blob->size, 1, true);
756 list_del(&blob->write_blobs_list);
757 list_del(&blob->blob_table_list);
758 if (new_blob->will_be_in_output_wim)
759 new_blob->out_refcnt += blob->out_refcnt;
760 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
761 ctx->cur_write_res_size -= blob->size;
763 ret = done_with_blob(blob, ctx);
764 free_blob_descriptor(blob);
767 return BEGIN_BLOB_STATUS_SKIP_BLOB;
769 /* The duplicate blob can validly be written,
770 * but was not marked as such. Discard the
771 * current blob descriptor and use the
772 * duplicate, but actually freeing the current
773 * blob descriptor must wait until
774 * read_blob_list() has finished reading its
776 DEBUG("Blob duplicate, but not already "
777 "selected for writing.");
778 list_replace(&blob->write_blobs_list,
779 &new_blob->write_blobs_list);
780 list_replace(&blob->blob_table_list,
781 &new_blob->blob_table_list);
782 blob->will_be_in_output_wim = 0;
783 new_blob->out_refcnt = blob->out_refcnt;
784 new_blob->will_be_in_output_wim = 1;
785 new_blob->may_send_done_with_file = 0;
790 list_move_tail(&blob->write_blobs_list, &ctx->blobs_being_compressed);
794 /* Rewrite a blob that was just written compressed (as a non-solid WIM resource)
795 * as uncompressed instead. */
797 write_blob_uncompressed(struct blob_descriptor *blob, struct filedes *out_fd)
800 u64 begin_offset = blob->out_reshdr.offset_in_wim;
801 u64 end_offset = out_fd->offset;
803 if (filedes_seek(out_fd, begin_offset) == -1)
806 ret = extract_full_blob_to_fd(blob, out_fd);
808 /* Error reading the uncompressed data. */
809 if (out_fd->offset == begin_offset &&
810 filedes_seek(out_fd, end_offset) != -1)
812 /* Nothing was actually written yet, and we successfully
813 * seeked to the end of the compressed resource, so
814 * don't issue a hard error; just keep the compressed
815 * resource instead. */
816 WARNING("Recovered compressed resource of "
817 "size %"PRIu64", continuing on.", blob->size);
823 wimlib_assert(out_fd->offset - begin_offset == blob->size);
825 if (out_fd->offset < end_offset &&
826 0 != ftruncate(out_fd->fd, out_fd->offset))
828 ERROR_WITH_ERRNO("Can't truncate output file to "
829 "offset %"PRIu64, out_fd->offset);
830 return WIMLIB_ERR_WRITE;
833 blob->out_reshdr.size_in_wim = blob->size;
834 blob->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
835 WIM_RESHDR_FLAG_SOLID);
839 /* Returns true if the specified blob, which was written as a non-solid
840 * resource, should be truncated from the WIM file and re-written uncompressed.
841 * blob->out_reshdr must be filled in from the initial write of the blob. */
843 should_rewrite_blob_uncompressed(const struct write_blobs_ctx *ctx,
844 const struct blob_descriptor *blob)
846 /* If the compressed data is smaller than the uncompressed data, prefer
847 * the compressed data. */
848 if (blob->out_reshdr.size_in_wim < blob->out_reshdr.uncompressed_size)
851 /* If we're not actually writing compressed data, then there's no need
853 if (!ctx->compressor)
856 /* If writing a pipable WIM, everything we write to the output is final
857 * (it might actually be a pipe!). */
858 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
861 /* If the blob that would need to be re-read is located in a solid
862 * resource in another WIM file, then re-reading it would be costly. So
865 * Exception: if the compressed size happens to be *exactly* the same as
866 * the uncompressed size, then the blob *must* be written uncompressed
867 * in order to remain compatible with the Windows Overlay Filesystem
868 * Filter Driver (WOF).
870 * TODO: we are currently assuming that the optimization for
871 * single-chunk resources in maybe_rewrite_blob_uncompressed() prevents
872 * this case from being triggered too often. To fully prevent excessive
873 * decompressions in degenerate cases, we really should obtain the
874 * uncompressed data by decompressing the compressed data we wrote to
877 if (blob->blob_location == BLOB_IN_WIM &&
878 blob->size != blob->rdesc->uncompressed_size &&
879 blob->size != blob->out_reshdr.size_in_wim)
886 maybe_rewrite_blob_uncompressed(struct write_blobs_ctx *ctx,
887 struct blob_descriptor *blob)
889 if (!should_rewrite_blob_uncompressed(ctx, blob))
892 /* Regular (non-solid) WIM resources with exactly one chunk and
893 * compressed size equal to uncompressed size are exactly the same as
894 * the corresponding compressed data --- since there must be 0 entries
895 * in the chunk table and the only chunk must be stored uncompressed.
896 * In this case, there's no need to rewrite anything. */
897 if (ctx->chunk_index == 1 &&
898 blob->out_reshdr.size_in_wim == blob->out_reshdr.uncompressed_size)
900 blob->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
904 return write_blob_uncompressed(blob, ctx->out_fd);
907 /* Write the next chunk of (typically compressed) data to the output WIM,
908 * handling the writing of the chunk table. */
910 write_chunk(struct write_blobs_ctx *ctx, const void *cchunk,
911 size_t csize, size_t usize)
914 struct blob_descriptor *blob;
915 u32 completed_blob_count;
918 blob = list_entry(ctx->blobs_being_compressed.next,
919 struct blob_descriptor, write_blobs_list);
921 if (ctx->cur_write_blob_offset == 0 &&
922 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
924 /* Starting to write a new blob in non-solid mode. */
926 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
927 DEBUG("Writing pipable WIM blob header "
928 "(offset=%"PRIu64")", ctx->out_fd->offset);
929 ret = write_pwm_blob_header(blob, ctx->out_fd,
930 ctx->compressor != NULL);
935 ret = begin_write_resource(ctx, blob->size);
940 if (ctx->compressor != NULL) {
941 /* Record the compresed chunk size. */
942 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
943 ctx->chunk_csizes[ctx->chunk_index++] = csize;
945 /* If writing a pipable WIM, before the chunk data write a chunk
946 * header that provides the compressed chunk size. */
947 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
948 struct pwm_chunk_hdr chunk_hdr = {
949 .compressed_size = cpu_to_le32(csize),
951 ret = full_write(ctx->out_fd, &chunk_hdr,
958 /* Write the chunk data. */
959 ret = full_write(ctx->out_fd, cchunk, csize);
963 ctx->cur_write_blob_offset += usize;
965 completed_size = usize;
966 completed_blob_count = 0;
967 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
968 /* Wrote chunk in solid mode. It may have finished multiple
970 struct blob_descriptor *next_blob;
972 while (blob && ctx->cur_write_blob_offset >= blob->size) {
974 ctx->cur_write_blob_offset -= blob->size;
976 if (ctx->cur_write_blob_offset)
977 next_blob = list_entry(blob->write_blobs_list.next,
978 struct blob_descriptor,
983 ret = done_with_blob(blob, ctx);
986 list_move_tail(&blob->write_blobs_list, &ctx->blobs_in_solid_resource);
987 completed_blob_count++;
992 /* Wrote chunk in non-solid mode. It may have finished a
994 if (ctx->cur_write_blob_offset == blob->size) {
996 wimlib_assert(ctx->cur_write_blob_offset ==
997 ctx->cur_write_res_size);
999 ret = end_write_resource(ctx, &blob->out_reshdr);
1003 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
1004 if (ctx->compressor != NULL)
1005 blob->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
1007 ret = maybe_rewrite_blob_uncompressed(ctx, blob);
1011 wimlib_assert(blob->out_reshdr.uncompressed_size == blob->size);
1013 ctx->cur_write_blob_offset = 0;
1015 ret = done_with_blob(blob, ctx);
1018 list_del(&blob->write_blobs_list);
1019 completed_blob_count++;
1023 return do_write_blobs_progress(&ctx->progress_data, completed_size,
1024 completed_blob_count, false);
1027 ERROR_WITH_ERRNO("Write error");
1032 prepare_chunk_buffer(struct write_blobs_ctx *ctx)
1034 /* While we are unable to get a new chunk buffer due to too many chunks
1035 * already outstanding, retrieve and write the next compressed chunk. */
1036 while (!(ctx->cur_chunk_buf =
1037 ctx->compressor->get_chunk_buffer(ctx->compressor)))
1045 bret = ctx->compressor->get_compression_result(ctx->compressor,
1049 wimlib_assert(bret);
1051 ret = write_chunk(ctx, cchunk, csize, usize);
1058 /* Process the next chunk of data to be written to a WIM resource. */
1060 write_blob_process_chunk(const void *chunk, size_t size, void *_ctx)
1062 struct write_blobs_ctx *ctx = _ctx;
1064 const u8 *chunkptr, *chunkend;
1066 wimlib_assert(size != 0);
1068 if (ctx->compressor == NULL) {
1069 /* Write chunk uncompressed. */
1070 ret = write_chunk(ctx, chunk, size, size);
1073 ctx->cur_read_blob_offset += size;
1077 /* Submit the chunk for compression, but take into account that the
1078 * @size the chunk was provided in may not correspond to the
1079 * @out_chunk_size being used for compression. */
1081 chunkend = chunkptr + size;
1083 size_t needed_chunk_size;
1084 size_t bytes_consumed;
1086 if (!ctx->cur_chunk_buf) {
1087 ret = prepare_chunk_buffer(ctx);
1092 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1093 needed_chunk_size = ctx->out_chunk_size;
1095 needed_chunk_size = min(ctx->out_chunk_size,
1096 ctx->cur_chunk_buf_filled +
1097 (ctx->cur_read_blob_size -
1098 ctx->cur_read_blob_offset));
1101 bytes_consumed = min(chunkend - chunkptr,
1102 needed_chunk_size - ctx->cur_chunk_buf_filled);
1104 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1105 chunkptr, bytes_consumed);
1107 chunkptr += bytes_consumed;
1108 ctx->cur_read_blob_offset += bytes_consumed;
1109 ctx->cur_chunk_buf_filled += bytes_consumed;
1111 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1112 ctx->compressor->signal_chunk_filled(ctx->compressor,
1113 ctx->cur_chunk_buf_filled);
1114 ctx->cur_chunk_buf = NULL;
1115 ctx->cur_chunk_buf_filled = 0;
1117 } while (chunkptr != chunkend);
1121 /* Finish processing a blob for writing. It may not have been completely
1122 * written yet, as the chunk_compressor implementation may still have chunks
1123 * buffered or being compressed. */
1125 write_blob_end_read(struct blob_descriptor *blob, int status, void *_ctx)
1127 struct write_blobs_ctx *ctx = _ctx;
1129 wimlib_assert(ctx->cur_read_blob_offset == ctx->cur_read_blob_size || status);
1131 if (!blob->will_be_in_output_wim) {
1132 /* The blob was a duplicate. Now that its data has finished
1133 * being read, it is being discarded in favor of the duplicate
1134 * entry. It therefore is no longer needed, and we can fire the
1135 * DONE_WITH_FILE callback because the file will not be read
1138 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1139 * blobs, since it needs to be possible to re-read the file if
1140 * it does not compress to less than its original size. */
1142 status = done_with_blob(blob, ctx);
1143 free_blob_descriptor(blob);
1144 } else if (!status && blob->unhashed && ctx->blob_table != NULL) {
1145 /* The blob was not a duplicate and was previously unhashed.
1146 * Since we passed COMPUTE_MISSING_BLOB_HASHES to
1147 * read_blob_list(), blob->hash is now computed and valid. So
1148 * turn this blob into a "hashed" blob. */
1149 list_del(&blob->unhashed_list);
1150 blob_table_insert(ctx->blob_table, blob);
1156 /* Compute statistics about a list of blobs that will be written.
1158 * Assumes the blobs are sorted such that all blobs located in each distinct WIM
1159 * (specified by WIMStruct) are together. */
1161 compute_blob_list_stats(struct list_head *blob_list,
1162 struct write_blobs_ctx *ctx)
1164 struct blob_descriptor *blob;
1165 u64 total_bytes = 0;
1167 u64 total_parts = 0;
1168 WIMStruct *prev_wim_part = NULL;
1170 list_for_each_entry(blob, blob_list, write_blobs_list) {
1172 total_bytes += blob->size;
1173 if (blob->blob_location == BLOB_IN_WIM) {
1174 if (prev_wim_part != blob->rdesc->wim) {
1175 prev_wim_part = blob->rdesc->wim;
1180 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1181 ctx->progress_data.progress.write_streams.total_streams = num_blobs;
1182 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1183 ctx->progress_data.progress.write_streams.completed_streams = 0;
1184 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1185 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1186 ctx->progress_data.progress.write_streams.completed_parts = 0;
1187 ctx->progress_data.next_progress = 0;
1190 /* Find blobs in @blob_list that can be copied to the output WIM in raw form
1191 * rather than compressed. Delete these blobs from @blob_list and move them to
1192 * @raw_copy_blobs. Return the total uncompressed size of the blobs that need
1193 * to be compressed. */
1195 find_raw_copy_blobs(struct list_head *blob_list,
1196 int write_resource_flags,
1199 struct list_head *raw_copy_blobs)
1201 struct blob_descriptor *blob, *tmp;
1202 u64 num_bytes_to_compress = 0;
1204 INIT_LIST_HEAD(raw_copy_blobs);
1206 /* Initialize temporary raw_copy_ok flag. */
1207 list_for_each_entry(blob, blob_list, write_blobs_list)
1208 if (blob->blob_location == BLOB_IN_WIM)
1209 blob->rdesc->raw_copy_ok = 0;
1211 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1212 if (blob->blob_location == BLOB_IN_WIM &&
1213 blob->rdesc->raw_copy_ok)
1215 list_move_tail(&blob->write_blobs_list,
1217 } else if (can_raw_copy(blob, write_resource_flags,
1218 out_ctype, out_chunk_size))
1220 blob->rdesc->raw_copy_ok = 1;
1221 list_move_tail(&blob->write_blobs_list,
1224 num_bytes_to_compress += blob->size;
1228 return num_bytes_to_compress;
1231 /* Copy a raw compressed resource located in another WIM file to the WIM file
1234 write_raw_copy_resource(struct wim_resource_descriptor *in_rdesc,
1235 struct filedes *out_fd)
1237 u64 cur_read_offset;
1238 u64 end_read_offset;
1239 u8 buf[BUFFER_SIZE];
1240 size_t bytes_to_read;
1242 struct filedes *in_fd;
1243 struct blob_descriptor *blob;
1244 u64 out_offset_in_wim;
1246 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1247 "uncompressed_size=%"PRIu64")",
1248 in_rdesc->size_in_wim, in_rdesc->uncompressed_size);
1250 /* Copy the raw data. */
1251 cur_read_offset = in_rdesc->offset_in_wim;
1252 end_read_offset = cur_read_offset + in_rdesc->size_in_wim;
1254 out_offset_in_wim = out_fd->offset;
1256 if (in_rdesc->is_pipable) {
1257 if (cur_read_offset < sizeof(struct pwm_blob_hdr))
1258 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1259 cur_read_offset -= sizeof(struct pwm_blob_hdr);
1260 out_offset_in_wim += sizeof(struct pwm_blob_hdr);
1262 in_fd = &in_rdesc->wim->in_fd;
1263 wimlib_assert(cur_read_offset != end_read_offset);
1266 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1268 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1272 ret = full_write(out_fd, buf, bytes_to_read);
1276 cur_read_offset += bytes_to_read;
1278 } while (cur_read_offset != end_read_offset);
1280 list_for_each_entry(blob, &in_rdesc->blob_list, rdesc_node) {
1281 if (blob->will_be_in_output_wim) {
1282 blob_set_out_reshdr_for_reuse(blob);
1283 if (in_rdesc->flags & WIM_RESHDR_FLAG_SOLID)
1284 blob->out_res_offset_in_wim = out_offset_in_wim;
1286 blob->out_reshdr.offset_in_wim = out_offset_in_wim;
1293 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1294 * WIM file being written. */
1296 write_raw_copy_resources(struct list_head *raw_copy_blobs,
1297 struct filedes *out_fd,
1298 struct write_blobs_progress_data *progress_data)
1300 struct blob_descriptor *blob;
1303 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list)
1304 blob->rdesc->raw_copy_ok = 1;
1306 list_for_each_entry(blob, raw_copy_blobs, write_blobs_list) {
1307 if (blob->rdesc->raw_copy_ok) {
1308 /* Write each solid resource only one time. */
1309 ret = write_raw_copy_resource(blob->rdesc, out_fd);
1312 blob->rdesc->raw_copy_ok = 0;
1314 ret = do_write_blobs_progress(progress_data, blob->size,
1322 /* Wait for and write all chunks pending in the compressor. */
1324 finish_remaining_chunks(struct write_blobs_ctx *ctx)
1331 if (ctx->compressor == NULL)
1334 if (ctx->cur_chunk_buf_filled != 0) {
1335 ctx->compressor->signal_chunk_filled(ctx->compressor,
1336 ctx->cur_chunk_buf_filled);
1339 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1342 ret = write_chunk(ctx, cdata, csize, usize);
1350 remove_empty_blobs(struct list_head *blob_list)
1352 struct blob_descriptor *blob, *tmp;
1354 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
1355 wimlib_assert(blob->will_be_in_output_wim);
1356 if (blob->size == 0) {
1357 list_del(&blob->write_blobs_list);
1358 blob->out_reshdr.offset_in_wim = 0;
1359 blob->out_reshdr.size_in_wim = 0;
1360 blob->out_reshdr.uncompressed_size = 0;
1361 blob->out_reshdr.flags = reshdr_flags_for_blob(blob);
1367 blob_is_in_file(const struct blob_descriptor *blob)
1369 return blob->blob_location == BLOB_IN_FILE_ON_DISK
1371 || blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK
1372 || blob->blob_location == BLOB_WIN32_ENCRYPTED
1378 init_done_with_file_info(struct list_head *blob_list)
1380 struct blob_descriptor *blob;
1382 list_for_each_entry(blob, blob_list, write_blobs_list) {
1383 if (blob_is_in_file(blob)) {
1384 blob->file_inode->num_remaining_streams = 0;
1385 blob->may_send_done_with_file = 1;
1387 blob->may_send_done_with_file = 0;
1391 list_for_each_entry(blob, blob_list, write_blobs_list)
1392 if (blob->may_send_done_with_file)
1393 blob->file_inode->num_remaining_streams++;
1397 * Write a list of blobs to the output WIM file.
1400 * The list of blobs to write, specified by a list of 'struct blob_descriptor' linked
1401 * by the 'write_blobs_list' member.
1404 * The file descriptor, opened for writing, to which to write the blobs.
1406 * @write_resource_flags
1407 * Flags to modify how the blobs are written:
1409 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1410 * Force compression of all resources, even if they could otherwise
1411 * be re-used by copying the raw data, due to being located in a WIM
1412 * file with compatible compression parameters.
1414 * WRITE_RESOURCE_FLAG_PIPABLE:
1415 * Write the resources in the wimlib-specific pipable format, and
1416 * furthermore do so in such a way that no seeking backwards in
1417 * @out_fd will be performed (so it may be a pipe).
1419 * WRITE_RESOURCE_FLAG_SOLID:
1420 * Combine all the blobs into a single resource rather than writing
1421 * them in separate resources. This flag is only valid if the WIM
1422 * version number has been, or will be, set to WIM_VERSION_SOLID.
1423 * This flag may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1426 * Compression format to use in the output resources, specified as one of
1427 * the WIMLIB_COMPRESSION_TYPE_* constants. WIMLIB_COMPRESSION_TYPE_NONE
1431 * Compression chunk size to use in the output resources. It must be a
1432 * valid chunk size for the specified compression format @out_ctype, unless
1433 * @out_ctype is WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter
1437 * Number of threads to use to compress data. If 0, a default number of
1438 * threads will be chosen. The number of threads still may be decreased
1439 * from the specified value if insufficient memory is detected.
1442 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1443 * must be pointer to the blob table for the WIMStruct on whose behalf the
1444 * blobs are being written. Otherwise, this parameter can be NULL.
1447 * If on-the-fly deduplication of unhashed blobs is desired, this parameter
1448 * can be a pointer to a context for blob filtering used to detect whether
1449 * the duplicate blob has been hard-filtered or not. If no blobs are
1450 * hard-filtered or no blobs are unhashed, this parameter can be NULL.
1452 * This function will write the blobs in @blob_list to resources in
1453 * consecutive positions in the output WIM file, or to a single solid resource
1454 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1455 * cases, the @out_reshdr of the `struct blob_descriptor' for each blob written will be
1456 * updated to specify its location, size, and flags in the output WIM. In the
1457 * solid resource case, WIM_RESHDR_FLAG_SOLID will be set in the @flags field of
1458 * each @out_reshdr, and furthermore @out_res_offset_in_wim and
1459 * @out_res_size_in_wim of each @out_reshdr will be set to the offset and size,
1460 * respectively, in the output WIM of the solid resource containing the
1461 * corresponding blob.
1463 * Each of the blobs to write may be in any location supported by the
1464 * resource-handling code (specifically, read_blob_list()), such as the contents
1465 * of external file that has been logically added to the output WIM, or a blob
1466 * in another WIM file that has been imported, or even a blob in the "same" WIM
1467 * file of which a modified copy is being written. In the case that a blob is
1468 * already in a WIM file and uses compatible compression parameters, by default
1469 * this function will re-use the raw data instead of decompressing it, then
1470 * recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1471 * specified in @write_resource_flags, this is not done.
1473 * As a further requirement, this function requires that the
1474 * @will_be_in_output_wim member be set to 1 on all blobs in @blob_list as well
1475 * as any other blobs not in @blob_list that will be in the output WIM file, but
1476 * set to 0 on any other blobs in the output WIM's blob table or sharing a solid
1477 * resource with a blob in @blob_list. Still furthermore, if on-the-fly
1478 * deduplication of blobs is possible, then all blobs in @blob_list must also be
1479 * linked by @blob_table_list along with any other blobs that have
1480 * @will_be_in_output_wim set.
1482 * This function handles on-the-fly deduplication of blobs for which SHA-1
1483 * message digests have not yet been calculated. Such blobs may or may not need
1484 * to be written. If @blob_table is non-NULL, then each blob in @blob_list that
1485 * has @unhashed set but not @unique_size set is checksummed immediately before
1486 * it would otherwise be read for writing in order to determine if it is
1487 * identical to another blob already being written or one that would be filtered
1488 * out of the output WIM using blob_filtered() with the context @filter_ctx.
1489 * Each such duplicate blob will be removed from @blob_list, its reference count
1490 * transfered to the pre-existing duplicate blob, its memory freed, and will not
1491 * be written. Alternatively, if a blob in @blob_list is a duplicate with any
1492 * blob in @blob_table that has not been marked for writing or would not be
1493 * hard-filtered, it is freed and the pre-existing duplicate is written instead,
1494 * taking ownership of the reference count and slot in the @blob_table_list.
1496 * Returns 0 if every blob was either written successfully or did not need to be
1497 * written; otherwise returns a non-zero error code.
1500 write_blob_list(struct list_head *blob_list,
1501 struct filedes *out_fd,
1502 int write_resource_flags,
1505 unsigned num_threads,
1506 struct blob_table *blob_table,
1507 struct filter_context *filter_ctx,
1508 wimlib_progress_func_t progfunc,
1512 struct write_blobs_ctx ctx;
1513 struct list_head raw_copy_blobs;
1515 wimlib_assert((write_resource_flags &
1516 (WRITE_RESOURCE_FLAG_SOLID |
1517 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1518 (WRITE_RESOURCE_FLAG_SOLID |
1519 WRITE_RESOURCE_FLAG_PIPABLE));
1521 remove_empty_blobs(blob_list);
1523 if (list_empty(blob_list)) {
1524 DEBUG("No blobs to write.");
1528 /* If needed, set auxiliary information so that we can detect when the
1529 * library has finished using each external file. */
1530 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1531 init_done_with_file_info(blob_list);
1533 memset(&ctx, 0, sizeof(ctx));
1535 ctx.out_fd = out_fd;
1536 ctx.blob_table = blob_table;
1537 ctx.out_ctype = out_ctype;
1538 ctx.out_chunk_size = out_chunk_size;
1539 ctx.write_resource_flags = write_resource_flags;
1540 ctx.filter_ctx = filter_ctx;
1543 * We normally sort the blobs to write by a "sequential" order that is
1544 * optimized for reading. But when using solid compression, we instead
1545 * sort the blobs by file extension and file name (when applicable; and
1546 * we don't do this for blobs from solid resources) so that similar
1547 * files are grouped together, which improves the compression ratio.
1548 * This is somewhat of a hack since a blob does not necessarily
1549 * correspond one-to-one with a filename, nor is there any guarantee
1550 * that two files with similar names or extensions are actually similar
1551 * in content. A potential TODO is to sort the blobs based on some
1552 * measure of similarity of their actual contents.
1555 ret = sort_blob_list_by_sequential_order(blob_list,
1556 offsetof(struct blob_descriptor,
1561 compute_blob_list_stats(blob_list, &ctx);
1563 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1564 ret = sort_blob_list_for_solid_compression(blob_list);
1566 WARNING("Failed to sort blobs for solid compression. Continuing anyways.");
1569 ctx.progress_data.progfunc = progfunc;
1570 ctx.progress_data.progctx = progctx;
1572 ctx.num_bytes_to_compress = find_raw_copy_blobs(blob_list,
1573 write_resource_flags,
1578 DEBUG("Writing blob list "
1579 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1580 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1581 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1582 out_fd->offset, write_resource_flags,
1583 out_ctype, out_chunk_size, num_threads,
1584 ctx.progress_data.progress.write_streams.total_bytes,
1585 ctx.num_bytes_to_compress);
1587 if (ctx.num_bytes_to_compress == 0) {
1588 DEBUG("No compression needed; skipping to raw copy!");
1589 goto out_write_raw_copy_resources;
1592 /* Unless uncompressed output was required, allocate a chunk_compressor
1593 * to do compression. There are serial and parallel implementations of
1594 * the chunk_compressor interface. We default to parallel using the
1595 * specified number of threads, unless the upper bound on the number
1596 * bytes needing to be compressed is less than a heuristic value. */
1597 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1599 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1600 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1601 ret = new_parallel_chunk_compressor(out_ctype,
1606 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1607 " Falling back to single-threaded compression.",
1608 wimlib_get_error_string(ret));
1613 if (ctx.compressor == NULL) {
1614 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1617 goto out_destroy_context;
1622 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1624 ctx.progress_data.progress.write_streams.num_threads = 1;
1626 DEBUG("Actually using %u threads",
1627 ctx.progress_data.progress.write_streams.num_threads);
1629 INIT_LIST_HEAD(&ctx.blobs_being_compressed);
1630 INIT_LIST_HEAD(&ctx.blobs_in_solid_resource);
1632 ret = call_progress(ctx.progress_data.progfunc,
1633 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1634 &ctx.progress_data.progress,
1635 ctx.progress_data.progctx);
1637 goto out_destroy_context;
1639 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1640 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1642 goto out_destroy_context;
1645 /* Read the list of blobs needing to be compressed, using the specified
1646 * callbacks to execute processing of the data. */
1648 struct read_blob_list_callbacks cbs = {
1649 .begin_blob = write_blob_begin_read,
1650 .begin_blob_ctx = &ctx,
1651 .consume_chunk = write_blob_process_chunk,
1652 .consume_chunk_ctx = &ctx,
1653 .end_blob = write_blob_end_read,
1654 .end_blob_ctx = &ctx,
1657 ret = read_blob_list(blob_list,
1658 offsetof(struct blob_descriptor, write_blobs_list),
1660 BLOB_LIST_ALREADY_SORTED |
1661 VERIFY_BLOB_HASHES |
1662 COMPUTE_MISSING_BLOB_HASHES);
1665 goto out_destroy_context;
1667 ret = finish_remaining_chunks(&ctx);
1669 goto out_destroy_context;
1671 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1672 struct wim_reshdr reshdr;
1673 struct blob_descriptor *blob;
1676 ret = end_write_resource(&ctx, &reshdr);
1678 goto out_destroy_context;
1680 DEBUG("Ending solid resource: %lu %lu %lu.",
1681 reshdr.offset_in_wim,
1683 reshdr.uncompressed_size);
1686 list_for_each_entry(blob, &ctx.blobs_in_solid_resource, write_blobs_list) {
1687 blob->out_reshdr.size_in_wim = blob->size;
1688 blob->out_reshdr.flags = reshdr_flags_for_blob(blob) |
1689 WIM_RESHDR_FLAG_SOLID;
1690 blob->out_reshdr.uncompressed_size = 0;
1691 blob->out_reshdr.offset_in_wim = offset_in_res;
1692 blob->out_res_offset_in_wim = reshdr.offset_in_wim;
1693 blob->out_res_size_in_wim = reshdr.size_in_wim;
1694 blob->out_res_uncompressed_size = reshdr.uncompressed_size;
1695 offset_in_res += blob->size;
1697 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1700 out_write_raw_copy_resources:
1701 /* Copy any compressed resources for which the raw data can be reused
1702 * without decompression. */
1703 ret = write_raw_copy_resources(&raw_copy_blobs, ctx.out_fd,
1704 &ctx.progress_data);
1706 out_destroy_context:
1707 FREE(ctx.chunk_csizes);
1709 ctx.compressor->destroy(ctx.compressor);
1710 DEBUG("Done (ret=%d)", ret);
1716 write_file_data_blobs(WIMStruct *wim,
1717 struct list_head *blob_list,
1719 unsigned num_threads,
1720 struct filter_context *filter_ctx)
1724 int write_resource_flags;
1726 write_resource_flags = write_flags_to_resource_flags(write_flags);
1728 /* wimlib v1.7.0: create a solid WIM file by default if the WIM version
1729 * has been set to WIM_VERSION_SOLID and at least one blob in the WIM's
1730 * blob table is located in a solid resource (may be the same WIM, or a
1731 * different one in the case of export). */
1732 if (wim->hdr.wim_version == WIM_VERSION_SOLID &&
1733 wim_has_solid_resources(wim))
1735 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
1738 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1739 out_chunk_size = wim->out_solid_chunk_size;
1740 out_ctype = wim->out_solid_compression_type;
1742 out_chunk_size = wim->out_chunk_size;
1743 out_ctype = wim->out_compression_type;
1746 return write_blob_list(blob_list,
1748 write_resource_flags,
1758 /* Write the contents of the specified blob as a WIM resource. */
1760 write_wim_resource(struct blob_descriptor *blob,
1761 struct filedes *out_fd,
1764 int write_resource_flags)
1766 LIST_HEAD(blob_list);
1767 list_add(&blob->write_blobs_list, &blob_list);
1768 blob->will_be_in_output_wim = 1;
1769 return write_blob_list(&blob_list,
1771 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1781 /* Write the contents of the specified buffer as a WIM resource. */
1783 write_wim_resource_from_buffer(const void *buf,
1786 struct filedes *out_fd,
1789 struct wim_reshdr *out_reshdr,
1791 int write_resource_flags)
1794 struct blob_descriptor blob;
1796 blob_set_is_located_in_attached_buffer(&blob, (void *)buf, buf_size);
1797 sha1_buffer(buf, buf_size, blob.hash);
1799 blob.is_metadata = is_metadata;
1801 ret = write_wim_resource(&blob, out_fd, out_ctype, out_chunk_size,
1802 write_resource_flags);
1806 copy_reshdr(out_reshdr, &blob.out_reshdr);
1809 copy_hash(hash_ret, blob.hash);
1813 struct blob_size_table {
1814 struct hlist_head *array;
1820 init_blob_size_table(struct blob_size_table *tab, size_t capacity)
1822 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1823 if (tab->array == NULL)
1824 return WIMLIB_ERR_NOMEM;
1825 tab->num_entries = 0;
1826 tab->capacity = capacity;
1831 destroy_blob_size_table(struct blob_size_table *tab)
1837 blob_size_table_insert(struct blob_descriptor *blob, void *_tab)
1839 struct blob_size_table *tab = _tab;
1841 struct blob_descriptor *same_size_blob;
1843 pos = hash_u64(blob->size) % tab->capacity;
1844 blob->unique_size = 1;
1845 hlist_for_each_entry(same_size_blob, &tab->array[pos], hash_list_2) {
1846 if (same_size_blob->size == blob->size) {
1847 blob->unique_size = 0;
1848 same_size_blob->unique_size = 0;
1853 hlist_add_head(&blob->hash_list_2, &tab->array[pos]);
1858 struct find_blobs_ctx {
1861 struct list_head blob_list;
1862 struct blob_size_table blob_size_tab;
1866 reference_blob_for_write(struct blob_descriptor *blob,
1867 struct list_head *blob_list, u32 nref)
1869 if (!blob->will_be_in_output_wim) {
1870 blob->out_refcnt = 0;
1871 list_add_tail(&blob->write_blobs_list, blob_list);
1872 blob->will_be_in_output_wim = 1;
1874 blob->out_refcnt += nref;
1878 fully_reference_blob_for_write(struct blob_descriptor *blob, void *_blob_list)
1880 struct list_head *blob_list = _blob_list;
1881 blob->will_be_in_output_wim = 0;
1882 reference_blob_for_write(blob, blob_list, blob->refcnt);
1887 inode_find_blobs_to_reference(const struct wim_inode *inode,
1888 const struct blob_table *table,
1889 struct list_head *blob_list)
1891 wimlib_assert(inode->i_nlink > 0);
1893 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1894 struct blob_descriptor *blob;
1897 blob = stream_blob(&inode->i_streams[i], table);
1899 reference_blob_for_write(blob, blob_list, inode->i_nlink);
1901 hash = stream_hash(&inode->i_streams[i]);
1902 if (!is_zero_hash(hash))
1903 return blob_not_found_error(inode, hash);
1910 do_blob_set_not_in_output_wim(struct blob_descriptor *blob, void *_ignore)
1912 blob->will_be_in_output_wim = 0;
1917 image_find_blobs_to_reference(WIMStruct *wim)
1919 struct wim_image_metadata *imd;
1920 struct wim_inode *inode;
1921 struct blob_descriptor *blob;
1922 struct list_head *blob_list;
1925 imd = wim_get_current_image_metadata(wim);
1927 image_for_each_unhashed_blob(blob, imd)
1928 blob->will_be_in_output_wim = 0;
1930 blob_list = wim->private;
1931 image_for_each_inode(inode, imd) {
1932 ret = inode_find_blobs_to_reference(inode,
1942 prepare_unfiltered_list_of_blobs_in_output_wim(WIMStruct *wim,
1945 struct list_head *blob_list_ret)
1949 INIT_LIST_HEAD(blob_list_ret);
1951 if (blobs_ok && (image == WIMLIB_ALL_IMAGES ||
1952 (image == 1 && wim->hdr.image_count == 1)))
1954 /* Fast case: Assume that all blobs are being written and that
1955 * the reference counts are correct. */
1956 struct blob_descriptor *blob;
1957 struct wim_image_metadata *imd;
1960 for_blob_in_table(wim->blob_table,
1961 fully_reference_blob_for_write,
1964 for (i = 0; i < wim->hdr.image_count; i++) {
1965 imd = wim->image_metadata[i];
1966 image_for_each_unhashed_blob(blob, imd)
1967 fully_reference_blob_for_write(blob, blob_list_ret);
1970 /* Slow case: Walk through the images being written and
1971 * determine the blobs referenced. */
1972 for_blob_in_table(wim->blob_table,
1973 do_blob_set_not_in_output_wim, NULL);
1974 wim->private = blob_list_ret;
1975 ret = for_image(wim, image, image_find_blobs_to_reference);
1983 struct insert_other_if_hard_filtered_ctx {
1984 struct blob_size_table *tab;
1985 struct filter_context *filter_ctx;
1989 insert_other_if_hard_filtered(struct blob_descriptor *blob, void *_ctx)
1991 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1993 if (!blob->will_be_in_output_wim &&
1994 blob_hard_filtered(blob, ctx->filter_ctx))
1995 blob_size_table_insert(blob, ctx->tab);
2000 determine_blob_size_uniquity(struct list_head *blob_list,
2001 struct blob_table *lt,
2002 struct filter_context *filter_ctx)
2005 struct blob_size_table tab;
2006 struct blob_descriptor *blob;
2008 ret = init_blob_size_table(&tab, 9001);
2012 if (may_hard_filter_blobs(filter_ctx)) {
2013 struct insert_other_if_hard_filtered_ctx ctx = {
2015 .filter_ctx = filter_ctx,
2017 for_blob_in_table(lt, insert_other_if_hard_filtered, &ctx);
2020 list_for_each_entry(blob, blob_list, write_blobs_list)
2021 blob_size_table_insert(blob, &tab);
2023 destroy_blob_size_table(&tab);
2028 filter_blob_list_for_write(struct list_head *blob_list,
2029 struct filter_context *filter_ctx)
2031 struct blob_descriptor *blob, *tmp;
2033 list_for_each_entry_safe(blob, tmp, blob_list, write_blobs_list) {
2034 int status = blob_filtered(blob, filter_ctx);
2041 /* Soft filtered. */
2043 /* Hard filtered. */
2044 blob->will_be_in_output_wim = 0;
2045 list_del(&blob->blob_table_list);
2047 list_del(&blob->write_blobs_list);
2053 * prepare_blob_list_for_write() -
2055 * Prepare the list of blobs to write for writing a WIM containing the specified
2056 * image(s) with the specified write flags.
2059 * The WIMStruct on whose behalf the write is occurring.
2062 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2065 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2067 * STREAMS_OK: For writes of all images, assume that all blobs in the blob
2068 * table of @wim and the per-image lists of unhashed blobs should be taken
2069 * as-is, and image metadata should not be searched for references. This
2070 * does not exclude filtering with OVERWRITE and SKIP_EXTERNAL_WIMS, below.
2072 * OVERWRITE: Blobs already present in @wim shall not be returned in
2075 * SKIP_EXTERNAL_WIMS: Blobs already present in a WIM file, but not @wim,
2076 * shall be returned in neither @blob_list_ret nor @blob_table_list_ret.
2079 * List of blobs, linked by write_blobs_list, that need to be written will
2082 * Note that this function assumes that unhashed blobs will be written; it
2083 * does not take into account that they may become duplicates when actually
2086 * @blob_table_list_ret
2087 * List of blobs, linked by blob_table_list, that need to be included in
2088 * the WIM's blob table will be returned here. This will be a superset of
2089 * the blobs in @blob_list_ret.
2091 * This list will be a proper superset of @blob_list_ret if and only if
2092 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2093 * the blobs that would otherwise need to be written were already located
2096 * All blobs in this list will have @out_refcnt set to the number of
2097 * references to the blob in the output WIM. If
2098 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2099 * may be as low as 0.
2102 * A context for queries of blob filter status with blob_filtered() is
2103 * returned in this location.
2105 * In addition, @will_be_in_output_wim will be set to 1 in all blobs inserted
2106 * into @blob_table_list_ret and to 0 in all blobs in the blob table of @wim not
2107 * inserted into @blob_table_list_ret.
2109 * Still furthermore, @unique_size will be set to 1 on all blobs in
2110 * @blob_list_ret that have unique size among all blobs in @blob_list_ret and
2111 * among all blobs in the blob table of @wim that are ineligible for being
2112 * written due to filtering.
2114 * Returns 0 on success; nonzero on read error, memory allocation error, or
2118 prepare_blob_list_for_write(WIMStruct *wim, int image,
2120 struct list_head *blob_list_ret,
2121 struct list_head *blob_table_list_ret,
2122 struct filter_context *filter_ctx_ret)
2125 struct blob_descriptor *blob;
2127 filter_ctx_ret->write_flags = write_flags;
2128 filter_ctx_ret->wim = wim;
2130 ret = prepare_unfiltered_list_of_blobs_in_output_wim(
2133 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2138 INIT_LIST_HEAD(blob_table_list_ret);
2139 list_for_each_entry(blob, blob_list_ret, write_blobs_list)
2140 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2142 ret = determine_blob_size_uniquity(blob_list_ret, wim->blob_table,
2147 if (may_filter_blobs(filter_ctx_ret))
2148 filter_blob_list_for_write(blob_list_ret, filter_ctx_ret);
2154 write_file_data(WIMStruct *wim, int image, int write_flags,
2155 unsigned num_threads,
2156 struct list_head *blob_list_override,
2157 struct list_head *blob_table_list_ret)
2160 struct list_head _blob_list;
2161 struct list_head *blob_list;
2162 struct blob_descriptor *blob;
2163 struct filter_context _filter_ctx;
2164 struct filter_context *filter_ctx;
2166 if (blob_list_override == NULL) {
2167 /* Normal case: prepare blob list from image(s) being written.
2169 blob_list = &_blob_list;
2170 filter_ctx = &_filter_ctx;
2171 ret = prepare_blob_list_for_write(wim, image, write_flags,
2173 blob_table_list_ret,
2178 /* Currently only as a result of wimlib_split() being called:
2179 * use blob list already explicitly provided. Use existing
2180 * reference counts. */
2181 blob_list = blob_list_override;
2183 INIT_LIST_HEAD(blob_table_list_ret);
2184 list_for_each_entry(blob, blob_list, write_blobs_list) {
2185 blob->out_refcnt = blob->refcnt;
2186 blob->will_be_in_output_wim = 1;
2187 blob->unique_size = 0;
2188 list_add_tail(&blob->blob_table_list, blob_table_list_ret);
2192 return write_file_data_blobs(wim,
2200 write_metadata_resources(WIMStruct *wim, int image, int write_flags)
2205 int write_resource_flags;
2207 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2208 DEBUG("Not writing any metadata resources.");
2212 write_resource_flags = write_flags_to_resource_flags(write_flags);
2214 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2216 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2217 wim->out_fd.offset);
2219 ret = call_progress(wim->progfunc,
2220 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2221 NULL, wim->progctx);
2225 if (image == WIMLIB_ALL_IMAGES) {
2227 end_image = wim->hdr.image_count;
2229 start_image = image;
2233 for (int i = start_image; i <= end_image; i++) {
2234 struct wim_image_metadata *imd;
2236 imd = wim->image_metadata[i - 1];
2237 /* Build a new metadata resource only if image was modified from
2238 * the original (or was newly added). Otherwise just copy the
2240 if (imd->modified) {
2241 DEBUG("Image %u was modified; building and writing new "
2242 "metadata resource", i);
2243 ret = write_metadata_resource(wim, i,
2244 write_resource_flags);
2245 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2246 DEBUG("Image %u was not modified; re-using existing "
2247 "metadata resource.", i);
2248 blob_set_out_reshdr_for_reuse(imd->metadata_blob);
2251 DEBUG("Image %u was not modified; copying existing "
2252 "metadata resource.", i);
2253 ret = write_wim_resource(imd->metadata_blob,
2255 wim->out_compression_type,
2256 wim->out_chunk_size,
2257 write_resource_flags);
2263 return call_progress(wim->progfunc,
2264 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2265 NULL, wim->progctx);
2269 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2272 DEBUG("Opening \"%"TS"\" for writing.", path);
2274 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2276 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2277 return WIMLIB_ERR_OPEN;
2279 filedes_init(&wim->out_fd, raw_fd);
2284 close_wim_writable(WIMStruct *wim, int write_flags)
2288 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2289 DEBUG("Closing WIM file.");
2290 if (filedes_valid(&wim->out_fd))
2291 if (filedes_close(&wim->out_fd))
2292 ret = WIMLIB_ERR_WRITE;
2294 filedes_invalidate(&wim->out_fd);
2299 cmp_blobs_by_out_rdesc(const void *p1, const void *p2)
2301 const struct blob_descriptor *blob1, *blob2;
2303 blob1 = *(const struct blob_descriptor**)p1;
2304 blob2 = *(const struct blob_descriptor**)p2;
2306 if (blob1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2307 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2308 if (blob1->out_res_offset_in_wim != blob2->out_res_offset_in_wim)
2309 return cmp_u64(blob1->out_res_offset_in_wim,
2310 blob2->out_res_offset_in_wim);
2315 if (blob2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2318 return cmp_u64(blob1->out_reshdr.offset_in_wim,
2319 blob2->out_reshdr.offset_in_wim);
2323 write_blob_table(WIMStruct *wim, int image, int write_flags,
2324 struct wim_reshdr *out_reshdr,
2325 struct list_head *blob_table_list)
2329 /* Set output resource metadata for blobs already present in WIM. */
2330 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2331 struct blob_descriptor *blob;
2332 list_for_each_entry(blob, blob_table_list, blob_table_list) {
2333 if (blob->blob_location == BLOB_IN_WIM &&
2334 blob->rdesc->wim == wim)
2336 blob_set_out_reshdr_for_reuse(blob);
2341 ret = sort_blob_list(blob_table_list,
2342 offsetof(struct blob_descriptor, blob_table_list),
2343 cmp_blobs_by_out_rdesc);
2347 /* Add entries for metadata resources. */
2348 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2352 if (image == WIMLIB_ALL_IMAGES) {
2354 end_image = wim->hdr.image_count;
2356 start_image = image;
2360 /* Push metadata blob table entries onto the front of the list
2361 * in reverse order, so that they're written in order.
2363 for (int i = end_image; i >= start_image; i--) {
2364 struct blob_descriptor *metadata_blob;
2366 metadata_blob = wim->image_metadata[i - 1]->metadata_blob;
2367 wimlib_assert(metadata_blob->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2368 metadata_blob->out_refcnt = 1;
2369 list_add(&metadata_blob->blob_table_list, blob_table_list);
2373 return write_blob_table_from_blob_list(blob_table_list,
2375 wim->hdr.part_number,
2377 write_flags_to_resource_flags(write_flags));
2383 * Finish writing a WIM file: write the blob table, xml data, and integrity
2384 * table, then overwrite the WIM header. By default, closes the WIM file
2385 * descriptor (@wim->out_fd) if successful.
2387 * write_flags is a bitwise OR of the following:
2389 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2390 * Include an integrity table.
2392 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2393 * fsync() the output file before closing it.
2395 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2396 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2397 * blob headers before the blob table and XML data, and also write
2398 * the WIM header at the end instead of seeking to the beginning.
2399 * Can't be combined with WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2401 * (private) WIMLIB_WRITE_FLAG_NO_BLOB_TABLE:
2402 * Don't write the blob table.
2404 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2405 * After writing the XML data but before writing the integrity
2406 * table, write a temporary WIM header and flush the file
2407 * descriptor so that the WIM is less likely to become corrupted
2408 * upon abrupt program termination.
2409 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2410 * Instead of overwriting the WIM header at the beginning of the
2411 * file, simply append it to the end of the file. (Used when
2413 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2414 * Do not close the file descriptor @wim->out_fd on either success
2416 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2417 * Use the existing <TOTALBYTES> stored in the in-memory XML
2418 * information, rather than setting it to the offset of the XML
2419 * data being written.
2420 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2421 * The existing WIM file is being updated in-place. The entries
2422 * from its integrity table may be re-used.
2425 finish_write(WIMStruct *wim, int image, int write_flags,
2426 struct list_head *blob_table_list)
2430 int write_resource_flags;
2431 off_t old_blob_table_end = 0;
2432 off_t new_blob_table_end;
2434 struct integrity_table *old_integrity_table = NULL;
2436 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2438 write_resource_flags = write_flags_to_resource_flags(write_flags);
2440 /* In the WIM header, there is room for the resource entry for a
2441 * metadata resource labeled as the "boot metadata". This entry should
2442 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2443 * it should be a copy of the resource entry for the image that is
2444 * marked as bootable. This is not well documented... */
2445 if (wim->hdr.boot_idx == 0) {
2446 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2448 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2449 &wim->image_metadata[
2450 wim->hdr.boot_idx - 1]->metadata_blob->out_reshdr);
2453 /* If overwriting the WIM file containing an integrity table in-place,
2454 * we'd like to re-use the information in the old integrity table
2455 * instead of recalculating it. But we might overwrite the old
2456 * integrity table when we expand the XML data. Read it into memory
2458 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2459 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2460 (WIMLIB_WRITE_FLAG_OVERWRITE |
2461 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2462 && wim_has_integrity_table(wim))
2464 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2465 wim->hdr.blob_table_reshdr.size_in_wim;
2466 (void)read_integrity_table(wim,
2467 old_blob_table_end - WIM_HEADER_DISK_SIZE,
2468 &old_integrity_table);
2469 /* If we couldn't read the old integrity table, we can still
2470 * re-calculate the full integrity table ourselves. Hence the
2471 * ignoring of the return value. */
2474 /* Write blob table. */
2475 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_BLOB_TABLE)) {
2476 ret = write_blob_table(wim, image, write_flags,
2477 &wim->hdr.blob_table_reshdr,
2480 free_integrity_table(old_integrity_table);
2485 /* Write XML data. */
2486 xml_totalbytes = wim->out_fd.offset;
2487 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2488 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2489 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2490 &wim->hdr.xml_data_reshdr,
2491 write_resource_flags);
2493 free_integrity_table(old_integrity_table);
2497 /* Write integrity table (optional). */
2498 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2499 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2500 struct wim_header checkpoint_hdr;
2501 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2502 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2503 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2504 ret = write_wim_header_at_offset(&checkpoint_hdr,
2507 free_integrity_table(old_integrity_table);
2512 new_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
2513 wim->hdr.blob_table_reshdr.size_in_wim;
2515 ret = write_integrity_table(wim,
2518 old_integrity_table);
2519 free_integrity_table(old_integrity_table);
2523 /* No integrity table. */
2524 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2527 /* Now that all information in the WIM header has been determined, the
2528 * preliminary header written earlier can be overwritten, the header of
2529 * the existing WIM file can be overwritten, or the final header can be
2530 * written to the end of the pipable WIM. */
2531 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2533 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2534 hdr_offset = wim->out_fd.offset;
2535 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2536 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2540 /* Possibly sync file data to disk before closing. On POSIX systems, it
2541 * is necessary to do this before using rename() to overwrite an
2542 * existing file with a new file. Otherwise, data loss would occur if
2543 * the system is abruptly terminated when the metadata for the rename
2544 * operation has been written to disk, but the new file data has not.
2546 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2547 DEBUG("Syncing WIM file.");
2548 if (fsync(wim->out_fd.fd)) {
2549 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2550 return WIMLIB_ERR_WRITE;
2554 if (close_wim_writable(wim, write_flags)) {
2555 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2556 return WIMLIB_ERR_WRITE;
2562 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2564 /* Set advisory lock on WIM file (if not already done so) */
2566 lock_wim_for_append(WIMStruct *wim)
2568 if (wim->locked_for_append)
2570 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2571 wim->locked_for_append = 1;
2574 if (errno != EWOULDBLOCK)
2576 return WIMLIB_ERR_ALREADY_LOCKED;
2579 /* Remove advisory lock on WIM file (if present) */
2581 unlock_wim_for_append(WIMStruct *wim)
2583 if (wim->locked_for_append) {
2584 flock(wim->in_fd.fd, LOCK_UN);
2585 wim->locked_for_append = 0;
2591 * write_pipable_wim():
2593 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2594 * capable of being applied from a pipe).
2596 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2597 * images can be applied from them sequentially when the file data is sent over
2598 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2599 * The modifications made to the WIM format for pipable WIMs are:
2601 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2602 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2603 * stops other software from trying to read the file as a normal WIM.
2605 * - The header at the beginning of the file does not contain all the normal
2606 * information; in particular it will have all 0's for the blob table and XML
2607 * data resource entries. This is because this information cannot be
2608 * determined until the blob table and XML data have been written.
2609 * Consequently, wimlib will write the full header at the very end of the
2610 * file. The header at the end, however, is only used when reading the WIM
2611 * from a seekable file (not a pipe).
2613 * - An extra copy of the XML data is placed directly after the header. This
2614 * allows image names and sizes to be determined at an appropriate time when
2615 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2616 * WIM is read from a seekable file (not a pipe).
2618 * - Solid resources are not allowed. Each blob is always stored in its own
2621 * - The format of resources, or blobs, has been modified to allow them to be
2622 * used before the "blob table" has been read. Each blob is prefixed with a
2623 * `struct pwm_blob_hdr' that is basically an abbreviated form of `struct
2624 * blob_descriptor_disk' that only contains the SHA-1 message digest,
2625 * uncompressed blob size, and flags that indicate whether the blob is
2626 * compressed. The data of uncompressed blobs then follows literally, while
2627 * the data of compressed blobs follows in a modified format. Compressed
2628 * blobs do not begin with a chunk table, since the chunk table cannot be
2629 * written until all chunks have been compressed. Instead, each compressed
2630 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2631 * Furthermore, the chunk table is written at the end of the resource instead
2632 * of the start. Note: chunk offsets are given in the chunk table as if the
2633 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2634 * used if the WIM is being read from a seekable file (not a pipe).
2636 * - Metadata blobs always come before non-metadata blobs. (This does not by
2637 * itself constitute an incompatibility with normal WIMs, since this is valid
2640 * - At least up to the end of the blobs, all components must be packed as
2641 * tightly as possible; there cannot be any "holes" in the WIM. (This does
2642 * not by itself consititute an incompatibility with normal WIMs, since this
2643 * is valid in normal WIMs.)
2645 * Note: the blob table, XML data, and header at the end are not used when
2646 * applying from a pipe. They exist to support functionality such as image
2647 * application and export when the WIM is *not* read from a pipe.
2649 * Layout of pipable WIM:
2651 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2652 * | Header | XML data | Metadata resources | File resources | Blob table | XML data | Header |
2653 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2655 * Layout of normal WIM:
2657 * +--------+-----------------------------+-------------------------+
2658 * | Header | File and metadata resources | Blob table | XML data |
2659 * +--------+-----------------------------+-------------------------+
2661 * An optional integrity table can follow the final XML data in both normal and
2662 * pipable WIMs. However, due to implementation details, wimlib currently can
2663 * only include an integrity table in a pipable WIM when writing it to a
2664 * seekable file (not a pipe).
2666 * Do note that since pipable WIMs are not supported by Microsoft's software,
2667 * wimlib does not create them unless explicitly requested (with
2668 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2669 * characters to identify the file.
2672 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2673 unsigned num_threads,
2674 struct list_head *blob_list_override,
2675 struct list_head *blob_table_list_ret)
2678 struct wim_reshdr xml_reshdr;
2680 WARNING("Creating a pipable WIM, which will "
2682 " with Microsoft's software (WIMGAPI/ImageX/DISM).");
2684 /* At this point, the header at the beginning of the file has already
2687 /* For efficiency, when wimlib adds an image to the WIM with
2688 * wimlib_add_image(), the SHA-1 message digests of files are not
2689 * calculated; instead, they are calculated while the files are being
2690 * written. However, this does not work when writing a pipable WIM,
2691 * since when writing a blob to a pipable WIM, its SHA-1 message digest
2692 * needs to be known before the blob data is written. Therefore, before
2693 * getting much farther, we need to pre-calculate the SHA-1 message
2694 * digests of all blobs that will be written. */
2695 ret = wim_checksum_unhashed_blobs(wim);
2699 /* Write extra copy of the XML data. */
2700 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2701 &xml_reshdr, WRITE_RESOURCE_FLAG_PIPABLE);
2705 /* Write metadata resources for the image(s) being included in the
2707 ret = write_metadata_resources(wim, image, write_flags);
2711 /* Write file data needed for the image(s) being included in the output
2712 * WIM, or file data needed for the split WIM part. */
2713 return write_file_data(wim, image, write_flags,
2714 num_threads, blob_list_override,
2715 blob_table_list_ret);
2717 /* The blob table, XML data, and header at end are handled by
2718 * finish_write(). */
2721 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2724 write_wim_part(WIMStruct *wim,
2725 const void *path_or_fd,
2728 unsigned num_threads,
2729 unsigned part_number,
2730 unsigned total_parts,
2731 struct list_head *blob_list_override,
2735 struct wim_header hdr_save;
2736 struct list_head blob_table_list;
2738 if (total_parts == 1)
2739 DEBUG("Writing standalone WIM.");
2741 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2742 if (image == WIMLIB_ALL_IMAGES)
2743 DEBUG("Including all images.");
2745 DEBUG("Including image %d only.", image);
2746 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2747 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2749 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2750 DEBUG("Write flags: 0x%08x", write_flags);
2752 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2753 DEBUG("\tCHECK_INTEGRITY");
2755 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2756 DEBUG("\tNO_CHECK_INTEGRITY");
2758 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2761 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2762 DEBUG("\tNOT_PIPABLE");
2764 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2765 DEBUG("\tRECOMPRESS");
2767 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2770 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2773 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2774 DEBUG("\tSOFT_DELETE");
2776 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2777 DEBUG("\tIGNORE_READONLY_FLAG");
2779 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2780 DEBUG("\tSKIP_EXTERNAL_WIMS");
2782 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2783 DEBUG("\tSTREAMS_OK");
2785 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2786 DEBUG("\tRETAIN_GUID");
2788 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2791 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
2792 DEBUG("\tSEND_DONE_WITH_FILE_MESSAGES");
2794 if (write_flags & WIMLIB_WRITE_FLAG_NO_SOLID_SORT)
2795 DEBUG("\tNO_SOLID_SORT");
2797 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2798 DEBUG("\tFILE_DESCRIPTOR");
2800 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2801 DEBUG("\tNO_METADATA");
2803 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2804 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2806 if (num_threads == 0)
2807 DEBUG("Number of threads: autodetect");
2809 DEBUG("Number of threads: %u", num_threads);
2810 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2811 DEBUG("Blob list: %s", (blob_list_override ? "specified" : "autodetect"));
2812 DEBUG("GUID: %s", (write_flags &
2813 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2814 : guid ? "explicit" : "generate new");
2816 /* Internally, this is always called with a valid part number and total
2818 wimlib_assert(total_parts >= 1);
2819 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2821 /* A valid image (or all images) must be specified. */
2822 if (image != WIMLIB_ALL_IMAGES &&
2823 (image < 1 || image > wim->hdr.image_count))
2824 return WIMLIB_ERR_INVALID_IMAGE;
2826 /* If we need to write metadata resources, make sure the ::WIMStruct has
2827 * the needed information attached (e.g. is not a resource-only WIM,
2828 * such as a non-first part of a split WIM). */
2829 if (!wim_has_metadata(wim) &&
2830 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2831 return WIMLIB_ERR_METADATA_NOT_FOUND;
2833 /* Check for contradictory flags. */
2834 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2835 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2836 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2837 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2838 return WIMLIB_ERR_INVALID_PARAM;
2840 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2841 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2842 == (WIMLIB_WRITE_FLAG_PIPABLE |
2843 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2844 return WIMLIB_ERR_INVALID_PARAM;
2846 /* Save previous header, then start initializing the new one. */
2847 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2849 /* Set default integrity, pipable, and solid flags. */
2850 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2851 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2852 if (wim_is_pipable(wim)) {
2853 DEBUG("WIM is pipable; default to PIPABLE.");
2854 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2857 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2858 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2859 if (wim_has_integrity_table(wim)) {
2860 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2861 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2864 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2865 WIMLIB_WRITE_FLAG_SOLID))
2866 == (WIMLIB_WRITE_FLAG_PIPABLE |
2867 WIMLIB_WRITE_FLAG_SOLID))
2869 ERROR("Cannot specify both PIPABLE and SOLID!");
2870 return WIMLIB_ERR_INVALID_PARAM;
2873 /* Set appropriate magic number. */
2874 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2875 wim->hdr.magic = PWM_MAGIC;
2877 wim->hdr.magic = WIM_MAGIC;
2879 /* Set appropriate version number. */
2880 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2881 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2882 wim->hdr.wim_version = WIM_VERSION_SOLID;
2884 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2886 /* Clear header flags that will be set automatically. */
2887 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2888 WIM_HDR_FLAG_RESOURCE_ONLY |
2889 WIM_HDR_FLAG_SPANNED |
2890 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2892 /* Set SPANNED header flag if writing part of a split WIM. */
2893 if (total_parts != 1)
2894 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2896 /* Set part number and total parts of split WIM. This will be 1 and 1
2897 * if the WIM is standalone. */
2898 wim->hdr.part_number = part_number;
2899 wim->hdr.total_parts = total_parts;
2901 /* Set the compression type and chunk size. */
2902 set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2903 wim->hdr.chunk_size = wim->out_chunk_size;
2906 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2908 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2910 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2913 /* Clear references to resources that have not been written yet. */
2914 zero_reshdr(&wim->hdr.blob_table_reshdr);
2915 zero_reshdr(&wim->hdr.xml_data_reshdr);
2916 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2917 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2919 /* Set image count and boot index correctly for single image writes. */
2920 if (image != WIMLIB_ALL_IMAGES) {
2921 wim->hdr.image_count = 1;
2922 if (wim->hdr.boot_idx == image)
2923 wim->hdr.boot_idx = 1;
2925 wim->hdr.boot_idx = 0;
2928 /* Split WIMs can't be bootable. */
2929 if (total_parts != 1)
2930 wim->hdr.boot_idx = 0;
2932 /* Set up output file descriptor. */
2933 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2934 /* File descriptor was explicitly provided. */
2935 filedes_init(&wim->out_fd, *(const int *)path_or_fd);
2936 if (!filedes_is_seekable(&wim->out_fd)) {
2937 /* The file descriptor is a pipe. */
2938 ret = WIMLIB_ERR_INVALID_PARAM;
2939 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2940 goto out_restore_hdr;
2941 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2942 ERROR("Can't include integrity check when "
2943 "writing pipable WIM to pipe!");
2944 goto out_restore_hdr;
2949 /* Filename of WIM to write was provided; open file descriptor
2951 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2952 O_TRUNC | O_CREAT | O_RDWR);
2954 goto out_restore_hdr;
2957 /* Write initial header. This is merely a "dummy" header since it
2958 * doesn't have all the information yet, so it will be overwritten later
2959 * (unless writing a pipable WIM). */
2960 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2961 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2962 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2963 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2965 goto out_restore_hdr;
2967 /* Write file data and metadata resources. */
2968 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2969 /* Default case: create a normal (non-pipable) WIM. */
2970 ret = write_file_data(wim, image, write_flags,
2975 goto out_restore_hdr;
2977 ret = write_metadata_resources(wim, image, write_flags);
2979 goto out_restore_hdr;
2981 /* Non-default case: create pipable WIM. */
2982 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2986 goto out_restore_hdr;
2987 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2991 /* Write blob table, XML data, and (optional) integrity table. */
2992 ret = finish_write(wim, image, write_flags, &blob_table_list);
2994 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2995 (void)close_wim_writable(wim, write_flags);
2996 DEBUG("ret=%d", ret);
3000 /* Write a standalone WIM to a file or file descriptor. */
3002 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
3003 int image, int write_flags, unsigned num_threads)
3005 return write_wim_part(wim, path_or_fd, image, write_flags,
3006 num_threads, 1, 1, NULL, NULL);
3009 /* API function documented in wimlib.h */
3011 wimlib_write(WIMStruct *wim, const tchar *path,
3012 int image, int write_flags, unsigned num_threads)
3014 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3015 return WIMLIB_ERR_INVALID_PARAM;
3017 if (path == NULL || path[0] == T('\0'))
3018 return WIMLIB_ERR_INVALID_PARAM;
3020 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3023 /* API function documented in wimlib.h */
3025 wimlib_write_to_fd(WIMStruct *wim, int fd,
3026 int image, int write_flags, unsigned num_threads)
3028 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3029 return WIMLIB_ERR_INVALID_PARAM;
3032 return WIMLIB_ERR_INVALID_PARAM;
3034 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3036 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3040 any_images_modified(WIMStruct *wim)
3042 for (int i = 0; i < wim->hdr.image_count; i++)
3043 if (wim->image_metadata[i]->modified)
3049 check_resource_offset(struct blob_descriptor *blob, void *_wim)
3051 const WIMStruct *wim = _wim;
3052 off_t end_offset = *(const off_t*)wim->private;
3054 if (blob->blob_location == BLOB_IN_WIM &&
3055 blob->rdesc->wim == wim &&
3056 blob->rdesc->offset_in_wim + blob->rdesc->size_in_wim > end_offset)
3057 return WIMLIB_ERR_RESOURCE_ORDER;
3061 /* Make sure no file or metadata resources are located after the XML data (or
3062 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3063 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3065 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3070 wim->private = &end_offset;
3071 ret = for_blob_in_table(wim->blob_table, check_resource_offset, wim);
3075 for (i = 0; i < wim->hdr.image_count; i++) {
3076 ret = check_resource_offset(wim->image_metadata[i]->metadata_blob, wim);
3084 * Overwrite a WIM, possibly appending new resources to it.
3086 * A WIM looks like (or is supposed to look like) the following:
3088 * Header (212 bytes)
3089 * Resources for metadata and files (variable size)
3090 * Blob table (variable size)
3091 * XML data (variable size)
3092 * Integrity table (optional) (variable size)
3094 * If we are not adding any new files or metadata, then the blob table is
3095 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3096 * header. This operation is potentially unsafe if the program is abruptly
3097 * terminated while the XML data or integrity table are being overwritten, but
3098 * before the new header has been written. To partially alleviate this problem,
3099 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3100 * finish_write() to cause a temporary WIM header to be written after the XML
3101 * data has been written. This may prevent the WIM from becoming corrupted if
3102 * the program is terminated while the integrity table is being calculated (but
3103 * no guarantees, due to write re-ordering...).
3105 * If we are adding new blobs, including new file data as well as any metadata
3106 * for any new images, then the blob table needs to be changed, and those blobs
3107 * need to be written. In this case, we try to perform a safe update of the WIM
3108 * file by writing the blobs *after* the end of the previous WIM, then writing
3109 * the new blob table, XML data, and (optionally) integrity table following the
3110 * new blobs. This will produce a layout like the following:
3112 * Header (212 bytes)
3113 * (OLD) Resources for metadata and files (variable size)
3114 * (OLD) Blob table (variable size)
3115 * (OLD) XML data (variable size)
3116 * (OLD) Integrity table (optional) (variable size)
3117 * (NEW) Resources for metadata and files (variable size)
3118 * (NEW) Blob table (variable size)
3119 * (NEW) XML data (variable size)
3120 * (NEW) Integrity table (optional) (variable size)
3122 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3123 * the header is overwritten to point to the new blob table, XML data, and
3124 * integrity table, to produce the following layout:
3126 * Header (212 bytes)
3127 * Resources for metadata and files (variable size)
3128 * Nothing (variable size)
3129 * Resources for metadata and files (variable size)
3130 * Blob table (variable size)
3131 * XML data (variable size)
3132 * Integrity table (optional) (variable size)
3134 * This method allows an image to be appended to a large WIM very quickly, and
3135 * is crash-safe except in the case of write re-ordering, but the disadvantage
3136 * is that a small hole is left in the WIM where the old blob table, xml data,
3137 * and integrity table were. (These usually only take up a small amount of
3138 * space compared to the blobs, however.)
3141 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3145 u64 old_blob_table_end, old_xml_begin, old_xml_end;
3146 struct wim_header hdr_save;
3147 struct list_head blob_list;
3148 struct list_head blob_table_list;
3149 struct filter_context filter_ctx;
3151 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3153 /* Save original header so it can be restored in case of error */
3154 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3156 /* Set default integrity flag. */
3157 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3158 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3159 if (wim_has_integrity_table(wim))
3160 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3162 /* Set WIM version if writing solid resources. */
3163 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
3164 wim->hdr.wim_version = WIM_VERSION_SOLID;
3166 /* Set additional flags for overwrite. */
3167 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3168 WIMLIB_WRITE_FLAG_STREAMS_OK;
3170 /* Make sure there is no data after the XML data, except possibily an
3171 * integrity table. If this were the case, then this data would be
3173 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3174 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3175 old_blob_table_end = wim->hdr.blob_table_reshdr.offset_in_wim +
3176 wim->hdr.blob_table_reshdr.size_in_wim;
3177 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3178 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3179 WARNING("Didn't expect the integrity table to be before the XML data");
3180 ret = WIMLIB_ERR_RESOURCE_ORDER;
3181 goto out_restore_memory_hdr;
3184 if (old_blob_table_end > old_xml_begin) {
3185 WARNING("Didn't expect the blob table to be after the XML data");
3186 ret = WIMLIB_ERR_RESOURCE_ORDER;
3187 goto out_restore_memory_hdr;
3190 /* Set @old_wim_end, which indicates the point beyond which we don't
3191 * allow any file and metadata resources to appear without returning
3192 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3193 * overwrite these resources). */
3194 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
3195 /* If no images have been modified and no images have been
3196 * deleted, a new blob table does not need to be written. We
3197 * shall write the new XML data and optional integrity table
3198 * immediately after the blob table. Note that this may
3199 * overwrite an existing integrity table. */
3200 DEBUG("Skipping writing blob table "
3201 "(no images modified or deleted)");
3202 old_wim_end = old_blob_table_end;
3203 write_flags |= WIMLIB_WRITE_FLAG_NO_BLOB_TABLE |
3204 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3205 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3206 /* Old WIM has an integrity table; begin writing new blobs after
3208 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3209 wim->hdr.integrity_table_reshdr.size_in_wim;
3211 /* No existing integrity table; begin writing new blobs after
3212 * the old XML data. */
3213 old_wim_end = old_xml_end;
3216 ret = check_resource_offsets(wim, old_wim_end);
3218 goto out_restore_memory_hdr;
3220 ret = prepare_blob_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3221 &blob_list, &blob_table_list,
3224 goto out_restore_memory_hdr;
3226 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3228 goto out_restore_memory_hdr;
3230 ret = lock_wim_for_append(wim);
3234 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3235 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3236 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3238 ERROR_WITH_ERRNO("Error updating WIM header flags");
3239 goto out_unlock_wim;
3242 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3243 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3244 ret = WIMLIB_ERR_WRITE;
3245 goto out_restore_physical_hdr;
3248 ret = write_file_data_blobs(wim, &blob_list, write_flags,
3249 num_threads, &filter_ctx);
3253 ret = write_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3257 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3262 unlock_wim_for_append(wim);
3266 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_BLOB_TABLE)) {
3267 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3268 wim->filename, old_wim_end);
3269 /* Return value of ftruncate() is ignored because this is
3270 * already an error path. */
3271 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3273 out_restore_physical_hdr:
3274 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3276 unlock_wim_for_append(wim);
3278 (void)close_wim_writable(wim, write_flags);
3279 out_restore_memory_hdr:
3280 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3285 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3287 size_t wim_name_len;
3290 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3292 /* Write the WIM to a temporary file in the same directory as the
3294 wim_name_len = tstrlen(wim->filename);
3295 tchar tmpfile[wim_name_len + 10];
3296 tmemcpy(tmpfile, wim->filename, wim_name_len);
3297 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3298 tmpfile[wim_name_len + 9] = T('\0');
3300 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3302 WIMLIB_WRITE_FLAG_FSYNC |
3303 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3310 if (filedes_valid(&wim->in_fd)) {
3311 filedes_close(&wim->in_fd);
3312 filedes_invalidate(&wim->in_fd);
3315 /* Rename the new WIM file to the original WIM file. Note: on Windows
3316 * this actually calls win32_rename_replacement(), not _wrename(), so
3317 * that removing the existing destination file can be handled. */
3318 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3319 ret = trename(tmpfile, wim->filename);
3321 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3322 tmpfile, wim->filename);
3329 return WIMLIB_ERR_RENAME;
3332 union wimlib_progress_info progress;
3333 progress.rename.from = tmpfile;
3334 progress.rename.to = wim->filename;
3335 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3336 &progress, wim->progctx);
3339 /* Determine if the specified WIM file may be updated by appending in-place
3340 * rather than writing and replacing it with an entirely new file. */
3342 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3344 /* REBUILD flag forces full rebuild. */
3345 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3348 /* Image deletions cause full rebuild by default. */
3349 if (wim->image_deletion_occurred &&
3350 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3353 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3354 * turned into a pipable WIM in-place. */
3355 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3358 /* The default compression type and compression chunk size selected for
3359 * the output WIM must be the same as those currently used for the WIM.
3361 if (wim->compression_type != wim->out_compression_type)
3363 if (wim->chunk_size != wim->out_chunk_size)
3369 /* API function documented in wimlib.h */
3371 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3376 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3377 return WIMLIB_ERR_INVALID_PARAM;
3380 return WIMLIB_ERR_NO_FILENAME;
3382 orig_hdr_flags = wim->hdr.flags;
3383 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3384 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3385 ret = can_modify_wim(wim);
3386 wim->hdr.flags = orig_hdr_flags;
3390 if (can_overwrite_wim_inplace(wim, write_flags)) {
3391 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3392 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3394 WARNING("Falling back to re-building entire WIM");
3396 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);