4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
11 * This file is free software; you can redistribute it and/or modify it under
12 * the terms of the GNU Lesser General Public License as published by the Free
13 * Software Foundation; either version 3 of the License, or (at your option) any
16 * This file is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this file; if not, see http://www.gnu.org/licenses/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
31 * overwrite the LIST_HEAD macro. */
32 # include <sys/file.h>
40 #include "wimlib/alloca.h"
41 #include "wimlib/assert.h"
42 #include "wimlib/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 /* A buffer of size @out_chunk_size that has been loaned out from the
383 * chunk compressor and is currently being filled with the uncompressed
384 * data of the next chunk. */
387 /* Number of bytes in @cur_chunk_buf that are currently filled. */
388 size_t cur_chunk_buf_filled;
390 /* List of streams that currently have chunks being compressed. */
391 struct list_head pending_streams;
393 /* List of streams in the solid resource. Streams are moved here after
394 * @pending_streams only when writing a solid resource. */
395 struct list_head solid_streams;
397 /* Current uncompressed offset in the stream being read. */
398 u64 cur_read_stream_offset;
400 /* Uncompressed size of the stream currently being read. */
401 u64 cur_read_stream_size;
403 /* Current uncompressed offset in the stream being written. */
404 u64 cur_write_stream_offset;
406 /* Uncompressed size of resource currently being written. */
407 u64 cur_write_res_size;
409 /* Array that is filled in with compressed chunk sizes as a resource is
413 /* Index of next entry in @chunk_csizes to fill in. */
416 /* Number of entries in @chunk_csizes currently allocated. */
417 size_t num_alloc_chunks;
419 /* Offset in the output file of the start of the chunks of the resource
420 * currently being written. */
421 u64 chunks_start_offset;
424 /* Reserve space for the chunk table and prepare to accumulate the chunk table
427 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
429 u64 expected_num_chunks;
430 u64 expected_num_chunk_entries;
434 /* Calculate the number of chunks and chunk entries that should be
435 * needed for the resource. These normally will be the final values,
436 * but in SOLID mode some of the streams we're planning to write into
437 * the resource may be duplicates, and therefore discarded, potentially
438 * decreasing the number of chunk entries needed. */
439 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
440 expected_num_chunk_entries = expected_num_chunks;
441 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
442 expected_num_chunk_entries--;
444 /* Make sure the chunk_csizes array is long enough to store the
445 * compressed size of each chunk. */
446 if (expected_num_chunks > ctx->num_alloc_chunks) {
447 u64 new_length = expected_num_chunks + 50;
449 if ((size_t)new_length != new_length) {
450 ERROR("Resource size too large (%"PRIu64" bytes!",
452 return WIMLIB_ERR_NOMEM;
455 FREE(ctx->chunk_csizes);
456 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
457 if (ctx->chunk_csizes == NULL) {
458 ctx->num_alloc_chunks = 0;
459 return WIMLIB_ERR_NOMEM;
461 ctx->num_alloc_chunks = new_length;
464 ctx->chunk_index = 0;
466 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
467 /* Reserve space for the chunk table in the output file. In the
468 * case of solid resources this reserves the upper bound for the
469 * needed space, not necessarily the exact space which will
470 * prove to be needed. At this point, we just use @chunk_csizes
471 * for a buffer of 0's because the actual compressed chunk sizes
473 reserve_size = expected_num_chunk_entries *
474 get_chunk_entry_size(res_expected_size,
475 0 != (ctx->write_resource_flags &
476 WRITE_RESOURCE_FLAG_SOLID));
477 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
478 reserve_size += sizeof(struct alt_chunk_table_header_disk);
479 memset(ctx->chunk_csizes, 0, reserve_size);
480 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
488 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
492 wimlib_assert(res_expected_size != 0);
494 if (ctx->compressor != NULL) {
495 ret = begin_chunk_table(ctx, res_expected_size);
500 /* Output file descriptor is now positioned at the offset at which to
501 * write the first chunk of the resource. */
502 ctx->chunks_start_offset = ctx->out_fd->offset;
503 ctx->cur_write_stream_offset = 0;
504 ctx->cur_write_res_size = res_expected_size;
509 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
510 u64 *res_start_offset_ret, u64 *res_store_size_ret)
512 size_t actual_num_chunks;
513 size_t actual_num_chunk_entries;
514 size_t chunk_entry_size;
517 actual_num_chunks = ctx->chunk_index;
518 actual_num_chunk_entries = actual_num_chunks;
519 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
520 actual_num_chunk_entries--;
522 chunk_entry_size = get_chunk_entry_size(res_actual_size,
523 0 != (ctx->write_resource_flags &
524 WRITE_RESOURCE_FLAG_SOLID));
526 typedef le64 _may_alias_attribute aliased_le64_t;
527 typedef le32 _may_alias_attribute aliased_le32_t;
529 if (chunk_entry_size == 4) {
530 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
532 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
533 for (size_t i = 0; i < actual_num_chunk_entries; i++)
534 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
536 u32 offset = ctx->chunk_csizes[0];
537 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
538 u32 next_size = ctx->chunk_csizes[i + 1];
539 entries[i] = cpu_to_le32(offset);
544 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
546 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
547 for (size_t i = 0; i < actual_num_chunk_entries; i++)
548 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
550 u64 offset = ctx->chunk_csizes[0];
551 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
552 u64 next_size = ctx->chunk_csizes[i + 1];
553 entries[i] = cpu_to_le64(offset);
559 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
560 u64 res_start_offset;
563 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
564 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
567 res_end_offset = ctx->out_fd->offset;
568 res_start_offset = ctx->chunks_start_offset;
570 res_end_offset = ctx->out_fd->offset;
572 u64 chunk_table_offset;
574 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
576 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
577 struct alt_chunk_table_header_disk hdr;
579 hdr.res_usize = cpu_to_le64(res_actual_size);
580 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
581 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
583 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
584 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
585 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
587 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
588 chunk_table_offset - sizeof(hdr));
591 res_start_offset = chunk_table_offset - sizeof(hdr);
593 res_start_offset = chunk_table_offset;
596 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
597 chunk_table_size, chunk_table_offset);
602 *res_start_offset_ret = res_start_offset;
603 *res_store_size_ret = res_end_offset - res_start_offset;
608 ERROR_WITH_ERRNO("Write error");
612 /* Finish writing a WIM resource by writing or updating the chunk table (if not
613 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
615 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
619 u64 res_uncompressed_size;
620 u64 res_offset_in_wim;
622 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
623 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID));
624 res_uncompressed_size = ctx->cur_write_res_size;
626 if (ctx->compressor) {
627 ret = end_chunk_table(ctx, res_uncompressed_size,
628 &res_offset_in_wim, &res_size_in_wim);
632 res_offset_in_wim = ctx->chunks_start_offset;
633 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
635 out_reshdr->uncompressed_size = res_uncompressed_size;
636 out_reshdr->size_in_wim = res_size_in_wim;
637 out_reshdr->offset_in_wim = res_offset_in_wim;
638 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
639 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
643 /* No more data streams of the file at @path are needed. */
645 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
647 union wimlib_progress_info info;
649 info.done_with_file.path_to_file = path;
651 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
656 is_file_stream(const struct wim_lookup_table_entry *lte)
658 return lte->resource_location == RESOURCE_IN_FILE_ON_DISK
660 || lte->resource_location == RESOURCE_IN_WINNT_FILE_ON_DISK
661 || lte->resource_location == RESOURCE_WIN32_ENCRYPTED
667 do_done_with_stream(struct wim_lookup_table_entry *lte,
668 wimlib_progress_func_t progfunc, void *progctx)
671 struct wim_inode *inode;
673 if (!lte->may_send_done_with_file)
676 inode = lte->file_inode;
678 wimlib_assert(inode != NULL);
679 wimlib_assert(inode->num_remaining_streams > 0);
680 if (--inode->num_remaining_streams > 0)
684 /* XXX: This logic really should be somewhere else. */
686 /* We want the path to the file, but lte->file_on_disk might actually
687 * refer to a named data stream. Temporarily strip the named data
688 * stream from the path. */
689 wchar_t *p_colon = NULL;
690 wchar_t *p_question_mark = NULL;
691 const wchar_t *p_stream_name;
693 p_stream_name = path_stream_name(lte->file_on_disk);
694 if (unlikely(p_stream_name)) {
695 p_colon = (wchar_t *)(p_stream_name - 1);
696 wimlib_assert(*p_colon == L':');
700 /* We also should use a fake Win32 path instead of a NT path */
701 if (!wcsncmp(lte->file_on_disk, L"\\??\\", 4)) {
702 p_question_mark = <e->file_on_disk[1];
703 *p_question_mark = L'\\';
707 ret = done_with_file(lte->file_on_disk, progfunc, progctx);
713 *p_question_mark = L'?';
718 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
720 done_with_stream(struct wim_lookup_table_entry *lte,
721 struct write_streams_ctx *ctx)
723 if (likely(!(ctx->write_resource_flags &
724 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
726 return do_done_with_stream(lte, ctx->progress_data.progfunc,
727 ctx->progress_data.progctx);
730 /* Begin processing a stream for writing. */
732 write_stream_begin_read(struct wim_lookup_table_entry *lte, void *_ctx)
734 struct write_streams_ctx *ctx = _ctx;
737 wimlib_assert(lte->size > 0);
739 ctx->cur_read_stream_offset = 0;
740 ctx->cur_read_stream_size = lte->size;
742 /* As an optimization, we allow some streams to be "unhashed", meaning
743 * their SHA1 message digests are unknown. This is the case with
744 * streams that are added by scanning a directry tree with
745 * wimlib_add_image(), for example. Since WIM uses single-instance
746 * streams, we don't know whether such each such stream really need to
747 * written until it is actually checksummed, unless it has a unique
748 * size. In such cases we read and checksum the stream in this
749 * function, thereby advancing ahead of read_stream_list(), which will
750 * still provide the data again to write_stream_process_chunk(). This
751 * is okay because an unhashed stream cannot be in a WIM resource, which
752 * might be costly to decompress. */
753 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
755 struct wim_lookup_table_entry *lte_new;
757 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
760 if (lte_new != lte) {
761 /* Duplicate stream detected. */
763 if (lte_new->will_be_in_output_wim ||
764 stream_filtered(lte_new, ctx->filter_ctx))
766 /* The duplicate stream is already being
767 * included in the output WIM, or it would be
768 * filtered out if it had been. Skip writing
769 * this stream (and reading it again) entirely,
770 * passing its output reference count to the
771 * duplicate stream in the former case. */
772 DEBUG("Discarding duplicate stream of "
773 "length %"PRIu64, lte->size);
774 ret = do_write_streams_progress(&ctx->progress_data,
777 list_del(<e->write_streams_list);
778 list_del(<e->lookup_table_list);
779 if (lte_new->will_be_in_output_wim)
780 lte_new->out_refcnt += lte->out_refcnt;
781 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID)
782 ctx->cur_write_res_size -= lte->size;
784 ret = done_with_stream(lte, ctx);
785 free_lookup_table_entry(lte);
788 return BEGIN_STREAM_STATUS_SKIP_STREAM;
790 /* The duplicate stream can validly be written,
791 * but was not marked as such. Discard the
792 * current stream entry and use the duplicate,
793 * but actually freeing the current entry must
794 * wait until read_stream_list() has finished
795 * reading its data. */
796 DEBUG("Stream duplicate, but not already "
797 "selected for writing.");
798 list_replace(<e->write_streams_list,
799 <e_new->write_streams_list);
800 list_replace(<e->lookup_table_list,
801 <e_new->lookup_table_list);
802 lte->will_be_in_output_wim = 0;
803 lte_new->out_refcnt = lte->out_refcnt;
804 lte_new->will_be_in_output_wim = 1;
805 lte_new->may_send_done_with_file = 0;
810 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
814 /* Rewrite a stream that was just written compressed as uncompressed instead.
815 * This function is optional, but if a stream did not compress to less than its
816 * original size, it might as well be written uncompressed. */
818 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
819 struct filedes *out_fd)
822 u64 begin_offset = lte->out_reshdr.offset_in_wim;
823 u64 end_offset = out_fd->offset;
825 if (filedes_seek(out_fd, begin_offset) == -1)
828 ret = extract_full_stream_to_fd(lte, out_fd);
830 /* Error reading the uncompressed data. */
831 if (out_fd->offset == begin_offset &&
832 filedes_seek(out_fd, end_offset) != -1)
834 /* Nothing was actually written yet, and we successfully
835 * seeked to the end of the compressed resource, so
836 * don't issue a hard error; just keep the compressed
837 * resource instead. */
838 WARNING("Recovered compressed stream of "
839 "size %"PRIu64", continuing on.",
846 wimlib_assert(out_fd->offset - begin_offset == lte->size);
848 if (out_fd->offset < end_offset &&
849 0 != ftruncate(out_fd->fd, out_fd->offset))
851 ERROR_WITH_ERRNO("Can't truncate output file to "
852 "offset %"PRIu64, out_fd->offset);
853 return WIMLIB_ERR_WRITE;
856 lte->out_reshdr.size_in_wim = lte->size;
857 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
858 WIM_RESHDR_FLAG_SOLID);
862 /* Returns true if the specified stream should be truncated from the WIM file
863 * and re-written as uncompressed. lte->out_reshdr must be filled in from the
864 * initial write of the stream. */
866 should_rewrite_stream_uncompressed(const struct write_streams_ctx *ctx,
867 const struct wim_lookup_table_entry *lte)
869 /* If the compressed data is smaller than the uncompressed data, prefer
870 * the compressed data. */
871 if (lte->out_reshdr.size_in_wim < lte->out_reshdr.uncompressed_size)
874 /* If we're not actually writing compressed data, then there's no need
876 if (!ctx->compressor)
879 /* If writing a pipable WIM, everything we write to the output is final
880 * (it might actually be a pipe!). */
881 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
884 /* If the stream that would need to be re-read is located in a solid
885 * resource in another WIM file, then re-reading it would be costly. So
888 * Exception: if the compressed size happens to be *exactly* the same as
889 * the uncompressed size, then the stream *must* be written uncompressed
890 * in order to remain compatible with the Windows Overlay Filesystem
891 * Filter Driver (WOF).
893 * TODO: we are currently assuming that the optimization for
894 * single-chunk resources in maybe_rewrite_stream_uncompressed()
895 * prevents this case from being triggered too often. To fully prevent
896 * excessive decompressions in degenerate cases, we really should
897 * obtain the uncompressed data by decompressing the compressed data we
898 * wrote to the output file.
900 if ((lte->flags & WIM_RESHDR_FLAG_SOLID) &&
901 (lte->out_reshdr.size_in_wim != lte->out_reshdr.uncompressed_size))
908 maybe_rewrite_stream_uncompressed(struct write_streams_ctx *ctx,
909 struct wim_lookup_table_entry *lte)
911 if (!should_rewrite_stream_uncompressed(ctx, lte))
914 /* Regular (non-solid) WIM resources with exactly one chunk and
915 * compressed size equal to uncompressed size are exactly the same as
916 * the corresponding compressed data --- since there must be 0 entries
917 * in the chunk table and the only chunk must be stored uncompressed.
918 * In this case, there's no need to rewrite anything. */
919 if (ctx->chunk_index == 1 &&
920 lte->out_reshdr.size_in_wim == lte->out_reshdr.uncompressed_size)
922 lte->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
926 return write_stream_uncompressed(lte, ctx->out_fd);
929 /* Write the next chunk of (typically compressed) data to the output WIM,
930 * handling the writing of the chunk table. */
932 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
933 size_t csize, size_t usize)
937 struct wim_lookup_table_entry *lte;
938 u32 completed_stream_count;
941 lte = list_entry(ctx->pending_streams.next,
942 struct wim_lookup_table_entry, write_streams_list);
944 if (ctx->cur_write_stream_offset == 0 &&
945 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID))
947 /* Starting to write a new stream in non-solid mode. */
949 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
950 int additional_reshdr_flags = 0;
951 if (ctx->compressor != NULL)
952 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
954 DEBUG("Writing pipable WIM stream header "
955 "(offset=%"PRIu64")", ctx->out_fd->offset);
957 ret = write_pwm_stream_header(lte, ctx->out_fd,
958 additional_reshdr_flags);
963 ret = begin_write_resource(ctx, lte->size);
968 if (ctx->compressor != NULL) {
969 /* Record the compresed chunk size. */
970 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
971 ctx->chunk_csizes[ctx->chunk_index++] = csize;
973 /* If writing a pipable WIM, before the chunk data write a chunk
974 * header that provides the compressed chunk size. */
975 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
976 struct pwm_chunk_hdr chunk_hdr = {
977 .compressed_size = cpu_to_le32(csize),
979 ret = full_write(ctx->out_fd, &chunk_hdr,
986 /* Write the chunk data. */
987 ret = full_write(ctx->out_fd, cchunk, csize);
991 ctx->cur_write_stream_offset += usize;
993 completed_size = usize;
994 completed_stream_count = 0;
995 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
996 /* Wrote chunk in solid mode. It may have finished multiple
998 struct wim_lookup_table_entry *next_lte;
1000 while (lte && ctx->cur_write_stream_offset >= lte->size) {
1002 ctx->cur_write_stream_offset -= lte->size;
1004 if (ctx->cur_write_stream_offset)
1005 next_lte = list_entry(lte->write_streams_list.next,
1006 struct wim_lookup_table_entry,
1007 write_streams_list);
1011 ret = done_with_stream(lte, ctx);
1014 list_move_tail(<e->write_streams_list, &ctx->solid_streams);
1015 completed_stream_count++;
1020 /* Wrote chunk in non-solid mode. It may have finished a
1022 if (ctx->cur_write_stream_offset == lte->size) {
1024 wimlib_assert(ctx->cur_write_stream_offset ==
1025 ctx->cur_write_res_size);
1027 ret = end_write_resource(ctx, <e->out_reshdr);
1031 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1032 if (ctx->compressor != NULL)
1033 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
1035 ret = maybe_rewrite_stream_uncompressed(ctx, lte);
1039 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
1041 ctx->cur_write_stream_offset = 0;
1043 ret = done_with_stream(lte, ctx);
1046 list_del(<e->write_streams_list);
1047 completed_stream_count++;
1051 return do_write_streams_progress(&ctx->progress_data,
1052 completed_size, completed_stream_count,
1056 ERROR_WITH_ERRNO("Write error");
1061 prepare_chunk_buffer(struct write_streams_ctx *ctx)
1063 /* While we are unable to get a new chunk buffer due to too many chunks
1064 * already outstanding, retrieve and write the next compressed chunk. */
1065 while (!(ctx->cur_chunk_buf =
1066 ctx->compressor->get_chunk_buffer(ctx->compressor)))
1074 bret = ctx->compressor->get_compression_result(ctx->compressor,
1078 wimlib_assert(bret);
1080 ret = write_chunk(ctx, cchunk, csize, usize);
1087 /* Process the next chunk of data to be written to a WIM resource. */
1089 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
1091 struct write_streams_ctx *ctx = _ctx;
1093 const u8 *chunkptr, *chunkend;
1095 wimlib_assert(size != 0);
1097 if (ctx->compressor == NULL) {
1098 /* Write chunk uncompressed. */
1099 ret = write_chunk(ctx, chunk, size, size);
1102 ctx->cur_read_stream_offset += size;
1106 /* Submit the chunk for compression, but take into account that the
1107 * @size the chunk was provided in may not correspond to the
1108 * @out_chunk_size being used for compression. */
1110 chunkend = chunkptr + size;
1112 size_t needed_chunk_size;
1113 size_t bytes_consumed;
1115 if (!ctx->cur_chunk_buf) {
1116 ret = prepare_chunk_buffer(ctx);
1121 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1122 needed_chunk_size = ctx->out_chunk_size;
1124 needed_chunk_size = min(ctx->out_chunk_size,
1125 ctx->cur_chunk_buf_filled +
1126 (ctx->cur_read_stream_size -
1127 ctx->cur_read_stream_offset));
1130 bytes_consumed = min(chunkend - chunkptr,
1131 needed_chunk_size - ctx->cur_chunk_buf_filled);
1133 memcpy(&ctx->cur_chunk_buf[ctx->cur_chunk_buf_filled],
1134 chunkptr, bytes_consumed);
1136 chunkptr += bytes_consumed;
1137 ctx->cur_read_stream_offset += bytes_consumed;
1138 ctx->cur_chunk_buf_filled += bytes_consumed;
1140 if (ctx->cur_chunk_buf_filled == needed_chunk_size) {
1141 ctx->compressor->signal_chunk_filled(ctx->compressor,
1142 ctx->cur_chunk_buf_filled);
1143 ctx->cur_chunk_buf = NULL;
1144 ctx->cur_chunk_buf_filled = 0;
1146 } while (chunkptr != chunkend);
1150 /* Finish processing a stream for writing. It may not have been completely
1151 * written yet, as the chunk_compressor implementation may still have chunks
1152 * buffered or being compressed. */
1154 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1156 struct write_streams_ctx *ctx = _ctx;
1158 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size || status);
1160 if (!lte->will_be_in_output_wim) {
1161 /* The 'lte' stream was a duplicate. Now that its data has
1162 * finished being read, it is being discarded in favor of the
1163 * duplicate entry. It therefore is no longer needed, and we
1164 * can fire the DONE_WITH_FILE callback because the file will
1165 * not be read again.
1167 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1168 * streams, since it needs to be possible to re-read the file if
1169 * it does not compress to less than its original size. */
1171 status = done_with_stream(lte, ctx);
1172 free_lookup_table_entry(lte);
1173 } else if (!status && lte->unhashed && ctx->lookup_table != NULL) {
1174 /* The 'lte' stream was not a duplicate and was previously
1175 * unhashed. Since we passed COMPUTE_MISSING_STREAM_HASHES to
1176 * read_stream_list(), lte->hash is now computed and valid. So
1177 * turn this stream into a "hashed" stream. */
1178 list_del(<e->unhashed_list);
1179 lookup_table_insert(ctx->lookup_table, lte);
1185 /* Compute statistics about a list of streams that will be written.
1187 * Assumes the streams are sorted such that all streams located in each distinct
1188 * WIM (specified by WIMStruct) are together. */
1190 compute_stream_list_stats(struct list_head *stream_list,
1191 struct write_streams_ctx *ctx)
1193 struct wim_lookup_table_entry *lte;
1194 u64 total_bytes = 0;
1195 u64 num_streams = 0;
1196 u64 total_parts = 0;
1197 WIMStruct *prev_wim_part = NULL;
1199 list_for_each_entry(lte, stream_list, write_streams_list) {
1201 total_bytes += lte->size;
1202 if (lte->resource_location == RESOURCE_IN_WIM) {
1203 if (prev_wim_part != lte->rspec->wim) {
1204 prev_wim_part = lte->rspec->wim;
1209 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1210 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1211 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1212 ctx->progress_data.progress.write_streams.completed_streams = 0;
1213 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1214 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1215 ctx->progress_data.progress.write_streams.completed_parts = 0;
1216 ctx->progress_data.next_progress = 0;
1219 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1220 * rather than compressed. Delete these streams from @stream_list and move them
1221 * to @raw_copy_streams. Return the total uncompressed size of the streams that
1222 * need to be compressed. */
1224 find_raw_copy_streams(struct list_head *stream_list,
1225 int write_resource_flags,
1228 struct list_head *raw_copy_streams)
1230 struct wim_lookup_table_entry *lte, *tmp;
1231 u64 num_bytes_to_compress = 0;
1233 INIT_LIST_HEAD(raw_copy_streams);
1235 /* Initialize temporary raw_copy_ok flag. */
1236 list_for_each_entry(lte, stream_list, write_streams_list)
1237 if (lte->resource_location == RESOURCE_IN_WIM)
1238 lte->rspec->raw_copy_ok = 0;
1240 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1241 if (lte->resource_location == RESOURCE_IN_WIM &&
1242 lte->rspec->raw_copy_ok)
1244 list_move_tail(<e->write_streams_list,
1246 } else if (can_raw_copy(lte, write_resource_flags,
1247 out_ctype, out_chunk_size))
1249 lte->rspec->raw_copy_ok = 1;
1250 list_move_tail(<e->write_streams_list,
1253 num_bytes_to_compress += lte->size;
1257 return num_bytes_to_compress;
1260 /* Copy a raw compressed resource located in another WIM file to the WIM file
1263 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1264 struct filedes *out_fd)
1266 u64 cur_read_offset;
1267 u64 end_read_offset;
1268 u8 buf[BUFFER_SIZE];
1269 size_t bytes_to_read;
1271 struct filedes *in_fd;
1272 struct wim_lookup_table_entry *lte;
1273 u64 out_offset_in_wim;
1275 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1276 "uncompressed_size=%"PRIu64")",
1277 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1279 /* Copy the raw data. */
1280 cur_read_offset = in_rspec->offset_in_wim;
1281 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1283 out_offset_in_wim = out_fd->offset;
1285 if (in_rspec->is_pipable) {
1286 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1287 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1288 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1289 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1291 in_fd = &in_rspec->wim->in_fd;
1292 wimlib_assert(cur_read_offset != end_read_offset);
1295 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1297 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1301 ret = full_write(out_fd, buf, bytes_to_read);
1305 cur_read_offset += bytes_to_read;
1307 } while (cur_read_offset != end_read_offset);
1309 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1310 if (lte->will_be_in_output_wim) {
1311 stream_set_out_reshdr_for_reuse(lte);
1312 if (in_rspec->flags & WIM_RESHDR_FLAG_SOLID)
1313 lte->out_res_offset_in_wim = out_offset_in_wim;
1315 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1322 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1323 * WIM file being written. */
1325 write_raw_copy_resources(struct list_head *raw_copy_streams,
1326 struct filedes *out_fd,
1327 struct write_streams_progress_data *progress_data)
1329 struct wim_lookup_table_entry *lte;
1332 list_for_each_entry(lte, raw_copy_streams, write_streams_list)
1333 lte->rspec->raw_copy_ok = 1;
1335 list_for_each_entry(lte, raw_copy_streams, write_streams_list) {
1336 if (lte->rspec->raw_copy_ok) {
1337 /* Write each solid resource only one time, no matter
1338 * how many streams reference it. */
1339 ret = write_raw_copy_resource(lte->rspec, out_fd);
1342 lte->rspec->raw_copy_ok = 0;
1344 ret = do_write_streams_progress(progress_data, lte->size,
1352 /* Wait for and write all chunks pending in the compressor. */
1354 finish_remaining_chunks(struct write_streams_ctx *ctx)
1361 if (ctx->compressor == NULL)
1364 if (ctx->cur_chunk_buf_filled != 0) {
1365 ctx->compressor->signal_chunk_filled(ctx->compressor,
1366 ctx->cur_chunk_buf_filled);
1369 while (ctx->compressor->get_compression_result(ctx->compressor, &cdata,
1372 ret = write_chunk(ctx, cdata, csize, usize);
1380 remove_zero_length_streams(struct list_head *stream_list)
1382 struct wim_lookup_table_entry *lte, *tmp;
1384 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1385 wimlib_assert(lte->will_be_in_output_wim);
1386 if (lte->size == 0) {
1387 list_del(<e->write_streams_list);
1388 lte->out_reshdr.offset_in_wim = 0;
1389 lte->out_reshdr.size_in_wim = 0;
1390 lte->out_reshdr.uncompressed_size = 0;
1391 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1397 init_done_with_file_info(struct list_head *stream_list)
1399 struct wim_lookup_table_entry *lte;
1401 list_for_each_entry(lte, stream_list, write_streams_list) {
1402 if (is_file_stream(lte)) {
1403 lte->file_inode->num_remaining_streams = 0;
1404 lte->may_send_done_with_file = 1;
1406 lte->may_send_done_with_file = 0;
1410 list_for_each_entry(lte, stream_list, write_streams_list)
1411 if (lte->may_send_done_with_file)
1412 lte->file_inode->num_remaining_streams++;
1416 * Write a list of streams to the output WIM file.
1419 * The list of streams to write, specified by a list of `struct
1420 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1423 * The file descriptor, opened for writing, to which to write the streams.
1425 * @write_resource_flags
1426 * Flags to modify how the streams are written:
1428 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1429 * Force compression of all resources, even if they could otherwise
1430 * be re-used by copying the raw data, due to being located in a WIM
1431 * file with compatible compression parameters.
1433 * WRITE_RESOURCE_FLAG_PIPABLE:
1434 * Write the resources in the wimlib-specific pipable format, and
1435 * furthermore do so in such a way that no seeking backwards in
1436 * @out_fd will be performed (so it may be a pipe).
1438 * WRITE_RESOURCE_FLAG_SOLID:
1439 * Combine all the streams into a single resource rather than
1440 * writing them in separate resources. This flag is only valid if
1441 * the WIM version number has been, or will be, set to
1442 * WIM_VERSION_SOLID. This flag may not be combined with
1443 * WRITE_RESOURCE_FLAG_PIPABLE.
1446 * Compression format to use to write the output streams, specified as one
1447 * of the WIMLIB_COMPRESSION_TYPE_* constants.
1448 * WIMLIB_COMPRESSION_TYPE_NONE is allowed.
1451 * Chunk size to use to write the streams. It must be a valid chunk size
1452 * for the specified compression format @out_ctype, unless @out_ctype is
1453 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1456 * Number of threads to use to compress data. If 0, a default number of
1457 * threads will be chosen. The number of threads still may be decreased
1458 * from the specified value if insufficient memory is detected.
1461 * If on-the-fly deduplication of unhashed streams is desired, this
1462 * parameter must be pointer to the lookup table for the WIMStruct on whose
1463 * behalf the streams are being written. Otherwise, this parameter can be
1467 * If on-the-fly deduplication of unhashed streams is desired, this
1468 * parameter can be a pointer to a context for stream filtering used to
1469 * detect whether the duplicate stream has been hard-filtered or not. If
1470 * no streams are hard-filtered or no streams are unhashed, this parameter
1473 * This function will write the streams in @stream_list to resources in
1474 * consecutive positions in the output WIM file, or to a single solid resource
1475 * if WRITE_RESOURCE_FLAG_SOLID was specified in @write_resource_flags. In both
1476 * cases, the @out_reshdr of the `struct wim_lookup_table_entry' for each stream
1477 * written will be updated to specify its location, size, and flags in the
1478 * output WIM. In the solid resource case, WIM_RESHDR_FLAG_SOLID will be set in
1479 * the @flags field of each @out_reshdr, and furthermore @out_res_offset_in_wim
1480 * and @out_res_size_in_wim of each @out_reshdr will be set to the offset and
1481 * size, respectively, in the output WIM of the solid resource containing the
1482 * corresponding stream.
1484 * Each of the streams to write may be in any location supported by the
1485 * resource-handling code (specifically, read_stream_list()), such as the
1486 * contents of external file that has been logically added to the output WIM, or
1487 * a stream in another WIM file that has been imported, or even a stream in the
1488 * "same" WIM file of which a modified copy is being written. In the case that
1489 * a stream is already in a WIM file and uses compatible compression parameters,
1490 * by default this function will re-use the raw data instead of decompressing
1491 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1492 * specified in @write_resource_flags, this is not done.
1494 * As a further requirement, this function requires that the
1495 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1496 * well as any other streams not in @stream_list that will be in the output WIM
1497 * file, but set to 0 on any other streams in the output WIM's lookup table or
1498 * sharing a solid resource with a stream in @stream_list. Still furthermore,
1499 * if on-the-fly deduplication of streams is possible, then all streams in
1500 * @stream_list must also be linked by @lookup_table_list along with any other
1501 * streams that have @will_be_in_output_wim set.
1503 * This function handles on-the-fly deduplication of streams for which SHA1
1504 * message digests have not yet been calculated. Such streams may or may not
1505 * need to be written. If @lookup_table is non-NULL, then each stream in
1506 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1507 * immediately before it would otherwise be read for writing in order to
1508 * determine if it is identical to another stream already being written or one
1509 * that would be filtered out of the output WIM using stream_filtered() with the
1510 * context @filter_ctx. Each such duplicate stream will be removed from
1511 * @stream_list, its reference count transfered to the pre-existing duplicate
1512 * stream, its memory freed, and will not be written. Alternatively, if a
1513 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1514 * has not been marked for writing or would not be hard-filtered, it is freed
1515 * and the pre-existing duplicate is written instead, taking ownership of the
1516 * reference count and slot in the @lookup_table_list.
1518 * Returns 0 if every stream was either written successfully or did not need to
1519 * be written; otherwise returns a non-zero error code.
1522 write_stream_list(struct list_head *stream_list,
1523 struct filedes *out_fd,
1524 int write_resource_flags,
1527 unsigned num_threads,
1528 struct wim_lookup_table *lookup_table,
1529 struct filter_context *filter_ctx,
1530 wimlib_progress_func_t progfunc,
1534 struct write_streams_ctx ctx;
1535 struct list_head raw_copy_streams;
1537 wimlib_assert((write_resource_flags &
1538 (WRITE_RESOURCE_FLAG_SOLID |
1539 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1540 (WRITE_RESOURCE_FLAG_SOLID |
1541 WRITE_RESOURCE_FLAG_PIPABLE));
1543 remove_zero_length_streams(stream_list);
1545 if (list_empty(stream_list)) {
1546 DEBUG("No streams to write.");
1550 /* If needed, set auxiliary information so that we can detect when the
1551 * library has finished using each external file. */
1552 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1553 init_done_with_file_info(stream_list);
1555 memset(&ctx, 0, sizeof(ctx));
1557 ctx.out_fd = out_fd;
1558 ctx.lookup_table = lookup_table;
1559 ctx.out_ctype = out_ctype;
1560 ctx.out_chunk_size = out_chunk_size;
1561 ctx.write_resource_flags = write_resource_flags;
1562 ctx.filter_ctx = filter_ctx;
1565 * We normally sort the streams to write by a "sequential" order that is
1566 * optimized for reading. But when using solid compression, we instead
1567 * sort the streams by file extension and file name (when applicable;
1568 * and we don't do this for streams from solid resources) so that
1569 * similar files are grouped together, which improves the compression
1570 * ratio. This is somewhat of a hack since a stream does not
1571 * necessarily correspond one-to-one with a filename, nor is there any
1572 * guarantee that two files with similar names or extensions are
1573 * actually similar in content. A potential TODO is to sort the streams
1574 * based on some measure of similarity of their actual contents.
1577 ret = sort_stream_list_by_sequential_order(stream_list,
1578 offsetof(struct wim_lookup_table_entry,
1579 write_streams_list));
1583 compute_stream_list_stats(stream_list, &ctx);
1585 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID_SORT) {
1586 ret = sort_stream_list_for_solid_compression(stream_list);
1588 WARNING("Failed to sort streams for solid compression. Continuing anyways.");
1591 ctx.progress_data.progfunc = progfunc;
1592 ctx.progress_data.progctx = progctx;
1594 ctx.num_bytes_to_compress = find_raw_copy_streams(stream_list,
1595 write_resource_flags,
1600 DEBUG("Writing stream list "
1601 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1602 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1603 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1604 out_fd->offset, write_resource_flags,
1605 out_ctype, out_chunk_size, num_threads,
1606 ctx.progress_data.progress.write_streams.total_bytes,
1607 ctx.num_bytes_to_compress);
1609 if (ctx.num_bytes_to_compress == 0) {
1610 DEBUG("No compression needed; skipping to raw copy!");
1611 goto out_write_raw_copy_resources;
1614 /* Unless uncompressed output was required, allocate a chunk_compressor
1615 * to do compression. There are serial and parallel implementations of
1616 * the chunk_compressor interface. We default to parallel using the
1617 * specified number of threads, unless the upper bound on the number
1618 * bytes needing to be compressed is less than a heuristic value. */
1619 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1621 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1622 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1623 ret = new_parallel_chunk_compressor(out_ctype,
1628 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1629 " Falling back to single-threaded compression.",
1630 wimlib_get_error_string(ret));
1635 if (ctx.compressor == NULL) {
1636 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1639 goto out_destroy_context;
1644 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1646 ctx.progress_data.progress.write_streams.num_threads = 1;
1648 DEBUG("Actually using %u threads",
1649 ctx.progress_data.progress.write_streams.num_threads);
1651 INIT_LIST_HEAD(&ctx.pending_streams);
1652 INIT_LIST_HEAD(&ctx.solid_streams);
1654 ret = call_progress(ctx.progress_data.progfunc,
1655 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1656 &ctx.progress_data.progress,
1657 ctx.progress_data.progctx);
1659 goto out_destroy_context;
1661 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1662 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1664 goto out_destroy_context;
1667 /* Read the list of streams needing to be compressed, using the
1668 * specified callbacks to execute processing of the data. */
1670 struct read_stream_list_callbacks cbs = {
1671 .begin_stream = write_stream_begin_read,
1672 .begin_stream_ctx = &ctx,
1673 .consume_chunk = write_stream_process_chunk,
1674 .consume_chunk_ctx = &ctx,
1675 .end_stream = write_stream_end_read,
1676 .end_stream_ctx = &ctx,
1679 ret = read_stream_list(stream_list,
1680 offsetof(struct wim_lookup_table_entry, write_streams_list),
1682 STREAM_LIST_ALREADY_SORTED |
1683 VERIFY_STREAM_HASHES |
1684 COMPUTE_MISSING_STREAM_HASHES);
1687 goto out_destroy_context;
1689 ret = finish_remaining_chunks(&ctx);
1691 goto out_destroy_context;
1693 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1694 struct wim_reshdr reshdr;
1695 struct wim_lookup_table_entry *lte;
1698 ret = end_write_resource(&ctx, &reshdr);
1700 goto out_destroy_context;
1702 DEBUG("Ending solid resource: %lu %lu %lu.",
1703 reshdr.offset_in_wim,
1705 reshdr.uncompressed_size);
1708 list_for_each_entry(lte, &ctx.solid_streams, write_streams_list) {
1709 lte->out_reshdr.size_in_wim = lte->size;
1710 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1711 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_SOLID;
1712 lte->out_reshdr.uncompressed_size = 0;
1713 lte->out_reshdr.offset_in_wim = offset_in_res;
1714 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1715 lte->out_res_size_in_wim = reshdr.size_in_wim;
1716 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1717 offset_in_res += lte->size;
1719 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1722 out_write_raw_copy_resources:
1723 /* Copy any compressed resources for which the raw data can be reused
1724 * without decompression. */
1725 ret = write_raw_copy_resources(&raw_copy_streams, ctx.out_fd,
1726 &ctx.progress_data);
1728 out_destroy_context:
1729 FREE(ctx.chunk_csizes);
1731 ctx.compressor->destroy(ctx.compressor);
1732 DEBUG("Done (ret=%d)", ret);
1737 is_stream_in_solid_resource(struct wim_lookup_table_entry *lte, void *_ignore)
1739 return lte_is_partial(lte);
1743 wim_has_solid_resources(WIMStruct *wim)
1745 return for_lookup_table_entry(wim->lookup_table,
1746 is_stream_in_solid_resource, NULL);
1750 wim_write_stream_list(WIMStruct *wim,
1751 struct list_head *stream_list,
1753 unsigned num_threads,
1754 struct filter_context *filter_ctx)
1758 int write_resource_flags;
1760 write_resource_flags = write_flags_to_resource_flags(write_flags);
1762 /* wimlib v1.7.0: create a solid WIM file by default if the WIM version
1763 * has been set to WIM_VERSION_SOLID and at least one stream in the
1764 * WIM's lookup table is located in a solid resource (may be the same
1765 * WIM, or a different one in the case of export). */
1766 if (wim->hdr.wim_version == WIM_VERSION_SOLID &&
1767 wim_has_solid_resources(wim))
1769 write_resource_flags |= WRITE_RESOURCE_FLAG_SOLID;
1772 if (write_resource_flags & WRITE_RESOURCE_FLAG_SOLID) {
1773 out_chunk_size = wim->out_solid_chunk_size;
1774 out_ctype = wim->out_solid_compression_type;
1776 out_chunk_size = wim->out_chunk_size;
1777 out_ctype = wim->out_compression_type;
1780 return write_stream_list(stream_list,
1782 write_resource_flags,
1793 write_wim_resource(struct wim_lookup_table_entry *lte,
1794 struct filedes *out_fd,
1797 int write_resource_flags)
1799 LIST_HEAD(stream_list);
1800 list_add(<e->write_streams_list, &stream_list);
1801 lte->will_be_in_output_wim = 1;
1802 return write_stream_list(&stream_list,
1804 write_resource_flags & ~WRITE_RESOURCE_FLAG_SOLID,
1815 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1816 int reshdr_flags, struct filedes *out_fd,
1819 struct wim_reshdr *out_reshdr,
1821 int write_resource_flags)
1824 struct wim_lookup_table_entry *lte;
1826 /* Set up a temporary lookup table entry to provide to
1827 * write_wim_resource(). */
1829 lte = new_lookup_table_entry();
1831 return WIMLIB_ERR_NOMEM;
1833 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1834 lte->attached_buffer = (void*)buf;
1835 lte->size = buf_size;
1836 lte->flags = reshdr_flags;
1838 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1839 sha1_buffer(buf, buf_size, lte->hash);
1845 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1846 write_resource_flags);
1850 copy_reshdr(out_reshdr, <e->out_reshdr);
1853 copy_hash(hash, lte->hash);
1856 lte->resource_location = RESOURCE_NONEXISTENT;
1857 free_lookup_table_entry(lte);
1861 struct stream_size_table {
1862 struct hlist_head *array;
1868 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1870 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1871 if (tab->array == NULL)
1872 return WIMLIB_ERR_NOMEM;
1873 tab->num_entries = 0;
1874 tab->capacity = capacity;
1879 destroy_stream_size_table(struct stream_size_table *tab)
1885 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1887 struct stream_size_table *tab = _tab;
1889 struct wim_lookup_table_entry *same_size_lte;
1890 struct hlist_node *tmp;
1892 pos = hash_u64(lte->size) % tab->capacity;
1893 lte->unique_size = 1;
1894 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1895 if (same_size_lte->size == lte->size) {
1896 lte->unique_size = 0;
1897 same_size_lte->unique_size = 0;
1902 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1907 struct find_streams_ctx {
1910 struct list_head stream_list;
1911 struct stream_size_table stream_size_tab;
1915 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1916 struct list_head *stream_list, u32 nref)
1918 if (!lte->will_be_in_output_wim) {
1919 lte->out_refcnt = 0;
1920 list_add_tail(<e->write_streams_list, stream_list);
1921 lte->will_be_in_output_wim = 1;
1923 lte->out_refcnt += nref;
1927 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1930 struct list_head *stream_list = _stream_list;
1931 lte->will_be_in_output_wim = 0;
1932 reference_stream_for_write(lte, stream_list, lte->refcnt);
1937 inode_find_streams_to_reference(const struct wim_inode *inode,
1938 const struct wim_lookup_table *table,
1939 struct list_head *stream_list)
1941 struct wim_lookup_table_entry *lte;
1944 wimlib_assert(inode->i_nlink > 0);
1946 for (i = 0; i <= inode->i_num_ads; i++) {
1947 lte = inode_stream_lte(inode, i, table);
1949 reference_stream_for_write(lte, stream_list,
1951 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1952 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1958 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1960 lte->will_be_in_output_wim = 0;
1965 image_find_streams_to_reference(WIMStruct *wim)
1967 struct wim_image_metadata *imd;
1968 struct wim_inode *inode;
1969 struct wim_lookup_table_entry *lte;
1970 struct list_head *stream_list;
1973 imd = wim_get_current_image_metadata(wim);
1975 image_for_each_unhashed_stream(lte, imd)
1976 lte->will_be_in_output_wim = 0;
1978 stream_list = wim->private;
1979 image_for_each_inode(inode, imd) {
1980 ret = inode_find_streams_to_reference(inode,
1990 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1993 struct list_head *stream_list_ret)
1997 INIT_LIST_HEAD(stream_list_ret);
1999 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
2000 (image == 1 && wim->hdr.image_count == 1)))
2002 /* Fast case: Assume that all streams are being written and
2003 * that the reference counts are correct. */
2004 struct wim_lookup_table_entry *lte;
2005 struct wim_image_metadata *imd;
2008 for_lookup_table_entry(wim->lookup_table,
2009 fully_reference_stream_for_write,
2012 for (i = 0; i < wim->hdr.image_count; i++) {
2013 imd = wim->image_metadata[i];
2014 image_for_each_unhashed_stream(lte, imd)
2015 fully_reference_stream_for_write(lte, stream_list_ret);
2018 /* Slow case: Walk through the images being written and
2019 * determine the streams referenced. */
2020 for_lookup_table_entry(wim->lookup_table,
2021 do_stream_set_not_in_output_wim, NULL);
2022 wim->private = stream_list_ret;
2023 ret = for_image(wim, image, image_find_streams_to_reference);
2031 struct insert_other_if_hard_filtered_ctx {
2032 struct stream_size_table *tab;
2033 struct filter_context *filter_ctx;
2037 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
2039 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
2041 if (!lte->will_be_in_output_wim &&
2042 stream_hard_filtered(lte, ctx->filter_ctx))
2043 stream_size_table_insert(lte, ctx->tab);
2048 determine_stream_size_uniquity(struct list_head *stream_list,
2049 struct wim_lookup_table *lt,
2050 struct filter_context *filter_ctx)
2053 struct stream_size_table tab;
2054 struct wim_lookup_table_entry *lte;
2056 ret = init_stream_size_table(&tab, 9001);
2060 if (may_hard_filter_streams(filter_ctx)) {
2061 struct insert_other_if_hard_filtered_ctx ctx = {
2063 .filter_ctx = filter_ctx,
2065 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
2068 list_for_each_entry(lte, stream_list, write_streams_list)
2069 stream_size_table_insert(lte, &tab);
2071 destroy_stream_size_table(&tab);
2076 filter_stream_list_for_write(struct list_head *stream_list,
2077 struct filter_context *filter_ctx)
2079 struct wim_lookup_table_entry *lte, *tmp;
2081 list_for_each_entry_safe(lte, tmp,
2082 stream_list, write_streams_list)
2084 int status = stream_filtered(lte, filter_ctx);
2091 /* Soft filtered. */
2093 /* Hard filtered. */
2094 lte->will_be_in_output_wim = 0;
2095 list_del(<e->lookup_table_list);
2097 list_del(<e->write_streams_list);
2103 * prepare_stream_list_for_write() -
2105 * Prepare the list of streams to write for writing a WIM containing the
2106 * specified image(s) with the specified write flags.
2109 * The WIMStruct on whose behalf the write is occurring.
2112 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2115 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2117 * STREAMS_OK: For writes of all images, assume that all streams in the
2118 * lookup table of @wim and the per-image lists of unhashed streams should
2119 * be taken as-is, and image metadata should not be searched for
2120 * references. This does not exclude filtering with OVERWRITE and
2121 * SKIP_EXTERNAL_WIMS, below.
2123 * OVERWRITE: Streams already present in @wim shall not be returned in
2126 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
2127 * @wim, shall be returned in neither @stream_list_ret nor
2128 * @lookup_table_list_ret.
2131 * List of streams, linked by write_streams_list, that need to be written
2132 * will be returned here.
2134 * Note that this function assumes that unhashed streams will be written;
2135 * it does not take into account that they may become duplicates when
2138 * @lookup_table_list_ret
2139 * List of streams, linked by lookup_table_list, that need to be included
2140 * in the WIM's lookup table will be returned here. This will be a
2141 * superset of the streams in @stream_list_ret.
2143 * This list will be a proper superset of @stream_list_ret if and only if
2144 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2145 * the streams that would otherwise need to be written were already located
2148 * All streams in this list will have @out_refcnt set to the number of
2149 * references to the stream in the output WIM. If
2150 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2151 * may be as low as 0.
2154 * A context for queries of stream filter status with stream_filtered() is
2155 * returned in this location.
2157 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
2158 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
2159 * lookup table of @wim not inserted into @lookup_table_list_ret.
2161 * Still furthermore, @unique_size will be set to 1 on all stream entries in
2162 * @stream_list_ret that have unique size among all stream entries in
2163 * @stream_list_ret and among all stream entries in the lookup table of @wim
2164 * that are ineligible for being written due to filtering.
2166 * Returns 0 on success; nonzero on read error, memory allocation error, or
2170 prepare_stream_list_for_write(WIMStruct *wim, int image,
2172 struct list_head *stream_list_ret,
2173 struct list_head *lookup_table_list_ret,
2174 struct filter_context *filter_ctx_ret)
2177 struct wim_lookup_table_entry *lte;
2179 filter_ctx_ret->write_flags = write_flags;
2180 filter_ctx_ret->wim = wim;
2182 ret = prepare_unfiltered_list_of_streams_in_output_wim(
2185 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2190 INIT_LIST_HEAD(lookup_table_list_ret);
2191 list_for_each_entry(lte, stream_list_ret, write_streams_list)
2192 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2194 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
2199 if (may_filter_streams(filter_ctx_ret))
2200 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2206 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2207 unsigned num_threads,
2208 struct list_head *stream_list_override,
2209 struct list_head *lookup_table_list_ret)
2212 struct list_head _stream_list;
2213 struct list_head *stream_list;
2214 struct wim_lookup_table_entry *lte;
2215 struct filter_context _filter_ctx;
2216 struct filter_context *filter_ctx;
2218 if (stream_list_override == NULL) {
2219 /* Normal case: prepare stream list from image(s) being written.
2221 stream_list = &_stream_list;
2222 filter_ctx = &_filter_ctx;
2223 ret = prepare_stream_list_for_write(wim, image, write_flags,
2225 lookup_table_list_ret,
2230 /* Currently only as a result of wimlib_split() being called:
2231 * use stream list already explicitly provided. Use existing
2232 * reference counts. */
2233 stream_list = stream_list_override;
2235 INIT_LIST_HEAD(lookup_table_list_ret);
2236 list_for_each_entry(lte, stream_list, write_streams_list) {
2237 lte->out_refcnt = lte->refcnt;
2238 lte->will_be_in_output_wim = 1;
2239 lte->unique_size = 0;
2240 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2244 return wim_write_stream_list(wim,
2252 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags)
2257 int write_resource_flags;
2259 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2260 DEBUG("Not writing any metadata resources.");
2264 write_resource_flags = write_flags_to_resource_flags(write_flags);
2266 write_resource_flags &= ~WRITE_RESOURCE_FLAG_SOLID;
2268 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2269 wim->out_fd.offset);
2271 ret = call_progress(wim->progfunc,
2272 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2273 NULL, wim->progctx);
2277 if (image == WIMLIB_ALL_IMAGES) {
2279 end_image = wim->hdr.image_count;
2281 start_image = image;
2285 for (int i = start_image; i <= end_image; i++) {
2286 struct wim_image_metadata *imd;
2288 imd = wim->image_metadata[i - 1];
2289 /* Build a new metadata resource only if image was modified from
2290 * the original (or was newly added). Otherwise just copy the
2292 if (imd->modified) {
2293 DEBUG("Image %u was modified; building and writing new "
2294 "metadata resource", i);
2295 ret = write_metadata_resource(wim, i,
2296 write_resource_flags);
2297 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2298 DEBUG("Image %u was not modified; re-using existing "
2299 "metadata resource.", i);
2300 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2303 DEBUG("Image %u was not modified; copying existing "
2304 "metadata resource.", i);
2305 ret = write_wim_resource(imd->metadata_lte,
2307 wim->out_compression_type,
2308 wim->out_chunk_size,
2309 write_resource_flags);
2315 return call_progress(wim->progfunc,
2316 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2317 NULL, wim->progctx);
2321 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2324 DEBUG("Opening \"%"TS"\" for writing.", path);
2326 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2328 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2329 return WIMLIB_ERR_OPEN;
2331 filedes_init(&wim->out_fd, raw_fd);
2336 close_wim_writable(WIMStruct *wim, int write_flags)
2340 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2341 DEBUG("Closing WIM file.");
2342 if (filedes_valid(&wim->out_fd))
2343 if (filedes_close(&wim->out_fd))
2344 ret = WIMLIB_ERR_WRITE;
2346 filedes_invalidate(&wim->out_fd);
2351 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2353 const struct wim_lookup_table_entry *lte1, *lte2;
2355 lte1 = *(const struct wim_lookup_table_entry**)p1;
2356 lte2 = *(const struct wim_lookup_table_entry**)p2;
2358 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2359 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
2360 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2361 return cmp_u64(lte1->out_res_offset_in_wim,
2362 lte2->out_res_offset_in_wim);
2367 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_SOLID)
2370 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2371 lte2->out_reshdr.offset_in_wim);
2375 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2376 struct wim_reshdr *out_reshdr,
2377 struct list_head *lookup_table_list)
2381 /* Set output resource metadata for streams already present in WIM. */
2382 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2383 struct wim_lookup_table_entry *lte;
2384 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2386 if (lte->resource_location == RESOURCE_IN_WIM &&
2387 lte->rspec->wim == wim)
2389 stream_set_out_reshdr_for_reuse(lte);
2394 ret = sort_stream_list(lookup_table_list,
2395 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2396 cmp_streams_by_out_rspec);
2400 /* Add entries for metadata resources. */
2401 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2405 if (image == WIMLIB_ALL_IMAGES) {
2407 end_image = wim->hdr.image_count;
2409 start_image = image;
2413 /* Push metadata resource lookup table entries onto the front of
2414 * the list in reverse order, so that they're written in order.
2416 for (int i = end_image; i >= start_image; i--) {
2417 struct wim_lookup_table_entry *metadata_lte;
2419 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2420 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2421 metadata_lte->out_refcnt = 1;
2422 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2426 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2428 wim->hdr.part_number,
2430 write_flags_to_resource_flags(write_flags));
2436 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2437 * table, then overwrite the WIM header. By default, closes the WIM file
2438 * descriptor (@wim->out_fd) if successful.
2440 * write_flags is a bitwise OR of the following:
2442 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2443 * Include an integrity table.
2445 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2446 * fsync() the output file before closing it.
2448 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2449 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2450 * stream headers before the lookup table and XML data, and also
2451 * write the WIM header at the end instead of seeking to the
2452 * beginning. Can't be combined with
2453 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2455 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2456 * Don't write the lookup table.
2458 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2459 * After writing the XML data but before writing the integrity
2460 * table, write a temporary WIM header and flush the stream so that
2461 * the WIM is less likely to become corrupted upon abrupt program
2463 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2464 * Instead of overwriting the WIM header at the beginning of the
2465 * file, simply append it to the end of the file. (Used when
2467 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2468 * Do not close the file descriptor @wim->out_fd on either success
2470 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2471 * Use the existing <TOTALBYTES> stored in the in-memory XML
2472 * information, rather than setting it to the offset of the XML
2473 * data being written.
2474 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2475 * The existing WIM file is being updated in-place. The entries
2476 * from its integrity table may be re-used.
2479 finish_write(WIMStruct *wim, int image, int write_flags,
2480 struct list_head *lookup_table_list)
2484 int write_resource_flags;
2485 off_t old_lookup_table_end = 0;
2486 off_t new_lookup_table_end;
2488 struct integrity_table *old_integrity_table = NULL;
2490 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2492 write_resource_flags = write_flags_to_resource_flags(write_flags);
2494 /* In the WIM header, there is room for the resource entry for a
2495 * metadata resource labeled as the "boot metadata". This entry should
2496 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2497 * it should be a copy of the resource entry for the image that is
2498 * marked as bootable. This is not well documented... */
2499 if (wim->hdr.boot_idx == 0) {
2500 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2502 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2503 &wim->image_metadata[
2504 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2507 /* If overwriting the WIM file containing an integrity table in-place,
2508 * we'd like to re-use the information in the old integrity table
2509 * instead of recalculating it. But we might overwrite the old
2510 * integrity table when we expand the XML data. Read it into memory
2512 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2513 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2514 (WIMLIB_WRITE_FLAG_OVERWRITE |
2515 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2516 && wim_has_integrity_table(wim))
2518 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2519 wim->hdr.lookup_table_reshdr.size_in_wim;
2520 (void)read_integrity_table(wim,
2521 old_lookup_table_end - WIM_HEADER_DISK_SIZE,
2522 &old_integrity_table);
2523 /* If we couldn't read the old integrity table, we can still
2524 * re-calculate the full integrity table ourselves. Hence the
2525 * ignoring of the return value. */
2528 /* Write lookup table. */
2529 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2530 ret = write_wim_lookup_table(wim, image, write_flags,
2531 &wim->hdr.lookup_table_reshdr,
2534 free_integrity_table(old_integrity_table);
2539 /* Write XML data. */
2540 xml_totalbytes = wim->out_fd.offset;
2541 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2542 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2543 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2544 &wim->hdr.xml_data_reshdr,
2545 write_resource_flags);
2547 free_integrity_table(old_integrity_table);
2551 /* Write integrity table (optional). */
2552 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2553 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2554 struct wim_header checkpoint_hdr;
2555 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2556 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2557 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2558 ret = write_wim_header_at_offset(&checkpoint_hdr,
2561 free_integrity_table(old_integrity_table);
2566 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2567 wim->hdr.lookup_table_reshdr.size_in_wim;
2569 ret = write_integrity_table(wim,
2570 new_lookup_table_end,
2571 old_lookup_table_end,
2572 old_integrity_table);
2573 free_integrity_table(old_integrity_table);
2577 /* No integrity table. */
2578 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2581 /* Now that all information in the WIM header has been determined, the
2582 * preliminary header written earlier can be overwritten, the header of
2583 * the existing WIM file can be overwritten, or the final header can be
2584 * written to the end of the pipable WIM. */
2585 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2587 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2588 hdr_offset = wim->out_fd.offset;
2589 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2590 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2594 /* Possibly sync file data to disk before closing. On POSIX systems, it
2595 * is necessary to do this before using rename() to overwrite an
2596 * existing file with a new file. Otherwise, data loss would occur if
2597 * the system is abruptly terminated when the metadata for the rename
2598 * operation has been written to disk, but the new file data has not.
2600 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2601 DEBUG("Syncing WIM file.");
2602 if (fsync(wim->out_fd.fd)) {
2603 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2604 return WIMLIB_ERR_WRITE;
2608 if (close_wim_writable(wim, write_flags)) {
2609 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2610 return WIMLIB_ERR_WRITE;
2616 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2618 /* Set advisory lock on WIM file (if not already done so) */
2620 lock_wim_for_append(WIMStruct *wim)
2622 if (wim->locked_for_append)
2624 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2625 wim->locked_for_append = 1;
2628 if (errno != EWOULDBLOCK)
2630 return WIMLIB_ERR_ALREADY_LOCKED;
2633 /* Remove advisory lock on WIM file (if present) */
2635 unlock_wim_for_append(WIMStruct *wim)
2637 if (wim->locked_for_append) {
2638 flock(wim->in_fd.fd, LOCK_UN);
2639 wim->locked_for_append = 0;
2645 * write_pipable_wim():
2647 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2648 * capable of being applied from a pipe).
2650 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2651 * images can be applied from them sequentially when the file data is sent over
2652 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2653 * The modifications made to the WIM format for pipable WIMs are:
2655 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2656 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2657 * stops other software from trying to read the file as a normal WIM.
2659 * - The header at the beginning of the file does not contain all the normal
2660 * information; in particular it will have all 0's for the lookup table and
2661 * XML data resource entries. This is because this information cannot be
2662 * determined until the lookup table and XML data have been written.
2663 * Consequently, wimlib will write the full header at the very end of the
2664 * file. The header at the end, however, is only used when reading the WIM
2665 * from a seekable file (not a pipe).
2667 * - An extra copy of the XML data is placed directly after the header. This
2668 * allows image names and sizes to be determined at an appropriate time when
2669 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2670 * WIM is read from a seekable file (not a pipe).
2672 * - The format of resources, or streams, has been modified to allow them to be
2673 * used before the "lookup table" has been read. Each stream is prefixed with
2674 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2675 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2676 * uncompressed stream size, and flags that indicate whether the stream is
2677 * compressed. The data of uncompressed streams then follows literally, while
2678 * the data of compressed streams follows in a modified format. Compressed
2679 * streams do not begin with a chunk table, since the chunk table cannot be
2680 * written until all chunks have been compressed. Instead, each compressed
2681 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2682 * Furthermore, the chunk table is written at the end of the resource instead
2683 * of the start. Note: chunk offsets are given in the chunk table as if the
2684 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2685 * used if the WIM is being read from a seekable file (not a pipe).
2687 * - Metadata resources always come before other file resources (streams).
2688 * (This does not by itself constitute an incompatibility with normal WIMs,
2689 * since this is valid in normal WIMs.)
2691 * - At least up to the end of the file resources, all components must be packed
2692 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2693 * not by itself consititute an incompatibility with normal WIMs, since this
2694 * is valid in normal WIMs.)
2696 * Note: the lookup table, XML data, and header at the end are not used when
2697 * applying from a pipe. They exist to support functionality such as image
2698 * application and export when the WIM is *not* read from a pipe.
2700 * Layout of pipable WIM:
2702 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2703 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2704 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2706 * Layout of normal WIM:
2708 * +--------+-----------------------------+-------------------------+
2709 * | Header | File and metadata resources | Lookup table | XML data |
2710 * +--------+-----------------------------+-------------------------+
2712 * An optional integrity table can follow the final XML data in both normal and
2713 * pipable WIMs. However, due to implementation details, wimlib currently can
2714 * only include an integrity table in a pipable WIM when writing it to a
2715 * seekable file (not a pipe).
2717 * Do note that since pipable WIMs are not supported by Microsoft's software,
2718 * wimlib does not create them unless explicitly requested (with
2719 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2720 * characters to identify the file.
2723 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2724 unsigned num_threads,
2725 struct list_head *stream_list_override,
2726 struct list_head *lookup_table_list_ret)
2729 struct wim_reshdr xml_reshdr;
2731 WARNING("Creating a pipable WIM, which will "
2733 " with Microsoft's software (wimgapi/imagex/Dism).");
2735 /* At this point, the header at the beginning of the file has already
2738 /* For efficiency, when wimlib adds an image to the WIM with
2739 * wimlib_add_image(), the SHA1 message digests of files is not
2740 * calculated; instead, they are calculated while the files are being
2741 * written. However, this does not work when writing a pipable WIM,
2742 * since when writing a stream to a pipable WIM, its SHA1 message digest
2743 * needs to be known before the stream data is written. Therefore,
2744 * before getting much farther, we need to pre-calculate the SHA1
2745 * message digests of all streams that will be written. */
2746 ret = wim_checksum_unhashed_streams(wim);
2750 /* Write extra copy of the XML data. */
2751 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2753 WRITE_RESOURCE_FLAG_PIPABLE);
2757 /* Write metadata resources for the image(s) being included in the
2759 ret = write_wim_metadata_resources(wim, image, write_flags);
2763 /* Write streams needed for the image(s) being included in the output
2764 * WIM, or streams needed for the split WIM part. */
2765 return write_wim_streams(wim, image, write_flags, num_threads,
2766 stream_list_override, lookup_table_list_ret);
2768 /* The lookup table, XML data, and header at end are handled by
2769 * finish_write(). */
2772 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2775 write_wim_part(WIMStruct *wim,
2776 const void *path_or_fd,
2779 unsigned num_threads,
2780 unsigned part_number,
2781 unsigned total_parts,
2782 struct list_head *stream_list_override,
2786 struct wim_header hdr_save;
2787 struct list_head lookup_table_list;
2789 if (total_parts == 1)
2790 DEBUG("Writing standalone WIM.");
2792 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2793 if (image == WIMLIB_ALL_IMAGES)
2794 DEBUG("Including all images.");
2796 DEBUG("Including image %d only.", image);
2797 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2798 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2800 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2801 DEBUG("Write flags: 0x%08x", write_flags);
2803 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2804 DEBUG("\tCHECK_INTEGRITY");
2806 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2807 DEBUG("\tNO_CHECK_INTEGRITY");
2809 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2812 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2813 DEBUG("\tNOT_PIPABLE");
2815 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2816 DEBUG("\tRECOMPRESS");
2818 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2821 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2824 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2825 DEBUG("\tSOFT_DELETE");
2827 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2828 DEBUG("\tIGNORE_READONLY_FLAG");
2830 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2831 DEBUG("\tSKIP_EXTERNAL_WIMS");
2833 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2834 DEBUG("\tSTREAMS_OK");
2836 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2837 DEBUG("\tRETAIN_GUID");
2839 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
2842 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2843 DEBUG("\tFILE_DESCRIPTOR");
2845 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2846 DEBUG("\tNO_METADATA");
2848 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2849 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2851 if (num_threads == 0)
2852 DEBUG("Number of threads: autodetect");
2854 DEBUG("Number of threads: %u", num_threads);
2855 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2856 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2857 DEBUG("GUID: %s", (write_flags &
2858 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2859 : guid ? "explicit" : "generate new");
2861 /* Internally, this is always called with a valid part number and total
2863 wimlib_assert(total_parts >= 1);
2864 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2866 /* A valid image (or all images) must be specified. */
2867 if (image != WIMLIB_ALL_IMAGES &&
2868 (image < 1 || image > wim->hdr.image_count))
2869 return WIMLIB_ERR_INVALID_IMAGE;
2871 /* If we need to write metadata resources, make sure the ::WIMStruct has
2872 * the needed information attached (e.g. is not a resource-only WIM,
2873 * such as a non-first part of a split WIM). */
2874 if (!wim_has_metadata(wim) &&
2875 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2876 return WIMLIB_ERR_METADATA_NOT_FOUND;
2878 /* Check for contradictory flags. */
2879 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2880 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2881 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2882 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2883 return WIMLIB_ERR_INVALID_PARAM;
2885 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2886 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2887 == (WIMLIB_WRITE_FLAG_PIPABLE |
2888 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2889 return WIMLIB_ERR_INVALID_PARAM;
2891 /* Save previous header, then start initializing the new one. */
2892 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2894 /* Set default integrity, pipable, and solid flags. */
2895 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2896 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2897 if (wim_is_pipable(wim)) {
2898 DEBUG("WIM is pipable; default to PIPABLE.");
2899 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2902 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2903 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2904 if (wim_has_integrity_table(wim)) {
2905 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2906 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2909 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2910 WIMLIB_WRITE_FLAG_SOLID))
2911 == (WIMLIB_WRITE_FLAG_PIPABLE |
2912 WIMLIB_WRITE_FLAG_SOLID))
2914 ERROR("Cannot specify both PIPABLE and SOLID!");
2915 return WIMLIB_ERR_INVALID_PARAM;
2918 /* Set appropriate magic number. */
2919 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2920 wim->hdr.magic = PWM_MAGIC;
2922 wim->hdr.magic = WIM_MAGIC;
2924 /* Set appropriate version number. */
2925 if ((write_flags & WIMLIB_WRITE_FLAG_SOLID) ||
2926 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2927 wim->hdr.wim_version = WIM_VERSION_SOLID;
2929 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2931 /* Clear header flags that will be set automatically. */
2932 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2933 WIM_HDR_FLAG_RESOURCE_ONLY |
2934 WIM_HDR_FLAG_SPANNED |
2935 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2937 /* Set SPANNED header flag if writing part of a split WIM. */
2938 if (total_parts != 1)
2939 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2941 /* Set part number and total parts of split WIM. This will be 1 and 1
2942 * if the WIM is standalone. */
2943 wim->hdr.part_number = part_number;
2944 wim->hdr.total_parts = total_parts;
2946 /* Set compression type if different. */
2947 if (wim->compression_type != wim->out_compression_type) {
2948 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2949 wimlib_assert(ret == 0);
2952 /* Set chunk size if different. */
2953 wim->hdr.chunk_size = wim->out_chunk_size;
2956 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2958 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2960 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2963 /* Clear references to resources that have not been written yet. */
2964 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2965 zero_reshdr(&wim->hdr.xml_data_reshdr);
2966 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2967 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2969 /* Set image count and boot index correctly for single image writes. */
2970 if (image != WIMLIB_ALL_IMAGES) {
2971 wim->hdr.image_count = 1;
2972 if (wim->hdr.boot_idx == image)
2973 wim->hdr.boot_idx = 1;
2975 wim->hdr.boot_idx = 0;
2978 /* Split WIMs can't be bootable. */
2979 if (total_parts != 1)
2980 wim->hdr.boot_idx = 0;
2982 /* Initialize output file descriptor. */
2983 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2984 /* File descriptor was explicitly provided. Return error if
2985 * file descriptor is not seekable, unless writing a pipable WIM
2987 wim->out_fd.fd = *(const int*)path_or_fd;
2988 wim->out_fd.offset = 0;
2989 if (!filedes_is_seekable(&wim->out_fd)) {
2990 ret = WIMLIB_ERR_INVALID_PARAM;
2991 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2992 goto out_restore_hdr;
2993 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2994 ERROR("Can't include integrity check when "
2995 "writing pipable WIM to pipe!");
2996 goto out_restore_hdr;
3001 /* Filename of WIM to write was provided; open file descriptor
3003 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
3004 O_TRUNC | O_CREAT | O_RDWR);
3006 goto out_restore_hdr;
3009 /* Write initial header. This is merely a "dummy" header since it
3010 * doesn't have all the information yet, so it will be overwritten later
3011 * (unless writing a pipable WIM). */
3012 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3013 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3014 ret = write_wim_header(&wim->hdr, &wim->out_fd);
3015 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3017 goto out_restore_hdr;
3019 /* Write metadata resources and streams. */
3020 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
3021 /* Default case: create a normal (non-pipable) WIM. */
3022 ret = write_wim_streams(wim, image, write_flags, num_threads,
3023 stream_list_override,
3024 &lookup_table_list);
3026 goto out_restore_hdr;
3028 ret = write_wim_metadata_resources(wim, image, write_flags);
3030 goto out_restore_hdr;
3032 /* Non-default case: create pipable WIM. */
3033 ret = write_pipable_wim(wim, image, write_flags, num_threads,
3034 stream_list_override,
3035 &lookup_table_list);
3037 goto out_restore_hdr;
3038 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
3042 /* Write lookup table, XML data, and (optional) integrity table. */
3043 ret = finish_write(wim, image, write_flags, &lookup_table_list);
3045 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3046 (void)close_wim_writable(wim, write_flags);
3047 DEBUG("ret=%d", ret);
3051 /* Write a standalone WIM to a file or file descriptor. */
3053 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
3054 int image, int write_flags, unsigned num_threads)
3056 return write_wim_part(wim, path_or_fd, image, write_flags,
3057 num_threads, 1, 1, NULL, NULL);
3060 /* API function documented in wimlib.h */
3062 wimlib_write(WIMStruct *wim, const tchar *path,
3063 int image, int write_flags, unsigned num_threads)
3065 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3066 return WIMLIB_ERR_INVALID_PARAM;
3068 if (path == NULL || path[0] == T('\0'))
3069 return WIMLIB_ERR_INVALID_PARAM;
3071 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3074 /* API function documented in wimlib.h */
3076 wimlib_write_to_fd(WIMStruct *wim, int fd,
3077 int image, int write_flags, unsigned num_threads)
3079 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3080 return WIMLIB_ERR_INVALID_PARAM;
3083 return WIMLIB_ERR_INVALID_PARAM;
3085 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3087 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3091 any_images_modified(WIMStruct *wim)
3093 for (int i = 0; i < wim->hdr.image_count; i++)
3094 if (wim->image_metadata[i]->modified)
3100 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
3102 const WIMStruct *wim = _wim;
3103 off_t end_offset = *(const off_t*)wim->private;
3105 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
3106 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
3107 return WIMLIB_ERR_RESOURCE_ORDER;
3111 /* Make sure no file or metadata resources are located after the XML data (or
3112 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3113 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3115 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3120 wim->private = &end_offset;
3121 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
3125 for (i = 0; i < wim->hdr.image_count; i++) {
3126 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
3134 * Overwrite a WIM, possibly appending streams to it.
3136 * A WIM looks like (or is supposed to look like) the following:
3138 * Header (212 bytes)
3139 * Streams and metadata resources (variable size)
3140 * Lookup table (variable size)
3141 * XML data (variable size)
3142 * Integrity table (optional) (variable size)
3144 * If we are not adding any streams or metadata resources, the lookup table is
3145 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3146 * header. This operation is potentially unsafe if the program is abruptly
3147 * terminated while the XML data or integrity table are being overwritten, but
3148 * before the new header has been written. To partially alleviate this problem,
3149 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3150 * finish_write() to cause a temporary WIM header to be written after the XML
3151 * data has been written. This may prevent the WIM from becoming corrupted if
3152 * the program is terminated while the integrity table is being calculated (but
3153 * no guarantees, due to write re-ordering...).
3155 * If we are adding new streams or images (metadata resources), the lookup table
3156 * needs to be changed, and those streams need to be written. In this case, we
3157 * try to perform a safe update of the WIM file by writing the streams *after*
3158 * the end of the previous WIM, then writing the new lookup table, XML data, and
3159 * (optionally) integrity table following the new streams. This will produce a
3160 * layout like the following:
3162 * Header (212 bytes)
3163 * (OLD) Streams and metadata resources (variable size)
3164 * (OLD) Lookup table (variable size)
3165 * (OLD) XML data (variable size)
3166 * (OLD) Integrity table (optional) (variable size)
3167 * (NEW) Streams and metadata resources (variable size)
3168 * (NEW) Lookup table (variable size)
3169 * (NEW) XML data (variable size)
3170 * (NEW) Integrity table (optional) (variable size)
3172 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3173 * the header is overwritten to point to the new lookup table, XML data, and
3174 * integrity table, to produce the following layout:
3176 * Header (212 bytes)
3177 * Streams and metadata resources (variable size)
3178 * Nothing (variable size)
3179 * More Streams and metadata resources (variable size)
3180 * Lookup table (variable size)
3181 * XML data (variable size)
3182 * Integrity table (optional) (variable size)
3184 * This method allows an image to be appended to a large WIM very quickly, and
3185 * is crash-safe except in the case of write re-ordering, but the
3186 * disadvantage is that a small hole is left in the WIM where the old lookup
3187 * table, xml data, and integrity table were. (These usually only take up a
3188 * small amount of space compared to the streams, however.)
3191 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3195 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
3196 struct wim_header hdr_save;
3197 struct list_head stream_list;
3198 struct list_head lookup_table_list;
3199 struct filter_context filter_ctx;
3201 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3203 /* Save original header so it can be restored in case of error */
3204 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3206 /* Set default integrity flag. */
3207 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3208 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3209 if (wim_has_integrity_table(wim))
3210 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3212 /* Set WIM version if writing solid resources. */
3213 if (write_flags & WIMLIB_WRITE_FLAG_SOLID)
3214 wim->hdr.wim_version = WIM_VERSION_SOLID;
3216 /* Set additional flags for overwrite. */
3217 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3218 WIMLIB_WRITE_FLAG_STREAMS_OK;
3220 /* Make sure that the integrity table (if present) is after the XML
3221 * data, and that there are no stream resources, metadata resources, or
3222 * lookup tables after the XML data. Otherwise, these data would be
3224 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3225 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3226 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
3227 wim->hdr.lookup_table_reshdr.size_in_wim;
3228 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3229 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3230 WARNING("Didn't expect the integrity table to be before the XML data");
3231 ret = WIMLIB_ERR_RESOURCE_ORDER;
3232 goto out_restore_memory_hdr;
3235 if (old_lookup_table_end > old_xml_begin) {
3236 WARNING("Didn't expect the lookup table to be after the XML data");
3237 ret = WIMLIB_ERR_RESOURCE_ORDER;
3238 goto out_restore_memory_hdr;
3241 /* Set @old_wim_end, which indicates the point beyond which we don't
3242 * allow any file and metadata resources to appear without returning
3243 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3244 * overwrite these resources). */
3245 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
3246 /* If no images have been modified and no images have been
3247 * deleted, a new lookup table does not need to be written. We
3248 * shall write the new XML data and optional integrity table
3249 * immediately after the lookup table. Note that this may
3250 * overwrite an existing integrity table. */
3251 DEBUG("Skipping writing lookup table "
3252 "(no images modified or deleted)");
3253 old_wim_end = old_lookup_table_end;
3254 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3255 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3256 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3257 /* Old WIM has an integrity table; begin writing new streams
3259 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3260 wim->hdr.integrity_table_reshdr.size_in_wim;
3262 /* No existing integrity table; begin writing new streams after
3263 * the old XML data. */
3264 old_wim_end = old_xml_end;
3267 ret = check_resource_offsets(wim, old_wim_end);
3269 goto out_restore_memory_hdr;
3271 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3272 &stream_list, &lookup_table_list,
3275 goto out_restore_memory_hdr;
3277 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3279 goto out_restore_memory_hdr;
3281 ret = lock_wim_for_append(wim);
3285 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3286 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3287 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3289 ERROR_WITH_ERRNO("Error updating WIM header flags");
3290 goto out_unlock_wim;
3293 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3294 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3295 ret = WIMLIB_ERR_WRITE;
3296 goto out_restore_physical_hdr;
3299 ret = wim_write_stream_list(wim,
3307 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3311 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3312 &lookup_table_list);
3316 unlock_wim_for_append(wim);
3320 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3321 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3322 wim->filename, old_wim_end);
3323 /* Return value of ftruncate() is ignored because this is
3324 * already an error path. */
3325 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3327 out_restore_physical_hdr:
3328 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3330 unlock_wim_for_append(wim);
3332 (void)close_wim_writable(wim, write_flags);
3333 out_restore_memory_hdr:
3334 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3339 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3341 size_t wim_name_len;
3344 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3346 /* Write the WIM to a temporary file in the same directory as the
3348 wim_name_len = tstrlen(wim->filename);
3349 tchar tmpfile[wim_name_len + 10];
3350 tmemcpy(tmpfile, wim->filename, wim_name_len);
3351 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3352 tmpfile[wim_name_len + 9] = T('\0');
3354 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3356 WIMLIB_WRITE_FLAG_FSYNC |
3357 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3364 if (filedes_valid(&wim->in_fd)) {
3365 filedes_close(&wim->in_fd);
3366 filedes_invalidate(&wim->in_fd);
3369 /* Rename the new WIM file to the original WIM file. Note: on Windows
3370 * this actually calls win32_rename_replacement(), not _wrename(), so
3371 * that removing the existing destination file can be handled. */
3372 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3373 ret = trename(tmpfile, wim->filename);
3375 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3376 tmpfile, wim->filename);
3383 return WIMLIB_ERR_RENAME;
3386 union wimlib_progress_info progress;
3387 progress.rename.from = tmpfile;
3388 progress.rename.to = wim->filename;
3389 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3390 &progress, wim->progctx);
3393 /* Determine if the specified WIM file may be updated by appending in-place
3394 * rather than writing and replacing it with an entirely new file. */
3396 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3398 /* REBUILD flag forces full rebuild. */
3399 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3402 /* Image deletions cause full rebuild by default. */
3403 if (wim->image_deletion_occurred &&
3404 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3407 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3408 * turned into a pipable WIM in-place. */
3409 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3412 /* The default compression type and compression chunk size selected for
3413 * the output WIM must be the same as those currently used for the WIM.
3415 if (wim->compression_type != wim->out_compression_type)
3417 if (wim->chunk_size != wim->out_chunk_size)
3423 /* API function documented in wimlib.h */
3425 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3430 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3431 return WIMLIB_ERR_INVALID_PARAM;
3434 return WIMLIB_ERR_NO_FILENAME;
3436 orig_hdr_flags = wim->hdr.flags;
3437 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3438 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3439 ret = can_modify_wim(wim);
3440 wim->hdr.flags = orig_hdr_flags;
3444 if (can_overwrite_wim_inplace(wim, write_flags)) {
3445 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3446 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3448 WARNING("Falling back to re-building entire WIM");
3450 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);