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/compress_chunks.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"
62 write_flags_to_resource_flags(int write_flags)
64 int write_resource_flags = 0;
66 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
67 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
68 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
69 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
70 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
71 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS;
72 return write_resource_flags;
75 struct filter_context {
80 /* Determine specified stream should be filtered out from the write.
84 * < 0 : The stream should be hard-filtered; that is, not included in the
86 * 0 : The stream should not be filtered out.
87 * > 0 : The stream should be soft-filtered; that is, it already exists in the
88 * WIM file and may not need to be written again.
91 stream_filtered(const struct wim_lookup_table_entry *lte,
92 const struct filter_context *ctx)
94 int write_flags = ctx->write_flags;
95 WIMStruct *wim = ctx->wim;
100 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
101 lte->resource_location == RESOURCE_IN_WIM &&
102 lte->rspec->wim == wim)
105 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
106 lte->resource_location == RESOURCE_IN_WIM &&
107 lte->rspec->wim != wim)
114 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
115 struct filter_context *ctx)
117 return stream_filtered(lte, ctx) < 0;
121 may_soft_filter_streams(const struct filter_context *ctx)
125 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
129 may_hard_filter_streams(const struct filter_context *ctx)
133 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
137 may_filter_streams(const struct filter_context *ctx)
139 return (may_soft_filter_streams(ctx) ||
140 may_hard_filter_streams(ctx));
144 /* Return true if the specified resource is compressed and the compressed data
145 * can be reused with the specified output parameters. */
147 can_raw_copy(const struct wim_lookup_table_entry *lte,
148 int write_resource_flags, int out_ctype, u32 out_chunk_size)
150 const struct wim_resource_spec *rspec;
152 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
155 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
158 if (lte->resource_location != RESOURCE_IN_WIM)
163 if (rspec->is_pipable != !!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
167 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
168 /* Normal compressed resource: Must use same compression type
170 return (rspec->wim->compression_type == out_ctype &&
171 rspec->wim->chunk_size == out_chunk_size);
174 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
175 (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
177 /* Packed resource: Such resources may contain multiple streams,
178 * and in general only a subset of them need to be written. As
179 * a heuristic, re-use the raw data if at least half the
180 * uncompressed size is being written. */
182 /* Note: packed resources contain a header that specifies the
183 * compression type and chunk size; therefore we don't need to
184 * check if they are compatible with @out_ctype and
185 * @out_chunk_size. */
187 struct wim_lookup_table_entry *res_stream;
190 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
191 if (res_stream->will_be_in_output_wim)
192 write_size += res_stream->size;
194 return (write_size > rspec->uncompressed_size / 2);
200 filter_resource_flags(u8 flags)
202 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
203 WIM_RESHDR_FLAG_COMPRESSED |
204 WIM_RESHDR_FLAG_SPANNED |
205 WIM_RESHDR_FLAG_FREE));
209 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
211 const struct wim_resource_spec *rspec;
213 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
216 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
218 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
220 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
221 lte->out_reshdr.uncompressed_size = 0;
222 lte->out_reshdr.size_in_wim = lte->size;
224 lte->out_res_offset_in_wim = rspec->offset_in_wim;
225 lte->out_res_size_in_wim = rspec->size_in_wim;
226 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
228 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
230 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
231 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
232 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
234 lte->out_reshdr.flags = lte->flags;
238 /* Write the header for a stream in a pipable WIM. */
240 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
241 struct filedes *out_fd,
242 int additional_reshdr_flags)
244 struct pwm_stream_hdr stream_hdr;
248 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
249 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
250 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
251 zero_out_hash(stream_hdr.hash);
253 wimlib_assert(!lte->unhashed);
254 copy_hash(stream_hdr.hash, lte->hash);
257 reshdr_flags = filter_resource_flags(lte->flags);
258 reshdr_flags |= additional_reshdr_flags;
259 stream_hdr.flags = cpu_to_le32(reshdr_flags);
260 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
262 ERROR_WITH_ERRNO("Write error");
268 seek_and_truncate(struct filedes *out_fd, off_t offset)
270 if (filedes_seek(out_fd, offset) == -1 ||
271 ftruncate(out_fd->fd, offset))
273 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
274 return WIMLIB_ERR_WRITE;
280 struct write_streams_progress_data {
281 wimlib_progress_func_t progress_func;
282 union wimlib_progress_info progress;
283 uint64_t next_progress;
284 WIMStruct *prev_wim_part;
288 do_write_streams_progress(struct write_streams_progress_data *progress_data,
291 struct wim_lookup_table_entry *cur_stream)
293 union wimlib_progress_info *progress = &progress_data->progress;
297 progress->write_streams.total_bytes -= size;
298 if (progress_data->next_progress != ~(uint64_t)0 &&
299 progress_data->next_progress > progress->write_streams.total_bytes)
301 progress_data->next_progress = progress->write_streams.total_bytes;
304 progress->write_streams.completed_bytes += size;
306 new_wim_part = false;
307 if (cur_stream->resource_location == RESOURCE_IN_WIM &&
308 cur_stream->rspec->wim != progress_data->prev_wim_part)
310 if (progress_data->prev_wim_part) {
312 progress->write_streams.completed_parts++;
314 progress_data->prev_wim_part = cur_stream->rspec->wim;
316 progress->write_streams.completed_streams++;
317 if (progress_data->progress_func
318 && (progress->write_streams.completed_bytes >= progress_data->next_progress
321 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
323 if (progress_data->next_progress == progress->write_streams.total_bytes) {
324 progress_data->next_progress = ~(uint64_t)0;
326 progress_data->next_progress =
327 min(progress->write_streams.total_bytes,
328 progress->write_streams.completed_bytes +
329 progress->write_streams.total_bytes / 100);
334 struct write_streams_ctx {
335 /* File descriptor the streams are being written to. */
336 struct filedes *out_fd;
338 /* Lookup table for the WIMStruct on whose behalf the streams are being
340 struct wim_lookup_table *lookup_table;
342 /* Compression format to use. */
345 /* Maximum uncompressed chunk size in compressed resources to use. */
348 /* Flags that affect how the streams will be written. */
349 int write_resource_flags;
351 /* Data used for issuing WRITE_STREAMS progress. */
352 struct write_streams_progress_data progress_data;
354 struct filter_context *filter_ctx;
356 /* Upper bound on the total number of bytes that need to be compressed.
358 u64 num_bytes_to_compress;
360 /* Pointer to the chunk_compressor implementation being used for
361 * compressing chunks of data, or NULL if chunks are being written
363 struct chunk_compressor *compressor;
365 /* Buffer for dividing the read data into chunks of size
366 * @out_chunk_size. */
369 /* Number of bytes in @chunk_buf that are currently filled. */
370 size_t chunk_buf_filled;
372 /* List of streams that currently have chunks being compressed. */
373 struct list_head pending_streams;
375 /* Set to true if the stream currently being read was a duplicate, and
376 * therefore the corresponding stream entry needs to be freed once the
377 * read finishes. (In this case we add the duplicate entry to
378 * pending_streams rather than the entry being read.) */
379 bool stream_was_duplicate;
381 /* Current uncompressed offset in the resource being read. */
382 u64 cur_read_res_offset;
384 /* Uncompressed size of the resource currently being read. */
385 u64 cur_read_res_size;
387 /* Current uncompressed offset in the resource being written. */
388 u64 cur_write_res_offset;
390 /* Uncompressed size of resource currently being written. */
391 u64 cur_write_res_size;
393 /* Array that is filled in with compressed chunk sizes as a resource is
397 /* Index of next entry in @chunk_csizes to fill in. */
400 /* Number of entries in @chunk_csizes currently allocated. */
401 size_t num_alloc_chunks;
403 /* Offset in the output file of the start of the chunks of the resource
404 * currently being written. */
405 u64 chunks_start_offset;
409 get_chunk_entry_size(u64 res_size, int write_resource_flags)
411 if (res_size <= UINT32_MAX ||
412 (write_resource_flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
418 /* Reserve space for the chunk table and prepare to accumulate the chunk table
421 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
423 u64 expected_num_chunks;
424 u64 expected_num_chunk_entries;
428 /* Calculate the number of chunks and chunk entries that should be
429 * needed for the resource. These normally will be the final values,
430 * but in PACKED_STREAMS mode some of the streams we're planning to
431 * write into the resource may be duplicates, and therefore discarded,
432 * potentially decreasing the number of chunk entries needed. */
433 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
434 expected_num_chunk_entries = expected_num_chunks;
435 if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
436 expected_num_chunk_entries--;
438 /* Make sure the chunk_csizes array is long enough to store the
439 * compressed size of each chunk. */
440 if (expected_num_chunks > ctx->num_alloc_chunks) {
441 u64 new_length = expected_num_chunks + 50;
443 if ((size_t)new_length != new_length) {
444 ERROR("Resource size too large (%"PRIu64" bytes!",
446 return WIMLIB_ERR_NOMEM;
449 FREE(ctx->chunk_csizes);
450 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
451 if (ctx->chunk_csizes == NULL) {
452 ctx->num_alloc_chunks = 0;
453 return WIMLIB_ERR_NOMEM;
455 ctx->num_alloc_chunks = new_length;
458 ctx->chunk_index = 0;
460 if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
461 /* Reserve space for the chunk table in the output file. In the
462 * case of packed resources this reserves the upper bound for
463 * the needed space, not necessarily the exact space which will
464 * prove to be needed. At this point, we just use @chunk_csizes
465 * for a buffer of 0's because the actual compressed chunk sizes
467 reserve_size = expected_num_chunk_entries *
468 get_chunk_entry_size(res_expected_size,
469 ctx->write_resource_flags);
470 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS)
471 reserve_size += sizeof(struct alt_chunk_table_header_disk);
472 memset(ctx->chunk_csizes, 0, reserve_size);
473 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
481 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
485 wimlib_assert(res_expected_size != 0);
487 if (ctx->compressor != NULL) {
488 ret = begin_chunk_table(ctx, res_expected_size);
493 /* Output file descriptor is now positioned at the offset at which to
494 * write the first chunk of the resource. */
495 ctx->chunks_start_offset = ctx->out_fd->offset;
496 ctx->cur_write_res_offset = 0;
497 ctx->cur_write_res_size = res_expected_size;
502 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
503 u64 *res_start_offset_ret, u64 *res_store_size_ret)
505 size_t actual_num_chunks;
506 size_t actual_num_chunk_entries;
507 size_t chunk_entry_size;
510 actual_num_chunks = ctx->chunk_index;
511 actual_num_chunk_entries = actual_num_chunks;
512 if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
513 actual_num_chunk_entries--;
515 chunk_entry_size = get_chunk_entry_size(res_actual_size,
516 ctx->write_resource_flags);
518 typedef le64 __attribute__((may_alias)) aliased_le64_t;
519 typedef le32 __attribute__((may_alias)) aliased_le32_t;
521 if (chunk_entry_size == 4) {
522 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
524 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
525 for (size_t i = 0; i < actual_num_chunk_entries; i++)
526 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
528 u32 offset = ctx->chunk_csizes[0];
529 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
530 u32 next_size = ctx->chunk_csizes[i + 1];
531 entries[i] = cpu_to_le32(offset);
536 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
538 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
539 for (size_t i = 0; i < actual_num_chunk_entries; i++)
540 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
542 u64 offset = ctx->chunk_csizes[0];
543 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
544 u64 next_size = ctx->chunk_csizes[i + 1];
545 entries[i] = cpu_to_le64(offset);
551 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
552 u64 res_start_offset;
555 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
556 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
559 res_end_offset = ctx->out_fd->offset;
560 res_start_offset = ctx->chunks_start_offset;
562 res_end_offset = ctx->out_fd->offset;
564 u64 chunk_table_offset;
566 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
568 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
569 struct alt_chunk_table_header_disk hdr;
571 hdr.res_usize = cpu_to_le64(res_actual_size);
572 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
573 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
575 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
576 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
577 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
579 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
580 chunk_table_offset - sizeof(hdr));
583 res_start_offset = chunk_table_offset - sizeof(hdr);
585 res_start_offset = chunk_table_offset;
588 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
589 chunk_table_size, chunk_table_offset);
594 *res_start_offset_ret = res_start_offset;
595 *res_store_size_ret = res_end_offset - res_start_offset;
600 ERROR_WITH_ERRNO("Write error");
604 /* Finish writing a WIM resource by writing or updating the chunk table (if not
605 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
607 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
611 u64 res_uncompressed_size;
612 u64 res_offset_in_wim;
614 wimlib_assert(ctx->cur_write_res_size == ctx->cur_write_res_offset);
615 res_uncompressed_size = ctx->cur_write_res_size;
617 if (ctx->compressor) {
618 ret = end_chunk_table(ctx, res_uncompressed_size,
619 &res_offset_in_wim, &res_size_in_wim);
623 res_offset_in_wim = ctx->chunks_start_offset;
624 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
626 out_reshdr->uncompressed_size = res_uncompressed_size;
627 out_reshdr->size_in_wim = res_size_in_wim;
628 out_reshdr->offset_in_wim = res_offset_in_wim;
629 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
630 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
634 /* Begin processing a stream for writing. */
636 write_stream_begin_read(struct wim_lookup_table_entry *lte,
637 bool is_partial_res, void *_ctx)
639 struct write_streams_ctx *ctx = _ctx;
642 wimlib_assert(lte->size > 0);
644 ctx->cur_read_res_offset = 0;
645 ctx->cur_read_res_size = lte->size;
647 /* As an optimization, we allow some streams to be "unhashed", meaning
648 * their SHA1 message digests are unknown. This is the case with
649 * streams that are added by scanning a directry tree with
650 * wimlib_add_image(), for example. Since WIM uses single-instance
651 * streams, we don't know whether such each such stream really need to
652 * written until it is actually checksummed, unless it has a unique
653 * size. In such cases we read and checksum the stream in this
654 * function, thereby advancing ahead of read_stream_list(), which will
655 * still provide the data again to write_stream_process_chunk(). This
656 * is okay because an unhashed stream cannot be in a WIM resource, which
657 * might be costly to decompress. */
658 ctx->stream_was_duplicate = false;
659 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
661 wimlib_assert(!is_partial_res);
663 struct wim_lookup_table_entry *lte_new;
665 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
668 if (lte_new != lte) {
669 /* Duplicate stream detected. */
671 if (lte_new->will_be_in_output_wim ||
672 stream_filtered(lte_new, ctx->filter_ctx))
674 /* The duplicate stream is already being
675 * included in the output WIM, or it would be
676 * filtered out if it had been. Skip writing
677 * this stream (and reading it again) entirely,
678 * passing its output reference count to the
679 * duplicate stream in the former case. */
680 DEBUG("Discarding duplicate stream of "
681 "length %"PRIu64, lte->size);
682 do_write_streams_progress(&ctx->progress_data,
683 lte->size, true, lte);
684 list_del(<e->write_streams_list);
685 list_del(<e->lookup_table_list);
686 if (lte_new->will_be_in_output_wim)
687 lte_new->out_refcnt += lte->out_refcnt;
688 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS)
689 ctx->cur_write_res_size -= lte->size;
690 free_lookup_table_entry(lte);
691 return BEGIN_STREAM_STATUS_SKIP_STREAM;
693 /* The duplicate stream can validly be written,
694 * but was not marked as such. Discard the
695 * current stream entry and use the duplicate,
696 * but actually freeing the current entry must
697 * wait until read_stream_list() has finished
698 * reading its data. */
699 DEBUG("Stream duplicate, but not already "
700 "selected for writing.");
701 list_replace(<e->write_streams_list,
702 <e_new->write_streams_list);
703 list_replace(<e->lookup_table_list,
704 <e_new->lookup_table_list);
705 lte_new->out_refcnt = lte->out_refcnt;
706 lte_new->will_be_in_output_wim = 1;
707 ctx->stream_was_duplicate = true;
712 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
716 /* Write the next chunk of (typically compressed) data to the output WIM,
717 * handling the writing of the chunk table. */
719 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
720 size_t csize, size_t usize)
724 struct wim_lookup_table_entry *lte;
726 lte = list_entry(ctx->pending_streams.next,
727 struct wim_lookup_table_entry, write_streams_list);
729 if (ctx->cur_write_res_offset == 0 &&
730 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
732 /* Starting to write a new stream in non-packed mode. */
734 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
735 int additional_reshdr_flags = 0;
736 if (ctx->compressor != NULL)
737 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
739 DEBUG("Writing pipable WIM stream header "
740 "(offset=%"PRIu64")", ctx->out_fd->offset);
742 ret = write_pwm_stream_header(lte, ctx->out_fd,
743 additional_reshdr_flags);
748 ret = begin_write_resource(ctx, lte->size);
753 if (ctx->compressor != NULL) {
754 /* Record the compresed chunk size. */
755 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
756 ctx->chunk_csizes[ctx->chunk_index++] = csize;
758 /* If writing a pipable WIM, before the chunk data write a chunk
759 * header that provides the compressed chunk size. */
760 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
761 struct pwm_chunk_hdr chunk_hdr = {
762 .compressed_size = cpu_to_le32(csize),
764 ret = full_write(ctx->out_fd, &chunk_hdr,
771 /* Write the chunk data. */
772 ret = full_write(ctx->out_fd, cchunk, csize);
776 ctx->cur_write_res_offset += usize;
778 do_write_streams_progress(&ctx->progress_data,
781 if (ctx->cur_write_res_offset == ctx->cur_write_res_size &&
782 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
784 struct wim_lookup_table_entry *lte;
786 lte = list_entry(ctx->pending_streams.next,
787 struct wim_lookup_table_entry, write_streams_list);
788 wimlib_assert(ctx->cur_write_res_offset == lte->size);
790 /* Finished writing a stream in non-packed mode. */
792 ret = end_write_resource(ctx, <e->out_reshdr);
796 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
798 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
799 if (ctx->compressor != NULL)
800 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
802 list_del(<e->write_streams_list);
803 ctx->cur_write_res_offset = 0;
809 ERROR_WITH_ERRNO("Write error");
814 submit_chunk_for_compression(struct write_streams_ctx *ctx,
815 const void *chunk, size_t size)
817 /* While we are unable to submit the chunk for compression (due to too
818 * many chunks already outstanding), retrieve and write the next
819 * compressed chunk. */
820 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
827 bret = ctx->compressor->get_chunk(ctx->compressor,
828 &cchunk, &csize, &usize);
832 ret = write_chunk(ctx, cchunk, csize, usize);
839 /* Process the next chunk of data to be written to a WIM resource. */
841 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
843 struct write_streams_ctx *ctx = _ctx;
845 const u8 *chunkptr, *chunkend;
847 wimlib_assert(size != 0);
849 if (ctx->compressor == NULL) {
850 /* Write chunk uncompressed. */
851 ret = write_chunk(ctx, chunk, size, size);
854 ctx->cur_read_res_offset += size;
858 /* Submit the chunk for compression, but take into account that the
859 * @size the chunk was provided in may not correspond to the
860 * @out_chunk_size being used for compression. */
862 chunkend = chunkptr + size;
864 const u8 *resized_chunk;
865 size_t needed_chunk_size;
867 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
868 needed_chunk_size = ctx->out_chunk_size;
870 u64 res_bytes_remaining;
872 res_bytes_remaining = ctx->cur_read_res_size -
873 ctx->cur_read_res_offset;
874 needed_chunk_size = min(ctx->out_chunk_size,
875 ctx->chunk_buf_filled +
876 res_bytes_remaining);
879 if (ctx->chunk_buf_filled == 0 &&
880 chunkend - chunkptr >= needed_chunk_size)
882 /* No intermediate buffering needed. */
883 resized_chunk = chunkptr;
884 chunkptr += needed_chunk_size;
885 ctx->cur_read_res_offset += needed_chunk_size;
887 /* Intermediate buffering needed. */
888 size_t bytes_consumed;
890 bytes_consumed = min(chunkend - chunkptr,
891 needed_chunk_size - ctx->chunk_buf_filled);
893 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
894 chunkptr, bytes_consumed);
896 resized_chunk = ctx->chunk_buf;
898 chunkptr += bytes_consumed;
899 ctx->cur_read_res_offset += bytes_consumed;
900 ctx->chunk_buf_filled += bytes_consumed;
901 if (ctx->chunk_buf_filled == needed_chunk_size) {
902 resized_chunk = ctx->chunk_buf;
903 ctx->chunk_buf_filled = 0;
910 ret = submit_chunk_for_compression(ctx, resized_chunk,
915 } while (chunkptr != chunkend);
919 /* Finish processing a stream for writing. It may not have been completely
920 * written yet, as the chunk_compressor implementation may still have chunks
921 * buffered or being compressed. */
923 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
925 struct write_streams_ctx *ctx = _ctx;
927 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
928 if (ctx->stream_was_duplicate) {
929 free_lookup_table_entry(lte);
930 } else if (lte->unhashed && ctx->lookup_table != NULL) {
931 list_del(<e->unhashed_list);
932 lookup_table_insert(ctx->lookup_table, lte);
938 /* Compute statistics about a list of streams that will be written.
940 * Assumes the streams are sorted such that all streams located in each distinct
941 * WIM (specified by WIMStruct) are together. */
943 compute_stream_list_stats(struct list_head *stream_list,
944 struct write_streams_ctx *ctx)
946 struct wim_lookup_table_entry *lte;
950 WIMStruct *prev_wim_part = NULL;
952 list_for_each_entry(lte, stream_list, write_streams_list) {
954 total_bytes += lte->size;
955 if (lte->resource_location == RESOURCE_IN_WIM) {
956 if (prev_wim_part != lte->rspec->wim) {
957 prev_wim_part = lte->rspec->wim;
962 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
963 ctx->progress_data.progress.write_streams.total_streams = num_streams;
964 ctx->progress_data.progress.write_streams.completed_bytes = 0;
965 ctx->progress_data.progress.write_streams.completed_streams = 0;
966 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
967 ctx->progress_data.progress.write_streams.total_parts = total_parts;
968 ctx->progress_data.progress.write_streams.completed_parts = 0;
969 ctx->progress_data.next_progress = 0;
970 ctx->progress_data.prev_wim_part = NULL;
973 /* Find streams in @stream_list that can be copied to the output WIM in raw form
974 * rather than compressed. Delete these streams from @stream_list, and move one
975 * per resource to @raw_copy_resources. Return the total uncompressed size of
976 * the streams that need to be compressed. */
978 find_raw_copy_resources(struct list_head *stream_list,
979 int write_resource_flags,
982 struct list_head *raw_copy_resources)
984 struct wim_lookup_table_entry *lte, *tmp;
985 u64 num_bytes_to_compress = 0;
987 INIT_LIST_HEAD(raw_copy_resources);
989 /* Initialize temporary raw_copy_ok flag. */
990 list_for_each_entry(lte, stream_list, write_streams_list)
991 if (lte->resource_location == RESOURCE_IN_WIM)
992 lte->rspec->raw_copy_ok = 0;
994 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
995 if (lte->resource_location == RESOURCE_IN_WIM &&
996 lte->rspec->raw_copy_ok)
998 list_del(<e->write_streams_list);
999 } else if (can_raw_copy(lte, write_resource_flags,
1000 out_ctype, out_chunk_size))
1002 lte->rspec->raw_copy_ok = 1;
1003 list_move_tail(<e->write_streams_list,
1004 raw_copy_resources);
1006 num_bytes_to_compress += lte->size;
1010 return num_bytes_to_compress;
1013 /* Copy a raw compressed resource located in another WIM file to the WIM file
1016 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1017 struct filedes *out_fd)
1019 u64 cur_read_offset;
1020 u64 end_read_offset;
1021 u8 buf[BUFFER_SIZE];
1022 size_t bytes_to_read;
1024 struct filedes *in_fd;
1025 struct wim_lookup_table_entry *lte;
1026 u64 out_offset_in_wim;
1028 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1029 "uncompressed_size=%"PRIu64")",
1030 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1032 /* Copy the raw data. */
1033 cur_read_offset = in_rspec->offset_in_wim;
1034 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1036 out_offset_in_wim = out_fd->offset;
1038 if (in_rspec->is_pipable) {
1039 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1040 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1041 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1042 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1044 in_fd = &in_rspec->wim->in_fd;
1045 while (cur_read_offset != end_read_offset) {
1047 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1049 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1053 ret = full_write(out_fd, buf, bytes_to_read);
1057 cur_read_offset += bytes_to_read;
1060 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1061 if (lte->will_be_in_output_wim) {
1062 stream_set_out_reshdr_for_reuse(lte);
1063 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1064 lte->out_res_offset_in_wim = out_offset_in_wim;
1066 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1073 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1074 * file being written. */
1076 write_raw_copy_resources(struct list_head *raw_copy_resources,
1077 struct filedes *out_fd)
1079 struct wim_lookup_table_entry *lte;
1082 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1083 ret = write_raw_copy_resource(lte->rspec, out_fd);
1090 /* Wait for and write all chunks pending in the compressor. */
1092 finish_remaining_chunks(struct write_streams_ctx *ctx)
1099 if (ctx->compressor == NULL)
1102 if (ctx->chunk_buf_filled != 0) {
1103 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1104 ctx->chunk_buf_filled);
1109 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1110 ret = write_chunk(ctx, cdata, csize, usize);
1118 remove_zero_length_streams(struct list_head *stream_list)
1120 struct wim_lookup_table_entry *lte, *tmp;
1122 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1123 wimlib_assert(lte->will_be_in_output_wim);
1124 if (lte->size == 0) {
1125 list_del(<e->write_streams_list);
1126 lte->out_reshdr.offset_in_wim = 0;
1127 lte->out_reshdr.size_in_wim = 0;
1128 lte->out_reshdr.uncompressed_size = 0;
1129 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1135 write_stream_list(struct list_head *stream_list,
1136 struct filedes *out_fd,
1137 int write_resource_flags,
1140 unsigned num_threads,
1141 struct wim_lookup_table *lookup_table,
1142 struct filter_context *filter_ctx,
1143 struct wimlib_lzx_context **comp_ctx,
1144 wimlib_progress_func_t progress_func)
1147 struct write_streams_ctx ctx;
1148 struct list_head raw_copy_resources;
1150 remove_zero_length_streams(stream_list);
1152 if (list_empty(stream_list)) {
1153 DEBUG("No streams to write.");
1157 memset(&ctx, 0, sizeof(ctx));
1159 /* Pre-sorting the streams is required for compute_stream_list_stats().
1160 * Afterwards, read_stream_list() need not sort them again. */
1161 ret = sort_stream_list_by_sequential_order(stream_list,
1162 offsetof(struct wim_lookup_table_entry,
1163 write_streams_list));
1167 ctx.out_fd = out_fd;
1168 ctx.lookup_table = lookup_table;
1169 ctx.out_ctype = out_ctype;
1170 ctx.out_chunk_size = out_chunk_size;
1171 ctx.write_resource_flags = write_resource_flags;
1172 ctx.filter_ctx = filter_ctx;
1174 if (out_chunk_size <= STACK_MAX) {
1175 ctx.chunk_buf = alloca(out_chunk_size);
1177 ctx.chunk_buf = MALLOC(out_chunk_size);
1178 if (ctx.chunk_buf == NULL) {
1179 ret = WIMLIB_ERR_NOMEM;
1180 goto out_destroy_context;
1183 ctx.chunk_buf_filled = 0;
1185 compute_stream_list_stats(stream_list, &ctx);
1187 ctx.progress_data.progress_func = progress_func;
1189 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1190 write_resource_flags,
1193 &raw_copy_resources);
1195 DEBUG("Writing stream list "
1196 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1197 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1198 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1199 out_fd->offset, write_resource_flags,
1200 out_ctype, out_chunk_size, num_threads,
1201 ctx.progress_data.progress.write_streams.total_bytes,
1202 ctx.num_bytes_to_compress);
1204 if (ctx.num_bytes_to_compress == 0) {
1205 DEBUG("No compression needed; skipping to raw copy!");
1206 goto out_write_raw_copy_resources;
1209 /* Unless uncompressed output was required, allocate a chunk_compressor
1210 * to do compression. There are serial and parallel implementations of
1211 * the chunk_compressor interface. We default to parallel using the
1212 * specified number of threads, unless the upper bound on the number
1213 * bytes needing to be compressed is less 2000000 (heuristic value). */
1214 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1216 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZMS &&
1217 ctx.lookup_table != NULL) {
1218 WARNING("LZMS compression not implemented; data will "
1219 "actually be written uncompressed.");
1222 if (ctx.num_bytes_to_compress >= 2000000) {
1223 ret = new_parallel_chunk_compressor(out_ctype,
1228 DEBUG("Couldn't create parallel chunk compressor "
1229 "(status %d)", ret);
1233 if (ctx.compressor == NULL) {
1234 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1235 ret = wimlib_lzx_alloc_context(out_chunk_size,
1239 goto out_destroy_context;
1241 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1242 *comp_ctx, &ctx.compressor);
1244 goto out_destroy_context;
1249 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1251 ctx.progress_data.progress.write_streams.num_threads = 1;
1253 DEBUG("Actually using %u threads",
1254 ctx.progress_data.progress.write_streams.num_threads);
1256 INIT_LIST_HEAD(&ctx.pending_streams);
1258 if (ctx.progress_data.progress_func) {
1259 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1260 &ctx.progress_data.progress);
1263 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1264 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1266 goto out_destroy_context;
1269 /* Read the list of streams needing to be compressed, using the
1270 * specified callbacks to execute processing of the data. */
1272 struct read_stream_list_callbacks cbs = {
1273 .begin_stream = write_stream_begin_read,
1274 .begin_stream_ctx = &ctx,
1275 .consume_chunk = write_stream_process_chunk,
1276 .consume_chunk_ctx = &ctx,
1277 .end_stream = write_stream_end_read,
1278 .end_stream_ctx = &ctx,
1281 ret = read_stream_list(stream_list,
1282 offsetof(struct wim_lookup_table_entry, write_streams_list),
1284 STREAM_LIST_ALREADY_SORTED |
1285 VERIFY_STREAM_HASHES |
1286 COMPUTE_MISSING_STREAM_HASHES);
1289 goto out_destroy_context;
1291 ret = finish_remaining_chunks(&ctx);
1293 goto out_destroy_context;
1295 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1296 struct wim_reshdr reshdr;
1297 struct wim_lookup_table_entry *lte;
1300 ret = end_write_resource(&ctx, &reshdr);
1302 goto out_destroy_context;
1304 DEBUG("Ending packed resource: %lu %lu %lu.",
1305 reshdr.offset_in_wim,
1307 reshdr.uncompressed_size);
1310 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1311 lte->out_reshdr.size_in_wim = lte->size;
1312 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1313 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1314 lte->out_reshdr.uncompressed_size = 0;
1315 lte->out_reshdr.offset_in_wim = offset_in_res;
1316 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1317 lte->out_res_size_in_wim = reshdr.size_in_wim;
1318 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1319 offset_in_res += lte->size;
1321 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1324 out_write_raw_copy_resources:
1325 /* Copy any compressed resources for which the raw data can be reused
1326 * without decompression. */
1327 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd);
1329 out_destroy_context:
1330 if (out_chunk_size > STACK_MAX)
1331 FREE(ctx.chunk_buf);
1332 FREE(ctx.chunk_csizes);
1334 ctx.compressor->destroy(ctx.compressor);
1335 DEBUG("Done (ret=%d)", ret);
1340 write_wim_resource(struct wim_lookup_table_entry *lte,
1341 struct filedes *out_fd,
1344 int write_resource_flags,
1345 struct wimlib_lzx_context **comp_ctx)
1347 LIST_HEAD(stream_list);
1348 list_add(<e->write_streams_list, &stream_list);
1349 lte->will_be_in_output_wim = 1;
1350 return write_stream_list(&stream_list,
1352 write_resource_flags & ~WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS,
1363 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1364 int reshdr_flags, struct filedes *out_fd,
1367 struct wim_reshdr *out_reshdr,
1369 int write_resource_flags,
1370 struct wimlib_lzx_context **comp_ctx)
1373 struct wim_lookup_table_entry *lte;
1375 /* Set up a temporary lookup table entry to provide to
1376 * write_wim_resource(). */
1378 lte = new_lookup_table_entry();
1380 return WIMLIB_ERR_NOMEM;
1382 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1383 lte->attached_buffer = (void*)buf;
1384 lte->size = buf_size;
1385 lte->flags = reshdr_flags;
1387 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
1388 sha1_buffer(buf, buf_size, lte->hash);
1394 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1395 write_resource_flags, comp_ctx);
1399 copy_reshdr(out_reshdr, <e->out_reshdr);
1402 copy_hash(hash, lte->hash);
1405 lte->resource_location = RESOURCE_NONEXISTENT;
1406 free_lookup_table_entry(lte);
1410 struct stream_size_table {
1411 struct hlist_head *array;
1417 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1419 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1420 if (tab->array == NULL)
1421 return WIMLIB_ERR_NOMEM;
1422 tab->num_entries = 0;
1423 tab->capacity = capacity;
1428 destroy_stream_size_table(struct stream_size_table *tab)
1434 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1436 struct stream_size_table *tab = _tab;
1438 struct wim_lookup_table_entry *same_size_lte;
1439 struct hlist_node *tmp;
1441 pos = hash_u64(lte->size) % tab->capacity;
1442 lte->unique_size = 1;
1443 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1444 if (same_size_lte->size == lte->size) {
1445 lte->unique_size = 0;
1446 same_size_lte->unique_size = 0;
1451 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1456 struct find_streams_ctx {
1459 struct list_head stream_list;
1460 struct stream_size_table stream_size_tab;
1464 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1465 struct list_head *stream_list, u32 nref)
1467 if (!lte->will_be_in_output_wim) {
1468 lte->out_refcnt = 0;
1469 list_add_tail(<e->write_streams_list, stream_list);
1470 lte->will_be_in_output_wim = 1;
1472 lte->out_refcnt += nref;
1476 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1479 struct list_head *stream_list = _stream_list;
1480 lte->will_be_in_output_wim = 0;
1481 reference_stream_for_write(lte, stream_list, lte->refcnt);
1486 inode_find_streams_to_reference(const struct wim_inode *inode,
1487 const struct wim_lookup_table *table,
1488 struct list_head *stream_list)
1490 struct wim_lookup_table_entry *lte;
1493 wimlib_assert(inode->i_nlink > 0);
1495 for (i = 0; i <= inode->i_num_ads; i++) {
1496 lte = inode_stream_lte(inode, i, table);
1498 reference_stream_for_write(lte, stream_list,
1500 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1501 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1507 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1509 lte->will_be_in_output_wim = 0;
1514 image_find_streams_to_reference(WIMStruct *wim)
1516 struct wim_image_metadata *imd;
1517 struct wim_inode *inode;
1518 struct wim_lookup_table_entry *lte;
1519 struct list_head *stream_list;
1522 imd = wim_get_current_image_metadata(wim);
1524 image_for_each_unhashed_stream(lte, imd)
1525 lte->will_be_in_output_wim = 0;
1527 stream_list = wim->private;
1528 image_for_each_inode(inode, imd) {
1529 ret = inode_find_streams_to_reference(inode,
1539 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1542 struct list_head *stream_list_ret)
1546 INIT_LIST_HEAD(stream_list_ret);
1548 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1549 (image == 1 && wim->hdr.image_count == 1)))
1551 /* Fast case: Assume that all streams are being written and
1552 * that the reference counts are correct. */
1553 struct wim_lookup_table_entry *lte;
1554 struct wim_image_metadata *imd;
1557 for_lookup_table_entry(wim->lookup_table,
1558 fully_reference_stream_for_write,
1561 for (i = 0; i < wim->hdr.image_count; i++) {
1562 imd = wim->image_metadata[i];
1563 image_for_each_unhashed_stream(lte, imd)
1564 fully_reference_stream_for_write(lte, stream_list_ret);
1567 /* Slow case: Walk through the images being written and
1568 * determine the streams referenced. */
1569 for_lookup_table_entry(wim->lookup_table,
1570 do_stream_set_not_in_output_wim, NULL);
1571 wim->private = stream_list_ret;
1572 ret = for_image(wim, image, image_find_streams_to_reference);
1580 struct insert_other_if_hard_filtered_ctx {
1581 struct stream_size_table *tab;
1582 struct filter_context *filter_ctx;
1586 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1588 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1590 if (!lte->will_be_in_output_wim &&
1591 stream_hard_filtered(lte, ctx->filter_ctx))
1592 stream_size_table_insert(lte, ctx->tab);
1597 determine_stream_size_uniquity(struct list_head *stream_list,
1598 struct wim_lookup_table *lt,
1599 struct filter_context *filter_ctx)
1602 struct stream_size_table tab;
1603 struct wim_lookup_table_entry *lte;
1605 ret = init_stream_size_table(&tab, lt->capacity);
1609 if (may_hard_filter_streams(filter_ctx)) {
1610 struct insert_other_if_hard_filtered_ctx ctx = {
1612 .filter_ctx = filter_ctx,
1614 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1617 list_for_each_entry(lte, stream_list, write_streams_list)
1618 stream_size_table_insert(lte, &tab);
1620 destroy_stream_size_table(&tab);
1625 filter_stream_list_for_write(struct list_head *stream_list,
1626 struct filter_context *filter_ctx)
1628 struct wim_lookup_table_entry *lte, *tmp;
1630 list_for_each_entry_safe(lte, tmp,
1631 stream_list, write_streams_list)
1633 int status = stream_filtered(lte, filter_ctx);
1640 /* Soft filtered. */
1642 /* Hard filtered. */
1643 lte->will_be_in_output_wim = 0;
1644 list_del(<e->lookup_table_list);
1646 list_del(<e->write_streams_list);
1652 * prepare_stream_list_for_write() -
1654 * Prepare the list of streams to write for writing a WIM containing the
1655 * specified image(s) with the specified write flags.
1658 * The WIMStruct on whose behalf the write is occurring.
1661 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1664 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1666 * STREAMS_OK: For writes of all images, assume that all streams in the
1667 * lookup table of @wim and the per-image lists of unhashed streams should
1668 * be taken as-is, and image metadata should not be searched for
1669 * references. This does not exclude filtering with OVERWRITE and
1670 * SKIP_EXTERNAL_WIMS, below.
1672 * OVERWRITE: Streams already present in @wim shall not be returned in
1675 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1676 * @wim, shall be be returned in neither @stream_list_ret nor
1677 * @lookup_table_list_ret.
1680 * List of streams, linked by write_streams_list, that need to be written
1681 * will be returned here.
1683 * Note that this function assumes that unhashed streams will be written;
1684 * it does not take into account that they may become duplicates when
1687 * @lookup_table_list_ret
1688 * List of streams, linked by lookup_table_list, that need to be included
1689 * in the WIM's lookup table will be returned here. This will be a
1690 * superset of the streams in @stream_list_ret.
1692 * This list will be a proper superset of @stream_list_ret if and only if
1693 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1694 * the streams that would otherwise need to be written were already located
1697 * All streams in this list will have @out_refcnt set to the number of
1698 * references to the stream in the output WIM. If
1699 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1700 * may be as low as 0.
1703 * A context for queries of stream filter status with stream_filtered() is
1704 * returned in this location.
1706 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1707 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1708 * lookup table of @wim not inserted into @lookup_table_list_ret.
1710 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1711 * @stream_list_ret that have unique size among all stream entries in
1712 * @stream_list_ret and among all stream entries in the lookup table of @wim
1713 * that are ineligible for being written due to filtering.
1715 * Returns 0 on success; nonzero on read error, memory allocation error, or
1719 prepare_stream_list_for_write(WIMStruct *wim, int image,
1721 struct list_head *stream_list_ret,
1722 struct list_head *lookup_table_list_ret,
1723 struct filter_context *filter_ctx_ret)
1726 struct wim_lookup_table_entry *lte;
1728 filter_ctx_ret->write_flags = write_flags;
1729 filter_ctx_ret->wim = wim;
1731 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1734 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1739 INIT_LIST_HEAD(lookup_table_list_ret);
1740 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1741 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1743 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1748 if (may_filter_streams(filter_ctx_ret))
1749 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1755 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1756 unsigned num_threads,
1757 wimlib_progress_func_t progress_func,
1758 struct list_head *stream_list_override,
1759 struct list_head *lookup_table_list_ret)
1762 struct list_head _stream_list;
1763 struct list_head *stream_list;
1764 struct wim_lookup_table_entry *lte;
1765 struct filter_context _filter_ctx;
1766 struct filter_context *filter_ctx;
1768 if (stream_list_override == NULL) {
1769 /* Normal case: prepare stream list from image(s) being written.
1771 stream_list = &_stream_list;
1772 filter_ctx = &_filter_ctx;
1773 ret = prepare_stream_list_for_write(wim, image, write_flags,
1775 lookup_table_list_ret,
1780 /* Currently only as a result of wimlib_split() being called:
1781 * use stream list already explicitly provided. Use existing
1782 * reference counts. */
1783 stream_list = stream_list_override;
1785 INIT_LIST_HEAD(lookup_table_list_ret);
1786 list_for_each_entry(lte, stream_list, write_streams_list) {
1787 lte->out_refcnt = lte->refcnt;
1788 lte->will_be_in_output_wim = 1;
1789 lte->unique_size = 0;
1790 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1794 return write_stream_list(stream_list,
1796 write_flags_to_resource_flags(write_flags),
1797 wim->out_compression_type,
1798 wim->out_chunk_size,
1807 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1808 wimlib_progress_func_t progress_func)
1813 int write_resource_flags;
1815 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1816 DEBUG("Not writing any metadata resources.");
1820 write_resource_flags = write_flags_to_resource_flags(write_flags);
1822 write_resource_flags &= ~WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS;
1824 DEBUG("Writing metadata resources (offset=%"PRIu64")",
1825 wim->out_fd.offset);
1828 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1830 if (image == WIMLIB_ALL_IMAGES) {
1832 end_image = wim->hdr.image_count;
1834 start_image = image;
1838 for (int i = start_image; i <= end_image; i++) {
1839 struct wim_image_metadata *imd;
1841 imd = wim->image_metadata[i - 1];
1842 /* Build a new metadata resource only if image was modified from
1843 * the original (or was newly added). Otherwise just copy the
1845 if (imd->modified) {
1846 DEBUG("Image %u was modified; building and writing new "
1847 "metadata resource", i);
1848 ret = write_metadata_resource(wim, i,
1849 write_resource_flags);
1850 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1851 DEBUG("Image %u was not modified; re-using existing "
1852 "metadata resource.", i);
1853 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
1856 DEBUG("Image %u was not modified; copying existing "
1857 "metadata resource.", i);
1858 ret = write_wim_resource(imd->metadata_lte,
1860 wim->out_compression_type,
1861 wim->out_chunk_size,
1862 write_resource_flags,
1869 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1874 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
1877 DEBUG("Opening \"%"TS"\" for writing.", path);
1879 raw_fd = topen(path, open_flags | O_BINARY, 0644);
1881 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
1882 return WIMLIB_ERR_OPEN;
1884 filedes_init(&wim->out_fd, raw_fd);
1889 close_wim_writable(WIMStruct *wim, int write_flags)
1893 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
1894 DEBUG("Closing WIM file.");
1895 if (filedes_valid(&wim->out_fd))
1896 if (filedes_close(&wim->out_fd))
1897 ret = WIMLIB_ERR_WRITE;
1899 filedes_invalidate(&wim->out_fd);
1904 cmp_streams_by_out_rspec(const void *p1, const void *p2)
1906 const struct wim_lookup_table_entry *lte1, *lte2;
1908 lte1 = *(const struct wim_lookup_table_entry**)p1;
1909 lte2 = *(const struct wim_lookup_table_entry**)p2;
1911 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1912 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1913 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
1914 return cmp_u64(lte1->out_res_offset_in_wim,
1915 lte2->out_res_offset_in_wim);
1920 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1923 return cmp_u64(lte1->out_reshdr.offset_in_wim,
1924 lte2->out_reshdr.offset_in_wim);
1928 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
1929 struct wim_reshdr *out_reshdr,
1930 struct list_head *lookup_table_list)
1934 /* Set output resource metadata for streams already present in WIM. */
1935 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1936 struct wim_lookup_table_entry *lte;
1937 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
1939 if (lte->resource_location == RESOURCE_IN_WIM &&
1940 lte->rspec->wim == wim)
1942 stream_set_out_reshdr_for_reuse(lte);
1947 ret = sort_stream_list(lookup_table_list,
1948 offsetof(struct wim_lookup_table_entry, lookup_table_list),
1949 cmp_streams_by_out_rspec);
1953 /* Add entries for metadata resources. */
1954 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
1958 if (image == WIMLIB_ALL_IMAGES) {
1960 end_image = wim->hdr.image_count;
1962 start_image = image;
1966 /* Push metadata resource lookup table entries onto the front of
1967 * the list in reverse order, so that they're written in order.
1969 for (int i = end_image; i >= start_image; i--) {
1970 struct wim_lookup_table_entry *metadata_lte;
1972 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
1973 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
1974 metadata_lte->out_refcnt = 1;
1975 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
1979 return write_wim_lookup_table_from_stream_list(lookup_table_list,
1981 wim->hdr.part_number,
1983 write_flags_to_resource_flags(write_flags),
1990 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1991 * table, then overwrite the WIM header. By default, closes the WIM file
1992 * descriptor (@wim->out_fd) if successful.
1994 * write_flags is a bitwise OR of the following:
1996 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1997 * Include an integrity table.
1999 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2000 * fsync() the output file before closing it.
2002 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2003 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2004 * stream headers before the lookup table and XML data, and also
2005 * write the WIM header at the end instead of seeking to the
2006 * beginning. Can't be combined with
2007 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2009 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2010 * Don't write the lookup table.
2012 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2013 * When (if) writing the integrity table, re-use entries from the
2014 * existing integrity table, if possible.
2016 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2017 * After writing the XML data but before writing the integrity
2018 * table, write a temporary WIM header and flush the stream so that
2019 * the WIM is less likely to become corrupted upon abrupt program
2021 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2022 * Instead of overwriting the WIM header at the beginning of the
2023 * file, simply append it to the end of the file. (Used when
2025 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2026 * Do not close the file descriptor @wim->out_fd on either success
2028 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2029 * Use the existing <TOTALBYTES> stored in the in-memory XML
2030 * information, rather than setting it to the offset of the XML
2031 * data being written.
2034 finish_write(WIMStruct *wim, int image, int write_flags,
2035 wimlib_progress_func_t progress_func,
2036 struct list_head *lookup_table_list)
2040 int write_resource_flags;
2041 off_t old_lookup_table_end;
2042 off_t new_lookup_table_end;
2045 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2047 write_resource_flags = write_flags_to_resource_flags(write_flags);
2049 /* In the WIM header, there is room for the resource entry for a
2050 * metadata resource labeled as the "boot metadata". This entry should
2051 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2052 * it should be a copy of the resource entry for the image that is
2053 * marked as bootable. This is not well documented... */
2054 if (wim->hdr.boot_idx == 0) {
2055 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2057 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2058 &wim->image_metadata[
2059 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2062 /* Write lookup table. (Save old position first.) */
2063 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2064 wim->hdr.lookup_table_reshdr.size_in_wim;
2065 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2066 ret = write_wim_lookup_table(wim, image, write_flags,
2067 &wim->hdr.lookup_table_reshdr,
2073 /* Write XML data. */
2074 xml_totalbytes = wim->out_fd.offset;
2075 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2076 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2077 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2078 &wim->hdr.xml_data_reshdr,
2079 write_resource_flags);
2083 /* Write integrity table (optional). */
2084 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2085 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2086 struct wim_header checkpoint_hdr;
2087 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2088 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2089 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2090 ret = write_wim_header_at_offset(&checkpoint_hdr,
2096 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2097 old_lookup_table_end = 0;
2099 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2100 wim->hdr.lookup_table_reshdr.size_in_wim;
2102 ret = write_integrity_table(wim,
2103 new_lookup_table_end,
2104 old_lookup_table_end,
2109 /* No integrity table. */
2110 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2113 /* Now that all information in the WIM header has been determined, the
2114 * preliminary header written earlier can be overwritten, the header of
2115 * the existing WIM file can be overwritten, or the final header can be
2116 * written to the end of the pipable WIM. */
2117 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2119 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2120 hdr_offset = wim->out_fd.offset;
2121 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2122 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2126 /* Possibly sync file data to disk before closing. On POSIX systems, it
2127 * is necessary to do this before using rename() to overwrite an
2128 * existing file with a new file. Otherwise, data loss would occur if
2129 * the system is abruptly terminated when the metadata for the rename
2130 * operation has been written to disk, but the new file data has not.
2132 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2133 DEBUG("Syncing WIM file.");
2134 if (fsync(wim->out_fd.fd)) {
2135 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2136 return WIMLIB_ERR_WRITE;
2140 if (close_wim_writable(wim, write_flags)) {
2141 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2142 return WIMLIB_ERR_WRITE;
2148 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2150 lock_wim(WIMStruct *wim, int fd)
2153 if (fd != -1 && !wim->wim_locked) {
2154 ret = flock(fd, LOCK_EX | LOCK_NB);
2156 if (errno == EWOULDBLOCK) {
2157 ERROR("`%"TS"' is already being modified or has been "
2158 "mounted read-write\n"
2159 " by another process!", wim->filename);
2160 ret = WIMLIB_ERR_ALREADY_LOCKED;
2162 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2167 wim->wim_locked = 1;
2175 * write_pipable_wim():
2177 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2178 * capable of being applied from a pipe).
2180 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2181 * images can be applied from them sequentially when the file data is sent over
2182 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2183 * The modifications made to the WIM format for pipable WIMs are:
2185 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2186 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2187 * stops other software from trying to read the file as a normal WIM.
2189 * - The header at the beginning of the file does not contain all the normal
2190 * information; in particular it will have all 0's for the lookup table and
2191 * XML data resource entries. This is because this information cannot be
2192 * determined until the lookup table and XML data have been written.
2193 * Consequently, wimlib will write the full header at the very end of the
2194 * file. The header at the end, however, is only used when reading the WIM
2195 * from a seekable file (not a pipe).
2197 * - An extra copy of the XML data is placed directly after the header. This
2198 * allows image names and sizes to be determined at an appropriate time when
2199 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2200 * WIM is read from a seekable file (not a pipe).
2202 * - The format of resources, or streams, has been modified to allow them to be
2203 * used before the "lookup table" has been read. Each stream is prefixed with
2204 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2205 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2206 * uncompressed stream size, and flags that indicate whether the stream is
2207 * compressed. The data of uncompressed streams then follows literally, while
2208 * the data of compressed streams follows in a modified format. Compressed
2209 * streams do not begin with a chunk table, since the chunk table cannot be
2210 * written until all chunks have been compressed. Instead, each compressed
2211 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2212 * Furthermore, the chunk table is written at the end of the resource instead
2213 * of the start. Note: chunk offsets are given in the chunk table as if the
2214 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2215 * used if the WIM is being read from a seekable file (not a pipe).
2217 * - Metadata resources always come before other file resources (streams).
2218 * (This does not by itself constitute an incompatibility with normal WIMs,
2219 * since this is valid in normal WIMs.)
2221 * - At least up to the end of the file resources, all components must be packed
2222 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2223 * not by itself consititute an incompatibility with normal WIMs, since this
2224 * is valid in normal WIMs.)
2226 * Note: the lookup table, XML data, and header at the end are not used when
2227 * applying from a pipe. They exist to support functionality such as image
2228 * application and export when the WIM is *not* read from a pipe.
2230 * Layout of pipable WIM:
2232 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2233 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2234 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2236 * Layout of normal WIM:
2238 * +--------+-----------------------------+-------------------------+
2239 * | Header | File and metadata resources | Lookup table | XML data |
2240 * +--------+-----------------------------+-------------------------+
2242 * An optional integrity table can follow the final XML data in both normal and
2243 * pipable WIMs. However, due to implementation details, wimlib currently can
2244 * only include an integrity table in a pipable WIM when writing it to a
2245 * seekable file (not a pipe).
2247 * Do note that since pipable WIMs are not supported by Microsoft's software,
2248 * wimlib does not create them unless explicitly requested (with
2249 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2250 * characters to identify the file.
2253 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2254 unsigned num_threads, wimlib_progress_func_t progress_func,
2255 struct list_head *stream_list_override,
2256 struct list_head *lookup_table_list_ret)
2259 struct wim_reshdr xml_reshdr;
2261 WARNING("Creating a pipable WIM, which will "
2263 " with Microsoft's software (wimgapi/imagex/Dism).");
2265 /* At this point, the header at the beginning of the file has already
2268 /* For efficiency, when wimlib adds an image to the WIM with
2269 * wimlib_add_image(), the SHA1 message digests of files is not
2270 * calculated; instead, they are calculated while the files are being
2271 * written. However, this does not work when writing a pipable WIM,
2272 * since when writing a stream to a pipable WIM, its SHA1 message digest
2273 * needs to be known before the stream data is written. Therefore,
2274 * before getting much farther, we need to pre-calculate the SHA1
2275 * message digests of all streams that will be written. */
2276 ret = wim_checksum_unhashed_streams(wim);
2280 /* Write extra copy of the XML data. */
2281 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2283 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2287 /* Write metadata resources for the image(s) being included in the
2289 ret = write_wim_metadata_resources(wim, image, write_flags,
2294 /* Write streams needed for the image(s) being included in the output
2295 * WIM, or streams needed for the split WIM part. */
2296 return write_wim_streams(wim, image, write_flags, num_threads,
2297 progress_func, stream_list_override,
2298 lookup_table_list_ret);
2300 /* The lookup table, XML data, and header at end are handled by
2301 * finish_write(). */
2304 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2307 write_wim_part(WIMStruct *wim,
2308 const void *path_or_fd,
2311 unsigned num_threads,
2312 wimlib_progress_func_t progress_func,
2313 unsigned part_number,
2314 unsigned total_parts,
2315 struct list_head *stream_list_override,
2319 struct wim_header hdr_save;
2320 struct list_head lookup_table_list;
2322 if (total_parts == 1)
2323 DEBUG("Writing standalone WIM.");
2325 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2326 if (image == WIMLIB_ALL_IMAGES)
2327 DEBUG("Including all images.");
2329 DEBUG("Including image %d only.", image);
2330 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2331 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2333 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2334 DEBUG("Write flags: 0x%08x", write_flags);
2336 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2337 DEBUG("\tCHECK_INTEGRITY");
2339 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2342 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2343 DEBUG("\tRECOMPRESS");
2345 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2348 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2351 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2352 DEBUG("\tIGNORE_READONLY_FLAG");
2354 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2357 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2358 DEBUG("\tNOT_PIPABLE");
2360 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2361 DEBUG("\tPACK_STREAMS");
2363 if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2364 DEBUG("\tNO_PACK_STREAMS");
2366 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2367 DEBUG("\tFILE_DESCRIPTOR");
2369 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2370 DEBUG("\tNO_METADATA");
2372 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2373 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2375 if (num_threads == 0)
2376 DEBUG("Number of threads: autodetect");
2378 DEBUG("Number of threads: %u", num_threads);
2379 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2380 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2381 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2382 "specified" : "generate new"));
2384 /* Internally, this is always called with a valid part number and total
2386 wimlib_assert(total_parts >= 1);
2387 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2389 /* A valid image (or all images) must be specified. */
2390 if (image != WIMLIB_ALL_IMAGES &&
2391 (image < 1 || image > wim->hdr.image_count))
2392 return WIMLIB_ERR_INVALID_IMAGE;
2394 /* If we need to write metadata resources, make sure the ::WIMStruct has
2395 * the needed information attached (e.g. is not a resource-only WIM,
2396 * such as a non-first part of a split WIM). */
2397 if (!wim_has_metadata(wim) &&
2398 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2399 return WIMLIB_ERR_METADATA_NOT_FOUND;
2401 /* Check for contradictory flags. */
2402 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2403 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2404 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2405 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2406 return WIMLIB_ERR_INVALID_PARAM;
2408 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2409 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2410 == (WIMLIB_WRITE_FLAG_PIPABLE |
2411 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2412 return WIMLIB_ERR_INVALID_PARAM;
2414 if ((write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2415 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2416 == (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2417 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2418 return WIMLIB_ERR_INVALID_PARAM;
2420 /* Save previous header, then start initializing the new one. */
2421 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2423 /* Set default integrity, pipable, and packed stream flags. */
2424 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2425 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2426 if (wim_is_pipable(wim)) {
2427 DEBUG("WIM is pipable; default to PIPABLE.");
2428 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2431 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2432 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2433 if (wim_has_integrity_table(wim)) {
2434 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2435 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2438 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2439 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2440 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS) {
2441 DEBUG("WIM version 3584; default to PACK_STREAMS.");
2442 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2445 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2446 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2447 == (WIMLIB_WRITE_FLAG_PIPABLE |
2448 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2449 return WIMLIB_ERR_INVALID_PARAM;
2451 /* Set appropriate magic number. */
2452 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2453 wim->hdr.magic = PWM_MAGIC;
2455 wim->hdr.magic = WIM_MAGIC;
2457 /* Set appropriate version number. */
2458 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2459 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2461 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2463 /* Clear header flags that will be set automatically. */
2464 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2465 WIM_HDR_FLAG_RESOURCE_ONLY |
2466 WIM_HDR_FLAG_SPANNED |
2467 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2469 /* Set SPANNED header flag if writing part of a split WIM. */
2470 if (total_parts != 1)
2471 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2473 /* Set part number and total parts of split WIM. This will be 1 and 1
2474 * if the WIM is standalone. */
2475 wim->hdr.part_number = part_number;
2476 wim->hdr.total_parts = total_parts;
2478 /* Set compression type if different. */
2479 if (wim->compression_type != wim->out_compression_type) {
2480 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2481 wimlib_assert(ret == 0);
2484 /* Set chunk size if different. */
2485 wim->hdr.chunk_size = wim->out_chunk_size;
2487 /* Use GUID if specified; otherwise generate a new one. */
2489 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2490 else if (!wim->guid_set_explicitly)
2491 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2493 /* Clear references to resources that have not been written yet. */
2494 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2495 zero_reshdr(&wim->hdr.xml_data_reshdr);
2496 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2497 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2499 /* Set image count and boot index correctly for single image writes. */
2500 if (image != WIMLIB_ALL_IMAGES) {
2501 wim->hdr.image_count = 1;
2502 if (wim->hdr.boot_idx == image)
2503 wim->hdr.boot_idx = 1;
2505 wim->hdr.boot_idx = 0;
2508 /* Split WIMs can't be bootable. */
2509 if (total_parts != 1)
2510 wim->hdr.boot_idx = 0;
2512 /* Initialize output file descriptor. */
2513 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2514 /* File descriptor was explicitly provided. Return error if
2515 * file descriptor is not seekable, unless writing a pipable WIM
2517 wim->out_fd.fd = *(const int*)path_or_fd;
2518 wim->out_fd.offset = 0;
2519 if (!filedes_is_seekable(&wim->out_fd)) {
2520 ret = WIMLIB_ERR_INVALID_PARAM;
2521 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2522 goto out_restore_hdr;
2523 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2524 ERROR("Can't include integrity check when "
2525 "writing pipable WIM to pipe!");
2526 goto out_restore_hdr;
2531 /* Filename of WIM to write was provided; open file descriptor
2533 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2534 O_TRUNC | O_CREAT | O_RDWR);
2536 goto out_restore_hdr;
2539 /* Write initial header. This is merely a "dummy" header since it
2540 * doesn't have all the information yet, so it will be overwritten later
2541 * (unless writing a pipable WIM). */
2542 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2543 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2544 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2545 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2547 goto out_restore_hdr;
2549 /* Write metadata resources and streams. */
2550 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2551 /* Default case: create a normal (non-pipable) WIM. */
2552 ret = write_wim_streams(wim, image, write_flags, num_threads,
2553 progress_func, stream_list_override,
2554 &lookup_table_list);
2556 goto out_restore_hdr;
2558 ret = write_wim_metadata_resources(wim, image, write_flags,
2561 goto out_restore_hdr;
2563 /* Non-default case: create pipable WIM. */
2564 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2565 progress_func, stream_list_override,
2566 &lookup_table_list);
2568 goto out_restore_hdr;
2569 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2573 /* Write lookup table, XML data, and (optional) integrity table. */
2574 ret = finish_write(wim, image, write_flags, progress_func,
2575 &lookup_table_list);
2577 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2578 (void)close_wim_writable(wim, write_flags);
2579 DEBUG("ret=%d", ret);
2583 /* Write a standalone WIM to a file or file descriptor. */
2585 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2586 int image, int write_flags, unsigned num_threads,
2587 wimlib_progress_func_t progress_func)
2589 return write_wim_part(wim, path_or_fd, image, write_flags,
2590 num_threads, progress_func, 1, 1, NULL, NULL);
2593 /* API function documented in wimlib.h */
2595 wimlib_write(WIMStruct *wim, const tchar *path,
2596 int image, int write_flags, unsigned num_threads,
2597 wimlib_progress_func_t progress_func)
2600 return WIMLIB_ERR_INVALID_PARAM;
2602 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2604 return write_standalone_wim(wim, path, image, write_flags,
2605 num_threads, progress_func);
2608 /* API function documented in wimlib.h */
2610 wimlib_write_to_fd(WIMStruct *wim, int fd,
2611 int image, int write_flags, unsigned num_threads,
2612 wimlib_progress_func_t progress_func)
2615 return WIMLIB_ERR_INVALID_PARAM;
2617 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2618 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2620 return write_standalone_wim(wim, &fd, image, write_flags,
2621 num_threads, progress_func);
2625 any_images_modified(WIMStruct *wim)
2627 for (int i = 0; i < wim->hdr.image_count; i++)
2628 if (wim->image_metadata[i]->modified)
2634 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2636 const WIMStruct *wim = _wim;
2637 off_t end_offset = *(const off_t*)wim->private;
2639 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2640 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2641 return WIMLIB_ERR_RESOURCE_ORDER;
2645 /* Make sure no file or metadata resources are located after the XML data (or
2646 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2647 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2649 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2654 wim->private = &end_offset;
2655 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2659 for (i = 0; i < wim->hdr.image_count; i++) {
2660 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2668 * Overwrite a WIM, possibly appending streams to it.
2670 * A WIM looks like (or is supposed to look like) the following:
2672 * Header (212 bytes)
2673 * Streams and metadata resources (variable size)
2674 * Lookup table (variable size)
2675 * XML data (variable size)
2676 * Integrity table (optional) (variable size)
2678 * If we are not adding any streams or metadata resources, the lookup table is
2679 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2680 * header. This operation is potentially unsafe if the program is abruptly
2681 * terminated while the XML data or integrity table are being overwritten, but
2682 * before the new header has been written. To partially alleviate this problem,
2683 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2684 * finish_write() to cause a temporary WIM header to be written after the XML
2685 * data has been written. This may prevent the WIM from becoming corrupted if
2686 * the program is terminated while the integrity table is being calculated (but
2687 * no guarantees, due to write re-ordering...).
2689 * If we are adding new streams or images (metadata resources), the lookup table
2690 * needs to be changed, and those streams need to be written. In this case, we
2691 * try to perform a safe update of the WIM file by writing the streams *after*
2692 * the end of the previous WIM, then writing the new lookup table, XML data, and
2693 * (optionally) integrity table following the new streams. This will produce a
2694 * layout like the following:
2696 * Header (212 bytes)
2697 * (OLD) Streams and metadata resources (variable size)
2698 * (OLD) Lookup table (variable size)
2699 * (OLD) XML data (variable size)
2700 * (OLD) Integrity table (optional) (variable size)
2701 * (NEW) Streams and metadata resources (variable size)
2702 * (NEW) Lookup table (variable size)
2703 * (NEW) XML data (variable size)
2704 * (NEW) Integrity table (optional) (variable size)
2706 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2707 * the header is overwritten to point to the new lookup table, XML data, and
2708 * integrity table, to produce the following layout:
2710 * Header (212 bytes)
2711 * Streams and metadata resources (variable size)
2712 * Nothing (variable size)
2713 * More Streams and metadata resources (variable size)
2714 * Lookup table (variable size)
2715 * XML data (variable size)
2716 * Integrity table (optional) (variable size)
2718 * This method allows an image to be appended to a large WIM very quickly, and
2719 * is is crash-safe except in the case of write re-ordering, but the
2720 * disadvantage is that a small hole is left in the WIM where the old lookup
2721 * table, xml data, and integrity table were. (These usually only take up a
2722 * small amount of space compared to the streams, however.)
2725 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2726 unsigned num_threads,
2727 wimlib_progress_func_t progress_func)
2731 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2732 struct wim_header hdr_save;
2733 struct list_head stream_list;
2734 struct list_head lookup_table_list;
2735 struct filter_context filter_ctx;
2737 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2739 /* Set default integrity flag. */
2740 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2741 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2742 if (wim_has_integrity_table(wim))
2743 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2745 /* Set default packed flag. */
2746 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2747 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2748 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
2749 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2751 /* Set additional flags for overwrite. */
2752 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2753 WIMLIB_WRITE_FLAG_STREAMS_OK;
2755 /* Make sure that the integrity table (if present) is after the XML
2756 * data, and that there are no stream resources, metadata resources, or
2757 * lookup tables after the XML data. Otherwise, these data would be
2759 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2760 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2761 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2762 wim->hdr.lookup_table_reshdr.size_in_wim;
2763 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2764 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2765 WARNING("Didn't expect the integrity table to be before the XML data");
2766 return WIMLIB_ERR_RESOURCE_ORDER;
2769 if (old_lookup_table_end > old_xml_begin) {
2770 WARNING("Didn't expect the lookup table to be after the XML data");
2771 return WIMLIB_ERR_RESOURCE_ORDER;
2774 /* Set @old_wim_end, which indicates the point beyond which we don't
2775 * allow any file and metadata resources to appear without returning
2776 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2777 * overwrite these resources). */
2778 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2779 /* If no images have been modified and no images have been
2780 * deleted, a new lookup table does not need to be written. We
2781 * shall write the new XML data and optional integrity table
2782 * immediately after the lookup table. Note that this may
2783 * overwrite an existing integrity table. */
2784 DEBUG("Skipping writing lookup table "
2785 "(no images modified or deleted)");
2786 old_wim_end = old_lookup_table_end;
2787 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2788 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2789 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2790 /* Old WIM has an integrity table; begin writing new streams
2792 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2793 wim->hdr.integrity_table_reshdr.size_in_wim;
2795 /* No existing integrity table; begin writing new streams after
2796 * the old XML data. */
2797 old_wim_end = old_xml_end;
2800 ret = check_resource_offsets(wim, old_wim_end);
2804 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2805 &stream_list, &lookup_table_list,
2810 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2814 ret = lock_wim(wim, wim->out_fd.fd);
2818 /* Save original header so it can be restored in case of error */
2819 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2821 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2822 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2823 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2825 ERROR_WITH_ERRNO("Error updating WIM header flags");
2826 goto out_restore_memory_hdr;
2829 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2830 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2831 ret = WIMLIB_ERR_WRITE;
2832 goto out_restore_physical_hdr;
2835 ret = write_stream_list(&stream_list,
2837 write_flags_to_resource_flags(write_flags),
2838 wim->compression_type,
2848 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2849 write_flags, progress_func);
2853 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2854 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2855 progress_func, &lookup_table_list);
2859 goto out_unlock_wim;
2862 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2863 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2864 wim->filename, old_wim_end);
2865 /* Return value of ftruncate() is ignored because this is
2866 * already an error path. */
2867 (void)ftruncate(wim->out_fd.fd, old_wim_end);
2869 out_restore_physical_hdr:
2870 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
2871 out_restore_memory_hdr:
2872 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2874 (void)close_wim_writable(wim, write_flags);
2876 wim->wim_locked = 0;
2881 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2882 unsigned num_threads,
2883 wimlib_progress_func_t progress_func)
2885 size_t wim_name_len;
2888 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2890 /* Write the WIM to a temporary file in the same directory as the
2892 wim_name_len = tstrlen(wim->filename);
2893 tchar tmpfile[wim_name_len + 10];
2894 tmemcpy(tmpfile, wim->filename, wim_name_len);
2895 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2896 tmpfile[wim_name_len + 9] = T('\0');
2898 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2899 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2900 num_threads, progress_func);
2908 /* Rename the new WIM file to the original WIM file. Note: on Windows
2909 * this actually calls win32_rename_replacement(), not _wrename(), so
2910 * that removing the existing destination file can be handled. */
2911 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
2912 ret = trename(tmpfile, wim->filename);
2914 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2915 tmpfile, wim->filename);
2922 return WIMLIB_ERR_RENAME;
2925 if (progress_func) {
2926 union wimlib_progress_info progress;
2927 progress.rename.from = tmpfile;
2928 progress.rename.to = wim->filename;
2929 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2935 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
2937 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2940 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2943 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2946 if (wim->compression_type != wim->out_compression_type)
2948 if (wim->chunk_size != wim->out_chunk_size)
2954 /* API function documented in wimlib.h */
2956 wimlib_overwrite(WIMStruct *wim, int write_flags,
2957 unsigned num_threads,
2958 wimlib_progress_func_t progress_func)
2963 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2965 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2966 return WIMLIB_ERR_INVALID_PARAM;
2969 return WIMLIB_ERR_NO_FILENAME;
2971 orig_hdr_flags = wim->hdr.flags;
2972 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2973 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
2974 ret = can_modify_wim(wim);
2975 wim->hdr.flags = orig_hdr_flags;
2979 if (can_overwrite_wim_inplace(wim, write_flags)) {
2980 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
2982 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
2984 WARNING("Falling back to re-building entire WIM");
2986 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,