4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/chunk_compressor.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/inode.h"
43 #include "wimlib/integrity.h"
44 #include "wimlib/lookup_table.h"
45 #include "wimlib/metadata.h"
46 #include "wimlib/resource.h"
48 # include "wimlib/win32.h" /* win32_rename_replacement() */
50 #include "wimlib/write.h"
51 #include "wimlib/xml.h"
62 /* wimlib internal flags used when writing resources. */
63 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
64 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
65 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
68 write_flags_to_resource_flags(int write_flags)
70 int write_resource_flags = 0;
72 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
73 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
74 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
75 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
76 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
77 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
78 return write_resource_flags;
81 struct filter_context {
86 /* Determine specified stream should be filtered out from the write.
90 * < 0 : The stream should be hard-filtered; that is, not included in the
92 * 0 : The stream should not be filtered out.
93 * > 0 : The stream should be soft-filtered; that is, it already exists in the
94 * WIM file and may not need to be written again.
97 stream_filtered(const struct wim_lookup_table_entry *lte,
98 const struct filter_context *ctx)
100 int write_flags = ctx->write_flags;
101 WIMStruct *wim = ctx->wim;
106 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
107 lte->resource_location == RESOURCE_IN_WIM &&
108 lte->rspec->wim == wim)
111 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
112 lte->resource_location == RESOURCE_IN_WIM &&
113 lte->rspec->wim != wim)
120 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
121 struct filter_context *ctx)
123 return stream_filtered(lte, ctx) < 0;
127 may_soft_filter_streams(const struct filter_context *ctx)
131 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
135 may_hard_filter_streams(const struct filter_context *ctx)
139 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
143 may_filter_streams(const struct filter_context *ctx)
145 return (may_soft_filter_streams(ctx) ||
146 may_hard_filter_streams(ctx));
150 /* Return true if the specified resource is compressed and the compressed data
151 * can be reused with the specified output parameters. */
153 can_raw_copy(const struct wim_lookup_table_entry *lte,
154 int write_resource_flags, int out_ctype, u32 out_chunk_size)
156 const struct wim_resource_spec *rspec;
158 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
161 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
164 if (lte->resource_location != RESOURCE_IN_WIM)
169 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
173 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
174 /* Normal compressed resource: Must use same compression type
176 return (rspec->compression_type == out_ctype &&
177 rspec->chunk_size == out_chunk_size);
180 /* XXX: For compatibility, we can't allow multiple packed resources per
183 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
184 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
186 /* Packed resource: Such resources may contain multiple streams,
187 * and in general only a subset of them need to be written. As
188 * a heuristic, re-use the raw data if at least half the
189 * uncompressed size is being written. */
191 /* Note: packed resources contain a header that specifies the
192 * compression type and chunk size; therefore we don't need to
193 * check if they are compatible with @out_ctype and
194 * @out_chunk_size. */
196 struct wim_lookup_table_entry *res_stream;
199 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
200 if (res_stream->will_be_in_output_wim)
201 write_size += res_stream->size;
203 return (write_size > rspec->uncompressed_size / 2);
211 filter_resource_flags(u8 flags)
213 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
214 WIM_RESHDR_FLAG_COMPRESSED |
215 WIM_RESHDR_FLAG_SPANNED |
216 WIM_RESHDR_FLAG_FREE));
220 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
222 const struct wim_resource_spec *rspec;
224 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
227 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
229 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
231 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
232 lte->out_reshdr.uncompressed_size = 0;
233 lte->out_reshdr.size_in_wim = lte->size;
235 lte->out_res_offset_in_wim = rspec->offset_in_wim;
236 lte->out_res_size_in_wim = rspec->size_in_wim;
237 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
239 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
241 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
242 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
243 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
245 lte->out_reshdr.flags = lte->flags;
249 /* Write the header for a stream in a pipable WIM. */
251 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
252 struct filedes *out_fd,
253 int additional_reshdr_flags)
255 struct pwm_stream_hdr stream_hdr;
259 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
260 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
261 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
262 zero_out_hash(stream_hdr.hash);
264 wimlib_assert(!lte->unhashed);
265 copy_hash(stream_hdr.hash, lte->hash);
268 reshdr_flags = filter_resource_flags(lte->flags);
269 reshdr_flags |= additional_reshdr_flags;
270 stream_hdr.flags = cpu_to_le32(reshdr_flags);
271 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
273 ERROR_WITH_ERRNO("Write error");
277 struct write_streams_progress_data {
278 wimlib_progress_func_t progress_func;
279 union wimlib_progress_info progress;
280 uint64_t next_progress;
284 do_write_streams_progress(struct write_streams_progress_data *progress_data,
285 struct wim_lookup_table_entry *cur_stream,
290 union wimlib_progress_info *progress = &progress_data->progress;
293 progress->write_streams.total_bytes -= complete_size;
294 progress->write_streams.total_streams -= complete_count;
295 if (progress_data->next_progress != ~(uint64_t)0 &&
296 progress_data->next_progress > progress->write_streams.total_bytes)
298 progress_data->next_progress = progress->write_streams.total_bytes;
301 progress->write_streams.completed_bytes += complete_size;
302 progress->write_streams.completed_streams += complete_count;
305 if (progress_data->progress_func
306 && (progress->write_streams.completed_bytes >= progress_data->next_progress))
308 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
310 if (progress_data->next_progress == progress->write_streams.total_bytes) {
311 progress_data->next_progress = ~(uint64_t)0;
313 progress_data->next_progress =
314 min(progress->write_streams.total_bytes,
315 progress->write_streams.completed_bytes +
316 progress->write_streams.total_bytes / 100);
321 struct write_streams_ctx {
322 /* File descriptor the streams are being written to. */
323 struct filedes *out_fd;
325 /* Lookup table for the WIMStruct on whose behalf the streams are being
327 struct wim_lookup_table *lookup_table;
329 /* Compression format to use. */
332 /* Maximum uncompressed chunk size in compressed resources to use. */
335 /* Flags that affect how the streams will be written. */
336 int write_resource_flags;
338 /* Data used for issuing WRITE_STREAMS progress. */
339 struct write_streams_progress_data progress_data;
341 struct filter_context *filter_ctx;
343 /* Upper bound on the total number of bytes that need to be compressed.
345 u64 num_bytes_to_compress;
347 /* Pointer to the chunk_compressor implementation being used for
348 * compressing chunks of data, or NULL if chunks are being written
350 struct chunk_compressor *compressor;
352 /* Buffer for dividing the read data into chunks of size
353 * @out_chunk_size. */
356 /* Number of bytes in @chunk_buf that are currently filled. */
357 size_t chunk_buf_filled;
359 /* List of streams that currently have chunks being compressed. */
360 struct list_head pending_streams;
362 /* List of streams in the resource pack. Streams are moved here after
363 * @pending_streams only when writing a packed resource. */
364 struct list_head pack_streams;
366 /* Set to true if the stream currently being read was a duplicate, and
367 * therefore the corresponding stream entry needs to be freed once the
368 * read finishes. (In this case we add the duplicate entry to
369 * pending_streams rather than the entry being read.) */
370 bool stream_was_duplicate;
372 /* Current uncompressed offset in the stream being read. */
373 u64 cur_read_stream_offset;
375 /* Uncompressed size of the stream currently being read. */
376 u64 cur_read_stream_size;
378 /* Current uncompressed offset in the stream being written. */
379 u64 cur_write_stream_offset;
381 /* Uncompressed size of resource currently being written. */
382 u64 cur_write_res_size;
384 /* Array that is filled in with compressed chunk sizes as a resource is
388 /* Index of next entry in @chunk_csizes to fill in. */
391 /* Number of entries in @chunk_csizes currently allocated. */
392 size_t num_alloc_chunks;
394 /* Offset in the output file of the start of the chunks of the resource
395 * currently being written. */
396 u64 chunks_start_offset;
399 /* Reserve space for the chunk table and prepare to accumulate the chunk table
402 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
404 u64 expected_num_chunks;
405 u64 expected_num_chunk_entries;
409 /* Calculate the number of chunks and chunk entries that should be
410 * needed for the resource. These normally will be the final values,
411 * but in PACKED_STREAMS mode some of the streams we're planning to
412 * write into the resource may be duplicates, and therefore discarded,
413 * potentially decreasing the number of chunk entries needed. */
414 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
415 expected_num_chunk_entries = expected_num_chunks;
416 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
417 expected_num_chunk_entries--;
419 /* Make sure the chunk_csizes array is long enough to store the
420 * compressed size of each chunk. */
421 if (expected_num_chunks > ctx->num_alloc_chunks) {
422 u64 new_length = expected_num_chunks + 50;
424 if ((size_t)new_length != new_length) {
425 ERROR("Resource size too large (%"PRIu64" bytes!",
427 return WIMLIB_ERR_NOMEM;
430 FREE(ctx->chunk_csizes);
431 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
432 if (ctx->chunk_csizes == NULL) {
433 ctx->num_alloc_chunks = 0;
434 return WIMLIB_ERR_NOMEM;
436 ctx->num_alloc_chunks = new_length;
439 ctx->chunk_index = 0;
441 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
442 /* Reserve space for the chunk table in the output file. In the
443 * case of packed resources this reserves the upper bound for
444 * the needed space, not necessarily the exact space which will
445 * prove to be needed. At this point, we just use @chunk_csizes
446 * for a buffer of 0's because the actual compressed chunk sizes
448 reserve_size = expected_num_chunk_entries *
449 get_chunk_entry_size(res_expected_size,
450 0 != (ctx->write_resource_flags &
451 WIM_RESHDR_FLAG_PACKED_STREAMS));
452 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
453 reserve_size += sizeof(struct alt_chunk_table_header_disk);
454 memset(ctx->chunk_csizes, 0, reserve_size);
455 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
463 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
467 wimlib_assert(res_expected_size != 0);
469 if (ctx->compressor != NULL) {
470 ret = begin_chunk_table(ctx, res_expected_size);
475 /* Output file descriptor is now positioned at the offset at which to
476 * write the first chunk of the resource. */
477 ctx->chunks_start_offset = ctx->out_fd->offset;
478 ctx->cur_write_stream_offset = 0;
479 ctx->cur_write_res_size = res_expected_size;
484 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
485 u64 *res_start_offset_ret, u64 *res_store_size_ret)
487 size_t actual_num_chunks;
488 size_t actual_num_chunk_entries;
489 size_t chunk_entry_size;
492 actual_num_chunks = ctx->chunk_index;
493 actual_num_chunk_entries = actual_num_chunks;
494 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
495 actual_num_chunk_entries--;
497 chunk_entry_size = get_chunk_entry_size(res_actual_size,
498 0 != (ctx->write_resource_flags &
499 WIM_RESHDR_FLAG_PACKED_STREAMS));
501 typedef le64 __attribute__((may_alias)) aliased_le64_t;
502 typedef le32 __attribute__((may_alias)) aliased_le32_t;
504 if (chunk_entry_size == 4) {
505 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
507 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
508 for (size_t i = 0; i < actual_num_chunk_entries; i++)
509 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
511 u32 offset = ctx->chunk_csizes[0];
512 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
513 u32 next_size = ctx->chunk_csizes[i + 1];
514 entries[i] = cpu_to_le32(offset);
519 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
521 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
522 for (size_t i = 0; i < actual_num_chunk_entries; i++)
523 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
525 u64 offset = ctx->chunk_csizes[0];
526 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
527 u64 next_size = ctx->chunk_csizes[i + 1];
528 entries[i] = cpu_to_le64(offset);
534 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
535 u64 res_start_offset;
538 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
539 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
542 res_end_offset = ctx->out_fd->offset;
543 res_start_offset = ctx->chunks_start_offset;
545 res_end_offset = ctx->out_fd->offset;
547 u64 chunk_table_offset;
549 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
551 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
552 struct alt_chunk_table_header_disk hdr;
554 hdr.res_usize = cpu_to_le64(res_actual_size);
555 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
556 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
558 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
559 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
560 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
562 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
563 chunk_table_offset - sizeof(hdr));
566 res_start_offset = chunk_table_offset - sizeof(hdr);
568 res_start_offset = chunk_table_offset;
571 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
572 chunk_table_size, chunk_table_offset);
577 *res_start_offset_ret = res_start_offset;
578 *res_store_size_ret = res_end_offset - res_start_offset;
583 ERROR_WITH_ERRNO("Write error");
587 /* Finish writing a WIM resource by writing or updating the chunk table (if not
588 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
590 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
594 u64 res_uncompressed_size;
595 u64 res_offset_in_wim;
597 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
598 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS));
599 res_uncompressed_size = ctx->cur_write_res_size;
601 if (ctx->compressor) {
602 ret = end_chunk_table(ctx, res_uncompressed_size,
603 &res_offset_in_wim, &res_size_in_wim);
607 res_offset_in_wim = ctx->chunks_start_offset;
608 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
610 out_reshdr->uncompressed_size = res_uncompressed_size;
611 out_reshdr->size_in_wim = res_size_in_wim;
612 out_reshdr->offset_in_wim = res_offset_in_wim;
613 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
614 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
618 /* Begin processing a stream for writing. */
620 write_stream_begin_read(struct wim_lookup_table_entry *lte,
621 bool is_partial_res, void *_ctx)
623 struct write_streams_ctx *ctx = _ctx;
626 wimlib_assert(lte->size > 0);
628 ctx->cur_read_stream_offset = 0;
629 ctx->cur_read_stream_size = lte->size;
631 /* As an optimization, we allow some streams to be "unhashed", meaning
632 * their SHA1 message digests are unknown. This is the case with
633 * streams that are added by scanning a directry tree with
634 * wimlib_add_image(), for example. Since WIM uses single-instance
635 * streams, we don't know whether such each such stream really need to
636 * written until it is actually checksummed, unless it has a unique
637 * size. In such cases we read and checksum the stream in this
638 * function, thereby advancing ahead of read_stream_list(), which will
639 * still provide the data again to write_stream_process_chunk(). This
640 * is okay because an unhashed stream cannot be in a WIM resource, which
641 * might be costly to decompress. */
642 ctx->stream_was_duplicate = false;
643 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
645 wimlib_assert(!is_partial_res);
647 struct wim_lookup_table_entry *lte_new;
649 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
652 if (lte_new != lte) {
653 /* Duplicate stream detected. */
655 if (lte_new->will_be_in_output_wim ||
656 stream_filtered(lte_new, ctx->filter_ctx))
658 /* The duplicate stream is already being
659 * included in the output WIM, or it would be
660 * filtered out if it had been. Skip writing
661 * this stream (and reading it again) entirely,
662 * passing its output reference count to the
663 * duplicate stream in the former case. */
664 DEBUG("Discarding duplicate stream of "
665 "length %"PRIu64, lte->size);
666 do_write_streams_progress(&ctx->progress_data,
669 list_del(<e->write_streams_list);
670 list_del(<e->lookup_table_list);
671 if (lte_new->will_be_in_output_wim)
672 lte_new->out_refcnt += lte->out_refcnt;
673 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
674 ctx->cur_write_res_size -= lte->size;
675 free_lookup_table_entry(lte);
676 return BEGIN_STREAM_STATUS_SKIP_STREAM;
678 /* The duplicate stream can validly be written,
679 * but was not marked as such. Discard the
680 * current stream entry and use the duplicate,
681 * but actually freeing the current entry must
682 * wait until read_stream_list() has finished
683 * reading its data. */
684 DEBUG("Stream duplicate, but not already "
685 "selected for writing.");
686 list_replace(<e->write_streams_list,
687 <e_new->write_streams_list);
688 list_replace(<e->lookup_table_list,
689 <e_new->lookup_table_list);
690 lte_new->out_refcnt = lte->out_refcnt;
691 lte_new->will_be_in_output_wim = 1;
692 ctx->stream_was_duplicate = true;
697 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
701 /* Rewrite a stream that was just written compressed as uncompressed instead.
702 * This function is optional, but if a stream did not compress to less than its
703 * original size, it might as well be written uncompressed. */
705 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
706 struct filedes *out_fd)
709 u64 begin_offset = lte->out_reshdr.offset_in_wim;
710 u64 end_offset = out_fd->offset;
712 if (filedes_seek(out_fd, begin_offset) == -1)
715 ret = extract_full_stream_to_fd(lte, out_fd);
717 /* Error reading the uncompressed data. */
718 if (out_fd->offset == begin_offset &&
719 filedes_seek(out_fd, end_offset) != -1)
721 /* Nothing was actually written yet, and we successfully
722 * seeked to the end of the compressed resource, so
723 * don't issue a hard error; just keep the compressed
724 * resource instead. */
725 WARNING("Recovered compressed stream of "
726 "size %"PRIu64", continuing on.",
733 wimlib_assert(out_fd->offset - begin_offset == lte->size);
735 if (out_fd->offset < end_offset &&
736 0 != ftruncate(out_fd->fd, out_fd->offset))
738 ERROR_WITH_ERRNO("Can't truncate output file to "
739 "offset %"PRIu64, out_fd->offset);
740 return WIMLIB_ERR_WRITE;
743 lte->out_reshdr.size_in_wim = lte->size;
744 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
745 WIM_RESHDR_FLAG_PACKED_STREAMS);
749 /* Write the next chunk of (typically compressed) data to the output WIM,
750 * handling the writing of the chunk table. */
752 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
753 size_t csize, size_t usize)
757 struct wim_lookup_table_entry *lte;
758 u32 completed_stream_count;
761 lte = list_entry(ctx->pending_streams.next,
762 struct wim_lookup_table_entry, write_streams_list);
764 if (ctx->cur_write_stream_offset == 0 &&
765 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
767 /* Starting to write a new stream in non-packed mode. */
769 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
770 int additional_reshdr_flags = 0;
771 if (ctx->compressor != NULL)
772 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
774 DEBUG("Writing pipable WIM stream header "
775 "(offset=%"PRIu64")", ctx->out_fd->offset);
777 ret = write_pwm_stream_header(lte, ctx->out_fd,
778 additional_reshdr_flags);
783 ret = begin_write_resource(ctx, lte->size);
788 if (ctx->compressor != NULL) {
789 /* Record the compresed chunk size. */
790 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
791 ctx->chunk_csizes[ctx->chunk_index++] = csize;
793 /* If writing a pipable WIM, before the chunk data write a chunk
794 * header that provides the compressed chunk size. */
795 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
796 struct pwm_chunk_hdr chunk_hdr = {
797 .compressed_size = cpu_to_le32(csize),
799 ret = full_write(ctx->out_fd, &chunk_hdr,
806 /* Write the chunk data. */
807 ret = full_write(ctx->out_fd, cchunk, csize);
811 ctx->cur_write_stream_offset += usize;
813 completed_size = usize;
814 completed_stream_count = 0;
815 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
816 /* Wrote chunk in packed mode. It may have finished multiple
818 while (ctx->cur_write_stream_offset > lte->size) {
819 struct wim_lookup_table_entry *next;
821 ctx->cur_write_stream_offset -= lte->size;
823 wimlib_assert(!list_is_singular(&ctx->pending_streams) &&
824 !list_empty(&ctx->pending_streams));
825 next = list_entry(lte->write_streams_list.next,
826 struct wim_lookup_table_entry,
828 list_move_tail(<e->write_streams_list,
831 completed_stream_count++;
833 if (ctx->cur_write_stream_offset == lte->size) {
834 ctx->cur_write_stream_offset = 0;
835 list_move_tail(<e->write_streams_list,
837 completed_stream_count++;
840 /* Wrote chunk in non-packed mode. It may have finished a
842 if (ctx->cur_write_stream_offset == lte->size) {
844 completed_stream_count++;
846 list_del(<e->write_streams_list);
848 wimlib_assert(ctx->cur_write_stream_offset ==
849 ctx->cur_write_res_size);
851 ret = end_write_resource(ctx, <e->out_reshdr);
855 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
856 if (ctx->compressor != NULL)
857 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
859 if (ctx->compressor != NULL &&
860 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
861 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) &&
862 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
864 /* Stream did not compress to less than its original
865 * size. If we're not writing a pipable WIM (which
866 * could mean the output file descriptor is
867 * non-seekable), and the stream isn't located in a
868 * resource pack (which would make reading it again
869 * costly), truncate the file to the start of the stream
870 * and write it uncompressed instead. */
871 DEBUG("Stream of size %"PRIu64" did not compress to "
872 "less than original size; writing uncompressed.",
874 ret = write_stream_uncompressed(lte, ctx->out_fd);
878 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
880 ctx->cur_write_stream_offset = 0;
884 do_write_streams_progress(&ctx->progress_data, lte,
885 completed_size, completed_stream_count,
891 ERROR_WITH_ERRNO("Write error");
896 submit_chunk_for_compression(struct write_streams_ctx *ctx,
897 const void *chunk, size_t size)
899 /* While we are unable to submit the chunk for compression (due to too
900 * many chunks already outstanding), retrieve and write the next
901 * compressed chunk. */
902 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
909 bret = ctx->compressor->get_chunk(ctx->compressor,
910 &cchunk, &csize, &usize);
914 ret = write_chunk(ctx, cchunk, csize, usize);
921 /* Process the next chunk of data to be written to a WIM resource. */
923 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
925 struct write_streams_ctx *ctx = _ctx;
927 const u8 *chunkptr, *chunkend;
929 wimlib_assert(size != 0);
931 if (ctx->compressor == NULL) {
932 /* Write chunk uncompressed. */
933 ret = write_chunk(ctx, chunk, size, size);
936 ctx->cur_read_stream_offset += size;
940 /* Submit the chunk for compression, but take into account that the
941 * @size the chunk was provided in may not correspond to the
942 * @out_chunk_size being used for compression. */
944 chunkend = chunkptr + size;
946 const u8 *resized_chunk;
947 size_t needed_chunk_size;
949 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
950 needed_chunk_size = ctx->out_chunk_size;
952 u64 res_bytes_remaining;
954 res_bytes_remaining = ctx->cur_read_stream_size -
955 ctx->cur_read_stream_offset;
956 needed_chunk_size = min(ctx->out_chunk_size,
957 ctx->chunk_buf_filled +
958 res_bytes_remaining);
961 if (ctx->chunk_buf_filled == 0 &&
962 chunkend - chunkptr >= needed_chunk_size)
964 /* No intermediate buffering needed. */
965 resized_chunk = chunkptr;
966 chunkptr += needed_chunk_size;
967 ctx->cur_read_stream_offset += needed_chunk_size;
969 /* Intermediate buffering needed. */
970 size_t bytes_consumed;
972 bytes_consumed = min(chunkend - chunkptr,
973 needed_chunk_size - ctx->chunk_buf_filled);
975 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
976 chunkptr, bytes_consumed);
978 chunkptr += bytes_consumed;
979 ctx->cur_read_stream_offset += bytes_consumed;
980 ctx->chunk_buf_filled += bytes_consumed;
981 if (ctx->chunk_buf_filled == needed_chunk_size) {
982 resized_chunk = ctx->chunk_buf;
983 ctx->chunk_buf_filled = 0;
990 ret = submit_chunk_for_compression(ctx, resized_chunk,
995 } while (chunkptr != chunkend);
999 /* Finish processing a stream for writing. It may not have been completely
1000 * written yet, as the chunk_compressor implementation may still have chunks
1001 * buffered or being compressed. */
1003 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1005 struct write_streams_ctx *ctx = _ctx;
1007 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size);
1008 if (ctx->stream_was_duplicate) {
1009 free_lookup_table_entry(lte);
1010 } else if (lte->unhashed && ctx->lookup_table != NULL) {
1011 list_del(<e->unhashed_list);
1012 lookup_table_insert(ctx->lookup_table, lte);
1018 /* Compute statistics about a list of streams that will be written.
1020 * Assumes the streams are sorted such that all streams located in each distinct
1021 * WIM (specified by WIMStruct) are together. */
1023 compute_stream_list_stats(struct list_head *stream_list,
1024 struct write_streams_ctx *ctx)
1026 struct wim_lookup_table_entry *lte;
1027 u64 total_bytes = 0;
1028 u64 num_streams = 0;
1029 u64 total_parts = 0;
1030 WIMStruct *prev_wim_part = NULL;
1032 list_for_each_entry(lte, stream_list, write_streams_list) {
1034 total_bytes += lte->size;
1035 if (lte->resource_location == RESOURCE_IN_WIM) {
1036 if (prev_wim_part != lte->rspec->wim) {
1037 prev_wim_part = lte->rspec->wim;
1042 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1043 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1044 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1045 ctx->progress_data.progress.write_streams.completed_streams = 0;
1046 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1047 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1048 ctx->progress_data.progress.write_streams.completed_parts = 0;
1049 ctx->progress_data.next_progress = 0;
1052 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1053 * rather than compressed. Delete these streams from @stream_list, and move one
1054 * per resource to @raw_copy_resources. Return the total uncompressed size of
1055 * the streams that need to be compressed. */
1057 find_raw_copy_resources(struct list_head *stream_list,
1058 int write_resource_flags,
1061 struct list_head *raw_copy_resources)
1063 struct wim_lookup_table_entry *lte, *tmp;
1064 u64 num_bytes_to_compress = 0;
1066 INIT_LIST_HEAD(raw_copy_resources);
1068 /* Initialize temporary raw_copy_ok flag. */
1069 list_for_each_entry(lte, stream_list, write_streams_list)
1070 if (lte->resource_location == RESOURCE_IN_WIM)
1071 lte->rspec->raw_copy_ok = 0;
1073 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1074 if (lte->resource_location == RESOURCE_IN_WIM &&
1075 lte->rspec->raw_copy_ok)
1077 list_del(<e->write_streams_list);
1078 } else if (can_raw_copy(lte, write_resource_flags,
1079 out_ctype, out_chunk_size))
1081 lte->rspec->raw_copy_ok = 1;
1082 list_move_tail(<e->write_streams_list,
1083 raw_copy_resources);
1085 num_bytes_to_compress += lte->size;
1089 return num_bytes_to_compress;
1092 /* Copy a raw compressed resource located in another WIM file to the WIM file
1095 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1096 struct filedes *out_fd)
1098 u64 cur_read_offset;
1099 u64 end_read_offset;
1100 u8 buf[BUFFER_SIZE];
1101 size_t bytes_to_read;
1103 struct filedes *in_fd;
1104 struct wim_lookup_table_entry *lte;
1105 u64 out_offset_in_wim;
1107 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1108 "uncompressed_size=%"PRIu64")",
1109 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1111 /* Copy the raw data. */
1112 cur_read_offset = in_rspec->offset_in_wim;
1113 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1115 out_offset_in_wim = out_fd->offset;
1117 if (in_rspec->is_pipable) {
1118 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1119 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1120 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1121 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1123 in_fd = &in_rspec->wim->in_fd;
1124 wimlib_assert(cur_read_offset != end_read_offset);
1127 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1129 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1133 ret = full_write(out_fd, buf, bytes_to_read);
1137 cur_read_offset += bytes_to_read;
1139 } while (cur_read_offset != end_read_offset);
1141 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1142 if (lte->will_be_in_output_wim) {
1143 stream_set_out_reshdr_for_reuse(lte);
1144 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1145 lte->out_res_offset_in_wim = out_offset_in_wim;
1147 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1154 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1155 * file being written. */
1157 write_raw_copy_resources(struct list_head *raw_copy_resources,
1158 struct filedes *out_fd,
1159 struct write_streams_progress_data *progress_data)
1161 struct wim_lookup_table_entry *lte;
1164 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1165 ret = write_raw_copy_resource(lte->rspec, out_fd);
1168 do_write_streams_progress(progress_data, lte, lte->size,
1174 /* Wait for and write all chunks pending in the compressor. */
1176 finish_remaining_chunks(struct write_streams_ctx *ctx)
1183 if (ctx->compressor == NULL)
1186 if (ctx->chunk_buf_filled != 0) {
1187 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1188 ctx->chunk_buf_filled);
1193 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1194 ret = write_chunk(ctx, cdata, csize, usize);
1202 remove_zero_length_streams(struct list_head *stream_list)
1204 struct wim_lookup_table_entry *lte, *tmp;
1206 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1207 wimlib_assert(lte->will_be_in_output_wim);
1208 if (lte->size == 0) {
1209 list_del(<e->write_streams_list);
1210 lte->out_reshdr.offset_in_wim = 0;
1211 lte->out_reshdr.size_in_wim = 0;
1212 lte->out_reshdr.uncompressed_size = 0;
1213 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1219 * Write a list of streams to the output WIM file.
1222 * The list of streams to write, specified by a list of `struct
1223 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1226 * The file descriptor, opened for writing, to which to write the streams.
1228 * @write_resource_flags
1229 * Flags to modify how the streams are written:
1231 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1232 * Force compression of all resources, even if they could otherwise
1233 * be re-used by copying the raw data, due to being located in a WIM
1234 * file with compatible compression parameters.
1236 * WRITE_RESOURCE_FLAG_PIPABLE:
1237 * Write the resources in the wimlib-specific pipable format, and
1238 * furthermore do so in such a way that no seeking backwards in
1239 * @out_fd will be performed (so it may be a pipe).
1241 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1242 * Pack all the streams into a single resource rather than writing
1243 * them in separate resources. This flag is only valid if the WIM
1244 * version number has been, or will be, set to
1245 * WIM_VERSION_PACKED_STREAMS. This flag may not be combined with
1246 * WRITE_RESOURCE_FLAG_PIPABLE.
1249 * Compression format to use to write the output streams, specified as one
1250 * of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1251 * WIMLIB_COMPRESSION_TYPE_INVALID but including
1252 * WIMLIB_COMPRESSION_TYPE_NONE.
1255 * Chunk size to use to write the streams. It must be a valid chunk size
1256 * for the specified compression format @out_ctype, unless @out_ctype is
1257 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1260 * Number of threads to use to compress data. If 0, a default number of
1261 * threads will be chosen. The number of threads still may be decreased
1262 * from the specified value if insufficient memory is detected.
1265 * If on-the-fly deduplication of unhashed streams is desired, this
1266 * parameter must be pointer to the lookup table for the WIMStruct on whose
1267 * behalf the streams are being written. Otherwise, this parameter can be
1271 * If on-the-fly deduplication of unhashed streams is desired, this
1272 * parameter can be a pointer to a context for stream filtering used to
1273 * detect whether the duplicate stream has been hard-filtered or not. If
1274 * no streams are hard-filtered or no streams are unhashed, this parameter
1278 * If non-NULL, a progress function that will be called periodically with
1279 * WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages. Note that on-the-fly
1280 * deduplication of unhashed streams may result in the total bytes provided
1281 * in the progress data to decrease from one message to the next.
1283 * This function will write the streams in @stream_list to resources in
1284 * consecutive positions in the output WIM file, or to a single packed resource
1285 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1286 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1287 * each stream written will be updated to specify its location, size, and flags
1288 * in the output WIM. In the packed resource case,
1289 * WIM_RESHDR_FLAG_PACKED_STREAMS will be set in the @flags field of each
1290 * @out_reshdr, and furthermore @out_res_offset_in_wim and @out_res_size_in_wim
1291 * of each @out_reshdr will be set to the offset and size, respectively, in the
1292 * output WIM of the packed resource containing the corresponding stream.
1294 * Each of the streams to write may be in any location supported by the
1295 * resource-handling code (specifically, read_stream_list()), such as the
1296 * contents of external file that has been logically added to the output WIM, or
1297 * a stream in another WIM file that has been imported, or even a stream in the
1298 * "same" WIM file of which a modified copy is being written. In the case that
1299 * a stream is already in a WIM file and uses compatible compression parameters,
1300 * by default this function will re-use the raw data instead of decompressing
1301 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1302 * specified in @write_resource_flags, this is not done.
1304 * As a further requirement, this function requires that the
1305 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1306 * well as any other streams not in @stream_list that will be in the output WIM
1307 * file, but set to 0 on any other streams in the output WIM's lookup table or
1308 * sharing a packed resource with a stream in @stream_list. Still furthermore,
1309 * if on-the-fly deduplication of streams is possible, then all streams in
1310 * @stream_list must also be linked by @lookup_table_list along with any other
1311 * streams that have @will_be_in_output_wim set.
1313 * This function handles on-the-fly deduplication of streams for which SHA1
1314 * message digests have not yet been calculated. Such streams may or may not
1315 * need to be written. If @lookup_table is non-NULL, then each stream in
1316 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1317 * immediately before it would otherwise be read for writing in order to
1318 * determine if it is identical to another stream already being written or one
1319 * that would be filtered out of the output WIM using stream_filtered() with the
1320 * context @filter_ctx. Each such duplicate stream will be removed from
1321 * @stream_list, its reference count transfered to the pre-existing duplicate
1322 * stream, its memory freed, and will not be written. Alternatively, if a
1323 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1324 * has not been marked for writing or would not be hard-filtered, it is freed
1325 * and the pre-existing duplicate is written instead, taking ownership of the
1326 * reference count and slot in the @lookup_table_list.
1328 * Returns 0 if every stream was either written successfully or did not need to
1329 * be written; otherwise returns a non-zero error code.
1332 write_stream_list(struct list_head *stream_list,
1333 struct filedes *out_fd,
1334 int write_resource_flags,
1337 unsigned num_threads,
1338 struct wim_lookup_table *lookup_table,
1339 struct filter_context *filter_ctx,
1340 wimlib_progress_func_t progress_func)
1343 struct write_streams_ctx ctx;
1344 struct list_head raw_copy_resources;
1346 wimlib_assert((write_resource_flags &
1347 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1348 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1349 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1350 WRITE_RESOURCE_FLAG_PIPABLE));
1352 remove_zero_length_streams(stream_list);
1354 if (list_empty(stream_list)) {
1355 DEBUG("No streams to write.");
1359 memset(&ctx, 0, sizeof(ctx));
1361 /* Pre-sorting the streams is required for compute_stream_list_stats().
1362 * Afterwards, read_stream_list() need not sort them again. */
1363 ret = sort_stream_list_by_sequential_order(stream_list,
1364 offsetof(struct wim_lookup_table_entry,
1365 write_streams_list));
1369 ctx.out_fd = out_fd;
1370 ctx.lookup_table = lookup_table;
1371 ctx.out_ctype = out_ctype;
1372 ctx.out_chunk_size = out_chunk_size;
1373 ctx.write_resource_flags = write_resource_flags;
1374 ctx.filter_ctx = filter_ctx;
1376 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1377 wimlib_assert(out_chunk_size != 0);
1378 if (out_chunk_size <= STACK_MAX) {
1379 ctx.chunk_buf = alloca(out_chunk_size);
1381 ctx.chunk_buf = MALLOC(out_chunk_size);
1382 if (ctx.chunk_buf == NULL) {
1383 ret = WIMLIB_ERR_NOMEM;
1384 goto out_destroy_context;
1388 ctx.chunk_buf_filled = 0;
1390 compute_stream_list_stats(stream_list, &ctx);
1392 ctx.progress_data.progress_func = progress_func;
1394 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1395 write_resource_flags,
1398 &raw_copy_resources);
1400 DEBUG("Writing stream list "
1401 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1402 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1403 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1404 out_fd->offset, write_resource_flags,
1405 out_ctype, out_chunk_size, num_threads,
1406 ctx.progress_data.progress.write_streams.total_bytes,
1407 ctx.num_bytes_to_compress);
1409 if (ctx.num_bytes_to_compress == 0) {
1410 DEBUG("No compression needed; skipping to raw copy!");
1411 goto out_write_raw_copy_resources;
1414 /* Unless uncompressed output was required, allocate a chunk_compressor
1415 * to do compression. There are serial and parallel implementations of
1416 * the chunk_compressor interface. We default to parallel using the
1417 * specified number of threads, unless the upper bound on the number
1418 * bytes needing to be compressed is less than a heuristic value. */
1419 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1421 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1422 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1423 ret = new_parallel_chunk_compressor(out_ctype,
1428 DEBUG("Couldn't create parallel chunk compressor "
1429 "(status %d)", ret);
1434 if (ctx.compressor == NULL) {
1435 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1438 goto out_destroy_context;
1443 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1445 ctx.progress_data.progress.write_streams.num_threads = 1;
1447 DEBUG("Actually using %u threads",
1448 ctx.progress_data.progress.write_streams.num_threads);
1450 INIT_LIST_HEAD(&ctx.pending_streams);
1451 INIT_LIST_HEAD(&ctx.pack_streams);
1453 if (ctx.progress_data.progress_func) {
1454 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1455 &ctx.progress_data.progress);
1458 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1459 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1461 goto out_destroy_context;
1464 /* Read the list of streams needing to be compressed, using the
1465 * specified callbacks to execute processing of the data. */
1467 struct read_stream_list_callbacks cbs = {
1468 .begin_stream = write_stream_begin_read,
1469 .begin_stream_ctx = &ctx,
1470 .consume_chunk = write_stream_process_chunk,
1471 .consume_chunk_ctx = &ctx,
1472 .end_stream = write_stream_end_read,
1473 .end_stream_ctx = &ctx,
1476 ret = read_stream_list(stream_list,
1477 offsetof(struct wim_lookup_table_entry, write_streams_list),
1479 STREAM_LIST_ALREADY_SORTED |
1480 VERIFY_STREAM_HASHES |
1481 COMPUTE_MISSING_STREAM_HASHES);
1484 goto out_destroy_context;
1486 ret = finish_remaining_chunks(&ctx);
1488 goto out_destroy_context;
1490 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1491 struct wim_reshdr reshdr;
1492 struct wim_lookup_table_entry *lte;
1495 ret = end_write_resource(&ctx, &reshdr);
1497 goto out_destroy_context;
1499 DEBUG("Ending packed resource: %lu %lu %lu.",
1500 reshdr.offset_in_wim,
1502 reshdr.uncompressed_size);
1505 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1506 lte->out_reshdr.size_in_wim = lte->size;
1507 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1508 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1509 lte->out_reshdr.uncompressed_size = 0;
1510 lte->out_reshdr.offset_in_wim = offset_in_res;
1511 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1512 lte->out_res_size_in_wim = reshdr.size_in_wim;
1513 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1514 offset_in_res += lte->size;
1516 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1519 out_write_raw_copy_resources:
1520 /* Copy any compressed resources for which the raw data can be reused
1521 * without decompression. */
1522 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1523 &ctx.progress_data);
1525 out_destroy_context:
1526 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1527 FREE(ctx.chunk_buf);
1528 FREE(ctx.chunk_csizes);
1530 ctx.compressor->destroy(ctx.compressor);
1531 DEBUG("Done (ret=%d)", ret);
1536 wim_write_stream_list(WIMStruct *wim,
1537 struct list_head *stream_list,
1539 unsigned num_threads,
1540 struct filter_context *filter_ctx,
1541 wimlib_progress_func_t progress_func)
1545 int write_resource_flags;
1547 write_resource_flags = write_flags_to_resource_flags(write_flags);
1549 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1550 out_chunk_size = wim->out_pack_chunk_size;
1551 out_ctype = wim->out_pack_compression_type;
1553 out_chunk_size = wim->out_chunk_size;
1554 out_ctype = wim->out_compression_type;
1557 return write_stream_list(stream_list,
1559 write_resource_flags,
1569 write_wim_resource(struct wim_lookup_table_entry *lte,
1570 struct filedes *out_fd,
1573 int write_resource_flags)
1575 LIST_HEAD(stream_list);
1576 list_add(<e->write_streams_list, &stream_list);
1577 lte->will_be_in_output_wim = 1;
1578 return write_stream_list(&stream_list,
1580 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1590 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1591 int reshdr_flags, struct filedes *out_fd,
1594 struct wim_reshdr *out_reshdr,
1596 int write_resource_flags)
1599 struct wim_lookup_table_entry *lte;
1601 /* Set up a temporary lookup table entry to provide to
1602 * write_wim_resource(). */
1604 lte = new_lookup_table_entry();
1606 return WIMLIB_ERR_NOMEM;
1608 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1609 lte->attached_buffer = (void*)buf;
1610 lte->size = buf_size;
1611 lte->flags = reshdr_flags;
1613 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1614 sha1_buffer(buf, buf_size, lte->hash);
1620 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1621 write_resource_flags);
1625 copy_reshdr(out_reshdr, <e->out_reshdr);
1628 copy_hash(hash, lte->hash);
1631 lte->resource_location = RESOURCE_NONEXISTENT;
1632 free_lookup_table_entry(lte);
1636 struct stream_size_table {
1637 struct hlist_head *array;
1643 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1645 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1646 if (tab->array == NULL)
1647 return WIMLIB_ERR_NOMEM;
1648 tab->num_entries = 0;
1649 tab->capacity = capacity;
1654 destroy_stream_size_table(struct stream_size_table *tab)
1660 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1662 struct stream_size_table *tab = _tab;
1664 struct wim_lookup_table_entry *same_size_lte;
1665 struct hlist_node *tmp;
1667 pos = hash_u64(lte->size) % tab->capacity;
1668 lte->unique_size = 1;
1669 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1670 if (same_size_lte->size == lte->size) {
1671 lte->unique_size = 0;
1672 same_size_lte->unique_size = 0;
1677 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1682 struct find_streams_ctx {
1685 struct list_head stream_list;
1686 struct stream_size_table stream_size_tab;
1690 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1691 struct list_head *stream_list, u32 nref)
1693 if (!lte->will_be_in_output_wim) {
1694 lte->out_refcnt = 0;
1695 list_add_tail(<e->write_streams_list, stream_list);
1696 lte->will_be_in_output_wim = 1;
1698 lte->out_refcnt += nref;
1702 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1705 struct list_head *stream_list = _stream_list;
1706 lte->will_be_in_output_wim = 0;
1707 reference_stream_for_write(lte, stream_list, lte->refcnt);
1712 inode_find_streams_to_reference(const struct wim_inode *inode,
1713 const struct wim_lookup_table *table,
1714 struct list_head *stream_list)
1716 struct wim_lookup_table_entry *lte;
1719 wimlib_assert(inode->i_nlink > 0);
1721 for (i = 0; i <= inode->i_num_ads; i++) {
1722 lte = inode_stream_lte(inode, i, table);
1724 reference_stream_for_write(lte, stream_list,
1726 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1727 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1733 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1735 lte->will_be_in_output_wim = 0;
1740 image_find_streams_to_reference(WIMStruct *wim)
1742 struct wim_image_metadata *imd;
1743 struct wim_inode *inode;
1744 struct wim_lookup_table_entry *lte;
1745 struct list_head *stream_list;
1748 imd = wim_get_current_image_metadata(wim);
1750 image_for_each_unhashed_stream(lte, imd)
1751 lte->will_be_in_output_wim = 0;
1753 stream_list = wim->private;
1754 image_for_each_inode(inode, imd) {
1755 ret = inode_find_streams_to_reference(inode,
1765 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1768 struct list_head *stream_list_ret)
1772 INIT_LIST_HEAD(stream_list_ret);
1774 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1775 (image == 1 && wim->hdr.image_count == 1)))
1777 /* Fast case: Assume that all streams are being written and
1778 * that the reference counts are correct. */
1779 struct wim_lookup_table_entry *lte;
1780 struct wim_image_metadata *imd;
1783 for_lookup_table_entry(wim->lookup_table,
1784 fully_reference_stream_for_write,
1787 for (i = 0; i < wim->hdr.image_count; i++) {
1788 imd = wim->image_metadata[i];
1789 image_for_each_unhashed_stream(lte, imd)
1790 fully_reference_stream_for_write(lte, stream_list_ret);
1793 /* Slow case: Walk through the images being written and
1794 * determine the streams referenced. */
1795 for_lookup_table_entry(wim->lookup_table,
1796 do_stream_set_not_in_output_wim, NULL);
1797 wim->private = stream_list_ret;
1798 ret = for_image(wim, image, image_find_streams_to_reference);
1806 struct insert_other_if_hard_filtered_ctx {
1807 struct stream_size_table *tab;
1808 struct filter_context *filter_ctx;
1812 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1814 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1816 if (!lte->will_be_in_output_wim &&
1817 stream_hard_filtered(lte, ctx->filter_ctx))
1818 stream_size_table_insert(lte, ctx->tab);
1823 determine_stream_size_uniquity(struct list_head *stream_list,
1824 struct wim_lookup_table *lt,
1825 struct filter_context *filter_ctx)
1828 struct stream_size_table tab;
1829 struct wim_lookup_table_entry *lte;
1831 ret = init_stream_size_table(&tab, 9001);
1835 if (may_hard_filter_streams(filter_ctx)) {
1836 struct insert_other_if_hard_filtered_ctx ctx = {
1838 .filter_ctx = filter_ctx,
1840 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1843 list_for_each_entry(lte, stream_list, write_streams_list)
1844 stream_size_table_insert(lte, &tab);
1846 destroy_stream_size_table(&tab);
1851 filter_stream_list_for_write(struct list_head *stream_list,
1852 struct filter_context *filter_ctx)
1854 struct wim_lookup_table_entry *lte, *tmp;
1856 list_for_each_entry_safe(lte, tmp,
1857 stream_list, write_streams_list)
1859 int status = stream_filtered(lte, filter_ctx);
1866 /* Soft filtered. */
1868 /* Hard filtered. */
1869 lte->will_be_in_output_wim = 0;
1870 list_del(<e->lookup_table_list);
1872 list_del(<e->write_streams_list);
1878 * prepare_stream_list_for_write() -
1880 * Prepare the list of streams to write for writing a WIM containing the
1881 * specified image(s) with the specified write flags.
1884 * The WIMStruct on whose behalf the write is occurring.
1887 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1890 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1892 * STREAMS_OK: For writes of all images, assume that all streams in the
1893 * lookup table of @wim and the per-image lists of unhashed streams should
1894 * be taken as-is, and image metadata should not be searched for
1895 * references. This does not exclude filtering with OVERWRITE and
1896 * SKIP_EXTERNAL_WIMS, below.
1898 * OVERWRITE: Streams already present in @wim shall not be returned in
1901 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1902 * @wim, shall be be returned in neither @stream_list_ret nor
1903 * @lookup_table_list_ret.
1906 * List of streams, linked by write_streams_list, that need to be written
1907 * will be returned here.
1909 * Note that this function assumes that unhashed streams will be written;
1910 * it does not take into account that they may become duplicates when
1913 * @lookup_table_list_ret
1914 * List of streams, linked by lookup_table_list, that need to be included
1915 * in the WIM's lookup table will be returned here. This will be a
1916 * superset of the streams in @stream_list_ret.
1918 * This list will be a proper superset of @stream_list_ret if and only if
1919 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1920 * the streams that would otherwise need to be written were already located
1923 * All streams in this list will have @out_refcnt set to the number of
1924 * references to the stream in the output WIM. If
1925 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1926 * may be as low as 0.
1929 * A context for queries of stream filter status with stream_filtered() is
1930 * returned in this location.
1932 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1933 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1934 * lookup table of @wim not inserted into @lookup_table_list_ret.
1936 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1937 * @stream_list_ret that have unique size among all stream entries in
1938 * @stream_list_ret and among all stream entries in the lookup table of @wim
1939 * that are ineligible for being written due to filtering.
1941 * Returns 0 on success; nonzero on read error, memory allocation error, or
1945 prepare_stream_list_for_write(WIMStruct *wim, int image,
1947 struct list_head *stream_list_ret,
1948 struct list_head *lookup_table_list_ret,
1949 struct filter_context *filter_ctx_ret)
1952 struct wim_lookup_table_entry *lte;
1954 filter_ctx_ret->write_flags = write_flags;
1955 filter_ctx_ret->wim = wim;
1957 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1960 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1965 INIT_LIST_HEAD(lookup_table_list_ret);
1966 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1967 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1969 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1974 if (may_filter_streams(filter_ctx_ret))
1975 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1981 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1982 unsigned num_threads,
1983 wimlib_progress_func_t progress_func,
1984 struct list_head *stream_list_override,
1985 struct list_head *lookup_table_list_ret)
1988 struct list_head _stream_list;
1989 struct list_head *stream_list;
1990 struct wim_lookup_table_entry *lte;
1991 struct filter_context _filter_ctx;
1992 struct filter_context *filter_ctx;
1994 if (stream_list_override == NULL) {
1995 /* Normal case: prepare stream list from image(s) being written.
1997 stream_list = &_stream_list;
1998 filter_ctx = &_filter_ctx;
1999 ret = prepare_stream_list_for_write(wim, image, write_flags,
2001 lookup_table_list_ret,
2006 /* Currently only as a result of wimlib_split() being called:
2007 * use stream list already explicitly provided. Use existing
2008 * reference counts. */
2009 stream_list = stream_list_override;
2011 INIT_LIST_HEAD(lookup_table_list_ret);
2012 list_for_each_entry(lte, stream_list, write_streams_list) {
2013 lte->out_refcnt = lte->refcnt;
2014 lte->will_be_in_output_wim = 1;
2015 lte->unique_size = 0;
2016 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2020 return wim_write_stream_list(wim,
2029 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2030 wimlib_progress_func_t progress_func)
2035 int write_resource_flags;
2037 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2038 DEBUG("Not writing any metadata resources.");
2042 write_resource_flags = write_flags_to_resource_flags(write_flags);
2044 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2046 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2047 wim->out_fd.offset);
2050 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2052 if (image == WIMLIB_ALL_IMAGES) {
2054 end_image = wim->hdr.image_count;
2056 start_image = image;
2060 for (int i = start_image; i <= end_image; i++) {
2061 struct wim_image_metadata *imd;
2063 imd = wim->image_metadata[i - 1];
2064 /* Build a new metadata resource only if image was modified from
2065 * the original (or was newly added). Otherwise just copy the
2067 if (imd->modified) {
2068 DEBUG("Image %u was modified; building and writing new "
2069 "metadata resource", i);
2070 ret = write_metadata_resource(wim, i,
2071 write_resource_flags);
2072 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2073 DEBUG("Image %u was not modified; re-using existing "
2074 "metadata resource.", i);
2075 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2078 DEBUG("Image %u was not modified; copying existing "
2079 "metadata resource.", i);
2080 ret = write_wim_resource(imd->metadata_lte,
2082 wim->out_compression_type,
2083 wim->out_chunk_size,
2084 write_resource_flags);
2090 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2095 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2098 DEBUG("Opening \"%"TS"\" for writing.", path);
2100 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2102 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2103 return WIMLIB_ERR_OPEN;
2105 filedes_init(&wim->out_fd, raw_fd);
2110 close_wim_writable(WIMStruct *wim, int write_flags)
2114 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2115 DEBUG("Closing WIM file.");
2116 if (filedes_valid(&wim->out_fd))
2117 if (filedes_close(&wim->out_fd))
2118 ret = WIMLIB_ERR_WRITE;
2120 filedes_invalidate(&wim->out_fd);
2125 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2127 const struct wim_lookup_table_entry *lte1, *lte2;
2129 lte1 = *(const struct wim_lookup_table_entry**)p1;
2130 lte2 = *(const struct wim_lookup_table_entry**)p2;
2132 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2133 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2134 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2135 return cmp_u64(lte1->out_res_offset_in_wim,
2136 lte2->out_res_offset_in_wim);
2141 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2144 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2145 lte2->out_reshdr.offset_in_wim);
2149 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2150 struct wim_reshdr *out_reshdr,
2151 struct list_head *lookup_table_list)
2155 /* Set output resource metadata for streams already present in WIM. */
2156 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2157 struct wim_lookup_table_entry *lte;
2158 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2160 if (lte->resource_location == RESOURCE_IN_WIM &&
2161 lte->rspec->wim == wim)
2163 stream_set_out_reshdr_for_reuse(lte);
2168 ret = sort_stream_list(lookup_table_list,
2169 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2170 cmp_streams_by_out_rspec);
2174 /* Add entries for metadata resources. */
2175 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2179 if (image == WIMLIB_ALL_IMAGES) {
2181 end_image = wim->hdr.image_count;
2183 start_image = image;
2187 /* Push metadata resource lookup table entries onto the front of
2188 * the list in reverse order, so that they're written in order.
2190 for (int i = end_image; i >= start_image; i--) {
2191 struct wim_lookup_table_entry *metadata_lte;
2193 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2194 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2195 metadata_lte->out_refcnt = 1;
2196 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2200 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2202 wim->hdr.part_number,
2204 write_flags_to_resource_flags(write_flags));
2210 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2211 * table, then overwrite the WIM header. By default, closes the WIM file
2212 * descriptor (@wim->out_fd) if successful.
2214 * write_flags is a bitwise OR of the following:
2216 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2217 * Include an integrity table.
2219 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2220 * fsync() the output file before closing it.
2222 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2223 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2224 * stream headers before the lookup table and XML data, and also
2225 * write the WIM header at the end instead of seeking to the
2226 * beginning. Can't be combined with
2227 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2229 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2230 * Don't write the lookup table.
2232 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2233 * When (if) writing the integrity table, re-use entries from the
2234 * existing integrity table, if possible.
2236 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2237 * After writing the XML data but before writing the integrity
2238 * table, write a temporary WIM header and flush the stream so that
2239 * the WIM is less likely to become corrupted upon abrupt program
2241 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2242 * Instead of overwriting the WIM header at the beginning of the
2243 * file, simply append it to the end of the file. (Used when
2245 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2246 * Do not close the file descriptor @wim->out_fd on either success
2248 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2249 * Use the existing <TOTALBYTES> stored in the in-memory XML
2250 * information, rather than setting it to the offset of the XML
2251 * data being written.
2254 finish_write(WIMStruct *wim, int image, int write_flags,
2255 wimlib_progress_func_t progress_func,
2256 struct list_head *lookup_table_list)
2260 int write_resource_flags;
2261 off_t old_lookup_table_end;
2262 off_t new_lookup_table_end;
2265 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2267 write_resource_flags = write_flags_to_resource_flags(write_flags);
2269 /* In the WIM header, there is room for the resource entry for a
2270 * metadata resource labeled as the "boot metadata". This entry should
2271 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2272 * it should be a copy of the resource entry for the image that is
2273 * marked as bootable. This is not well documented... */
2274 if (wim->hdr.boot_idx == 0) {
2275 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2277 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2278 &wim->image_metadata[
2279 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2282 /* Write lookup table. (Save old position first.) */
2283 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2284 wim->hdr.lookup_table_reshdr.size_in_wim;
2285 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2286 ret = write_wim_lookup_table(wim, image, write_flags,
2287 &wim->hdr.lookup_table_reshdr,
2293 /* Write XML data. */
2294 xml_totalbytes = wim->out_fd.offset;
2295 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2296 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2297 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2298 &wim->hdr.xml_data_reshdr,
2299 write_resource_flags);
2303 /* Write integrity table (optional). */
2304 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2305 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2306 struct wim_header checkpoint_hdr;
2307 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2308 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2309 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2310 ret = write_wim_header_at_offset(&checkpoint_hdr,
2316 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2317 old_lookup_table_end = 0;
2319 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2320 wim->hdr.lookup_table_reshdr.size_in_wim;
2322 ret = write_integrity_table(wim,
2323 new_lookup_table_end,
2324 old_lookup_table_end,
2329 /* No integrity table. */
2330 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2333 /* Now that all information in the WIM header has been determined, the
2334 * preliminary header written earlier can be overwritten, the header of
2335 * the existing WIM file can be overwritten, or the final header can be
2336 * written to the end of the pipable WIM. */
2337 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2339 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2340 hdr_offset = wim->out_fd.offset;
2341 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2342 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2346 /* Possibly sync file data to disk before closing. On POSIX systems, it
2347 * is necessary to do this before using rename() to overwrite an
2348 * existing file with a new file. Otherwise, data loss would occur if
2349 * the system is abruptly terminated when the metadata for the rename
2350 * operation has been written to disk, but the new file data has not.
2352 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2353 DEBUG("Syncing WIM file.");
2354 if (fsync(wim->out_fd.fd)) {
2355 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2356 return WIMLIB_ERR_WRITE;
2360 if (close_wim_writable(wim, write_flags)) {
2361 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2362 return WIMLIB_ERR_WRITE;
2368 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2370 lock_wim(WIMStruct *wim, int fd)
2373 if (fd != -1 && !wim->wim_locked) {
2374 ret = flock(fd, LOCK_EX | LOCK_NB);
2376 if (errno == EWOULDBLOCK) {
2377 ERROR("`%"TS"' is already being modified or has been "
2378 "mounted read-write\n"
2379 " by another process!", wim->filename);
2380 ret = WIMLIB_ERR_ALREADY_LOCKED;
2382 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2387 wim->wim_locked = 1;
2395 * write_pipable_wim():
2397 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2398 * capable of being applied from a pipe).
2400 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2401 * images can be applied from them sequentially when the file data is sent over
2402 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2403 * The modifications made to the WIM format for pipable WIMs are:
2405 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2406 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2407 * stops other software from trying to read the file as a normal WIM.
2409 * - The header at the beginning of the file does not contain all the normal
2410 * information; in particular it will have all 0's for the lookup table and
2411 * XML data resource entries. This is because this information cannot be
2412 * determined until the lookup table and XML data have been written.
2413 * Consequently, wimlib will write the full header at the very end of the
2414 * file. The header at the end, however, is only used when reading the WIM
2415 * from a seekable file (not a pipe).
2417 * - An extra copy of the XML data is placed directly after the header. This
2418 * allows image names and sizes to be determined at an appropriate time when
2419 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2420 * WIM is read from a seekable file (not a pipe).
2422 * - The format of resources, or streams, has been modified to allow them to be
2423 * used before the "lookup table" has been read. Each stream is prefixed with
2424 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2425 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2426 * uncompressed stream size, and flags that indicate whether the stream is
2427 * compressed. The data of uncompressed streams then follows literally, while
2428 * the data of compressed streams follows in a modified format. Compressed
2429 * streams do not begin with a chunk table, since the chunk table cannot be
2430 * written until all chunks have been compressed. Instead, each compressed
2431 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2432 * Furthermore, the chunk table is written at the end of the resource instead
2433 * of the start. Note: chunk offsets are given in the chunk table as if the
2434 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2435 * used if the WIM is being read from a seekable file (not a pipe).
2437 * - Metadata resources always come before other file resources (streams).
2438 * (This does not by itself constitute an incompatibility with normal WIMs,
2439 * since this is valid in normal WIMs.)
2441 * - At least up to the end of the file resources, all components must be packed
2442 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2443 * not by itself consititute an incompatibility with normal WIMs, since this
2444 * is valid in normal WIMs.)
2446 * Note: the lookup table, XML data, and header at the end are not used when
2447 * applying from a pipe. They exist to support functionality such as image
2448 * application and export when the WIM is *not* read from a pipe.
2450 * Layout of pipable WIM:
2452 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2453 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2454 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2456 * Layout of normal WIM:
2458 * +--------+-----------------------------+-------------------------+
2459 * | Header | File and metadata resources | Lookup table | XML data |
2460 * +--------+-----------------------------+-------------------------+
2462 * An optional integrity table can follow the final XML data in both normal and
2463 * pipable WIMs. However, due to implementation details, wimlib currently can
2464 * only include an integrity table in a pipable WIM when writing it to a
2465 * seekable file (not a pipe).
2467 * Do note that since pipable WIMs are not supported by Microsoft's software,
2468 * wimlib does not create them unless explicitly requested (with
2469 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2470 * characters to identify the file.
2473 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2474 unsigned num_threads, wimlib_progress_func_t progress_func,
2475 struct list_head *stream_list_override,
2476 struct list_head *lookup_table_list_ret)
2479 struct wim_reshdr xml_reshdr;
2481 WARNING("Creating a pipable WIM, which will "
2483 " with Microsoft's software (wimgapi/imagex/Dism).");
2485 /* At this point, the header at the beginning of the file has already
2488 /* For efficiency, when wimlib adds an image to the WIM with
2489 * wimlib_add_image(), the SHA1 message digests of files is not
2490 * calculated; instead, they are calculated while the files are being
2491 * written. However, this does not work when writing a pipable WIM,
2492 * since when writing a stream to a pipable WIM, its SHA1 message digest
2493 * needs to be known before the stream data is written. Therefore,
2494 * before getting much farther, we need to pre-calculate the SHA1
2495 * message digests of all streams that will be written. */
2496 ret = wim_checksum_unhashed_streams(wim);
2500 /* Write extra copy of the XML data. */
2501 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2503 WRITE_RESOURCE_FLAG_PIPABLE);
2507 /* Write metadata resources for the image(s) being included in the
2509 ret = write_wim_metadata_resources(wim, image, write_flags,
2514 /* Write streams needed for the image(s) being included in the output
2515 * WIM, or streams needed for the split WIM part. */
2516 return write_wim_streams(wim, image, write_flags, num_threads,
2517 progress_func, stream_list_override,
2518 lookup_table_list_ret);
2520 /* The lookup table, XML data, and header at end are handled by
2521 * finish_write(). */
2524 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2527 write_wim_part(WIMStruct *wim,
2528 const void *path_or_fd,
2531 unsigned num_threads,
2532 wimlib_progress_func_t progress_func,
2533 unsigned part_number,
2534 unsigned total_parts,
2535 struct list_head *stream_list_override,
2539 struct wim_header hdr_save;
2540 struct list_head lookup_table_list;
2542 if (total_parts == 1)
2543 DEBUG("Writing standalone WIM.");
2545 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2546 if (image == WIMLIB_ALL_IMAGES)
2547 DEBUG("Including all images.");
2549 DEBUG("Including image %d only.", image);
2550 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2551 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2553 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2554 DEBUG("Write flags: 0x%08x", write_flags);
2556 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2557 DEBUG("\tCHECK_INTEGRITY");
2559 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2562 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2563 DEBUG("\tRECOMPRESS");
2565 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2568 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2571 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2572 DEBUG("\tIGNORE_READONLY_FLAG");
2574 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2577 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2578 DEBUG("\tNOT_PIPABLE");
2580 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2581 DEBUG("\tPACK_STREAMS");
2583 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2584 DEBUG("\tFILE_DESCRIPTOR");
2586 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2587 DEBUG("\tNO_METADATA");
2589 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2590 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2592 if (num_threads == 0)
2593 DEBUG("Number of threads: autodetect");
2595 DEBUG("Number of threads: %u", num_threads);
2596 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2597 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2598 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2599 "specified" : "generate new"));
2601 /* Internally, this is always called with a valid part number and total
2603 wimlib_assert(total_parts >= 1);
2604 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2606 /* A valid image (or all images) must be specified. */
2607 if (image != WIMLIB_ALL_IMAGES &&
2608 (image < 1 || image > wim->hdr.image_count))
2609 return WIMLIB_ERR_INVALID_IMAGE;
2611 /* If we need to write metadata resources, make sure the ::WIMStruct has
2612 * the needed information attached (e.g. is not a resource-only WIM,
2613 * such as a non-first part of a split WIM). */
2614 if (!wim_has_metadata(wim) &&
2615 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2616 return WIMLIB_ERR_METADATA_NOT_FOUND;
2618 /* Check for contradictory flags. */
2619 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2620 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2621 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2622 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2623 return WIMLIB_ERR_INVALID_PARAM;
2625 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2626 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2627 == (WIMLIB_WRITE_FLAG_PIPABLE |
2628 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2629 return WIMLIB_ERR_INVALID_PARAM;
2631 /* Save previous header, then start initializing the new one. */
2632 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2634 /* Set default integrity, pipable, and packed stream flags. */
2635 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2636 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2637 if (wim_is_pipable(wim)) {
2638 DEBUG("WIM is pipable; default to PIPABLE.");
2639 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2642 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2643 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2644 if (wim_has_integrity_table(wim)) {
2645 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2646 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2649 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2650 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2651 == (WIMLIB_WRITE_FLAG_PIPABLE |
2652 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2654 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2655 return WIMLIB_ERR_INVALID_PARAM;
2658 /* Set appropriate magic number. */
2659 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2660 wim->hdr.magic = PWM_MAGIC;
2662 wim->hdr.magic = WIM_MAGIC;
2664 /* Set appropriate version number. */
2665 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2666 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2667 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2669 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2671 /* Clear header flags that will be set automatically. */
2672 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2673 WIM_HDR_FLAG_RESOURCE_ONLY |
2674 WIM_HDR_FLAG_SPANNED |
2675 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2677 /* Set SPANNED header flag if writing part of a split WIM. */
2678 if (total_parts != 1)
2679 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2681 /* Set part number and total parts of split WIM. This will be 1 and 1
2682 * if the WIM is standalone. */
2683 wim->hdr.part_number = part_number;
2684 wim->hdr.total_parts = total_parts;
2686 /* Set compression type if different. */
2687 if (wim->compression_type != wim->out_compression_type) {
2688 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2689 wimlib_assert(ret == 0);
2692 /* Set chunk size if different. */
2693 wim->hdr.chunk_size = wim->out_chunk_size;
2695 /* Use GUID if specified; otherwise generate a new one. */
2697 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2698 else if (!wim->guid_set_explicitly)
2699 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2701 /* Clear references to resources that have not been written yet. */
2702 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2703 zero_reshdr(&wim->hdr.xml_data_reshdr);
2704 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2705 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2707 /* Set image count and boot index correctly for single image writes. */
2708 if (image != WIMLIB_ALL_IMAGES) {
2709 wim->hdr.image_count = 1;
2710 if (wim->hdr.boot_idx == image)
2711 wim->hdr.boot_idx = 1;
2713 wim->hdr.boot_idx = 0;
2716 /* Split WIMs can't be bootable. */
2717 if (total_parts != 1)
2718 wim->hdr.boot_idx = 0;
2720 /* Initialize output file descriptor. */
2721 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2722 /* File descriptor was explicitly provided. Return error if
2723 * file descriptor is not seekable, unless writing a pipable WIM
2725 wim->out_fd.fd = *(const int*)path_or_fd;
2726 wim->out_fd.offset = 0;
2727 if (!filedes_is_seekable(&wim->out_fd)) {
2728 ret = WIMLIB_ERR_INVALID_PARAM;
2729 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2730 goto out_restore_hdr;
2731 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2732 ERROR("Can't include integrity check when "
2733 "writing pipable WIM to pipe!");
2734 goto out_restore_hdr;
2739 /* Filename of WIM to write was provided; open file descriptor
2741 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2742 O_TRUNC | O_CREAT | O_RDWR);
2744 goto out_restore_hdr;
2747 /* Write initial header. This is merely a "dummy" header since it
2748 * doesn't have all the information yet, so it will be overwritten later
2749 * (unless writing a pipable WIM). */
2750 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2751 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2752 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2753 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2755 goto out_restore_hdr;
2757 /* Write metadata resources and streams. */
2758 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2759 /* Default case: create a normal (non-pipable) WIM. */
2760 ret = write_wim_streams(wim, image, write_flags, num_threads,
2761 progress_func, stream_list_override,
2762 &lookup_table_list);
2764 goto out_restore_hdr;
2766 ret = write_wim_metadata_resources(wim, image, write_flags,
2769 goto out_restore_hdr;
2771 /* Non-default case: create pipable WIM. */
2772 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2773 progress_func, stream_list_override,
2774 &lookup_table_list);
2776 goto out_restore_hdr;
2777 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2781 /* Write lookup table, XML data, and (optional) integrity table. */
2782 ret = finish_write(wim, image, write_flags, progress_func,
2783 &lookup_table_list);
2785 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2786 (void)close_wim_writable(wim, write_flags);
2787 DEBUG("ret=%d", ret);
2791 /* Write a standalone WIM to a file or file descriptor. */
2793 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2794 int image, int write_flags, unsigned num_threads,
2795 wimlib_progress_func_t progress_func)
2797 return write_wim_part(wim, path_or_fd, image, write_flags,
2798 num_threads, progress_func, 1, 1, NULL, NULL);
2801 /* API function documented in wimlib.h */
2803 wimlib_write(WIMStruct *wim, const tchar *path,
2804 int image, int write_flags, unsigned num_threads,
2805 wimlib_progress_func_t progress_func)
2807 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2808 return WIMLIB_ERR_INVALID_PARAM;
2810 if (path == NULL || path[0] == T('\0'))
2811 return WIMLIB_ERR_INVALID_PARAM;
2813 return write_standalone_wim(wim, path, image, write_flags,
2814 num_threads, progress_func);
2817 /* API function documented in wimlib.h */
2819 wimlib_write_to_fd(WIMStruct *wim, int fd,
2820 int image, int write_flags, unsigned num_threads,
2821 wimlib_progress_func_t progress_func)
2823 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2824 return WIMLIB_ERR_INVALID_PARAM;
2827 return WIMLIB_ERR_INVALID_PARAM;
2829 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2831 return write_standalone_wim(wim, &fd, image, write_flags,
2832 num_threads, progress_func);
2836 any_images_modified(WIMStruct *wim)
2838 for (int i = 0; i < wim->hdr.image_count; i++)
2839 if (wim->image_metadata[i]->modified)
2845 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2847 const WIMStruct *wim = _wim;
2848 off_t end_offset = *(const off_t*)wim->private;
2850 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2851 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2852 return WIMLIB_ERR_RESOURCE_ORDER;
2856 /* Make sure no file or metadata resources are located after the XML data (or
2857 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2858 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2860 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2865 wim->private = &end_offset;
2866 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2870 for (i = 0; i < wim->hdr.image_count; i++) {
2871 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2879 * Overwrite a WIM, possibly appending streams to it.
2881 * A WIM looks like (or is supposed to look like) the following:
2883 * Header (212 bytes)
2884 * Streams and metadata resources (variable size)
2885 * Lookup table (variable size)
2886 * XML data (variable size)
2887 * Integrity table (optional) (variable size)
2889 * If we are not adding any streams or metadata resources, the lookup table is
2890 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2891 * header. This operation is potentially unsafe if the program is abruptly
2892 * terminated while the XML data or integrity table are being overwritten, but
2893 * before the new header has been written. To partially alleviate this problem,
2894 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2895 * finish_write() to cause a temporary WIM header to be written after the XML
2896 * data has been written. This may prevent the WIM from becoming corrupted if
2897 * the program is terminated while the integrity table is being calculated (but
2898 * no guarantees, due to write re-ordering...).
2900 * If we are adding new streams or images (metadata resources), the lookup table
2901 * needs to be changed, and those streams need to be written. In this case, we
2902 * try to perform a safe update of the WIM file by writing the streams *after*
2903 * the end of the previous WIM, then writing the new lookup table, XML data, and
2904 * (optionally) integrity table following the new streams. This will produce a
2905 * layout like the following:
2907 * Header (212 bytes)
2908 * (OLD) Streams and metadata resources (variable size)
2909 * (OLD) Lookup table (variable size)
2910 * (OLD) XML data (variable size)
2911 * (OLD) Integrity table (optional) (variable size)
2912 * (NEW) Streams and metadata resources (variable size)
2913 * (NEW) Lookup table (variable size)
2914 * (NEW) XML data (variable size)
2915 * (NEW) Integrity table (optional) (variable size)
2917 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2918 * the header is overwritten to point to the new lookup table, XML data, and
2919 * integrity table, to produce the following layout:
2921 * Header (212 bytes)
2922 * Streams and metadata resources (variable size)
2923 * Nothing (variable size)
2924 * More Streams and metadata resources (variable size)
2925 * Lookup table (variable size)
2926 * XML data (variable size)
2927 * Integrity table (optional) (variable size)
2929 * This method allows an image to be appended to a large WIM very quickly, and
2930 * is is crash-safe except in the case of write re-ordering, but the
2931 * disadvantage is that a small hole is left in the WIM where the old lookup
2932 * table, xml data, and integrity table were. (These usually only take up a
2933 * small amount of space compared to the streams, however.)
2936 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2937 unsigned num_threads,
2938 wimlib_progress_func_t progress_func)
2942 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2943 struct wim_header hdr_save;
2944 struct list_head stream_list;
2945 struct list_head lookup_table_list;
2946 struct filter_context filter_ctx;
2948 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2950 /* Save original header so it can be restored in case of error */
2951 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2953 /* Set default integrity flag. */
2954 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2955 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2956 if (wim_has_integrity_table(wim))
2957 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2959 /* Set WIM version if adding packed streams. */
2960 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2961 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2963 /* Set additional flags for overwrite. */
2964 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2965 WIMLIB_WRITE_FLAG_STREAMS_OK;
2967 /* Make sure that the integrity table (if present) is after the XML
2968 * data, and that there are no stream resources, metadata resources, or
2969 * lookup tables after the XML data. Otherwise, these data would be
2971 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2972 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2973 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2974 wim->hdr.lookup_table_reshdr.size_in_wim;
2975 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2976 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2977 WARNING("Didn't expect the integrity table to be before the XML data");
2978 ret = WIMLIB_ERR_RESOURCE_ORDER;
2979 goto out_restore_memory_hdr;
2982 if (old_lookup_table_end > old_xml_begin) {
2983 WARNING("Didn't expect the lookup table to be after the XML data");
2984 ret = WIMLIB_ERR_RESOURCE_ORDER;
2985 goto out_restore_memory_hdr;
2988 /* Set @old_wim_end, which indicates the point beyond which we don't
2989 * allow any file and metadata resources to appear without returning
2990 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2991 * overwrite these resources). */
2992 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2993 /* If no images have been modified and no images have been
2994 * deleted, a new lookup table does not need to be written. We
2995 * shall write the new XML data and optional integrity table
2996 * immediately after the lookup table. Note that this may
2997 * overwrite an existing integrity table. */
2998 DEBUG("Skipping writing lookup table "
2999 "(no images modified or deleted)");
3000 old_wim_end = old_lookup_table_end;
3001 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3002 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3003 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3004 /* Old WIM has an integrity table; begin writing new streams
3006 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3007 wim->hdr.integrity_table_reshdr.size_in_wim;
3009 /* No existing integrity table; begin writing new streams after
3010 * the old XML data. */
3011 old_wim_end = old_xml_end;
3014 ret = check_resource_offsets(wim, old_wim_end);
3016 goto out_restore_memory_hdr;
3018 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3019 &stream_list, &lookup_table_list,
3022 goto out_restore_memory_hdr;
3024 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3026 goto out_restore_memory_hdr;
3028 ret = lock_wim(wim, wim->out_fd.fd);
3032 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3033 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3034 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3036 ERROR_WITH_ERRNO("Error updating WIM header flags");
3037 goto out_unlock_wim;
3040 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3041 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3042 ret = WIMLIB_ERR_WRITE;
3043 goto out_restore_physical_hdr;
3046 ret = wim_write_stream_list(wim,
3055 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3056 write_flags, progress_func);
3060 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3061 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3062 progress_func, &lookup_table_list);
3066 wim->wim_locked = 0;
3070 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3071 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3072 wim->filename, old_wim_end);
3073 /* Return value of ftruncate() is ignored because this is
3074 * already an error path. */
3075 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3077 out_restore_physical_hdr:
3078 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3080 wim->wim_locked = 0;
3082 (void)close_wim_writable(wim, write_flags);
3083 out_restore_memory_hdr:
3084 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3089 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3090 unsigned num_threads,
3091 wimlib_progress_func_t progress_func)
3093 size_t wim_name_len;
3096 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3098 /* Write the WIM to a temporary file in the same directory as the
3100 wim_name_len = tstrlen(wim->filename);
3101 tchar tmpfile[wim_name_len + 10];
3102 tmemcpy(tmpfile, wim->filename, wim_name_len);
3103 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3104 tmpfile[wim_name_len + 9] = T('\0');
3106 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3107 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3108 num_threads, progress_func);
3114 if (filedes_valid(&wim->in_fd)) {
3115 filedes_close(&wim->in_fd);
3116 filedes_invalidate(&wim->in_fd);
3119 /* Rename the new WIM file to the original WIM file. Note: on Windows
3120 * this actually calls win32_rename_replacement(), not _wrename(), so
3121 * that removing the existing destination file can be handled. */
3122 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3123 ret = trename(tmpfile, wim->filename);
3125 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3126 tmpfile, wim->filename);
3133 return WIMLIB_ERR_RENAME;
3136 if (progress_func) {
3137 union wimlib_progress_info progress;
3138 progress.rename.from = tmpfile;
3139 progress.rename.to = wim->filename;
3140 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3145 /* Determine if the specified WIM file may be updated by appending in-place
3146 * rather than writing and replacing it with an entirely new file. */
3148 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3150 /* REBUILD flag forces full rebuild. */
3151 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3154 /* Deletions cause full rebuild by default. */
3155 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3158 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3159 * turned into a pipable WIM in-place. */
3160 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3163 /* wimlib allows multiple packs in a single WIM, but they don't seem to
3164 * be compatible with WIMGAPI, so force all streams to be repacked if
3165 * the WIM already may have contained a pack and PACK_STREAMS was
3167 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3168 wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3171 /* The default compression type and compression chunk size selected for
3172 * the output WIM must be the same as those currently used for the WIM.
3174 if (wim->compression_type != wim->out_compression_type)
3176 if (wim->chunk_size != wim->out_chunk_size)
3182 /* API function documented in wimlib.h */
3184 wimlib_overwrite(WIMStruct *wim, int write_flags,
3185 unsigned num_threads,
3186 wimlib_progress_func_t progress_func)
3191 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3192 return WIMLIB_ERR_INVALID_PARAM;
3195 return WIMLIB_ERR_NO_FILENAME;
3197 orig_hdr_flags = wim->hdr.flags;
3198 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3199 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3200 ret = can_modify_wim(wim);
3201 wim->hdr.flags = orig_hdr_flags;
3205 if (can_overwrite_wim_inplace(wim, write_flags)) {
3206 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3208 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3210 WARNING("Falling back to re-building entire WIM");
3212 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,