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 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/chunk_compressor.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/inode.h"
43 #include "wimlib/integrity.h"
44 #include "wimlib/lookup_table.h"
45 #include "wimlib/metadata.h"
46 #include "wimlib/resource.h"
48 # include "wimlib/win32.h" /* win32_rename_replacement() */
50 #include "wimlib/write.h"
51 #include "wimlib/xml.h"
62 /* wimlib internal flags used when writing resources. */
63 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
64 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
65 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
68 write_flags_to_resource_flags(int write_flags)
70 int write_resource_flags = 0;
72 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
73 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
74 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
75 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
76 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
77 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
78 return write_resource_flags;
81 struct filter_context {
86 /* Determine specified stream should be filtered out from the write.
90 * < 0 : The stream should be hard-filtered; that is, not included in the
92 * 0 : The stream should not be filtered out.
93 * > 0 : The stream should be soft-filtered; that is, it already exists in the
94 * WIM file and may not need to be written again.
97 stream_filtered(const struct wim_lookup_table_entry *lte,
98 const struct filter_context *ctx)
100 int write_flags = ctx->write_flags;
101 WIMStruct *wim = ctx->wim;
106 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
107 lte->resource_location == RESOURCE_IN_WIM &&
108 lte->rspec->wim == wim)
111 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
112 lte->resource_location == RESOURCE_IN_WIM &&
113 lte->rspec->wim != wim)
120 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
121 struct filter_context *ctx)
123 return stream_filtered(lte, ctx) < 0;
127 may_soft_filter_streams(const struct filter_context *ctx)
131 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
135 may_hard_filter_streams(const struct filter_context *ctx)
139 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
143 may_filter_streams(const struct filter_context *ctx)
145 return (may_soft_filter_streams(ctx) ||
146 may_hard_filter_streams(ctx));
150 /* Return true if the specified resource is compressed and the compressed data
151 * can be reused with the specified output parameters. */
153 can_raw_copy(const struct wim_lookup_table_entry *lte,
154 int write_resource_flags, int out_ctype, u32 out_chunk_size)
156 const struct wim_resource_spec *rspec;
158 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
161 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
164 if (lte->resource_location != RESOURCE_IN_WIM)
169 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
173 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
174 /* Normal compressed resource: Must use same compression type
176 return (rspec->compression_type == out_ctype &&
177 rspec->chunk_size == out_chunk_size);
180 /* XXX: For compatibility, we can't allow multiple packed resources per
183 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
184 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
186 /* Packed resource: Such resources may contain multiple streams,
187 * and in general only a subset of them need to be written. As
188 * a heuristic, re-use the raw data if at least half the
189 * uncompressed size is being written. */
191 /* Note: packed resources contain a header that specifies the
192 * compression type and chunk size; therefore we don't need to
193 * check if they are compatible with @out_ctype and
194 * @out_chunk_size. */
196 struct wim_lookup_table_entry *res_stream;
199 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
200 if (res_stream->will_be_in_output_wim)
201 write_size += res_stream->size;
203 return (write_size > rspec->uncompressed_size / 2);
211 filter_resource_flags(u8 flags)
213 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
214 WIM_RESHDR_FLAG_COMPRESSED |
215 WIM_RESHDR_FLAG_SPANNED |
216 WIM_RESHDR_FLAG_FREE));
220 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
222 const struct wim_resource_spec *rspec;
224 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
227 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
229 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
231 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
232 lte->out_reshdr.uncompressed_size = 0;
233 lte->out_reshdr.size_in_wim = lte->size;
235 lte->out_res_offset_in_wim = rspec->offset_in_wim;
236 lte->out_res_size_in_wim = rspec->size_in_wim;
237 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
239 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
241 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
242 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
243 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
245 lte->out_reshdr.flags = lte->flags;
249 /* Write the header for a stream in a pipable WIM. */
251 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
252 struct filedes *out_fd,
253 int additional_reshdr_flags)
255 struct pwm_stream_hdr stream_hdr;
259 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
260 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
261 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
262 zero_out_hash(stream_hdr.hash);
264 wimlib_assert(!lte->unhashed);
265 copy_hash(stream_hdr.hash, lte->hash);
268 reshdr_flags = filter_resource_flags(lte->flags);
269 reshdr_flags |= additional_reshdr_flags;
270 stream_hdr.flags = cpu_to_le32(reshdr_flags);
271 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
273 ERROR_WITH_ERRNO("Write error");
277 struct write_streams_progress_data {
278 wimlib_progress_func_t progress_func;
279 union wimlib_progress_info progress;
280 uint64_t next_progress;
281 WIMStruct *prev_wim_part;
285 do_write_streams_progress(struct write_streams_progress_data *progress_data,
286 struct wim_lookup_table_entry *cur_stream,
291 union wimlib_progress_info *progress = &progress_data->progress;
295 progress->write_streams.total_bytes -= complete_size;
296 progress->write_streams.total_streams -= complete_count;
297 if (progress_data->next_progress != ~(uint64_t)0 &&
298 progress_data->next_progress > progress->write_streams.total_bytes)
300 progress_data->next_progress = progress->write_streams.total_bytes;
303 progress->write_streams.completed_bytes += complete_size;
304 progress->write_streams.completed_streams += complete_count;
307 new_wim_part = false;
308 if (cur_stream->resource_location == RESOURCE_IN_WIM &&
309 cur_stream->rspec->wim != progress_data->prev_wim_part)
311 if (progress_data->prev_wim_part) {
313 progress->write_streams.completed_parts++;
315 progress_data->prev_wim_part = cur_stream->rspec->wim;
318 if (progress_data->progress_func
319 && (progress->write_streams.completed_bytes >= progress_data->next_progress
322 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
324 if (progress_data->next_progress == progress->write_streams.total_bytes) {
325 progress_data->next_progress = ~(uint64_t)0;
327 progress_data->next_progress =
328 min(progress->write_streams.total_bytes,
329 progress->write_streams.completed_bytes +
330 progress->write_streams.total_bytes / 100);
335 struct write_streams_ctx {
336 /* File descriptor the streams are being written to. */
337 struct filedes *out_fd;
339 /* Lookup table for the WIMStruct on whose behalf the streams are being
341 struct wim_lookup_table *lookup_table;
343 /* Compression format to use. */
346 /* Maximum uncompressed chunk size in compressed resources to use. */
349 /* Flags that affect how the streams will be written. */
350 int write_resource_flags;
352 /* Data used for issuing WRITE_STREAMS progress. */
353 struct write_streams_progress_data progress_data;
355 struct filter_context *filter_ctx;
357 /* Upper bound on the total number of bytes that need to be compressed.
359 u64 num_bytes_to_compress;
361 /* Pointer to the chunk_compressor implementation being used for
362 * compressing chunks of data, or NULL if chunks are being written
364 struct chunk_compressor *compressor;
366 /* Buffer for dividing the read data into chunks of size
367 * @out_chunk_size. */
370 /* Number of bytes in @chunk_buf that are currently filled. */
371 size_t chunk_buf_filled;
373 /* List of streams that currently have chunks being compressed. */
374 struct list_head pending_streams;
376 /* List of streams in the resource pack. Streams are moved here after
377 * @pending_streams only when writing a packed resource. */
378 struct list_head pack_streams;
380 /* Set to true if the stream currently being read was a duplicate, and
381 * therefore the corresponding stream entry needs to be freed once the
382 * read finishes. (In this case we add the duplicate entry to
383 * pending_streams rather than the entry being read.) */
384 bool stream_was_duplicate;
386 /* Current uncompressed offset in the stream being read. */
387 u64 cur_read_stream_offset;
389 /* Uncompressed size of the stream currently being read. */
390 u64 cur_read_stream_size;
392 /* Current uncompressed offset in the stream being written. */
393 u64 cur_write_stream_offset;
395 /* Uncompressed size of resource currently being written. */
396 u64 cur_write_res_size;
398 /* Array that is filled in with compressed chunk sizes as a resource is
402 /* Index of next entry in @chunk_csizes to fill in. */
405 /* Number of entries in @chunk_csizes currently allocated. */
406 size_t num_alloc_chunks;
408 /* Offset in the output file of the start of the chunks of the resource
409 * currently being written. */
410 u64 chunks_start_offset;
413 /* Reserve space for the chunk table and prepare to accumulate the chunk table
416 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
418 u64 expected_num_chunks;
419 u64 expected_num_chunk_entries;
423 /* Calculate the number of chunks and chunk entries that should be
424 * needed for the resource. These normally will be the final values,
425 * but in PACKED_STREAMS mode some of the streams we're planning to
426 * write into the resource may be duplicates, and therefore discarded,
427 * potentially decreasing the number of chunk entries needed. */
428 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
429 expected_num_chunk_entries = expected_num_chunks;
430 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
431 expected_num_chunk_entries--;
433 /* Make sure the chunk_csizes array is long enough to store the
434 * compressed size of each chunk. */
435 if (expected_num_chunks > ctx->num_alloc_chunks) {
436 u64 new_length = expected_num_chunks + 50;
438 if ((size_t)new_length != new_length) {
439 ERROR("Resource size too large (%"PRIu64" bytes!",
441 return WIMLIB_ERR_NOMEM;
444 FREE(ctx->chunk_csizes);
445 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
446 if (ctx->chunk_csizes == NULL) {
447 ctx->num_alloc_chunks = 0;
448 return WIMLIB_ERR_NOMEM;
450 ctx->num_alloc_chunks = new_length;
453 ctx->chunk_index = 0;
455 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
456 /* Reserve space for the chunk table in the output file. In the
457 * case of packed resources this reserves the upper bound for
458 * the needed space, not necessarily the exact space which will
459 * prove to be needed. At this point, we just use @chunk_csizes
460 * for a buffer of 0's because the actual compressed chunk sizes
462 reserve_size = expected_num_chunk_entries *
463 get_chunk_entry_size(res_expected_size,
464 0 != (ctx->write_resource_flags &
465 WIM_RESHDR_FLAG_PACKED_STREAMS));
466 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
467 reserve_size += sizeof(struct alt_chunk_table_header_disk);
468 memset(ctx->chunk_csizes, 0, reserve_size);
469 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
477 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
481 wimlib_assert(res_expected_size != 0);
483 if (ctx->compressor != NULL) {
484 ret = begin_chunk_table(ctx, res_expected_size);
489 /* Output file descriptor is now positioned at the offset at which to
490 * write the first chunk of the resource. */
491 ctx->chunks_start_offset = ctx->out_fd->offset;
492 ctx->cur_write_stream_offset = 0;
493 ctx->cur_write_res_size = res_expected_size;
498 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
499 u64 *res_start_offset_ret, u64 *res_store_size_ret)
501 size_t actual_num_chunks;
502 size_t actual_num_chunk_entries;
503 size_t chunk_entry_size;
506 actual_num_chunks = ctx->chunk_index;
507 actual_num_chunk_entries = actual_num_chunks;
508 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
509 actual_num_chunk_entries--;
511 chunk_entry_size = get_chunk_entry_size(res_actual_size,
512 0 != (ctx->write_resource_flags &
513 WIM_RESHDR_FLAG_PACKED_STREAMS));
515 typedef le64 __attribute__((may_alias)) aliased_le64_t;
516 typedef le32 __attribute__((may_alias)) aliased_le32_t;
518 if (chunk_entry_size == 4) {
519 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
521 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
522 for (size_t i = 0; i < actual_num_chunk_entries; i++)
523 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
525 u32 offset = ctx->chunk_csizes[0];
526 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
527 u32 next_size = ctx->chunk_csizes[i + 1];
528 entries[i] = cpu_to_le32(offset);
533 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
535 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
536 for (size_t i = 0; i < actual_num_chunk_entries; i++)
537 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
539 u64 offset = ctx->chunk_csizes[0];
540 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
541 u64 next_size = ctx->chunk_csizes[i + 1];
542 entries[i] = cpu_to_le64(offset);
548 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
549 u64 res_start_offset;
552 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
553 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
556 res_end_offset = ctx->out_fd->offset;
557 res_start_offset = ctx->chunks_start_offset;
559 res_end_offset = ctx->out_fd->offset;
561 u64 chunk_table_offset;
563 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
565 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
566 struct alt_chunk_table_header_disk hdr;
568 hdr.res_usize = cpu_to_le64(res_actual_size);
569 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
570 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
572 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
573 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
574 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
576 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
577 chunk_table_offset - sizeof(hdr));
580 res_start_offset = chunk_table_offset - sizeof(hdr);
582 res_start_offset = chunk_table_offset;
585 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
586 chunk_table_size, chunk_table_offset);
591 *res_start_offset_ret = res_start_offset;
592 *res_store_size_ret = res_end_offset - res_start_offset;
597 ERROR_WITH_ERRNO("Write error");
601 /* Finish writing a WIM resource by writing or updating the chunk table (if not
602 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
604 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
608 u64 res_uncompressed_size;
609 u64 res_offset_in_wim;
611 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
612 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS));
613 res_uncompressed_size = ctx->cur_write_res_size;
615 if (ctx->compressor) {
616 ret = end_chunk_table(ctx, res_uncompressed_size,
617 &res_offset_in_wim, &res_size_in_wim);
621 res_offset_in_wim = ctx->chunks_start_offset;
622 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
624 out_reshdr->uncompressed_size = res_uncompressed_size;
625 out_reshdr->size_in_wim = res_size_in_wim;
626 out_reshdr->offset_in_wim = res_offset_in_wim;
627 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
628 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
632 /* Begin processing a stream for writing. */
634 write_stream_begin_read(struct wim_lookup_table_entry *lte,
635 bool is_partial_res, void *_ctx)
637 struct write_streams_ctx *ctx = _ctx;
640 wimlib_assert(lte->size > 0);
642 ctx->cur_read_stream_offset = 0;
643 ctx->cur_read_stream_size = lte->size;
645 /* As an optimization, we allow some streams to be "unhashed", meaning
646 * their SHA1 message digests are unknown. This is the case with
647 * streams that are added by scanning a directry tree with
648 * wimlib_add_image(), for example. Since WIM uses single-instance
649 * streams, we don't know whether such each such stream really need to
650 * written until it is actually checksummed, unless it has a unique
651 * size. In such cases we read and checksum the stream in this
652 * function, thereby advancing ahead of read_stream_list(), which will
653 * still provide the data again to write_stream_process_chunk(). This
654 * is okay because an unhashed stream cannot be in a WIM resource, which
655 * might be costly to decompress. */
656 ctx->stream_was_duplicate = false;
657 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
659 wimlib_assert(!is_partial_res);
661 struct wim_lookup_table_entry *lte_new;
663 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
666 if (lte_new != lte) {
667 /* Duplicate stream detected. */
669 if (lte_new->will_be_in_output_wim ||
670 stream_filtered(lte_new, ctx->filter_ctx))
672 /* The duplicate stream is already being
673 * included in the output WIM, or it would be
674 * filtered out if it had been. Skip writing
675 * this stream (and reading it again) entirely,
676 * passing its output reference count to the
677 * duplicate stream in the former case. */
678 DEBUG("Discarding duplicate stream of "
679 "length %"PRIu64, lte->size);
680 do_write_streams_progress(&ctx->progress_data,
683 list_del(<e->write_streams_list);
684 list_del(<e->lookup_table_list);
685 if (lte_new->will_be_in_output_wim)
686 lte_new->out_refcnt += lte->out_refcnt;
687 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
688 ctx->cur_write_res_size -= lte->size;
689 free_lookup_table_entry(lte);
690 return BEGIN_STREAM_STATUS_SKIP_STREAM;
692 /* The duplicate stream can validly be written,
693 * but was not marked as such. Discard the
694 * current stream entry and use the duplicate,
695 * but actually freeing the current entry must
696 * wait until read_stream_list() has finished
697 * reading its data. */
698 DEBUG("Stream duplicate, but not already "
699 "selected for writing.");
700 list_replace(<e->write_streams_list,
701 <e_new->write_streams_list);
702 list_replace(<e->lookup_table_list,
703 <e_new->lookup_table_list);
704 lte_new->out_refcnt = lte->out_refcnt;
705 lte_new->will_be_in_output_wim = 1;
706 ctx->stream_was_duplicate = true;
711 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
715 /* Rewrite a stream that was just written compressed as uncompressed instead.
716 * This function is optional, but if a stream did not compress to less than its
717 * original size, it might as well be written uncompressed. */
719 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
720 struct filedes *out_fd)
723 u64 begin_offset = lte->out_reshdr.offset_in_wim;
724 u64 end_offset = out_fd->offset;
726 if (filedes_seek(out_fd, begin_offset) == -1)
729 ret = extract_full_stream_to_fd(lte, out_fd);
731 /* Error reading the uncompressed data. */
732 if (out_fd->offset == begin_offset &&
733 filedes_seek(out_fd, end_offset) != -1)
735 /* Nothing was actually written yet, and we successfully
736 * seeked to the end of the compressed resource, so
737 * don't issue a hard error; just keep the compressed
738 * resource instead. */
739 WARNING("Recovered compressed stream of "
740 "size %"PRIu64", continuing on.",
747 wimlib_assert(out_fd->offset - begin_offset == lte->size);
749 if (out_fd->offset < end_offset &&
750 0 != ftruncate(out_fd->fd, out_fd->offset))
752 ERROR_WITH_ERRNO("Can't truncate output file to "
753 "offset %"PRIu64, out_fd->offset);
754 return WIMLIB_ERR_WRITE;
757 lte->out_reshdr.size_in_wim = lte->size;
758 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
759 WIM_RESHDR_FLAG_PACKED_STREAMS);
763 /* Write the next chunk of (typically compressed) data to the output WIM,
764 * handling the writing of the chunk table. */
766 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
767 size_t csize, size_t usize)
771 struct wim_lookup_table_entry *lte;
772 u32 completed_stream_count;
775 lte = list_entry(ctx->pending_streams.next,
776 struct wim_lookup_table_entry, write_streams_list);
778 if (ctx->cur_write_stream_offset == 0 &&
779 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
781 /* Starting to write a new stream in non-packed mode. */
783 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
784 int additional_reshdr_flags = 0;
785 if (ctx->compressor != NULL)
786 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
788 DEBUG("Writing pipable WIM stream header "
789 "(offset=%"PRIu64")", ctx->out_fd->offset);
791 ret = write_pwm_stream_header(lte, ctx->out_fd,
792 additional_reshdr_flags);
797 ret = begin_write_resource(ctx, lte->size);
802 if (ctx->compressor != NULL) {
803 /* Record the compresed chunk size. */
804 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
805 ctx->chunk_csizes[ctx->chunk_index++] = csize;
807 /* If writing a pipable WIM, before the chunk data write a chunk
808 * header that provides the compressed chunk size. */
809 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
810 struct pwm_chunk_hdr chunk_hdr = {
811 .compressed_size = cpu_to_le32(csize),
813 ret = full_write(ctx->out_fd, &chunk_hdr,
820 /* Write the chunk data. */
821 ret = full_write(ctx->out_fd, cchunk, csize);
825 ctx->cur_write_stream_offset += usize;
827 completed_size = usize;
828 completed_stream_count = 0;
829 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
830 /* Wrote chunk in packed mode. It may have finished multiple
832 while (ctx->cur_write_stream_offset > lte->size) {
833 struct wim_lookup_table_entry *next;
835 ctx->cur_write_stream_offset -= lte->size;
837 wimlib_assert(!list_is_singular(&ctx->pending_streams) &&
838 !list_empty(&ctx->pending_streams));
839 next = list_entry(lte->write_streams_list.next,
840 struct wim_lookup_table_entry,
842 list_move_tail(<e->write_streams_list,
845 completed_stream_count++;
847 if (ctx->cur_write_stream_offset == lte->size) {
848 ctx->cur_write_stream_offset = 0;
849 list_move_tail(<e->write_streams_list,
851 completed_stream_count++;
854 /* Wrote chunk in non-packed mode. It may have finished a
856 if (ctx->cur_write_stream_offset == lte->size) {
858 completed_stream_count++;
860 list_del(<e->write_streams_list);
862 wimlib_assert(ctx->cur_write_stream_offset ==
863 ctx->cur_write_res_size);
865 ret = end_write_resource(ctx, <e->out_reshdr);
869 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
870 if (ctx->compressor != NULL)
871 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
873 if (ctx->compressor != NULL &&
874 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
875 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) &&
876 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
878 /* Stream did not compress to less than its original
879 * size. If we're not writing a pipable WIM (which
880 * could mean the output file descriptor is
881 * non-seekable), and the stream isn't located in a
882 * resource pack (which would make reading it again
883 * costly), truncate the file to the start of the stream
884 * and write it uncompressed instead. */
885 DEBUG("Stream of size %"PRIu64" did not compress to "
886 "less than original size; writing uncompressed.",
888 ret = write_stream_uncompressed(lte, ctx->out_fd);
892 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
894 ctx->cur_write_stream_offset = 0;
898 do_write_streams_progress(&ctx->progress_data, lte,
899 completed_size, completed_stream_count,
905 ERROR_WITH_ERRNO("Write error");
910 submit_chunk_for_compression(struct write_streams_ctx *ctx,
911 const void *chunk, size_t size)
913 /* While we are unable to submit the chunk for compression (due to too
914 * many chunks already outstanding), retrieve and write the next
915 * compressed chunk. */
916 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
923 bret = ctx->compressor->get_chunk(ctx->compressor,
924 &cchunk, &csize, &usize);
928 ret = write_chunk(ctx, cchunk, csize, usize);
935 /* Process the next chunk of data to be written to a WIM resource. */
937 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
939 struct write_streams_ctx *ctx = _ctx;
941 const u8 *chunkptr, *chunkend;
943 wimlib_assert(size != 0);
945 if (ctx->compressor == NULL) {
946 /* Write chunk uncompressed. */
947 ret = write_chunk(ctx, chunk, size, size);
950 ctx->cur_read_stream_offset += size;
954 /* Submit the chunk for compression, but take into account that the
955 * @size the chunk was provided in may not correspond to the
956 * @out_chunk_size being used for compression. */
958 chunkend = chunkptr + size;
960 const u8 *resized_chunk;
961 size_t needed_chunk_size;
963 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
964 needed_chunk_size = ctx->out_chunk_size;
966 u64 res_bytes_remaining;
968 res_bytes_remaining = ctx->cur_read_stream_size -
969 ctx->cur_read_stream_offset;
970 needed_chunk_size = min(ctx->out_chunk_size,
971 ctx->chunk_buf_filled +
972 res_bytes_remaining);
975 if (ctx->chunk_buf_filled == 0 &&
976 chunkend - chunkptr >= needed_chunk_size)
978 /* No intermediate buffering needed. */
979 resized_chunk = chunkptr;
980 chunkptr += needed_chunk_size;
981 ctx->cur_read_stream_offset += needed_chunk_size;
983 /* Intermediate buffering needed. */
984 size_t bytes_consumed;
986 bytes_consumed = min(chunkend - chunkptr,
987 needed_chunk_size - ctx->chunk_buf_filled);
989 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
990 chunkptr, bytes_consumed);
992 chunkptr += bytes_consumed;
993 ctx->cur_read_stream_offset += bytes_consumed;
994 ctx->chunk_buf_filled += bytes_consumed;
995 if (ctx->chunk_buf_filled == needed_chunk_size) {
996 resized_chunk = ctx->chunk_buf;
997 ctx->chunk_buf_filled = 0;
1004 ret = submit_chunk_for_compression(ctx, resized_chunk,
1009 } while (chunkptr != chunkend);
1013 /* Finish processing a stream for writing. It may not have been completely
1014 * written yet, as the chunk_compressor implementation may still have chunks
1015 * buffered or being compressed. */
1017 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1019 struct write_streams_ctx *ctx = _ctx;
1021 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size);
1022 if (ctx->stream_was_duplicate) {
1023 free_lookup_table_entry(lte);
1024 } else if (lte->unhashed && ctx->lookup_table != NULL) {
1025 list_del(<e->unhashed_list);
1026 lookup_table_insert(ctx->lookup_table, lte);
1032 /* Compute statistics about a list of streams that will be written.
1034 * Assumes the streams are sorted such that all streams located in each distinct
1035 * WIM (specified by WIMStruct) are together. */
1037 compute_stream_list_stats(struct list_head *stream_list,
1038 struct write_streams_ctx *ctx)
1040 struct wim_lookup_table_entry *lte;
1041 u64 total_bytes = 0;
1042 u64 num_streams = 0;
1043 u64 total_parts = 0;
1044 WIMStruct *prev_wim_part = NULL;
1046 list_for_each_entry(lte, stream_list, write_streams_list) {
1048 total_bytes += lte->size;
1049 if (lte->resource_location == RESOURCE_IN_WIM) {
1050 if (prev_wim_part != lte->rspec->wim) {
1051 prev_wim_part = lte->rspec->wim;
1056 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1057 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1058 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1059 ctx->progress_data.progress.write_streams.completed_streams = 0;
1060 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1061 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1062 ctx->progress_data.progress.write_streams.completed_parts = 0;
1063 ctx->progress_data.next_progress = 0;
1064 ctx->progress_data.prev_wim_part = NULL;
1067 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1068 * rather than compressed. Delete these streams from @stream_list, and move one
1069 * per resource to @raw_copy_resources. Return the total uncompressed size of
1070 * the streams that need to be compressed. */
1072 find_raw_copy_resources(struct list_head *stream_list,
1073 int write_resource_flags,
1076 struct list_head *raw_copy_resources)
1078 struct wim_lookup_table_entry *lte, *tmp;
1079 u64 num_bytes_to_compress = 0;
1081 INIT_LIST_HEAD(raw_copy_resources);
1083 /* Initialize temporary raw_copy_ok flag. */
1084 list_for_each_entry(lte, stream_list, write_streams_list)
1085 if (lte->resource_location == RESOURCE_IN_WIM)
1086 lte->rspec->raw_copy_ok = 0;
1088 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1089 if (lte->resource_location == RESOURCE_IN_WIM &&
1090 lte->rspec->raw_copy_ok)
1092 list_del(<e->write_streams_list);
1093 } else if (can_raw_copy(lte, write_resource_flags,
1094 out_ctype, out_chunk_size))
1096 lte->rspec->raw_copy_ok = 1;
1097 list_move_tail(<e->write_streams_list,
1098 raw_copy_resources);
1100 num_bytes_to_compress += lte->size;
1104 return num_bytes_to_compress;
1107 /* Copy a raw compressed resource located in another WIM file to the WIM file
1110 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1111 struct filedes *out_fd)
1113 u64 cur_read_offset;
1114 u64 end_read_offset;
1115 u8 buf[BUFFER_SIZE];
1116 size_t bytes_to_read;
1118 struct filedes *in_fd;
1119 struct wim_lookup_table_entry *lte;
1120 u64 out_offset_in_wim;
1122 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1123 "uncompressed_size=%"PRIu64")",
1124 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1126 /* Copy the raw data. */
1127 cur_read_offset = in_rspec->offset_in_wim;
1128 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1130 out_offset_in_wim = out_fd->offset;
1132 if (in_rspec->is_pipable) {
1133 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1134 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1135 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1136 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1138 in_fd = &in_rspec->wim->in_fd;
1139 wimlib_assert(cur_read_offset != end_read_offset);
1142 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1144 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1148 ret = full_write(out_fd, buf, bytes_to_read);
1152 cur_read_offset += bytes_to_read;
1154 } while (cur_read_offset != end_read_offset);
1156 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1157 if (lte->will_be_in_output_wim) {
1158 stream_set_out_reshdr_for_reuse(lte);
1159 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1160 lte->out_res_offset_in_wim = out_offset_in_wim;
1162 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1169 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1170 * file being written. */
1172 write_raw_copy_resources(struct list_head *raw_copy_resources,
1173 struct filedes *out_fd,
1174 struct write_streams_progress_data *progress_data)
1176 struct wim_lookup_table_entry *lte;
1179 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1180 ret = write_raw_copy_resource(lte->rspec, out_fd);
1183 do_write_streams_progress(progress_data, lte, lte->size,
1189 /* Wait for and write all chunks pending in the compressor. */
1191 finish_remaining_chunks(struct write_streams_ctx *ctx)
1198 if (ctx->compressor == NULL)
1201 if (ctx->chunk_buf_filled != 0) {
1202 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1203 ctx->chunk_buf_filled);
1208 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1209 ret = write_chunk(ctx, cdata, csize, usize);
1217 remove_zero_length_streams(struct list_head *stream_list)
1219 struct wim_lookup_table_entry *lte, *tmp;
1221 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1222 wimlib_assert(lte->will_be_in_output_wim);
1223 if (lte->size == 0) {
1224 list_del(<e->write_streams_list);
1225 lte->out_reshdr.offset_in_wim = 0;
1226 lte->out_reshdr.size_in_wim = 0;
1227 lte->out_reshdr.uncompressed_size = 0;
1228 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1234 * Write a list of streams to the output WIM file.
1237 * The list of streams to write, specified by a list of `struct
1238 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1241 * The file descriptor, opened for writing, to which to write the streams.
1243 * @write_resource_flags
1244 * Flags to modify how the streams are written:
1246 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1247 * Force compression of all resources, even if they could otherwise
1248 * be re-used by copying the raw data, due to being located in a WIM
1249 * file with compatible compression parameters.
1251 * WRITE_RESOURCE_FLAG_PIPABLE:
1252 * Write the resources in the wimlib-specific pipable format, and
1253 * furthermore do so in such a way that no seeking backwards in
1254 * @out_fd will be performed (so it may be a pipe).
1256 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1257 * Pack all the streams into a single resource rather than writing
1258 * them in separate resources. This flag is only valid if the WIM
1259 * version number has been, or will be, set to
1260 * WIM_VERSION_PACKED_STREAMS. This flag may not be combined with
1261 * WRITE_RESOURCE_FLAG_PIPABLE.
1264 * Compression format to use to write the output streams, specified as one
1265 * of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1266 * WIMLIB_COMPRESSION_TYPE_INVALID but including
1267 * WIMLIB_COMPRESSION_TYPE_NONE.
1270 * Chunk size to use to write the streams. It must be a valid chunk size
1271 * for the specified compression format @out_ctype, unless @out_ctype is
1272 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1275 * Number of threads to use to compress data. If 0, a default number of
1276 * threads will be chosen. The number of threads still may be decreased
1277 * from the specified value if insufficient memory is detected.
1280 * If on-the-fly deduplication of unhashed streams is desired, this
1281 * parameter must be pointer to the lookup table for the WIMStruct on whose
1282 * behalf the streams are being written. Otherwise, this parameter can be
1286 * If on-the-fly deduplication of unhashed streams is desired, this
1287 * parameter can be a pointer to a context for stream filtering used to
1288 * detect whether the duplicate stream has been hard-filtered or not. If
1289 * no streams are hard-filtered or no streams are unhashed, this parameter
1293 * If non-NULL, a progress function that will be called periodically with
1294 * WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages. Note that on-the-fly
1295 * deduplication of unhashed streams may result in the total bytes provided
1296 * in the progress data to decrease from one message to the next.
1298 * This function will write the streams in @stream_list to resources in
1299 * consecutive positions in the output WIM file, or to a single packed resource
1300 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1301 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1302 * each stream written will be updated to specify its location, size, and flags
1303 * in the output WIM. In the packed resource case,
1304 * WIM_RESHDR_FLAG_PACKED_STREAMS will be set in the @flags field of each
1305 * @out_reshdr, and furthermore @out_res_offset_in_wim and @out_res_size_in_wim
1306 * of each @out_reshdr will be set to the offset and size, respectively, in the
1307 * output WIM of the packed resource containing the corresponding stream.
1309 * Each of the streams to write may be in any location supported by the
1310 * resource-handling code (specifically, read_stream_list()), such as the
1311 * contents of external file that has been logically added to the output WIM, or
1312 * a stream in another WIM file that has been imported, or even a stream in the
1313 * "same" WIM file of which a modified copy is being written. In the case that
1314 * a stream is already in a WIM file and uses compatible compression parameters,
1315 * by default this function will re-use the raw data instead of decompressing
1316 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1317 * specified in @write_resource_flags, this is not done.
1319 * As a further requirement, this function requires that the
1320 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1321 * well as any other streams not in @stream_list that will be in the output WIM
1322 * file, but set to 0 on any other streams in the output WIM's lookup table or
1323 * sharing a packed resource with a stream in @stream_list. Still furthermore,
1324 * if on-the-fly deduplication of streams is possible, then all streams in
1325 * @stream_list must also be linked by @lookup_table_list along with any other
1326 * streams that have @will_be_in_output_wim set.
1328 * This function handles on-the-fly deduplication of streams for which SHA1
1329 * message digests have not yet been calculated. Such streams may or may not
1330 * need to be written. If @lookup_table is non-NULL, then each stream in
1331 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1332 * immediately before it would otherwise be read for writing in order to
1333 * determine if it is identical to another stream already being written or one
1334 * that would be filtered out of the output WIM using stream_filtered() with the
1335 * context @filter_ctx. Each such duplicate stream will be removed from
1336 * @stream_list, its reference count transfered to the pre-existing duplicate
1337 * stream, its memory freed, and will not be written. Alternatively, if a
1338 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1339 * has not been marked for writing or would not be hard-filtered, it is freed
1340 * and the pre-existing duplicate is written instead, taking ownership of the
1341 * reference count and slot in the @lookup_table_list.
1343 * Returns 0 if every stream was either written successfully or did not need to
1344 * be written; otherwise returns a non-zero error code.
1347 write_stream_list(struct list_head *stream_list,
1348 struct filedes *out_fd,
1349 int write_resource_flags,
1352 unsigned num_threads,
1353 struct wim_lookup_table *lookup_table,
1354 struct filter_context *filter_ctx,
1355 wimlib_progress_func_t progress_func)
1358 struct write_streams_ctx ctx;
1359 struct list_head raw_copy_resources;
1361 wimlib_assert((write_resource_flags &
1362 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1363 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1364 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1365 WRITE_RESOURCE_FLAG_PIPABLE));
1367 remove_zero_length_streams(stream_list);
1369 if (list_empty(stream_list)) {
1370 DEBUG("No streams to write.");
1374 memset(&ctx, 0, sizeof(ctx));
1376 /* Pre-sorting the streams is required for compute_stream_list_stats().
1377 * Afterwards, read_stream_list() need not sort them again. */
1378 ret = sort_stream_list_by_sequential_order(stream_list,
1379 offsetof(struct wim_lookup_table_entry,
1380 write_streams_list));
1384 ctx.out_fd = out_fd;
1385 ctx.lookup_table = lookup_table;
1386 ctx.out_ctype = out_ctype;
1387 ctx.out_chunk_size = out_chunk_size;
1388 ctx.write_resource_flags = write_resource_flags;
1389 ctx.filter_ctx = filter_ctx;
1391 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1392 wimlib_assert(out_chunk_size != 0);
1393 if (out_chunk_size <= STACK_MAX) {
1394 ctx.chunk_buf = alloca(out_chunk_size);
1396 ctx.chunk_buf = MALLOC(out_chunk_size);
1397 if (ctx.chunk_buf == NULL) {
1398 ret = WIMLIB_ERR_NOMEM;
1399 goto out_destroy_context;
1403 ctx.chunk_buf_filled = 0;
1405 compute_stream_list_stats(stream_list, &ctx);
1407 ctx.progress_data.progress_func = progress_func;
1409 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1410 write_resource_flags,
1413 &raw_copy_resources);
1415 DEBUG("Writing stream list "
1416 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1417 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1418 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1419 out_fd->offset, write_resource_flags,
1420 out_ctype, out_chunk_size, num_threads,
1421 ctx.progress_data.progress.write_streams.total_bytes,
1422 ctx.num_bytes_to_compress);
1424 if (ctx.num_bytes_to_compress == 0) {
1425 DEBUG("No compression needed; skipping to raw copy!");
1426 goto out_write_raw_copy_resources;
1429 /* Unless uncompressed output was required, allocate a chunk_compressor
1430 * to do compression. There are serial and parallel implementations of
1431 * the chunk_compressor interface. We default to parallel using the
1432 * specified number of threads, unless the upper bound on the number
1433 * bytes needing to be compressed is less than a heuristic value. */
1434 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1436 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1437 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1438 ret = new_parallel_chunk_compressor(out_ctype,
1443 DEBUG("Couldn't create parallel chunk compressor "
1444 "(status %d)", ret);
1449 if (ctx.compressor == NULL) {
1450 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1453 goto out_destroy_context;
1458 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1460 ctx.progress_data.progress.write_streams.num_threads = 1;
1462 DEBUG("Actually using %u threads",
1463 ctx.progress_data.progress.write_streams.num_threads);
1465 INIT_LIST_HEAD(&ctx.pending_streams);
1466 INIT_LIST_HEAD(&ctx.pack_streams);
1468 if (ctx.progress_data.progress_func) {
1469 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1470 &ctx.progress_data.progress);
1473 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1474 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1476 goto out_destroy_context;
1479 /* Read the list of streams needing to be compressed, using the
1480 * specified callbacks to execute processing of the data. */
1482 struct read_stream_list_callbacks cbs = {
1483 .begin_stream = write_stream_begin_read,
1484 .begin_stream_ctx = &ctx,
1485 .consume_chunk = write_stream_process_chunk,
1486 .consume_chunk_ctx = &ctx,
1487 .end_stream = write_stream_end_read,
1488 .end_stream_ctx = &ctx,
1491 ret = read_stream_list(stream_list,
1492 offsetof(struct wim_lookup_table_entry, write_streams_list),
1494 STREAM_LIST_ALREADY_SORTED |
1495 VERIFY_STREAM_HASHES |
1496 COMPUTE_MISSING_STREAM_HASHES);
1499 goto out_destroy_context;
1501 ret = finish_remaining_chunks(&ctx);
1503 goto out_destroy_context;
1505 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1506 struct wim_reshdr reshdr;
1507 struct wim_lookup_table_entry *lte;
1510 ret = end_write_resource(&ctx, &reshdr);
1512 goto out_destroy_context;
1514 DEBUG("Ending packed resource: %lu %lu %lu.",
1515 reshdr.offset_in_wim,
1517 reshdr.uncompressed_size);
1520 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1521 lte->out_reshdr.size_in_wim = lte->size;
1522 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1523 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1524 lte->out_reshdr.uncompressed_size = 0;
1525 lte->out_reshdr.offset_in_wim = offset_in_res;
1526 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1527 lte->out_res_size_in_wim = reshdr.size_in_wim;
1528 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1529 offset_in_res += lte->size;
1531 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1534 out_write_raw_copy_resources:
1535 /* Copy any compressed resources for which the raw data can be reused
1536 * without decompression. */
1537 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1538 &ctx.progress_data);
1540 out_destroy_context:
1541 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1542 FREE(ctx.chunk_buf);
1543 FREE(ctx.chunk_csizes);
1545 ctx.compressor->destroy(ctx.compressor);
1546 DEBUG("Done (ret=%d)", ret);
1551 wim_write_stream_list(WIMStruct *wim,
1552 struct list_head *stream_list,
1554 unsigned num_threads,
1555 struct filter_context *filter_ctx,
1556 wimlib_progress_func_t progress_func)
1560 int write_resource_flags;
1562 write_resource_flags = write_flags_to_resource_flags(write_flags);
1564 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1565 out_chunk_size = wim->out_pack_chunk_size;
1566 out_ctype = wim->out_pack_compression_type;
1568 out_chunk_size = wim->out_chunk_size;
1569 out_ctype = wim->out_compression_type;
1572 return write_stream_list(stream_list,
1574 write_resource_flags,
1584 write_wim_resource(struct wim_lookup_table_entry *lte,
1585 struct filedes *out_fd,
1588 int write_resource_flags)
1590 LIST_HEAD(stream_list);
1591 list_add(<e->write_streams_list, &stream_list);
1592 lte->will_be_in_output_wim = 1;
1593 return write_stream_list(&stream_list,
1595 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1605 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1606 int reshdr_flags, struct filedes *out_fd,
1609 struct wim_reshdr *out_reshdr,
1611 int write_resource_flags)
1614 struct wim_lookup_table_entry *lte;
1616 /* Set up a temporary lookup table entry to provide to
1617 * write_wim_resource(). */
1619 lte = new_lookup_table_entry();
1621 return WIMLIB_ERR_NOMEM;
1623 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1624 lte->attached_buffer = (void*)buf;
1625 lte->size = buf_size;
1626 lte->flags = reshdr_flags;
1628 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1629 sha1_buffer(buf, buf_size, lte->hash);
1635 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1636 write_resource_flags);
1640 copy_reshdr(out_reshdr, <e->out_reshdr);
1643 copy_hash(hash, lte->hash);
1646 lte->resource_location = RESOURCE_NONEXISTENT;
1647 free_lookup_table_entry(lte);
1651 struct stream_size_table {
1652 struct hlist_head *array;
1658 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1660 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1661 if (tab->array == NULL)
1662 return WIMLIB_ERR_NOMEM;
1663 tab->num_entries = 0;
1664 tab->capacity = capacity;
1669 destroy_stream_size_table(struct stream_size_table *tab)
1675 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1677 struct stream_size_table *tab = _tab;
1679 struct wim_lookup_table_entry *same_size_lte;
1680 struct hlist_node *tmp;
1682 pos = hash_u64(lte->size) % tab->capacity;
1683 lte->unique_size = 1;
1684 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1685 if (same_size_lte->size == lte->size) {
1686 lte->unique_size = 0;
1687 same_size_lte->unique_size = 0;
1692 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1697 struct find_streams_ctx {
1700 struct list_head stream_list;
1701 struct stream_size_table stream_size_tab;
1705 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1706 struct list_head *stream_list, u32 nref)
1708 if (!lte->will_be_in_output_wim) {
1709 lte->out_refcnt = 0;
1710 list_add_tail(<e->write_streams_list, stream_list);
1711 lte->will_be_in_output_wim = 1;
1713 lte->out_refcnt += nref;
1717 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1720 struct list_head *stream_list = _stream_list;
1721 lte->will_be_in_output_wim = 0;
1722 reference_stream_for_write(lte, stream_list, lte->refcnt);
1727 inode_find_streams_to_reference(const struct wim_inode *inode,
1728 const struct wim_lookup_table *table,
1729 struct list_head *stream_list)
1731 struct wim_lookup_table_entry *lte;
1734 wimlib_assert(inode->i_nlink > 0);
1736 for (i = 0; i <= inode->i_num_ads; i++) {
1737 lte = inode_stream_lte(inode, i, table);
1739 reference_stream_for_write(lte, stream_list,
1741 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1742 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1748 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1750 lte->will_be_in_output_wim = 0;
1755 image_find_streams_to_reference(WIMStruct *wim)
1757 struct wim_image_metadata *imd;
1758 struct wim_inode *inode;
1759 struct wim_lookup_table_entry *lte;
1760 struct list_head *stream_list;
1763 imd = wim_get_current_image_metadata(wim);
1765 image_for_each_unhashed_stream(lte, imd)
1766 lte->will_be_in_output_wim = 0;
1768 stream_list = wim->private;
1769 image_for_each_inode(inode, imd) {
1770 ret = inode_find_streams_to_reference(inode,
1780 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1783 struct list_head *stream_list_ret)
1787 INIT_LIST_HEAD(stream_list_ret);
1789 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1790 (image == 1 && wim->hdr.image_count == 1)))
1792 /* Fast case: Assume that all streams are being written and
1793 * that the reference counts are correct. */
1794 struct wim_lookup_table_entry *lte;
1795 struct wim_image_metadata *imd;
1798 for_lookup_table_entry(wim->lookup_table,
1799 fully_reference_stream_for_write,
1802 for (i = 0; i < wim->hdr.image_count; i++) {
1803 imd = wim->image_metadata[i];
1804 image_for_each_unhashed_stream(lte, imd)
1805 fully_reference_stream_for_write(lte, stream_list_ret);
1808 /* Slow case: Walk through the images being written and
1809 * determine the streams referenced. */
1810 for_lookup_table_entry(wim->lookup_table,
1811 do_stream_set_not_in_output_wim, NULL);
1812 wim->private = stream_list_ret;
1813 ret = for_image(wim, image, image_find_streams_to_reference);
1821 struct insert_other_if_hard_filtered_ctx {
1822 struct stream_size_table *tab;
1823 struct filter_context *filter_ctx;
1827 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1829 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1831 if (!lte->will_be_in_output_wim &&
1832 stream_hard_filtered(lte, ctx->filter_ctx))
1833 stream_size_table_insert(lte, ctx->tab);
1838 determine_stream_size_uniquity(struct list_head *stream_list,
1839 struct wim_lookup_table *lt,
1840 struct filter_context *filter_ctx)
1843 struct stream_size_table tab;
1844 struct wim_lookup_table_entry *lte;
1846 ret = init_stream_size_table(&tab, 9001);
1850 if (may_hard_filter_streams(filter_ctx)) {
1851 struct insert_other_if_hard_filtered_ctx ctx = {
1853 .filter_ctx = filter_ctx,
1855 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1858 list_for_each_entry(lte, stream_list, write_streams_list)
1859 stream_size_table_insert(lte, &tab);
1861 destroy_stream_size_table(&tab);
1866 filter_stream_list_for_write(struct list_head *stream_list,
1867 struct filter_context *filter_ctx)
1869 struct wim_lookup_table_entry *lte, *tmp;
1871 list_for_each_entry_safe(lte, tmp,
1872 stream_list, write_streams_list)
1874 int status = stream_filtered(lte, filter_ctx);
1881 /* Soft filtered. */
1883 /* Hard filtered. */
1884 lte->will_be_in_output_wim = 0;
1885 list_del(<e->lookup_table_list);
1887 list_del(<e->write_streams_list);
1893 * prepare_stream_list_for_write() -
1895 * Prepare the list of streams to write for writing a WIM containing the
1896 * specified image(s) with the specified write flags.
1899 * The WIMStruct on whose behalf the write is occurring.
1902 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1905 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1907 * STREAMS_OK: For writes of all images, assume that all streams in the
1908 * lookup table of @wim and the per-image lists of unhashed streams should
1909 * be taken as-is, and image metadata should not be searched for
1910 * references. This does not exclude filtering with OVERWRITE and
1911 * SKIP_EXTERNAL_WIMS, below.
1913 * OVERWRITE: Streams already present in @wim shall not be returned in
1916 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1917 * @wim, shall be be returned in neither @stream_list_ret nor
1918 * @lookup_table_list_ret.
1921 * List of streams, linked by write_streams_list, that need to be written
1922 * will be returned here.
1924 * Note that this function assumes that unhashed streams will be written;
1925 * it does not take into account that they may become duplicates when
1928 * @lookup_table_list_ret
1929 * List of streams, linked by lookup_table_list, that need to be included
1930 * in the WIM's lookup table will be returned here. This will be a
1931 * superset of the streams in @stream_list_ret.
1933 * This list will be a proper superset of @stream_list_ret if and only if
1934 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1935 * the streams that would otherwise need to be written were already located
1938 * All streams in this list will have @out_refcnt set to the number of
1939 * references to the stream in the output WIM. If
1940 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1941 * may be as low as 0.
1944 * A context for queries of stream filter status with stream_filtered() is
1945 * returned in this location.
1947 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1948 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1949 * lookup table of @wim not inserted into @lookup_table_list_ret.
1951 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1952 * @stream_list_ret that have unique size among all stream entries in
1953 * @stream_list_ret and among all stream entries in the lookup table of @wim
1954 * that are ineligible for being written due to filtering.
1956 * Returns 0 on success; nonzero on read error, memory allocation error, or
1960 prepare_stream_list_for_write(WIMStruct *wim, int image,
1962 struct list_head *stream_list_ret,
1963 struct list_head *lookup_table_list_ret,
1964 struct filter_context *filter_ctx_ret)
1967 struct wim_lookup_table_entry *lte;
1969 filter_ctx_ret->write_flags = write_flags;
1970 filter_ctx_ret->wim = wim;
1972 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1975 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1980 INIT_LIST_HEAD(lookup_table_list_ret);
1981 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1982 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1984 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1989 if (may_filter_streams(filter_ctx_ret))
1990 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1996 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1997 unsigned num_threads,
1998 wimlib_progress_func_t progress_func,
1999 struct list_head *stream_list_override,
2000 struct list_head *lookup_table_list_ret)
2003 struct list_head _stream_list;
2004 struct list_head *stream_list;
2005 struct wim_lookup_table_entry *lte;
2006 struct filter_context _filter_ctx;
2007 struct filter_context *filter_ctx;
2009 if (stream_list_override == NULL) {
2010 /* Normal case: prepare stream list from image(s) being written.
2012 stream_list = &_stream_list;
2013 filter_ctx = &_filter_ctx;
2014 ret = prepare_stream_list_for_write(wim, image, write_flags,
2016 lookup_table_list_ret,
2021 /* Currently only as a result of wimlib_split() being called:
2022 * use stream list already explicitly provided. Use existing
2023 * reference counts. */
2024 stream_list = stream_list_override;
2026 INIT_LIST_HEAD(lookup_table_list_ret);
2027 list_for_each_entry(lte, stream_list, write_streams_list) {
2028 lte->out_refcnt = lte->refcnt;
2029 lte->will_be_in_output_wim = 1;
2030 lte->unique_size = 0;
2031 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2035 return wim_write_stream_list(wim,
2044 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2045 wimlib_progress_func_t progress_func)
2050 int write_resource_flags;
2052 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2053 DEBUG("Not writing any metadata resources.");
2057 write_resource_flags = write_flags_to_resource_flags(write_flags);
2059 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2061 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2062 wim->out_fd.offset);
2065 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2067 if (image == WIMLIB_ALL_IMAGES) {
2069 end_image = wim->hdr.image_count;
2071 start_image = image;
2075 for (int i = start_image; i <= end_image; i++) {
2076 struct wim_image_metadata *imd;
2078 imd = wim->image_metadata[i - 1];
2079 /* Build a new metadata resource only if image was modified from
2080 * the original (or was newly added). Otherwise just copy the
2082 if (imd->modified) {
2083 DEBUG("Image %u was modified; building and writing new "
2084 "metadata resource", i);
2085 ret = write_metadata_resource(wim, i,
2086 write_resource_flags);
2087 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2088 DEBUG("Image %u was not modified; re-using existing "
2089 "metadata resource.", i);
2090 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2093 DEBUG("Image %u was not modified; copying existing "
2094 "metadata resource.", i);
2095 ret = write_wim_resource(imd->metadata_lte,
2097 wim->out_compression_type,
2098 wim->out_chunk_size,
2099 write_resource_flags);
2105 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2110 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2113 DEBUG("Opening \"%"TS"\" for writing.", path);
2115 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2117 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2118 return WIMLIB_ERR_OPEN;
2120 filedes_init(&wim->out_fd, raw_fd);
2125 close_wim_writable(WIMStruct *wim, int write_flags)
2129 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2130 DEBUG("Closing WIM file.");
2131 if (filedes_valid(&wim->out_fd))
2132 if (filedes_close(&wim->out_fd))
2133 ret = WIMLIB_ERR_WRITE;
2135 filedes_invalidate(&wim->out_fd);
2140 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2142 const struct wim_lookup_table_entry *lte1, *lte2;
2144 lte1 = *(const struct wim_lookup_table_entry**)p1;
2145 lte2 = *(const struct wim_lookup_table_entry**)p2;
2147 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2148 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2149 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2150 return cmp_u64(lte1->out_res_offset_in_wim,
2151 lte2->out_res_offset_in_wim);
2156 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2159 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2160 lte2->out_reshdr.offset_in_wim);
2164 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2165 struct wim_reshdr *out_reshdr,
2166 struct list_head *lookup_table_list)
2170 /* Set output resource metadata for streams already present in WIM. */
2171 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2172 struct wim_lookup_table_entry *lte;
2173 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2175 if (lte->resource_location == RESOURCE_IN_WIM &&
2176 lte->rspec->wim == wim)
2178 stream_set_out_reshdr_for_reuse(lte);
2183 ret = sort_stream_list(lookup_table_list,
2184 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2185 cmp_streams_by_out_rspec);
2189 /* Add entries for metadata resources. */
2190 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2194 if (image == WIMLIB_ALL_IMAGES) {
2196 end_image = wim->hdr.image_count;
2198 start_image = image;
2202 /* Push metadata resource lookup table entries onto the front of
2203 * the list in reverse order, so that they're written in order.
2205 for (int i = end_image; i >= start_image; i--) {
2206 struct wim_lookup_table_entry *metadata_lte;
2208 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2209 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2210 metadata_lte->out_refcnt = 1;
2211 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2215 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2217 wim->hdr.part_number,
2219 write_flags_to_resource_flags(write_flags));
2225 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2226 * table, then overwrite the WIM header. By default, closes the WIM file
2227 * descriptor (@wim->out_fd) if successful.
2229 * write_flags is a bitwise OR of the following:
2231 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2232 * Include an integrity table.
2234 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2235 * fsync() the output file before closing it.
2237 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2238 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2239 * stream headers before the lookup table and XML data, and also
2240 * write the WIM header at the end instead of seeking to the
2241 * beginning. Can't be combined with
2242 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2244 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2245 * Don't write the lookup table.
2247 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2248 * When (if) writing the integrity table, re-use entries from the
2249 * existing integrity table, if possible.
2251 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2252 * After writing the XML data but before writing the integrity
2253 * table, write a temporary WIM header and flush the stream so that
2254 * the WIM is less likely to become corrupted upon abrupt program
2256 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2257 * Instead of overwriting the WIM header at the beginning of the
2258 * file, simply append it to the end of the file. (Used when
2260 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2261 * Do not close the file descriptor @wim->out_fd on either success
2263 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2264 * Use the existing <TOTALBYTES> stored in the in-memory XML
2265 * information, rather than setting it to the offset of the XML
2266 * data being written.
2269 finish_write(WIMStruct *wim, int image, int write_flags,
2270 wimlib_progress_func_t progress_func,
2271 struct list_head *lookup_table_list)
2275 int write_resource_flags;
2276 off_t old_lookup_table_end;
2277 off_t new_lookup_table_end;
2280 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2282 write_resource_flags = write_flags_to_resource_flags(write_flags);
2284 /* In the WIM header, there is room for the resource entry for a
2285 * metadata resource labeled as the "boot metadata". This entry should
2286 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2287 * it should be a copy of the resource entry for the image that is
2288 * marked as bootable. This is not well documented... */
2289 if (wim->hdr.boot_idx == 0) {
2290 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2292 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2293 &wim->image_metadata[
2294 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2297 /* Write lookup table. (Save old position first.) */
2298 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2299 wim->hdr.lookup_table_reshdr.size_in_wim;
2300 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2301 ret = write_wim_lookup_table(wim, image, write_flags,
2302 &wim->hdr.lookup_table_reshdr,
2308 /* Write XML data. */
2309 xml_totalbytes = wim->out_fd.offset;
2310 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2311 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2312 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2313 &wim->hdr.xml_data_reshdr,
2314 write_resource_flags);
2318 /* Write integrity table (optional). */
2319 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2320 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2321 struct wim_header checkpoint_hdr;
2322 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2323 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2324 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2325 ret = write_wim_header_at_offset(&checkpoint_hdr,
2331 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2332 old_lookup_table_end = 0;
2334 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2335 wim->hdr.lookup_table_reshdr.size_in_wim;
2337 ret = write_integrity_table(wim,
2338 new_lookup_table_end,
2339 old_lookup_table_end,
2344 /* No integrity table. */
2345 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2348 /* Now that all information in the WIM header has been determined, the
2349 * preliminary header written earlier can be overwritten, the header of
2350 * the existing WIM file can be overwritten, or the final header can be
2351 * written to the end of the pipable WIM. */
2352 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2354 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2355 hdr_offset = wim->out_fd.offset;
2356 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2357 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2361 /* Possibly sync file data to disk before closing. On POSIX systems, it
2362 * is necessary to do this before using rename() to overwrite an
2363 * existing file with a new file. Otherwise, data loss would occur if
2364 * the system is abruptly terminated when the metadata for the rename
2365 * operation has been written to disk, but the new file data has not.
2367 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2368 DEBUG("Syncing WIM file.");
2369 if (fsync(wim->out_fd.fd)) {
2370 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2371 return WIMLIB_ERR_WRITE;
2375 if (close_wim_writable(wim, write_flags)) {
2376 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2377 return WIMLIB_ERR_WRITE;
2383 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2385 lock_wim(WIMStruct *wim, int fd)
2388 if (fd != -1 && !wim->wim_locked) {
2389 ret = flock(fd, LOCK_EX | LOCK_NB);
2391 if (errno == EWOULDBLOCK) {
2392 ERROR("`%"TS"' is already being modified or has been "
2393 "mounted read-write\n"
2394 " by another process!", wim->filename);
2395 ret = WIMLIB_ERR_ALREADY_LOCKED;
2397 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2402 wim->wim_locked = 1;
2410 * write_pipable_wim():
2412 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2413 * capable of being applied from a pipe).
2415 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2416 * images can be applied from them sequentially when the file data is sent over
2417 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2418 * The modifications made to the WIM format for pipable WIMs are:
2420 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2421 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2422 * stops other software from trying to read the file as a normal WIM.
2424 * - The header at the beginning of the file does not contain all the normal
2425 * information; in particular it will have all 0's for the lookup table and
2426 * XML data resource entries. This is because this information cannot be
2427 * determined until the lookup table and XML data have been written.
2428 * Consequently, wimlib will write the full header at the very end of the
2429 * file. The header at the end, however, is only used when reading the WIM
2430 * from a seekable file (not a pipe).
2432 * - An extra copy of the XML data is placed directly after the header. This
2433 * allows image names and sizes to be determined at an appropriate time when
2434 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2435 * WIM is read from a seekable file (not a pipe).
2437 * - The format of resources, or streams, has been modified to allow them to be
2438 * used before the "lookup table" has been read. Each stream is prefixed with
2439 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2440 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2441 * uncompressed stream size, and flags that indicate whether the stream is
2442 * compressed. The data of uncompressed streams then follows literally, while
2443 * the data of compressed streams follows in a modified format. Compressed
2444 * streams do not begin with a chunk table, since the chunk table cannot be
2445 * written until all chunks have been compressed. Instead, each compressed
2446 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2447 * Furthermore, the chunk table is written at the end of the resource instead
2448 * of the start. Note: chunk offsets are given in the chunk table as if the
2449 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2450 * used if the WIM is being read from a seekable file (not a pipe).
2452 * - Metadata resources always come before other file resources (streams).
2453 * (This does not by itself constitute an incompatibility with normal WIMs,
2454 * since this is valid in normal WIMs.)
2456 * - At least up to the end of the file resources, all components must be packed
2457 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2458 * not by itself consititute an incompatibility with normal WIMs, since this
2459 * is valid in normal WIMs.)
2461 * Note: the lookup table, XML data, and header at the end are not used when
2462 * applying from a pipe. They exist to support functionality such as image
2463 * application and export when the WIM is *not* read from a pipe.
2465 * Layout of pipable WIM:
2467 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2468 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2469 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2471 * Layout of normal WIM:
2473 * +--------+-----------------------------+-------------------------+
2474 * | Header | File and metadata resources | Lookup table | XML data |
2475 * +--------+-----------------------------+-------------------------+
2477 * An optional integrity table can follow the final XML data in both normal and
2478 * pipable WIMs. However, due to implementation details, wimlib currently can
2479 * only include an integrity table in a pipable WIM when writing it to a
2480 * seekable file (not a pipe).
2482 * Do note that since pipable WIMs are not supported by Microsoft's software,
2483 * wimlib does not create them unless explicitly requested (with
2484 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2485 * characters to identify the file.
2488 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2489 unsigned num_threads, wimlib_progress_func_t progress_func,
2490 struct list_head *stream_list_override,
2491 struct list_head *lookup_table_list_ret)
2494 struct wim_reshdr xml_reshdr;
2496 WARNING("Creating a pipable WIM, which will "
2498 " with Microsoft's software (wimgapi/imagex/Dism).");
2500 /* At this point, the header at the beginning of the file has already
2503 /* For efficiency, when wimlib adds an image to the WIM with
2504 * wimlib_add_image(), the SHA1 message digests of files is not
2505 * calculated; instead, they are calculated while the files are being
2506 * written. However, this does not work when writing a pipable WIM,
2507 * since when writing a stream to a pipable WIM, its SHA1 message digest
2508 * needs to be known before the stream data is written. Therefore,
2509 * before getting much farther, we need to pre-calculate the SHA1
2510 * message digests of all streams that will be written. */
2511 ret = wim_checksum_unhashed_streams(wim);
2515 /* Write extra copy of the XML data. */
2516 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2518 WRITE_RESOURCE_FLAG_PIPABLE);
2522 /* Write metadata resources for the image(s) being included in the
2524 ret = write_wim_metadata_resources(wim, image, write_flags,
2529 /* Write streams needed for the image(s) being included in the output
2530 * WIM, or streams needed for the split WIM part. */
2531 return write_wim_streams(wim, image, write_flags, num_threads,
2532 progress_func, stream_list_override,
2533 lookup_table_list_ret);
2535 /* The lookup table, XML data, and header at end are handled by
2536 * finish_write(). */
2539 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2542 write_wim_part(WIMStruct *wim,
2543 const void *path_or_fd,
2546 unsigned num_threads,
2547 wimlib_progress_func_t progress_func,
2548 unsigned part_number,
2549 unsigned total_parts,
2550 struct list_head *stream_list_override,
2554 struct wim_header hdr_save;
2555 struct list_head lookup_table_list;
2557 if (total_parts == 1)
2558 DEBUG("Writing standalone WIM.");
2560 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2561 if (image == WIMLIB_ALL_IMAGES)
2562 DEBUG("Including all images.");
2564 DEBUG("Including image %d only.", image);
2565 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2566 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2568 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2569 DEBUG("Write flags: 0x%08x", write_flags);
2571 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2572 DEBUG("\tCHECK_INTEGRITY");
2574 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2577 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2578 DEBUG("\tRECOMPRESS");
2580 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2583 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2586 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2587 DEBUG("\tIGNORE_READONLY_FLAG");
2589 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2592 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2593 DEBUG("\tNOT_PIPABLE");
2595 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2596 DEBUG("\tPACK_STREAMS");
2598 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2599 DEBUG("\tFILE_DESCRIPTOR");
2601 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2602 DEBUG("\tNO_METADATA");
2604 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2605 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2607 if (num_threads == 0)
2608 DEBUG("Number of threads: autodetect");
2610 DEBUG("Number of threads: %u", num_threads);
2611 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2612 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2613 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2614 "specified" : "generate new"));
2616 /* Internally, this is always called with a valid part number and total
2618 wimlib_assert(total_parts >= 1);
2619 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2621 /* A valid image (or all images) must be specified. */
2622 if (image != WIMLIB_ALL_IMAGES &&
2623 (image < 1 || image > wim->hdr.image_count))
2624 return WIMLIB_ERR_INVALID_IMAGE;
2626 /* If we need to write metadata resources, make sure the ::WIMStruct has
2627 * the needed information attached (e.g. is not a resource-only WIM,
2628 * such as a non-first part of a split WIM). */
2629 if (!wim_has_metadata(wim) &&
2630 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2631 return WIMLIB_ERR_METADATA_NOT_FOUND;
2633 /* Check for contradictory flags. */
2634 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2635 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2636 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2637 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2638 return WIMLIB_ERR_INVALID_PARAM;
2640 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2641 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2642 == (WIMLIB_WRITE_FLAG_PIPABLE |
2643 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2644 return WIMLIB_ERR_INVALID_PARAM;
2646 /* Save previous header, then start initializing the new one. */
2647 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2649 /* Set default integrity, pipable, and packed stream flags. */
2650 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2651 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2652 if (wim_is_pipable(wim)) {
2653 DEBUG("WIM is pipable; default to PIPABLE.");
2654 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2657 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2658 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2659 if (wim_has_integrity_table(wim)) {
2660 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2661 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2664 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2665 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2666 == (WIMLIB_WRITE_FLAG_PIPABLE |
2667 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2669 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2670 return WIMLIB_ERR_INVALID_PARAM;
2673 /* Set appropriate magic number. */
2674 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2675 wim->hdr.magic = PWM_MAGIC;
2677 wim->hdr.magic = WIM_MAGIC;
2679 /* Set appropriate version number. */
2680 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2681 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2682 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2684 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2686 /* Clear header flags that will be set automatically. */
2687 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2688 WIM_HDR_FLAG_RESOURCE_ONLY |
2689 WIM_HDR_FLAG_SPANNED |
2690 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2692 /* Set SPANNED header flag if writing part of a split WIM. */
2693 if (total_parts != 1)
2694 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2696 /* Set part number and total parts of split WIM. This will be 1 and 1
2697 * if the WIM is standalone. */
2698 wim->hdr.part_number = part_number;
2699 wim->hdr.total_parts = total_parts;
2701 /* Set compression type if different. */
2702 if (wim->compression_type != wim->out_compression_type) {
2703 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2704 wimlib_assert(ret == 0);
2707 /* Set chunk size if different. */
2708 wim->hdr.chunk_size = wim->out_chunk_size;
2710 /* Use GUID if specified; otherwise generate a new one. */
2712 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2713 else if (!wim->guid_set_explicitly)
2714 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2716 /* Clear references to resources that have not been written yet. */
2717 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2718 zero_reshdr(&wim->hdr.xml_data_reshdr);
2719 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2720 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2722 /* Set image count and boot index correctly for single image writes. */
2723 if (image != WIMLIB_ALL_IMAGES) {
2724 wim->hdr.image_count = 1;
2725 if (wim->hdr.boot_idx == image)
2726 wim->hdr.boot_idx = 1;
2728 wim->hdr.boot_idx = 0;
2731 /* Split WIMs can't be bootable. */
2732 if (total_parts != 1)
2733 wim->hdr.boot_idx = 0;
2735 /* Initialize output file descriptor. */
2736 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2737 /* File descriptor was explicitly provided. Return error if
2738 * file descriptor is not seekable, unless writing a pipable WIM
2740 wim->out_fd.fd = *(const int*)path_or_fd;
2741 wim->out_fd.offset = 0;
2742 if (!filedes_is_seekable(&wim->out_fd)) {
2743 ret = WIMLIB_ERR_INVALID_PARAM;
2744 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2745 goto out_restore_hdr;
2746 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2747 ERROR("Can't include integrity check when "
2748 "writing pipable WIM to pipe!");
2749 goto out_restore_hdr;
2754 /* Filename of WIM to write was provided; open file descriptor
2756 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2757 O_TRUNC | O_CREAT | O_RDWR);
2759 goto out_restore_hdr;
2762 /* Write initial header. This is merely a "dummy" header since it
2763 * doesn't have all the information yet, so it will be overwritten later
2764 * (unless writing a pipable WIM). */
2765 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2766 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2767 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2768 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2770 goto out_restore_hdr;
2772 /* Write metadata resources and streams. */
2773 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2774 /* Default case: create a normal (non-pipable) WIM. */
2775 ret = write_wim_streams(wim, image, write_flags, num_threads,
2776 progress_func, stream_list_override,
2777 &lookup_table_list);
2779 goto out_restore_hdr;
2781 ret = write_wim_metadata_resources(wim, image, write_flags,
2784 goto out_restore_hdr;
2786 /* Non-default case: create pipable WIM. */
2787 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2788 progress_func, stream_list_override,
2789 &lookup_table_list);
2791 goto out_restore_hdr;
2792 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2796 /* Write lookup table, XML data, and (optional) integrity table. */
2797 ret = finish_write(wim, image, write_flags, progress_func,
2798 &lookup_table_list);
2800 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2801 (void)close_wim_writable(wim, write_flags);
2802 DEBUG("ret=%d", ret);
2806 /* Write a standalone WIM to a file or file descriptor. */
2808 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2809 int image, int write_flags, unsigned num_threads,
2810 wimlib_progress_func_t progress_func)
2812 return write_wim_part(wim, path_or_fd, image, write_flags,
2813 num_threads, progress_func, 1, 1, NULL, NULL);
2816 /* API function documented in wimlib.h */
2818 wimlib_write(WIMStruct *wim, const tchar *path,
2819 int image, int write_flags, unsigned num_threads,
2820 wimlib_progress_func_t progress_func)
2823 return WIMLIB_ERR_INVALID_PARAM;
2825 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2827 return write_standalone_wim(wim, path, image, write_flags,
2828 num_threads, progress_func);
2831 /* API function documented in wimlib.h */
2833 wimlib_write_to_fd(WIMStruct *wim, int fd,
2834 int image, int write_flags, unsigned num_threads,
2835 wimlib_progress_func_t progress_func)
2838 return WIMLIB_ERR_INVALID_PARAM;
2840 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2841 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2843 return write_standalone_wim(wim, &fd, image, write_flags,
2844 num_threads, progress_func);
2848 any_images_modified(WIMStruct *wim)
2850 for (int i = 0; i < wim->hdr.image_count; i++)
2851 if (wim->image_metadata[i]->modified)
2857 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2859 const WIMStruct *wim = _wim;
2860 off_t end_offset = *(const off_t*)wim->private;
2862 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2863 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2864 return WIMLIB_ERR_RESOURCE_ORDER;
2868 /* Make sure no file or metadata resources are located after the XML data (or
2869 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2870 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2872 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2877 wim->private = &end_offset;
2878 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2882 for (i = 0; i < wim->hdr.image_count; i++) {
2883 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2891 * Overwrite a WIM, possibly appending streams to it.
2893 * A WIM looks like (or is supposed to look like) the following:
2895 * Header (212 bytes)
2896 * Streams and metadata resources (variable size)
2897 * Lookup table (variable size)
2898 * XML data (variable size)
2899 * Integrity table (optional) (variable size)
2901 * If we are not adding any streams or metadata resources, the lookup table is
2902 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2903 * header. This operation is potentially unsafe if the program is abruptly
2904 * terminated while the XML data or integrity table are being overwritten, but
2905 * before the new header has been written. To partially alleviate this problem,
2906 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2907 * finish_write() to cause a temporary WIM header to be written after the XML
2908 * data has been written. This may prevent the WIM from becoming corrupted if
2909 * the program is terminated while the integrity table is being calculated (but
2910 * no guarantees, due to write re-ordering...).
2912 * If we are adding new streams or images (metadata resources), the lookup table
2913 * needs to be changed, and those streams need to be written. In this case, we
2914 * try to perform a safe update of the WIM file by writing the streams *after*
2915 * the end of the previous WIM, then writing the new lookup table, XML data, and
2916 * (optionally) integrity table following the new streams. This will produce a
2917 * layout like the following:
2919 * Header (212 bytes)
2920 * (OLD) Streams and metadata resources (variable size)
2921 * (OLD) Lookup table (variable size)
2922 * (OLD) XML data (variable size)
2923 * (OLD) Integrity table (optional) (variable size)
2924 * (NEW) Streams and metadata resources (variable size)
2925 * (NEW) Lookup table (variable size)
2926 * (NEW) XML data (variable size)
2927 * (NEW) Integrity table (optional) (variable size)
2929 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2930 * the header is overwritten to point to the new lookup table, XML data, and
2931 * integrity table, to produce the following layout:
2933 * Header (212 bytes)
2934 * Streams and metadata resources (variable size)
2935 * Nothing (variable size)
2936 * More Streams and metadata resources (variable size)
2937 * Lookup table (variable size)
2938 * XML data (variable size)
2939 * Integrity table (optional) (variable size)
2941 * This method allows an image to be appended to a large WIM very quickly, and
2942 * is is crash-safe except in the case of write re-ordering, but the
2943 * disadvantage is that a small hole is left in the WIM where the old lookup
2944 * table, xml data, and integrity table were. (These usually only take up a
2945 * small amount of space compared to the streams, however.)
2948 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2949 unsigned num_threads,
2950 wimlib_progress_func_t progress_func)
2954 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2955 struct wim_header hdr_save;
2956 struct list_head stream_list;
2957 struct list_head lookup_table_list;
2958 struct filter_context filter_ctx;
2960 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2962 /* Save original header so it can be restored in case of error */
2963 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2965 /* Set default integrity flag. */
2966 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2967 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2968 if (wim_has_integrity_table(wim))
2969 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2971 /* Set WIM version if adding packed streams. */
2972 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2973 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2975 /* Set additional flags for overwrite. */
2976 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2977 WIMLIB_WRITE_FLAG_STREAMS_OK;
2979 /* Make sure that the integrity table (if present) is after the XML
2980 * data, and that there are no stream resources, metadata resources, or
2981 * lookup tables after the XML data. Otherwise, these data would be
2983 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2984 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2985 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2986 wim->hdr.lookup_table_reshdr.size_in_wim;
2987 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2988 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2989 WARNING("Didn't expect the integrity table to be before the XML data");
2990 ret = WIMLIB_ERR_RESOURCE_ORDER;
2991 goto out_restore_memory_hdr;
2994 if (old_lookup_table_end > old_xml_begin) {
2995 WARNING("Didn't expect the lookup table to be after the XML data");
2996 ret = WIMLIB_ERR_RESOURCE_ORDER;
2997 goto out_restore_memory_hdr;
3000 /* Set @old_wim_end, which indicates the point beyond which we don't
3001 * allow any file and metadata resources to appear without returning
3002 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3003 * overwrite these resources). */
3004 if (!wim->deletion_occurred && !any_images_modified(wim)) {
3005 /* If no images have been modified and no images have been
3006 * deleted, a new lookup table does not need to be written. We
3007 * shall write the new XML data and optional integrity table
3008 * immediately after the lookup table. Note that this may
3009 * overwrite an existing integrity table. */
3010 DEBUG("Skipping writing lookup table "
3011 "(no images modified or deleted)");
3012 old_wim_end = old_lookup_table_end;
3013 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3014 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3015 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3016 /* Old WIM has an integrity table; begin writing new streams
3018 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3019 wim->hdr.integrity_table_reshdr.size_in_wim;
3021 /* No existing integrity table; begin writing new streams after
3022 * the old XML data. */
3023 old_wim_end = old_xml_end;
3026 ret = check_resource_offsets(wim, old_wim_end);
3028 goto out_restore_memory_hdr;
3030 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3031 &stream_list, &lookup_table_list,
3034 goto out_restore_memory_hdr;
3036 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3038 goto out_restore_memory_hdr;
3040 ret = lock_wim(wim, wim->out_fd.fd);
3044 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3045 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3046 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3048 ERROR_WITH_ERRNO("Error updating WIM header flags");
3049 goto out_unlock_wim;
3052 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3053 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3054 ret = WIMLIB_ERR_WRITE;
3055 goto out_restore_physical_hdr;
3058 ret = wim_write_stream_list(wim,
3067 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3068 write_flags, progress_func);
3072 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3073 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3074 progress_func, &lookup_table_list);
3078 wim->wim_locked = 0;
3082 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3083 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3084 wim->filename, old_wim_end);
3085 /* Return value of ftruncate() is ignored because this is
3086 * already an error path. */
3087 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3089 out_restore_physical_hdr:
3090 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3092 wim->wim_locked = 0;
3094 (void)close_wim_writable(wim, write_flags);
3095 out_restore_memory_hdr:
3096 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3101 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3102 unsigned num_threads,
3103 wimlib_progress_func_t progress_func)
3105 size_t wim_name_len;
3108 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3110 /* Write the WIM to a temporary file in the same directory as the
3112 wim_name_len = tstrlen(wim->filename);
3113 tchar tmpfile[wim_name_len + 10];
3114 tmemcpy(tmpfile, wim->filename, wim_name_len);
3115 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3116 tmpfile[wim_name_len + 9] = T('\0');
3118 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3119 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3120 num_threads, progress_func);
3128 /* Rename the new WIM file to the original WIM file. Note: on Windows
3129 * this actually calls win32_rename_replacement(), not _wrename(), so
3130 * that removing the existing destination file can be handled. */
3131 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3132 ret = trename(tmpfile, wim->filename);
3134 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3135 tmpfile, wim->filename);
3142 return WIMLIB_ERR_RENAME;
3145 if (progress_func) {
3146 union wimlib_progress_info progress;
3147 progress.rename.from = tmpfile;
3148 progress.rename.to = wim->filename;
3149 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3154 /* Determine if the specified WIM file may be updated by appending in-place
3155 * rather than writing and replacing it with an entirely new file. */
3157 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3159 /* REBUILD flag forces full rebuild. */
3160 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3163 /* Deletions cause full rebuild by default. */
3164 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3167 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3168 * turned into a pipable WIM in-place. */
3169 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3172 /* wimlib allows multiple packs in a single WIM, but they don't seem to
3173 * be compatible with WIMGAPI, so force all streams to be repacked if
3174 * the WIM already may have contained a pack and PACK_STREAMS was
3176 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3177 wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3180 /* The default compression type and compression chunk size selected for
3181 * the output WIM must be the same as those currently used for the WIM.
3183 if (wim->compression_type != wim->out_compression_type)
3185 if (wim->chunk_size != wim->out_chunk_size)
3191 /* API function documented in wimlib.h */
3193 wimlib_overwrite(WIMStruct *wim, int write_flags,
3194 unsigned num_threads,
3195 wimlib_progress_func_t progress_func)
3200 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3202 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3203 return WIMLIB_ERR_INVALID_PARAM;
3206 return WIMLIB_ERR_NO_FILENAME;
3208 orig_hdr_flags = wim->hdr.flags;
3209 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3210 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3211 ret = can_modify_wim(wim);
3212 wim->hdr.flags = orig_hdr_flags;
3216 if (can_overwrite_wim_inplace(wim, write_flags)) {
3217 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3219 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3221 WARNING("Falling back to re-building entire WIM");
3223 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,