4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013, 2014 Eric Biggers
11 * This file is free software; you can redistribute it and/or modify it under
12 * the terms of the GNU Lesser General Public License as published by the Free
13 * Software Foundation; either version 3 of the License, or (at your option) any
16 * This file is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this file; if not, see http://www.gnu.org/licenses/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
31 * overwrite the LIST_HEAD macro. */
32 # include <sys/file.h>
35 #include "wimlib/assert.h"
36 #include "wimlib/chunk_compressor.h"
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/header.h"
41 #include "wimlib/inode.h"
42 #include "wimlib/integrity.h"
43 #include "wimlib/lookup_table.h"
44 #include "wimlib/metadata.h"
45 #include "wimlib/paths.h"
46 #include "wimlib/progress.h"
47 #include "wimlib/resource.h"
49 # include "wimlib/win32.h" /* win32_rename_replacement() */
51 #include "wimlib/write.h"
52 #include "wimlib/xml.h"
63 /* wimlib internal flags used when writing resources. */
64 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
65 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
66 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
67 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
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_PACK_STREAMS)
79 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
80 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
81 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
82 return write_resource_flags;
85 struct filter_context {
90 /* Determine specified stream should be filtered out from the write.
94 * < 0 : The stream should be hard-filtered; that is, not included in the
96 * 0 : The stream should not be filtered out.
97 * > 0 : The stream should be soft-filtered; that is, it already exists in the
98 * WIM file and may not need to be written again.
101 stream_filtered(const struct wim_lookup_table_entry *lte,
102 const struct filter_context *ctx)
110 write_flags = ctx->write_flags;
113 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
114 lte->resource_location == RESOURCE_IN_WIM &&
115 lte->rspec->wim == wim)
118 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
119 lte->resource_location == RESOURCE_IN_WIM &&
120 lte->rspec->wim != wim)
127 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
128 struct filter_context *ctx)
130 return stream_filtered(lte, ctx) < 0;
134 may_soft_filter_streams(const struct filter_context *ctx)
138 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
142 may_hard_filter_streams(const struct filter_context *ctx)
146 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
150 may_filter_streams(const struct filter_context *ctx)
152 return (may_soft_filter_streams(ctx) ||
153 may_hard_filter_streams(ctx));
157 /* Return true if the specified resource is compressed and the compressed data
158 * can be reused with the specified output parameters. */
160 can_raw_copy(const struct wim_lookup_table_entry *lte,
161 int write_resource_flags, int out_ctype, u32 out_chunk_size)
163 const struct wim_resource_spec *rspec;
165 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
168 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
171 if (lte->resource_location != RESOURCE_IN_WIM)
176 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
179 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
180 /* Normal compressed resource: Must use same compression type
182 return (rspec->compression_type == out_ctype &&
183 rspec->chunk_size == out_chunk_size);
186 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
187 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
189 /* Packed resource: Such resources may contain multiple streams,
190 * and in general only a subset of them need to be written. As
191 * a heuristic, re-use the raw data if more than two-thirds the
192 * uncompressed size is being written. */
194 /* Note: packed resources contain a header that specifies the
195 * compression type and chunk size; therefore we don't need to
196 * check if they are compatible with @out_ctype and
197 * @out_chunk_size. */
199 struct wim_lookup_table_entry *res_stream;
202 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
203 if (res_stream->will_be_in_output_wim)
204 write_size += res_stream->size;
206 return (write_size > rspec->uncompressed_size * 2 / 3);
213 filter_resource_flags(u8 flags)
215 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
216 WIM_RESHDR_FLAG_COMPRESSED |
217 WIM_RESHDR_FLAG_SPANNED |
218 WIM_RESHDR_FLAG_FREE));
222 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
224 const struct wim_resource_spec *rspec;
226 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
229 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
231 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
233 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
234 lte->out_reshdr.uncompressed_size = 0;
235 lte->out_reshdr.size_in_wim = lte->size;
237 lte->out_res_offset_in_wim = rspec->offset_in_wim;
238 lte->out_res_size_in_wim = rspec->size_in_wim;
239 lte->out_res_uncompressed_size = rspec->uncompressed_size;
241 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
243 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
244 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
245 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
247 lte->out_reshdr.flags = lte->flags;
251 /* Write the header for a stream in a pipable WIM. */
253 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
254 struct filedes *out_fd,
255 int additional_reshdr_flags)
257 struct pwm_stream_hdr stream_hdr;
261 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
262 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
263 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
264 zero_out_hash(stream_hdr.hash);
266 wimlib_assert(!lte->unhashed);
267 copy_hash(stream_hdr.hash, lte->hash);
270 reshdr_flags = filter_resource_flags(lte->flags);
271 reshdr_flags |= additional_reshdr_flags;
272 stream_hdr.flags = cpu_to_le32(reshdr_flags);
273 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
275 ERROR_WITH_ERRNO("Write error");
279 struct write_streams_progress_data {
280 wimlib_progress_func_t progfunc;
282 union wimlib_progress_info progress;
283 uint64_t next_progress;
287 do_write_streams_progress(struct write_streams_progress_data *progress_data,
292 union wimlib_progress_info *progress = &progress_data->progress;
296 progress->write_streams.total_bytes -= complete_size;
297 progress->write_streams.total_streams -= complete_count;
298 if (progress_data->next_progress != ~(uint64_t)0 &&
299 progress_data->next_progress > progress->write_streams.total_bytes)
301 progress_data->next_progress = progress->write_streams.total_bytes;
304 progress->write_streams.completed_bytes += complete_size;
305 progress->write_streams.completed_streams += complete_count;
308 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
310 ret = call_progress(progress_data->progfunc,
311 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
313 progress_data->progctx);
317 if (progress_data->next_progress == progress->write_streams.total_bytes) {
318 progress_data->next_progress = ~(uint64_t)0;
320 /* Handle rate-limiting of messages */
322 /* Send new message as soon as another 1/128 of the
323 * total has been written. (Arbitrary number.) */
324 progress_data->next_progress =
325 progress->write_streams.completed_bytes +
326 progress->write_streams.total_bytes / 128;
328 /* ... Unless that would be more than 5000000 bytes, in
329 * which case send the next after the next 5000000
330 * bytes. (Another arbitrary number.) */
331 if (progress->write_streams.completed_bytes + 5000000 <
332 progress_data->next_progress)
333 progress_data->next_progress =
334 progress->write_streams.completed_bytes + 5000000;
336 /* ... But always send a message as soon as we're
337 * completely done. */
338 if (progress->write_streams.total_bytes <
339 progress_data->next_progress)
340 progress_data->next_progress =
341 progress->write_streams.total_bytes;
347 struct write_streams_ctx {
348 /* File descriptor the streams are being written to. */
349 struct filedes *out_fd;
351 /* Lookup table for the WIMStruct on whose behalf the streams are being
353 struct wim_lookup_table *lookup_table;
355 /* Compression format to use. */
358 /* Maximum uncompressed chunk size in compressed resources to use. */
361 /* Flags that affect how the streams will be written. */
362 int write_resource_flags;
364 /* Data used for issuing WRITE_STREAMS progress. */
365 struct write_streams_progress_data progress_data;
367 struct filter_context *filter_ctx;
369 /* Upper bound on the total number of bytes that need to be compressed.
371 u64 num_bytes_to_compress;
373 /* Pointer to the chunk_compressor implementation being used for
374 * compressing chunks of data, or NULL if chunks are being written
376 struct chunk_compressor *compressor;
378 /* Buffer for dividing the read data into chunks of size
379 * @out_chunk_size. */
382 /* Number of bytes in @chunk_buf that are currently filled. */
383 size_t chunk_buf_filled;
385 /* List of streams that currently have chunks being compressed. */
386 struct list_head pending_streams;
388 /* List of streams in the resource pack. Streams are moved here after
389 * @pending_streams only when writing a packed resource. */
390 struct list_head pack_streams;
392 /* Current uncompressed offset in the stream being read. */
393 u64 cur_read_stream_offset;
395 /* Uncompressed size of the stream currently being read. */
396 u64 cur_read_stream_size;
398 /* Current uncompressed offset in the stream being written. */
399 u64 cur_write_stream_offset;
401 /* Uncompressed size of resource currently being written. */
402 u64 cur_write_res_size;
404 /* Array that is filled in with compressed chunk sizes as a resource is
408 /* Index of next entry in @chunk_csizes to fill in. */
411 /* Number of entries in @chunk_csizes currently allocated. */
412 size_t num_alloc_chunks;
414 /* Offset in the output file of the start of the chunks of the resource
415 * currently being written. */
416 u64 chunks_start_offset;
419 /* Reserve space for the chunk table and prepare to accumulate the chunk table
422 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
424 u64 expected_num_chunks;
425 u64 expected_num_chunk_entries;
429 /* Calculate the number of chunks and chunk entries that should be
430 * needed for the resource. These normally will be the final values,
431 * but in PACKED_STREAMS mode some of the streams we're planning to
432 * write into the resource may be duplicates, and therefore discarded,
433 * potentially decreasing the number of chunk entries needed. */
434 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
435 expected_num_chunk_entries = expected_num_chunks;
436 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
437 expected_num_chunk_entries--;
439 /* Make sure the chunk_csizes array is long enough to store the
440 * compressed size of each chunk. */
441 if (expected_num_chunks > ctx->num_alloc_chunks) {
442 u64 new_length = expected_num_chunks + 50;
444 if ((size_t)new_length != new_length) {
445 ERROR("Resource size too large (%"PRIu64" bytes!",
447 return WIMLIB_ERR_NOMEM;
450 FREE(ctx->chunk_csizes);
451 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
452 if (ctx->chunk_csizes == NULL) {
453 ctx->num_alloc_chunks = 0;
454 return WIMLIB_ERR_NOMEM;
456 ctx->num_alloc_chunks = new_length;
459 ctx->chunk_index = 0;
461 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
462 /* Reserve space for the chunk table in the output file. In the
463 * case of packed resources this reserves the upper bound for
464 * the needed space, not necessarily the exact space which will
465 * prove to be needed. At this point, we just use @chunk_csizes
466 * for a buffer of 0's because the actual compressed chunk sizes
468 reserve_size = expected_num_chunk_entries *
469 get_chunk_entry_size(res_expected_size,
470 0 != (ctx->write_resource_flags &
471 WRITE_RESOURCE_FLAG_PACK_STREAMS));
472 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
473 reserve_size += sizeof(struct alt_chunk_table_header_disk);
474 memset(ctx->chunk_csizes, 0, reserve_size);
475 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
483 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
487 wimlib_assert(res_expected_size != 0);
489 if (ctx->compressor != NULL) {
490 ret = begin_chunk_table(ctx, res_expected_size);
495 /* Output file descriptor is now positioned at the offset at which to
496 * write the first chunk of the resource. */
497 ctx->chunks_start_offset = ctx->out_fd->offset;
498 ctx->cur_write_stream_offset = 0;
499 ctx->cur_write_res_size = res_expected_size;
504 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
505 u64 *res_start_offset_ret, u64 *res_store_size_ret)
507 size_t actual_num_chunks;
508 size_t actual_num_chunk_entries;
509 size_t chunk_entry_size;
512 actual_num_chunks = ctx->chunk_index;
513 actual_num_chunk_entries = actual_num_chunks;
514 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
515 actual_num_chunk_entries--;
517 chunk_entry_size = get_chunk_entry_size(res_actual_size,
518 0 != (ctx->write_resource_flags &
519 WRITE_RESOURCE_FLAG_PACK_STREAMS));
521 typedef le64 _may_alias_attribute aliased_le64_t;
522 typedef le32 _may_alias_attribute aliased_le32_t;
524 if (chunk_entry_size == 4) {
525 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
527 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
528 for (size_t i = 0; i < actual_num_chunk_entries; i++)
529 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
531 u32 offset = ctx->chunk_csizes[0];
532 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
533 u32 next_size = ctx->chunk_csizes[i + 1];
534 entries[i] = cpu_to_le32(offset);
539 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
541 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
542 for (size_t i = 0; i < actual_num_chunk_entries; i++)
543 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
545 u64 offset = ctx->chunk_csizes[0];
546 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
547 u64 next_size = ctx->chunk_csizes[i + 1];
548 entries[i] = cpu_to_le64(offset);
554 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
555 u64 res_start_offset;
558 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
559 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
562 res_end_offset = ctx->out_fd->offset;
563 res_start_offset = ctx->chunks_start_offset;
565 res_end_offset = ctx->out_fd->offset;
567 u64 chunk_table_offset;
569 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
571 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
572 struct alt_chunk_table_header_disk hdr;
574 hdr.res_usize = cpu_to_le64(res_actual_size);
575 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
576 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
578 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
579 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
580 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
582 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
583 chunk_table_offset - sizeof(hdr));
586 res_start_offset = chunk_table_offset - sizeof(hdr);
588 res_start_offset = chunk_table_offset;
591 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
592 chunk_table_size, chunk_table_offset);
597 *res_start_offset_ret = res_start_offset;
598 *res_store_size_ret = res_end_offset - res_start_offset;
603 ERROR_WITH_ERRNO("Write error");
607 /* Finish writing a WIM resource by writing or updating the chunk table (if not
608 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
610 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
614 u64 res_uncompressed_size;
615 u64 res_offset_in_wim;
617 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
618 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS));
619 res_uncompressed_size = ctx->cur_write_res_size;
621 if (ctx->compressor) {
622 ret = end_chunk_table(ctx, res_uncompressed_size,
623 &res_offset_in_wim, &res_size_in_wim);
627 res_offset_in_wim = ctx->chunks_start_offset;
628 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
630 out_reshdr->uncompressed_size = res_uncompressed_size;
631 out_reshdr->size_in_wim = res_size_in_wim;
632 out_reshdr->offset_in_wim = res_offset_in_wim;
633 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
634 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
638 /* No more data streams of the file at @path are needed. */
640 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
642 union wimlib_progress_info info;
644 info.done_with_file.path_to_file = path;
646 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
651 is_file_stream(const struct wim_lookup_table_entry *lte)
653 return lte->resource_location == RESOURCE_IN_FILE_ON_DISK
655 || lte->resource_location == RESOURCE_IN_WINNT_FILE_ON_DISK
656 || lte->resource_location == RESOURCE_WIN32_ENCRYPTED
662 do_done_with_stream(struct wim_lookup_table_entry *lte,
663 wimlib_progress_func_t progfunc, void *progctx)
666 struct wim_inode *inode;
668 if (!lte->may_send_done_with_file)
671 inode = lte->file_inode;
673 wimlib_assert(inode != NULL);
674 wimlib_assert(inode->num_remaining_streams > 0);
675 if (--inode->num_remaining_streams > 0)
679 /* XXX: This logic really should be somewhere else. */
681 /* We want the path to the file, but lte->file_on_disk might actually
682 * refer to a named data stream. Temporarily strip the named data
683 * stream from the path. */
684 wchar_t *p_colon = NULL;
685 wchar_t *p_question_mark = NULL;
686 const wchar_t *p_stream_name;
688 p_stream_name = path_stream_name(lte->file_on_disk);
689 if (unlikely(p_stream_name)) {
690 p_colon = (wchar_t *)(p_stream_name - 1);
691 wimlib_assert(*p_colon == L':');
695 /* We also should use a fake Win32 path instead of a NT path */
696 if (!wcsncmp(lte->file_on_disk, L"\\??\\", 4)) {
697 p_question_mark = <e->file_on_disk[1];
698 *p_question_mark = L'\\';
702 ret = done_with_file(lte->file_on_disk, progfunc, progctx);
708 *p_question_mark = L'?';
713 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
715 done_with_stream(struct wim_lookup_table_entry *lte,
716 struct write_streams_ctx *ctx)
718 if (likely(!(ctx->write_resource_flags &
719 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)))
721 return do_done_with_stream(lte, ctx->progress_data.progfunc,
722 ctx->progress_data.progctx);
725 /* Begin processing a stream for writing. */
727 write_stream_begin_read(struct wim_lookup_table_entry *lte, void *_ctx)
729 struct write_streams_ctx *ctx = _ctx;
732 wimlib_assert(lte->size > 0);
734 ctx->cur_read_stream_offset = 0;
735 ctx->cur_read_stream_size = lte->size;
737 /* As an optimization, we allow some streams to be "unhashed", meaning
738 * their SHA1 message digests are unknown. This is the case with
739 * streams that are added by scanning a directry tree with
740 * wimlib_add_image(), for example. Since WIM uses single-instance
741 * streams, we don't know whether such each such stream really need to
742 * written until it is actually checksummed, unless it has a unique
743 * size. In such cases we read and checksum the stream in this
744 * function, thereby advancing ahead of read_stream_list(), which will
745 * still provide the data again to write_stream_process_chunk(). This
746 * is okay because an unhashed stream cannot be in a WIM resource, which
747 * might be costly to decompress. */
748 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
750 struct wim_lookup_table_entry *lte_new;
752 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
755 if (lte_new != lte) {
756 /* Duplicate stream detected. */
758 if (lte_new->will_be_in_output_wim ||
759 stream_filtered(lte_new, ctx->filter_ctx))
761 /* The duplicate stream is already being
762 * included in the output WIM, or it would be
763 * filtered out if it had been. Skip writing
764 * this stream (and reading it again) entirely,
765 * passing its output reference count to the
766 * duplicate stream in the former case. */
767 DEBUG("Discarding duplicate stream of "
768 "length %"PRIu64, lte->size);
769 ret = do_write_streams_progress(&ctx->progress_data,
772 list_del(<e->write_streams_list);
773 list_del(<e->lookup_table_list);
774 if (lte_new->will_be_in_output_wim)
775 lte_new->out_refcnt += lte->out_refcnt;
776 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
777 ctx->cur_write_res_size -= lte->size;
779 ret = done_with_stream(lte, ctx);
780 free_lookup_table_entry(lte);
783 return BEGIN_STREAM_STATUS_SKIP_STREAM;
785 /* The duplicate stream can validly be written,
786 * but was not marked as such. Discard the
787 * current stream entry and use the duplicate,
788 * but actually freeing the current entry must
789 * wait until read_stream_list() has finished
790 * reading its data. */
791 DEBUG("Stream duplicate, but not already "
792 "selected for writing.");
793 list_replace(<e->write_streams_list,
794 <e_new->write_streams_list);
795 list_replace(<e->lookup_table_list,
796 <e_new->lookup_table_list);
797 lte->will_be_in_output_wim = 0;
798 lte_new->out_refcnt = lte->out_refcnt;
799 lte_new->will_be_in_output_wim = 1;
800 lte_new->may_send_done_with_file = 0;
805 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
809 /* Rewrite a stream that was just written compressed as uncompressed instead.
810 * This function is optional, but if a stream did not compress to less than its
811 * original size, it might as well be written uncompressed. */
813 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
814 struct filedes *out_fd)
817 u64 begin_offset = lte->out_reshdr.offset_in_wim;
818 u64 end_offset = out_fd->offset;
820 if (filedes_seek(out_fd, begin_offset) == -1)
823 ret = extract_full_stream_to_fd(lte, out_fd);
825 /* Error reading the uncompressed data. */
826 if (out_fd->offset == begin_offset &&
827 filedes_seek(out_fd, end_offset) != -1)
829 /* Nothing was actually written yet, and we successfully
830 * seeked to the end of the compressed resource, so
831 * don't issue a hard error; just keep the compressed
832 * resource instead. */
833 WARNING("Recovered compressed stream of "
834 "size %"PRIu64", continuing on.",
841 wimlib_assert(out_fd->offset - begin_offset == lte->size);
843 if (out_fd->offset < end_offset &&
844 0 != ftruncate(out_fd->fd, out_fd->offset))
846 ERROR_WITH_ERRNO("Can't truncate output file to "
847 "offset %"PRIu64, out_fd->offset);
848 return WIMLIB_ERR_WRITE;
851 lte->out_reshdr.size_in_wim = lte->size;
852 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
853 WIM_RESHDR_FLAG_PACKED_STREAMS);
857 /* Returns true if the specified stream should be truncated from the WIM file
858 * and re-written as uncompressed. lte->out_reshdr must be filled in from the
859 * initial write of the stream. */
861 should_rewrite_stream_uncompressed(const struct write_streams_ctx *ctx,
862 const struct wim_lookup_table_entry *lte)
864 /* If the compressed data is smaller than the uncompressed data, prefer
865 * the compressed data. */
866 if (lte->out_reshdr.size_in_wim < lte->out_reshdr.uncompressed_size)
869 /* If we're not actually writing compressed data, then there's no need
871 if (!ctx->compressor)
874 /* If writing a pipable WIM, everything we write to the output is final
875 * (it might actually be a pipe!). */
876 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)
879 /* If the stream that would need to be re-read is located in a solid
880 * block in another WIM file, then re-reading it would be costly. So
883 * Exception: if the compressed size happens to be *exactly* the same as
884 * the uncompressed size, then the stream *must* be written uncompressed
885 * in order to remain compatible with the Windows Overlay Filesystem
886 * Filter Driver (WOF).
888 * TODO: we are currently assuming that the optimization for
889 * single-chunk resources in maybe_rewrite_stream_uncompressed()
890 * prevents this case from being triggered too often. To fully prevent
891 * excessive decompressions in degenerate cases, we really should
892 * obtain the uncompressed data by decompressing the compressed data we
893 * wrote to the output file.
895 if ((lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
896 (lte->out_reshdr.size_in_wim != lte->out_reshdr.uncompressed_size))
903 maybe_rewrite_stream_uncompressed(struct write_streams_ctx *ctx,
904 struct wim_lookup_table_entry *lte)
906 if (!should_rewrite_stream_uncompressed(ctx, lte))
909 /* Regular (non-solid) WIM resources with exactly one chunk and
910 * compressed size equal to uncompressed size are exactly the same as
911 * the corresponding compressed data --- since there must be 0 entries
912 * in the chunk table and the only chunk must be stored uncompressed.
913 * In this case, there's no need to rewrite anything. */
914 if (ctx->chunk_index == 1 &&
915 lte->out_reshdr.size_in_wim == lte->out_reshdr.uncompressed_size)
917 lte->out_reshdr.flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
921 return write_stream_uncompressed(lte, ctx->out_fd);
924 /* Write the next chunk of (typically compressed) data to the output WIM,
925 * handling the writing of the chunk table. */
927 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
928 size_t csize, size_t usize)
932 struct wim_lookup_table_entry *lte;
933 u32 completed_stream_count;
936 lte = list_entry(ctx->pending_streams.next,
937 struct wim_lookup_table_entry, write_streams_list);
939 if (ctx->cur_write_stream_offset == 0 &&
940 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
942 /* Starting to write a new stream in non-packed mode. */
944 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
945 int additional_reshdr_flags = 0;
946 if (ctx->compressor != NULL)
947 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
949 DEBUG("Writing pipable WIM stream header "
950 "(offset=%"PRIu64")", ctx->out_fd->offset);
952 ret = write_pwm_stream_header(lte, ctx->out_fd,
953 additional_reshdr_flags);
958 ret = begin_write_resource(ctx, lte->size);
963 if (ctx->compressor != NULL) {
964 /* Record the compresed chunk size. */
965 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
966 ctx->chunk_csizes[ctx->chunk_index++] = csize;
968 /* If writing a pipable WIM, before the chunk data write a chunk
969 * header that provides the compressed chunk size. */
970 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
971 struct pwm_chunk_hdr chunk_hdr = {
972 .compressed_size = cpu_to_le32(csize),
974 ret = full_write(ctx->out_fd, &chunk_hdr,
981 /* Write the chunk data. */
982 ret = full_write(ctx->out_fd, cchunk, csize);
986 ctx->cur_write_stream_offset += usize;
988 completed_size = usize;
989 completed_stream_count = 0;
990 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
991 /* Wrote chunk in packed mode. It may have finished multiple
993 struct wim_lookup_table_entry *next_lte;
995 while (lte && ctx->cur_write_stream_offset >= lte->size) {
997 ctx->cur_write_stream_offset -= lte->size;
999 if (ctx->cur_write_stream_offset)
1000 next_lte = list_entry(lte->write_streams_list.next,
1001 struct wim_lookup_table_entry,
1002 write_streams_list);
1006 ret = done_with_stream(lte, ctx);
1009 list_move_tail(<e->write_streams_list, &ctx->pack_streams);
1010 completed_stream_count++;
1015 /* Wrote chunk in non-packed mode. It may have finished a
1017 if (ctx->cur_write_stream_offset == lte->size) {
1019 wimlib_assert(ctx->cur_write_stream_offset ==
1020 ctx->cur_write_res_size);
1022 ret = end_write_resource(ctx, <e->out_reshdr);
1026 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1027 if (ctx->compressor != NULL)
1028 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
1030 ret = maybe_rewrite_stream_uncompressed(ctx, lte);
1034 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
1036 ctx->cur_write_stream_offset = 0;
1038 ret = done_with_stream(lte, ctx);
1041 list_del(<e->write_streams_list);
1042 completed_stream_count++;
1046 return do_write_streams_progress(&ctx->progress_data,
1047 completed_size, completed_stream_count,
1051 ERROR_WITH_ERRNO("Write error");
1056 submit_chunk_for_compression(struct write_streams_ctx *ctx,
1057 const void *chunk, size_t size)
1059 /* While we are unable to submit the chunk for compression (due to too
1060 * many chunks already outstanding), retrieve and write the next
1061 * compressed chunk. */
1062 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
1069 bret = ctx->compressor->get_chunk(ctx->compressor,
1070 &cchunk, &csize, &usize);
1072 wimlib_assert(bret);
1074 ret = write_chunk(ctx, cchunk, csize, usize);
1081 /* Process the next chunk of data to be written to a WIM resource. */
1083 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
1085 struct write_streams_ctx *ctx = _ctx;
1087 const u8 *chunkptr, *chunkend;
1089 wimlib_assert(size != 0);
1091 if (ctx->compressor == NULL) {
1092 /* Write chunk uncompressed. */
1093 ret = write_chunk(ctx, chunk, size, size);
1096 ctx->cur_read_stream_offset += size;
1100 /* Submit the chunk for compression, but take into account that the
1101 * @size the chunk was provided in may not correspond to the
1102 * @out_chunk_size being used for compression. */
1104 chunkend = chunkptr + size;
1106 const u8 *resized_chunk;
1107 size_t needed_chunk_size;
1109 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1110 needed_chunk_size = ctx->out_chunk_size;
1112 u64 res_bytes_remaining;
1114 res_bytes_remaining = ctx->cur_read_stream_size -
1115 ctx->cur_read_stream_offset;
1116 needed_chunk_size = min(ctx->out_chunk_size,
1117 ctx->chunk_buf_filled +
1118 res_bytes_remaining);
1121 if (ctx->chunk_buf_filled == 0 &&
1122 chunkend - chunkptr >= needed_chunk_size)
1124 /* No intermediate buffering needed. */
1125 resized_chunk = chunkptr;
1126 chunkptr += needed_chunk_size;
1127 ctx->cur_read_stream_offset += needed_chunk_size;
1129 /* Intermediate buffering needed. */
1130 size_t bytes_consumed;
1132 bytes_consumed = min(chunkend - chunkptr,
1133 needed_chunk_size - ctx->chunk_buf_filled);
1135 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
1136 chunkptr, bytes_consumed);
1138 chunkptr += bytes_consumed;
1139 ctx->cur_read_stream_offset += bytes_consumed;
1140 ctx->chunk_buf_filled += bytes_consumed;
1141 if (ctx->chunk_buf_filled == needed_chunk_size) {
1142 resized_chunk = ctx->chunk_buf;
1143 ctx->chunk_buf_filled = 0;
1150 ret = submit_chunk_for_compression(ctx, resized_chunk,
1155 } while (chunkptr != chunkend);
1159 /* Finish processing a stream for writing. It may not have been completely
1160 * written yet, as the chunk_compressor implementation may still have chunks
1161 * buffered or being compressed. */
1163 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1165 struct write_streams_ctx *ctx = _ctx;
1167 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size || status);
1169 if (!lte->will_be_in_output_wim) {
1170 /* The 'lte' stream was a duplicate. Now that its data has
1171 * finished being read, it is being discarded in favor of the
1172 * duplicate entry. It therefore is no longer needed, and we
1173 * can fire the DONE_WITH_FILE callback because the file will
1174 * not be read again.
1176 * Note: we can't yet fire DONE_WITH_FILE for non-duplicate
1177 * streams, since it needs to be possible to re-read the file if
1178 * it does not compress to less than its original size. */
1180 status = done_with_stream(lte, ctx);
1181 free_lookup_table_entry(lte);
1182 } else if (!status && lte->unhashed && ctx->lookup_table != NULL) {
1183 /* The 'lte' stream was not a duplicate and was previously
1184 * unhashed. Since we passed COMPUTE_MISSING_STREAM_HASHES to
1185 * read_stream_list(), lte->hash is now computed and valid. So
1186 * turn this stream into a "hashed" stream. */
1187 list_del(<e->unhashed_list);
1188 lookup_table_insert(ctx->lookup_table, lte);
1194 /* Compute statistics about a list of streams that will be written.
1196 * Assumes the streams are sorted such that all streams located in each distinct
1197 * WIM (specified by WIMStruct) are together. */
1199 compute_stream_list_stats(struct list_head *stream_list,
1200 struct write_streams_ctx *ctx)
1202 struct wim_lookup_table_entry *lte;
1203 u64 total_bytes = 0;
1204 u64 num_streams = 0;
1205 u64 total_parts = 0;
1206 WIMStruct *prev_wim_part = NULL;
1208 list_for_each_entry(lte, stream_list, write_streams_list) {
1210 total_bytes += lte->size;
1211 if (lte->resource_location == RESOURCE_IN_WIM) {
1212 if (prev_wim_part != lte->rspec->wim) {
1213 prev_wim_part = lte->rspec->wim;
1218 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1219 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1220 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1221 ctx->progress_data.progress.write_streams.completed_streams = 0;
1222 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1223 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1224 ctx->progress_data.progress.write_streams.completed_parts = 0;
1225 ctx->progress_data.next_progress = 0;
1228 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1229 * rather than compressed. Delete these streams from @stream_list and move them
1230 * to @raw_copy_streams. Return the total uncompressed size of the streams that
1231 * need to be compressed. */
1233 find_raw_copy_streams(struct list_head *stream_list,
1234 int write_resource_flags,
1237 struct list_head *raw_copy_streams)
1239 struct wim_lookup_table_entry *lte, *tmp;
1240 u64 num_bytes_to_compress = 0;
1242 INIT_LIST_HEAD(raw_copy_streams);
1244 /* Initialize temporary raw_copy_ok flag. */
1245 list_for_each_entry(lte, stream_list, write_streams_list)
1246 if (lte->resource_location == RESOURCE_IN_WIM)
1247 lte->rspec->raw_copy_ok = 0;
1249 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1250 if (lte->resource_location == RESOURCE_IN_WIM &&
1251 lte->rspec->raw_copy_ok)
1253 list_move_tail(<e->write_streams_list,
1255 } else if (can_raw_copy(lte, write_resource_flags,
1256 out_ctype, out_chunk_size))
1258 lte->rspec->raw_copy_ok = 1;
1259 list_move_tail(<e->write_streams_list,
1262 num_bytes_to_compress += lte->size;
1266 return num_bytes_to_compress;
1269 /* Copy a raw compressed resource located in another WIM file to the WIM file
1272 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1273 struct filedes *out_fd)
1275 u64 cur_read_offset;
1276 u64 end_read_offset;
1277 u8 buf[BUFFER_SIZE];
1278 size_t bytes_to_read;
1280 struct filedes *in_fd;
1281 struct wim_lookup_table_entry *lte;
1282 u64 out_offset_in_wim;
1284 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1285 "uncompressed_size=%"PRIu64")",
1286 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1288 /* Copy the raw data. */
1289 cur_read_offset = in_rspec->offset_in_wim;
1290 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1292 out_offset_in_wim = out_fd->offset;
1294 if (in_rspec->is_pipable) {
1295 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1296 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1297 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1298 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1300 in_fd = &in_rspec->wim->in_fd;
1301 wimlib_assert(cur_read_offset != end_read_offset);
1304 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1306 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1310 ret = full_write(out_fd, buf, bytes_to_read);
1314 cur_read_offset += bytes_to_read;
1316 } while (cur_read_offset != end_read_offset);
1318 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1319 if (lte->will_be_in_output_wim) {
1320 stream_set_out_reshdr_for_reuse(lte);
1321 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1322 lte->out_res_offset_in_wim = out_offset_in_wim;
1324 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1331 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1332 * WIM file being written. */
1334 write_raw_copy_resources(struct list_head *raw_copy_streams,
1335 struct filedes *out_fd,
1336 struct write_streams_progress_data *progress_data)
1338 struct wim_lookup_table_entry *lte;
1341 list_for_each_entry(lte, raw_copy_streams, write_streams_list)
1342 lte->rspec->raw_copy_ok = 1;
1344 list_for_each_entry(lte, raw_copy_streams, write_streams_list) {
1345 if (lte->rspec->raw_copy_ok) {
1346 /* Write each packed resource only one time, no matter
1347 * how many streams reference it. */
1348 ret = write_raw_copy_resource(lte->rspec, out_fd);
1351 lte->rspec->raw_copy_ok = 0;
1353 ret = do_write_streams_progress(progress_data, lte->size,
1361 /* Wait for and write all chunks pending in the compressor. */
1363 finish_remaining_chunks(struct write_streams_ctx *ctx)
1370 if (ctx->compressor == NULL)
1373 if (ctx->chunk_buf_filled != 0) {
1374 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1375 ctx->chunk_buf_filled);
1380 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1381 ret = write_chunk(ctx, cdata, csize, usize);
1389 remove_zero_length_streams(struct list_head *stream_list)
1391 struct wim_lookup_table_entry *lte, *tmp;
1393 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1394 wimlib_assert(lte->will_be_in_output_wim);
1395 if (lte->size == 0) {
1396 list_del(<e->write_streams_list);
1397 lte->out_reshdr.offset_in_wim = 0;
1398 lte->out_reshdr.size_in_wim = 0;
1399 lte->out_reshdr.uncompressed_size = 0;
1400 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1406 init_done_with_file_info(struct list_head *stream_list)
1408 struct wim_lookup_table_entry *lte;
1410 list_for_each_entry(lte, stream_list, write_streams_list) {
1411 if (is_file_stream(lte)) {
1412 lte->file_inode->num_remaining_streams = 0;
1413 lte->may_send_done_with_file = 1;
1415 lte->may_send_done_with_file = 0;
1419 list_for_each_entry(lte, stream_list, write_streams_list)
1420 if (lte->may_send_done_with_file)
1421 lte->file_inode->num_remaining_streams++;
1425 * Write a list of streams to the output WIM file.
1428 * The list of streams to write, specified by a list of `struct
1429 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1432 * The file descriptor, opened for writing, to which to write the streams.
1434 * @write_resource_flags
1435 * Flags to modify how the streams are written:
1437 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1438 * Force compression of all resources, even if they could otherwise
1439 * be re-used by copying the raw data, due to being located in a WIM
1440 * file with compatible compression parameters.
1442 * WRITE_RESOURCE_FLAG_PIPABLE:
1443 * Write the resources in the wimlib-specific pipable format, and
1444 * furthermore do so in such a way that no seeking backwards in
1445 * @out_fd will be performed (so it may be a pipe).
1447 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1448 * Pack all the streams into a single resource rather than writing
1449 * them in separate resources. This flag is only valid if the WIM
1450 * version number has been, or will be, set to
1451 * WIM_VERSION_PACKED_STREAMS. This flag may not be combined with
1452 * WRITE_RESOURCE_FLAG_PIPABLE.
1455 * Compression format to use to write the output streams, specified as one
1456 * of the WIMLIB_COMPRESSION_TYPE_* constants.
1457 * WIMLIB_COMPRESSION_TYPE_NONE is allowed.
1460 * Chunk size to use to write the streams. It must be a valid chunk size
1461 * for the specified compression format @out_ctype, unless @out_ctype is
1462 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1465 * Number of threads to use to compress data. If 0, a default number of
1466 * threads will be chosen. The number of threads still may be decreased
1467 * from the specified value if insufficient memory is detected.
1470 * If on-the-fly deduplication of unhashed streams is desired, this
1471 * parameter must be pointer to the lookup table for the WIMStruct on whose
1472 * behalf the streams are being written. Otherwise, this parameter can be
1476 * If on-the-fly deduplication of unhashed streams is desired, this
1477 * parameter can be a pointer to a context for stream filtering used to
1478 * detect whether the duplicate stream has been hard-filtered or not. If
1479 * no streams are hard-filtered or no streams are unhashed, this parameter
1482 * This function will write the streams in @stream_list to resources in
1483 * consecutive positions in the output WIM file, or to a single packed resource
1484 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1485 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1486 * each stream written will be updated to specify its location, size, and flags
1487 * in the output WIM. In the packed resource case,
1488 * WIM_RESHDR_FLAG_PACKED_STREAMS will be set in the @flags field of each
1489 * @out_reshdr, and furthermore @out_res_offset_in_wim and @out_res_size_in_wim
1490 * of each @out_reshdr will be set to the offset and size, respectively, in the
1491 * output WIM of the packed resource containing the corresponding stream.
1493 * Each of the streams to write may be in any location supported by the
1494 * resource-handling code (specifically, read_stream_list()), such as the
1495 * contents of external file that has been logically added to the output WIM, or
1496 * a stream in another WIM file that has been imported, or even a stream in the
1497 * "same" WIM file of which a modified copy is being written. In the case that
1498 * a stream is already in a WIM file and uses compatible compression parameters,
1499 * by default this function will re-use the raw data instead of decompressing
1500 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1501 * specified in @write_resource_flags, this is not done.
1503 * As a further requirement, this function requires that the
1504 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1505 * well as any other streams not in @stream_list that will be in the output WIM
1506 * file, but set to 0 on any other streams in the output WIM's lookup table or
1507 * sharing a packed resource with a stream in @stream_list. Still furthermore,
1508 * if on-the-fly deduplication of streams is possible, then all streams in
1509 * @stream_list must also be linked by @lookup_table_list along with any other
1510 * streams that have @will_be_in_output_wim set.
1512 * This function handles on-the-fly deduplication of streams for which SHA1
1513 * message digests have not yet been calculated. Such streams may or may not
1514 * need to be written. If @lookup_table is non-NULL, then each stream in
1515 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1516 * immediately before it would otherwise be read for writing in order to
1517 * determine if it is identical to another stream already being written or one
1518 * that would be filtered out of the output WIM using stream_filtered() with the
1519 * context @filter_ctx. Each such duplicate stream will be removed from
1520 * @stream_list, its reference count transfered to the pre-existing duplicate
1521 * stream, its memory freed, and will not be written. Alternatively, if a
1522 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1523 * has not been marked for writing or would not be hard-filtered, it is freed
1524 * and the pre-existing duplicate is written instead, taking ownership of the
1525 * reference count and slot in the @lookup_table_list.
1527 * Returns 0 if every stream was either written successfully or did not need to
1528 * be written; otherwise returns a non-zero error code.
1531 write_stream_list(struct list_head *stream_list,
1532 struct filedes *out_fd,
1533 int write_resource_flags,
1536 unsigned num_threads,
1537 struct wim_lookup_table *lookup_table,
1538 struct filter_context *filter_ctx,
1539 wimlib_progress_func_t progfunc,
1543 struct write_streams_ctx ctx;
1544 struct list_head raw_copy_streams;
1546 wimlib_assert((write_resource_flags &
1547 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1548 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1549 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1550 WRITE_RESOURCE_FLAG_PIPABLE));
1552 remove_zero_length_streams(stream_list);
1554 if (list_empty(stream_list)) {
1555 DEBUG("No streams to write.");
1559 /* If needed, set auxiliary information so that we can detect when the
1560 * library has finished using each external file. */
1561 if (unlikely(write_resource_flags & WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
1562 init_done_with_file_info(stream_list);
1564 memset(&ctx, 0, sizeof(ctx));
1566 /* Pre-sorting the streams is required for compute_stream_list_stats().
1567 * Afterwards, read_stream_list() need not sort them again. */
1568 ret = sort_stream_list_by_sequential_order(stream_list,
1569 offsetof(struct wim_lookup_table_entry,
1570 write_streams_list));
1574 ctx.out_fd = out_fd;
1575 ctx.lookup_table = lookup_table;
1576 ctx.out_ctype = out_ctype;
1577 ctx.out_chunk_size = out_chunk_size;
1578 ctx.write_resource_flags = write_resource_flags;
1579 ctx.filter_ctx = filter_ctx;
1581 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1582 wimlib_assert(out_chunk_size != 0);
1583 if (out_chunk_size <= STACK_MAX) {
1584 ctx.chunk_buf = alloca(out_chunk_size);
1586 ctx.chunk_buf = MALLOC(out_chunk_size);
1587 if (ctx.chunk_buf == NULL) {
1588 ret = WIMLIB_ERR_NOMEM;
1589 goto out_destroy_context;
1593 ctx.chunk_buf_filled = 0;
1595 compute_stream_list_stats(stream_list, &ctx);
1597 ctx.progress_data.progfunc = progfunc;
1598 ctx.progress_data.progctx = progctx;
1600 ctx.num_bytes_to_compress = find_raw_copy_streams(stream_list,
1601 write_resource_flags,
1606 DEBUG("Writing stream list "
1607 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1608 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1609 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1610 out_fd->offset, write_resource_flags,
1611 out_ctype, out_chunk_size, num_threads,
1612 ctx.progress_data.progress.write_streams.total_bytes,
1613 ctx.num_bytes_to_compress);
1615 if (ctx.num_bytes_to_compress == 0) {
1616 DEBUG("No compression needed; skipping to raw copy!");
1617 goto out_write_raw_copy_resources;
1620 /* Unless uncompressed output was required, allocate a chunk_compressor
1621 * to do compression. There are serial and parallel implementations of
1622 * the chunk_compressor interface. We default to parallel using the
1623 * specified number of threads, unless the upper bound on the number
1624 * bytes needing to be compressed is less than a heuristic value. */
1625 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1627 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1628 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1629 ret = new_parallel_chunk_compressor(out_ctype,
1634 WARNING("Couldn't create parallel chunk compressor: %"TS".\n"
1635 " Falling back to single-threaded compression.",
1636 wimlib_get_error_string(ret));
1641 if (ctx.compressor == NULL) {
1642 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1645 goto out_destroy_context;
1650 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1652 ctx.progress_data.progress.write_streams.num_threads = 1;
1654 DEBUG("Actually using %u threads",
1655 ctx.progress_data.progress.write_streams.num_threads);
1657 INIT_LIST_HEAD(&ctx.pending_streams);
1658 INIT_LIST_HEAD(&ctx.pack_streams);
1660 ret = call_progress(ctx.progress_data.progfunc,
1661 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1662 &ctx.progress_data.progress,
1663 ctx.progress_data.progctx);
1665 goto out_destroy_context;
1667 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1668 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1670 goto out_destroy_context;
1673 /* Read the list of streams needing to be compressed, using the
1674 * specified callbacks to execute processing of the data. */
1676 struct read_stream_list_callbacks cbs = {
1677 .begin_stream = write_stream_begin_read,
1678 .begin_stream_ctx = &ctx,
1679 .consume_chunk = write_stream_process_chunk,
1680 .consume_chunk_ctx = &ctx,
1681 .end_stream = write_stream_end_read,
1682 .end_stream_ctx = &ctx,
1685 ret = read_stream_list(stream_list,
1686 offsetof(struct wim_lookup_table_entry, write_streams_list),
1688 STREAM_LIST_ALREADY_SORTED |
1689 VERIFY_STREAM_HASHES |
1690 COMPUTE_MISSING_STREAM_HASHES);
1693 goto out_destroy_context;
1695 ret = finish_remaining_chunks(&ctx);
1697 goto out_destroy_context;
1699 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1700 struct wim_reshdr reshdr;
1701 struct wim_lookup_table_entry *lte;
1704 ret = end_write_resource(&ctx, &reshdr);
1706 goto out_destroy_context;
1708 DEBUG("Ending packed resource: %lu %lu %lu.",
1709 reshdr.offset_in_wim,
1711 reshdr.uncompressed_size);
1714 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1715 lte->out_reshdr.size_in_wim = lte->size;
1716 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1717 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1718 lte->out_reshdr.uncompressed_size = 0;
1719 lte->out_reshdr.offset_in_wim = offset_in_res;
1720 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1721 lte->out_res_size_in_wim = reshdr.size_in_wim;
1722 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1723 offset_in_res += lte->size;
1725 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1728 out_write_raw_copy_resources:
1729 /* Copy any compressed resources for which the raw data can be reused
1730 * without decompression. */
1731 ret = write_raw_copy_resources(&raw_copy_streams, ctx.out_fd,
1732 &ctx.progress_data);
1734 out_destroy_context:
1735 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1736 FREE(ctx.chunk_buf);
1737 FREE(ctx.chunk_csizes);
1739 ctx.compressor->destroy(ctx.compressor);
1740 DEBUG("Done (ret=%d)", ret);
1745 is_stream_packed(struct wim_lookup_table_entry *lte, void *_ignore)
1747 return lte_is_partial(lte);
1751 wim_has_packed_streams(WIMStruct *wim)
1753 return for_lookup_table_entry(wim->lookup_table, is_stream_packed, NULL);
1757 wim_write_stream_list(WIMStruct *wim,
1758 struct list_head *stream_list,
1760 unsigned num_threads,
1761 struct filter_context *filter_ctx)
1765 int write_resource_flags;
1767 write_resource_flags = write_flags_to_resource_flags(write_flags);
1769 /* wimlib v1.7.0: pack streams by default if the WIM version has been
1770 * set to WIM_VERSION_PACKED_STREAMS and at least one stream in the
1771 * WIM's lookup table is located in a packed resource (may be the same
1772 * WIM, or a different one in the case of export). */
1773 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS &&
1774 wim_has_packed_streams(wim))
1776 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
1779 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1780 out_chunk_size = wim->out_pack_chunk_size;
1781 out_ctype = wim->out_pack_compression_type;
1783 out_chunk_size = wim->out_chunk_size;
1784 out_ctype = wim->out_compression_type;
1787 return write_stream_list(stream_list,
1789 write_resource_flags,
1800 write_wim_resource(struct wim_lookup_table_entry *lte,
1801 struct filedes *out_fd,
1804 int write_resource_flags)
1806 LIST_HEAD(stream_list);
1807 list_add(<e->write_streams_list, &stream_list);
1808 lte->will_be_in_output_wim = 1;
1809 return write_stream_list(&stream_list,
1811 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1822 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1823 int reshdr_flags, struct filedes *out_fd,
1826 struct wim_reshdr *out_reshdr,
1828 int write_resource_flags)
1831 struct wim_lookup_table_entry *lte;
1833 /* Set up a temporary lookup table entry to provide to
1834 * write_wim_resource(). */
1836 lte = new_lookup_table_entry();
1838 return WIMLIB_ERR_NOMEM;
1840 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1841 lte->attached_buffer = (void*)buf;
1842 lte->size = buf_size;
1843 lte->flags = reshdr_flags;
1845 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1846 sha1_buffer(buf, buf_size, lte->hash);
1852 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1853 write_resource_flags);
1857 copy_reshdr(out_reshdr, <e->out_reshdr);
1860 copy_hash(hash, lte->hash);
1863 lte->resource_location = RESOURCE_NONEXISTENT;
1864 free_lookup_table_entry(lte);
1868 struct stream_size_table {
1869 struct hlist_head *array;
1875 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1877 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1878 if (tab->array == NULL)
1879 return WIMLIB_ERR_NOMEM;
1880 tab->num_entries = 0;
1881 tab->capacity = capacity;
1886 destroy_stream_size_table(struct stream_size_table *tab)
1892 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1894 struct stream_size_table *tab = _tab;
1896 struct wim_lookup_table_entry *same_size_lte;
1897 struct hlist_node *tmp;
1899 pos = hash_u64(lte->size) % tab->capacity;
1900 lte->unique_size = 1;
1901 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1902 if (same_size_lte->size == lte->size) {
1903 lte->unique_size = 0;
1904 same_size_lte->unique_size = 0;
1909 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1914 struct find_streams_ctx {
1917 struct list_head stream_list;
1918 struct stream_size_table stream_size_tab;
1922 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1923 struct list_head *stream_list, u32 nref)
1925 if (!lte->will_be_in_output_wim) {
1926 lte->out_refcnt = 0;
1927 list_add_tail(<e->write_streams_list, stream_list);
1928 lte->will_be_in_output_wim = 1;
1930 lte->out_refcnt += nref;
1934 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1937 struct list_head *stream_list = _stream_list;
1938 lte->will_be_in_output_wim = 0;
1939 reference_stream_for_write(lte, stream_list, lte->refcnt);
1944 inode_find_streams_to_reference(const struct wim_inode *inode,
1945 const struct wim_lookup_table *table,
1946 struct list_head *stream_list)
1948 struct wim_lookup_table_entry *lte;
1951 wimlib_assert(inode->i_nlink > 0);
1953 for (i = 0; i <= inode->i_num_ads; i++) {
1954 lte = inode_stream_lte(inode, i, table);
1956 reference_stream_for_write(lte, stream_list,
1958 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1959 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1965 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1967 lte->will_be_in_output_wim = 0;
1972 image_find_streams_to_reference(WIMStruct *wim)
1974 struct wim_image_metadata *imd;
1975 struct wim_inode *inode;
1976 struct wim_lookup_table_entry *lte;
1977 struct list_head *stream_list;
1980 imd = wim_get_current_image_metadata(wim);
1982 image_for_each_unhashed_stream(lte, imd)
1983 lte->will_be_in_output_wim = 0;
1985 stream_list = wim->private;
1986 image_for_each_inode(inode, imd) {
1987 ret = inode_find_streams_to_reference(inode,
1997 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
2000 struct list_head *stream_list_ret)
2004 INIT_LIST_HEAD(stream_list_ret);
2006 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
2007 (image == 1 && wim->hdr.image_count == 1)))
2009 /* Fast case: Assume that all streams are being written and
2010 * that the reference counts are correct. */
2011 struct wim_lookup_table_entry *lte;
2012 struct wim_image_metadata *imd;
2015 for_lookup_table_entry(wim->lookup_table,
2016 fully_reference_stream_for_write,
2019 for (i = 0; i < wim->hdr.image_count; i++) {
2020 imd = wim->image_metadata[i];
2021 image_for_each_unhashed_stream(lte, imd)
2022 fully_reference_stream_for_write(lte, stream_list_ret);
2025 /* Slow case: Walk through the images being written and
2026 * determine the streams referenced. */
2027 for_lookup_table_entry(wim->lookup_table,
2028 do_stream_set_not_in_output_wim, NULL);
2029 wim->private = stream_list_ret;
2030 ret = for_image(wim, image, image_find_streams_to_reference);
2038 struct insert_other_if_hard_filtered_ctx {
2039 struct stream_size_table *tab;
2040 struct filter_context *filter_ctx;
2044 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
2046 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
2048 if (!lte->will_be_in_output_wim &&
2049 stream_hard_filtered(lte, ctx->filter_ctx))
2050 stream_size_table_insert(lte, ctx->tab);
2055 determine_stream_size_uniquity(struct list_head *stream_list,
2056 struct wim_lookup_table *lt,
2057 struct filter_context *filter_ctx)
2060 struct stream_size_table tab;
2061 struct wim_lookup_table_entry *lte;
2063 ret = init_stream_size_table(&tab, 9001);
2067 if (may_hard_filter_streams(filter_ctx)) {
2068 struct insert_other_if_hard_filtered_ctx ctx = {
2070 .filter_ctx = filter_ctx,
2072 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
2075 list_for_each_entry(lte, stream_list, write_streams_list)
2076 stream_size_table_insert(lte, &tab);
2078 destroy_stream_size_table(&tab);
2083 filter_stream_list_for_write(struct list_head *stream_list,
2084 struct filter_context *filter_ctx)
2086 struct wim_lookup_table_entry *lte, *tmp;
2088 list_for_each_entry_safe(lte, tmp,
2089 stream_list, write_streams_list)
2091 int status = stream_filtered(lte, filter_ctx);
2098 /* Soft filtered. */
2100 /* Hard filtered. */
2101 lte->will_be_in_output_wim = 0;
2102 list_del(<e->lookup_table_list);
2104 list_del(<e->write_streams_list);
2110 * prepare_stream_list_for_write() -
2112 * Prepare the list of streams to write for writing a WIM containing the
2113 * specified image(s) with the specified write flags.
2116 * The WIMStruct on whose behalf the write is occurring.
2119 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2122 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2124 * STREAMS_OK: For writes of all images, assume that all streams in the
2125 * lookup table of @wim and the per-image lists of unhashed streams should
2126 * be taken as-is, and image metadata should not be searched for
2127 * references. This does not exclude filtering with OVERWRITE and
2128 * SKIP_EXTERNAL_WIMS, below.
2130 * OVERWRITE: Streams already present in @wim shall not be returned in
2133 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
2134 * @wim, shall be returned in neither @stream_list_ret nor
2135 * @lookup_table_list_ret.
2138 * List of streams, linked by write_streams_list, that need to be written
2139 * will be returned here.
2141 * Note that this function assumes that unhashed streams will be written;
2142 * it does not take into account that they may become duplicates when
2145 * @lookup_table_list_ret
2146 * List of streams, linked by lookup_table_list, that need to be included
2147 * in the WIM's lookup table will be returned here. This will be a
2148 * superset of the streams in @stream_list_ret.
2150 * This list will be a proper superset of @stream_list_ret if and only if
2151 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2152 * the streams that would otherwise need to be written were already located
2155 * All streams in this list will have @out_refcnt set to the number of
2156 * references to the stream in the output WIM. If
2157 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2158 * may be as low as 0.
2161 * A context for queries of stream filter status with stream_filtered() is
2162 * returned in this location.
2164 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
2165 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
2166 * lookup table of @wim not inserted into @lookup_table_list_ret.
2168 * Still furthermore, @unique_size will be set to 1 on all stream entries in
2169 * @stream_list_ret that have unique size among all stream entries in
2170 * @stream_list_ret and among all stream entries in the lookup table of @wim
2171 * that are ineligible for being written due to filtering.
2173 * Returns 0 on success; nonzero on read error, memory allocation error, or
2177 prepare_stream_list_for_write(WIMStruct *wim, int image,
2179 struct list_head *stream_list_ret,
2180 struct list_head *lookup_table_list_ret,
2181 struct filter_context *filter_ctx_ret)
2184 struct wim_lookup_table_entry *lte;
2186 filter_ctx_ret->write_flags = write_flags;
2187 filter_ctx_ret->wim = wim;
2189 ret = prepare_unfiltered_list_of_streams_in_output_wim(
2192 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2197 INIT_LIST_HEAD(lookup_table_list_ret);
2198 list_for_each_entry(lte, stream_list_ret, write_streams_list)
2199 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2201 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
2206 if (may_filter_streams(filter_ctx_ret))
2207 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2213 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2214 unsigned num_threads,
2215 struct list_head *stream_list_override,
2216 struct list_head *lookup_table_list_ret)
2219 struct list_head _stream_list;
2220 struct list_head *stream_list;
2221 struct wim_lookup_table_entry *lte;
2222 struct filter_context _filter_ctx;
2223 struct filter_context *filter_ctx;
2225 if (stream_list_override == NULL) {
2226 /* Normal case: prepare stream list from image(s) being written.
2228 stream_list = &_stream_list;
2229 filter_ctx = &_filter_ctx;
2230 ret = prepare_stream_list_for_write(wim, image, write_flags,
2232 lookup_table_list_ret,
2237 /* Currently only as a result of wimlib_split() being called:
2238 * use stream list already explicitly provided. Use existing
2239 * reference counts. */
2240 stream_list = stream_list_override;
2242 INIT_LIST_HEAD(lookup_table_list_ret);
2243 list_for_each_entry(lte, stream_list, write_streams_list) {
2244 lte->out_refcnt = lte->refcnt;
2245 lte->will_be_in_output_wim = 1;
2246 lte->unique_size = 0;
2247 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2251 return wim_write_stream_list(wim,
2259 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags)
2264 int write_resource_flags;
2266 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2267 DEBUG("Not writing any metadata resources.");
2271 write_resource_flags = write_flags_to_resource_flags(write_flags);
2273 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2275 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2276 wim->out_fd.offset);
2278 ret = call_progress(wim->progfunc,
2279 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2280 NULL, wim->progctx);
2284 if (image == WIMLIB_ALL_IMAGES) {
2286 end_image = wim->hdr.image_count;
2288 start_image = image;
2292 for (int i = start_image; i <= end_image; i++) {
2293 struct wim_image_metadata *imd;
2295 imd = wim->image_metadata[i - 1];
2296 /* Build a new metadata resource only if image was modified from
2297 * the original (or was newly added). Otherwise just copy the
2299 if (imd->modified) {
2300 DEBUG("Image %u was modified; building and writing new "
2301 "metadata resource", i);
2302 ret = write_metadata_resource(wim, i,
2303 write_resource_flags);
2304 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2305 DEBUG("Image %u was not modified; re-using existing "
2306 "metadata resource.", i);
2307 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2310 DEBUG("Image %u was not modified; copying existing "
2311 "metadata resource.", i);
2312 ret = write_wim_resource(imd->metadata_lte,
2314 wim->out_compression_type,
2315 wim->out_chunk_size,
2316 write_resource_flags);
2322 return call_progress(wim->progfunc,
2323 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2324 NULL, wim->progctx);
2328 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2331 DEBUG("Opening \"%"TS"\" for writing.", path);
2333 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2335 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2336 return WIMLIB_ERR_OPEN;
2338 filedes_init(&wim->out_fd, raw_fd);
2343 close_wim_writable(WIMStruct *wim, int write_flags)
2347 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2348 DEBUG("Closing WIM file.");
2349 if (filedes_valid(&wim->out_fd))
2350 if (filedes_close(&wim->out_fd))
2351 ret = WIMLIB_ERR_WRITE;
2353 filedes_invalidate(&wim->out_fd);
2358 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2360 const struct wim_lookup_table_entry *lte1, *lte2;
2362 lte1 = *(const struct wim_lookup_table_entry**)p1;
2363 lte2 = *(const struct wim_lookup_table_entry**)p2;
2365 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2366 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2367 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2368 return cmp_u64(lte1->out_res_offset_in_wim,
2369 lte2->out_res_offset_in_wim);
2374 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2377 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2378 lte2->out_reshdr.offset_in_wim);
2382 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2383 struct wim_reshdr *out_reshdr,
2384 struct list_head *lookup_table_list)
2388 /* Set output resource metadata for streams already present in WIM. */
2389 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2390 struct wim_lookup_table_entry *lte;
2391 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2393 if (lte->resource_location == RESOURCE_IN_WIM &&
2394 lte->rspec->wim == wim)
2396 stream_set_out_reshdr_for_reuse(lte);
2401 ret = sort_stream_list(lookup_table_list,
2402 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2403 cmp_streams_by_out_rspec);
2407 /* Add entries for metadata resources. */
2408 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2412 if (image == WIMLIB_ALL_IMAGES) {
2414 end_image = wim->hdr.image_count;
2416 start_image = image;
2420 /* Push metadata resource lookup table entries onto the front of
2421 * the list in reverse order, so that they're written in order.
2423 for (int i = end_image; i >= start_image; i--) {
2424 struct wim_lookup_table_entry *metadata_lte;
2426 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2427 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2428 metadata_lte->out_refcnt = 1;
2429 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2433 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2435 wim->hdr.part_number,
2437 write_flags_to_resource_flags(write_flags));
2443 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2444 * table, then overwrite the WIM header. By default, closes the WIM file
2445 * descriptor (@wim->out_fd) if successful.
2447 * write_flags is a bitwise OR of the following:
2449 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2450 * Include an integrity table.
2452 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2453 * fsync() the output file before closing it.
2455 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2456 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2457 * stream headers before the lookup table and XML data, and also
2458 * write the WIM header at the end instead of seeking to the
2459 * beginning. Can't be combined with
2460 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2462 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2463 * Don't write the lookup table.
2465 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2466 * After writing the XML data but before writing the integrity
2467 * table, write a temporary WIM header and flush the stream so that
2468 * the WIM is less likely to become corrupted upon abrupt program
2470 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2471 * Instead of overwriting the WIM header at the beginning of the
2472 * file, simply append it to the end of the file. (Used when
2474 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2475 * Do not close the file descriptor @wim->out_fd on either success
2477 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2478 * Use the existing <TOTALBYTES> stored in the in-memory XML
2479 * information, rather than setting it to the offset of the XML
2480 * data being written.
2481 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2482 * The existing WIM file is being updated in-place. The entries
2483 * from its integrity table may be re-used.
2486 finish_write(WIMStruct *wim, int image, int write_flags,
2487 struct list_head *lookup_table_list)
2491 int write_resource_flags;
2492 off_t old_lookup_table_end = 0;
2493 off_t new_lookup_table_end;
2495 struct integrity_table *old_integrity_table = NULL;
2497 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2499 write_resource_flags = write_flags_to_resource_flags(write_flags);
2501 /* In the WIM header, there is room for the resource entry for a
2502 * metadata resource labeled as the "boot metadata". This entry should
2503 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2504 * it should be a copy of the resource entry for the image that is
2505 * marked as bootable. This is not well documented... */
2506 if (wim->hdr.boot_idx == 0) {
2507 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2509 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2510 &wim->image_metadata[
2511 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2514 /* If overwriting the WIM file containing an integrity table in-place,
2515 * we'd like to re-use the information in the old integrity table
2516 * instead of recalculating it. But we might overwrite the old
2517 * integrity table when we expand the XML data. Read it into memory
2519 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2520 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2521 (WIMLIB_WRITE_FLAG_OVERWRITE |
2522 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2523 && wim_has_integrity_table(wim))
2525 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2526 wim->hdr.lookup_table_reshdr.size_in_wim;
2527 (void)read_integrity_table(wim,
2528 old_lookup_table_end - WIM_HEADER_DISK_SIZE,
2529 &old_integrity_table);
2530 /* If we couldn't read the old integrity table, we can still
2531 * re-calculate the full integrity table ourselves. Hence the
2532 * ignoring of the return value. */
2535 /* Write lookup table. */
2536 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2537 ret = write_wim_lookup_table(wim, image, write_flags,
2538 &wim->hdr.lookup_table_reshdr,
2541 free_integrity_table(old_integrity_table);
2546 /* Write XML data. */
2547 xml_totalbytes = wim->out_fd.offset;
2548 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2549 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2550 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2551 &wim->hdr.xml_data_reshdr,
2552 write_resource_flags);
2554 free_integrity_table(old_integrity_table);
2558 /* Write integrity table (optional). */
2559 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2560 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2561 struct wim_header checkpoint_hdr;
2562 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2563 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2564 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2565 ret = write_wim_header_at_offset(&checkpoint_hdr,
2568 free_integrity_table(old_integrity_table);
2573 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2574 wim->hdr.lookup_table_reshdr.size_in_wim;
2576 ret = write_integrity_table(wim,
2577 new_lookup_table_end,
2578 old_lookup_table_end,
2579 old_integrity_table);
2580 free_integrity_table(old_integrity_table);
2584 /* No integrity table. */
2585 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2588 /* Now that all information in the WIM header has been determined, the
2589 * preliminary header written earlier can be overwritten, the header of
2590 * the existing WIM file can be overwritten, or the final header can be
2591 * written to the end of the pipable WIM. */
2592 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2594 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2595 hdr_offset = wim->out_fd.offset;
2596 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2597 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2601 /* Possibly sync file data to disk before closing. On POSIX systems, it
2602 * is necessary to do this before using rename() to overwrite an
2603 * existing file with a new file. Otherwise, data loss would occur if
2604 * the system is abruptly terminated when the metadata for the rename
2605 * operation has been written to disk, but the new file data has not.
2607 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2608 DEBUG("Syncing WIM file.");
2609 if (fsync(wim->out_fd.fd)) {
2610 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2611 return WIMLIB_ERR_WRITE;
2615 if (close_wim_writable(wim, write_flags)) {
2616 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2617 return WIMLIB_ERR_WRITE;
2623 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2625 /* Set advisory lock on WIM file (if not already done so) */
2627 lock_wim_for_append(WIMStruct *wim)
2629 if (wim->locked_for_append)
2631 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2632 wim->locked_for_append = 1;
2635 if (errno != EWOULDBLOCK)
2637 return WIMLIB_ERR_ALREADY_LOCKED;
2640 /* Remove advisory lock on WIM file (if present) */
2642 unlock_wim_for_append(WIMStruct *wim)
2644 if (wim->locked_for_append) {
2645 flock(wim->in_fd.fd, LOCK_UN);
2646 wim->locked_for_append = 0;
2652 * write_pipable_wim():
2654 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2655 * capable of being applied from a pipe).
2657 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2658 * images can be applied from them sequentially when the file data is sent over
2659 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2660 * The modifications made to the WIM format for pipable WIMs are:
2662 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2663 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2664 * stops other software from trying to read the file as a normal WIM.
2666 * - The header at the beginning of the file does not contain all the normal
2667 * information; in particular it will have all 0's for the lookup table and
2668 * XML data resource entries. This is because this information cannot be
2669 * determined until the lookup table and XML data have been written.
2670 * Consequently, wimlib will write the full header at the very end of the
2671 * file. The header at the end, however, is only used when reading the WIM
2672 * from a seekable file (not a pipe).
2674 * - An extra copy of the XML data is placed directly after the header. This
2675 * allows image names and sizes to be determined at an appropriate time when
2676 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2677 * WIM is read from a seekable file (not a pipe).
2679 * - The format of resources, or streams, has been modified to allow them to be
2680 * used before the "lookup table" has been read. Each stream is prefixed with
2681 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2682 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2683 * uncompressed stream size, and flags that indicate whether the stream is
2684 * compressed. The data of uncompressed streams then follows literally, while
2685 * the data of compressed streams follows in a modified format. Compressed
2686 * streams do not begin with a chunk table, since the chunk table cannot be
2687 * written until all chunks have been compressed. Instead, each compressed
2688 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2689 * Furthermore, the chunk table is written at the end of the resource instead
2690 * of the start. Note: chunk offsets are given in the chunk table as if the
2691 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2692 * used if the WIM is being read from a seekable file (not a pipe).
2694 * - Metadata resources always come before other file resources (streams).
2695 * (This does not by itself constitute an incompatibility with normal WIMs,
2696 * since this is valid in normal WIMs.)
2698 * - At least up to the end of the file resources, all components must be packed
2699 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2700 * not by itself consititute an incompatibility with normal WIMs, since this
2701 * is valid in normal WIMs.)
2703 * Note: the lookup table, XML data, and header at the end are not used when
2704 * applying from a pipe. They exist to support functionality such as image
2705 * application and export when the WIM is *not* read from a pipe.
2707 * Layout of pipable WIM:
2709 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2710 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2711 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2713 * Layout of normal WIM:
2715 * +--------+-----------------------------+-------------------------+
2716 * | Header | File and metadata resources | Lookup table | XML data |
2717 * +--------+-----------------------------+-------------------------+
2719 * An optional integrity table can follow the final XML data in both normal and
2720 * pipable WIMs. However, due to implementation details, wimlib currently can
2721 * only include an integrity table in a pipable WIM when writing it to a
2722 * seekable file (not a pipe).
2724 * Do note that since pipable WIMs are not supported by Microsoft's software,
2725 * wimlib does not create them unless explicitly requested (with
2726 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2727 * characters to identify the file.
2730 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2731 unsigned num_threads,
2732 struct list_head *stream_list_override,
2733 struct list_head *lookup_table_list_ret)
2736 struct wim_reshdr xml_reshdr;
2738 WARNING("Creating a pipable WIM, which will "
2740 " with Microsoft's software (wimgapi/imagex/Dism).");
2742 /* At this point, the header at the beginning of the file has already
2745 /* For efficiency, when wimlib adds an image to the WIM with
2746 * wimlib_add_image(), the SHA1 message digests of files is not
2747 * calculated; instead, they are calculated while the files are being
2748 * written. However, this does not work when writing a pipable WIM,
2749 * since when writing a stream to a pipable WIM, its SHA1 message digest
2750 * needs to be known before the stream data is written. Therefore,
2751 * before getting much farther, we need to pre-calculate the SHA1
2752 * message digests of all streams that will be written. */
2753 ret = wim_checksum_unhashed_streams(wim);
2757 /* Write extra copy of the XML data. */
2758 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2760 WRITE_RESOURCE_FLAG_PIPABLE);
2764 /* Write metadata resources for the image(s) being included in the
2766 ret = write_wim_metadata_resources(wim, image, write_flags);
2770 /* Write streams needed for the image(s) being included in the output
2771 * WIM, or streams needed for the split WIM part. */
2772 return write_wim_streams(wim, image, write_flags, num_threads,
2773 stream_list_override, lookup_table_list_ret);
2775 /* The lookup table, XML data, and header at end are handled by
2776 * finish_write(). */
2779 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2782 write_wim_part(WIMStruct *wim,
2783 const void *path_or_fd,
2786 unsigned num_threads,
2787 unsigned part_number,
2788 unsigned total_parts,
2789 struct list_head *stream_list_override,
2793 struct wim_header hdr_save;
2794 struct list_head lookup_table_list;
2796 if (total_parts == 1)
2797 DEBUG("Writing standalone WIM.");
2799 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2800 if (image == WIMLIB_ALL_IMAGES)
2801 DEBUG("Including all images.");
2803 DEBUG("Including image %d only.", image);
2804 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2805 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2807 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2808 DEBUG("Write flags: 0x%08x", write_flags);
2810 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2811 DEBUG("\tCHECK_INTEGRITY");
2813 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2814 DEBUG("\tNO_CHECK_INTEGRITY");
2816 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2819 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2820 DEBUG("\tNOT_PIPABLE");
2822 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2823 DEBUG("\tRECOMPRESS");
2825 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2828 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2831 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2832 DEBUG("\tSOFT_DELETE");
2834 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2835 DEBUG("\tIGNORE_READONLY_FLAG");
2837 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2838 DEBUG("\tSKIP_EXTERNAL_WIMS");
2840 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2841 DEBUG("\tSTREAMS_OK");
2843 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2844 DEBUG("\tRETAIN_GUID");
2846 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2847 DEBUG("\tPACK_STREAMS");
2849 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2850 DEBUG("\tFILE_DESCRIPTOR");
2852 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2853 DEBUG("\tNO_METADATA");
2855 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2856 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2858 if (num_threads == 0)
2859 DEBUG("Number of threads: autodetect");
2861 DEBUG("Number of threads: %u", num_threads);
2862 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2863 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2864 DEBUG("GUID: %s", (write_flags &
2865 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2866 : guid ? "explicit" : "generate new");
2868 /* Internally, this is always called with a valid part number and total
2870 wimlib_assert(total_parts >= 1);
2871 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2873 /* A valid image (or all images) must be specified. */
2874 if (image != WIMLIB_ALL_IMAGES &&
2875 (image < 1 || image > wim->hdr.image_count))
2876 return WIMLIB_ERR_INVALID_IMAGE;
2878 /* If we need to write metadata resources, make sure the ::WIMStruct has
2879 * the needed information attached (e.g. is not a resource-only WIM,
2880 * such as a non-first part of a split WIM). */
2881 if (!wim_has_metadata(wim) &&
2882 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2883 return WIMLIB_ERR_METADATA_NOT_FOUND;
2885 /* Check for contradictory flags. */
2886 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2887 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2888 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2889 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2890 return WIMLIB_ERR_INVALID_PARAM;
2892 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2893 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2894 == (WIMLIB_WRITE_FLAG_PIPABLE |
2895 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2896 return WIMLIB_ERR_INVALID_PARAM;
2898 /* Save previous header, then start initializing the new one. */
2899 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2901 /* Set default integrity, pipable, and packed stream flags. */
2902 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2903 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2904 if (wim_is_pipable(wim)) {
2905 DEBUG("WIM is pipable; default to PIPABLE.");
2906 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2909 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2910 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2911 if (wim_has_integrity_table(wim)) {
2912 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2913 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2916 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2917 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2918 == (WIMLIB_WRITE_FLAG_PIPABLE |
2919 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2921 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2922 return WIMLIB_ERR_INVALID_PARAM;
2925 /* Set appropriate magic number. */
2926 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2927 wim->hdr.magic = PWM_MAGIC;
2929 wim->hdr.magic = WIM_MAGIC;
2931 /* Set appropriate version number. */
2932 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2933 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2934 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2936 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2938 /* Clear header flags that will be set automatically. */
2939 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2940 WIM_HDR_FLAG_RESOURCE_ONLY |
2941 WIM_HDR_FLAG_SPANNED |
2942 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2944 /* Set SPANNED header flag if writing part of a split WIM. */
2945 if (total_parts != 1)
2946 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2948 /* Set part number and total parts of split WIM. This will be 1 and 1
2949 * if the WIM is standalone. */
2950 wim->hdr.part_number = part_number;
2951 wim->hdr.total_parts = total_parts;
2953 /* Set compression type if different. */
2954 if (wim->compression_type != wim->out_compression_type) {
2955 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2956 wimlib_assert(ret == 0);
2959 /* Set chunk size if different. */
2960 wim->hdr.chunk_size = wim->out_chunk_size;
2963 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2965 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2967 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2970 /* Clear references to resources that have not been written yet. */
2971 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2972 zero_reshdr(&wim->hdr.xml_data_reshdr);
2973 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2974 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2976 /* Set image count and boot index correctly for single image writes. */
2977 if (image != WIMLIB_ALL_IMAGES) {
2978 wim->hdr.image_count = 1;
2979 if (wim->hdr.boot_idx == image)
2980 wim->hdr.boot_idx = 1;
2982 wim->hdr.boot_idx = 0;
2985 /* Split WIMs can't be bootable. */
2986 if (total_parts != 1)
2987 wim->hdr.boot_idx = 0;
2989 /* Initialize output file descriptor. */
2990 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2991 /* File descriptor was explicitly provided. Return error if
2992 * file descriptor is not seekable, unless writing a pipable WIM
2994 wim->out_fd.fd = *(const int*)path_or_fd;
2995 wim->out_fd.offset = 0;
2996 if (!filedes_is_seekable(&wim->out_fd)) {
2997 ret = WIMLIB_ERR_INVALID_PARAM;
2998 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2999 goto out_restore_hdr;
3000 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
3001 ERROR("Can't include integrity check when "
3002 "writing pipable WIM to pipe!");
3003 goto out_restore_hdr;
3008 /* Filename of WIM to write was provided; open file descriptor
3010 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
3011 O_TRUNC | O_CREAT | O_RDWR);
3013 goto out_restore_hdr;
3016 /* Write initial header. This is merely a "dummy" header since it
3017 * doesn't have all the information yet, so it will be overwritten later
3018 * (unless writing a pipable WIM). */
3019 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3020 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3021 ret = write_wim_header(&wim->hdr, &wim->out_fd);
3022 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3024 goto out_restore_hdr;
3026 /* Write metadata resources and streams. */
3027 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
3028 /* Default case: create a normal (non-pipable) WIM. */
3029 ret = write_wim_streams(wim, image, write_flags, num_threads,
3030 stream_list_override,
3031 &lookup_table_list);
3033 goto out_restore_hdr;
3035 ret = write_wim_metadata_resources(wim, image, write_flags);
3037 goto out_restore_hdr;
3039 /* Non-default case: create pipable WIM. */
3040 ret = write_pipable_wim(wim, image, write_flags, num_threads,
3041 stream_list_override,
3042 &lookup_table_list);
3044 goto out_restore_hdr;
3045 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
3049 /* Write lookup table, XML data, and (optional) integrity table. */
3050 ret = finish_write(wim, image, write_flags, &lookup_table_list);
3052 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3053 (void)close_wim_writable(wim, write_flags);
3054 DEBUG("ret=%d", ret);
3058 /* Write a standalone WIM to a file or file descriptor. */
3060 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
3061 int image, int write_flags, unsigned num_threads)
3063 return write_wim_part(wim, path_or_fd, image, write_flags,
3064 num_threads, 1, 1, NULL, NULL);
3067 /* API function documented in wimlib.h */
3069 wimlib_write(WIMStruct *wim, const tchar *path,
3070 int image, int write_flags, unsigned num_threads)
3072 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3073 return WIMLIB_ERR_INVALID_PARAM;
3075 if (path == NULL || path[0] == T('\0'))
3076 return WIMLIB_ERR_INVALID_PARAM;
3078 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3081 /* API function documented in wimlib.h */
3083 wimlib_write_to_fd(WIMStruct *wim, int fd,
3084 int image, int write_flags, unsigned num_threads)
3086 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3087 return WIMLIB_ERR_INVALID_PARAM;
3090 return WIMLIB_ERR_INVALID_PARAM;
3092 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3094 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3098 any_images_modified(WIMStruct *wim)
3100 for (int i = 0; i < wim->hdr.image_count; i++)
3101 if (wim->image_metadata[i]->modified)
3107 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
3109 const WIMStruct *wim = _wim;
3110 off_t end_offset = *(const off_t*)wim->private;
3112 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
3113 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
3114 return WIMLIB_ERR_RESOURCE_ORDER;
3118 /* Make sure no file or metadata resources are located after the XML data (or
3119 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3120 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3122 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3127 wim->private = &end_offset;
3128 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
3132 for (i = 0; i < wim->hdr.image_count; i++) {
3133 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
3141 * Overwrite a WIM, possibly appending streams to it.
3143 * A WIM looks like (or is supposed to look like) the following:
3145 * Header (212 bytes)
3146 * Streams and metadata resources (variable size)
3147 * Lookup table (variable size)
3148 * XML data (variable size)
3149 * Integrity table (optional) (variable size)
3151 * If we are not adding any streams or metadata resources, the lookup table is
3152 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3153 * header. This operation is potentially unsafe if the program is abruptly
3154 * terminated while the XML data or integrity table are being overwritten, but
3155 * before the new header has been written. To partially alleviate this problem,
3156 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3157 * finish_write() to cause a temporary WIM header to be written after the XML
3158 * data has been written. This may prevent the WIM from becoming corrupted if
3159 * the program is terminated while the integrity table is being calculated (but
3160 * no guarantees, due to write re-ordering...).
3162 * If we are adding new streams or images (metadata resources), the lookup table
3163 * needs to be changed, and those streams need to be written. In this case, we
3164 * try to perform a safe update of the WIM file by writing the streams *after*
3165 * the end of the previous WIM, then writing the new lookup table, XML data, and
3166 * (optionally) integrity table following the new streams. This will produce a
3167 * layout like the following:
3169 * Header (212 bytes)
3170 * (OLD) Streams and metadata resources (variable size)
3171 * (OLD) Lookup table (variable size)
3172 * (OLD) XML data (variable size)
3173 * (OLD) Integrity table (optional) (variable size)
3174 * (NEW) Streams and metadata resources (variable size)
3175 * (NEW) Lookup table (variable size)
3176 * (NEW) XML data (variable size)
3177 * (NEW) Integrity table (optional) (variable size)
3179 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3180 * the header is overwritten to point to the new lookup table, XML data, and
3181 * integrity table, to produce the following layout:
3183 * Header (212 bytes)
3184 * Streams and metadata resources (variable size)
3185 * Nothing (variable size)
3186 * More Streams and metadata resources (variable size)
3187 * Lookup table (variable size)
3188 * XML data (variable size)
3189 * Integrity table (optional) (variable size)
3191 * This method allows an image to be appended to a large WIM very quickly, and
3192 * is crash-safe except in the case of write re-ordering, but the
3193 * disadvantage is that a small hole is left in the WIM where the old lookup
3194 * table, xml data, and integrity table were. (These usually only take up a
3195 * small amount of space compared to the streams, however.)
3198 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3202 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
3203 struct wim_header hdr_save;
3204 struct list_head stream_list;
3205 struct list_head lookup_table_list;
3206 struct filter_context filter_ctx;
3208 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3210 /* Save original header so it can be restored in case of error */
3211 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3213 /* Set default integrity flag. */
3214 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3215 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3216 if (wim_has_integrity_table(wim))
3217 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3219 /* Set WIM version if adding packed streams. */
3220 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
3221 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
3223 /* Set additional flags for overwrite. */
3224 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3225 WIMLIB_WRITE_FLAG_STREAMS_OK;
3227 /* Make sure that the integrity table (if present) is after the XML
3228 * data, and that there are no stream resources, metadata resources, or
3229 * lookup tables after the XML data. Otherwise, these data would be
3231 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3232 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3233 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
3234 wim->hdr.lookup_table_reshdr.size_in_wim;
3235 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3236 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3237 WARNING("Didn't expect the integrity table to be before the XML data");
3238 ret = WIMLIB_ERR_RESOURCE_ORDER;
3239 goto out_restore_memory_hdr;
3242 if (old_lookup_table_end > old_xml_begin) {
3243 WARNING("Didn't expect the lookup table to be after the XML data");
3244 ret = WIMLIB_ERR_RESOURCE_ORDER;
3245 goto out_restore_memory_hdr;
3248 /* Set @old_wim_end, which indicates the point beyond which we don't
3249 * allow any file and metadata resources to appear without returning
3250 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3251 * overwrite these resources). */
3252 if (!wim->image_deletion_occurred && !any_images_modified(wim)) {
3253 /* If no images have been modified and no images have been
3254 * deleted, a new lookup table does not need to be written. We
3255 * shall write the new XML data and optional integrity table
3256 * immediately after the lookup table. Note that this may
3257 * overwrite an existing integrity table. */
3258 DEBUG("Skipping writing lookup table "
3259 "(no images modified or deleted)");
3260 old_wim_end = old_lookup_table_end;
3261 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3262 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3263 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3264 /* Old WIM has an integrity table; begin writing new streams
3266 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3267 wim->hdr.integrity_table_reshdr.size_in_wim;
3269 /* No existing integrity table; begin writing new streams after
3270 * the old XML data. */
3271 old_wim_end = old_xml_end;
3274 ret = check_resource_offsets(wim, old_wim_end);
3276 goto out_restore_memory_hdr;
3278 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3279 &stream_list, &lookup_table_list,
3282 goto out_restore_memory_hdr;
3284 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3286 goto out_restore_memory_hdr;
3288 ret = lock_wim_for_append(wim);
3292 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3293 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3294 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3296 ERROR_WITH_ERRNO("Error updating WIM header flags");
3297 goto out_unlock_wim;
3300 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3301 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3302 ret = WIMLIB_ERR_WRITE;
3303 goto out_restore_physical_hdr;
3306 ret = wim_write_stream_list(wim,
3314 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3318 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3319 &lookup_table_list);
3323 unlock_wim_for_append(wim);
3327 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3328 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3329 wim->filename, old_wim_end);
3330 /* Return value of ftruncate() is ignored because this is
3331 * already an error path. */
3332 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3334 out_restore_physical_hdr:
3335 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3337 unlock_wim_for_append(wim);
3339 (void)close_wim_writable(wim, write_flags);
3340 out_restore_memory_hdr:
3341 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3346 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3348 size_t wim_name_len;
3351 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3353 /* Write the WIM to a temporary file in the same directory as the
3355 wim_name_len = tstrlen(wim->filename);
3356 tchar tmpfile[wim_name_len + 10];
3357 tmemcpy(tmpfile, wim->filename, wim_name_len);
3358 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3359 tmpfile[wim_name_len + 9] = T('\0');
3361 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3363 WIMLIB_WRITE_FLAG_FSYNC |
3364 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3371 if (filedes_valid(&wim->in_fd)) {
3372 filedes_close(&wim->in_fd);
3373 filedes_invalidate(&wim->in_fd);
3376 /* Rename the new WIM file to the original WIM file. Note: on Windows
3377 * this actually calls win32_rename_replacement(), not _wrename(), so
3378 * that removing the existing destination file can be handled. */
3379 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3380 ret = trename(tmpfile, wim->filename);
3382 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3383 tmpfile, wim->filename);
3390 return WIMLIB_ERR_RENAME;
3393 union wimlib_progress_info progress;
3394 progress.rename.from = tmpfile;
3395 progress.rename.to = wim->filename;
3396 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3397 &progress, wim->progctx);
3400 /* Determine if the specified WIM file may be updated by appending in-place
3401 * rather than writing and replacing it with an entirely new file. */
3403 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3405 /* REBUILD flag forces full rebuild. */
3406 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3409 /* Image deletions cause full rebuild by default. */
3410 if (wim->image_deletion_occurred &&
3411 !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3414 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3415 * turned into a pipable WIM in-place. */
3416 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3419 /* The default compression type and compression chunk size selected for
3420 * the output WIM must be the same as those currently used for the WIM.
3422 if (wim->compression_type != wim->out_compression_type)
3424 if (wim->chunk_size != wim->out_chunk_size)
3430 /* API function documented in wimlib.h */
3432 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3437 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3438 return WIMLIB_ERR_INVALID_PARAM;
3441 return WIMLIB_ERR_NO_FILENAME;
3443 orig_hdr_flags = wim->hdr.flags;
3444 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3445 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3446 ret = can_modify_wim(wim);
3447 wim->hdr.flags = orig_hdr_flags;
3451 if (can_overwrite_wim_inplace(wim, write_flags)) {
3452 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3453 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3455 WARNING("Falling back to re-building entire WIM");
3457 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);