4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/chunk_compressor.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/integrity.h"
43 #include "wimlib/lookup_table.h"
44 #include "wimlib/metadata.h"
45 #include "wimlib/resource.h"
47 # include "wimlib/win32.h" /* win32_rename_replacement() */
49 #include "wimlib/write.h"
50 #include "wimlib/xml.h"
61 /* wimlib internal flags used when writing resources. */
62 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
63 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
64 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
67 write_flags_to_resource_flags(int write_flags)
69 int write_resource_flags = 0;
71 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
72 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
73 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
74 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
75 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
77 return write_resource_flags;
80 struct filter_context {
85 /* Determine specified stream should be filtered out from the write.
89 * < 0 : The stream should be hard-filtered; that is, not included in the
91 * 0 : The stream should not be filtered out.
92 * > 0 : The stream should be soft-filtered; that is, it already exists in the
93 * WIM file and may not need to be written again.
96 stream_filtered(const struct wim_lookup_table_entry *lte,
97 const struct filter_context *ctx)
99 int write_flags = ctx->write_flags;
100 WIMStruct *wim = ctx->wim;
105 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
106 lte->resource_location == RESOURCE_IN_WIM &&
107 lte->rspec->wim == wim)
110 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
111 lte->resource_location == RESOURCE_IN_WIM &&
112 lte->rspec->wim != wim)
119 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
120 struct filter_context *ctx)
122 return stream_filtered(lte, ctx) < 0;
126 may_soft_filter_streams(const struct filter_context *ctx)
130 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
134 may_hard_filter_streams(const struct filter_context *ctx)
138 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
142 may_filter_streams(const struct filter_context *ctx)
144 return (may_soft_filter_streams(ctx) ||
145 may_hard_filter_streams(ctx));
149 /* Return true if the specified resource is compressed and the compressed data
150 * can be reused with the specified output parameters. */
152 can_raw_copy(const struct wim_lookup_table_entry *lte,
153 int write_resource_flags, int out_ctype, u32 out_chunk_size)
155 const struct wim_resource_spec *rspec;
157 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
160 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
163 if (lte->resource_location != RESOURCE_IN_WIM)
168 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
172 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
173 /* Normal compressed resource: Must use same compression type
175 return (rspec->wim->compression_type == out_ctype &&
176 rspec->wim->chunk_size == out_chunk_size);
179 /* XXX: For compatibility, we can't allow multiple packed resources per
182 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
183 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
185 /* Packed resource: Such resources may contain multiple streams,
186 * and in general only a subset of them need to be written. As
187 * a heuristic, re-use the raw data if at least half the
188 * uncompressed size is being written. */
190 /* Note: packed resources contain a header that specifies the
191 * compression type and chunk size; therefore we don't need to
192 * check if they are compatible with @out_ctype and
193 * @out_chunk_size. */
195 struct wim_lookup_table_entry *res_stream;
198 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
199 if (res_stream->will_be_in_output_wim)
200 write_size += res_stream->size;
202 return (write_size > rspec->uncompressed_size / 2);
210 filter_resource_flags(u8 flags)
212 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
213 WIM_RESHDR_FLAG_COMPRESSED |
214 WIM_RESHDR_FLAG_SPANNED |
215 WIM_RESHDR_FLAG_FREE));
219 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
221 const struct wim_resource_spec *rspec;
223 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
226 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
228 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
230 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
231 lte->out_reshdr.uncompressed_size = 0;
232 lte->out_reshdr.size_in_wim = lte->size;
234 lte->out_res_offset_in_wim = rspec->offset_in_wim;
235 lte->out_res_size_in_wim = rspec->size_in_wim;
236 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
238 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
240 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
241 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
242 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
244 lte->out_reshdr.flags = lte->flags;
248 /* Write the header for a stream in a pipable WIM. */
250 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
251 struct filedes *out_fd,
252 int additional_reshdr_flags)
254 struct pwm_stream_hdr stream_hdr;
258 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
259 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
260 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
261 zero_out_hash(stream_hdr.hash);
263 wimlib_assert(!lte->unhashed);
264 copy_hash(stream_hdr.hash, lte->hash);
267 reshdr_flags = filter_resource_flags(lte->flags);
268 reshdr_flags |= additional_reshdr_flags;
269 stream_hdr.flags = cpu_to_le32(reshdr_flags);
270 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
272 ERROR_WITH_ERRNO("Write error");
276 struct write_streams_progress_data {
277 wimlib_progress_func_t progress_func;
278 union wimlib_progress_info progress;
279 uint64_t next_progress;
280 WIMStruct *prev_wim_part;
284 do_write_streams_progress(struct write_streams_progress_data *progress_data,
285 struct wim_lookup_table_entry *cur_stream,
290 union wimlib_progress_info *progress = &progress_data->progress;
294 progress->write_streams.total_bytes -= complete_size;
295 progress->write_streams.total_streams -= complete_count;
296 if (progress_data->next_progress != ~(uint64_t)0 &&
297 progress_data->next_progress > progress->write_streams.total_bytes)
299 progress_data->next_progress = progress->write_streams.total_bytes;
302 progress->write_streams.completed_bytes += complete_size;
303 progress->write_streams.completed_streams += complete_count;
306 new_wim_part = false;
307 if (cur_stream->resource_location == RESOURCE_IN_WIM &&
308 cur_stream->rspec->wim != progress_data->prev_wim_part)
310 if (progress_data->prev_wim_part) {
312 progress->write_streams.completed_parts++;
314 progress_data->prev_wim_part = cur_stream->rspec->wim;
317 if (progress_data->progress_func
318 && (progress->write_streams.completed_bytes >= progress_data->next_progress
321 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
323 if (progress_data->next_progress == progress->write_streams.total_bytes) {
324 progress_data->next_progress = ~(uint64_t)0;
326 progress_data->next_progress =
327 min(progress->write_streams.total_bytes,
328 progress->write_streams.completed_bytes +
329 progress->write_streams.total_bytes / 100);
334 struct write_streams_ctx {
335 /* File descriptor the streams are being written to. */
336 struct filedes *out_fd;
338 /* Lookup table for the WIMStruct on whose behalf the streams are being
340 struct wim_lookup_table *lookup_table;
342 /* Compression format to use. */
345 /* Maximum uncompressed chunk size in compressed resources to use. */
348 /* Flags that affect how the streams will be written. */
349 int write_resource_flags;
351 /* Data used for issuing WRITE_STREAMS progress. */
352 struct write_streams_progress_data progress_data;
354 struct filter_context *filter_ctx;
356 /* Upper bound on the total number of bytes that need to be compressed.
358 u64 num_bytes_to_compress;
360 /* Pointer to the chunk_compressor implementation being used for
361 * compressing chunks of data, or NULL if chunks are being written
363 struct chunk_compressor *compressor;
365 /* Buffer for dividing the read data into chunks of size
366 * @out_chunk_size. */
369 /* Number of bytes in @chunk_buf that are currently filled. */
370 size_t chunk_buf_filled;
372 /* List of streams that currently have chunks being compressed. */
373 struct list_head pending_streams;
375 /* List of streams in the resource pack. Streams are moved here after
376 * @pending_streams only when writing a packed resource. */
377 struct list_head pack_streams;
379 /* Set to true if the stream currently being read was a duplicate, and
380 * therefore the corresponding stream entry needs to be freed once the
381 * read finishes. (In this case we add the duplicate entry to
382 * pending_streams rather than the entry being read.) */
383 bool stream_was_duplicate;
385 /* Current uncompressed offset in the stream being read. */
386 u64 cur_read_stream_offset;
388 /* Uncompressed size of the stream currently being read. */
389 u64 cur_read_stream_size;
391 /* Current uncompressed offset in the stream being written. */
392 u64 cur_write_stream_offset;
394 /* Uncompressed size of resource currently being written. */
395 u64 cur_write_res_size;
397 /* Array that is filled in with compressed chunk sizes as a resource is
401 /* Index of next entry in @chunk_csizes to fill in. */
404 /* Number of entries in @chunk_csizes currently allocated. */
405 size_t num_alloc_chunks;
407 /* Offset in the output file of the start of the chunks of the resource
408 * currently being written. */
409 u64 chunks_start_offset;
413 get_chunk_entry_size(u64 res_size, int write_resource_flags)
415 if (res_size <= UINT32_MAX ||
416 (write_resource_flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
422 /* Reserve space for the chunk table and prepare to accumulate the chunk table
425 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
427 u64 expected_num_chunks;
428 u64 expected_num_chunk_entries;
432 /* Calculate the number of chunks and chunk entries that should be
433 * needed for the resource. These normally will be the final values,
434 * but in PACKED_STREAMS mode some of the streams we're planning to
435 * write into the resource may be duplicates, and therefore discarded,
436 * potentially decreasing the number of chunk entries needed. */
437 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
438 expected_num_chunk_entries = expected_num_chunks;
439 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
440 expected_num_chunk_entries--;
442 /* Make sure the chunk_csizes array is long enough to store the
443 * compressed size of each chunk. */
444 if (expected_num_chunks > ctx->num_alloc_chunks) {
445 u64 new_length = expected_num_chunks + 50;
447 if ((size_t)new_length != new_length) {
448 ERROR("Resource size too large (%"PRIu64" bytes!",
450 return WIMLIB_ERR_NOMEM;
453 FREE(ctx->chunk_csizes);
454 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
455 if (ctx->chunk_csizes == NULL) {
456 ctx->num_alloc_chunks = 0;
457 return WIMLIB_ERR_NOMEM;
459 ctx->num_alloc_chunks = new_length;
462 ctx->chunk_index = 0;
464 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
465 /* Reserve space for the chunk table in the output file. In the
466 * case of packed resources this reserves the upper bound for
467 * the needed space, not necessarily the exact space which will
468 * prove to be needed. At this point, we just use @chunk_csizes
469 * for a buffer of 0's because the actual compressed chunk sizes
471 reserve_size = expected_num_chunk_entries *
472 get_chunk_entry_size(res_expected_size,
473 ctx->write_resource_flags);
474 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
475 reserve_size += sizeof(struct alt_chunk_table_header_disk);
476 memset(ctx->chunk_csizes, 0, reserve_size);
477 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
485 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
489 wimlib_assert(res_expected_size != 0);
491 if (ctx->compressor != NULL) {
492 ret = begin_chunk_table(ctx, res_expected_size);
497 /* Output file descriptor is now positioned at the offset at which to
498 * write the first chunk of the resource. */
499 ctx->chunks_start_offset = ctx->out_fd->offset;
500 ctx->cur_write_stream_offset = 0;
501 ctx->cur_write_res_size = res_expected_size;
506 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
507 u64 *res_start_offset_ret, u64 *res_store_size_ret)
509 size_t actual_num_chunks;
510 size_t actual_num_chunk_entries;
511 size_t chunk_entry_size;
514 actual_num_chunks = ctx->chunk_index;
515 actual_num_chunk_entries = actual_num_chunks;
516 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
517 actual_num_chunk_entries--;
519 chunk_entry_size = get_chunk_entry_size(res_actual_size,
520 ctx->write_resource_flags);
522 typedef le64 __attribute__((may_alias)) aliased_le64_t;
523 typedef le32 __attribute__((may_alias)) aliased_le32_t;
525 if (chunk_entry_size == 4) {
526 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
528 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
529 for (size_t i = 0; i < actual_num_chunk_entries; i++)
530 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
532 u32 offset = ctx->chunk_csizes[0];
533 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
534 u32 next_size = ctx->chunk_csizes[i + 1];
535 entries[i] = cpu_to_le32(offset);
540 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
542 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
543 for (size_t i = 0; i < actual_num_chunk_entries; i++)
544 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
546 u64 offset = ctx->chunk_csizes[0];
547 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
548 u64 next_size = ctx->chunk_csizes[i + 1];
549 entries[i] = cpu_to_le64(offset);
555 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
556 u64 res_start_offset;
559 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
560 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
563 res_end_offset = ctx->out_fd->offset;
564 res_start_offset = ctx->chunks_start_offset;
566 res_end_offset = ctx->out_fd->offset;
568 u64 chunk_table_offset;
570 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
572 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
573 struct alt_chunk_table_header_disk hdr;
575 hdr.res_usize = cpu_to_le64(res_actual_size);
576 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
577 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
579 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
580 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
581 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
583 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
584 chunk_table_offset - sizeof(hdr));
587 res_start_offset = chunk_table_offset - sizeof(hdr);
589 res_start_offset = chunk_table_offset;
592 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
593 chunk_table_size, chunk_table_offset);
598 *res_start_offset_ret = res_start_offset;
599 *res_store_size_ret = res_end_offset - res_start_offset;
604 ERROR_WITH_ERRNO("Write error");
608 /* Finish writing a WIM resource by writing or updating the chunk table (if not
609 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
611 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
615 u64 res_uncompressed_size;
616 u64 res_offset_in_wim;
618 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
619 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS));
620 res_uncompressed_size = ctx->cur_write_res_size;
622 if (ctx->compressor) {
623 ret = end_chunk_table(ctx, res_uncompressed_size,
624 &res_offset_in_wim, &res_size_in_wim);
628 res_offset_in_wim = ctx->chunks_start_offset;
629 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
631 out_reshdr->uncompressed_size = res_uncompressed_size;
632 out_reshdr->size_in_wim = res_size_in_wim;
633 out_reshdr->offset_in_wim = res_offset_in_wim;
634 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
635 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
639 /* Begin processing a stream for writing. */
641 write_stream_begin_read(struct wim_lookup_table_entry *lte,
642 bool is_partial_res, void *_ctx)
644 struct write_streams_ctx *ctx = _ctx;
647 wimlib_assert(lte->size > 0);
649 ctx->cur_read_stream_offset = 0;
650 ctx->cur_read_stream_size = lte->size;
652 /* As an optimization, we allow some streams to be "unhashed", meaning
653 * their SHA1 message digests are unknown. This is the case with
654 * streams that are added by scanning a directry tree with
655 * wimlib_add_image(), for example. Since WIM uses single-instance
656 * streams, we don't know whether such each such stream really need to
657 * written until it is actually checksummed, unless it has a unique
658 * size. In such cases we read and checksum the stream in this
659 * function, thereby advancing ahead of read_stream_list(), which will
660 * still provide the data again to write_stream_process_chunk(). This
661 * is okay because an unhashed stream cannot be in a WIM resource, which
662 * might be costly to decompress. */
663 ctx->stream_was_duplicate = false;
664 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
666 wimlib_assert(!is_partial_res);
668 struct wim_lookup_table_entry *lte_new;
670 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
673 if (lte_new != lte) {
674 /* Duplicate stream detected. */
676 if (lte_new->will_be_in_output_wim ||
677 stream_filtered(lte_new, ctx->filter_ctx))
679 /* The duplicate stream is already being
680 * included in the output WIM, or it would be
681 * filtered out if it had been. Skip writing
682 * this stream (and reading it again) entirely,
683 * passing its output reference count to the
684 * duplicate stream in the former case. */
685 DEBUG("Discarding duplicate stream of "
686 "length %"PRIu64, lte->size);
687 do_write_streams_progress(&ctx->progress_data,
690 list_del(<e->write_streams_list);
691 list_del(<e->lookup_table_list);
692 if (lte_new->will_be_in_output_wim)
693 lte_new->out_refcnt += lte->out_refcnt;
694 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
695 ctx->cur_write_res_size -= lte->size;
696 free_lookup_table_entry(lte);
697 return BEGIN_STREAM_STATUS_SKIP_STREAM;
699 /* The duplicate stream can validly be written,
700 * but was not marked as such. Discard the
701 * current stream entry and use the duplicate,
702 * but actually freeing the current entry must
703 * wait until read_stream_list() has finished
704 * reading its data. */
705 DEBUG("Stream duplicate, but not already "
706 "selected for writing.");
707 list_replace(<e->write_streams_list,
708 <e_new->write_streams_list);
709 list_replace(<e->lookup_table_list,
710 <e_new->lookup_table_list);
711 lte_new->out_refcnt = lte->out_refcnt;
712 lte_new->will_be_in_output_wim = 1;
713 ctx->stream_was_duplicate = true;
718 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
722 /* Rewrite a stream that was just written compressed as uncompressed instead.
723 * This function is optional, but if a stream did not compress to less than its
724 * original size, it might as well be written uncompressed. */
726 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
727 struct filedes *out_fd)
730 u64 begin_offset = lte->out_reshdr.offset_in_wim;
731 u64 end_offset = out_fd->offset;
733 if (filedes_seek(out_fd, begin_offset) == -1)
736 ret = extract_full_stream_to_fd(lte, out_fd);
738 /* Error reading the uncompressed data. */
739 if (out_fd->offset == begin_offset &&
740 filedes_seek(out_fd, end_offset) != -1)
742 /* Nothing was actually written yet, and we successfully
743 * seeked to the end of the compressed resource, so
744 * don't issue a hard error; just keep the compressed
745 * resource instead. */
746 WARNING("Recovered compressed stream of "
747 "size %"PRIu64", continuing on.",
754 wimlib_assert(out_fd->offset - begin_offset == lte->size);
756 if (out_fd->offset < end_offset &&
757 0 != ftruncate(out_fd->fd, out_fd->offset))
759 ERROR_WITH_ERRNO("Can't truncate output file to "
760 "offset %"PRIu64, out_fd->offset);
761 return WIMLIB_ERR_WRITE;
764 lte->out_reshdr.size_in_wim = lte->size;
765 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
766 WIM_RESHDR_FLAG_PACKED_STREAMS);
770 /* Write the next chunk of (typically compressed) data to the output WIM,
771 * handling the writing of the chunk table. */
773 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
774 size_t csize, size_t usize)
778 struct wim_lookup_table_entry *lte;
779 u32 completed_stream_count;
782 lte = list_entry(ctx->pending_streams.next,
783 struct wim_lookup_table_entry, write_streams_list);
785 if (ctx->cur_write_stream_offset == 0 &&
786 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
788 /* Starting to write a new stream in non-packed mode. */
790 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
791 int additional_reshdr_flags = 0;
792 if (ctx->compressor != NULL)
793 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
795 DEBUG("Writing pipable WIM stream header "
796 "(offset=%"PRIu64")", ctx->out_fd->offset);
798 ret = write_pwm_stream_header(lte, ctx->out_fd,
799 additional_reshdr_flags);
804 ret = begin_write_resource(ctx, lte->size);
809 if (ctx->compressor != NULL) {
810 /* Record the compresed chunk size. */
811 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
812 ctx->chunk_csizes[ctx->chunk_index++] = csize;
814 /* If writing a pipable WIM, before the chunk data write a chunk
815 * header that provides the compressed chunk size. */
816 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
817 struct pwm_chunk_hdr chunk_hdr = {
818 .compressed_size = cpu_to_le32(csize),
820 ret = full_write(ctx->out_fd, &chunk_hdr,
827 /* Write the chunk data. */
828 ret = full_write(ctx->out_fd, cchunk, csize);
832 ctx->cur_write_stream_offset += usize;
834 completed_size = usize;
835 completed_stream_count = 0;
836 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
837 /* Wrote chunk in packed mode. It may have finished multiple
839 while (ctx->cur_write_stream_offset > lte->size) {
840 struct wim_lookup_table_entry *next;
842 ctx->cur_write_stream_offset -= lte->size;
844 wimlib_assert(!list_is_singular(&ctx->pending_streams) &&
845 !list_empty(&ctx->pending_streams));
846 next = list_entry(lte->write_streams_list.next,
847 struct wim_lookup_table_entry,
849 list_move_tail(<e->write_streams_list,
852 completed_stream_count++;
854 if (ctx->cur_write_stream_offset == lte->size) {
855 ctx->cur_write_stream_offset = 0;
856 list_move_tail(<e->write_streams_list,
858 completed_stream_count++;
861 /* Wrote chunk in non-packed mode. It may have finished a
863 if (ctx->cur_write_stream_offset == lte->size) {
865 completed_stream_count++;
867 list_del(<e->write_streams_list);
869 wimlib_assert(ctx->cur_write_stream_offset ==
870 ctx->cur_write_res_size);
872 ret = end_write_resource(ctx, <e->out_reshdr);
876 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
877 if (ctx->compressor != NULL)
878 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
880 if (ctx->compressor != NULL &&
881 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
882 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) &&
883 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
885 /* Stream did not compress to less than its original
886 * size. If we're not writing a pipable WIM (which
887 * could mean the output file descriptor is
888 * non-seekable), and the stream isn't located in a
889 * resource pack (which would make reading it again
890 * costly), truncate the file to the start of the stream
891 * and write it uncompressed instead. */
892 DEBUG("Stream of size %"PRIu64" did not compress to "
893 "less than original size; writing uncompressed.",
895 ret = write_stream_uncompressed(lte, ctx->out_fd);
899 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
901 ctx->cur_write_stream_offset = 0;
905 do_write_streams_progress(&ctx->progress_data, lte,
906 completed_size, completed_stream_count,
912 ERROR_WITH_ERRNO("Write error");
917 submit_chunk_for_compression(struct write_streams_ctx *ctx,
918 const void *chunk, size_t size)
920 /* While we are unable to submit the chunk for compression (due to too
921 * many chunks already outstanding), retrieve and write the next
922 * compressed chunk. */
923 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
930 bret = ctx->compressor->get_chunk(ctx->compressor,
931 &cchunk, &csize, &usize);
935 ret = write_chunk(ctx, cchunk, csize, usize);
942 /* Process the next chunk of data to be written to a WIM resource. */
944 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
946 struct write_streams_ctx *ctx = _ctx;
948 const u8 *chunkptr, *chunkend;
950 wimlib_assert(size != 0);
952 if (ctx->compressor == NULL) {
953 /* Write chunk uncompressed. */
954 ret = write_chunk(ctx, chunk, size, size);
957 ctx->cur_read_stream_offset += size;
961 /* Submit the chunk for compression, but take into account that the
962 * @size the chunk was provided in may not correspond to the
963 * @out_chunk_size being used for compression. */
965 chunkend = chunkptr + size;
967 const u8 *resized_chunk;
968 size_t needed_chunk_size;
970 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
971 needed_chunk_size = ctx->out_chunk_size;
973 u64 res_bytes_remaining;
975 res_bytes_remaining = ctx->cur_read_stream_size -
976 ctx->cur_read_stream_offset;
977 needed_chunk_size = min(ctx->out_chunk_size,
978 ctx->chunk_buf_filled +
979 res_bytes_remaining);
982 if (ctx->chunk_buf_filled == 0 &&
983 chunkend - chunkptr >= needed_chunk_size)
985 /* No intermediate buffering needed. */
986 resized_chunk = chunkptr;
987 chunkptr += needed_chunk_size;
988 ctx->cur_read_stream_offset += needed_chunk_size;
990 /* Intermediate buffering needed. */
991 size_t bytes_consumed;
993 bytes_consumed = min(chunkend - chunkptr,
994 needed_chunk_size - ctx->chunk_buf_filled);
996 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
997 chunkptr, bytes_consumed);
999 chunkptr += bytes_consumed;
1000 ctx->cur_read_stream_offset += bytes_consumed;
1001 ctx->chunk_buf_filled += bytes_consumed;
1002 if (ctx->chunk_buf_filled == needed_chunk_size) {
1003 resized_chunk = ctx->chunk_buf;
1004 ctx->chunk_buf_filled = 0;
1011 ret = submit_chunk_for_compression(ctx, resized_chunk,
1016 } while (chunkptr != chunkend);
1020 /* Finish processing a stream for writing. It may not have been completely
1021 * written yet, as the chunk_compressor implementation may still have chunks
1022 * buffered or being compressed. */
1024 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1026 struct write_streams_ctx *ctx = _ctx;
1028 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size);
1029 if (ctx->stream_was_duplicate) {
1030 free_lookup_table_entry(lte);
1031 } else if (lte->unhashed && ctx->lookup_table != NULL) {
1032 list_del(<e->unhashed_list);
1033 lookup_table_insert(ctx->lookup_table, lte);
1039 /* Compute statistics about a list of streams that will be written.
1041 * Assumes the streams are sorted such that all streams located in each distinct
1042 * WIM (specified by WIMStruct) are together. */
1044 compute_stream_list_stats(struct list_head *stream_list,
1045 struct write_streams_ctx *ctx)
1047 struct wim_lookup_table_entry *lte;
1048 u64 total_bytes = 0;
1049 u64 num_streams = 0;
1050 u64 total_parts = 0;
1051 WIMStruct *prev_wim_part = NULL;
1053 list_for_each_entry(lte, stream_list, write_streams_list) {
1055 total_bytes += lte->size;
1056 if (lte->resource_location == RESOURCE_IN_WIM) {
1057 if (prev_wim_part != lte->rspec->wim) {
1058 prev_wim_part = lte->rspec->wim;
1063 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1064 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1065 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1066 ctx->progress_data.progress.write_streams.completed_streams = 0;
1067 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1068 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1069 ctx->progress_data.progress.write_streams.completed_parts = 0;
1070 ctx->progress_data.next_progress = 0;
1071 ctx->progress_data.prev_wim_part = NULL;
1074 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1075 * rather than compressed. Delete these streams from @stream_list, and move one
1076 * per resource to @raw_copy_resources. Return the total uncompressed size of
1077 * the streams that need to be compressed. */
1079 find_raw_copy_resources(struct list_head *stream_list,
1080 int write_resource_flags,
1083 struct list_head *raw_copy_resources)
1085 struct wim_lookup_table_entry *lte, *tmp;
1086 u64 num_bytes_to_compress = 0;
1088 INIT_LIST_HEAD(raw_copy_resources);
1090 /* Initialize temporary raw_copy_ok flag. */
1091 list_for_each_entry(lte, stream_list, write_streams_list)
1092 if (lte->resource_location == RESOURCE_IN_WIM)
1093 lte->rspec->raw_copy_ok = 0;
1095 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1096 if (lte->resource_location == RESOURCE_IN_WIM &&
1097 lte->rspec->raw_copy_ok)
1099 list_del(<e->write_streams_list);
1100 } else if (can_raw_copy(lte, write_resource_flags,
1101 out_ctype, out_chunk_size))
1103 lte->rspec->raw_copy_ok = 1;
1104 list_move_tail(<e->write_streams_list,
1105 raw_copy_resources);
1107 num_bytes_to_compress += lte->size;
1111 return num_bytes_to_compress;
1114 /* Copy a raw compressed resource located in another WIM file to the WIM file
1117 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1118 struct filedes *out_fd)
1120 u64 cur_read_offset;
1121 u64 end_read_offset;
1122 u8 buf[BUFFER_SIZE];
1123 size_t bytes_to_read;
1125 struct filedes *in_fd;
1126 struct wim_lookup_table_entry *lte;
1127 u64 out_offset_in_wim;
1129 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1130 "uncompressed_size=%"PRIu64")",
1131 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1133 /* Copy the raw data. */
1134 cur_read_offset = in_rspec->offset_in_wim;
1135 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1137 out_offset_in_wim = out_fd->offset;
1139 if (in_rspec->is_pipable) {
1140 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1141 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1142 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1143 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1145 in_fd = &in_rspec->wim->in_fd;
1146 wimlib_assert(cur_read_offset != end_read_offset);
1149 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1151 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1155 ret = full_write(out_fd, buf, bytes_to_read);
1159 cur_read_offset += bytes_to_read;
1161 } while (cur_read_offset != end_read_offset);
1163 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1164 if (lte->will_be_in_output_wim) {
1165 stream_set_out_reshdr_for_reuse(lte);
1166 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1167 lte->out_res_offset_in_wim = out_offset_in_wim;
1169 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1176 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1177 * file being written. */
1179 write_raw_copy_resources(struct list_head *raw_copy_resources,
1180 struct filedes *out_fd,
1181 struct write_streams_progress_data *progress_data)
1183 struct wim_lookup_table_entry *lte;
1186 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1187 ret = write_raw_copy_resource(lte->rspec, out_fd);
1190 do_write_streams_progress(progress_data, lte, lte->size,
1196 /* Wait for and write all chunks pending in the compressor. */
1198 finish_remaining_chunks(struct write_streams_ctx *ctx)
1205 if (ctx->compressor == NULL)
1208 if (ctx->chunk_buf_filled != 0) {
1209 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1210 ctx->chunk_buf_filled);
1215 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1216 ret = write_chunk(ctx, cdata, csize, usize);
1224 remove_zero_length_streams(struct list_head *stream_list)
1226 struct wim_lookup_table_entry *lte, *tmp;
1228 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1229 wimlib_assert(lte->will_be_in_output_wim);
1230 if (lte->size == 0) {
1231 list_del(<e->write_streams_list);
1232 lte->out_reshdr.offset_in_wim = 0;
1233 lte->out_reshdr.size_in_wim = 0;
1234 lte->out_reshdr.uncompressed_size = 0;
1235 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1241 * Write a list of streams to the output WIM file.
1244 * The list of streams to write, specifies a list of `struct
1245 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1248 * The file descriptor, opened for writing, to which to write the streams.
1250 * @write_resource_flags
1251 * Flags to modify how the streams are written:
1253 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1254 * Force compression of all resources, even if they could otherwise
1255 * be re-used by caping the raw data, due to being located in a WIM
1256 * file with compatible compression parameters.
1258 * WRITE_RESOURCE_FLAG_PIPABLE:
1259 * Write the resources in the wimlib-specific pipable format, and
1260 * furthermore do so in such a way that no seeking backwards in
1261 * @out_fd will be performed (so it may be a pipe, contrary to the
1262 * default behavior).
1264 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1265 * Pack all the streams into a single resource rather than writing
1266 * them in separate resources. This format is only valid if the
1267 * WIM version number is WIM_VERSION_PACKED_STREAMS. This flag
1268 * currently may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1271 * Compression format to use to write the output streams, specified as one
1272 * of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1273 * WIMLIB_COMPRESSION_TYPE_INVALID but including
1274 * WIMLIB_COMPRESSION_TYPE_NONE.
1277 * Chunk size to use to write the streams. It must be a valid chunk size
1278 * for the specified compression format @out_ctype, unless @out_ctype is
1279 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1282 * Number of threads to use to compress data. If 0, a default number of
1283 * threads will be chosen. The number of threads still may be decreased
1284 * from the specified value if insufficient memory is detected.
1287 * If on-the-fly deduplication of unhashed streams is desired, this
1288 * parameter must be pointer to the lookup table for the WIMStruct on whose
1289 * behalf the streams are being written. Otherwise, this parameter can be
1293 * If on-the-fly deduplication of unhashed streams is desired, this
1294 * parameter can be a pointer to a context for stream filtering used to
1295 * detect whether the duplicate stream has been hard-filtered or not. If
1296 * no streams are hard-filtered or no streams are unhashed, this parameter
1300 * If non-NULL, a progress function that will be called periodically with
1301 * WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages. Note that on-the-fly
1302 * deduplication of unhashed streams may result in the total bytes provided
1303 * in the progress data to decrease from one message to the next.
1305 * This function will write the streams in @stream_list to resources in
1306 * consecutive positions in the output WIM file, or to a single packed resource
1307 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1308 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1309 * each stream written will be updated to specify its location, size, and flags
1310 * in the output WIM. In the packed resource case,
1311 * WIM_RESHDR_FLAG_PACKED_STREAMS shall be set in the @flags field of the
1312 * @out_reshdr, and @out_res_offset_in_wim and @out_res_size_in_wim will also
1313 * be set to the offset and size, respectively, in the output WIM of the full
1314 * packed resource containing the corresponding stream.
1316 * Each of the streams to write may be in any location supported by the
1317 * resource-handling code (specifically, read_stream_list()), such as the
1318 * contents of external file that has been logically added to the output WIM, or
1319 * a stream in another WIM file that has been imported, or even stream in the
1320 * "same" WIM file of which a modified copy is being written. In the case that
1321 * a stream is already in a WIM file and uses compatible compression parameters,
1322 * by default this function will re-use the raw data instead of decompressing
1323 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1324 * specified in @write_resource_flags, this is not done.
1326 * As a further requirement, this function requires that the
1327 * @will_be_in_output_wim member be set on all streams in @stream_list as well
1328 * as any other streams not in @stream_list that will be in the output WIM file,
1329 * but not on any other streams in the output WIM's lookup table or sharing a
1330 * packed resource with a stream in @stream_list. Still furthermore, if
1331 * on-the-fly deduplication of streams is possible, then all streams in
1332 * @stream_list must also be linked by @lookup_table_list along with any other
1333 * streams that have @will_be_in_output_wim set.
1335 * This function handles on-the-fly deduplication of streams for which SHA1
1336 * message digests have not yet been calculated and it is therefore known
1337 * whether such streams are already in @stream_list or in the WIM's lookup table
1338 * at all. If @lookup_table is non-NULL, then each stream in @stream_list that
1339 * has @unhashed set but not @unique_size set is checksummed immediately before
1340 * it would otherwise be read for writing in order to determine if it is
1341 * identical to another stream already being written or one that would be
1342 * filtered out of the output WIM using stream_filtered() with the context
1343 * @filter_ctx. Each such duplicate stream will be removed from @stream_list, its
1344 * reference count transfered to the pre-existing duplicate stream, its memory
1345 * freed, and will not be written. Alternatively, if a stream in @stream_list
1346 * is a duplicate with any stream in @lookup_table that has not been marked for
1347 * writing or would not be hard-filtered, it is freed and the pre-existing
1348 * duplicate is written instead, taking ownership of the reference count and
1349 * slot in the @lookup_table_list.
1351 * Returns 0 if all streams were written successfully (or did not need to be
1352 * written); otherwise a non-zero error code.
1355 write_stream_list(struct list_head *stream_list,
1356 struct filedes *out_fd,
1357 int write_resource_flags,
1360 unsigned num_threads,
1361 struct wim_lookup_table *lookup_table,
1362 struct filter_context *filter_ctx,
1363 wimlib_progress_func_t progress_func)
1366 struct write_streams_ctx ctx;
1367 struct list_head raw_copy_resources;
1369 wimlib_assert((write_resource_flags &
1370 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1371 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1372 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1373 WRITE_RESOURCE_FLAG_PIPABLE));
1375 remove_zero_length_streams(stream_list);
1377 if (list_empty(stream_list)) {
1378 DEBUG("No streams to write.");
1382 memset(&ctx, 0, sizeof(ctx));
1384 /* Pre-sorting the streams is required for compute_stream_list_stats().
1385 * Afterwards, read_stream_list() need not sort them again. */
1386 ret = sort_stream_list_by_sequential_order(stream_list,
1387 offsetof(struct wim_lookup_table_entry,
1388 write_streams_list));
1392 ctx.out_fd = out_fd;
1393 ctx.lookup_table = lookup_table;
1394 ctx.out_ctype = out_ctype;
1395 ctx.out_chunk_size = out_chunk_size;
1396 ctx.write_resource_flags = write_resource_flags;
1397 ctx.filter_ctx = filter_ctx;
1399 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1400 wimlib_assert(out_chunk_size != 0);
1401 if (out_chunk_size <= STACK_MAX) {
1402 ctx.chunk_buf = alloca(out_chunk_size);
1404 ctx.chunk_buf = MALLOC(out_chunk_size);
1405 if (ctx.chunk_buf == NULL) {
1406 ret = WIMLIB_ERR_NOMEM;
1407 goto out_destroy_context;
1411 ctx.chunk_buf_filled = 0;
1413 compute_stream_list_stats(stream_list, &ctx);
1415 ctx.progress_data.progress_func = progress_func;
1417 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1418 write_resource_flags,
1421 &raw_copy_resources);
1423 DEBUG("Writing stream list "
1424 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1425 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1426 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1427 out_fd->offset, write_resource_flags,
1428 out_ctype, out_chunk_size, num_threads,
1429 ctx.progress_data.progress.write_streams.total_bytes,
1430 ctx.num_bytes_to_compress);
1432 if (ctx.num_bytes_to_compress == 0) {
1433 DEBUG("No compression needed; skipping to raw copy!");
1434 goto out_write_raw_copy_resources;
1437 /* Unless uncompressed output was required, allocate a chunk_compressor
1438 * to do compression. There are serial and parallel implementations of
1439 * the chunk_compressor interface. We default to parallel using the
1440 * specified number of threads, unless the upper bound on the number
1441 * bytes needing to be compressed is less 2000000 (heuristic value). */
1442 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1444 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1445 if (ctx.num_bytes_to_compress >= 2000000) {
1446 ret = new_parallel_chunk_compressor(out_ctype,
1451 DEBUG("Couldn't create parallel chunk compressor "
1452 "(status %d)", ret);
1457 if (ctx.compressor == NULL) {
1458 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1461 goto out_destroy_context;
1466 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1468 ctx.progress_data.progress.write_streams.num_threads = 1;
1470 DEBUG("Actually using %u threads",
1471 ctx.progress_data.progress.write_streams.num_threads);
1473 INIT_LIST_HEAD(&ctx.pending_streams);
1474 INIT_LIST_HEAD(&ctx.pack_streams);
1476 if (ctx.progress_data.progress_func) {
1477 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1478 &ctx.progress_data.progress);
1481 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1482 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1484 goto out_destroy_context;
1487 /* Read the list of streams needing to be compressed, using the
1488 * specified callbacks to execute processing of the data. */
1490 struct read_stream_list_callbacks cbs = {
1491 .begin_stream = write_stream_begin_read,
1492 .begin_stream_ctx = &ctx,
1493 .consume_chunk = write_stream_process_chunk,
1494 .consume_chunk_ctx = &ctx,
1495 .end_stream = write_stream_end_read,
1496 .end_stream_ctx = &ctx,
1499 ret = read_stream_list(stream_list,
1500 offsetof(struct wim_lookup_table_entry, write_streams_list),
1502 STREAM_LIST_ALREADY_SORTED |
1503 VERIFY_STREAM_HASHES |
1504 COMPUTE_MISSING_STREAM_HASHES);
1507 goto out_destroy_context;
1509 ret = finish_remaining_chunks(&ctx);
1511 goto out_destroy_context;
1513 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1514 struct wim_reshdr reshdr;
1515 struct wim_lookup_table_entry *lte;
1518 ret = end_write_resource(&ctx, &reshdr);
1520 goto out_destroy_context;
1522 DEBUG("Ending packed resource: %lu %lu %lu.",
1523 reshdr.offset_in_wim,
1525 reshdr.uncompressed_size);
1528 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1529 lte->out_reshdr.size_in_wim = lte->size;
1530 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1531 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1532 lte->out_reshdr.uncompressed_size = 0;
1533 lte->out_reshdr.offset_in_wim = offset_in_res;
1534 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1535 lte->out_res_size_in_wim = reshdr.size_in_wim;
1536 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1537 offset_in_res += lte->size;
1539 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1542 out_write_raw_copy_resources:
1543 /* Copy any compressed resources for which the raw data can be reused
1544 * without decompression. */
1545 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1546 &ctx.progress_data);
1548 out_destroy_context:
1549 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1550 FREE(ctx.chunk_buf);
1551 FREE(ctx.chunk_csizes);
1553 ctx.compressor->destroy(ctx.compressor);
1554 DEBUG("Done (ret=%d)", ret);
1559 wim_write_stream_list(WIMStruct *wim,
1560 struct list_head *stream_list,
1562 unsigned num_threads,
1563 struct filter_context *filter_ctx,
1564 wimlib_progress_func_t progress_func)
1568 int write_resource_flags;
1570 write_resource_flags = write_flags_to_resource_flags(write_flags);
1572 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1573 out_chunk_size = wim->out_pack_chunk_size;
1574 out_ctype = wim->out_pack_compression_type;
1576 out_chunk_size = wim->out_chunk_size;
1577 out_ctype = wim->out_compression_type;
1580 return write_stream_list(stream_list,
1582 write_resource_flags,
1592 write_wim_resource(struct wim_lookup_table_entry *lte,
1593 struct filedes *out_fd,
1596 int write_resource_flags)
1598 LIST_HEAD(stream_list);
1599 list_add(<e->write_streams_list, &stream_list);
1600 lte->will_be_in_output_wim = 1;
1601 return write_stream_list(&stream_list,
1603 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1613 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1614 int reshdr_flags, struct filedes *out_fd,
1617 struct wim_reshdr *out_reshdr,
1619 int write_resource_flags)
1622 struct wim_lookup_table_entry *lte;
1624 /* Set up a temporary lookup table entry to provide to
1625 * write_wim_resource(). */
1627 lte = new_lookup_table_entry();
1629 return WIMLIB_ERR_NOMEM;
1631 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1632 lte->attached_buffer = (void*)buf;
1633 lte->size = buf_size;
1634 lte->flags = reshdr_flags;
1636 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1637 sha1_buffer(buf, buf_size, lte->hash);
1643 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1644 write_resource_flags);
1648 copy_reshdr(out_reshdr, <e->out_reshdr);
1651 copy_hash(hash, lte->hash);
1654 lte->resource_location = RESOURCE_NONEXISTENT;
1655 free_lookup_table_entry(lte);
1659 struct stream_size_table {
1660 struct hlist_head *array;
1666 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1668 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1669 if (tab->array == NULL)
1670 return WIMLIB_ERR_NOMEM;
1671 tab->num_entries = 0;
1672 tab->capacity = capacity;
1677 destroy_stream_size_table(struct stream_size_table *tab)
1683 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1685 struct stream_size_table *tab = _tab;
1687 struct wim_lookup_table_entry *same_size_lte;
1688 struct hlist_node *tmp;
1690 pos = hash_u64(lte->size) % tab->capacity;
1691 lte->unique_size = 1;
1692 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1693 if (same_size_lte->size == lte->size) {
1694 lte->unique_size = 0;
1695 same_size_lte->unique_size = 0;
1700 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1705 struct find_streams_ctx {
1708 struct list_head stream_list;
1709 struct stream_size_table stream_size_tab;
1713 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1714 struct list_head *stream_list, u32 nref)
1716 if (!lte->will_be_in_output_wim) {
1717 lte->out_refcnt = 0;
1718 list_add_tail(<e->write_streams_list, stream_list);
1719 lte->will_be_in_output_wim = 1;
1721 lte->out_refcnt += nref;
1725 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1728 struct list_head *stream_list = _stream_list;
1729 lte->will_be_in_output_wim = 0;
1730 reference_stream_for_write(lte, stream_list, lte->refcnt);
1735 inode_find_streams_to_reference(const struct wim_inode *inode,
1736 const struct wim_lookup_table *table,
1737 struct list_head *stream_list)
1739 struct wim_lookup_table_entry *lte;
1742 wimlib_assert(inode->i_nlink > 0);
1744 for (i = 0; i <= inode->i_num_ads; i++) {
1745 lte = inode_stream_lte(inode, i, table);
1747 reference_stream_for_write(lte, stream_list,
1749 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1750 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1756 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1758 lte->will_be_in_output_wim = 0;
1763 image_find_streams_to_reference(WIMStruct *wim)
1765 struct wim_image_metadata *imd;
1766 struct wim_inode *inode;
1767 struct wim_lookup_table_entry *lte;
1768 struct list_head *stream_list;
1771 imd = wim_get_current_image_metadata(wim);
1773 image_for_each_unhashed_stream(lte, imd)
1774 lte->will_be_in_output_wim = 0;
1776 stream_list = wim->private;
1777 image_for_each_inode(inode, imd) {
1778 ret = inode_find_streams_to_reference(inode,
1788 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1791 struct list_head *stream_list_ret)
1795 INIT_LIST_HEAD(stream_list_ret);
1797 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1798 (image == 1 && wim->hdr.image_count == 1)))
1800 /* Fast case: Assume that all streams are being written and
1801 * that the reference counts are correct. */
1802 struct wim_lookup_table_entry *lte;
1803 struct wim_image_metadata *imd;
1806 for_lookup_table_entry(wim->lookup_table,
1807 fully_reference_stream_for_write,
1810 for (i = 0; i < wim->hdr.image_count; i++) {
1811 imd = wim->image_metadata[i];
1812 image_for_each_unhashed_stream(lte, imd)
1813 fully_reference_stream_for_write(lte, stream_list_ret);
1816 /* Slow case: Walk through the images being written and
1817 * determine the streams referenced. */
1818 for_lookup_table_entry(wim->lookup_table,
1819 do_stream_set_not_in_output_wim, NULL);
1820 wim->private = stream_list_ret;
1821 ret = for_image(wim, image, image_find_streams_to_reference);
1829 struct insert_other_if_hard_filtered_ctx {
1830 struct stream_size_table *tab;
1831 struct filter_context *filter_ctx;
1835 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1837 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1839 if (!lte->will_be_in_output_wim &&
1840 stream_hard_filtered(lte, ctx->filter_ctx))
1841 stream_size_table_insert(lte, ctx->tab);
1846 determine_stream_size_uniquity(struct list_head *stream_list,
1847 struct wim_lookup_table *lt,
1848 struct filter_context *filter_ctx)
1851 struct stream_size_table tab;
1852 struct wim_lookup_table_entry *lte;
1854 ret = init_stream_size_table(&tab, lt->capacity);
1858 if (may_hard_filter_streams(filter_ctx)) {
1859 struct insert_other_if_hard_filtered_ctx ctx = {
1861 .filter_ctx = filter_ctx,
1863 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1866 list_for_each_entry(lte, stream_list, write_streams_list)
1867 stream_size_table_insert(lte, &tab);
1869 destroy_stream_size_table(&tab);
1874 filter_stream_list_for_write(struct list_head *stream_list,
1875 struct filter_context *filter_ctx)
1877 struct wim_lookup_table_entry *lte, *tmp;
1879 list_for_each_entry_safe(lte, tmp,
1880 stream_list, write_streams_list)
1882 int status = stream_filtered(lte, filter_ctx);
1889 /* Soft filtered. */
1891 /* Hard filtered. */
1892 lte->will_be_in_output_wim = 0;
1893 list_del(<e->lookup_table_list);
1895 list_del(<e->write_streams_list);
1901 * prepare_stream_list_for_write() -
1903 * Prepare the list of streams to write for writing a WIM containing the
1904 * specified image(s) with the specified write flags.
1907 * The WIMStruct on whose behalf the write is occurring.
1910 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1913 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1915 * STREAMS_OK: For writes of all images, assume that all streams in the
1916 * lookup table of @wim and the per-image lists of unhashed streams should
1917 * be taken as-is, and image metadata should not be searched for
1918 * references. This does not exclude filtering with OVERWRITE and
1919 * SKIP_EXTERNAL_WIMS, below.
1921 * OVERWRITE: Streams already present in @wim shall not be returned in
1924 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1925 * @wim, shall be be returned in neither @stream_list_ret nor
1926 * @lookup_table_list_ret.
1929 * List of streams, linked by write_streams_list, that need to be written
1930 * will be returned here.
1932 * Note that this function assumes that unhashed streams will be written;
1933 * it does not take into account that they may become duplicates when
1936 * @lookup_table_list_ret
1937 * List of streams, linked by lookup_table_list, that need to be included
1938 * in the WIM's lookup table will be returned here. This will be a
1939 * superset of the streams in @stream_list_ret.
1941 * This list will be a proper superset of @stream_list_ret if and only if
1942 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1943 * the streams that would otherwise need to be written were already located
1946 * All streams in this list will have @out_refcnt set to the number of
1947 * references to the stream in the output WIM. If
1948 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1949 * may be as low as 0.
1952 * A context for queries of stream filter status with stream_filtered() is
1953 * returned in this location.
1955 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1956 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1957 * lookup table of @wim not inserted into @lookup_table_list_ret.
1959 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1960 * @stream_list_ret that have unique size among all stream entries in
1961 * @stream_list_ret and among all stream entries in the lookup table of @wim
1962 * that are ineligible for being written due to filtering.
1964 * Returns 0 on success; nonzero on read error, memory allocation error, or
1968 prepare_stream_list_for_write(WIMStruct *wim, int image,
1970 struct list_head *stream_list_ret,
1971 struct list_head *lookup_table_list_ret,
1972 struct filter_context *filter_ctx_ret)
1975 struct wim_lookup_table_entry *lte;
1977 filter_ctx_ret->write_flags = write_flags;
1978 filter_ctx_ret->wim = wim;
1980 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1983 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1988 INIT_LIST_HEAD(lookup_table_list_ret);
1989 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1990 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1992 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1997 if (may_filter_streams(filter_ctx_ret))
1998 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2004 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2005 unsigned num_threads,
2006 wimlib_progress_func_t progress_func,
2007 struct list_head *stream_list_override,
2008 struct list_head *lookup_table_list_ret)
2011 struct list_head _stream_list;
2012 struct list_head *stream_list;
2013 struct wim_lookup_table_entry *lte;
2014 struct filter_context _filter_ctx;
2015 struct filter_context *filter_ctx;
2017 if (stream_list_override == NULL) {
2018 /* Normal case: prepare stream list from image(s) being written.
2020 stream_list = &_stream_list;
2021 filter_ctx = &_filter_ctx;
2022 ret = prepare_stream_list_for_write(wim, image, write_flags,
2024 lookup_table_list_ret,
2029 /* Currently only as a result of wimlib_split() being called:
2030 * use stream list already explicitly provided. Use existing
2031 * reference counts. */
2032 stream_list = stream_list_override;
2034 INIT_LIST_HEAD(lookup_table_list_ret);
2035 list_for_each_entry(lte, stream_list, write_streams_list) {
2036 lte->out_refcnt = lte->refcnt;
2037 lte->will_be_in_output_wim = 1;
2038 lte->unique_size = 0;
2039 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2043 return wim_write_stream_list(wim,
2052 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2053 wimlib_progress_func_t progress_func)
2058 int write_resource_flags;
2060 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2061 DEBUG("Not writing any metadata resources.");
2065 write_resource_flags = write_flags_to_resource_flags(write_flags);
2067 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2069 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2070 wim->out_fd.offset);
2073 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2075 if (image == WIMLIB_ALL_IMAGES) {
2077 end_image = wim->hdr.image_count;
2079 start_image = image;
2083 for (int i = start_image; i <= end_image; i++) {
2084 struct wim_image_metadata *imd;
2086 imd = wim->image_metadata[i - 1];
2087 /* Build a new metadata resource only if image was modified from
2088 * the original (or was newly added). Otherwise just copy the
2090 if (imd->modified) {
2091 DEBUG("Image %u was modified; building and writing new "
2092 "metadata resource", i);
2093 ret = write_metadata_resource(wim, i,
2094 write_resource_flags);
2095 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2096 DEBUG("Image %u was not modified; re-using existing "
2097 "metadata resource.", i);
2098 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2101 DEBUG("Image %u was not modified; copying existing "
2102 "metadata resource.", i);
2103 ret = write_wim_resource(imd->metadata_lte,
2105 wim->out_compression_type,
2106 wim->out_chunk_size,
2107 write_resource_flags);
2113 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2118 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2121 DEBUG("Opening \"%"TS"\" for writing.", path);
2123 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2125 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2126 return WIMLIB_ERR_OPEN;
2128 filedes_init(&wim->out_fd, raw_fd);
2133 close_wim_writable(WIMStruct *wim, int write_flags)
2137 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2138 DEBUG("Closing WIM file.");
2139 if (filedes_valid(&wim->out_fd))
2140 if (filedes_close(&wim->out_fd))
2141 ret = WIMLIB_ERR_WRITE;
2143 filedes_invalidate(&wim->out_fd);
2148 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2150 const struct wim_lookup_table_entry *lte1, *lte2;
2152 lte1 = *(const struct wim_lookup_table_entry**)p1;
2153 lte2 = *(const struct wim_lookup_table_entry**)p2;
2155 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2156 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2157 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2158 return cmp_u64(lte1->out_res_offset_in_wim,
2159 lte2->out_res_offset_in_wim);
2164 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2167 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2168 lte2->out_reshdr.offset_in_wim);
2172 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2173 struct wim_reshdr *out_reshdr,
2174 struct list_head *lookup_table_list)
2178 /* Set output resource metadata for streams already present in WIM. */
2179 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2180 struct wim_lookup_table_entry *lte;
2181 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2183 if (lte->resource_location == RESOURCE_IN_WIM &&
2184 lte->rspec->wim == wim)
2186 stream_set_out_reshdr_for_reuse(lte);
2191 ret = sort_stream_list(lookup_table_list,
2192 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2193 cmp_streams_by_out_rspec);
2197 /* Add entries for metadata resources. */
2198 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2202 if (image == WIMLIB_ALL_IMAGES) {
2204 end_image = wim->hdr.image_count;
2206 start_image = image;
2210 /* Push metadata resource lookup table entries onto the front of
2211 * the list in reverse order, so that they're written in order.
2213 for (int i = end_image; i >= start_image; i--) {
2214 struct wim_lookup_table_entry *metadata_lte;
2216 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2217 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2218 metadata_lte->out_refcnt = 1;
2219 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2223 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2225 wim->hdr.part_number,
2227 write_flags_to_resource_flags(write_flags));
2233 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2234 * table, then overwrite the WIM header. By default, closes the WIM file
2235 * descriptor (@wim->out_fd) if successful.
2237 * write_flags is a bitwise OR of the following:
2239 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2240 * Include an integrity table.
2242 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2243 * fsync() the output file before closing it.
2245 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2246 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2247 * stream headers before the lookup table and XML data, and also
2248 * write the WIM header at the end instead of seeking to the
2249 * beginning. Can't be combined with
2250 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2252 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2253 * Don't write the lookup table.
2255 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2256 * When (if) writing the integrity table, re-use entries from the
2257 * existing integrity table, if possible.
2259 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2260 * After writing the XML data but before writing the integrity
2261 * table, write a temporary WIM header and flush the stream so that
2262 * the WIM is less likely to become corrupted upon abrupt program
2264 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2265 * Instead of overwriting the WIM header at the beginning of the
2266 * file, simply append it to the end of the file. (Used when
2268 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2269 * Do not close the file descriptor @wim->out_fd on either success
2271 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2272 * Use the existing <TOTALBYTES> stored in the in-memory XML
2273 * information, rather than setting it to the offset of the XML
2274 * data being written.
2277 finish_write(WIMStruct *wim, int image, int write_flags,
2278 wimlib_progress_func_t progress_func,
2279 struct list_head *lookup_table_list)
2283 int write_resource_flags;
2284 off_t old_lookup_table_end;
2285 off_t new_lookup_table_end;
2288 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2290 write_resource_flags = write_flags_to_resource_flags(write_flags);
2292 /* In the WIM header, there is room for the resource entry for a
2293 * metadata resource labeled as the "boot metadata". This entry should
2294 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2295 * it should be a copy of the resource entry for the image that is
2296 * marked as bootable. This is not well documented... */
2297 if (wim->hdr.boot_idx == 0) {
2298 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2300 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2301 &wim->image_metadata[
2302 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2305 /* Write lookup table. (Save old position first.) */
2306 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2307 wim->hdr.lookup_table_reshdr.size_in_wim;
2308 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2309 ret = write_wim_lookup_table(wim, image, write_flags,
2310 &wim->hdr.lookup_table_reshdr,
2316 /* Write XML data. */
2317 xml_totalbytes = wim->out_fd.offset;
2318 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2319 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2320 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2321 &wim->hdr.xml_data_reshdr,
2322 write_resource_flags);
2326 /* Write integrity table (optional). */
2327 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2328 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2329 struct wim_header checkpoint_hdr;
2330 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2331 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2332 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2333 ret = write_wim_header_at_offset(&checkpoint_hdr,
2339 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2340 old_lookup_table_end = 0;
2342 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2343 wim->hdr.lookup_table_reshdr.size_in_wim;
2345 ret = write_integrity_table(wim,
2346 new_lookup_table_end,
2347 old_lookup_table_end,
2352 /* No integrity table. */
2353 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2356 /* Now that all information in the WIM header has been determined, the
2357 * preliminary header written earlier can be overwritten, the header of
2358 * the existing WIM file can be overwritten, or the final header can be
2359 * written to the end of the pipable WIM. */
2360 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2362 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2363 hdr_offset = wim->out_fd.offset;
2364 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2365 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2369 /* Possibly sync file data to disk before closing. On POSIX systems, it
2370 * is necessary to do this before using rename() to overwrite an
2371 * existing file with a new file. Otherwise, data loss would occur if
2372 * the system is abruptly terminated when the metadata for the rename
2373 * operation has been written to disk, but the new file data has not.
2375 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2376 DEBUG("Syncing WIM file.");
2377 if (fsync(wim->out_fd.fd)) {
2378 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2379 return WIMLIB_ERR_WRITE;
2383 if (close_wim_writable(wim, write_flags)) {
2384 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2385 return WIMLIB_ERR_WRITE;
2391 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2393 lock_wim(WIMStruct *wim, int fd)
2396 if (fd != -1 && !wim->wim_locked) {
2397 ret = flock(fd, LOCK_EX | LOCK_NB);
2399 if (errno == EWOULDBLOCK) {
2400 ERROR("`%"TS"' is already being modified or has been "
2401 "mounted read-write\n"
2402 " by another process!", wim->filename);
2403 ret = WIMLIB_ERR_ALREADY_LOCKED;
2405 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2410 wim->wim_locked = 1;
2418 * write_pipable_wim():
2420 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2421 * capable of being applied from a pipe).
2423 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2424 * images can be applied from them sequentially when the file data is sent over
2425 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2426 * The modifications made to the WIM format for pipable WIMs are:
2428 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2429 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2430 * stops other software from trying to read the file as a normal WIM.
2432 * - The header at the beginning of the file does not contain all the normal
2433 * information; in particular it will have all 0's for the lookup table and
2434 * XML data resource entries. This is because this information cannot be
2435 * determined until the lookup table and XML data have been written.
2436 * Consequently, wimlib will write the full header at the very end of the
2437 * file. The header at the end, however, is only used when reading the WIM
2438 * from a seekable file (not a pipe).
2440 * - An extra copy of the XML data is placed directly after the header. This
2441 * allows image names and sizes to be determined at an appropriate time when
2442 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2443 * WIM is read from a seekable file (not a pipe).
2445 * - The format of resources, or streams, has been modified to allow them to be
2446 * used before the "lookup table" has been read. Each stream is prefixed with
2447 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2448 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2449 * uncompressed stream size, and flags that indicate whether the stream is
2450 * compressed. The data of uncompressed streams then follows literally, while
2451 * the data of compressed streams follows in a modified format. Compressed
2452 * streams do not begin with a chunk table, since the chunk table cannot be
2453 * written until all chunks have been compressed. Instead, each compressed
2454 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2455 * Furthermore, the chunk table is written at the end of the resource instead
2456 * of the start. Note: chunk offsets are given in the chunk table as if the
2457 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2458 * used if the WIM is being read from a seekable file (not a pipe).
2460 * - Metadata resources always come before other file resources (streams).
2461 * (This does not by itself constitute an incompatibility with normal WIMs,
2462 * since this is valid in normal WIMs.)
2464 * - At least up to the end of the file resources, all components must be packed
2465 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2466 * not by itself consititute an incompatibility with normal WIMs, since this
2467 * is valid in normal WIMs.)
2469 * Note: the lookup table, XML data, and header at the end are not used when
2470 * applying from a pipe. They exist to support functionality such as image
2471 * application and export when the WIM is *not* read from a pipe.
2473 * Layout of pipable WIM:
2475 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2476 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2477 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2479 * Layout of normal WIM:
2481 * +--------+-----------------------------+-------------------------+
2482 * | Header | File and metadata resources | Lookup table | XML data |
2483 * +--------+-----------------------------+-------------------------+
2485 * An optional integrity table can follow the final XML data in both normal and
2486 * pipable WIMs. However, due to implementation details, wimlib currently can
2487 * only include an integrity table in a pipable WIM when writing it to a
2488 * seekable file (not a pipe).
2490 * Do note that since pipable WIMs are not supported by Microsoft's software,
2491 * wimlib does not create them unless explicitly requested (with
2492 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2493 * characters to identify the file.
2496 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2497 unsigned num_threads, wimlib_progress_func_t progress_func,
2498 struct list_head *stream_list_override,
2499 struct list_head *lookup_table_list_ret)
2502 struct wim_reshdr xml_reshdr;
2504 WARNING("Creating a pipable WIM, which will "
2506 " with Microsoft's software (wimgapi/imagex/Dism).");
2508 /* At this point, the header at the beginning of the file has already
2511 /* For efficiency, when wimlib adds an image to the WIM with
2512 * wimlib_add_image(), the SHA1 message digests of files is not
2513 * calculated; instead, they are calculated while the files are being
2514 * written. However, this does not work when writing a pipable WIM,
2515 * since when writing a stream to a pipable WIM, its SHA1 message digest
2516 * needs to be known before the stream data is written. Therefore,
2517 * before getting much farther, we need to pre-calculate the SHA1
2518 * message digests of all streams that will be written. */
2519 ret = wim_checksum_unhashed_streams(wim);
2523 /* Write extra copy of the XML data. */
2524 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2526 WRITE_RESOURCE_FLAG_PIPABLE);
2530 /* Write metadata resources for the image(s) being included in the
2532 ret = write_wim_metadata_resources(wim, image, write_flags,
2537 /* Write streams needed for the image(s) being included in the output
2538 * WIM, or streams needed for the split WIM part. */
2539 return write_wim_streams(wim, image, write_flags, num_threads,
2540 progress_func, stream_list_override,
2541 lookup_table_list_ret);
2543 /* The lookup table, XML data, and header at end are handled by
2544 * finish_write(). */
2547 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2550 write_wim_part(WIMStruct *wim,
2551 const void *path_or_fd,
2554 unsigned num_threads,
2555 wimlib_progress_func_t progress_func,
2556 unsigned part_number,
2557 unsigned total_parts,
2558 struct list_head *stream_list_override,
2562 struct wim_header hdr_save;
2563 struct list_head lookup_table_list;
2565 if (total_parts == 1)
2566 DEBUG("Writing standalone WIM.");
2568 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2569 if (image == WIMLIB_ALL_IMAGES)
2570 DEBUG("Including all images.");
2572 DEBUG("Including image %d only.", image);
2573 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2574 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2576 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2577 DEBUG("Write flags: 0x%08x", write_flags);
2579 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2580 DEBUG("\tCHECK_INTEGRITY");
2582 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2585 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2586 DEBUG("\tRECOMPRESS");
2588 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2591 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2594 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2595 DEBUG("\tIGNORE_READONLY_FLAG");
2597 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2600 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2601 DEBUG("\tNOT_PIPABLE");
2603 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2604 DEBUG("\tPACK_STREAMS");
2606 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2607 DEBUG("\tFILE_DESCRIPTOR");
2609 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2610 DEBUG("\tNO_METADATA");
2612 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2613 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2615 if (num_threads == 0)
2616 DEBUG("Number of threads: autodetect");
2618 DEBUG("Number of threads: %u", num_threads);
2619 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2620 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2621 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2622 "specified" : "generate new"));
2624 /* Internally, this is always called with a valid part number and total
2626 wimlib_assert(total_parts >= 1);
2627 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2629 /* A valid image (or all images) must be specified. */
2630 if (image != WIMLIB_ALL_IMAGES &&
2631 (image < 1 || image > wim->hdr.image_count))
2632 return WIMLIB_ERR_INVALID_IMAGE;
2634 /* If we need to write metadata resources, make sure the ::WIMStruct has
2635 * the needed information attached (e.g. is not a resource-only WIM,
2636 * such as a non-first part of a split WIM). */
2637 if (!wim_has_metadata(wim) &&
2638 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2639 return WIMLIB_ERR_METADATA_NOT_FOUND;
2641 /* Check for contradictory flags. */
2642 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2643 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2644 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2645 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2646 return WIMLIB_ERR_INVALID_PARAM;
2648 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2649 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2650 == (WIMLIB_WRITE_FLAG_PIPABLE |
2651 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2652 return WIMLIB_ERR_INVALID_PARAM;
2654 /* Save previous header, then start initializing the new one. */
2655 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2657 /* Set default integrity, pipable, and packed stream flags. */
2658 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2659 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2660 if (wim_is_pipable(wim)) {
2661 DEBUG("WIM is pipable; default to PIPABLE.");
2662 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2665 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2666 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2667 if (wim_has_integrity_table(wim)) {
2668 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2669 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2672 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2673 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2674 == (WIMLIB_WRITE_FLAG_PIPABLE |
2675 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2677 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2678 return WIMLIB_ERR_INVALID_PARAM;
2681 /* Set appropriate magic number. */
2682 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2683 wim->hdr.magic = PWM_MAGIC;
2685 wim->hdr.magic = WIM_MAGIC;
2687 /* Set appropriate version number. */
2688 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2689 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2690 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2692 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2694 /* Clear header flags that will be set automatically. */
2695 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2696 WIM_HDR_FLAG_RESOURCE_ONLY |
2697 WIM_HDR_FLAG_SPANNED |
2698 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2700 /* Set SPANNED header flag if writing part of a split WIM. */
2701 if (total_parts != 1)
2702 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2704 /* Set part number and total parts of split WIM. This will be 1 and 1
2705 * if the WIM is standalone. */
2706 wim->hdr.part_number = part_number;
2707 wim->hdr.total_parts = total_parts;
2709 /* Set compression type if different. */
2710 if (wim->compression_type != wim->out_compression_type) {
2711 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2712 wimlib_assert(ret == 0);
2715 /* Set chunk size if different. */
2716 wim->hdr.chunk_size = wim->out_chunk_size;
2718 /* Use GUID if specified; otherwise generate a new one. */
2720 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2721 else if (!wim->guid_set_explicitly)
2722 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2724 /* Clear references to resources that have not been written yet. */
2725 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2726 zero_reshdr(&wim->hdr.xml_data_reshdr);
2727 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2728 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2730 /* Set image count and boot index correctly for single image writes. */
2731 if (image != WIMLIB_ALL_IMAGES) {
2732 wim->hdr.image_count = 1;
2733 if (wim->hdr.boot_idx == image)
2734 wim->hdr.boot_idx = 1;
2736 wim->hdr.boot_idx = 0;
2739 /* Split WIMs can't be bootable. */
2740 if (total_parts != 1)
2741 wim->hdr.boot_idx = 0;
2743 /* Initialize output file descriptor. */
2744 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2745 /* File descriptor was explicitly provided. Return error if
2746 * file descriptor is not seekable, unless writing a pipable WIM
2748 wim->out_fd.fd = *(const int*)path_or_fd;
2749 wim->out_fd.offset = 0;
2750 if (!filedes_is_seekable(&wim->out_fd)) {
2751 ret = WIMLIB_ERR_INVALID_PARAM;
2752 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2753 goto out_restore_hdr;
2754 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2755 ERROR("Can't include integrity check when "
2756 "writing pipable WIM to pipe!");
2757 goto out_restore_hdr;
2762 /* Filename of WIM to write was provided; open file descriptor
2764 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2765 O_TRUNC | O_CREAT | O_RDWR);
2767 goto out_restore_hdr;
2770 /* Write initial header. This is merely a "dummy" header since it
2771 * doesn't have all the information yet, so it will be overwritten later
2772 * (unless writing a pipable WIM). */
2773 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2774 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2775 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2776 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2778 goto out_restore_hdr;
2780 /* Write metadata resources and streams. */
2781 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2782 /* Default case: create a normal (non-pipable) WIM. */
2783 ret = write_wim_streams(wim, image, write_flags, num_threads,
2784 progress_func, stream_list_override,
2785 &lookup_table_list);
2787 goto out_restore_hdr;
2789 ret = write_wim_metadata_resources(wim, image, write_flags,
2792 goto out_restore_hdr;
2794 /* Non-default case: create pipable WIM. */
2795 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2796 progress_func, stream_list_override,
2797 &lookup_table_list);
2799 goto out_restore_hdr;
2800 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2804 /* Write lookup table, XML data, and (optional) integrity table. */
2805 ret = finish_write(wim, image, write_flags, progress_func,
2806 &lookup_table_list);
2808 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2809 (void)close_wim_writable(wim, write_flags);
2810 DEBUG("ret=%d", ret);
2814 /* Write a standalone WIM to a file or file descriptor. */
2816 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2817 int image, int write_flags, unsigned num_threads,
2818 wimlib_progress_func_t progress_func)
2820 return write_wim_part(wim, path_or_fd, image, write_flags,
2821 num_threads, progress_func, 1, 1, NULL, NULL);
2824 /* API function documented in wimlib.h */
2826 wimlib_write(WIMStruct *wim, const tchar *path,
2827 int image, int write_flags, unsigned num_threads,
2828 wimlib_progress_func_t progress_func)
2831 return WIMLIB_ERR_INVALID_PARAM;
2833 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2835 return write_standalone_wim(wim, path, image, write_flags,
2836 num_threads, progress_func);
2839 /* API function documented in wimlib.h */
2841 wimlib_write_to_fd(WIMStruct *wim, int fd,
2842 int image, int write_flags, unsigned num_threads,
2843 wimlib_progress_func_t progress_func)
2846 return WIMLIB_ERR_INVALID_PARAM;
2848 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2849 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2851 return write_standalone_wim(wim, &fd, image, write_flags,
2852 num_threads, progress_func);
2856 any_images_modified(WIMStruct *wim)
2858 for (int i = 0; i < wim->hdr.image_count; i++)
2859 if (wim->image_metadata[i]->modified)
2865 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2867 const WIMStruct *wim = _wim;
2868 off_t end_offset = *(const off_t*)wim->private;
2870 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2871 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2872 return WIMLIB_ERR_RESOURCE_ORDER;
2876 /* Make sure no file or metadata resources are located after the XML data (or
2877 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2878 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2880 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2885 wim->private = &end_offset;
2886 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2890 for (i = 0; i < wim->hdr.image_count; i++) {
2891 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2899 * Overwrite a WIM, possibly appending streams to it.
2901 * A WIM looks like (or is supposed to look like) the following:
2903 * Header (212 bytes)
2904 * Streams and metadata resources (variable size)
2905 * Lookup table (variable size)
2906 * XML data (variable size)
2907 * Integrity table (optional) (variable size)
2909 * If we are not adding any streams or metadata resources, the lookup table is
2910 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2911 * header. This operation is potentially unsafe if the program is abruptly
2912 * terminated while the XML data or integrity table are being overwritten, but
2913 * before the new header has been written. To partially alleviate this problem,
2914 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2915 * finish_write() to cause a temporary WIM header to be written after the XML
2916 * data has been written. This may prevent the WIM from becoming corrupted if
2917 * the program is terminated while the integrity table is being calculated (but
2918 * no guarantees, due to write re-ordering...).
2920 * If we are adding new streams or images (metadata resources), the lookup table
2921 * needs to be changed, and those streams need to be written. In this case, we
2922 * try to perform a safe update of the WIM file by writing the streams *after*
2923 * the end of the previous WIM, then writing the new lookup table, XML data, and
2924 * (optionally) integrity table following the new streams. This will produce a
2925 * layout like the following:
2927 * Header (212 bytes)
2928 * (OLD) Streams and metadata resources (variable size)
2929 * (OLD) Lookup table (variable size)
2930 * (OLD) XML data (variable size)
2931 * (OLD) Integrity table (optional) (variable size)
2932 * (NEW) Streams and metadata resources (variable size)
2933 * (NEW) Lookup table (variable size)
2934 * (NEW) XML data (variable size)
2935 * (NEW) Integrity table (optional) (variable size)
2937 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2938 * the header is overwritten to point to the new lookup table, XML data, and
2939 * integrity table, to produce the following layout:
2941 * Header (212 bytes)
2942 * Streams and metadata resources (variable size)
2943 * Nothing (variable size)
2944 * More Streams and metadata resources (variable size)
2945 * Lookup table (variable size)
2946 * XML data (variable size)
2947 * Integrity table (optional) (variable size)
2949 * This method allows an image to be appended to a large WIM very quickly, and
2950 * is is crash-safe except in the case of write re-ordering, but the
2951 * disadvantage is that a small hole is left in the WIM where the old lookup
2952 * table, xml data, and integrity table were. (These usually only take up a
2953 * small amount of space compared to the streams, however.)
2956 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2957 unsigned num_threads,
2958 wimlib_progress_func_t progress_func)
2962 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2963 struct wim_header hdr_save;
2964 struct list_head stream_list;
2965 struct list_head lookup_table_list;
2966 struct filter_context filter_ctx;
2968 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2970 /* Save original header so it can be restored in case of error */
2971 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2973 /* Set default integrity flag. */
2974 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2975 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2976 if (wim_has_integrity_table(wim))
2977 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2979 /* Set WIM version if adding packed streams. */
2980 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2981 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2983 /* Set additional flags for overwrite. */
2984 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2985 WIMLIB_WRITE_FLAG_STREAMS_OK;
2987 /* Make sure that the integrity table (if present) is after the XML
2988 * data, and that there are no stream resources, metadata resources, or
2989 * lookup tables after the XML data. Otherwise, these data would be
2991 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2992 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2993 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2994 wim->hdr.lookup_table_reshdr.size_in_wim;
2995 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2996 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2997 WARNING("Didn't expect the integrity table to be before the XML data");
2998 ret = WIMLIB_ERR_RESOURCE_ORDER;
2999 goto out_restore_memory_hdr;
3002 if (old_lookup_table_end > old_xml_begin) {
3003 WARNING("Didn't expect the lookup table to be after the XML data");
3004 ret = WIMLIB_ERR_RESOURCE_ORDER;
3005 goto out_restore_memory_hdr;
3008 /* Set @old_wim_end, which indicates the point beyond which we don't
3009 * allow any file and metadata resources to appear without returning
3010 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3011 * overwrite these resources). */
3012 if (!wim->deletion_occurred && !any_images_modified(wim)) {
3013 /* If no images have been modified and no images have been
3014 * deleted, a new lookup table does not need to be written. We
3015 * shall write the new XML data and optional integrity table
3016 * immediately after the lookup table. Note that this may
3017 * overwrite an existing integrity table. */
3018 DEBUG("Skipping writing lookup table "
3019 "(no images modified or deleted)");
3020 old_wim_end = old_lookup_table_end;
3021 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3022 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3023 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3024 /* Old WIM has an integrity table; begin writing new streams
3026 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3027 wim->hdr.integrity_table_reshdr.size_in_wim;
3029 /* No existing integrity table; begin writing new streams after
3030 * the old XML data. */
3031 old_wim_end = old_xml_end;
3034 ret = check_resource_offsets(wim, old_wim_end);
3036 goto out_restore_memory_hdr;
3038 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3039 &stream_list, &lookup_table_list,
3042 goto out_restore_memory_hdr;
3044 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3046 goto out_restore_memory_hdr;
3048 ret = lock_wim(wim, wim->out_fd.fd);
3052 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3053 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3054 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3056 ERROR_WITH_ERRNO("Error updating WIM header flags");
3057 goto out_unlock_wim;
3060 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3061 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3062 ret = WIMLIB_ERR_WRITE;
3063 goto out_restore_physical_hdr;
3066 ret = wim_write_stream_list(wim,
3075 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3076 write_flags, progress_func);
3080 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3081 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3082 progress_func, &lookup_table_list);
3086 wim->wim_locked = 0;
3090 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3091 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3092 wim->filename, old_wim_end);
3093 /* Return value of ftruncate() is ignored because this is
3094 * already an error path. */
3095 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3097 out_restore_physical_hdr:
3098 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3100 wim->wim_locked = 0;
3102 (void)close_wim_writable(wim, write_flags);
3103 out_restore_memory_hdr:
3104 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3109 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3110 unsigned num_threads,
3111 wimlib_progress_func_t progress_func)
3113 size_t wim_name_len;
3116 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3118 /* Write the WIM to a temporary file in the same directory as the
3120 wim_name_len = tstrlen(wim->filename);
3121 tchar tmpfile[wim_name_len + 10];
3122 tmemcpy(tmpfile, wim->filename, wim_name_len);
3123 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3124 tmpfile[wim_name_len + 9] = T('\0');
3126 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3127 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3128 num_threads, progress_func);
3136 /* Rename the new WIM file to the original WIM file. Note: on Windows
3137 * this actually calls win32_rename_replacement(), not _wrename(), so
3138 * that removing the existing destination file can be handled. */
3139 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3140 ret = trename(tmpfile, wim->filename);
3142 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3143 tmpfile, wim->filename);
3150 return WIMLIB_ERR_RENAME;
3153 if (progress_func) {
3154 union wimlib_progress_info progress;
3155 progress.rename.from = tmpfile;
3156 progress.rename.to = wim->filename;
3157 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3162 /* Determine if the specified WIM file may be updated by appending in-place
3163 * rather than writing and replacing it with an entirely new file. */
3165 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3167 /* REBUILD flag forces full rebuild. */
3168 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3171 /* Deletions cause full rebuild by default. */
3172 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3175 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3176 * turned into a pipable WIM in-place. */
3177 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3180 /* wimlib allows multiple packs in a single WIM, but they don't seem to
3181 * be compatible with WIMGAPI, so force all streams to be repacked if
3182 * the WIM already may have contained a pack and PACK_STREAMS was
3184 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3185 wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3188 /* The default compression type and compression chunk size selected for
3189 * the output WIM must be the same as those currently used for the WIM.
3191 if (wim->compression_type != wim->out_compression_type)
3193 if (wim->chunk_size != wim->out_chunk_size)
3199 /* API function documented in wimlib.h */
3201 wimlib_overwrite(WIMStruct *wim, int write_flags,
3202 unsigned num_threads,
3203 wimlib_progress_func_t progress_func)
3208 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3210 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3211 return WIMLIB_ERR_INVALID_PARAM;
3214 return WIMLIB_ERR_NO_FILENAME;
3216 orig_hdr_flags = wim->hdr.flags;
3217 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3218 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3219 ret = can_modify_wim(wim);
3220 wim->hdr.flags = orig_hdr_flags;
3224 if (can_overwrite_wim_inplace(wim, write_flags)) {
3225 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3227 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3229 WARNING("Falling back to re-building entire WIM");
3231 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,