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/integrity.h"
43 #include "wimlib/lookup_table.h"
44 #include "wimlib/metadata.h"
45 #include "wimlib/resource.h"
47 # include "wimlib/win32.h" /* win32_rename_replacement() */
49 #include "wimlib/write.h"
50 #include "wimlib/xml.h"
61 /* wimlib internal flags used when writing resources. */
62 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
63 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
64 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
67 write_flags_to_resource_flags(int write_flags)
69 int write_resource_flags = 0;
71 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
72 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
73 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
74 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
75 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
77 return write_resource_flags;
80 struct filter_context {
85 /* Determine specified stream should be filtered out from the write.
89 * < 0 : The stream should be hard-filtered; that is, not included in the
91 * 0 : The stream should not be filtered out.
92 * > 0 : The stream should be soft-filtered; that is, it already exists in the
93 * WIM file and may not need to be written again.
96 stream_filtered(const struct wim_lookup_table_entry *lte,
97 const struct filter_context *ctx)
99 int write_flags = ctx->write_flags;
100 WIMStruct *wim = ctx->wim;
105 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
106 lte->resource_location == RESOURCE_IN_WIM &&
107 lte->rspec->wim == wim)
110 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
111 lte->resource_location == RESOURCE_IN_WIM &&
112 lte->rspec->wim != wim)
119 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
120 struct filter_context *ctx)
122 return stream_filtered(lte, ctx) < 0;
126 may_soft_filter_streams(const struct filter_context *ctx)
130 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
134 may_hard_filter_streams(const struct filter_context *ctx)
138 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
142 may_filter_streams(const struct filter_context *ctx)
144 return (may_soft_filter_streams(ctx) ||
145 may_hard_filter_streams(ctx));
149 /* Return true if the specified resource is compressed and the compressed data
150 * can be reused with the specified output parameters. */
152 can_raw_copy(const struct wim_lookup_table_entry *lte,
153 int write_resource_flags, int out_ctype, u32 out_chunk_size)
155 const struct wim_resource_spec *rspec;
157 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
160 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
163 if (lte->resource_location != RESOURCE_IN_WIM)
168 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
172 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
173 /* Normal compressed resource: Must use same compression type
175 return (rspec->wim->compression_type == out_ctype &&
176 rspec->wim->chunk_size == out_chunk_size);
179 /* XXX: For compatibility, we can't allow multiple packed resources per
182 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
183 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
185 /* Packed resource: Such resources may contain multiple streams,
186 * and in general only a subset of them need to be written. As
187 * a heuristic, re-use the raw data if at least half the
188 * uncompressed size is being written. */
190 /* Note: packed resources contain a header that specifies the
191 * compression type and chunk size; therefore we don't need to
192 * check if they are compatible with @out_ctype and
193 * @out_chunk_size. */
195 struct wim_lookup_table_entry *res_stream;
198 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
199 if (res_stream->will_be_in_output_wim)
200 write_size += res_stream->size;
202 return (write_size > rspec->uncompressed_size / 2);
210 filter_resource_flags(u8 flags)
212 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
213 WIM_RESHDR_FLAG_COMPRESSED |
214 WIM_RESHDR_FLAG_SPANNED |
215 WIM_RESHDR_FLAG_FREE));
219 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
221 const struct wim_resource_spec *rspec;
223 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
226 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
228 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
230 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
231 lte->out_reshdr.uncompressed_size = 0;
232 lte->out_reshdr.size_in_wim = lte->size;
234 lte->out_res_offset_in_wim = rspec->offset_in_wim;
235 lte->out_res_size_in_wim = rspec->size_in_wim;
236 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
238 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
240 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
241 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
242 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
244 lte->out_reshdr.flags = lte->flags;
248 /* Write the header for a stream in a pipable WIM. */
250 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
251 struct filedes *out_fd,
252 int additional_reshdr_flags)
254 struct pwm_stream_hdr stream_hdr;
258 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
259 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
260 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
261 zero_out_hash(stream_hdr.hash);
263 wimlib_assert(!lte->unhashed);
264 copy_hash(stream_hdr.hash, lte->hash);
267 reshdr_flags = filter_resource_flags(lte->flags);
268 reshdr_flags |= additional_reshdr_flags;
269 stream_hdr.flags = cpu_to_le32(reshdr_flags);
270 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
272 ERROR_WITH_ERRNO("Write error");
276 struct write_streams_progress_data {
277 wimlib_progress_func_t progress_func;
278 union wimlib_progress_info progress;
279 uint64_t next_progress;
280 WIMStruct *prev_wim_part;
284 do_write_streams_progress(struct write_streams_progress_data *progress_data,
287 struct wim_lookup_table_entry *cur_stream)
289 union wimlib_progress_info *progress = &progress_data->progress;
293 progress->write_streams.total_bytes -= size;
294 if (progress_data->next_progress != ~(uint64_t)0 &&
295 progress_data->next_progress > progress->write_streams.total_bytes)
297 progress_data->next_progress = progress->write_streams.total_bytes;
300 progress->write_streams.completed_bytes += size;
302 new_wim_part = false;
303 if (cur_stream->resource_location == RESOURCE_IN_WIM &&
304 cur_stream->rspec->wim != progress_data->prev_wim_part)
306 if (progress_data->prev_wim_part) {
308 progress->write_streams.completed_parts++;
310 progress_data->prev_wim_part = cur_stream->rspec->wim;
312 progress->write_streams.completed_streams++;
313 if (progress_data->progress_func
314 && (progress->write_streams.completed_bytes >= progress_data->next_progress
317 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
319 if (progress_data->next_progress == progress->write_streams.total_bytes) {
320 progress_data->next_progress = ~(uint64_t)0;
322 progress_data->next_progress =
323 min(progress->write_streams.total_bytes,
324 progress->write_streams.completed_bytes +
325 progress->write_streams.total_bytes / 100);
330 struct write_streams_ctx {
331 /* File descriptor the streams are being written to. */
332 struct filedes *out_fd;
334 /* Lookup table for the WIMStruct on whose behalf the streams are being
336 struct wim_lookup_table *lookup_table;
338 /* Compression format to use. */
341 /* Maximum uncompressed chunk size in compressed resources to use. */
344 /* Flags that affect how the streams will be written. */
345 int write_resource_flags;
347 /* Data used for issuing WRITE_STREAMS progress. */
348 struct write_streams_progress_data progress_data;
350 struct filter_context *filter_ctx;
352 /* Upper bound on the total number of bytes that need to be compressed.
354 u64 num_bytes_to_compress;
356 /* Pointer to the chunk_compressor implementation being used for
357 * compressing chunks of data, or NULL if chunks are being written
359 struct chunk_compressor *compressor;
361 /* Buffer for dividing the read data into chunks of size
362 * @out_chunk_size. */
365 /* Number of bytes in @chunk_buf that are currently filled. */
366 size_t chunk_buf_filled;
368 /* List of streams that currently have chunks being compressed. */
369 struct list_head pending_streams;
371 /* Set to true if the stream currently being read was a duplicate, and
372 * therefore the corresponding stream entry needs to be freed once the
373 * read finishes. (In this case we add the duplicate entry to
374 * pending_streams rather than the entry being read.) */
375 bool stream_was_duplicate;
377 /* Current uncompressed offset in the resource being read. */
378 u64 cur_read_res_offset;
380 /* Uncompressed size of the resource currently being read. */
381 u64 cur_read_res_size;
383 /* Current uncompressed offset in the resource being written. */
384 u64 cur_write_res_offset;
386 /* Uncompressed size of resource currently being written. */
387 u64 cur_write_res_size;
389 /* Array that is filled in with compressed chunk sizes as a resource is
393 /* Index of next entry in @chunk_csizes to fill in. */
396 /* Number of entries in @chunk_csizes currently allocated. */
397 size_t num_alloc_chunks;
399 /* Offset in the output file of the start of the chunks of the resource
400 * currently being written. */
401 u64 chunks_start_offset;
405 get_chunk_entry_size(u64 res_size, int write_resource_flags)
407 if (res_size <= UINT32_MAX ||
408 (write_resource_flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
414 /* Reserve space for the chunk table and prepare to accumulate the chunk table
417 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
419 u64 expected_num_chunks;
420 u64 expected_num_chunk_entries;
424 /* Calculate the number of chunks and chunk entries that should be
425 * needed for the resource. These normally will be the final values,
426 * but in PACKED_STREAMS mode some of the streams we're planning to
427 * write into the resource may be duplicates, and therefore discarded,
428 * potentially decreasing the number of chunk entries needed. */
429 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
430 expected_num_chunk_entries = expected_num_chunks;
431 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
432 expected_num_chunk_entries--;
434 /* Make sure the chunk_csizes array is long enough to store the
435 * compressed size of each chunk. */
436 if (expected_num_chunks > ctx->num_alloc_chunks) {
437 u64 new_length = expected_num_chunks + 50;
439 if ((size_t)new_length != new_length) {
440 ERROR("Resource size too large (%"PRIu64" bytes!",
442 return WIMLIB_ERR_NOMEM;
445 FREE(ctx->chunk_csizes);
446 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
447 if (ctx->chunk_csizes == NULL) {
448 ctx->num_alloc_chunks = 0;
449 return WIMLIB_ERR_NOMEM;
451 ctx->num_alloc_chunks = new_length;
454 ctx->chunk_index = 0;
456 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
457 /* Reserve space for the chunk table in the output file. In the
458 * case of packed resources this reserves the upper bound for
459 * the needed space, not necessarily the exact space which will
460 * prove to be needed. At this point, we just use @chunk_csizes
461 * for a buffer of 0's because the actual compressed chunk sizes
463 reserve_size = expected_num_chunk_entries *
464 get_chunk_entry_size(res_expected_size,
465 ctx->write_resource_flags);
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_res_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 ctx->write_resource_flags);
514 typedef le64 __attribute__((may_alias)) aliased_le64_t;
515 typedef le32 __attribute__((may_alias)) aliased_le32_t;
517 if (chunk_entry_size == 4) {
518 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
520 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
521 for (size_t i = 0; i < actual_num_chunk_entries; i++)
522 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
524 u32 offset = ctx->chunk_csizes[0];
525 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
526 u32 next_size = ctx->chunk_csizes[i + 1];
527 entries[i] = cpu_to_le32(offset);
532 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
534 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
535 for (size_t i = 0; i < actual_num_chunk_entries; i++)
536 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
538 u64 offset = ctx->chunk_csizes[0];
539 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
540 u64 next_size = ctx->chunk_csizes[i + 1];
541 entries[i] = cpu_to_le64(offset);
547 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
548 u64 res_start_offset;
551 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
552 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
555 res_end_offset = ctx->out_fd->offset;
556 res_start_offset = ctx->chunks_start_offset;
558 res_end_offset = ctx->out_fd->offset;
560 u64 chunk_table_offset;
562 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
564 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
565 struct alt_chunk_table_header_disk hdr;
567 hdr.res_usize = cpu_to_le64(res_actual_size);
568 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
569 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
571 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
572 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
573 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
575 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
576 chunk_table_offset - sizeof(hdr));
579 res_start_offset = chunk_table_offset - sizeof(hdr);
581 res_start_offset = chunk_table_offset;
584 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
585 chunk_table_size, chunk_table_offset);
590 *res_start_offset_ret = res_start_offset;
591 *res_store_size_ret = res_end_offset - res_start_offset;
596 ERROR_WITH_ERRNO("Write error");
600 /* Finish writing a WIM resource by writing or updating the chunk table (if not
601 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
603 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
607 u64 res_uncompressed_size;
608 u64 res_offset_in_wim;
610 wimlib_assert(ctx->cur_write_res_size == ctx->cur_write_res_offset);
611 res_uncompressed_size = ctx->cur_write_res_size;
613 if (ctx->compressor) {
614 ret = end_chunk_table(ctx, res_uncompressed_size,
615 &res_offset_in_wim, &res_size_in_wim);
619 res_offset_in_wim = ctx->chunks_start_offset;
620 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
622 out_reshdr->uncompressed_size = res_uncompressed_size;
623 out_reshdr->size_in_wim = res_size_in_wim;
624 out_reshdr->offset_in_wim = res_offset_in_wim;
625 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
626 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
630 /* Begin processing a stream for writing. */
632 write_stream_begin_read(struct wim_lookup_table_entry *lte,
633 bool is_partial_res, void *_ctx)
635 struct write_streams_ctx *ctx = _ctx;
638 wimlib_assert(lte->size > 0);
640 ctx->cur_read_res_offset = 0;
641 ctx->cur_read_res_size = lte->size;
643 /* As an optimization, we allow some streams to be "unhashed", meaning
644 * their SHA1 message digests are unknown. This is the case with
645 * streams that are added by scanning a directry tree with
646 * wimlib_add_image(), for example. Since WIM uses single-instance
647 * streams, we don't know whether such each such stream really need to
648 * written until it is actually checksummed, unless it has a unique
649 * size. In such cases we read and checksum the stream in this
650 * function, thereby advancing ahead of read_stream_list(), which will
651 * still provide the data again to write_stream_process_chunk(). This
652 * is okay because an unhashed stream cannot be in a WIM resource, which
653 * might be costly to decompress. */
654 ctx->stream_was_duplicate = false;
655 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
657 wimlib_assert(!is_partial_res);
659 struct wim_lookup_table_entry *lte_new;
661 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
664 if (lte_new != lte) {
665 /* Duplicate stream detected. */
667 if (lte_new->will_be_in_output_wim ||
668 stream_filtered(lte_new, ctx->filter_ctx))
670 /* The duplicate stream is already being
671 * included in the output WIM, or it would be
672 * filtered out if it had been. Skip writing
673 * this stream (and reading it again) entirely,
674 * passing its output reference count to the
675 * duplicate stream in the former case. */
676 DEBUG("Discarding duplicate stream of "
677 "length %"PRIu64, lte->size);
678 do_write_streams_progress(&ctx->progress_data,
679 lte->size, true, lte);
680 list_del(<e->write_streams_list);
681 list_del(<e->lookup_table_list);
682 if (lte_new->will_be_in_output_wim)
683 lte_new->out_refcnt += lte->out_refcnt;
684 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
685 ctx->cur_write_res_size -= lte->size;
686 free_lookup_table_entry(lte);
687 return BEGIN_STREAM_STATUS_SKIP_STREAM;
689 /* The duplicate stream can validly be written,
690 * but was not marked as such. Discard the
691 * current stream entry and use the duplicate,
692 * but actually freeing the current entry must
693 * wait until read_stream_list() has finished
694 * reading its data. */
695 DEBUG("Stream duplicate, but not already "
696 "selected for writing.");
697 list_replace(<e->write_streams_list,
698 <e_new->write_streams_list);
699 list_replace(<e->lookup_table_list,
700 <e_new->lookup_table_list);
701 lte_new->out_refcnt = lte->out_refcnt;
702 lte_new->will_be_in_output_wim = 1;
703 ctx->stream_was_duplicate = true;
708 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
713 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
714 struct filedes *out_fd)
718 if (-1 == lseek(out_fd->fd, lte->out_reshdr.offset_in_wim, SEEK_SET) ||
719 0 != ftruncate(out_fd->fd, lte->out_reshdr.offset_in_wim))
721 ERROR_WITH_ERRNO("Can't truncate output file to "
722 "offset %"PRIu64, lte->out_reshdr.offset_in_wim);
723 return WIMLIB_ERR_WRITE;
726 out_fd->offset = lte->out_reshdr.offset_in_wim;
728 ret = extract_stream_to_fd(lte, out_fd, lte->size);
732 wimlib_assert(out_fd->offset - lte->out_reshdr.offset_in_wim == lte->size);
733 lte->out_reshdr.size_in_wim = lte->size;
734 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
735 WIM_RESHDR_FLAG_PACKED_STREAMS);
739 /* Write the next chunk of (typically compressed) data to the output WIM,
740 * handling the writing of the chunk table. */
742 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
743 size_t csize, size_t usize)
747 struct wim_lookup_table_entry *lte;
749 lte = list_entry(ctx->pending_streams.next,
750 struct wim_lookup_table_entry, write_streams_list);
752 if (ctx->cur_write_res_offset == 0 &&
753 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
755 /* Starting to write a new stream in non-packed mode. */
757 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
758 int additional_reshdr_flags = 0;
759 if (ctx->compressor != NULL)
760 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
762 DEBUG("Writing pipable WIM stream header "
763 "(offset=%"PRIu64")", ctx->out_fd->offset);
765 ret = write_pwm_stream_header(lte, ctx->out_fd,
766 additional_reshdr_flags);
771 ret = begin_write_resource(ctx, lte->size);
776 if (ctx->compressor != NULL) {
777 /* Record the compresed chunk size. */
778 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
779 ctx->chunk_csizes[ctx->chunk_index++] = csize;
781 /* If writing a pipable WIM, before the chunk data write a chunk
782 * header that provides the compressed chunk size. */
783 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
784 struct pwm_chunk_hdr chunk_hdr = {
785 .compressed_size = cpu_to_le32(csize),
787 ret = full_write(ctx->out_fd, &chunk_hdr,
794 /* Write the chunk data. */
795 ret = full_write(ctx->out_fd, cchunk, csize);
799 ctx->cur_write_res_offset += usize;
801 do_write_streams_progress(&ctx->progress_data,
804 if (ctx->cur_write_res_offset == ctx->cur_write_res_size &&
805 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
807 wimlib_assert(ctx->cur_write_res_offset == lte->size);
809 /* Finished writing a stream in non-packed mode. */
811 ret = end_write_resource(ctx, <e->out_reshdr);
815 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
816 if (ctx->compressor != NULL)
817 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
819 if (ctx->compressor != NULL &&
820 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
821 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) &&
822 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
824 /* Stream did not compress to less than its original
825 * size. If we're not writing a pipable WIM (which
826 * could mean the output file descriptor is
827 * non-seekable), and the stream isn't located in a
828 * resource pack (which would make reading it again
829 * costly), truncate the file to the start of the stream
830 * and write it uncompressed instead. */
831 DEBUG("Stream of size %"PRIu64" did not compress to "
832 "less than original size; writing uncompressed.",
834 ret = write_stream_uncompressed(lte, ctx->out_fd);
839 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
841 list_del(<e->write_streams_list);
842 ctx->cur_write_res_offset = 0;
848 ERROR_WITH_ERRNO("Write error");
853 submit_chunk_for_compression(struct write_streams_ctx *ctx,
854 const void *chunk, size_t size)
856 /* While we are unable to submit the chunk for compression (due to too
857 * many chunks already outstanding), retrieve and write the next
858 * compressed chunk. */
859 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
866 bret = ctx->compressor->get_chunk(ctx->compressor,
867 &cchunk, &csize, &usize);
871 ret = write_chunk(ctx, cchunk, csize, usize);
878 /* Process the next chunk of data to be written to a WIM resource. */
880 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
882 struct write_streams_ctx *ctx = _ctx;
884 const u8 *chunkptr, *chunkend;
886 wimlib_assert(size != 0);
888 if (ctx->compressor == NULL) {
889 /* Write chunk uncompressed. */
890 ret = write_chunk(ctx, chunk, size, size);
893 ctx->cur_read_res_offset += size;
897 /* Submit the chunk for compression, but take into account that the
898 * @size the chunk was provided in may not correspond to the
899 * @out_chunk_size being used for compression. */
901 chunkend = chunkptr + size;
903 const u8 *resized_chunk;
904 size_t needed_chunk_size;
906 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
907 needed_chunk_size = ctx->out_chunk_size;
909 u64 res_bytes_remaining;
911 res_bytes_remaining = ctx->cur_read_res_size -
912 ctx->cur_read_res_offset;
913 needed_chunk_size = min(ctx->out_chunk_size,
914 ctx->chunk_buf_filled +
915 res_bytes_remaining);
918 if (ctx->chunk_buf_filled == 0 &&
919 chunkend - chunkptr >= needed_chunk_size)
921 /* No intermediate buffering needed. */
922 resized_chunk = chunkptr;
923 chunkptr += needed_chunk_size;
924 ctx->cur_read_res_offset += needed_chunk_size;
926 /* Intermediate buffering needed. */
927 size_t bytes_consumed;
929 bytes_consumed = min(chunkend - chunkptr,
930 needed_chunk_size - ctx->chunk_buf_filled);
932 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
933 chunkptr, bytes_consumed);
935 resized_chunk = ctx->chunk_buf;
937 chunkptr += bytes_consumed;
938 ctx->cur_read_res_offset += bytes_consumed;
939 ctx->chunk_buf_filled += bytes_consumed;
940 if (ctx->chunk_buf_filled == needed_chunk_size) {
941 resized_chunk = ctx->chunk_buf;
942 ctx->chunk_buf_filled = 0;
949 ret = submit_chunk_for_compression(ctx, resized_chunk,
954 } while (chunkptr != chunkend);
958 /* Finish processing a stream for writing. It may not have been completely
959 * written yet, as the chunk_compressor implementation may still have chunks
960 * buffered or being compressed. */
962 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
964 struct write_streams_ctx *ctx = _ctx;
966 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
967 if (ctx->stream_was_duplicate) {
968 free_lookup_table_entry(lte);
969 } else if (lte->unhashed && ctx->lookup_table != NULL) {
970 list_del(<e->unhashed_list);
971 lookup_table_insert(ctx->lookup_table, lte);
977 /* Compute statistics about a list of streams that will be written.
979 * Assumes the streams are sorted such that all streams located in each distinct
980 * WIM (specified by WIMStruct) are together. */
982 compute_stream_list_stats(struct list_head *stream_list,
983 struct write_streams_ctx *ctx)
985 struct wim_lookup_table_entry *lte;
989 WIMStruct *prev_wim_part = NULL;
991 list_for_each_entry(lte, stream_list, write_streams_list) {
993 total_bytes += lte->size;
994 if (lte->resource_location == RESOURCE_IN_WIM) {
995 if (prev_wim_part != lte->rspec->wim) {
996 prev_wim_part = lte->rspec->wim;
1001 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1002 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1003 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1004 ctx->progress_data.progress.write_streams.completed_streams = 0;
1005 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1006 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1007 ctx->progress_data.progress.write_streams.completed_parts = 0;
1008 ctx->progress_data.next_progress = 0;
1009 ctx->progress_data.prev_wim_part = NULL;
1012 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1013 * rather than compressed. Delete these streams from @stream_list, and move one
1014 * per resource to @raw_copy_resources. Return the total uncompressed size of
1015 * the streams that need to be compressed. */
1017 find_raw_copy_resources(struct list_head *stream_list,
1018 int write_resource_flags,
1021 struct list_head *raw_copy_resources)
1023 struct wim_lookup_table_entry *lte, *tmp;
1024 u64 num_bytes_to_compress = 0;
1026 INIT_LIST_HEAD(raw_copy_resources);
1028 /* Initialize temporary raw_copy_ok flag. */
1029 list_for_each_entry(lte, stream_list, write_streams_list)
1030 if (lte->resource_location == RESOURCE_IN_WIM)
1031 lte->rspec->raw_copy_ok = 0;
1033 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1034 if (lte->resource_location == RESOURCE_IN_WIM &&
1035 lte->rspec->raw_copy_ok)
1037 list_del(<e->write_streams_list);
1038 } else if (can_raw_copy(lte, write_resource_flags,
1039 out_ctype, out_chunk_size))
1041 lte->rspec->raw_copy_ok = 1;
1042 list_move_tail(<e->write_streams_list,
1043 raw_copy_resources);
1045 num_bytes_to_compress += lte->size;
1049 return num_bytes_to_compress;
1052 /* Copy a raw compressed resource located in another WIM file to the WIM file
1055 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1056 struct filedes *out_fd)
1058 u64 cur_read_offset;
1059 u64 end_read_offset;
1060 u8 buf[BUFFER_SIZE];
1061 size_t bytes_to_read;
1063 struct filedes *in_fd;
1064 struct wim_lookup_table_entry *lte;
1065 u64 out_offset_in_wim;
1067 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1068 "uncompressed_size=%"PRIu64")",
1069 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1071 /* Copy the raw data. */
1072 cur_read_offset = in_rspec->offset_in_wim;
1073 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1075 out_offset_in_wim = out_fd->offset;
1077 if (in_rspec->is_pipable) {
1078 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1079 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1080 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1081 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1083 in_fd = &in_rspec->wim->in_fd;
1084 wimlib_assert(cur_read_offset != end_read_offset);
1087 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1089 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1093 ret = full_write(out_fd, buf, bytes_to_read);
1097 cur_read_offset += bytes_to_read;
1099 } while (cur_read_offset != end_read_offset);
1101 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1102 if (lte->will_be_in_output_wim) {
1103 stream_set_out_reshdr_for_reuse(lte);
1104 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1105 lte->out_res_offset_in_wim = out_offset_in_wim;
1107 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1114 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1115 * file being written. */
1117 write_raw_copy_resources(struct list_head *raw_copy_resources,
1118 struct filedes *out_fd,
1119 struct write_streams_progress_data *progress_data)
1121 struct wim_lookup_table_entry *lte;
1124 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1125 ret = write_raw_copy_resource(lte->rspec, out_fd);
1128 do_write_streams_progress(progress_data, lte->size, false, lte);
1133 /* Wait for and write all chunks pending in the compressor. */
1135 finish_remaining_chunks(struct write_streams_ctx *ctx)
1142 if (ctx->compressor == NULL)
1145 if (ctx->chunk_buf_filled != 0) {
1146 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1147 ctx->chunk_buf_filled);
1152 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1153 ret = write_chunk(ctx, cdata, csize, usize);
1161 remove_zero_length_streams(struct list_head *stream_list)
1163 struct wim_lookup_table_entry *lte, *tmp;
1165 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1166 wimlib_assert(lte->will_be_in_output_wim);
1167 if (lte->size == 0) {
1168 list_del(<e->write_streams_list);
1169 lte->out_reshdr.offset_in_wim = 0;
1170 lte->out_reshdr.size_in_wim = 0;
1171 lte->out_reshdr.uncompressed_size = 0;
1172 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1178 * Write a list of streams to the output WIM file.
1181 * The list of streams to write, specifies a list of `struct
1182 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1185 * The file descriptor, opened for writing, to which to write the streams.
1187 * @write_resource_flags
1188 * Flags to modify how the streams are written:
1190 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1191 * Force compression of all resources, even if they could otherwise
1192 * be re-used by caping the raw data, due to being located in a WIM
1193 * file with compatible compression parameters.
1195 * WRITE_RESOURCE_FLAG_PIPABLE:
1196 * Write the resources in the wimlib-specific pipable format, and
1197 * furthermore do so in such a way that no seeking backwards in
1198 * @out_fd will be performed (so it may be a pipe, contrary to the
1199 * default behavior).
1201 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1202 * Pack all the streams into a single resource rather than writing
1203 * them in separate resources. This format is only valid if the
1204 * WIM version number is WIM_VERSION_PACKED_STREAMS. This flag
1205 * currently may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1208 * Compression format to use to write the output streams, specified as one
1209 * of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1210 * WIMLIB_COMPRESSION_TYPE_INVALID but including
1211 * WIMLIB_COMPRESSION_TYPE_NONE.
1214 * Chunk size to use to write the streams. It must be a valid chunk size
1215 * for the specified compression format @out_ctype, unless @out_ctype is
1216 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1219 * Number of threads to use to compress data. If 0, a default number of
1220 * threads will be chosen. The number of threads still may be decreased
1221 * from the specified value if insufficient memory is detected.
1224 * If on-the-fly deduplication of unhashed streams is desired, this
1225 * parameter must be pointer to the lookup table for the WIMStruct on whose
1226 * behalf the streams are being written. Otherwise, this parameter can be
1230 * If on-the-fly deduplication of unhashed streams is desired, this
1231 * parameter can be a pointer to a context for stream filtering used to
1232 * detect whether the duplicate stream has been hard-filtered or not. If
1233 * no streams are hard-filtered or no streams are unhashed, this parameter
1237 * If non-NULL, a progress function that will be called periodically with
1238 * WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages. Note that on-the-fly
1239 * deduplication of unhashed streams may result in the total bytes provided
1240 * in the progress data to decrease from one message to the next.
1242 * This function will write the streams in @stream_list to resources in
1243 * consecutive positions in the output WIM file, or to a single packed resource
1244 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1245 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1246 * each stream written will be updated to specify its location, size, and flags
1247 * in the output WIM. In the packed resource case,
1248 * WIM_RESHDR_FLAG_PACKED_STREAMS shall be set in the @flags field of the
1249 * @out_reshdr, and @out_res_offset_in_wim and @out_res_size_in_wim will also
1250 * be set to the offset and size, respectively, in the output WIM of the full
1251 * packed resource containing the corresponding stream.
1253 * Each of the streams to write may be in any location supported by the
1254 * resource-handling code (specifically, read_stream_list()), such as the
1255 * contents of external file that has been logically added to the output WIM, or
1256 * a stream in another WIM file that has been imported, or even stream in the
1257 * "same" WIM file of which a modified copy is being written. In the case that
1258 * a stream is already in a WIM file and uses compatible compression parameters,
1259 * by default this function will re-use the raw data instead of decompressing
1260 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1261 * specified in @write_resource_flags, this is not done.
1263 * As a further requirement, this function requires that the
1264 * @will_be_in_output_wim member be set on all streams in @stream_list as well
1265 * as any other streams not in @stream_list that will be in the output WIM file,
1266 * but not on any other streams in the output WIM's lookup table or sharing a
1267 * packed resource with a stream in @stream_list. Still furthermore, if
1268 * on-the-fly deduplication of streams is possible, then all streams in
1269 * @stream_list must also be linked by @lookup_table_list along with any other
1270 * streams that have @will_be_in_output_wim set.
1272 * This function handles on-the-fly deduplication of streams for which SHA1
1273 * message digests have not yet been calculated and it is therefore known
1274 * whether such streams are already in @stream_list or in the WIM's lookup table
1275 * at all. If @lookup_table is non-NULL, then each stream in @stream_list that
1276 * has @unhashed set but not @unique_size set is checksummed immediately before
1277 * it would otherwise be read for writing in order to determine if it is
1278 * identical to another stream already being written or one that would be
1279 * filtered out of the output WIM using stream_filtered() with the context
1280 * @filter_ctx. Each such duplicate stream will be removed from @stream_list, its
1281 * reference count transfered to the pre-existing duplicate stream, its memory
1282 * freed, and will not be written. Alternatively, if a stream in @stream_list
1283 * is a duplicate with any stream in @lookup_table that has not been marked for
1284 * writing or would not be hard-filtered, it is freed and the pre-existing
1285 * duplicate is written instead, taking ownership of the reference count and
1286 * slot in the @lookup_table_list.
1288 * Returns 0 if all streams were written successfully (or did not need to be
1289 * written); otherwise a non-zero error code.
1292 write_stream_list(struct list_head *stream_list,
1293 struct filedes *out_fd,
1294 int write_resource_flags,
1297 unsigned num_threads,
1298 struct wim_lookup_table *lookup_table,
1299 struct filter_context *filter_ctx,
1300 wimlib_progress_func_t progress_func)
1303 struct write_streams_ctx ctx;
1304 struct list_head raw_copy_resources;
1306 wimlib_assert((write_resource_flags &
1307 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1308 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1309 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1310 WRITE_RESOURCE_FLAG_PIPABLE));
1312 remove_zero_length_streams(stream_list);
1314 if (list_empty(stream_list)) {
1315 DEBUG("No streams to write.");
1319 memset(&ctx, 0, sizeof(ctx));
1321 /* Pre-sorting the streams is required for compute_stream_list_stats().
1322 * Afterwards, read_stream_list() need not sort them again. */
1323 ret = sort_stream_list_by_sequential_order(stream_list,
1324 offsetof(struct wim_lookup_table_entry,
1325 write_streams_list));
1329 ctx.out_fd = out_fd;
1330 ctx.lookup_table = lookup_table;
1331 ctx.out_ctype = out_ctype;
1332 ctx.out_chunk_size = out_chunk_size;
1333 ctx.write_resource_flags = write_resource_flags;
1334 ctx.filter_ctx = filter_ctx;
1336 if (out_chunk_size != 0) {
1337 if (out_chunk_size <= STACK_MAX) {
1338 ctx.chunk_buf = alloca(out_chunk_size);
1340 ctx.chunk_buf = MALLOC(out_chunk_size);
1341 if (ctx.chunk_buf == NULL) {
1342 ret = WIMLIB_ERR_NOMEM;
1343 goto out_destroy_context;
1347 ctx.chunk_buf_filled = 0;
1349 compute_stream_list_stats(stream_list, &ctx);
1351 ctx.progress_data.progress_func = progress_func;
1353 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1354 write_resource_flags,
1357 &raw_copy_resources);
1359 DEBUG("Writing stream list "
1360 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1361 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1362 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1363 out_fd->offset, write_resource_flags,
1364 out_ctype, out_chunk_size, num_threads,
1365 ctx.progress_data.progress.write_streams.total_bytes,
1366 ctx.num_bytes_to_compress);
1368 if (ctx.num_bytes_to_compress == 0) {
1369 DEBUG("No compression needed; skipping to raw copy!");
1370 goto out_write_raw_copy_resources;
1373 /* Unless uncompressed output was required, allocate a chunk_compressor
1374 * to do compression. There are serial and parallel implementations of
1375 * the chunk_compressor interface. We default to parallel using the
1376 * specified number of threads, unless the upper bound on the number
1377 * bytes needing to be compressed is less 2000000 (heuristic value). */
1378 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1380 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1381 if (ctx.num_bytes_to_compress >= 2000000) {
1382 ret = new_parallel_chunk_compressor(out_ctype,
1387 DEBUG("Couldn't create parallel chunk compressor "
1388 "(status %d)", ret);
1393 if (ctx.compressor == NULL) {
1394 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1397 goto out_destroy_context;
1402 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1404 ctx.progress_data.progress.write_streams.num_threads = 1;
1406 DEBUG("Actually using %u threads",
1407 ctx.progress_data.progress.write_streams.num_threads);
1409 INIT_LIST_HEAD(&ctx.pending_streams);
1411 if (ctx.progress_data.progress_func) {
1412 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1413 &ctx.progress_data.progress);
1416 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1417 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1419 goto out_destroy_context;
1422 /* Read the list of streams needing to be compressed, using the
1423 * specified callbacks to execute processing of the data. */
1425 struct read_stream_list_callbacks cbs = {
1426 .begin_stream = write_stream_begin_read,
1427 .begin_stream_ctx = &ctx,
1428 .consume_chunk = write_stream_process_chunk,
1429 .consume_chunk_ctx = &ctx,
1430 .end_stream = write_stream_end_read,
1431 .end_stream_ctx = &ctx,
1434 ret = read_stream_list(stream_list,
1435 offsetof(struct wim_lookup_table_entry, write_streams_list),
1437 STREAM_LIST_ALREADY_SORTED |
1438 VERIFY_STREAM_HASHES |
1439 COMPUTE_MISSING_STREAM_HASHES);
1442 goto out_destroy_context;
1444 ret = finish_remaining_chunks(&ctx);
1446 goto out_destroy_context;
1448 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1449 struct wim_reshdr reshdr;
1450 struct wim_lookup_table_entry *lte;
1453 ret = end_write_resource(&ctx, &reshdr);
1455 goto out_destroy_context;
1457 DEBUG("Ending packed resource: %lu %lu %lu.",
1458 reshdr.offset_in_wim,
1460 reshdr.uncompressed_size);
1463 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1464 lte->out_reshdr.size_in_wim = lte->size;
1465 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1466 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1467 lte->out_reshdr.uncompressed_size = 0;
1468 lte->out_reshdr.offset_in_wim = offset_in_res;
1469 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1470 lte->out_res_size_in_wim = reshdr.size_in_wim;
1471 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1472 offset_in_res += lte->size;
1474 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1477 out_write_raw_copy_resources:
1478 /* Copy any compressed resources for which the raw data can be reused
1479 * without decompression. */
1480 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1481 &ctx.progress_data);
1483 out_destroy_context:
1484 if (out_chunk_size > STACK_MAX)
1485 FREE(ctx.chunk_buf);
1486 FREE(ctx.chunk_csizes);
1488 ctx.compressor->destroy(ctx.compressor);
1489 DEBUG("Done (ret=%d)", ret);
1494 wim_write_stream_list(WIMStruct *wim,
1495 struct list_head *stream_list,
1497 unsigned num_threads,
1498 struct filter_context *filter_ctx,
1499 wimlib_progress_func_t progress_func)
1503 int write_resource_flags;
1505 write_resource_flags = write_flags_to_resource_flags(write_flags);
1507 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1508 out_chunk_size = wim->out_pack_chunk_size;
1509 out_ctype = wim->out_pack_compression_type;
1511 out_chunk_size = wim->out_chunk_size;
1512 out_ctype = wim->out_compression_type;
1515 return write_stream_list(stream_list,
1517 write_resource_flags,
1527 write_wim_resource(struct wim_lookup_table_entry *lte,
1528 struct filedes *out_fd,
1531 int write_resource_flags)
1533 LIST_HEAD(stream_list);
1534 list_add(<e->write_streams_list, &stream_list);
1535 lte->will_be_in_output_wim = 1;
1536 return write_stream_list(&stream_list,
1538 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1548 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1549 int reshdr_flags, struct filedes *out_fd,
1552 struct wim_reshdr *out_reshdr,
1554 int write_resource_flags)
1557 struct wim_lookup_table_entry *lte;
1559 /* Set up a temporary lookup table entry to provide to
1560 * write_wim_resource(). */
1562 lte = new_lookup_table_entry();
1564 return WIMLIB_ERR_NOMEM;
1566 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1567 lte->attached_buffer = (void*)buf;
1568 lte->size = buf_size;
1569 lte->flags = reshdr_flags;
1571 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1572 sha1_buffer(buf, buf_size, lte->hash);
1578 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1579 write_resource_flags);
1583 copy_reshdr(out_reshdr, <e->out_reshdr);
1586 copy_hash(hash, lte->hash);
1589 lte->resource_location = RESOURCE_NONEXISTENT;
1590 free_lookup_table_entry(lte);
1594 struct stream_size_table {
1595 struct hlist_head *array;
1601 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1603 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1604 if (tab->array == NULL)
1605 return WIMLIB_ERR_NOMEM;
1606 tab->num_entries = 0;
1607 tab->capacity = capacity;
1612 destroy_stream_size_table(struct stream_size_table *tab)
1618 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1620 struct stream_size_table *tab = _tab;
1622 struct wim_lookup_table_entry *same_size_lte;
1623 struct hlist_node *tmp;
1625 pos = hash_u64(lte->size) % tab->capacity;
1626 lte->unique_size = 1;
1627 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1628 if (same_size_lte->size == lte->size) {
1629 lte->unique_size = 0;
1630 same_size_lte->unique_size = 0;
1635 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1640 struct find_streams_ctx {
1643 struct list_head stream_list;
1644 struct stream_size_table stream_size_tab;
1648 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1649 struct list_head *stream_list, u32 nref)
1651 if (!lte->will_be_in_output_wim) {
1652 lte->out_refcnt = 0;
1653 list_add_tail(<e->write_streams_list, stream_list);
1654 lte->will_be_in_output_wim = 1;
1656 lte->out_refcnt += nref;
1660 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1663 struct list_head *stream_list = _stream_list;
1664 lte->will_be_in_output_wim = 0;
1665 reference_stream_for_write(lte, stream_list, lte->refcnt);
1670 inode_find_streams_to_reference(const struct wim_inode *inode,
1671 const struct wim_lookup_table *table,
1672 struct list_head *stream_list)
1674 struct wim_lookup_table_entry *lte;
1677 wimlib_assert(inode->i_nlink > 0);
1679 for (i = 0; i <= inode->i_num_ads; i++) {
1680 lte = inode_stream_lte(inode, i, table);
1682 reference_stream_for_write(lte, stream_list,
1684 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1685 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1691 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1693 lte->will_be_in_output_wim = 0;
1698 image_find_streams_to_reference(WIMStruct *wim)
1700 struct wim_image_metadata *imd;
1701 struct wim_inode *inode;
1702 struct wim_lookup_table_entry *lte;
1703 struct list_head *stream_list;
1706 imd = wim_get_current_image_metadata(wim);
1708 image_for_each_unhashed_stream(lte, imd)
1709 lte->will_be_in_output_wim = 0;
1711 stream_list = wim->private;
1712 image_for_each_inode(inode, imd) {
1713 ret = inode_find_streams_to_reference(inode,
1723 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1726 struct list_head *stream_list_ret)
1730 INIT_LIST_HEAD(stream_list_ret);
1732 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1733 (image == 1 && wim->hdr.image_count == 1)))
1735 /* Fast case: Assume that all streams are being written and
1736 * that the reference counts are correct. */
1737 struct wim_lookup_table_entry *lte;
1738 struct wim_image_metadata *imd;
1741 for_lookup_table_entry(wim->lookup_table,
1742 fully_reference_stream_for_write,
1745 for (i = 0; i < wim->hdr.image_count; i++) {
1746 imd = wim->image_metadata[i];
1747 image_for_each_unhashed_stream(lte, imd)
1748 fully_reference_stream_for_write(lte, stream_list_ret);
1751 /* Slow case: Walk through the images being written and
1752 * determine the streams referenced. */
1753 for_lookup_table_entry(wim->lookup_table,
1754 do_stream_set_not_in_output_wim, NULL);
1755 wim->private = stream_list_ret;
1756 ret = for_image(wim, image, image_find_streams_to_reference);
1764 struct insert_other_if_hard_filtered_ctx {
1765 struct stream_size_table *tab;
1766 struct filter_context *filter_ctx;
1770 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1772 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1774 if (!lte->will_be_in_output_wim &&
1775 stream_hard_filtered(lte, ctx->filter_ctx))
1776 stream_size_table_insert(lte, ctx->tab);
1781 determine_stream_size_uniquity(struct list_head *stream_list,
1782 struct wim_lookup_table *lt,
1783 struct filter_context *filter_ctx)
1786 struct stream_size_table tab;
1787 struct wim_lookup_table_entry *lte;
1789 ret = init_stream_size_table(&tab, lt->capacity);
1793 if (may_hard_filter_streams(filter_ctx)) {
1794 struct insert_other_if_hard_filtered_ctx ctx = {
1796 .filter_ctx = filter_ctx,
1798 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1801 list_for_each_entry(lte, stream_list, write_streams_list)
1802 stream_size_table_insert(lte, &tab);
1804 destroy_stream_size_table(&tab);
1809 filter_stream_list_for_write(struct list_head *stream_list,
1810 struct filter_context *filter_ctx)
1812 struct wim_lookup_table_entry *lte, *tmp;
1814 list_for_each_entry_safe(lte, tmp,
1815 stream_list, write_streams_list)
1817 int status = stream_filtered(lte, filter_ctx);
1824 /* Soft filtered. */
1826 /* Hard filtered. */
1827 lte->will_be_in_output_wim = 0;
1828 list_del(<e->lookup_table_list);
1830 list_del(<e->write_streams_list);
1836 * prepare_stream_list_for_write() -
1838 * Prepare the list of streams to write for writing a WIM containing the
1839 * specified image(s) with the specified write flags.
1842 * The WIMStruct on whose behalf the write is occurring.
1845 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1848 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1850 * STREAMS_OK: For writes of all images, assume that all streams in the
1851 * lookup table of @wim and the per-image lists of unhashed streams should
1852 * be taken as-is, and image metadata should not be searched for
1853 * references. This does not exclude filtering with OVERWRITE and
1854 * SKIP_EXTERNAL_WIMS, below.
1856 * OVERWRITE: Streams already present in @wim shall not be returned in
1859 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1860 * @wim, shall be be returned in neither @stream_list_ret nor
1861 * @lookup_table_list_ret.
1864 * List of streams, linked by write_streams_list, that need to be written
1865 * will be returned here.
1867 * Note that this function assumes that unhashed streams will be written;
1868 * it does not take into account that they may become duplicates when
1871 * @lookup_table_list_ret
1872 * List of streams, linked by lookup_table_list, that need to be included
1873 * in the WIM's lookup table will be returned here. This will be a
1874 * superset of the streams in @stream_list_ret.
1876 * This list will be a proper superset of @stream_list_ret if and only if
1877 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1878 * the streams that would otherwise need to be written were already located
1881 * All streams in this list will have @out_refcnt set to the number of
1882 * references to the stream in the output WIM. If
1883 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1884 * may be as low as 0.
1887 * A context for queries of stream filter status with stream_filtered() is
1888 * returned in this location.
1890 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1891 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1892 * lookup table of @wim not inserted into @lookup_table_list_ret.
1894 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1895 * @stream_list_ret that have unique size among all stream entries in
1896 * @stream_list_ret and among all stream entries in the lookup table of @wim
1897 * that are ineligible for being written due to filtering.
1899 * Returns 0 on success; nonzero on read error, memory allocation error, or
1903 prepare_stream_list_for_write(WIMStruct *wim, int image,
1905 struct list_head *stream_list_ret,
1906 struct list_head *lookup_table_list_ret,
1907 struct filter_context *filter_ctx_ret)
1910 struct wim_lookup_table_entry *lte;
1912 filter_ctx_ret->write_flags = write_flags;
1913 filter_ctx_ret->wim = wim;
1915 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1918 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1923 INIT_LIST_HEAD(lookup_table_list_ret);
1924 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1925 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1927 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1932 if (may_filter_streams(filter_ctx_ret))
1933 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1939 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1940 unsigned num_threads,
1941 wimlib_progress_func_t progress_func,
1942 struct list_head *stream_list_override,
1943 struct list_head *lookup_table_list_ret)
1946 struct list_head _stream_list;
1947 struct list_head *stream_list;
1948 struct wim_lookup_table_entry *lte;
1949 struct filter_context _filter_ctx;
1950 struct filter_context *filter_ctx;
1952 if (stream_list_override == NULL) {
1953 /* Normal case: prepare stream list from image(s) being written.
1955 stream_list = &_stream_list;
1956 filter_ctx = &_filter_ctx;
1957 ret = prepare_stream_list_for_write(wim, image, write_flags,
1959 lookup_table_list_ret,
1964 /* Currently only as a result of wimlib_split() being called:
1965 * use stream list already explicitly provided. Use existing
1966 * reference counts. */
1967 stream_list = stream_list_override;
1969 INIT_LIST_HEAD(lookup_table_list_ret);
1970 list_for_each_entry(lte, stream_list, write_streams_list) {
1971 lte->out_refcnt = lte->refcnt;
1972 lte->will_be_in_output_wim = 1;
1973 lte->unique_size = 0;
1974 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1978 return wim_write_stream_list(wim,
1987 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1988 wimlib_progress_func_t progress_func)
1993 int write_resource_flags;
1995 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1996 DEBUG("Not writing any metadata resources.");
2000 write_resource_flags = write_flags_to_resource_flags(write_flags);
2002 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2004 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2005 wim->out_fd.offset);
2008 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2010 if (image == WIMLIB_ALL_IMAGES) {
2012 end_image = wim->hdr.image_count;
2014 start_image = image;
2018 for (int i = start_image; i <= end_image; i++) {
2019 struct wim_image_metadata *imd;
2021 imd = wim->image_metadata[i - 1];
2022 /* Build a new metadata resource only if image was modified from
2023 * the original (or was newly added). Otherwise just copy the
2025 if (imd->modified) {
2026 DEBUG("Image %u was modified; building and writing new "
2027 "metadata resource", i);
2028 ret = write_metadata_resource(wim, i,
2029 write_resource_flags);
2030 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2031 DEBUG("Image %u was not modified; re-using existing "
2032 "metadata resource.", i);
2033 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2036 DEBUG("Image %u was not modified; copying existing "
2037 "metadata resource.", i);
2038 ret = write_wim_resource(imd->metadata_lte,
2040 wim->out_compression_type,
2041 wim->out_chunk_size,
2042 write_resource_flags);
2048 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2053 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2056 DEBUG("Opening \"%"TS"\" for writing.", path);
2058 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2060 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2061 return WIMLIB_ERR_OPEN;
2063 filedes_init(&wim->out_fd, raw_fd);
2068 close_wim_writable(WIMStruct *wim, int write_flags)
2072 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2073 DEBUG("Closing WIM file.");
2074 if (filedes_valid(&wim->out_fd))
2075 if (filedes_close(&wim->out_fd))
2076 ret = WIMLIB_ERR_WRITE;
2078 filedes_invalidate(&wim->out_fd);
2083 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2085 const struct wim_lookup_table_entry *lte1, *lte2;
2087 lte1 = *(const struct wim_lookup_table_entry**)p1;
2088 lte2 = *(const struct wim_lookup_table_entry**)p2;
2090 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2091 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2092 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2093 return cmp_u64(lte1->out_res_offset_in_wim,
2094 lte2->out_res_offset_in_wim);
2099 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2102 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2103 lte2->out_reshdr.offset_in_wim);
2107 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2108 struct wim_reshdr *out_reshdr,
2109 struct list_head *lookup_table_list)
2113 /* Set output resource metadata for streams already present in WIM. */
2114 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2115 struct wim_lookup_table_entry *lte;
2116 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2118 if (lte->resource_location == RESOURCE_IN_WIM &&
2119 lte->rspec->wim == wim)
2121 stream_set_out_reshdr_for_reuse(lte);
2126 ret = sort_stream_list(lookup_table_list,
2127 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2128 cmp_streams_by_out_rspec);
2132 /* Add entries for metadata resources. */
2133 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2137 if (image == WIMLIB_ALL_IMAGES) {
2139 end_image = wim->hdr.image_count;
2141 start_image = image;
2145 /* Push metadata resource lookup table entries onto the front of
2146 * the list in reverse order, so that they're written in order.
2148 for (int i = end_image; i >= start_image; i--) {
2149 struct wim_lookup_table_entry *metadata_lte;
2151 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2152 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2153 metadata_lte->out_refcnt = 1;
2154 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2158 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2160 wim->hdr.part_number,
2162 write_flags_to_resource_flags(write_flags));
2168 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2169 * table, then overwrite the WIM header. By default, closes the WIM file
2170 * descriptor (@wim->out_fd) if successful.
2172 * write_flags is a bitwise OR of the following:
2174 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2175 * Include an integrity table.
2177 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2178 * fsync() the output file before closing it.
2180 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2181 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2182 * stream headers before the lookup table and XML data, and also
2183 * write the WIM header at the end instead of seeking to the
2184 * beginning. Can't be combined with
2185 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2187 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2188 * Don't write the lookup table.
2190 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2191 * When (if) writing the integrity table, re-use entries from the
2192 * existing integrity table, if possible.
2194 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2195 * After writing the XML data but before writing the integrity
2196 * table, write a temporary WIM header and flush the stream so that
2197 * the WIM is less likely to become corrupted upon abrupt program
2199 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2200 * Instead of overwriting the WIM header at the beginning of the
2201 * file, simply append it to the end of the file. (Used when
2203 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2204 * Do not close the file descriptor @wim->out_fd on either success
2206 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2207 * Use the existing <TOTALBYTES> stored in the in-memory XML
2208 * information, rather than setting it to the offset of the XML
2209 * data being written.
2212 finish_write(WIMStruct *wim, int image, int write_flags,
2213 wimlib_progress_func_t progress_func,
2214 struct list_head *lookup_table_list)
2218 int write_resource_flags;
2219 off_t old_lookup_table_end;
2220 off_t new_lookup_table_end;
2223 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2225 write_resource_flags = write_flags_to_resource_flags(write_flags);
2227 /* In the WIM header, there is room for the resource entry for a
2228 * metadata resource labeled as the "boot metadata". This entry should
2229 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2230 * it should be a copy of the resource entry for the image that is
2231 * marked as bootable. This is not well documented... */
2232 if (wim->hdr.boot_idx == 0) {
2233 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2235 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2236 &wim->image_metadata[
2237 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2240 /* Write lookup table. (Save old position first.) */
2241 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2242 wim->hdr.lookup_table_reshdr.size_in_wim;
2243 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2244 ret = write_wim_lookup_table(wim, image, write_flags,
2245 &wim->hdr.lookup_table_reshdr,
2251 /* Write XML data. */
2252 xml_totalbytes = wim->out_fd.offset;
2253 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2254 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2255 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2256 &wim->hdr.xml_data_reshdr,
2257 write_resource_flags);
2261 /* Write integrity table (optional). */
2262 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2263 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2264 struct wim_header checkpoint_hdr;
2265 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2266 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2267 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2268 ret = write_wim_header_at_offset(&checkpoint_hdr,
2274 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2275 old_lookup_table_end = 0;
2277 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2278 wim->hdr.lookup_table_reshdr.size_in_wim;
2280 ret = write_integrity_table(wim,
2281 new_lookup_table_end,
2282 old_lookup_table_end,
2287 /* No integrity table. */
2288 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2291 /* Now that all information in the WIM header has been determined, the
2292 * preliminary header written earlier can be overwritten, the header of
2293 * the existing WIM file can be overwritten, or the final header can be
2294 * written to the end of the pipable WIM. */
2295 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2297 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2298 hdr_offset = wim->out_fd.offset;
2299 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2300 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2304 /* Possibly sync file data to disk before closing. On POSIX systems, it
2305 * is necessary to do this before using rename() to overwrite an
2306 * existing file with a new file. Otherwise, data loss would occur if
2307 * the system is abruptly terminated when the metadata for the rename
2308 * operation has been written to disk, but the new file data has not.
2310 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2311 DEBUG("Syncing WIM file.");
2312 if (fsync(wim->out_fd.fd)) {
2313 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2314 return WIMLIB_ERR_WRITE;
2318 if (close_wim_writable(wim, write_flags)) {
2319 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2320 return WIMLIB_ERR_WRITE;
2326 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2328 lock_wim(WIMStruct *wim, int fd)
2331 if (fd != -1 && !wim->wim_locked) {
2332 ret = flock(fd, LOCK_EX | LOCK_NB);
2334 if (errno == EWOULDBLOCK) {
2335 ERROR("`%"TS"' is already being modified or has been "
2336 "mounted read-write\n"
2337 " by another process!", wim->filename);
2338 ret = WIMLIB_ERR_ALREADY_LOCKED;
2340 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2345 wim->wim_locked = 1;
2353 * write_pipable_wim():
2355 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2356 * capable of being applied from a pipe).
2358 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2359 * images can be applied from them sequentially when the file data is sent over
2360 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2361 * The modifications made to the WIM format for pipable WIMs are:
2363 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2364 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2365 * stops other software from trying to read the file as a normal WIM.
2367 * - The header at the beginning of the file does not contain all the normal
2368 * information; in particular it will have all 0's for the lookup table and
2369 * XML data resource entries. This is because this information cannot be
2370 * determined until the lookup table and XML data have been written.
2371 * Consequently, wimlib will write the full header at the very end of the
2372 * file. The header at the end, however, is only used when reading the WIM
2373 * from a seekable file (not a pipe).
2375 * - An extra copy of the XML data is placed directly after the header. This
2376 * allows image names and sizes to be determined at an appropriate time when
2377 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2378 * WIM is read from a seekable file (not a pipe).
2380 * - The format of resources, or streams, has been modified to allow them to be
2381 * used before the "lookup table" has been read. Each stream is prefixed with
2382 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2383 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2384 * uncompressed stream size, and flags that indicate whether the stream is
2385 * compressed. The data of uncompressed streams then follows literally, while
2386 * the data of compressed streams follows in a modified format. Compressed
2387 * streams do not begin with a chunk table, since the chunk table cannot be
2388 * written until all chunks have been compressed. Instead, each compressed
2389 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2390 * Furthermore, the chunk table is written at the end of the resource instead
2391 * of the start. Note: chunk offsets are given in the chunk table as if the
2392 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2393 * used if the WIM is being read from a seekable file (not a pipe).
2395 * - Metadata resources always come before other file resources (streams).
2396 * (This does not by itself constitute an incompatibility with normal WIMs,
2397 * since this is valid in normal WIMs.)
2399 * - At least up to the end of the file resources, all components must be packed
2400 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2401 * not by itself consititute an incompatibility with normal WIMs, since this
2402 * is valid in normal WIMs.)
2404 * Note: the lookup table, XML data, and header at the end are not used when
2405 * applying from a pipe. They exist to support functionality such as image
2406 * application and export when the WIM is *not* read from a pipe.
2408 * Layout of pipable WIM:
2410 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2411 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2412 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2414 * Layout of normal WIM:
2416 * +--------+-----------------------------+-------------------------+
2417 * | Header | File and metadata resources | Lookup table | XML data |
2418 * +--------+-----------------------------+-------------------------+
2420 * An optional integrity table can follow the final XML data in both normal and
2421 * pipable WIMs. However, due to implementation details, wimlib currently can
2422 * only include an integrity table in a pipable WIM when writing it to a
2423 * seekable file (not a pipe).
2425 * Do note that since pipable WIMs are not supported by Microsoft's software,
2426 * wimlib does not create them unless explicitly requested (with
2427 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2428 * characters to identify the file.
2431 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2432 unsigned num_threads, wimlib_progress_func_t progress_func,
2433 struct list_head *stream_list_override,
2434 struct list_head *lookup_table_list_ret)
2437 struct wim_reshdr xml_reshdr;
2439 WARNING("Creating a pipable WIM, which will "
2441 " with Microsoft's software (wimgapi/imagex/Dism).");
2443 /* At this point, the header at the beginning of the file has already
2446 /* For efficiency, when wimlib adds an image to the WIM with
2447 * wimlib_add_image(), the SHA1 message digests of files is not
2448 * calculated; instead, they are calculated while the files are being
2449 * written. However, this does not work when writing a pipable WIM,
2450 * since when writing a stream to a pipable WIM, its SHA1 message digest
2451 * needs to be known before the stream data is written. Therefore,
2452 * before getting much farther, we need to pre-calculate the SHA1
2453 * message digests of all streams that will be written. */
2454 ret = wim_checksum_unhashed_streams(wim);
2458 /* Write extra copy of the XML data. */
2459 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2461 WRITE_RESOURCE_FLAG_PIPABLE);
2465 /* Write metadata resources for the image(s) being included in the
2467 ret = write_wim_metadata_resources(wim, image, write_flags,
2472 /* Write streams needed for the image(s) being included in the output
2473 * WIM, or streams needed for the split WIM part. */
2474 return write_wim_streams(wim, image, write_flags, num_threads,
2475 progress_func, stream_list_override,
2476 lookup_table_list_ret);
2478 /* The lookup table, XML data, and header at end are handled by
2479 * finish_write(). */
2482 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2485 write_wim_part(WIMStruct *wim,
2486 const void *path_or_fd,
2489 unsigned num_threads,
2490 wimlib_progress_func_t progress_func,
2491 unsigned part_number,
2492 unsigned total_parts,
2493 struct list_head *stream_list_override,
2497 struct wim_header hdr_save;
2498 struct list_head lookup_table_list;
2500 if (total_parts == 1)
2501 DEBUG("Writing standalone WIM.");
2503 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2504 if (image == WIMLIB_ALL_IMAGES)
2505 DEBUG("Including all images.");
2507 DEBUG("Including image %d only.", image);
2508 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2509 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2511 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2512 DEBUG("Write flags: 0x%08x", write_flags);
2514 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2515 DEBUG("\tCHECK_INTEGRITY");
2517 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2520 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2521 DEBUG("\tRECOMPRESS");
2523 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2526 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2529 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2530 DEBUG("\tIGNORE_READONLY_FLAG");
2532 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2535 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2536 DEBUG("\tNOT_PIPABLE");
2538 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2539 DEBUG("\tPACK_STREAMS");
2541 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2542 DEBUG("\tFILE_DESCRIPTOR");
2544 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2545 DEBUG("\tNO_METADATA");
2547 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2548 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2550 if (num_threads == 0)
2551 DEBUG("Number of threads: autodetect");
2553 DEBUG("Number of threads: %u", num_threads);
2554 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2555 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2556 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2557 "specified" : "generate new"));
2559 /* Internally, this is always called with a valid part number and total
2561 wimlib_assert(total_parts >= 1);
2562 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2564 /* A valid image (or all images) must be specified. */
2565 if (image != WIMLIB_ALL_IMAGES &&
2566 (image < 1 || image > wim->hdr.image_count))
2567 return WIMLIB_ERR_INVALID_IMAGE;
2569 /* If we need to write metadata resources, make sure the ::WIMStruct has
2570 * the needed information attached (e.g. is not a resource-only WIM,
2571 * such as a non-first part of a split WIM). */
2572 if (!wim_has_metadata(wim) &&
2573 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2574 return WIMLIB_ERR_METADATA_NOT_FOUND;
2576 /* Check for contradictory flags. */
2577 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2578 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2579 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2580 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2581 return WIMLIB_ERR_INVALID_PARAM;
2583 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2584 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2585 == (WIMLIB_WRITE_FLAG_PIPABLE |
2586 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2587 return WIMLIB_ERR_INVALID_PARAM;
2589 /* Save previous header, then start initializing the new one. */
2590 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2592 /* Set default integrity, pipable, and packed stream flags. */
2593 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2594 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2595 if (wim_is_pipable(wim)) {
2596 DEBUG("WIM is pipable; default to PIPABLE.");
2597 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2600 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2601 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2602 if (wim_has_integrity_table(wim)) {
2603 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2604 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2607 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2608 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2609 == (WIMLIB_WRITE_FLAG_PIPABLE |
2610 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2612 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2613 return WIMLIB_ERR_INVALID_PARAM;
2616 /* Set appropriate magic number. */
2617 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2618 wim->hdr.magic = PWM_MAGIC;
2620 wim->hdr.magic = WIM_MAGIC;
2622 /* Set appropriate version number. */
2623 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2624 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2625 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2627 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2629 /* Clear header flags that will be set automatically. */
2630 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2631 WIM_HDR_FLAG_RESOURCE_ONLY |
2632 WIM_HDR_FLAG_SPANNED |
2633 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2635 /* Set SPANNED header flag if writing part of a split WIM. */
2636 if (total_parts != 1)
2637 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2639 /* Set part number and total parts of split WIM. This will be 1 and 1
2640 * if the WIM is standalone. */
2641 wim->hdr.part_number = part_number;
2642 wim->hdr.total_parts = total_parts;
2644 /* Set compression type if different. */
2645 if (wim->compression_type != wim->out_compression_type) {
2646 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2647 wimlib_assert(ret == 0);
2650 /* Set chunk size if different. */
2651 wim->hdr.chunk_size = wim->out_chunk_size;
2653 /* Use GUID if specified; otherwise generate a new one. */
2655 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2656 else if (!wim->guid_set_explicitly)
2657 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2659 /* Clear references to resources that have not been written yet. */
2660 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2661 zero_reshdr(&wim->hdr.xml_data_reshdr);
2662 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2663 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2665 /* Set image count and boot index correctly for single image writes. */
2666 if (image != WIMLIB_ALL_IMAGES) {
2667 wim->hdr.image_count = 1;
2668 if (wim->hdr.boot_idx == image)
2669 wim->hdr.boot_idx = 1;
2671 wim->hdr.boot_idx = 0;
2674 /* Split WIMs can't be bootable. */
2675 if (total_parts != 1)
2676 wim->hdr.boot_idx = 0;
2678 /* Initialize output file descriptor. */
2679 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2680 /* File descriptor was explicitly provided. Return error if
2681 * file descriptor is not seekable, unless writing a pipable WIM
2683 wim->out_fd.fd = *(const int*)path_or_fd;
2684 wim->out_fd.offset = 0;
2685 if (!filedes_is_seekable(&wim->out_fd)) {
2686 ret = WIMLIB_ERR_INVALID_PARAM;
2687 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2688 goto out_restore_hdr;
2689 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2690 ERROR("Can't include integrity check when "
2691 "writing pipable WIM to pipe!");
2692 goto out_restore_hdr;
2697 /* Filename of WIM to write was provided; open file descriptor
2699 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2700 O_TRUNC | O_CREAT | O_RDWR);
2702 goto out_restore_hdr;
2705 /* Write initial header. This is merely a "dummy" header since it
2706 * doesn't have all the information yet, so it will be overwritten later
2707 * (unless writing a pipable WIM). */
2708 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2709 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2710 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2711 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2713 goto out_restore_hdr;
2715 /* Write metadata resources and streams. */
2716 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2717 /* Default case: create a normal (non-pipable) WIM. */
2718 ret = write_wim_streams(wim, image, write_flags, num_threads,
2719 progress_func, stream_list_override,
2720 &lookup_table_list);
2722 goto out_restore_hdr;
2724 ret = write_wim_metadata_resources(wim, image, write_flags,
2727 goto out_restore_hdr;
2729 /* Non-default case: create pipable WIM. */
2730 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2731 progress_func, stream_list_override,
2732 &lookup_table_list);
2734 goto out_restore_hdr;
2735 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2739 /* Write lookup table, XML data, and (optional) integrity table. */
2740 ret = finish_write(wim, image, write_flags, progress_func,
2741 &lookup_table_list);
2743 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2744 (void)close_wim_writable(wim, write_flags);
2745 DEBUG("ret=%d", ret);
2749 /* Write a standalone WIM to a file or file descriptor. */
2751 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2752 int image, int write_flags, unsigned num_threads,
2753 wimlib_progress_func_t progress_func)
2755 return write_wim_part(wim, path_or_fd, image, write_flags,
2756 num_threads, progress_func, 1, 1, NULL, NULL);
2759 /* API function documented in wimlib.h */
2761 wimlib_write(WIMStruct *wim, const tchar *path,
2762 int image, int write_flags, unsigned num_threads,
2763 wimlib_progress_func_t progress_func)
2766 return WIMLIB_ERR_INVALID_PARAM;
2768 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2770 return write_standalone_wim(wim, path, image, write_flags,
2771 num_threads, progress_func);
2774 /* API function documented in wimlib.h */
2776 wimlib_write_to_fd(WIMStruct *wim, int fd,
2777 int image, int write_flags, unsigned num_threads,
2778 wimlib_progress_func_t progress_func)
2781 return WIMLIB_ERR_INVALID_PARAM;
2783 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2784 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2786 return write_standalone_wim(wim, &fd, image, write_flags,
2787 num_threads, progress_func);
2791 any_images_modified(WIMStruct *wim)
2793 for (int i = 0; i < wim->hdr.image_count; i++)
2794 if (wim->image_metadata[i]->modified)
2800 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2802 const WIMStruct *wim = _wim;
2803 off_t end_offset = *(const off_t*)wim->private;
2805 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2806 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2807 return WIMLIB_ERR_RESOURCE_ORDER;
2811 /* Make sure no file or metadata resources are located after the XML data (or
2812 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2813 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2815 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2820 wim->private = &end_offset;
2821 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2825 for (i = 0; i < wim->hdr.image_count; i++) {
2826 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2834 * Overwrite a WIM, possibly appending streams to it.
2836 * A WIM looks like (or is supposed to look like) the following:
2838 * Header (212 bytes)
2839 * Streams and metadata resources (variable size)
2840 * Lookup table (variable size)
2841 * XML data (variable size)
2842 * Integrity table (optional) (variable size)
2844 * If we are not adding any streams or metadata resources, the lookup table is
2845 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2846 * header. This operation is potentially unsafe if the program is abruptly
2847 * terminated while the XML data or integrity table are being overwritten, but
2848 * before the new header has been written. To partially alleviate this problem,
2849 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2850 * finish_write() to cause a temporary WIM header to be written after the XML
2851 * data has been written. This may prevent the WIM from becoming corrupted if
2852 * the program is terminated while the integrity table is being calculated (but
2853 * no guarantees, due to write re-ordering...).
2855 * If we are adding new streams or images (metadata resources), the lookup table
2856 * needs to be changed, and those streams need to be written. In this case, we
2857 * try to perform a safe update of the WIM file by writing the streams *after*
2858 * the end of the previous WIM, then writing the new lookup table, XML data, and
2859 * (optionally) integrity table following the new streams. This will produce a
2860 * layout like the following:
2862 * Header (212 bytes)
2863 * (OLD) Streams and metadata resources (variable size)
2864 * (OLD) Lookup table (variable size)
2865 * (OLD) XML data (variable size)
2866 * (OLD) Integrity table (optional) (variable size)
2867 * (NEW) Streams and metadata resources (variable size)
2868 * (NEW) Lookup table (variable size)
2869 * (NEW) XML data (variable size)
2870 * (NEW) Integrity table (optional) (variable size)
2872 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2873 * the header is overwritten to point to the new lookup table, XML data, and
2874 * integrity table, to produce the following layout:
2876 * Header (212 bytes)
2877 * Streams and metadata resources (variable size)
2878 * Nothing (variable size)
2879 * More Streams and metadata resources (variable size)
2880 * Lookup table (variable size)
2881 * XML data (variable size)
2882 * Integrity table (optional) (variable size)
2884 * This method allows an image to be appended to a large WIM very quickly, and
2885 * is is crash-safe except in the case of write re-ordering, but the
2886 * disadvantage is that a small hole is left in the WIM where the old lookup
2887 * table, xml data, and integrity table were. (These usually only take up a
2888 * small amount of space compared to the streams, however.)
2891 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2892 unsigned num_threads,
2893 wimlib_progress_func_t progress_func)
2897 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2898 struct wim_header hdr_save;
2899 struct list_head stream_list;
2900 struct list_head lookup_table_list;
2901 struct filter_context filter_ctx;
2903 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2905 /* Save original header so it can be restored in case of error */
2906 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2908 /* Set default integrity flag. */
2909 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2910 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2911 if (wim_has_integrity_table(wim))
2912 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2914 /* Set WIM version if adding packed streams. */
2915 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2916 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2918 /* Set additional flags for overwrite. */
2919 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2920 WIMLIB_WRITE_FLAG_STREAMS_OK;
2922 /* Make sure that the integrity table (if present) is after the XML
2923 * data, and that there are no stream resources, metadata resources, or
2924 * lookup tables after the XML data. Otherwise, these data would be
2926 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2927 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2928 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2929 wim->hdr.lookup_table_reshdr.size_in_wim;
2930 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2931 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2932 WARNING("Didn't expect the integrity table to be before the XML data");
2933 ret = WIMLIB_ERR_RESOURCE_ORDER;
2934 goto out_restore_memory_hdr;
2937 if (old_lookup_table_end > old_xml_begin) {
2938 WARNING("Didn't expect the lookup table to be after the XML data");
2939 ret = WIMLIB_ERR_RESOURCE_ORDER;
2940 goto out_restore_memory_hdr;
2943 /* Set @old_wim_end, which indicates the point beyond which we don't
2944 * allow any file and metadata resources to appear without returning
2945 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2946 * overwrite these resources). */
2947 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2948 /* If no images have been modified and no images have been
2949 * deleted, a new lookup table does not need to be written. We
2950 * shall write the new XML data and optional integrity table
2951 * immediately after the lookup table. Note that this may
2952 * overwrite an existing integrity table. */
2953 DEBUG("Skipping writing lookup table "
2954 "(no images modified or deleted)");
2955 old_wim_end = old_lookup_table_end;
2956 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2957 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2958 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2959 /* Old WIM has an integrity table; begin writing new streams
2961 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2962 wim->hdr.integrity_table_reshdr.size_in_wim;
2964 /* No existing integrity table; begin writing new streams after
2965 * the old XML data. */
2966 old_wim_end = old_xml_end;
2969 ret = check_resource_offsets(wim, old_wim_end);
2971 goto out_restore_memory_hdr;
2973 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2974 &stream_list, &lookup_table_list,
2977 goto out_restore_memory_hdr;
2979 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2981 goto out_restore_memory_hdr;
2983 ret = lock_wim(wim, wim->out_fd.fd);
2987 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2988 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2989 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2991 ERROR_WITH_ERRNO("Error updating WIM header flags");
2992 goto out_unlock_wim;
2995 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2996 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2997 ret = WIMLIB_ERR_WRITE;
2998 goto out_restore_physical_hdr;
3001 ret = wim_write_stream_list(wim,
3010 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3011 write_flags, progress_func);
3015 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3016 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3017 progress_func, &lookup_table_list);
3021 wim->wim_locked = 0;
3025 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3026 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3027 wim->filename, old_wim_end);
3028 /* Return value of ftruncate() is ignored because this is
3029 * already an error path. */
3030 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3032 out_restore_physical_hdr:
3033 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3035 wim->wim_locked = 0;
3037 (void)close_wim_writable(wim, write_flags);
3038 out_restore_memory_hdr:
3039 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3044 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3045 unsigned num_threads,
3046 wimlib_progress_func_t progress_func)
3048 size_t wim_name_len;
3051 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3053 /* Write the WIM to a temporary file in the same directory as the
3055 wim_name_len = tstrlen(wim->filename);
3056 tchar tmpfile[wim_name_len + 10];
3057 tmemcpy(tmpfile, wim->filename, wim_name_len);
3058 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3059 tmpfile[wim_name_len + 9] = T('\0');
3061 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3062 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3063 num_threads, progress_func);
3071 /* Rename the new WIM file to the original WIM file. Note: on Windows
3072 * this actually calls win32_rename_replacement(), not _wrename(), so
3073 * that removing the existing destination file can be handled. */
3074 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3075 ret = trename(tmpfile, wim->filename);
3077 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3078 tmpfile, wim->filename);
3085 return WIMLIB_ERR_RENAME;
3088 if (progress_func) {
3089 union wimlib_progress_info progress;
3090 progress.rename.from = tmpfile;
3091 progress.rename.to = wim->filename;
3092 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3097 /* Determine if the specified WIM file may be updated by appending in-place
3098 * rather than writing and replacing it with an entirely new file. */
3100 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3102 /* REBUILD flag forces full rebuild. */
3103 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3106 /* Deletions cause full rebuild by default. */
3107 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3110 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3111 * turned into a pipable WIM in-place. */
3112 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3115 /* wimlib allows multiple packs in a single WIM, but they don't seem to
3116 * be compatible with WIMGAPI, so force all streams to be repacked if
3117 * the WIM already may have contained a pack and PACK_STREAMS was
3119 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3120 wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3123 /* The default compression type and compression chunk size selected for
3124 * the output WIM must be the same as those currently used for the WIM.
3126 if (wim->compression_type != wim->out_compression_type)
3128 if (wim->chunk_size != wim->out_chunk_size)
3134 /* API function documented in wimlib.h */
3136 wimlib_overwrite(WIMStruct *wim, int write_flags,
3137 unsigned num_threads,
3138 wimlib_progress_func_t progress_func)
3143 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3145 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3146 return WIMLIB_ERR_INVALID_PARAM;
3149 return WIMLIB_ERR_NO_FILENAME;
3151 orig_hdr_flags = wim->hdr.flags;
3152 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3153 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3154 ret = can_modify_wim(wim);
3155 wim->hdr.flags = orig_hdr_flags;
3159 if (can_overwrite_wim_inplace(wim, write_flags)) {
3160 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3162 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3164 WARNING("Falling back to re-building entire WIM");
3166 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,