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"
46 #include "wimlib/write.h"
47 #include "wimlib/xml.h"
59 write_flags_to_resource_flags(int write_flags)
61 int write_resource_flags = 0;
63 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
64 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
65 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
66 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
67 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
68 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS;
69 return write_resource_flags;
72 struct filter_context {
77 /* Determine specified stream should be filtered out from the write.
81 * < 0 : The stream should be hard-filtered; that is, not included in the
83 * 0 : The stream should not be filtered out.
84 * > 0 : The stream should be soft-filtered; that is, it already exists in the
85 * WIM file and may not need to be written again.
88 stream_filtered(const struct wim_lookup_table_entry *lte,
89 const struct filter_context *ctx)
91 int write_flags = ctx->write_flags;
92 WIMStruct *wim = ctx->wim;
97 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
98 lte->resource_location == RESOURCE_IN_WIM &&
99 lte->rspec->wim == wim)
102 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
103 lte->resource_location == RESOURCE_IN_WIM &&
104 lte->rspec->wim != wim)
111 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
112 struct filter_context *ctx)
114 return stream_filtered(lte, ctx) < 0;
118 may_soft_filter_streams(const struct filter_context *ctx)
122 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
126 may_hard_filter_streams(const struct filter_context *ctx)
130 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
134 may_filter_streams(const struct filter_context *ctx)
136 return (may_soft_filter_streams(ctx) ||
137 may_hard_filter_streams(ctx));
141 /* Return true if the specified resource is compressed and the compressed data
142 * can be reused with the specified output parameters. */
144 can_raw_copy(const struct wim_lookup_table_entry *lte,
145 int write_resource_flags, int out_ctype, u32 out_chunk_size)
147 const struct wim_resource_spec *rspec;
149 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
152 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
155 if (lte->resource_location != RESOURCE_IN_WIM)
160 if (rspec->is_pipable != !!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
164 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
165 /* Normal compressed resource: Must use same compression type
167 return (rspec->wim->compression_type == out_ctype &&
168 rspec->wim->chunk_size == out_chunk_size);
171 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
172 (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
174 /* Packed resource: Such resources may contain multiple streams,
175 * and in general only a subset of them need to be written. As
176 * a heuristic, re-use the raw data if at least half the
177 * uncompressed size is being written. */
179 /* Note: packed resources contain a header that specifies the
180 * compression type and chunk size; therefore we don't need to
181 * check if they are compatible with @out_ctype and
182 * @out_chunk_size. */
184 struct wim_lookup_table_entry *res_stream;
187 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
188 if (res_stream->will_be_in_output_wim)
189 write_size += res_stream->size;
191 return (write_size > rspec->uncompressed_size / 2);
197 filter_resource_flags(u8 flags)
199 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
200 WIM_RESHDR_FLAG_COMPRESSED |
201 WIM_RESHDR_FLAG_SPANNED |
202 WIM_RESHDR_FLAG_FREE));
206 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
208 const struct wim_resource_spec *rspec;
210 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
213 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
215 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
217 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
218 lte->out_reshdr.uncompressed_size = 0;
219 lte->out_reshdr.size_in_wim = lte->size;
221 lte->out_res_offset_in_wim = rspec->offset_in_wim;
222 lte->out_res_size_in_wim = rspec->size_in_wim;
223 lte->out_res_uncompressed_size = rspec->uncompressed_size;
225 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
227 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
228 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
229 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
231 lte->out_reshdr.flags = lte->flags;
235 /* Write the header for a stream in a pipable WIM. */
237 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
238 struct filedes *out_fd,
239 int additional_reshdr_flags)
241 struct pwm_stream_hdr stream_hdr;
245 stream_hdr.magic = PWM_STREAM_MAGIC;
246 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
247 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
248 zero_out_hash(stream_hdr.hash);
250 wimlib_assert(!lte->unhashed);
251 copy_hash(stream_hdr.hash, lte->hash);
254 reshdr_flags = filter_resource_flags(lte->flags);
255 reshdr_flags |= additional_reshdr_flags;
256 stream_hdr.flags = cpu_to_le32(reshdr_flags);
257 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
259 ERROR_WITH_ERRNO("Write error");
265 seek_and_truncate(struct filedes *out_fd, off_t offset)
267 if (filedes_seek(out_fd, offset) == -1 ||
268 ftruncate(out_fd->fd, offset))
270 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
271 return WIMLIB_ERR_WRITE;
277 struct write_streams_progress_data {
278 wimlib_progress_func_t progress_func;
279 union wimlib_progress_info progress;
280 uint64_t next_progress;
281 WIMStruct *prev_wim_part;
285 do_write_streams_progress(struct write_streams_progress_data *progress_data,
286 struct wim_lookup_table_entry *lte,
287 bool stream_discarded)
289 union wimlib_progress_info *progress = &progress_data->progress;
292 if (stream_discarded) {
293 progress->write_streams.total_bytes -= lte->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 += lte->size;
302 new_wim_part = false;
303 if (lte->resource_location == RESOURCE_IN_WIM &&
304 lte->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 = lte->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)
407 if (res_size <= UINT32_MAX)
413 /* Reserve space for the chunk table and prepare to accumulate the chunk table
416 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
418 u64 expected_num_chunks;
419 u64 expected_num_chunk_entries;
423 /* Calculate the number of chunks and chunk entries that should be
424 * needed for the resource. These normally will be the final values,
425 * but in PACKED_STREAMS mode some of the streams we're planning to
426 * write into the resource may be duplicates, and therefore discarded,
427 * potentially decreasing the number of chunk entries needed. */
428 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
429 expected_num_chunk_entries = expected_num_chunks;
430 if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
431 expected_num_chunk_entries--;
433 /* Make sure the chunk_csizes array is long enough to store the
434 * compressed size of each chunk. */
435 if (expected_num_chunks > ctx->num_alloc_chunks) {
436 u64 new_length = expected_num_chunks + 50;
438 if ((size_t)new_length != new_length) {
439 ERROR("Resource size too large (%"PRIu64" bytes!",
441 return WIMLIB_ERR_NOMEM;
444 FREE(ctx->chunk_csizes);
445 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
446 if (ctx->chunk_csizes == NULL) {
447 ctx->num_alloc_chunks = 0;
448 return WIMLIB_ERR_NOMEM;
450 ctx->num_alloc_chunks = new_length;
453 ctx->chunk_index = 0;
455 if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
456 /* Reserve space for the chunk table in the output file. In the
457 * case of packed resources this reserves the upper bound for
458 * the needed space, not necessarily the exact space which will
459 * prove to be needed. At this point, we just use @chunk_csizes
460 * for a buffer of 0's because the actual compressed chunk sizes
462 reserve_size = expected_num_chunk_entries * get_chunk_entry_size(res_expected_size);
463 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS)
464 reserve_size += sizeof(struct alt_chunk_table_header_disk);
465 memset(ctx->chunk_csizes, 0, reserve_size);
466 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
474 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
478 wimlib_assert(res_expected_size != 0);
480 if (ctx->compressor != NULL) {
481 ret = begin_chunk_table(ctx, res_expected_size);
486 /* Output file descriptor is now positioned at the offset at which to
487 * write the first chunk of the resource. */
488 ctx->chunks_start_offset = ctx->out_fd->offset;
489 ctx->cur_write_res_offset = 0;
490 ctx->cur_write_res_size = res_expected_size;
495 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
496 u64 *res_start_offset_ret, u64 *res_store_size_ret)
498 size_t actual_num_chunks;
499 size_t actual_num_chunk_entries;
500 size_t chunk_entry_size;
503 actual_num_chunks = ctx->chunk_index;
504 actual_num_chunk_entries = actual_num_chunks;
505 if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
506 actual_num_chunk_entries--;
508 chunk_entry_size = get_chunk_entry_size(res_actual_size);
510 typedef le64 __attribute__((may_alias)) aliased_le64_t;
511 typedef le32 __attribute__((may_alias)) aliased_le32_t;
513 if (chunk_entry_size == 4) {
514 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
516 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
517 for (size_t i = 0; i < actual_num_chunk_entries; i++)
518 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
520 u32 offset = ctx->chunk_csizes[0];
521 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
522 u32 next_size = ctx->chunk_csizes[i + 1];
523 entries[i] = cpu_to_le32(offset);
528 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
530 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
531 for (size_t i = 0; i < actual_num_chunk_entries; i++)
532 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
534 u64 offset = ctx->chunk_csizes[0];
535 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
536 u64 next_size = ctx->chunk_csizes[i + 1];
537 entries[i] = cpu_to_le64(offset);
543 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
544 u64 res_start_offset;
545 u64 res_end_offset = ctx->out_fd->offset;
547 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
548 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
551 res_end_offset = ctx->out_fd->offset;
552 res_start_offset = ctx->chunks_start_offset;
554 res_end_offset = ctx->out_fd->offset;
556 u64 chunk_table_offset;
558 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
560 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
561 struct alt_chunk_table_header_disk hdr;
563 hdr.res_usize = cpu_to_le64(res_actual_size);
564 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
565 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
567 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
568 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
569 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
571 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
572 chunk_table_offset - sizeof(hdr));
575 res_start_offset = chunk_table_offset - sizeof(hdr);
577 res_start_offset = chunk_table_offset;
580 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
581 chunk_table_size, chunk_table_offset);
586 *res_start_offset_ret = res_start_offset;
587 *res_store_size_ret = res_end_offset - res_start_offset;
592 ERROR_WITH_ERRNO("Write error");
596 /* Finish writing a WIM resource by writing or updating the chunk table (if not
597 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
599 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
603 u64 res_uncompressed_size;
604 u64 res_offset_in_wim;
606 wimlib_assert(ctx->cur_write_res_size == ctx->cur_write_res_offset);
607 res_uncompressed_size = ctx->cur_write_res_size;
609 if (ctx->compressor) {
610 ret = end_chunk_table(ctx, res_uncompressed_size,
611 &res_offset_in_wim, &res_size_in_wim);
615 res_offset_in_wim = ctx->chunks_start_offset;
616 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
618 out_reshdr->uncompressed_size = res_uncompressed_size;
619 out_reshdr->size_in_wim = res_size_in_wim;
620 out_reshdr->offset_in_wim = res_offset_in_wim;
621 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
622 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
626 /* Begin processing a stream for writing. */
628 write_stream_begin_read(struct wim_lookup_table_entry *lte,
629 bool is_partial_res, void *_ctx)
631 struct write_streams_ctx *ctx = _ctx;
634 wimlib_assert(lte->size > 0);
636 ctx->cur_read_res_offset = 0;
637 ctx->cur_read_res_size = lte->size;
639 /* As an optimization, we allow some streams to be "unhashed", meaning
640 * their SHA1 message digests are unknown. This is the case with
641 * streams that are added by scanning a directry tree with
642 * wimlib_add_image(), for example. Since WIM uses single-instance
643 * streams, we don't know whether such each such stream really need to
644 * written until it is actually checksummed, unless it has a unique
645 * size. In such cases we read and checksum the stream in this
646 * function, thereby advancing ahead of read_stream_list(), which will
647 * still provide the data again to write_stream_process_chunk(). This
648 * is okay because an unhashed stream cannot be in a WIM resource, which
649 * might be costly to decompress. */
650 ctx->stream_was_duplicate = false;
651 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
653 wimlib_assert(!is_partial_res);
654 wimlib_assert(ctx->lookup_table != NULL);
656 struct wim_lookup_table_entry *lte_new;
658 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
661 if (lte_new != lte) {
662 /* Duplicate stream detected. */
664 if (lte_new->will_be_in_output_wim ||
665 stream_filtered(lte_new, ctx->filter_ctx))
667 /* The duplicate stream is already being
668 * included in the output WIM, or it would be
669 * filtered out if it had been. Skip writing
670 * this stream (and reading it again) entirely,
671 * passing its output reference count to the
672 * duplicate stream in the former case. */
673 DEBUG("Discarding duplicate stream of "
674 "length %"PRIu64, lte->size);
675 do_write_streams_progress(&ctx->progress_data,
677 list_del(<e->write_streams_list);
678 list_del(<e->lookup_table_list);
679 if (lte_new->will_be_in_output_wim)
680 lte_new->out_refcnt += lte->out_refcnt;
681 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS)
682 ctx->cur_write_res_size -= lte->size;
683 free_lookup_table_entry(lte);
684 return BEGIN_STREAM_STATUS_SKIP_STREAM;
686 /* The duplicate stream can validly be written,
687 * but was not marked as such. Discard the
688 * current stream entry and use the duplicate,
689 * but actually freeing the current entry must
690 * wait until read_stream_list() has finished
691 * reading its data. */
692 DEBUG("Stream duplicate, but not already "
693 "selected for writing.");
694 list_replace(<e->write_streams_list,
695 <e_new->write_streams_list);
696 list_replace(<e->lookup_table_list,
697 <e_new->lookup_table_list);
698 lte_new->out_refcnt = lte->out_refcnt;
699 lte_new->will_be_in_output_wim = 1;
700 ctx->stream_was_duplicate = true;
705 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
709 /* Write the next chunk of (typically compressed) data to the output WIM,
710 * handling the writing of the chunk table. */
712 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
713 size_t csize, size_t usize)
717 if (ctx->cur_write_res_offset == 0 &&
718 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
720 /* Starting to write a new stream in non-packed mode. */
722 struct wim_lookup_table_entry *lte;
724 lte = list_entry(ctx->pending_streams.next,
725 struct wim_lookup_table_entry, write_streams_list);
727 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
728 int additional_reshdr_flags = 0;
729 if (ctx->compressor != NULL)
730 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
732 DEBUG("Writing pipable WIM stream header "
733 "(offset=%"PRIu64")", ctx->out_fd->offset);
735 ret = write_pwm_stream_header(lte, ctx->out_fd,
736 additional_reshdr_flags);
741 ret = begin_write_resource(ctx, lte->size);
746 if (ctx->compressor != NULL) {
747 /* Record the compresed chunk size. */
748 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
749 ctx->chunk_csizes[ctx->chunk_index++] = csize;
751 /* If writing a pipable WIM, before the chunk data write a chunk
752 * header that provides the compressed chunk size. */
753 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
754 struct pwm_chunk_hdr chunk_hdr = {
755 .compressed_size = cpu_to_le32(csize),
757 ret = full_write(ctx->out_fd, &chunk_hdr,
764 /* Write the chunk data. */
765 ret = full_write(ctx->out_fd, cchunk, csize);
769 ctx->cur_write_res_offset += usize;
771 if (ctx->cur_write_res_offset == ctx->cur_write_res_size &&
772 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
774 struct wim_lookup_table_entry *lte;
776 lte = list_entry(ctx->pending_streams.next,
777 struct wim_lookup_table_entry, write_streams_list);
778 wimlib_assert(ctx->cur_write_res_offset == lte->size);
780 /* Finished writing a stream in non-packed mode. */
782 do_write_streams_progress(&ctx->progress_data, lte, false);
784 ret = end_write_resource(ctx, <e->out_reshdr);
788 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
790 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
791 if (ctx->compressor != NULL)
792 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
794 list_del(<e->write_streams_list);
795 ctx->cur_write_res_offset = 0;
801 ERROR_WITH_ERRNO("Write error");
806 submit_chunk_for_compression(struct write_streams_ctx *ctx,
807 const void *chunk, size_t size)
809 /* While we are unable to submit the chunk for compression (due to too
810 * many chunks already outstanding), retrieve and write the next
811 * compressed chunk. */
812 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
819 bret = ctx->compressor->get_chunk(ctx->compressor,
820 &cchunk, &csize, &usize);
824 ret = write_chunk(ctx, cchunk, csize, usize);
831 /* Process the next chunk of data to be written to a WIM resource. */
833 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
835 struct write_streams_ctx *ctx = _ctx;
837 const u8 *chunkptr, *chunkend;
839 wimlib_assert(size != 0);
841 if (ctx->compressor == NULL) {
842 /* Write chunk uncompressed. */
843 ret = write_chunk(ctx, chunk, size, size);
846 ctx->cur_read_res_offset += size;
850 /* Submit the chunk for compression, but take into account that the
851 * @size the chunk was provided in may not correspond to the
852 * @out_chunk_size being used for compression. */
854 chunkend = chunkptr + size;
856 const u8 *resized_chunk;
857 size_t needed_chunk_size;
859 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
860 needed_chunk_size = ctx->out_chunk_size;
862 u64 res_bytes_remaining;
864 res_bytes_remaining = ctx->cur_read_res_size -
865 ctx->cur_read_res_offset;
866 needed_chunk_size = min(ctx->out_chunk_size,
867 ctx->chunk_buf_filled +
868 res_bytes_remaining);
871 if (ctx->chunk_buf_filled == 0 &&
872 chunkend - chunkptr >= needed_chunk_size)
874 /* No intermediate buffering needed. */
875 resized_chunk = chunkptr;
876 chunkptr += needed_chunk_size;
877 ctx->cur_read_res_offset += needed_chunk_size;
879 /* Intermediate buffering needed. */
880 size_t bytes_consumed;
882 bytes_consumed = min(chunkend - chunkptr,
883 needed_chunk_size - ctx->chunk_buf_filled);
885 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
886 chunkptr, bytes_consumed);
888 resized_chunk = ctx->chunk_buf;
890 chunkptr += bytes_consumed;
891 ctx->cur_read_res_offset += bytes_consumed;
892 ctx->chunk_buf_filled += bytes_consumed;
893 if (ctx->chunk_buf_filled == needed_chunk_size) {
894 resized_chunk = ctx->chunk_buf;
895 ctx->chunk_buf_filled = 0;
902 ret = submit_chunk_for_compression(ctx, resized_chunk,
907 } while (chunkptr != chunkend);
911 /* Finish processing a stream for writing. It may not have been completely
912 * written yet, as the chunk_compressor implementation may still have chunks
913 * buffered or being compressed. */
915 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
917 struct write_streams_ctx *ctx = _ctx;
919 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
920 if (ctx->stream_was_duplicate) {
921 free_lookup_table_entry(lte);
922 } else if (lte->unhashed && ctx->lookup_table != NULL) {
923 list_del(<e->unhashed_list);
924 lookup_table_insert(ctx->lookup_table, lte);
930 /* Compute statistics about a list of streams that will be written.
932 * Assumes the streams are sorted such that all streams located in each distinct
933 * WIM (specified by WIMStruct) are together. */
935 compute_stream_list_stats(struct list_head *stream_list,
936 struct write_streams_ctx *ctx)
938 struct wim_lookup_table_entry *lte;
942 WIMStruct *prev_wim_part = NULL;
944 list_for_each_entry(lte, stream_list, write_streams_list) {
946 total_bytes += lte->size;
947 if (lte->resource_location == RESOURCE_IN_WIM) {
948 if (prev_wim_part != lte->rspec->wim) {
949 prev_wim_part = lte->rspec->wim;
954 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
955 ctx->progress_data.progress.write_streams.total_streams = num_streams;
956 ctx->progress_data.progress.write_streams.completed_bytes = 0;
957 ctx->progress_data.progress.write_streams.completed_streams = 0;
958 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
959 ctx->progress_data.progress.write_streams.total_parts = total_parts;
960 ctx->progress_data.progress.write_streams.completed_parts = 0;
961 ctx->progress_data.next_progress = 0;
962 ctx->progress_data.prev_wim_part = NULL;
965 /* Find streams in @stream_list that can be copied to the output WIM in raw form
966 * rather than compressed. Delete these streams from @stream_list, and move one
967 * per resource to @raw_copy_resources. Return the total uncompressed size of
968 * the streams that need to be compressed. */
970 find_raw_copy_resources(struct list_head *stream_list,
971 int write_resource_flags,
974 struct list_head *raw_copy_resources)
976 struct wim_lookup_table_entry *lte, *tmp;
977 u64 num_bytes_to_compress = 0;
979 INIT_LIST_HEAD(raw_copy_resources);
981 /* Initialize temporary raw_copy_ok flag. */
982 list_for_each_entry(lte, stream_list, write_streams_list)
983 if (lte->resource_location == RESOURCE_IN_WIM)
984 lte->rspec->raw_copy_ok = 0;
986 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
987 if (lte->resource_location == RESOURCE_IN_WIM &&
988 lte->rspec->raw_copy_ok)
990 list_del(<e->write_streams_list);
991 } else if (can_raw_copy(lte, write_resource_flags,
992 out_ctype, out_chunk_size))
994 lte->rspec->raw_copy_ok = 1;
995 list_move_tail(<e->write_streams_list,
998 num_bytes_to_compress += lte->size;
1002 return num_bytes_to_compress;
1005 /* Copy a raw compressed resource located in another WIM file to the WIM file
1008 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1009 struct filedes *out_fd)
1011 u64 cur_read_offset;
1012 u64 end_read_offset;
1013 u8 buf[BUFFER_SIZE];
1014 size_t bytes_to_read;
1016 struct filedes *in_fd;
1017 struct wim_lookup_table_entry *lte;
1018 u64 out_offset_in_wim;
1020 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1021 "uncompressed_size=%"PRIu64")",
1022 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1024 /* Copy the raw data. */
1025 cur_read_offset = in_rspec->offset_in_wim;
1026 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1028 out_offset_in_wim = out_fd->offset;
1030 if (in_rspec->is_pipable) {
1031 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1032 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1033 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1034 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1036 in_fd = &in_rspec->wim->in_fd;
1037 while (cur_read_offset != end_read_offset) {
1039 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1041 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1045 ret = full_write(out_fd, buf, bytes_to_read);
1049 cur_read_offset += bytes_to_read;
1052 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1053 if (lte->will_be_in_output_wim) {
1054 stream_set_out_reshdr_for_reuse(lte);
1055 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1056 lte->out_res_offset_in_wim = out_offset_in_wim;
1058 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1065 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1066 * file being written. */
1068 write_raw_copy_resources(struct list_head *raw_copy_resources,
1069 struct filedes *out_fd)
1071 struct wim_lookup_table_entry *lte;
1074 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1075 ret = write_raw_copy_resource(lte->rspec, out_fd);
1082 /* Wait for and write all chunks pending in the compressor. */
1084 finish_remaining_chunks(struct write_streams_ctx *ctx)
1091 if (ctx->compressor == NULL)
1094 if (ctx->chunk_buf_filled != 0) {
1095 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1096 ctx->chunk_buf_filled);
1101 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1102 ret = write_chunk(ctx, cdata, csize, usize);
1110 remove_zero_length_streams(struct list_head *stream_list)
1112 struct wim_lookup_table_entry *lte, *tmp;
1114 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1115 wimlib_assert(lte->will_be_in_output_wim);
1116 if (lte->size == 0) {
1117 list_del(<e->write_streams_list);
1118 lte->out_reshdr.offset_in_wim = 0;
1119 lte->out_reshdr.size_in_wim = 0;
1120 lte->out_reshdr.uncompressed_size = 0;
1121 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1127 write_stream_list(struct list_head *stream_list,
1128 struct filedes *out_fd,
1129 int write_resource_flags,
1132 unsigned num_threads,
1133 struct wim_lookup_table *lookup_table,
1134 struct filter_context *filter_ctx,
1135 struct wimlib_lzx_context **comp_ctx,
1136 wimlib_progress_func_t progress_func)
1139 struct write_streams_ctx ctx;
1140 struct list_head raw_copy_resources;
1142 remove_zero_length_streams(stream_list);
1144 if (list_empty(stream_list)) {
1145 DEBUG("No streams to write.");
1149 memset(&ctx, 0, sizeof(ctx));
1151 /* Pre-sorting the streams is required for compute_stream_list_stats().
1152 * Afterwards, read_stream_list() need not sort them again. */
1153 ret = sort_stream_list_by_sequential_order(stream_list,
1154 offsetof(struct wim_lookup_table_entry,
1155 write_streams_list));
1159 ctx.out_fd = out_fd;
1160 ctx.lookup_table = lookup_table;
1161 ctx.out_ctype = out_ctype;
1162 ctx.out_chunk_size = out_chunk_size;
1163 ctx.write_resource_flags = write_resource_flags;
1164 ctx.filter_ctx = filter_ctx;
1166 if (out_chunk_size <= STACK_MAX) {
1167 ctx.chunk_buf = alloca(out_chunk_size);
1169 ctx.chunk_buf = MALLOC(out_chunk_size);
1170 if (ctx.chunk_buf == NULL) {
1171 ret = WIMLIB_ERR_NOMEM;
1172 goto out_destroy_context;
1175 ctx.chunk_buf_filled = 0;
1177 compute_stream_list_stats(stream_list, &ctx);
1179 ctx.progress_data.progress_func = progress_func;
1181 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1182 write_resource_flags,
1185 &raw_copy_resources);
1187 DEBUG("Writing stream list "
1188 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1189 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1190 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1191 out_fd->offset, write_resource_flags,
1192 out_ctype, out_chunk_size, num_threads,
1193 ctx.progress_data.progress.write_streams.total_bytes,
1194 ctx.num_bytes_to_compress);
1196 if (ctx.num_bytes_to_compress == 0) {
1197 DEBUG("No compression needed; skipping to raw copy!");
1198 goto out_write_raw_copy_resources;
1201 /* Unless uncompressed output was required, allocate a chunk_compressor
1202 * to do compression. There are serial and parallel implementations of
1203 * the chunk_compressor interface. We default to parallel using the
1204 * specified number of threads, unless the upper bound on the number
1205 * bytes needing to be compressed is less 2000000 (heuristic value). */
1206 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1208 if (ctx.num_bytes_to_compress >= 2000000) {
1209 ret = new_parallel_chunk_compressor(out_ctype,
1214 DEBUG("Couldn't create parallel chunk compressor "
1215 "(status %d)", ret);
1219 if (ctx.compressor == NULL) {
1220 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1221 ret = wimlib_lzx_alloc_context(out_chunk_size,
1225 goto out_destroy_context;
1227 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1228 *comp_ctx, &ctx.compressor);
1230 goto out_destroy_context;
1235 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1237 ctx.progress_data.progress.write_streams.num_threads = 1;
1239 DEBUG("Actually using %u threads",
1240 ctx.progress_data.progress.write_streams.num_threads);
1242 INIT_LIST_HEAD(&ctx.pending_streams);
1244 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1245 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1247 goto out_destroy_context;
1250 /* Read the list of streams needing to be compressed, using the
1251 * specified callbacks to execute processing of the data. */
1253 struct read_stream_list_callbacks cbs = {
1254 .begin_stream = write_stream_begin_read,
1255 .begin_stream_ctx = &ctx,
1256 .consume_chunk = write_stream_process_chunk,
1257 .consume_chunk_ctx = &ctx,
1258 .end_stream = write_stream_end_read,
1259 .end_stream_ctx = &ctx,
1262 ret = read_stream_list(stream_list,
1263 offsetof(struct wim_lookup_table_entry, write_streams_list),
1265 STREAM_LIST_ALREADY_SORTED |
1266 VERIFY_STREAM_HASHES |
1267 COMPUTE_MISSING_STREAM_HASHES);
1270 goto out_destroy_context;
1272 ret = finish_remaining_chunks(&ctx);
1274 goto out_destroy_context;
1276 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1277 struct wim_reshdr reshdr;
1278 struct wim_lookup_table_entry *lte;
1281 ret = end_write_resource(&ctx, &reshdr);
1283 goto out_destroy_context;
1285 DEBUG("Ending packed resource: %lu %lu %lu.",
1286 reshdr.offset_in_wim,
1288 reshdr.uncompressed_size);
1291 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1292 lte->out_reshdr.size_in_wim = lte->size;
1293 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1294 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1295 lte->out_reshdr.uncompressed_size = 0;
1296 lte->out_reshdr.offset_in_wim = offset_in_res;
1297 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1298 lte->out_res_size_in_wim = reshdr.size_in_wim;
1299 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1300 offset_in_res += lte->size;
1302 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1305 out_write_raw_copy_resources:
1306 /* Copy any compressed resources for which the raw data can be reused
1307 * without decompression. */
1308 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd);
1310 out_destroy_context:
1311 if (out_chunk_size > STACK_MAX)
1312 FREE(ctx.chunk_buf);
1313 FREE(ctx.chunk_csizes);
1315 ctx.compressor->destroy(ctx.compressor);
1316 DEBUG("Done (ret=%d)", ret);
1321 write_wim_resource(struct wim_lookup_table_entry *lte,
1322 struct filedes *out_fd,
1325 int write_resource_flags,
1326 struct wimlib_lzx_context **comp_ctx)
1328 LIST_HEAD(stream_list);
1329 list_add(<e->write_streams_list, &stream_list);
1330 lte->will_be_in_output_wim = 1;
1331 return write_stream_list(&stream_list,
1333 write_resource_flags & ~WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS,
1344 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1345 int reshdr_flags, struct filedes *out_fd,
1348 struct wim_reshdr *out_reshdr,
1350 int write_resource_flags,
1351 struct wimlib_lzx_context **comp_ctx)
1354 struct wim_lookup_table_entry *lte;
1356 /* Set up a temporary lookup table entry to provide to
1357 * write_wim_resource(). */
1359 lte = new_lookup_table_entry();
1361 return WIMLIB_ERR_NOMEM;
1363 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1364 lte->attached_buffer = (void*)buf;
1365 lte->size = buf_size;
1366 lte->flags = reshdr_flags;
1368 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
1369 sha1_buffer(buf, buf_size, lte->hash);
1375 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1376 write_resource_flags, comp_ctx);
1380 copy_reshdr(out_reshdr, <e->out_reshdr);
1383 copy_hash(hash, lte->hash);
1386 lte->resource_location = RESOURCE_NONEXISTENT;
1387 free_lookup_table_entry(lte);
1391 struct stream_size_table {
1392 struct hlist_head *array;
1398 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1400 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1401 if (tab->array == NULL)
1402 return WIMLIB_ERR_NOMEM;
1403 tab->num_entries = 0;
1404 tab->capacity = capacity;
1409 destroy_stream_size_table(struct stream_size_table *tab)
1415 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1417 struct stream_size_table *tab = _tab;
1419 struct wim_lookup_table_entry *same_size_lte;
1420 struct hlist_node *tmp;
1422 pos = hash_u64(lte->size) % tab->capacity;
1423 lte->unique_size = 1;
1424 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1425 if (same_size_lte->size == lte->size) {
1426 lte->unique_size = 0;
1427 same_size_lte->unique_size = 0;
1432 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1437 struct find_streams_ctx {
1440 struct list_head stream_list;
1441 struct stream_size_table stream_size_tab;
1445 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1446 struct list_head *stream_list, u32 nref)
1448 if (!lte->will_be_in_output_wim) {
1449 lte->out_refcnt = 0;
1450 list_add_tail(<e->write_streams_list, stream_list);
1451 lte->will_be_in_output_wim = 1;
1453 lte->out_refcnt += nref;
1457 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1460 struct list_head *stream_list = _stream_list;
1461 lte->will_be_in_output_wim = 0;
1462 reference_stream_for_write(lte, stream_list, lte->refcnt);
1467 inode_find_streams_to_reference(const struct wim_inode *inode,
1468 const struct wim_lookup_table *table,
1469 struct list_head *stream_list)
1471 struct wim_lookup_table_entry *lte;
1474 wimlib_assert(inode->i_nlink > 0);
1476 for (i = 0; i <= inode->i_num_ads; i++) {
1477 lte = inode_stream_lte(inode, i, table);
1479 reference_stream_for_write(lte, stream_list,
1481 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1482 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1488 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1490 lte->will_be_in_output_wim = 0;
1495 image_find_streams_to_reference(WIMStruct *wim)
1497 struct wim_image_metadata *imd;
1498 struct wim_inode *inode;
1499 struct wim_lookup_table_entry *lte;
1500 struct list_head *stream_list;
1503 imd = wim_get_current_image_metadata(wim);
1505 image_for_each_unhashed_stream(lte, imd)
1506 lte->will_be_in_output_wim = 0;
1508 stream_list = wim->private;
1509 image_for_each_inode(inode, imd) {
1510 ret = inode_find_streams_to_reference(inode,
1520 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1523 struct list_head *stream_list_ret)
1527 INIT_LIST_HEAD(stream_list_ret);
1529 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1530 (image == 1 && wim->hdr.image_count == 1)))
1532 /* Fast case: Assume that all streams are being written and
1533 * that the reference counts are correct. */
1534 struct wim_lookup_table_entry *lte;
1535 struct wim_image_metadata *imd;
1538 for_lookup_table_entry(wim->lookup_table,
1539 fully_reference_stream_for_write,
1542 for (i = 0; i < wim->hdr.image_count; i++) {
1543 imd = wim->image_metadata[i];
1544 image_for_each_unhashed_stream(lte, imd)
1545 fully_reference_stream_for_write(lte, stream_list_ret);
1548 /* Slow case: Walk through the images being written and
1549 * determine the streams referenced. */
1550 for_lookup_table_entry(wim->lookup_table,
1551 do_stream_set_not_in_output_wim, NULL);
1552 wim->private = stream_list_ret;
1553 ret = for_image(wim, image, image_find_streams_to_reference);
1561 struct insert_other_if_hard_filtered_ctx {
1562 struct stream_size_table *tab;
1563 struct filter_context *filter_ctx;
1567 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1569 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1571 if (!lte->will_be_in_output_wim &&
1572 stream_hard_filtered(lte, ctx->filter_ctx))
1573 stream_size_table_insert(lte, ctx->tab);
1578 determine_stream_size_uniquity(struct list_head *stream_list,
1579 struct wim_lookup_table *lt,
1580 struct filter_context *filter_ctx)
1583 struct stream_size_table tab;
1584 struct wim_lookup_table_entry *lte;
1586 ret = init_stream_size_table(&tab, lt->capacity);
1590 if (may_hard_filter_streams(filter_ctx)) {
1591 struct insert_other_if_hard_filtered_ctx ctx = {
1593 .filter_ctx = filter_ctx,
1595 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1598 list_for_each_entry(lte, stream_list, write_streams_list)
1599 stream_size_table_insert(lte, &tab);
1601 destroy_stream_size_table(&tab);
1606 filter_stream_list_for_write(struct list_head *stream_list,
1607 struct filter_context *filter_ctx)
1609 struct wim_lookup_table_entry *lte, *tmp;
1611 list_for_each_entry_safe(lte, tmp,
1612 stream_list, write_streams_list)
1614 int status = stream_filtered(lte, filter_ctx);
1621 /* Soft filtered. */
1623 /* Hard filtered. */
1624 lte->will_be_in_output_wim = 0;
1625 list_del(<e->lookup_table_list);
1627 list_del(<e->write_streams_list);
1633 * prepare_stream_list_for_write() -
1635 * Prepare the list of streams to write for writing a WIM containing the
1636 * specified image(s) with the specified write flags.
1639 * The WIMStruct on whose behalf the write is occurring.
1642 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1645 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1647 * STREAMS_OK: For writes of all images, assume that all streams in the
1648 * lookup table of @wim and the per-image lists of unhashed streams should
1649 * be taken as-is, and image metadata should not be searched for
1650 * references. This does not exclude filtering with OVERWRITE and
1651 * SKIP_EXTERNAL_WIMS, below.
1653 * OVERWRITE: Streams already present in @wim shall not be returned in
1656 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1657 * @wim, shall be be returned in neither @stream_list_ret nor
1658 * @lookup_table_list_ret.
1661 * List of streams, linked by write_streams_list, that need to be written
1662 * will be returned here.
1664 * Note that this function assumes that unhashed streams will be written;
1665 * it does not take into account that they may become duplicates when
1668 * @lookup_table_list_ret
1669 * List of streams, linked by lookup_table_list, that need to be included
1670 * in the WIM's lookup table will be returned here. This will be a
1671 * superset of the streams in @stream_list_ret.
1673 * This list will be a proper superset of @stream_list_ret if and only if
1674 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1675 * the streams that would otherwise need to be written were already located
1678 * All streams in this list will have @out_refcnt set to the number of
1679 * references to the stream in the output WIM. If
1680 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1681 * may be as low as 0.
1684 * A context for queries of stream filter status with stream_filtered() is
1685 * returned in this location.
1687 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1688 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1689 * lookup table of @wim not inserted into @lookup_table_list_ret.
1691 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1692 * @stream_list_ret that have unique size among all stream entries in
1693 * @stream_list_ret and among all stream entries in the lookup table of @wim
1694 * that are ineligible for being written due to filtering.
1696 * Returns 0 on success; nonzero on read error, memory allocation error, or
1700 prepare_stream_list_for_write(WIMStruct *wim, int image,
1702 struct list_head *stream_list_ret,
1703 struct list_head *lookup_table_list_ret,
1704 struct filter_context *filter_ctx_ret)
1707 struct wim_lookup_table_entry *lte;
1709 filter_ctx_ret->write_flags = write_flags;
1710 filter_ctx_ret->wim = wim;
1712 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1715 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1720 INIT_LIST_HEAD(lookup_table_list_ret);
1721 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1722 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1724 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1729 if (may_filter_streams(filter_ctx_ret))
1730 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1736 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1737 unsigned num_threads,
1738 wimlib_progress_func_t progress_func,
1739 struct list_head *stream_list_override,
1740 struct list_head *lookup_table_list_ret)
1743 struct list_head _stream_list;
1744 struct list_head *stream_list;
1745 struct wim_lookup_table_entry *lte;
1746 struct filter_context _filter_ctx;
1747 struct filter_context *filter_ctx;
1749 if (stream_list_override == NULL) {
1750 /* Normal case: prepare stream list from image(s) being written.
1752 stream_list = &_stream_list;
1753 filter_ctx = &_filter_ctx;
1754 ret = prepare_stream_list_for_write(wim, image, write_flags,
1756 lookup_table_list_ret,
1761 /* Currently only as a result of wimlib_split() being called:
1762 * use stream list already explicitly provided. Use existing
1763 * reference counts. */
1764 stream_list = stream_list_override;
1766 INIT_LIST_HEAD(lookup_table_list_ret);
1767 list_for_each_entry(lte, stream_list, write_streams_list) {
1768 lte->out_refcnt = lte->refcnt;
1769 lte->will_be_in_output_wim = 1;
1770 lte->unique_size = 0;
1771 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1775 return write_stream_list(stream_list,
1777 write_flags_to_resource_flags(write_flags),
1778 wim->out_compression_type,
1779 wim->out_chunk_size,
1788 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1789 wimlib_progress_func_t progress_func)
1794 int write_resource_flags;
1796 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1797 DEBUG("Not writing any metadata resources.");
1801 write_resource_flags = write_flags_to_resource_flags(write_flags);
1803 write_resource_flags &= ~WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS;
1805 DEBUG("Writing metadata resources (offset=%"PRIu64")",
1806 wim->out_fd.offset);
1809 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1811 if (image == WIMLIB_ALL_IMAGES) {
1813 end_image = wim->hdr.image_count;
1815 start_image = image;
1819 for (int i = start_image; i <= end_image; i++) {
1820 struct wim_image_metadata *imd;
1822 imd = wim->image_metadata[i - 1];
1823 /* Build a new metadata resource only if image was modified from
1824 * the original (or was newly added). Otherwise just copy the
1826 if (imd->modified) {
1827 DEBUG("Image %u was modified; building and writing new "
1828 "metadata resource", i);
1829 ret = write_metadata_resource(wim, i,
1830 write_resource_flags);
1831 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1832 DEBUG("Image %u was not modified; re-using existing "
1833 "metadata resource.", i);
1834 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
1837 DEBUG("Image %u was not modified; copying existing "
1838 "metadata resource.", i);
1839 ret = write_wim_resource(imd->metadata_lte,
1841 wim->out_compression_type,
1842 wim->out_chunk_size,
1843 write_resource_flags,
1850 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1855 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
1858 DEBUG("Opening \"%"TS"\" for writing.", path);
1860 raw_fd = topen(path, open_flags | O_BINARY, 0644);
1862 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
1863 return WIMLIB_ERR_OPEN;
1865 filedes_init(&wim->out_fd, raw_fd);
1870 close_wim_writable(WIMStruct *wim, int write_flags)
1874 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
1875 DEBUG("Closing WIM file.");
1876 if (filedes_valid(&wim->out_fd))
1877 if (filedes_close(&wim->out_fd))
1878 ret = WIMLIB_ERR_WRITE;
1880 filedes_invalidate(&wim->out_fd);
1885 cmp_streams_by_out_rspec(const void *p1, const void *p2)
1887 const struct wim_lookup_table_entry *lte1, *lte2;
1889 lte1 = *(const struct wim_lookup_table_entry**)p1;
1890 lte2 = *(const struct wim_lookup_table_entry**)p2;
1892 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1893 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1894 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
1895 return cmp_u64(lte1->out_res_offset_in_wim,
1896 lte2->out_res_offset_in_wim);
1901 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1904 return cmp_u64(lte1->out_reshdr.offset_in_wim,
1905 lte2->out_reshdr.offset_in_wim);
1909 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
1910 struct wim_reshdr *out_reshdr,
1911 struct list_head *lookup_table_list)
1915 /* Set output resource metadata for streams already present in WIM. */
1916 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1917 struct wim_lookup_table_entry *lte;
1918 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
1920 if (lte->resource_location == RESOURCE_IN_WIM &&
1921 lte->rspec->wim == wim)
1923 stream_set_out_reshdr_for_reuse(lte);
1928 ret = sort_stream_list(lookup_table_list,
1929 offsetof(struct wim_lookup_table_entry, lookup_table_list),
1930 cmp_streams_by_out_rspec);
1934 /* Add entries for metadata resources. */
1935 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
1939 if (image == WIMLIB_ALL_IMAGES) {
1941 end_image = wim->hdr.image_count;
1943 start_image = image;
1947 /* Push metadata resource lookup table entries onto the front of
1948 * the list in reverse order, so that they're written in order.
1950 for (int i = end_image; i >= start_image; i--) {
1951 struct wim_lookup_table_entry *metadata_lte;
1953 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
1954 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
1955 metadata_lte->out_refcnt = 1;
1956 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
1960 return write_wim_lookup_table_from_stream_list(lookup_table_list,
1962 wim->hdr.part_number,
1964 write_flags_to_resource_flags(write_flags),
1971 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1972 * table, then overwrite the WIM header. By default, closes the WIM file
1973 * descriptor (@wim->out_fd) if successful.
1975 * write_flags is a bitwise OR of the following:
1977 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1978 * Include an integrity table.
1980 * (public) WIMLIB_WRITE_FLAG_FSYNC:
1981 * fsync() the output file before closing it.
1983 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
1984 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
1985 * stream headers before the lookup table and XML data, and also
1986 * write the WIM header at the end instead of seeking to the
1987 * beginning. Can't be combined with
1988 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
1990 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1991 * Don't write the lookup table.
1993 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1994 * When (if) writing the integrity table, re-use entries from the
1995 * existing integrity table, if possible.
1997 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1998 * After writing the XML data but before writing the integrity
1999 * table, write a temporary WIM header and flush the stream so that
2000 * the WIM is less likely to become corrupted upon abrupt program
2002 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2003 * Instead of overwriting the WIM header at the beginning of the
2004 * file, simply append it to the end of the file. (Used when
2006 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2007 * Do not close the file descriptor @wim->out_fd on either success
2009 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2010 * Use the existing <TOTALBYTES> stored in the in-memory XML
2011 * information, rather than setting it to the offset of the XML
2012 * data being written.
2015 finish_write(WIMStruct *wim, int image, int write_flags,
2016 wimlib_progress_func_t progress_func,
2017 struct list_head *lookup_table_list)
2021 int write_resource_flags;
2022 off_t old_lookup_table_end;
2023 off_t new_lookup_table_end;
2026 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2028 write_resource_flags = write_flags_to_resource_flags(write_flags);
2030 /* In the WIM header, there is room for the resource entry for a
2031 * metadata resource labeled as the "boot metadata". This entry should
2032 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2033 * it should be a copy of the resource entry for the image that is
2034 * marked as bootable. This is not well documented... */
2035 if (wim->hdr.boot_idx == 0) {
2036 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2038 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2039 &wim->image_metadata[
2040 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2043 /* Write lookup table. (Save old position first.) */
2044 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2045 wim->hdr.lookup_table_reshdr.size_in_wim;
2046 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2047 ret = write_wim_lookup_table(wim, image, write_flags,
2048 &wim->hdr.lookup_table_reshdr,
2054 /* Write XML data. */
2055 xml_totalbytes = wim->out_fd.offset;
2056 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2057 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2058 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2059 &wim->hdr.xml_data_reshdr,
2060 write_resource_flags);
2064 /* Write integrity table (optional). */
2065 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2066 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2067 struct wim_header checkpoint_hdr;
2068 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2069 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2070 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2071 ret = write_wim_header_at_offset(&checkpoint_hdr,
2077 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2078 old_lookup_table_end = 0;
2080 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2081 wim->hdr.lookup_table_reshdr.size_in_wim;
2083 ret = write_integrity_table(wim,
2084 new_lookup_table_end,
2085 old_lookup_table_end,
2090 /* No integrity table. */
2091 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2094 /* Now that all information in the WIM header has been determined, the
2095 * preliminary header written earlier can be overwritten, the header of
2096 * the existing WIM file can be overwritten, or the final header can be
2097 * written to the end of the pipable WIM. */
2098 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2100 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2101 hdr_offset = wim->out_fd.offset;
2102 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2103 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2107 /* Possibly sync file data to disk before closing. On POSIX systems, it
2108 * is necessary to do this before using rename() to overwrite an
2109 * existing file with a new file. Otherwise, data loss would occur if
2110 * the system is abruptly terminated when the metadata for the rename
2111 * operation has been written to disk, but the new file data has not.
2113 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2114 DEBUG("Syncing WIM file.");
2115 if (fsync(wim->out_fd.fd)) {
2116 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2117 return WIMLIB_ERR_WRITE;
2121 if (close_wim_writable(wim, write_flags)) {
2122 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2123 return WIMLIB_ERR_WRITE;
2129 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2131 lock_wim(WIMStruct *wim, int fd)
2134 if (fd != -1 && !wim->wim_locked) {
2135 ret = flock(fd, LOCK_EX | LOCK_NB);
2137 if (errno == EWOULDBLOCK) {
2138 ERROR("`%"TS"' is already being modified or has been "
2139 "mounted read-write\n"
2140 " by another process!", wim->filename);
2141 ret = WIMLIB_ERR_ALREADY_LOCKED;
2143 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2148 wim->wim_locked = 1;
2156 * write_pipable_wim():
2158 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2159 * capable of being applied from a pipe).
2161 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2162 * images can be applied from them sequentially when the file data is sent over
2163 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2164 * The modifications made to the WIM format for pipable WIMs are:
2166 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2167 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2168 * stops other software from trying to read the file as a normal WIM.
2170 * - The header at the beginning of the file does not contain all the normal
2171 * information; in particular it will have all 0's for the lookup table and
2172 * XML data resource entries. This is because this information cannot be
2173 * determined until the lookup table and XML data have been written.
2174 * Consequently, wimlib will write the full header at the very end of the
2175 * file. The header at the end, however, is only used when reading the WIM
2176 * from a seekable file (not a pipe).
2178 * - An extra copy of the XML data is placed directly after the header. This
2179 * allows image names and sizes to be determined at an appropriate time when
2180 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2181 * WIM is read from a seekable file (not a pipe).
2183 * - The format of resources, or streams, has been modified to allow them to be
2184 * used before the "lookup table" has been read. Each stream is prefixed with
2185 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2186 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2187 * uncompressed stream size, and flags that indicate whether the stream is
2188 * compressed. The data of uncompressed streams then follows literally, while
2189 * the data of compressed streams follows in a modified format. Compressed
2190 * streams do not begin with a chunk table, since the chunk table cannot be
2191 * written until all chunks have been compressed. Instead, each compressed
2192 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2193 * Furthermore, the chunk table is written at the end of the resource instead
2194 * of the start. Note: chunk offsets are given in the chunk table as if the
2195 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2196 * used if the WIM is being read from a seekable file (not a pipe).
2198 * - Metadata resources always come before other file resources (streams).
2199 * (This does not by itself constitute an incompatibility with normal WIMs,
2200 * since this is valid in normal WIMs.)
2202 * - At least up to the end of the file resources, all components must be packed
2203 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2204 * not by itself consititute an incompatibility with normal WIMs, since this
2205 * is valid in normal WIMs.)
2207 * Note: the lookup table, XML data, and header at the end are not used when
2208 * applying from a pipe. They exist to support functionality such as image
2209 * application and export when the WIM is *not* read from a pipe.
2211 * Layout of pipable WIM:
2213 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2214 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2215 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2217 * Layout of normal WIM:
2219 * +--------+-----------------------------+-------------------------+
2220 * | Header | File and metadata resources | Lookup table | XML data |
2221 * +--------+-----------------------------+-------------------------+
2223 * An optional integrity table can follow the final XML data in both normal and
2224 * pipable WIMs. However, due to implementation details, wimlib currently can
2225 * only include an integrity table in a pipable WIM when writing it to a
2226 * seekable file (not a pipe).
2228 * Do note that since pipable WIMs are not supported by Microsoft's software,
2229 * wimlib does not create them unless explicitly requested (with
2230 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2231 * characters to identify the file.
2234 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2235 unsigned num_threads, wimlib_progress_func_t progress_func,
2236 struct list_head *stream_list_override,
2237 struct list_head *lookup_table_list_ret)
2240 struct wim_reshdr xml_reshdr;
2242 WARNING("Creating a pipable WIM, which will "
2244 " with Microsoft's software (wimgapi/imagex/Dism).");
2246 /* At this point, the header at the beginning of the file has already
2249 /* For efficiency, when wimlib adds an image to the WIM with
2250 * wimlib_add_image(), the SHA1 message digests of files is not
2251 * calculated; instead, they are calculated while the files are being
2252 * written. However, this does not work when writing a pipable WIM,
2253 * since when writing a stream to a pipable WIM, its SHA1 message digest
2254 * needs to be known before the stream data is written. Therefore,
2255 * before getting much farther, we need to pre-calculate the SHA1
2256 * message digests of all streams that will be written. */
2257 ret = wim_checksum_unhashed_streams(wim);
2261 /* Write extra copy of the XML data. */
2262 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2264 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2268 /* Write metadata resources for the image(s) being included in the
2270 ret = write_wim_metadata_resources(wim, image, write_flags,
2275 /* Write streams needed for the image(s) being included in the output
2276 * WIM, or streams needed for the split WIM part. */
2277 return write_wim_streams(wim, image, write_flags, num_threads,
2278 progress_func, stream_list_override,
2279 lookup_table_list_ret);
2281 /* The lookup table, XML data, and header at end are handled by
2282 * finish_write(). */
2285 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2288 write_wim_part(WIMStruct *wim,
2289 const void *path_or_fd,
2292 unsigned num_threads,
2293 wimlib_progress_func_t progress_func,
2294 unsigned part_number,
2295 unsigned total_parts,
2296 struct list_head *stream_list_override,
2300 struct wim_header hdr_save;
2301 struct list_head lookup_table_list;
2303 if (total_parts == 1)
2304 DEBUG("Writing standalone WIM.");
2306 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2307 if (image == WIMLIB_ALL_IMAGES)
2308 DEBUG("Including all images.");
2310 DEBUG("Including image %d only.", image);
2311 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2312 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2314 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2315 DEBUG("Write flags: 0x%08x", write_flags);
2317 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2318 DEBUG("\tCHECK_INTEGRITY");
2320 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2323 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2324 DEBUG("\tRECOMPRESS");
2326 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2329 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2332 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2333 DEBUG("\tIGNORE_READONLY_FLAG");
2335 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2338 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2339 DEBUG("\tNOT_PIPABLE");
2341 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2342 DEBUG("\tPACK_STREAMS");
2344 if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2345 DEBUG("\tNO_PACK_STREAMS");
2347 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2348 DEBUG("\tFILE_DESCRIPTOR");
2350 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2351 DEBUG("\tNO_METADATA");
2353 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2354 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2356 if (num_threads == 0)
2357 DEBUG("Number of threads: autodetect");
2359 DEBUG("Number of threads: %u", num_threads);
2360 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2361 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2362 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2363 "specified" : "generate new"));
2365 /* Internally, this is always called with a valid part number and total
2367 wimlib_assert(total_parts >= 1);
2368 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2370 /* A valid image (or all images) must be specified. */
2371 if (image != WIMLIB_ALL_IMAGES &&
2372 (image < 1 || image > wim->hdr.image_count))
2373 return WIMLIB_ERR_INVALID_IMAGE;
2375 /* If we need to write metadata resources, make sure the ::WIMStruct has
2376 * the needed information attached (e.g. is not a resource-only WIM,
2377 * such as a non-first part of a split WIM). */
2378 if (!wim_has_metadata(wim) &&
2379 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2380 return WIMLIB_ERR_METADATA_NOT_FOUND;
2382 /* Check for contradictory flags. */
2383 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2384 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2385 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2386 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2387 return WIMLIB_ERR_INVALID_PARAM;
2389 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2390 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2391 == (WIMLIB_WRITE_FLAG_PIPABLE |
2392 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2393 return WIMLIB_ERR_INVALID_PARAM;
2395 if ((write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2396 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2397 == (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2398 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2399 return WIMLIB_ERR_INVALID_PARAM;
2401 /* Save previous header, then start initializing the new one. */
2402 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2404 /* Set default integrity, pipable, and packed stream flags. */
2405 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2406 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2407 if (wim_is_pipable(wim)) {
2408 DEBUG("WIM is pipable; default to PIPABLE.");
2409 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2412 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2413 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2414 if (wim_has_integrity_table(wim)) {
2415 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2416 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2419 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2420 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2421 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS) {
2422 DEBUG("WIM version 3584; default to PACK_STREAMS.");
2423 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2426 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2427 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2428 == (WIMLIB_WRITE_FLAG_PIPABLE |
2429 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2430 return WIMLIB_ERR_INVALID_PARAM;
2432 /* Set appropriate magic number. */
2433 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2434 wim->hdr.magic = PWM_MAGIC;
2436 wim->hdr.magic = WIM_MAGIC;
2438 /* Set appropriate version number. */
2439 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2440 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2442 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2444 /* Clear header flags that will be set automatically. */
2445 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2446 WIM_HDR_FLAG_RESOURCE_ONLY |
2447 WIM_HDR_FLAG_SPANNED |
2448 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2450 /* Set SPANNED header flag if writing part of a split WIM. */
2451 if (total_parts != 1)
2452 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2454 /* Set part number and total parts of split WIM. This will be 1 and 1
2455 * if the WIM is standalone. */
2456 wim->hdr.part_number = part_number;
2457 wim->hdr.total_parts = total_parts;
2459 /* Set compression type if different. */
2460 if (wim->compression_type != wim->out_compression_type) {
2461 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2462 wimlib_assert(ret == 0);
2465 /* Set chunk size if different. */
2466 wim->hdr.chunk_size = wim->out_chunk_size;
2468 /* Use GUID if specified; otherwise generate a new one. */
2470 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2471 else if (!wim->guid_set_explicitly)
2472 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2474 /* Clear references to resources that have not been written yet. */
2475 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2476 zero_reshdr(&wim->hdr.xml_data_reshdr);
2477 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2478 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2480 /* Set image count and boot index correctly for single image writes. */
2481 if (image != WIMLIB_ALL_IMAGES) {
2482 wim->hdr.image_count = 1;
2483 if (wim->hdr.boot_idx == image)
2484 wim->hdr.boot_idx = 1;
2486 wim->hdr.boot_idx = 0;
2489 /* Split WIMs can't be bootable. */
2490 if (total_parts != 1)
2491 wim->hdr.boot_idx = 0;
2493 /* Initialize output file descriptor. */
2494 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2495 /* File descriptor was explicitly provided. Return error if
2496 * file descriptor is not seekable, unless writing a pipable WIM
2498 wim->out_fd.fd = *(const int*)path_or_fd;
2499 wim->out_fd.offset = 0;
2500 if (!filedes_is_seekable(&wim->out_fd)) {
2501 ret = WIMLIB_ERR_INVALID_PARAM;
2502 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2503 goto out_restore_hdr;
2504 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2505 ERROR("Can't include integrity check when "
2506 "writing pipable WIM to pipe!");
2507 goto out_restore_hdr;
2512 /* Filename of WIM to write was provided; open file descriptor
2514 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2515 O_TRUNC | O_CREAT | O_RDWR);
2517 goto out_restore_hdr;
2520 /* Write initial header. This is merely a "dummy" header since it
2521 * doesn't have all the information yet, so it will be overwritten later
2522 * (unless writing a pipable WIM). */
2523 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2524 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2525 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2526 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2528 goto out_restore_hdr;
2530 /* Write metadata resources and streams. */
2531 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2532 /* Default case: create a normal (non-pipable) WIM. */
2533 ret = write_wim_streams(wim, image, write_flags, num_threads,
2534 progress_func, stream_list_override,
2535 &lookup_table_list);
2537 goto out_restore_hdr;
2539 ret = write_wim_metadata_resources(wim, image, write_flags,
2542 goto out_restore_hdr;
2544 /* Non-default case: create pipable WIM. */
2545 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2546 progress_func, stream_list_override,
2547 &lookup_table_list);
2549 goto out_restore_hdr;
2550 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2554 /* Write lookup table, XML data, and (optional) integrity table. */
2555 ret = finish_write(wim, image, write_flags, progress_func,
2556 &lookup_table_list);
2558 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2559 (void)close_wim_writable(wim, write_flags);
2560 DEBUG("ret=%d", ret);
2564 /* Write a standalone WIM to a file or file descriptor. */
2566 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2567 int image, int write_flags, unsigned num_threads,
2568 wimlib_progress_func_t progress_func)
2570 return write_wim_part(wim, path_or_fd, image, write_flags,
2571 num_threads, progress_func, 1, 1, NULL, NULL);
2574 /* API function documented in wimlib.h */
2576 wimlib_write(WIMStruct *wim, const tchar *path,
2577 int image, int write_flags, unsigned num_threads,
2578 wimlib_progress_func_t progress_func)
2581 return WIMLIB_ERR_INVALID_PARAM;
2583 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2585 return write_standalone_wim(wim, path, image, write_flags,
2586 num_threads, progress_func);
2589 /* API function documented in wimlib.h */
2591 wimlib_write_to_fd(WIMStruct *wim, int fd,
2592 int image, int write_flags, unsigned num_threads,
2593 wimlib_progress_func_t progress_func)
2596 return WIMLIB_ERR_INVALID_PARAM;
2598 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2599 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2601 return write_standalone_wim(wim, &fd, image, write_flags,
2602 num_threads, progress_func);
2606 any_images_modified(WIMStruct *wim)
2608 for (int i = 0; i < wim->hdr.image_count; i++)
2609 if (wim->image_metadata[i]->modified)
2615 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2617 const WIMStruct *wim = _wim;
2618 off_t end_offset = *(const off_t*)wim->private;
2620 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2621 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2622 return WIMLIB_ERR_RESOURCE_ORDER;
2626 /* Make sure no file or metadata resources are located after the XML data (or
2627 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2628 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2630 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2635 wim->private = &end_offset;
2636 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2640 for (i = 0; i < wim->hdr.image_count; i++) {
2641 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2649 * Overwrite a WIM, possibly appending streams to it.
2651 * A WIM looks like (or is supposed to look like) the following:
2653 * Header (212 bytes)
2654 * Streams and metadata resources (variable size)
2655 * Lookup table (variable size)
2656 * XML data (variable size)
2657 * Integrity table (optional) (variable size)
2659 * If we are not adding any streams or metadata resources, the lookup table is
2660 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2661 * header. This operation is potentially unsafe if the program is abruptly
2662 * terminated while the XML data or integrity table are being overwritten, but
2663 * before the new header has been written. To partially alleviate this problem,
2664 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2665 * finish_write() to cause a temporary WIM header to be written after the XML
2666 * data has been written. This may prevent the WIM from becoming corrupted if
2667 * the program is terminated while the integrity table is being calculated (but
2668 * no guarantees, due to write re-ordering...).
2670 * If we are adding new streams or images (metadata resources), the lookup table
2671 * needs to be changed, and those streams need to be written. In this case, we
2672 * try to perform a safe update of the WIM file by writing the streams *after*
2673 * the end of the previous WIM, then writing the new lookup table, XML data, and
2674 * (optionally) integrity table following the new streams. This will produce a
2675 * layout like the following:
2677 * Header (212 bytes)
2678 * (OLD) Streams and metadata resources (variable size)
2679 * (OLD) Lookup table (variable size)
2680 * (OLD) XML data (variable size)
2681 * (OLD) Integrity table (optional) (variable size)
2682 * (NEW) Streams and metadata resources (variable size)
2683 * (NEW) Lookup table (variable size)
2684 * (NEW) XML data (variable size)
2685 * (NEW) Integrity table (optional) (variable size)
2687 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2688 * the header is overwritten to point to the new lookup table, XML data, and
2689 * integrity table, to produce the following layout:
2691 * Header (212 bytes)
2692 * Streams and metadata resources (variable size)
2693 * Nothing (variable size)
2694 * More Streams and metadata resources (variable size)
2695 * Lookup table (variable size)
2696 * XML data (variable size)
2697 * Integrity table (optional) (variable size)
2699 * This method allows an image to be appended to a large WIM very quickly, and
2700 * is is crash-safe except in the case of write re-ordering, but the
2701 * disadvantage is that a small hole is left in the WIM where the old lookup
2702 * table, xml data, and integrity table were. (These usually only take up a
2703 * small amount of space compared to the streams, however.)
2706 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2707 unsigned num_threads,
2708 wimlib_progress_func_t progress_func)
2712 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2713 struct wim_header hdr_save;
2714 struct list_head stream_list;
2715 struct list_head lookup_table_list;
2716 struct filter_context filter_ctx;
2718 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2720 /* Set default integrity flag. */
2721 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2722 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2723 if (wim_has_integrity_table(wim))
2724 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2726 /* Set default packed flag. */
2727 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2728 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2729 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
2730 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2732 /* Set additional flags for overwrite. */
2733 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2734 WIMLIB_WRITE_FLAG_STREAMS_OK;
2736 /* Make sure that the integrity table (if present) is after the XML
2737 * data, and that there are no stream resources, metadata resources, or
2738 * lookup tables after the XML data. Otherwise, these data would be
2740 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2741 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2742 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2743 wim->hdr.lookup_table_reshdr.size_in_wim;
2744 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2745 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2746 WARNING("Didn't expect the integrity table to be before the XML data");
2747 return WIMLIB_ERR_RESOURCE_ORDER;
2750 if (old_lookup_table_end > old_xml_begin) {
2751 WARNING("Didn't expect the lookup table to be after the XML data");
2752 return WIMLIB_ERR_RESOURCE_ORDER;
2755 /* Set @old_wim_end, which indicates the point beyond which we don't
2756 * allow any file and metadata resources to appear without returning
2757 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2758 * overwrite these resources). */
2759 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2760 /* If no images have been modified and no images have been
2761 * deleted, a new lookup table does not need to be written. We
2762 * shall write the new XML data and optional integrity table
2763 * immediately after the lookup table. Note that this may
2764 * overwrite an existing integrity table. */
2765 DEBUG("Skipping writing lookup table "
2766 "(no images modified or deleted)");
2767 old_wim_end = old_lookup_table_end;
2768 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2769 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2770 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2771 /* Old WIM has an integrity table; begin writing new streams
2773 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2774 wim->hdr.integrity_table_reshdr.size_in_wim;
2776 /* No existing integrity table; begin writing new streams after
2777 * the old XML data. */
2778 old_wim_end = old_xml_end;
2781 ret = check_resource_offsets(wim, old_wim_end);
2785 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2786 &stream_list, &lookup_table_list,
2791 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2795 ret = lock_wim(wim, wim->out_fd.fd);
2799 /* Save original header so it can be restored in case of error */
2800 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2802 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2803 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2804 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2806 ERROR_WITH_ERRNO("Error updating WIM header flags");
2807 goto out_restore_memory_hdr;
2810 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2811 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2812 ret = WIMLIB_ERR_WRITE;
2813 goto out_restore_physical_hdr;
2816 ret = write_stream_list(&stream_list,
2818 write_flags_to_resource_flags(write_flags),
2819 wim->compression_type,
2829 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2830 write_flags, progress_func);
2834 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2835 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2836 progress_func, &lookup_table_list);
2840 goto out_unlock_wim;
2843 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2844 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2845 wim->filename, old_wim_end);
2846 /* Return value of ftruncate() is ignored because this is
2847 * already an error path. */
2848 (void)ftruncate(wim->out_fd.fd, old_wim_end);
2850 out_restore_physical_hdr:
2851 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
2852 out_restore_memory_hdr:
2853 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2855 (void)close_wim_writable(wim, write_flags);
2857 wim->wim_locked = 0;
2862 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2863 unsigned num_threads,
2864 wimlib_progress_func_t progress_func)
2866 size_t wim_name_len;
2869 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2871 /* Write the WIM to a temporary file in the same directory as the
2873 wim_name_len = tstrlen(wim->filename);
2874 tchar tmpfile[wim_name_len + 10];
2875 tmemcpy(tmpfile, wim->filename, wim_name_len);
2876 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2877 tmpfile[wim_name_len + 9] = T('\0');
2879 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2880 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2881 num_threads, progress_func);
2889 /* Rename the new WIM file to the original WIM file. Note: on Windows
2890 * this actually calls win32_rename_replacement(), not _wrename(), so
2891 * that removing the existing destination file can be handled. */
2892 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
2893 ret = trename(tmpfile, wim->filename);
2895 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2896 tmpfile, wim->filename);
2903 return WIMLIB_ERR_RENAME;
2906 if (progress_func) {
2907 union wimlib_progress_info progress;
2908 progress.rename.from = tmpfile;
2909 progress.rename.to = wim->filename;
2910 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2916 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
2918 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2921 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2924 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2927 if (wim->hdr.wim_version != WIM_VERSION_PACKED_STREAMS) {
2928 if (wim->compression_type != wim->out_compression_type)
2930 if (wim->chunk_size != wim->out_chunk_size)
2937 /* API function documented in wimlib.h */
2939 wimlib_overwrite(WIMStruct *wim, int write_flags,
2940 unsigned num_threads,
2941 wimlib_progress_func_t progress_func)
2946 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2948 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2949 return WIMLIB_ERR_INVALID_PARAM;
2952 return WIMLIB_ERR_NO_FILENAME;
2954 orig_hdr_flags = wim->hdr.flags;
2955 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2956 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
2957 ret = can_modify_wim(wim);
2958 wim->hdr.flags = orig_hdr_flags;
2962 if (can_overwrite_wim_inplace(wim, write_flags)) {
2963 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
2965 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
2967 WARNING("Falling back to re-building entire WIM");
2969 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,