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 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/chunk_compressor.h"
43 #include "wimlib/endianness.h"
44 #include "wimlib/error.h"
45 #include "wimlib/file_io.h"
46 #include "wimlib/header.h"
47 #include "wimlib/inode.h"
48 #include "wimlib/integrity.h"
49 #include "wimlib/lookup_table.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;
76 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
77 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
78 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
79 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
80 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
81 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
82 if ((write_flags & (WIMLIB_WRITE_FLAG_SOLID |
83 WIMLIB_WRITE_FLAG_NO_SOLID_SORT)) ==
84 WIMLIB_WRITE_FLAG_SOLID)
85 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID_SORT;
86 return write_resource_flags;
89 struct filter_context {
94 /* Determine specified stream should be filtered out from the write.
98 * < 0 : The stream should be hard-filtered; that is, not included in the
100 * 0 : The stream should not be filtered out.
101 * > 0 : The stream should be soft-filtered; that is, it already exists in the
102 * WIM file and may not need to be written again.
105 stream_filtered(const struct wim_lookup_table_entry *lte,
106 const struct filter_context *ctx)
114 write_flags = ctx->write_flags;
117 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
118 lte->resource_location == RESOURCE_IN_WIM &&
119 lte->rspec->wim == wim)
122 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
123 lte->resource_location == RESOURCE_IN_WIM &&
124 lte->rspec->wim != wim)
131 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
132 struct filter_context *ctx)
134 return stream_filtered(lte, ctx) < 0;
138 may_soft_filter_streams(const struct filter_context *ctx)
142 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
146 may_hard_filter_streams(const struct filter_context *ctx)
150 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
154 may_filter_streams(const struct filter_context *ctx)
156 return (may_soft_filter_streams(ctx) ||
157 may_hard_filter_streams(ctx));
161 /* Return true if the specified resource is compressed and the compressed data
162 * can be reused with the specified output parameters. */
164 can_raw_copy(const struct wim_lookup_table_entry *lte,
165 int write_resource_flags, int out_ctype, u32 out_chunk_size)
167 const struct wim_resource_spec *rspec;
169 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
172 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
175 if (lte->resource_location != RESOURCE_IN_WIM)
180 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
183 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
184 /* Normal compressed resource: Must use same compression type
186 return (rspec->compression_type == out_ctype &&
187 rspec->chunk_size == out_chunk_size);
190 if ((rspec->flags & WIM_RESHDR_FLAG_SOLID) &&
191 (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
193 /* Solid resource: Such resources may contain multiple streams,
194 * and in general only a subset of them need to be written. As
195 * a heuristic, re-use the raw data if more than two-thirds the
196 * uncompressed size is being written. */
198 /* Note: solid resources contain a header that specifies the
199 * compression type and chunk size; therefore we don't need to
200 * check if they are compatible with @out_ctype and
201 * @out_chunk_size. */
203 struct wim_lookup_table_entry *res_stream;
206 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
207 if (res_stream->will_be_in_output_wim)
208 write_size += res_stream->size;
210 return (write_size > rspec->uncompressed_size * 2 / 3);
217 filter_resource_flags(u8 flags)
219 return (flags & ~(WIM_RESHDR_FLAG_SOLID |
220 WIM_RESHDR_FLAG_COMPRESSED |
221 WIM_RESHDR_FLAG_SPANNED |
222 WIM_RESHDR_FLAG_FREE));
226 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
228 const struct wim_resource_spec *rspec;
230 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
233 if (rspec->flags & WIM_RESHDR_FLAG_SOLID) {
235 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_SOLID);
237 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
238 lte->out_reshdr.uncompressed_size = 0;
239 lte->out_reshdr.size_in_wim = lte->size;
241 lte->out_res_offset_in_wim = rspec->offset_in_wim;
242 lte->out_res_size_in_wim = rspec->size_in_wim;
243 lte->out_res_uncompressed_size = rspec->uncompressed_size;
245 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_SOLID));
247 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
248 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
249 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
251 lte->out_reshdr.flags = lte->flags;
255 /* Write the header for a stream in a pipable WIM. */
257 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
258 struct filedes *out_fd,
259 int additional_reshdr_flags)
261 struct pwm_stream_hdr stream_hdr;
265 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
266 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
267 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
268 zero_out_hash(stream_hdr.hash);
270 wimlib_assert(!lte->unhashed);
271 copy_hash(stream_hdr.hash, lte->hash);
274 reshdr_flags = filter_resource_flags(lte->flags);
275 reshdr_flags |= additional_reshdr_flags;
276 stream_hdr.flags = cpu_to_le32(reshdr_flags);
277 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
279 ERROR_WITH_ERRNO("Write error");
283 struct write_streams_progress_data {
284 wimlib_progress_func_t progfunc;
286 union wimlib_progress_info progress;
287 uint64_t next_progress;
291 do_write_streams_progress(struct write_streams_progress_data *progress_data,
296 union wimlib_progress_info *progress = &progress_data->progress;
300 progress->write_streams.total_bytes -= complete_size;
301 progress->write_streams.total_streams -= complete_count;
302 if (progress_data->next_progress != ~(uint64_t)0 &&
303 progress_data->next_progress > progress->write_streams.total_bytes)
305 progress_data->next_progress = progress->write_streams.total_bytes;
308 progress->write_streams.completed_bytes += complete_size;
309 progress->write_streams.completed_streams += complete_count;
312 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
314 ret = call_progress(progress_data->progfunc,
315 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
317 progress_data->progctx);
321 if (progress_data->next_progress == progress->write_streams.total_bytes) {
322 progress_data->next_progress = ~(uint64_t)0;
324 /* Handle rate-limiting of messages */
326 /* Send new message as soon as another 1/128 of the
327 * total has been written. (Arbitrary number.) */
328 progress_data->next_progress =
329 progress->write_streams.completed_bytes +
330 progress->write_streams.total_bytes / 128;
332 /* ... Unless that would be more than 5000000 bytes, in
333 * which case send the next after the next 5000000
334 * bytes. (Another arbitrary number.) */
335 if (progress->write_streams.completed_bytes + 5000000 <
336 progress_data->next_progress)
337 progress_data->next_progress =
338 progress->write_streams.completed_bytes + 5000000;
340 /* ... But always send a message as soon as we're
341 * completely done. */
342 if (progress->write_streams.total_bytes <
343 progress_data->next_progress)
344 progress_data->next_progress =
345 progress->write_streams.total_bytes;
351 struct write_streams_ctx {
352 /* File descriptor the streams are being written to. */
353 struct filedes *out_fd;
355 /* Lookup table for the WIMStruct on whose behalf the streams are being
357 struct wim_lookup_table *lookup_table;
359 /* Compression format to use. */
362 /* Maximum uncompressed chunk size in compressed resources to use. */
365 /* Flags that affect how the streams will be written. */
366 int write_resource_flags;
368 /* Data used for issuing WRITE_STREAMS progress. */
369 struct write_streams_progress_data progress_data;
371 struct filter_context *filter_ctx;
373 /* Upper bound on the total number of bytes that need to be compressed.
375 u64 num_bytes_to_compress;
377 /* Pointer to the chunk_compressor implementation being used for
378 * compressing chunks of data, or NULL if chunks are being written
380 struct chunk_compressor *compressor;
382 /* Buffer for dividing the read data into chunks of size
383 * @out_chunk_size. */
386 /* Number of bytes in @chunk_buf that are currently filled. */
387 size_t chunk_buf_filled;
389 /* List of streams that currently have chunks being compressed. */
390 struct list_head pending_streams;
392 /* List of streams in the solid resource. Streams are moved here after
393 * @pending_streams only when writing a solid resource. */
394 struct list_head solid_streams;
396 /* Current uncompressed offset in the stream being read. */
397 u64 cur_read_stream_offset;
399 /* Uncompressed size of the stream currently being read. */
400 u64 cur_read_stream_size;
402 /* Current uncompressed offset in the stream being written. */
403 u64 cur_write_stream_offset;
405 /* Uncompressed size of resource currently being written. */
406 u64 cur_write_res_size;
408 /* Array that is filled in with compressed chunk sizes as a resource is
412 /* Index of next entry in @chunk_csizes to fill in. */
415 /* Number of entries in @chunk_csizes currently allocated. */
416 size_t num_alloc_chunks;
418 /* Offset in the output file of the start of the chunks of the resource
419 * currently being written. */
420 u64 chunks_start_offset;
423 /* Reserve space for the chunk table and prepare to accumulate the chunk table
426 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
428 u64 expected_num_chunks;
429 u64 expected_num_chunk_entries;
433 /* Calculate the number of chunks and chunk entries that should be
434 * needed for the resource. These normally will be the final values,
435 * but in SOLID mode some of the streams we're planning to write into
436 * the resource may be duplicates, and therefore discarded, potentially
437 * decreasing the number of chunk entries needed. */
438 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
439 expected_num_chunk_entries = expected_num_chunks;
440 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
441 expected_num_chunk_entries--;
443 /* Make sure the chunk_csizes array is long enough to store the
444 * compressed size of each chunk. */
445 if (expected_num_chunks > ctx->num_alloc_chunks) {
446 u64 new_length = expected_num_chunks + 50;
448 if ((size_t)new_length != new_length) {
449 ERROR("Resource size too large (%"PRIu64" bytes!",
451 return WIMLIB_ERR_NOMEM;
454 FREE(ctx->chunk_csizes);
455 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
456 if (ctx->chunk_csizes == NULL) {
457 ctx->num_alloc_chunks = 0;
458 return WIMLIB_ERR_NOMEM;
460 ctx->num_alloc_chunks = new_length;
463 ctx->chunk_index = 0;
465 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
466 /* Reserve space for the chunk table in the output file. In the
467 * case of solid resources this reserves the upper bound for the
468 * needed space, not necessarily the exact space which will
469 * prove to be needed. At this point, we just use @chunk_csizes
470 * for a buffer of 0's because the actual compressed chunk sizes
472 reserve_size = expected_num_chunk_entries *
473 get_chunk_entry_size(res_expected_size,
474 0 != (ctx->write_resource_flags &
475 WRITE_RESOURCE_FLAG_SOLID));
476 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
477 reserve_size += sizeof(struct alt_chunk_table_header_disk);
478 memset(ctx->chunk_csizes, 0, reserve_size);
479 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
487 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
491 wimlib_assert(res_expected_size != 0);
493 if (ctx->compressor != NULL) {
494 ret = begin_chunk_table(ctx, res_expected_size);
499 /* Output file descriptor is now positioned at the offset at which to
500 * write the first chunk of the resource. */
501 ctx->chunks_start_offset = ctx->out_fd->offset;
502 ctx->cur_write_stream_offset = 0;
503 ctx->cur_write_res_size = res_expected_size;
508 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
509 u64 *res_start_offset_ret, u64 *res_store_size_ret)
511 size_t actual_num_chunks;
512 size_t actual_num_chunk_entries;
513 size_t chunk_entry_size;
516 actual_num_chunks = ctx->chunk_index;
517 actual_num_chunk_entries = actual_num_chunks;
518 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
519 actual_num_chunk_entries--;
521 chunk_entry_size = get_chunk_entry_size(res_actual_size,
522 0 != (ctx->write_resource_flags &
523 WRITE_RESOURCE_FLAG_SOLID));
525 typedef le64 _may_alias_attribute aliased_le64_t;
526 typedef le32 _may_alias_attribute aliased_le32_t;
528 if (chunk_entry_size == 4) {
529 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
531 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
532 for (size_t i = 0; i < actual_num_chunk_entries; i++)
533 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
535 u32 offset = ctx->chunk_csizes[0];
536 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
537 u32 next_size = ctx->chunk_csizes[i + 1];
538 entries[i] = cpu_to_le32(offset);
543 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
545 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
546 for (size_t i = 0; i < actual_num_chunk_entries; i++)
547 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
549 u64 offset = ctx->chunk_csizes[0];
550 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
551 u64 next_size = ctx->chunk_csizes[i + 1];
552 entries[i] = cpu_to_le64(offset);
558 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
559 u64 res_start_offset;
562 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
563 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
566 res_end_offset = ctx->out_fd->offset;
567 res_start_offset = ctx->chunks_start_offset;
569 res_end_offset = ctx->out_fd->offset;
571 u64 chunk_table_offset;
573 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
575 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
576 struct alt_chunk_table_header_disk hdr;
578 hdr.res_usize = cpu_to_le64(res_actual_size);
579 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
580 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
582 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
583 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
584 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
586 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
587 chunk_table_offset - sizeof(hdr));
590 res_start_offset = chunk_table_offset - sizeof(hdr);
592 res_start_offset = chunk_table_offset;
595 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
596 chunk_table_size, chunk_table_offset);
601 *res_start_offset_ret = res_start_offset;
602 *res_store_size_ret = res_end_offset - res_start_offset;
607 ERROR_WITH_ERRNO("Write error");
611 /* Finish writing a WIM resource by writing or updating the chunk table (if not
612 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
614 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
618 u64 res_uncompressed_size;
619 u64 res_offset_in_wim;
621 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
622 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
623 res_uncompressed_size = ctx->cur_write_res_size;
625 if (ctx->compressor) {
626 ret = end_chunk_table(ctx, res_uncompressed_size,
627 &res_offset_in_wim, &res_size_in_wim);
631 res_offset_in_wim = ctx->chunks_start_offset;
632 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
634 out_reshdr->uncompressed_size = res_uncompressed_size;
635 out_reshdr->size_in_wim = res_size_in_wim;
636 out_reshdr->offset_in_wim = res_offset_in_wim;
637 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
638 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
642 /* No more data streams of the file at @path are needed. */
644 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
646 union wimlib_progress_info info;
648 info.done_with_file.path_to_file = path;
650 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
655 is_file_stream(const struct wim_lookup_table_entry *lte)
657 return lte->resource_location == RESOURCE_IN_FILE_ON_DISK
659 || lte->resource_location == RESOURCE_IN_WINNT_FILE_ON_DISK
660 || lte->resource_location == RESOURCE_WIN32_ENCRYPTED
666 do_done_with_stream(struct wim_lookup_table_entry *lte,
667 wimlib_progress_func_t progfunc, void *progctx)
670 struct wim_inode *inode;
672 if (!lte->may_send_done_with_file)
675 inode = lte->file_inode;
677 wimlib_assert(inode != NULL);
678 wimlib_assert(inode->num_remaining_streams > 0);
679 if (--inode->num_remaining_streams > 0)
683 /* XXX: This logic really should be somewhere else. */
685 /* We want the path to the file, but lte->file_on_disk might actually
686 * refer to a named data stream. Temporarily strip the named data
687 * stream from the path. */
688 wchar_t *p_colon = NULL;
689 wchar_t *p_question_mark = NULL;
690 const wchar_t *p_stream_name;
692 p_stream_name = path_stream_name(lte->file_on_disk);
693 if (unlikely(p_stream_name)) {
694 p_colon = (wchar_t *)(p_stream_name - 1);
695 wimlib_assert(*p_colon == L':');
699 /* We also should use a fake Win32 path instead of a NT path */
700 if (!wcsncmp(lte->file_on_disk, L"\\??\\", 4)) {
701 p_question_mark = <e->file_on_disk[1];
702 *p_question_mark = L'\\';
706 ret = done_with_file(lte->file_on_disk, progfunc, progctx);
712 *p_question_mark = L'?';
717 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
719 done_with_stream(struct wim_lookup_table_entry *lte,
720 struct write_streams_ctx *ctx)
722 if (likely(!(ctx->write_resource_flags &
723 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
725 return do_done_with_stream(lte, ctx->progress_data.progfunc,
726 ctx->progress_data.progctx);
729 /* Begin processing a stream for writing. */
731 write_stream_begin_read(struct wim_lookup_table_entry *lte, void *_ctx)
733 struct write_streams_ctx *ctx = _ctx;
736 wimlib_assert(lte->size > 0);
738 ctx->cur_read_stream_offset = 0;
739 ctx->cur_read_stream_size = lte->size;
741 /* As an optimization, we allow some streams to be "unhashed", meaning
742 * their SHA1 message digests are unknown. This is the case with
743 * streams that are added by scanning a directry tree with
744 * wimlib_add_image(), for example. Since WIM uses single-instance
745 * streams, we don't know whether such each such stream really need to
746 * written until it is actually checksummed, unless it has a unique
747 * size. In such cases we read and checksum the stream in this
748 * function, thereby advancing ahead of read_stream_list(), which will
749 * still provide the data again to write_stream_process_chunk(). This
750 * is okay because an unhashed stream cannot be in a WIM resource, which
751 * might be costly to decompress. */
752 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
754 struct wim_lookup_table_entry *lte_new;
756 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
759 if (lte_new != lte) {
760 /* Duplicate stream detected. */
762 if (lte_new->will_be_in_output_wim ||
763 stream_filtered(lte_new, ctx->filter_ctx))
765 /* The duplicate stream is already being
766 * included in the output WIM, or it would be
767 * filtered out if it had been. Skip writing
768 * this stream (and reading it again) entirely,
769 * passing its output reference count to the
770 * duplicate stream in the former case. */
771 DEBUG("Discarding duplicate stream of "
772 "length %"PRIu64, lte->size);
773 ret = do_write_streams_progress(&ctx->progress_data,
776 list_del(<e->write_streams_list);
777 list_del(<e->lookup_table_list);
778 if (lte_new->will_be_in_output_wim)
779 lte_new->out_refcnt += lte->out_refcnt;
780 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
781 ctx->cur_write_res_size -= lte->size;
783 ret = done_with_stream(lte, ctx);
784 free_lookup_table_entry(lte);
787 return BEGIN_STREAM_STATUS_SKIP_STREAM;
789 /* The duplicate stream can validly be written,
790 * but was not marked as such. Discard the
791 * current stream entry and use the duplicate,
792 * but actually freeing the current entry must
793 * wait until read_stream_list() has finished
794 * reading its data. */
795 DEBUG("Stream duplicate, but not already "
796 "selected for writing.");
797 list_replace(<e->write_streams_list,
798 <e_new->write_streams_list);
799 list_replace(<e->lookup_table_list,
800 <e_new->lookup_table_list);
801 lte->will_be_in_output_wim = 0;
802 lte_new->out_refcnt = lte->out_refcnt;
803 lte_new->will_be_in_output_wim = 1;
804 lte_new->may_send_done_with_file = 0;
809 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
813 /* Rewrite a stream that was just written compressed as uncompressed instead.
814 * This function is optional, but if a stream did not compress to less than its
815 * original size, it might as well be written uncompressed. */
817 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
818 struct filedes *out_fd)
821 u64 begin_offset = lte->out_reshdr.offset_in_wim;
822 u64 end_offset = out_fd->offset;
824 if (filedes_seek(out_fd, begin_offset) == -1)
827 ret = extract_full_stream_to_fd(lte, out_fd);
829 /* Error reading the uncompressed data. */
830 if (out_fd->offset == begin_offset &&
831 filedes_seek(out_fd, end_offset) != -1)
833 /* Nothing was actually written yet, and we successfully
834 * seeked to the end of the compressed resource, so
835 * don't issue a hard error; just keep the compressed
836 * resource instead. */
837 WARNING("Recovered compressed stream of "
838 "size %"PRIu64", continuing on.",
845 wimlib_assert(out_fd->offset - begin_offset == lte->size);
847 if (out_fd->offset < end_offset &&
848 0 != ftruncate(out_fd->fd, out_fd->offset))
850 ERROR_WITH_ERRNO("Can't truncate output file to "
851 "offset %"PRIu64, out_fd->offset);
852 return WIMLIB_ERR_WRITE;
855 lte->out_reshdr.size_in_wim = lte->size;
856 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
857 WIM_RESHDR_FLAG_SOLID);
861 /* Returns true if the specified stream should be truncated from the WIM file
862 * and re-written as uncompressed. lte->out_reshdr must be filled in from the
863 * initial write of the stream. */
865 should_rewrite_stream_uncompressed(const struct write_streams_ctx *ctx,
866 const struct wim_lookup_table_entry *lte)
868 /* If the compressed data is smaller than the uncompressed data, prefer
869 * the compressed data. */
870 if (lte->out_reshdr.size_in_wim < lte->out_reshdr.uncompressed_size)
873 /* If we're not actually writing compressed data, then there's no need
875 if (!ctx->compressor)
878 /* If writing a pipable WIM, everything we write to the output is final
879 * (it might actually be a pipe!). */
880 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
883 /* If the stream that would need to be re-read is located in a solid
884 * resource in another WIM file, then re-reading it would be costly. So
887 * Exception: if the compressed size happens to be *exactly* the same as
888 * the uncompressed size, then the stream *must* be written uncompressed
889 * in order to remain compatible with the Windows Overlay Filesystem
890 * Filter Driver (WOF).
892 * TODO: we are currently assuming that the optimization for
893 * single-chunk resources in maybe_rewrite_stream_uncompressed()
894 * prevents this case from being triggered too often. To fully prevent
895 * excessive decompressions in degenerate cases, we really should
896 * obtain the uncompressed data by decompressing the compressed data we
897 * wrote to the output file.
899 if ((lte->flags & WIM_RESHDR_FLAG_SOLID) &&
900 (lte->out_reshdr.size_in_wim != lte->out_reshdr.uncompressed_size))
907 maybe_rewrite_stream_uncompressed(struct write_streams_ctx *ctx,
908 struct wim_lookup_table_entry *lte)
910 if (!should_rewrite_stream_uncompressed(ctx, lte))
913 /* Regular (non-solid) WIM resources with exactly one chunk and
914 * compressed size equal to uncompressed size are exactly the same as
915 * the corresponding compressed data --- since there must be 0 entries
916 * in the chunk table and the only chunk must be stored uncompressed.
917 * In this case, there's no need to rewrite anything. */
918 if (ctx->chunk_index == 1 &&
919 lte->out_reshdr.size_in_wim == lte->out_reshdr.uncompressed_size)
921 lte->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
925 return write_stream_uncompressed(lte, ctx->out_fd);
928 /* Write the next chunk of (typically compressed) data to the output WIM,
929 * handling the writing of the chunk table. */
931 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
932 size_t csize, size_t usize)
936 struct wim_lookup_table_entry *lte;
937 u32 completed_stream_count;
940 lte = list_entry(ctx->pending_streams.next,
941 struct wim_lookup_table_entry, write_streams_list);
943 if (ctx->cur_write_stream_offset == 0 &&
944 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
946 /* Starting to write a new stream in non-solid mode. */
948 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
949 int additional_reshdr_flags = 0;
950 if (ctx->compressor != NULL)
951 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
953 DEBUG("Writing pipable WIM stream header "
954 "(offset=%"PRIu64")", ctx->out_fd->offset);
956 ret = write_pwm_stream_header(lte, ctx->out_fd,
957 additional_reshdr_flags);
962 ret = begin_write_resource(ctx, lte->size);
967 if (ctx->compressor != NULL) {
968 /* Record the compresed chunk size. */
969 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
970 ctx->chunk_csizes[ctx->chunk_index++] = csize;
972 /* If writing a pipable WIM, before the chunk data write a chunk
973 * header that provides the compressed chunk size. */
974 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
975 struct pwm_chunk_hdr chunk_hdr = {
976 .compressed_size = cpu_to_le32(csize),
978 ret = full_write(ctx->out_fd, &chunk_hdr,
985 /* Write the chunk data. */
986 ret = full_write(ctx->out_fd, cchunk, csize);
990 ctx->cur_write_stream_offset += usize;
992 completed_size = usize;
993 completed_stream_count = 0;
994 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
995 /* Wrote chunk in solid mode. It may have finished multiple
997 struct wim_lookup_table_entry *next_lte;
999 while (lte && ctx->cur_write_stream_offset >= lte->size) {
1001 ctx->cur_write_stream_offset -= lte->size;
1003 if (ctx->cur_write_stream_offset)
1004 next_lte = list_entry(lte->write_streams_list.next,
1005 struct wim_lookup_table_entry,
1006 write_streams_list);
1010 ret = done_with_stream(lte, ctx);
1013 list_move_tail(<e->write_streams_list, &ctx->solid_streams);
1014 completed_stream_count++;
1019 /* Wrote chunk in non-solid mode. It may have finished a
1021 if (ctx->cur_write_stream_offset == lte->size) {
1023 wimlib_assert(ctx->cur_write_stream_offset ==
1024 ctx->cur_write_res_size);
1026 ret = end_write_resource(ctx, <e->out_reshdr);
1030 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1031 if (ctx->compressor != NULL)
1032 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
1034 ret = maybe_rewrite_stream_uncompressed(ctx, lte);
1038 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
1040 ctx->cur_write_stream_offset = 0;
1042 ret = done_with_stream(lte, ctx);
1045 list_del(<e->write_streams_list);
1046 completed_stream_count++;
1050 return do_write_streams_progress(&ctx->progress_data,
1051 completed_size, completed_stream_count,
1055 ERROR_WITH_ERRNO("Write error");
1060 submit_chunk_for_compression(struct write_streams_ctx *ctx,
1061 const void *chunk, size_t size)
1063 /* While we are unable to submit the chunk for compression (due to too
1064 * many chunks already outstanding), retrieve and write the next
1065 * compressed chunk. */
1066 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
1073 bret = ctx->compressor->get_chunk(ctx->compressor,
1074 &cchunk, &csize, &usize);
1076 wimlib_assert(bret);
1078 ret = write_chunk(ctx, cchunk, csize, usize);
1085 /* Process the next chunk of data to be written to a WIM resource. */
1087 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
1089 struct write_streams_ctx *ctx = _ctx;
1091 const u8 *chunkptr, *chunkend;
1093 wimlib_assert(size != 0);
1095 if (ctx->compressor == NULL) {
1096 /* Write chunk uncompressed. */
1097 ret = write_chunk(ctx, chunk, size, size);
1100 ctx->cur_read_stream_offset += size;
1104 /* Submit the chunk for compression, but take into account that the
1105 * @size the chunk was provided in may not correspond to the
1106 * @out_chunk_size being used for compression. */
1108 chunkend = chunkptr + size;
1110 const u8 *resized_chunk;
1111 size_t needed_chunk_size;
1113 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1114 needed_chunk_size = ctx->out_chunk_size;
1116 u64 res_bytes_remaining;
1118 res_bytes_remaining = ctx->cur_read_stream_size -
1119 ctx->cur_read_stream_offset;
1120 needed_chunk_size = min(ctx->out_chunk_size,
1121 ctx->chunk_buf_filled +
1122 res_bytes_remaining);
1125 if (ctx->chunk_buf_filled == 0 &&
1126 chunkend - chunkptr >= needed_chunk_size)
1128 /* No intermediate buffering needed. */
1129 resized_chunk = chunkptr;
1130 chunkptr += needed_chunk_size;
1131 ctx->cur_read_stream_offset += needed_chunk_size;
1133 /* Intermediate buffering needed. */
1134 size_t bytes_consumed;
1136 bytes_consumed = min(chunkend - chunkptr,
1137 needed_chunk_size - ctx->chunk_buf_filled);
1139 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
1140 chunkptr, bytes_consumed);
1142 chunkptr += bytes_consumed;
1143 ctx->cur_read_stream_offset += bytes_consumed;
1144 ctx->chunk_buf_filled += bytes_consumed;
1145 if (ctx->chunk_buf_filled == needed_chunk_size) {
1146 resized_chunk = ctx->chunk_buf;
1147 ctx->chunk_buf_filled = 0;
1154 ret = submit_chunk_for_compression(ctx, resized_chunk,
1159 } while (chunkptr != chunkend);
1163 /* Finish processing a stream for writing. It may not have been completely
1164 * written yet, as the chunk_compressor implementation may still have chunks
1165 * buffered or being compressed. */
1167 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1169 struct write_streams_ctx *ctx = _ctx;
1171 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size || status);
1173 if (!lte->will_be_in_output_wim) {
1174 /* The 'lte' stream was a duplicate. Now that its data has
1175 * finished being read, it is being discarded in favor of the
1176 * duplicate entry. It therefore is no longer needed, and we
1177 * can fire the DONE_WITH_FILE callback because the file will
1178 * not be read again.
1180 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1181 * streams, since it needs to be possible to re-read the file if
1182 * it does not compress to less than its original size. */
1184 status = done_with_stream(lte, ctx);
1185 free_lookup_table_entry(lte);
1186 } else if (!status && lte->unhashed && ctx->lookup_table != NULL) {
1187 /* The 'lte' stream was not a duplicate and was previously
1188 * unhashed. Since we passed COMPUTE_MISSING_STREAM_HASHES to
1189 * read_stream_list(), lte->hash is now computed and valid. So
1190 * turn this stream into a "hashed" stream. */
1191 list_del(<e->unhashed_list);
1192 lookup_table_insert(ctx->lookup_table, lte);
1198 /* Compute statistics about a list of streams that will be written.
1200 * Assumes the streams are sorted such that all streams located in each distinct
1201 * WIM (specified by WIMStruct) are together. */
1203 compute_stream_list_stats(struct list_head *stream_list,
1204 struct write_streams_ctx *ctx)
1206 struct wim_lookup_table_entry *lte;
1207 u64 total_bytes = 0;
1208 u64 num_streams = 0;
1209 u64 total_parts = 0;
1210 WIMStruct *prev_wim_part = NULL;
1212 list_for_each_entry(lte, stream_list, write_streams_list) {
1214 total_bytes += lte->size;
1215 if (lte->resource_location == RESOURCE_IN_WIM) {
1216 if (prev_wim_part != lte->rspec->wim) {
1217 prev_wim_part = lte->rspec->wim;
1222 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1223 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1224 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1225 ctx->progress_data.progress.write_streams.completed_streams = 0;
1226 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1227 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1228 ctx->progress_data.progress.write_streams.completed_parts = 0;
1229 ctx->progress_data.next_progress = 0;
1232 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1233 * rather than compressed. Delete these streams from @stream_list and move them
1234 * to @raw_copy_streams. Return the total uncompressed size of the streams that
1235 * need to be compressed. */
1237 find_raw_copy_streams(struct list_head *stream_list,
1238 int write_resource_flags,
1241 struct list_head *raw_copy_streams)
1243 struct wim_lookup_table_entry *lte, *tmp;
1244 u64 num_bytes_to_compress = 0;
1246 INIT_LIST_HEAD(raw_copy_streams);
1248 /* Initialize temporary raw_copy_ok flag. */
1249 list_for_each_entry(lte, stream_list, write_streams_list)
1250 if (lte->resource_location == RESOURCE_IN_WIM)
1251 lte->rspec->raw_copy_ok = 0;
1253 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1254 if (lte->resource_location == RESOURCE_IN_WIM &&
1255 lte->rspec->raw_copy_ok)
1257 list_move_tail(<e->write_streams_list,
1259 } else if (can_raw_copy(lte, write_resource_flags,
1260 out_ctype, out_chunk_size))
1262 lte->rspec->raw_copy_ok = 1;
1263 list_move_tail(<e->write_streams_list,
1266 num_bytes_to_compress += lte->size;
1270 return num_bytes_to_compress;
1273 /* Copy a raw compressed resource located in another WIM file to the WIM file
1276 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1277 struct filedes *out_fd)
1279 u64 cur_read_offset;
1280 u64 end_read_offset;
1281 u8 buf[BUFFER_SIZE];
1282 size_t bytes_to_read;
1284 struct filedes *in_fd;
1285 struct wim_lookup_table_entry *lte;
1286 u64 out_offset_in_wim;
1288 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1289 "uncompressed_size=%"PRIu64")",
1290 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1292 /* Copy the raw data. */
1293 cur_read_offset = in_rspec->offset_in_wim;
1294 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1296 out_offset_in_wim = out_fd->offset;
1298 if (in_rspec->is_pipable) {
1299 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1300 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1301 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1302 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1304 in_fd = &in_rspec->wim->in_fd;
1305 wimlib_assert(cur_read_offset != end_read_offset);
1308 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1310 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1314 ret = full_write(out_fd, buf, bytes_to_read);
1318 cur_read_offset += bytes_to_read;
1320 } while (cur_read_offset != end_read_offset);
1322 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1323 if (lte->will_be_in_output_wim) {
1324 stream_set_out_reshdr_for_reuse(lte);
1325 if (in_rspec->flags & WIM_RESHDR_FLAG_SOLID)
1326 lte->out_res_offset_in_wim = out_offset_in_wim;
1328 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1335 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1336 * WIM file being written. */
1338 write_raw_copy_resources(struct list_head *raw_copy_streams,
1339 struct filedes *out_fd,
1340 struct write_streams_progress_data *progress_data)
1342 struct wim_lookup_table_entry *lte;
1345 list_for_each_entry(lte, raw_copy_streams, write_streams_list)
1346 lte->rspec->raw_copy_ok = 1;
1348 list_for_each_entry(lte, raw_copy_streams, write_streams_list) {
1349 if (lte->rspec->raw_copy_ok) {
1350 /* Write each solid resource only one time, no matter
1351 * how many streams reference it. */
1352 ret = write_raw_copy_resource(lte->rspec, out_fd);
1355 lte->rspec->raw_copy_ok = 0;
1357 ret = do_write_streams_progress(progress_data, lte->size,
1365 /* Wait for and write all chunks pending in the compressor. */
1367 finish_remaining_chunks(struct write_streams_ctx *ctx)
1374 if (ctx->compressor == NULL)
1377 if (ctx->chunk_buf_filled != 0) {
1378 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1379 ctx->chunk_buf_filled);
1384 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1385 ret = write_chunk(ctx, cdata, csize, usize);
1393 remove_zero_length_streams(struct list_head *stream_list)
1395 struct wim_lookup_table_entry *lte, *tmp;
1397 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1398 wimlib_assert(lte->will_be_in_output_wim);
1399 if (lte->size == 0) {
1400 list_del(<e->write_streams_list);
1401 lte->out_reshdr.offset_in_wim = 0;
1402 lte->out_reshdr.size_in_wim = 0;
1403 lte->out_reshdr.uncompressed_size = 0;
1404 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1410 init_done_with_file_info(struct list_head *stream_list)
1412 struct wim_lookup_table_entry *lte;
1414 list_for_each_entry(lte, stream_list, write_streams_list) {
1415 if (is_file_stream(lte)) {
1416 lte->file_inode->num_remaining_streams = 0;
1417 lte->may_send_done_with_file = 1;
1419 lte->may_send_done_with_file = 0;
1423 list_for_each_entry(lte, stream_list, write_streams_list)
1424 if (lte->may_send_done_with_file)
1425 lte->file_inode->num_remaining_streams++;
1429 * Write a list of streams to the output WIM file.
1432 * The list of streams to write, specified by a list of `struct
1433 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1436 * The file descriptor, opened for writing, to which to write the streams.
1438 * @write_resource_flags
1439 * Flags to modify how the streams are written:
1441 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1442 * Force compression of all resources, even if they could otherwise
1443 * be re-used by copying the raw data, due to being located in a WIM
1444 * file with compatible compression parameters.
1446 * WRITE_RESOURCE_FLAG_PIPABLE:
1447 * Write the resources in the wimlib-specific pipable format, and
1448 * furthermore do so in such a way that no seeking backwards in
1449 * @out_fd will be performed (so it may be a pipe).
1451 * WRITE_RESOURCE_FLAG_SOLID:
1452 * Combine all the streams into a single resource rather than
1453 * writing them in separate resources. This flag is only valid if
1454 * the WIM version number has been, or will be, set to
1455 * WIM_VERSION_SOLID. This flag may not be combined with
1456 * WRITE_RESOURCE_FLAG_PIPABLE.
1459 * Compression format to use to write the output streams, specified as one
1460 * of the WIMLIB_COMPRESSION_TYPE_* constants.
1461 * WIMLIB_COMPRESSION_TYPE_NONE is allowed.
1464 * Chunk size to use to write the streams. It must be a valid chunk size
1465 * for the specified compression format @out_ctype, unless @out_ctype is
1466 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1469 * Number of threads to use to compress data. If 0, a default number of
1470 * threads will be chosen. The number of threads still may be decreased
1471 * from the specified value if insufficient memory is detected.
1474 * If on-the-fly deduplication of unhashed streams is desired, this
1475 * parameter must be pointer to the lookup table for the WIMStruct on whose
1476 * behalf the streams are being written. Otherwise, this parameter can be
1480 * If on-the-fly deduplication of unhashed streams is desired, this
1481 * parameter can be a pointer to a context for stream filtering used to
1482 * detect whether the duplicate stream has been hard-filtered or not. If
1483 * no streams are hard-filtered or no streams are unhashed, this parameter
1486 * This function will write the streams in @stream_list to resources in
1487 * consecutive positions in the output WIM file, or to a single solid resource
1488 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1489 * cases, the @out_reshdr of the `struct wim_lookup_table_entry' for each stream
1490 * written will be updated to specify its location, size, and flags in the
1491 * output WIM. In the solid resource case, WIM_RESHDR_FLAG_SOLID will be set in
1492 * the @flags field of each @out_reshdr, and furthermore @out_res_offset_in_wim
1493 * and @out_res_size_in_wim of each @out_reshdr will be set to the offset and
1494 * size, respectively, in the output WIM of the solid resource containing the
1495 * corresponding stream.
1497 * Each of the streams to write may be in any location supported by the
1498 * resource-handling code (specifically, read_stream_list()), such as the
1499 * contents of external file that has been logically added to the output WIM, or
1500 * a stream in another WIM file that has been imported, or even a stream in the
1501 * "same" WIM file of which a modified copy is being written. In the case that
1502 * a stream is already in a WIM file and uses compatible compression parameters,
1503 * by default this function will re-use the raw data instead of decompressing
1504 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1505 * specified in @write_resource_flags, this is not done.
1507 * As a further requirement, this function requires that the
1508 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1509 * well as any other streams not in @stream_list that will be in the output WIM
1510 * file, but set to 0 on any other streams in the output WIM's lookup table or
1511 * sharing a solid resource with a stream in @stream_list. Still furthermore,
1512 * if on-the-fly deduplication of streams is possible, then all streams in
1513 * @stream_list must also be linked by @lookup_table_list along with any other
1514 * streams that have @will_be_in_output_wim set.
1516 * This function handles on-the-fly deduplication of streams for which SHA1
1517 * message digests have not yet been calculated. Such streams may or may not
1518 * need to be written. If @lookup_table is non-NULL, then each stream in
1519 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1520 * immediately before it would otherwise be read for writing in order to
1521 * determine if it is identical to another stream already being written or one
1522 * that would be filtered out of the output WIM using stream_filtered() with the
1523 * context @filter_ctx. Each such duplicate stream will be removed from
1524 * @stream_list, its reference count transfered to the pre-existing duplicate
1525 * stream, its memory freed, and will not be written. Alternatively, if a
1526 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1527 * has not been marked for writing or would not be hard-filtered, it is freed
1528 * and the pre-existing duplicate is written instead, taking ownership of the
1529 * reference count and slot in the @lookup_table_list.
1531 * Returns 0 if every stream was either written successfully or did not need to
1532 * be written; otherwise returns a non-zero error code.
1535 write_stream_list(struct list_head *stream_list,
1536 struct filedes *out_fd,
1537 int write_resource_flags,
1540 unsigned num_threads,
1541 struct wim_lookup_table *lookup_table,
1542 struct filter_context *filter_ctx,
1543 wimlib_progress_func_t progfunc,
1547 struct write_streams_ctx ctx;
1548 struct list_head raw_copy_streams;
1550 wimlib_assert((write_resource_flags &
1551 (WRITE_RESOURCE_FLAG_SOLID |
1552 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1553 (WRITE_RESOURCE_FLAG_SOLID |
1554 WRITE_RESOURCE_FLAG_PIPABLE));
1556 remove_zero_length_streams(stream_list);
1558 if (list_empty(stream_list)) {
1559 DEBUG("No streams to write.");
1563 /* If needed, set auxiliary information so that we can detect when the
1564 * library has finished using each external file. */
1565 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1566 init_done_with_file_info(stream_list);
1568 memset(&ctx, 0, sizeof(ctx));
1570 ctx.out_fd = out_fd;
1571 ctx.lookup_table = lookup_table;
1572 ctx.out_ctype = out_ctype;
1573 ctx.out_chunk_size = out_chunk_size;
1574 ctx.write_resource_flags = write_resource_flags;
1575 ctx.filter_ctx = filter_ctx;
1578 * We normally sort the streams to write by a "sequential" order that is
1579 * optimized for reading. But when using solid compression, we instead
1580 * sort the streams by file extension and file name (when applicable;
1581 * and we don't do this for streams from solid resources) so that
1582 * similar files are grouped together, which improves the compression
1583 * ratio. This is somewhat of a hack since a stream does not
1584 * necessarily correspond one-to-one with a filename, nor is there any
1585 * guarantee that two files with similar names or extensions are
1586 * actually similar in content. A potential TODO is to sort the streams
1587 * based on some measure of similarity of their actual contents.
1590 ret = sort_stream_list_by_sequential_order(stream_list,
1591 offsetof(struct wim_lookup_table_entry,
1592 write_streams_list));
1596 compute_stream_list_stats(stream_list, &ctx);
1598 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1599 ret = sort_stream_list_for_solid_compression(stream_list);
1601 WARNING("Failed to sort streams for solid compression. Continuing anyways.");
1604 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1605 wimlib_assert(out_chunk_size != 0);
1606 if (out_chunk_size <= STACK_MAX) {
1607 ctx.chunk_buf = alloca(out_chunk_size);
1609 ctx.chunk_buf = MALLOC(out_chunk_size);
1610 if (ctx.chunk_buf == NULL) {
1611 ret = WIMLIB_ERR_NOMEM;
1612 goto out_destroy_context;
1616 ctx.chunk_buf_filled = 0;
1618 ctx.progress_data.progfunc = progfunc;
1619 ctx.progress_data.progctx = progctx;
1621 ctx.num_bytes_to_compress = find_raw_copy_streams(stream_list,
1622 write_resource_flags,
1627 DEBUG("Writing stream list "
1628 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1629 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1630 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1631 out_fd->offset, write_resource_flags,
1632 out_ctype, out_chunk_size, num_threads,
1633 ctx.progress_data.progress.write_streams.total_bytes,
1634 ctx.num_bytes_to_compress);
1636 if (ctx.num_bytes_to_compress == 0) {
1637 DEBUG("No compression needed; skipping to raw copy!");
1638 goto out_write_raw_copy_resources;
1641 /* Unless uncompressed output was required, allocate a chunk_compressor
1642 * to do compression. There are serial and parallel implementations of
1643 * the chunk_compressor interface. We default to parallel using the
1644 * specified number of threads, unless the upper bound on the number
1645 * bytes needing to be compressed is less than a heuristic value. */
1646 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1648 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1649 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1650 ret = new_parallel_chunk_compressor(out_ctype,
1655 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1656 " Falling back to single-threaded compression.",
1657 wimlib_get_error_string(ret));
1662 if (ctx.compressor == NULL) {
1663 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1666 goto out_destroy_context;
1671 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1673 ctx.progress_data.progress.write_streams.num_threads = 1;
1675 DEBUG("Actually using %u threads",
1676 ctx.progress_data.progress.write_streams.num_threads);
1678 INIT_LIST_HEAD(&ctx.pending_streams);
1679 INIT_LIST_HEAD(&ctx.solid_streams);
1681 ret = call_progress(ctx.progress_data.progfunc,
1682 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1683 &ctx.progress_data.progress,
1684 ctx.progress_data.progctx);
1686 goto out_destroy_context;
1688 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1689 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1691 goto out_destroy_context;
1694 /* Read the list of streams needing to be compressed, using the
1695 * specified callbacks to execute processing of the data. */
1697 struct read_stream_list_callbacks cbs = {
1698 .begin_stream = write_stream_begin_read,
1699 .begin_stream_ctx = &ctx,
1700 .consume_chunk = write_stream_process_chunk,
1701 .consume_chunk_ctx = &ctx,
1702 .end_stream = write_stream_end_read,
1703 .end_stream_ctx = &ctx,
1706 ret = read_stream_list(stream_list,
1707 offsetof(struct wim_lookup_table_entry, write_streams_list),
1709 STREAM_LIST_ALREADY_SORTED |
1710 VERIFY_STREAM_HASHES |
1711 COMPUTE_MISSING_STREAM_HASHES);
1714 goto out_destroy_context;
1716 ret = finish_remaining_chunks(&ctx);
1718 goto out_destroy_context;
1720 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1721 struct wim_reshdr reshdr;
1722 struct wim_lookup_table_entry *lte;
1725 ret = end_write_resource(&ctx, &reshdr);
1727 goto out_destroy_context;
1729 DEBUG("Ending solid resource: %lu %lu %lu.",
1730 reshdr.offset_in_wim,
1732 reshdr.uncompressed_size);
1735 list_for_each_entry(lte, &ctx.solid_streams, write_streams_list) {
1736 lte->out_reshdr.size_in_wim = lte->size;
1737 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1738 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_SOLID;
1739 lte->out_reshdr.uncompressed_size = 0;
1740 lte->out_reshdr.offset_in_wim = offset_in_res;
1741 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1742 lte->out_res_size_in_wim = reshdr.size_in_wim;
1743 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1744 offset_in_res += lte->size;
1746 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1749 out_write_raw_copy_resources:
1750 /* Copy any compressed resources for which the raw data can be reused
1751 * without decompression. */
1752 ret = write_raw_copy_resources(&raw_copy_streams, ctx.out_fd,
1753 &ctx.progress_data);
1755 out_destroy_context:
1756 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1757 FREE(ctx.chunk_buf);
1758 FREE(ctx.chunk_csizes);
1760 ctx.compressor->destroy(ctx.compressor);
1761 DEBUG("Done (ret=%d)", ret);
1766 is_stream_in_solid_resource(struct wim_lookup_table_entry *lte, void *_ignore)
1768 return lte_is_partial(lte);
1772 wim_has_solid_resources(WIMStruct *wim)
1774 return for_lookup_table_entry(wim->lookup_table,
1775 is_stream_in_solid_resource, NULL);
1779 wim_write_stream_list(WIMStruct *wim,
1780 struct list_head *stream_list,
1782 unsigned num_threads,
1783 struct filter_context *filter_ctx)
1787 int write_resource_flags;
1789 write_resource_flags = write_flags_to_resource_flags(write_flags);
1791 /* wimlib v1.7.0: create a solid WIM file by default if the WIM version
1792 * has been set to WIM_VERSION_SOLID and at least one stream in the
1793 * WIM's lookup table is located in a solid resource (may be the same
1794 * WIM, or a different one in the case of export). */
1795 if (wim->hdr.wim_version == WIM_VERSION_SOLID &&
1796 wim_has_solid_resources(wim))
1798 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
1801 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1802 out_chunk_size = wim->out_solid_chunk_size;
1803 out_ctype = wim->out_solid_compression_type;
1805 out_chunk_size = wim->out_chunk_size;
1806 out_ctype = wim->out_compression_type;
1809 return write_stream_list(stream_list,
1811 write_resource_flags,
1822 write_wim_resource(struct wim_lookup_table_entry *lte,
1823 struct filedes *out_fd,
1826 int write_resource_flags)
1828 LIST_HEAD(stream_list);
1829 list_add(<e->write_streams_list, &stream_list);
1830 lte->will_be_in_output_wim = 1;
1831 return write_stream_list(&stream_list,
1833 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1844 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1845 int reshdr_flags, struct filedes *out_fd,
1848 struct wim_reshdr *out_reshdr,
1850 int write_resource_flags)
1853 struct wim_lookup_table_entry *lte;
1855 /* Set up a temporary lookup table entry to provide to
1856 * write_wim_resource(). */
1858 lte = new_lookup_table_entry();
1860 return WIMLIB_ERR_NOMEM;
1862 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1863 lte->attached_buffer = (void*)buf;
1864 lte->size = buf_size;
1865 lte->flags = reshdr_flags;
1867 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1868 sha1_buffer(buf, buf_size, lte->hash);
1874 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1875 write_resource_flags);
1879 copy_reshdr(out_reshdr, <e->out_reshdr);
1882 copy_hash(hash, lte->hash);
1885 lte->resource_location = RESOURCE_NONEXISTENT;
1886 free_lookup_table_entry(lte);
1890 struct stream_size_table {
1891 struct hlist_head *array;
1897 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1899 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1900 if (tab->array == NULL)
1901 return WIMLIB_ERR_NOMEM;
1902 tab->num_entries = 0;
1903 tab->capacity = capacity;
1908 destroy_stream_size_table(struct stream_size_table *tab)
1914 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1916 struct stream_size_table *tab = _tab;
1918 struct wim_lookup_table_entry *same_size_lte;
1919 struct hlist_node *tmp;
1921 pos = hash_u64(lte->size) % tab->capacity;
1922 lte->unique_size = 1;
1923 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1924 if (same_size_lte->size == lte->size) {
1925 lte->unique_size = 0;
1926 same_size_lte->unique_size = 0;
1931 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1936 struct find_streams_ctx {
1939 struct list_head stream_list;
1940 struct stream_size_table stream_size_tab;
1944 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1945 struct list_head *stream_list, u32 nref)
1947 if (!lte->will_be_in_output_wim) {
1948 lte->out_refcnt = 0;
1949 list_add_tail(<e->write_streams_list, stream_list);
1950 lte->will_be_in_output_wim = 1;
1952 lte->out_refcnt += nref;
1956 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1959 struct list_head *stream_list = _stream_list;
1960 lte->will_be_in_output_wim = 0;
1961 reference_stream_for_write(lte, stream_list, lte->refcnt);
1966 inode_find_streams_to_reference(const struct wim_inode *inode,
1967 const struct wim_lookup_table *table,
1968 struct list_head *stream_list)
1970 struct wim_lookup_table_entry *lte;
1973 wimlib_assert(inode->i_nlink > 0);
1975 for (i = 0; i <= inode->i_num_ads; i++) {
1976 lte = inode_stream_lte(inode, i, table);
1978 reference_stream_for_write(lte, stream_list,
1980 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1981 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1987 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1989 lte->will_be_in_output_wim = 0;
1994 image_find_streams_to_reference(WIMStruct *wim)
1996 struct wim_image_metadata *imd;
1997 struct wim_inode *inode;
1998 struct wim_lookup_table_entry *lte;
1999 struct list_head *stream_list;
2002 imd = wim_get_current_image_metadata(wim);
2004 image_for_each_unhashed_stream(lte, imd)
2005 lte->will_be_in_output_wim = 0;
2007 stream_list = wim->private;
2008 image_for_each_inode(inode, imd) {
2009 ret = inode_find_streams_to_reference(inode,
2019 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
2022 struct list_head *stream_list_ret)
2026 INIT_LIST_HEAD(stream_list_ret);
2028 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
2029 (image == 1 && wim->hdr.image_count == 1)))
2031 /* Fast case: Assume that all streams are being written and
2032 * that the reference counts are correct. */
2033 struct wim_lookup_table_entry *lte;
2034 struct wim_image_metadata *imd;
2037 for_lookup_table_entry(wim->lookup_table,
2038 fully_reference_stream_for_write,
2041 for (i = 0; i < wim->hdr.image_count; i++) {
2042 imd = wim->image_metadata[i];
2043 image_for_each_unhashed_stream(lte, imd)
2044 fully_reference_stream_for_write(lte, stream_list_ret);
2047 /* Slow case: Walk through the images being written and
2048 * determine the streams referenced. */
2049 for_lookup_table_entry(wim->lookup_table,
2050 do_stream_set_not_in_output_wim, NULL);
2051 wim->private = stream_list_ret;
2052 ret = for_image(wim, image, image_find_streams_to_reference);
2060 struct insert_other_if_hard_filtered_ctx {
2061 struct stream_size_table *tab;
2062 struct filter_context *filter_ctx;
2066 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
2068 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
2070 if (!lte->will_be_in_output_wim &&
2071 stream_hard_filtered(lte, ctx->filter_ctx))
2072 stream_size_table_insert(lte, ctx->tab);
2077 determine_stream_size_uniquity(struct list_head *stream_list,
2078 struct wim_lookup_table *lt,
2079 struct filter_context *filter_ctx)
2082 struct stream_size_table tab;
2083 struct wim_lookup_table_entry *lte;
2085 ret = init_stream_size_table(&tab, 9001);
2089 if (may_hard_filter_streams(filter_ctx)) {
2090 struct insert_other_if_hard_filtered_ctx ctx = {
2092 .filter_ctx = filter_ctx,
2094 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
2097 list_for_each_entry(lte, stream_list, write_streams_list)
2098 stream_size_table_insert(lte, &tab);
2100 destroy_stream_size_table(&tab);
2105 filter_stream_list_for_write(struct list_head *stream_list,
2106 struct filter_context *filter_ctx)
2108 struct wim_lookup_table_entry *lte, *tmp;
2110 list_for_each_entry_safe(lte, tmp,
2111 stream_list, write_streams_list)
2113 int status = stream_filtered(lte, filter_ctx);
2120 /* Soft filtered. */
2122 /* Hard filtered. */
2123 lte->will_be_in_output_wim = 0;
2124 list_del(<e->lookup_table_list);
2126 list_del(<e->write_streams_list);
2132 * prepare_stream_list_for_write() -
2134 * Prepare the list of streams to write for writing a WIM containing the
2135 * specified image(s) with the specified write flags.
2138 * The WIMStruct on whose behalf the write is occurring.
2141 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2144 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2146 * STREAMS_OK: For writes of all images, assume that all streams in the
2147 * lookup table of @wim and the per-image lists of unhashed streams should
2148 * be taken as-is, and image metadata should not be searched for
2149 * references. This does not exclude filtering with OVERWRITE and
2150 * SKIP_EXTERNAL_WIMS, below.
2152 * OVERWRITE: Streams already present in @wim shall not be returned in
2155 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
2156 * @wim, shall be returned in neither @stream_list_ret nor
2157 * @lookup_table_list_ret.
2160 * List of streams, linked by write_streams_list, that need to be written
2161 * will be returned here.
2163 * Note that this function assumes that unhashed streams will be written;
2164 * it does not take into account that they may become duplicates when
2167 * @lookup_table_list_ret
2168 * List of streams, linked by lookup_table_list, that need to be included
2169 * in the WIM's lookup table will be returned here. This will be a
2170 * superset of the streams in @stream_list_ret.
2172 * This list will be a proper superset of @stream_list_ret if and only if
2173 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2174 * the streams that would otherwise need to be written were already located
2177 * All streams in this list will have @out_refcnt set to the number of
2178 * references to the stream in the output WIM. If
2179 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2180 * may be as low as 0.
2183 * A context for queries of stream filter status with stream_filtered() is
2184 * returned in this location.
2186 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
2187 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
2188 * lookup table of @wim not inserted into @lookup_table_list_ret.
2190 * Still furthermore, @unique_size will be set to 1 on all stream entries in
2191 * @stream_list_ret that have unique size among all stream entries in
2192 * @stream_list_ret and among all stream entries in the lookup table of @wim
2193 * that are ineligible for being written due to filtering.
2195 * Returns 0 on success; nonzero on read error, memory allocation error, or
2199 prepare_stream_list_for_write(WIMStruct *wim, int image,
2201 struct list_head *stream_list_ret,
2202 struct list_head *lookup_table_list_ret,
2203 struct filter_context *filter_ctx_ret)
2206 struct wim_lookup_table_entry *lte;
2208 filter_ctx_ret->write_flags = write_flags;
2209 filter_ctx_ret->wim = wim;
2211 ret = prepare_unfiltered_list_of_streams_in_output_wim(
2214 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2219 INIT_LIST_HEAD(lookup_table_list_ret);
2220 list_for_each_entry(lte, stream_list_ret, write_streams_list)
2221 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2223 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
2228 if (may_filter_streams(filter_ctx_ret))
2229 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2235 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2236 unsigned num_threads,
2237 struct list_head *stream_list_override,
2238 struct list_head *lookup_table_list_ret)
2241 struct list_head _stream_list;
2242 struct list_head *stream_list;
2243 struct wim_lookup_table_entry *lte;
2244 struct filter_context _filter_ctx;
2245 struct filter_context *filter_ctx;
2247 if (stream_list_override == NULL) {
2248 /* Normal case: prepare stream list from image(s) being written.
2250 stream_list = &_stream_list;
2251 filter_ctx = &_filter_ctx;
2252 ret = prepare_stream_list_for_write(wim, image, write_flags,
2254 lookup_table_list_ret,
2259 /* Currently only as a result of wimlib_split() being called:
2260 * use stream list already explicitly provided. Use existing
2261 * reference counts. */
2262 stream_list = stream_list_override;
2264 INIT_LIST_HEAD(lookup_table_list_ret);
2265 list_for_each_entry(lte, stream_list, write_streams_list) {
2266 lte->out_refcnt = lte->refcnt;
2267 lte->will_be_in_output_wim = 1;
2268 lte->unique_size = 0;
2269 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2273 return wim_write_stream_list(wim,
2281 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags)
2286 int write_resource_flags;
2288 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2289 DEBUG("Not writing any metadata resources.");
2293 write_resource_flags = write_flags_to_resource_flags(write_flags);
2295 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2297 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2298 wim->out_fd.offset);
2300 ret = call_progress(wim->progfunc,
2301 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2302 NULL, wim->progctx);
2306 if (image == WIMLIB_ALL_IMAGES) {
2308 end_image = wim->hdr.image_count;
2310 start_image = image;
2314 for (int i = start_image; i <= end_image; i++) {
2315 struct wim_image_metadata *imd;
2317 imd = wim->image_metadata[i - 1];
2318 /* Build a new metadata resource only if image was modified from
2319 * the original (or was newly added). Otherwise just copy the
2321 if (imd->modified) {
2322 DEBUG("Image %u was modified; building and writing new "
2323 "metadata resource", i);
2324 ret = write_metadata_resource(wim, i,
2325 write_resource_flags);
2326 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2327 DEBUG("Image %u was not modified; re-using existing "
2328 "metadata resource.", i);
2329 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2332 DEBUG("Image %u was not modified; copying existing "
2333 "metadata resource.", i);
2334 ret = write_wim_resource(imd->metadata_lte,
2336 wim->out_compression_type,
2337 wim->out_chunk_size,
2338 write_resource_flags);
2344 return call_progress(wim->progfunc,
2345 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2346 NULL, wim->progctx);
2350 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2353 DEBUG("Opening \"%"TS"\" for writing.", path);
2355 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2357 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2358 return WIMLIB_ERR_OPEN;
2360 filedes_init(&wim->out_fd, raw_fd);
2365 close_wim_writable(WIMStruct *wim, int write_flags)
2369 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2370 DEBUG("Closing WIM file.");
2371 if (filedes_valid(&wim->out_fd))
2372 if (filedes_close(&wim->out_fd))
2373 ret = WIMLIB_ERR_WRITE;
2375 filedes_invalidate(&wim->out_fd);
2380 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2382 const struct wim_lookup_table_entry *lte1, *lte2;
2384 lte1 = *(const struct wim_lookup_table_entry**)p1;
2385 lte2 = *(const struct wim_lookup_table_entry**)p2;
2387 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2388 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2389 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2390 return cmp_u64(lte1->out_res_offset_in_wim,
2391 lte2->out_res_offset_in_wim);
2396 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2399 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2400 lte2->out_reshdr.offset_in_wim);
2404 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2405 struct wim_reshdr *out_reshdr,
2406 struct list_head *lookup_table_list)
2410 /* Set output resource metadata for streams already present in WIM. */
2411 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2412 struct wim_lookup_table_entry *lte;
2413 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2415 if (lte->resource_location == RESOURCE_IN_WIM &&
2416 lte->rspec->wim == wim)
2418 stream_set_out_reshdr_for_reuse(lte);
2423 ret = sort_stream_list(lookup_table_list,
2424 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2425 cmp_streams_by_out_rspec);
2429 /* Add entries for metadata resources. */
2430 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2434 if (image == WIMLIB_ALL_IMAGES) {
2436 end_image = wim->hdr.image_count;
2438 start_image = image;
2442 /* Push metadata resource lookup table entries onto the front of
2443 * the list in reverse order, so that they're written in order.
2445 for (int i = end_image; i >= start_image; i--) {
2446 struct wim_lookup_table_entry *metadata_lte;
2448 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2449 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2450 metadata_lte->out_refcnt = 1;
2451 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2455 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2457 wim->hdr.part_number,
2459 write_flags_to_resource_flags(write_flags));
2465 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2466 * table, then overwrite the WIM header. By default, closes the WIM file
2467 * descriptor (@wim->out_fd) if successful.
2469 * write_flags is a bitwise OR of the following:
2471 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2472 * Include an integrity table.
2474 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2475 * fsync() the output file before closing it.
2477 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2478 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2479 * stream headers before the lookup table and XML data, and also
2480 * write the WIM header at the end instead of seeking to the
2481 * beginning. Can't be combined with
2482 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2484 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2485 * Don't write the lookup table.
2487 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2488 * After writing the XML data but before writing the integrity
2489 * table, write a temporary WIM header and flush the stream so that
2490 * the WIM is less likely to become corrupted upon abrupt program
2492 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2493 * Instead of overwriting the WIM header at the beginning of the
2494 * file, simply append it to the end of the file. (Used when
2496 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2497 * Do not close the file descriptor @wim->out_fd on either success
2499 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2500 * Use the existing <TOTALBYTES> stored in the in-memory XML
2501 * information, rather than setting it to the offset of the XML
2502 * data being written.
2503 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2504 * The existing WIM file is being updated in-place. The entries
2505 * from its integrity table may be re-used.
2508 finish_write(WIMStruct *wim, int image, int write_flags,
2509 struct list_head *lookup_table_list)
2513 int write_resource_flags;
2514 off_t old_lookup_table_end = 0;
2515 off_t new_lookup_table_end;
2517 struct integrity_table *old_integrity_table = NULL;
2519 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2521 write_resource_flags = write_flags_to_resource_flags(write_flags);
2523 /* In the WIM header, there is room for the resource entry for a
2524 * metadata resource labeled as the "boot metadata". This entry should
2525 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2526 * it should be a copy of the resource entry for the image that is
2527 * marked as bootable. This is not well documented... */
2528 if (wim->hdr.boot_idx == 0) {
2529 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2531 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2532 &wim->image_metadata[
2533 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2536 /* If overwriting the WIM file containing an integrity table in-place,
2537 * we'd like to re-use the information in the old integrity table
2538 * instead of recalculating it. But we might overwrite the old
2539 * integrity table when we expand the XML data. Read it into memory
2541 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2542 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2543 (WIMLIB_WRITE_FLAG_OVERWRITE |
2544 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2545 && wim_has_integrity_table(wim))
2547 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2548 wim->hdr.lookup_table_reshdr.size_in_wim;
2549 (void)read_integrity_table(wim,
2550 old_lookup_table_end - WIM_HEADER_DISK_SIZE,
2551 &old_integrity_table);
2552 /* If we couldn't read the old integrity table, we can still
2553 * re-calculate the full integrity table ourselves. Hence the
2554 * ignoring of the return value. */
2557 /* Write lookup table. */
2558 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2559 ret = write_wim_lookup_table(wim, image, write_flags,
2560 &wim->hdr.lookup_table_reshdr,
2563 free_integrity_table(old_integrity_table);
2568 /* Write XML data. */
2569 xml_totalbytes = wim->out_fd.offset;
2570 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2571 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2572 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2573 &wim->hdr.xml_data_reshdr,
2574 write_resource_flags);
2576 free_integrity_table(old_integrity_table);
2580 /* Write integrity table (optional). */
2581 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2582 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2583 struct wim_header checkpoint_hdr;
2584 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2585 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2586 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2587 ret = write_wim_header_at_offset(&checkpoint_hdr,
2590 free_integrity_table(old_integrity_table);
2595 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2596 wim->hdr.lookup_table_reshdr.size_in_wim;
2598 ret = write_integrity_table(wim,
2599 new_lookup_table_end,
2600 old_lookup_table_end,
2601 old_integrity_table);
2602 free_integrity_table(old_integrity_table);
2606 /* No integrity table. */
2607 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2610 /* Now that all information in the WIM header has been determined, the
2611 * preliminary header written earlier can be overwritten, the header of
2612 * the existing WIM file can be overwritten, or the final header can be
2613 * written to the end of the pipable WIM. */
2614 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2616 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2617 hdr_offset = wim->out_fd.offset;
2618 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2619 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2623 /* Possibly sync file data to disk before closing. On POSIX systems, it
2624 * is necessary to do this before using rename() to overwrite an
2625 * existing file with a new file. Otherwise, data loss would occur if
2626 * the system is abruptly terminated when the metadata for the rename
2627 * operation has been written to disk, but the new file data has not.
2629 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2630 DEBUG("Syncing WIM file.");
2631 if (fsync(wim->out_fd.fd)) {
2632 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2633 return WIMLIB_ERR_WRITE;
2637 if (close_wim_writable(wim, write_flags)) {
2638 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2639 return WIMLIB_ERR_WRITE;
2645 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2647 /* Set advisory lock on WIM file (if not already done so) */
2649 lock_wim_for_append(WIMStruct *wim)
2651 if (wim->locked_for_append)
2653 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2654 wim->locked_for_append = 1;
2657 if (errno != EWOULDBLOCK)
2659 return WIMLIB_ERR_ALREADY_LOCKED;
2662 /* Remove advisory lock on WIM file (if present) */
2664 unlock_wim_for_append(WIMStruct *wim)
2666 if (wim->locked_for_append) {
2667 flock(wim->in_fd.fd, LOCK_UN);
2668 wim->locked_for_append = 0;
2674 * write_pipable_wim():
2676 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2677 * capable of being applied from a pipe).
2679 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2680 * images can be applied from them sequentially when the file data is sent over
2681 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2682 * The modifications made to the WIM format for pipable WIMs are:
2684 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2685 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2686 * stops other software from trying to read the file as a normal WIM.
2688 * - The header at the beginning of the file does not contain all the normal
2689 * information; in particular it will have all 0's for the lookup table and
2690 * XML data resource entries. This is because this information cannot be
2691 * determined until the lookup table and XML data have been written.
2692 * Consequently, wimlib will write the full header at the very end of the
2693 * file. The header at the end, however, is only used when reading the WIM
2694 * from a seekable file (not a pipe).
2696 * - An extra copy of the XML data is placed directly after the header. This
2697 * allows image names and sizes to be determined at an appropriate time when
2698 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2699 * WIM is read from a seekable file (not a pipe).
2701 * - The format of resources, or streams, has been modified to allow them to be
2702 * used before the "lookup table" has been read. Each stream is prefixed with
2703 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2704 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2705 * uncompressed stream size, and flags that indicate whether the stream is
2706 * compressed. The data of uncompressed streams then follows literally, while
2707 * the data of compressed streams follows in a modified format. Compressed
2708 * streams do not begin with a chunk table, since the chunk table cannot be
2709 * written until all chunks have been compressed. Instead, each compressed
2710 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2711 * Furthermore, the chunk table is written at the end of the resource instead
2712 * of the start. Note: chunk offsets are given in the chunk table as if the
2713 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2714 * used if the WIM is being read from a seekable file (not a pipe).
2716 * - Metadata resources always come before other file resources (streams).
2717 * (This does not by itself constitute an incompatibility with normal WIMs,
2718 * since this is valid in normal WIMs.)
2720 * - At least up to the end of the file resources, all components must be packed
2721 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2722 * not by itself consititute an incompatibility with normal WIMs, since this
2723 * is valid in normal WIMs.)
2725 * Note: the lookup table, XML data, and header at the end are not used when
2726 * applying from a pipe. They exist to support functionality such as image
2727 * application and export when the WIM is *not* read from a pipe.
2729 * Layout of pipable WIM:
2731 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2732 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2733 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2735 * Layout of normal WIM:
2737 * +--------+-----------------------------+-------------------------+
2738 * | Header | File and metadata resources | Lookup table | XML data |
2739 * +--------+-----------------------------+-------------------------+
2741 * An optional integrity table can follow the final XML data in both normal and
2742 * pipable WIMs. However, due to implementation details, wimlib currently can
2743 * only include an integrity table in a pipable WIM when writing it to a
2744 * seekable file (not a pipe).
2746 * Do note that since pipable WIMs are not supported by Microsoft's software,
2747 * wimlib does not create them unless explicitly requested (with
2748 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2749 * characters to identify the file.
2752 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2753 unsigned num_threads,
2754 struct list_head *stream_list_override,
2755 struct list_head *lookup_table_list_ret)
2758 struct wim_reshdr xml_reshdr;
2760 WARNING("Creating a pipable WIM, which will "
2762 " with Microsoft's software (wimgapi/imagex/Dism).");
2764 /* At this point, the header at the beginning of the file has already
2767 /* For efficiency, when wimlib adds an image to the WIM with
2768 * wimlib_add_image(), the SHA1 message digests of files is not
2769 * calculated; instead, they are calculated while the files are being
2770 * written. However, this does not work when writing a pipable WIM,
2771 * since when writing a stream to a pipable WIM, its SHA1 message digest
2772 * needs to be known before the stream data is written. Therefore,
2773 * before getting much farther, we need to pre-calculate the SHA1
2774 * message digests of all streams that will be written. */
2775 ret = wim_checksum_unhashed_streams(wim);
2779 /* Write extra copy of the XML data. */
2780 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2782 WRITE_RESOURCE_FLAG_PIPABLE);
2786 /* Write metadata resources for the image(s) being included in the
2788 ret = write_wim_metadata_resources(wim, image, write_flags);
2792 /* Write streams needed for the image(s) being included in the output
2793 * WIM, or streams needed for the split WIM part. */
2794 return write_wim_streams(wim, image, write_flags, num_threads,
2795 stream_list_override, lookup_table_list_ret);
2797 /* The lookup table, XML data, and header at end are handled by
2798 * finish_write(). */
2801 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2804 write_wim_part(WIMStruct *wim,
2805 const void *path_or_fd,
2808 unsigned num_threads,
2809 unsigned part_number,
2810 unsigned total_parts,
2811 struct list_head *stream_list_override,
2815 struct wim_header hdr_save;
2816 struct list_head lookup_table_list;
2818 if (total_parts == 1)
2819 DEBUG("Writing standalone WIM.");
2821 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2822 if (image == WIMLIB_ALL_IMAGES)
2823 DEBUG("Including all images.");
2825 DEBUG("Including image %d only.", image);
2826 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2827 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2829 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2830 DEBUG("Write flags: 0x%08x", write_flags);
2832 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2833 DEBUG("\tCHECK_INTEGRITY");
2835 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2836 DEBUG("\tNO_CHECK_INTEGRITY");
2838 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2841 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2842 DEBUG("\tNOT_PIPABLE");
2844 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2845 DEBUG("\tRECOMPRESS");
2847 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2850 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2853 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2854 DEBUG("\tSOFT_DELETE");
2856 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2857 DEBUG("\tIGNORE_READONLY_FLAG");
2859 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2860 DEBUG("\tSKIP_EXTERNAL_WIMS");
2862 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2863 DEBUG("\tSTREAMS_OK");
2865 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2866 DEBUG("\tRETAIN_GUID");
2868 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2871 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2872 DEBUG("\tFILE_DESCRIPTOR");
2874 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2875 DEBUG("\tNO_METADATA");
2877 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2878 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2880 if (num_threads == 0)
2881 DEBUG("Number of threads: autodetect");
2883 DEBUG("Number of threads: %u", num_threads);
2884 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2885 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2886 DEBUG("GUID: %s", (write_flags &
2887 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2888 : guid ? "explicit" : "generate new");
2890 /* Internally, this is always called with a valid part number and total
2892 wimlib_assert(total_parts >= 1);
2893 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2895 /* A valid image (or all images) must be specified. */
2896 if (image != WIMLIB_ALL_IMAGES &&
2897 (image < 1 || image > wim->hdr.image_count))
2898 return WIMLIB_ERR_INVALID_IMAGE;
2900 /* If we need to write metadata resources, make sure the ::WIMStruct has
2901 * the needed information attached (e.g. is not a resource-only WIM,
2902 * such as a non-first part of a split WIM). */
2903 if (!wim_has_metadata(wim) &&
2904 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2905 return WIMLIB_ERR_METADATA_NOT_FOUND;
2907 /* Check for contradictory flags. */
2908 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2909 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2910 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2911 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2912 return WIMLIB_ERR_INVALID_PARAM;
2914 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2915 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2916 == (WIMLIB_WRITE_FLAG_PIPABLE |
2917 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2918 return WIMLIB_ERR_INVALID_PARAM;
2920 /* Save previous header, then start initializing the new one. */
2921 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2923 /* Set default integrity, pipable, and solid flags. */
2924 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2925 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2926 if (wim_is_pipable(wim)) {
2927 DEBUG("WIM is pipable; default to PIPABLE.");
2928 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2931 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2932 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2933 if (wim_has_integrity_table(wim)) {
2934 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2935 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2938 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2939 WIMLIB_WRITE_FLAG_SOLID))
2940 == (WIMLIB_WRITE_FLAG_PIPABLE |
2941 WIMLIB_WRITE_FLAG_SOLID))
2943 ERROR("Cannot specify both PIPABLE and SOLID!");
2944 return WIMLIB_ERR_INVALID_PARAM;
2947 /* Set appropriate magic number. */
2948 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2949 wim->hdr.magic = PWM_MAGIC;
2951 wim->hdr.magic = WIM_MAGIC;
2953 /* Set appropriate version number. */
2954 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2955 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2956 wim->hdr.wim_version = WIM_VERSION_SOLID;
2958 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2960 /* Clear header flags that will be set automatically. */
2961 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2962 WIM_HDR_FLAG_RESOURCE_ONLY |
2963 WIM_HDR_FLAG_SPANNED |
2964 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2966 /* Set SPANNED header flag if writing part of a split WIM. */
2967 if (total_parts != 1)
2968 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2970 /* Set part number and total parts of split WIM. This will be 1 and 1
2971 * if the WIM is standalone. */
2972 wim->hdr.part_number = part_number;
2973 wim->hdr.total_parts = total_parts;
2975 /* Set compression type if different. */
2976 if (wim->compression_type != wim->out_compression_type) {
2977 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2978 wimlib_assert(ret == 0);
2981 /* Set chunk size if different. */
2982 wim->hdr.chunk_size = wim->out_chunk_size;
2985 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2987 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2989 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2992 /* Clear references to resources that have not been written yet. */
2993 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2994 zero_reshdr(&wim->hdr.xml_data_reshdr);
2995 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2996 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2998 /* Set image count and boot index correctly for single image writes. */
2999 if (image != WIMLIB_ALL_IMAGES) {
3000 wim->hdr.image_count = 1;
3001 if (wim->hdr.boot_idx == image)
3002 wim->hdr.boot_idx = 1;
3004 wim->hdr.boot_idx = 0;
3007 /* Split WIMs can't be bootable. */
3008 if (total_parts != 1)
3009 wim->hdr.boot_idx = 0;
3011 /* Initialize output file descriptor. */
3012 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
3013 /* File descriptor was explicitly provided. Return error if
3014 * file descriptor is not seekable, unless writing a pipable WIM
3016 wim->out_fd.fd = *(const int*)path_or_fd;
3017 wim->out_fd.offset = 0;
3018 if (!filedes_is_seekable(&wim->out_fd)) {
3019 ret = WIMLIB_ERR_INVALID_PARAM;
3020 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3021 goto out_restore_hdr;
3022 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
3023 ERROR("Can't include integrity check when "
3024 "writing pipable WIM to pipe!");
3025 goto out_restore_hdr;
3030 /* Filename of WIM to write was provided; open file descriptor
3032 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
3033 O_TRUNC | O_CREAT | O_RDWR);
3035 goto out_restore_hdr;
3038 /* Write initial header. This is merely a "dummy" header since it
3039 * doesn't have all the information yet, so it will be overwritten later
3040 * (unless writing a pipable WIM). */
3041 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3042 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3043 ret = write_wim_header(&wim->hdr, &wim->out_fd);
3044 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3046 goto out_restore_hdr;
3048 /* Write metadata resources and streams. */
3049 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
3050 /* Default case: create a normal (non-pipable) WIM. */
3051 ret = write_wim_streams(wim, image, write_flags, num_threads,
3052 stream_list_override,
3053 &lookup_table_list);
3055 goto out_restore_hdr;
3057 ret = write_wim_metadata_resources(wim, image, write_flags);
3059 goto out_restore_hdr;
3061 /* Non-default case: create pipable WIM. */
3062 ret = write_pipable_wim(wim, image, write_flags, num_threads,
3063 stream_list_override,
3064 &lookup_table_list);
3066 goto out_restore_hdr;
3067 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
3071 /* Write lookup table, XML data, and (optional) integrity table. */
3072 ret = finish_write(wim, image, write_flags, &lookup_table_list);
3074 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3075 (void)close_wim_writable(wim, write_flags);
3076 DEBUG("ret=%d", ret);
3080 /* Write a standalone WIM to a file or file descriptor. */
3082 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
3083 int image, int write_flags, unsigned num_threads)
3085 return write_wim_part(wim, path_or_fd, image, write_flags,
3086 num_threads, 1, 1, NULL, NULL);
3089 /* API function documented in wimlib.h */
3091 wimlib_write(WIMStruct *wim, const tchar *path,
3092 int image, int write_flags, unsigned num_threads)
3094 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3095 return WIMLIB_ERR_INVALID_PARAM;
3097 if (path == NULL || path[0] == T('\0'))
3098 return WIMLIB_ERR_INVALID_PARAM;
3100 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3103 /* API function documented in wimlib.h */
3105 wimlib_write_to_fd(WIMStruct *wim, int fd,
3106 int image, int write_flags, unsigned num_threads)
3108 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3109 return WIMLIB_ERR_INVALID_PARAM;
3112 return WIMLIB_ERR_INVALID_PARAM;
3114 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3116 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3120 any_images_modified(WIMStruct *wim)
3122 for (int i = 0; i < wim->hdr.image_count; i++)
3123 if (wim->image_metadata[i]->modified)
3129 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
3131 const WIMStruct *wim = _wim;
3132 off_t end_offset = *(const off_t*)wim->private;
3134 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
3135 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
3136 return WIMLIB_ERR_RESOURCE_ORDER;
3140 /* Make sure no file or metadata resources are located after the XML data (or
3141 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3142 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3144 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3149 wim->private = &end_offset;
3150 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
3154 for (i = 0; i < wim->hdr.image_count; i++) {
3155 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
3163 * Overwrite a WIM, possibly appending streams to it.
3165 * A WIM looks like (or is supposed to look like) the following:
3167 * Header (212 bytes)
3168 * Streams and metadata resources (variable size)
3169 * Lookup table (variable size)
3170 * XML data (variable size)
3171 * Integrity table (optional) (variable size)
3173 * If we are not adding any streams or metadata resources, the lookup table is
3174 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3175 * header. This operation is potentially unsafe if the program is abruptly
3176 * terminated while the XML data or integrity table are being overwritten, but
3177 * before the new header has been written. To partially alleviate this problem,
3178 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3179 * finish_write() to cause a temporary WIM header to be written after the XML
3180 * data has been written. This may prevent the WIM from becoming corrupted if
3181 * the program is terminated while the integrity table is being calculated (but
3182 * no guarantees, due to write re-ordering...).
3184 * If we are adding new streams or images (metadata resources), the lookup table
3185 * needs to be changed, and those streams need to be written. In this case, we
3186 * try to perform a safe update of the WIM file by writing the streams *after*
3187 * the end of the previous WIM, then writing the new lookup table, XML data, and
3188 * (optionally) integrity table following the new streams. This will produce a
3189 * layout like the following:
3191 * Header (212 bytes)
3192 * (OLD) Streams and metadata resources (variable size)
3193 * (OLD) Lookup table (variable size)
3194 * (OLD) XML data (variable size)
3195 * (OLD) Integrity table (optional) (variable size)
3196 * (NEW) Streams and metadata resources (variable size)
3197 * (NEW) Lookup table (variable size)
3198 * (NEW) XML data (variable size)
3199 * (NEW) Integrity table (optional) (variable size)
3201 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3202 * the header is overwritten to point to the new lookup table, XML data, and
3203 * integrity table, to produce the following layout:
3205 * Header (212 bytes)
3206 * Streams and metadata resources (variable size)
3207 * Nothing (variable size)
3208 * More Streams and metadata resources (variable size)
3209 * Lookup table (variable size)
3210 * XML data (variable size)
3211 * Integrity table (optional) (variable size)
3213 * This method allows an image to be appended to a large WIM very quickly, and
3214 * is crash-safe except in the case of write re-ordering, but the
3215 * disadvantage is that a small hole is left in the WIM where the old lookup
3216 * table, xml data, and integrity table were. (These usually only take up a
3217 * small amount of space compared to the streams, however.)
3220 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3224 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
3225 struct wim_header hdr_save;
3226 struct list_head stream_list;
3227 struct list_head lookup_table_list;
3228 struct filter_context filter_ctx;
3230 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3232 /* Save original header so it can be restored in case of error */
3233 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3235 /* Set default integrity flag. */
3236 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3237 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3238 if (wim_has_integrity_table(wim))
3239 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3241 /* Set WIM version if writing solid resources. */
3242 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
3243 wim->hdr.wim_version = WIM_VERSION_SOLID;
3245 /* Set additional flags for overwrite. */
3246 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3247 WIMLIB_WRITE_FLAG_STREAMS_OK;
3249 /* Make sure that the integrity table (if present) is after the XML
3250 * data, and that there are no stream resources, metadata resources, or
3251 * lookup tables after the XML data. Otherwise, these data would be
3253 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3254 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3255 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
3256 wim->hdr.lookup_table_reshdr.size_in_wim;
3257 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3258 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3259 WARNING("Didn't expect the integrity table to be before the XML data");
3260 ret = WIMLIB_ERR_RESOURCE_ORDER;
3261 goto out_restore_memory_hdr;
3264 if (old_lookup_table_end > old_xml_begin) {
3265 WARNING("Didn't expect the lookup table to be after the XML data");
3266 ret = WIMLIB_ERR_RESOURCE_ORDER;
3267 goto out_restore_memory_hdr;
3270 /* Set @old_wim_end, which indicates the point beyond which we don't
3271 * allow any file and metadata resources to appear without returning
3272 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3273 * overwrite these resources). */
3274 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
3275 /* If no images have been modified and no images have been
3276 * deleted, a new lookup table does not need to be written. We
3277 * shall write the new XML data and optional integrity table
3278 * immediately after the lookup table. Note that this may
3279 * overwrite an existing integrity table. */
3280 DEBUG("Skipping writing lookup table "
3281 "(no images modified or deleted)");
3282 old_wim_end = old_lookup_table_end;
3283 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3284 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3285 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3286 /* Old WIM has an integrity table; begin writing new streams
3288 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3289 wim->hdr.integrity_table_reshdr.size_in_wim;
3291 /* No existing integrity table; begin writing new streams after
3292 * the old XML data. */
3293 old_wim_end = old_xml_end;
3296 ret = check_resource_offsets(wim, old_wim_end);
3298 goto out_restore_memory_hdr;
3300 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3301 &stream_list, &lookup_table_list,
3304 goto out_restore_memory_hdr;
3306 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3308 goto out_restore_memory_hdr;
3310 ret = lock_wim_for_append(wim);
3314 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3315 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3316 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3318 ERROR_WITH_ERRNO("Error updating WIM header flags");
3319 goto out_unlock_wim;
3322 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3323 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3324 ret = WIMLIB_ERR_WRITE;
3325 goto out_restore_physical_hdr;
3328 ret = wim_write_stream_list(wim,
3336 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3340 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3341 &lookup_table_list);
3345 unlock_wim_for_append(wim);
3349 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3350 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3351 wim->filename, old_wim_end);
3352 /* Return value of ftruncate() is ignored because this is
3353 * already an error path. */
3354 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3356 out_restore_physical_hdr:
3357 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3359 unlock_wim_for_append(wim);
3361 (void)close_wim_writable(wim, write_flags);
3362 out_restore_memory_hdr:
3363 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3368 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3370 size_t wim_name_len;
3373 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3375 /* Write the WIM to a temporary file in the same directory as the
3377 wim_name_len = tstrlen(wim->filename);
3378 tchar tmpfile[wim_name_len + 10];
3379 tmemcpy(tmpfile, wim->filename, wim_name_len);
3380 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3381 tmpfile[wim_name_len + 9] = T('\0');
3383 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3385 WIMLIB_WRITE_FLAG_FSYNC |
3386 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3393 if (filedes_valid(&wim->in_fd)) {
3394 filedes_close(&wim->in_fd);
3395 filedes_invalidate(&wim->in_fd);
3398 /* Rename the new WIM file to the original WIM file. Note: on Windows
3399 * this actually calls win32_rename_replacement(), not _wrename(), so
3400 * that removing the existing destination file can be handled. */
3401 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3402 ret = trename(tmpfile, wim->filename);
3404 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3405 tmpfile, wim->filename);
3412 return WIMLIB_ERR_RENAME;
3415 union wimlib_progress_info progress;
3416 progress.rename.from = tmpfile;
3417 progress.rename.to = wim->filename;
3418 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3419 &progress, wim->progctx);
3422 /* Determine if the specified WIM file may be updated by appending in-place
3423 * rather than writing and replacing it with an entirely new file. */
3425 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3427 /* REBUILD flag forces full rebuild. */
3428 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3431 /* Image deletions cause full rebuild by default. */
3432 if (wim->image_deletion_occurred &&
3433 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3436 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3437 * turned into a pipable WIM in-place. */
3438 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3441 /* The default compression type and compression chunk size selected for
3442 * the output WIM must be the same as those currently used for the WIM.
3444 if (wim->compression_type != wim->out_compression_type)
3446 if (wim->chunk_size != wim->out_chunk_size)
3452 /* API function documented in wimlib.h */
3454 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3459 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3460 return WIMLIB_ERR_INVALID_PARAM;
3463 return WIMLIB_ERR_NO_FILENAME;
3465 orig_hdr_flags = wim->hdr.flags;
3466 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3467 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3468 ret = can_modify_wim(wim);
3469 wim->hdr.flags = orig_hdr_flags;
3473 if (can_overwrite_wim_inplace(wim, write_flags)) {
3474 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3475 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3477 WARNING("Falling back to re-building entire WIM");
3479 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);