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, 2014 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/chunk_compressor.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/inode.h"
43 #include "wimlib/integrity.h"
44 #include "wimlib/lookup_table.h"
45 #include "wimlib/metadata.h"
46 #include "wimlib/progress.h"
47 #include "wimlib/resource.h"
49 # include "wimlib/win32.h" /* win32_rename_replacement() */
51 #include "wimlib/write.h"
52 #include "wimlib/xml.h"
63 /* wimlib internal flags used when writing resources. */
64 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
65 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
66 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
69 write_flags_to_resource_flags(int write_flags)
71 int write_resource_flags = 0;
73 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
74 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
75 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
77 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
78 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
79 return write_resource_flags;
82 struct filter_context {
87 /* Determine specified stream should be filtered out from the write.
91 * < 0 : The stream should be hard-filtered; that is, not included in the
93 * 0 : The stream should not be filtered out.
94 * > 0 : The stream should be soft-filtered; that is, it already exists in the
95 * WIM file and may not need to be written again.
98 stream_filtered(const struct wim_lookup_table_entry *lte,
99 const struct filter_context *ctx)
101 int write_flags = ctx->write_flags;
102 WIMStruct *wim = ctx->wim;
107 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
108 lte->resource_location == RESOURCE_IN_WIM &&
109 lte->rspec->wim == wim)
112 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
113 lte->resource_location == RESOURCE_IN_WIM &&
114 lte->rspec->wim != wim)
121 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
122 struct filter_context *ctx)
124 return stream_filtered(lte, ctx) < 0;
128 may_soft_filter_streams(const struct filter_context *ctx)
132 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
136 may_hard_filter_streams(const struct filter_context *ctx)
140 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
144 may_filter_streams(const struct filter_context *ctx)
146 return (may_soft_filter_streams(ctx) ||
147 may_hard_filter_streams(ctx));
151 /* Return true if the specified resource is compressed and the compressed data
152 * can be reused with the specified output parameters. */
154 can_raw_copy(const struct wim_lookup_table_entry *lte,
155 int write_resource_flags, int out_ctype, u32 out_chunk_size)
157 const struct wim_resource_spec *rspec;
159 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
162 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
165 if (lte->resource_location != RESOURCE_IN_WIM)
170 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
173 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
174 /* Normal compressed resource: Must use same compression type
176 return (rspec->compression_type == out_ctype &&
177 rspec->chunk_size == out_chunk_size);
180 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
181 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
183 /* Packed resource: Such resources may contain multiple streams,
184 * and in general only a subset of them need to be written. As
185 * a heuristic, re-use the raw data if more than two-thirds the
186 * uncompressed size is being written. */
188 /* Note: packed resources contain a header that specifies the
189 * compression type and chunk size; therefore we don't need to
190 * check if they are compatible with @out_ctype and
191 * @out_chunk_size. */
193 struct wim_lookup_table_entry *res_stream;
196 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
197 if (res_stream->will_be_in_output_wim)
198 write_size += res_stream->size;
200 return (write_size > rspec->uncompressed_size * 2 / 3);
207 filter_resource_flags(u8 flags)
209 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
210 WIM_RESHDR_FLAG_COMPRESSED |
211 WIM_RESHDR_FLAG_SPANNED |
212 WIM_RESHDR_FLAG_FREE));
216 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
218 const struct wim_resource_spec *rspec;
220 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
223 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
225 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
227 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
228 lte->out_reshdr.uncompressed_size = 0;
229 lte->out_reshdr.size_in_wim = lte->size;
231 lte->out_res_offset_in_wim = rspec->offset_in_wim;
232 lte->out_res_size_in_wim = rspec->size_in_wim;
233 lte->out_res_uncompressed_size = rspec->uncompressed_size;
235 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
237 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
238 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
239 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
241 lte->out_reshdr.flags = lte->flags;
245 /* Write the header for a stream in a pipable WIM. */
247 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
248 struct filedes *out_fd,
249 int additional_reshdr_flags)
251 struct pwm_stream_hdr stream_hdr;
255 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
256 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
257 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
258 zero_out_hash(stream_hdr.hash);
260 wimlib_assert(!lte->unhashed);
261 copy_hash(stream_hdr.hash, lte->hash);
264 reshdr_flags = filter_resource_flags(lte->flags);
265 reshdr_flags |= additional_reshdr_flags;
266 stream_hdr.flags = cpu_to_le32(reshdr_flags);
267 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
269 ERROR_WITH_ERRNO("Write error");
273 struct write_streams_progress_data {
274 wimlib_progress_func_t progfunc;
276 union wimlib_progress_info progress;
277 uint64_t next_progress;
281 do_write_streams_progress(struct write_streams_progress_data *progress_data,
282 struct wim_lookup_table_entry *cur_stream,
287 union wimlib_progress_info *progress = &progress_data->progress;
291 progress->write_streams.total_bytes -= complete_size;
292 progress->write_streams.total_streams -= complete_count;
293 if (progress_data->next_progress != ~(uint64_t)0 &&
294 progress_data->next_progress > progress->write_streams.total_bytes)
296 progress_data->next_progress = progress->write_streams.total_bytes;
299 progress->write_streams.completed_bytes += complete_size;
300 progress->write_streams.completed_streams += complete_count;
303 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
305 ret = call_progress(progress_data->progfunc,
306 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
308 progress_data->progctx);
312 if (progress_data->next_progress == progress->write_streams.total_bytes) {
313 progress_data->next_progress = ~(uint64_t)0;
315 /* Handle rate-limiting of messages */
317 /* Send new message as soon as another 1/128 of the
318 * total has been written. (Arbitrary number.) */
319 progress_data->next_progress =
320 progress->write_streams.completed_bytes +
321 progress->write_streams.total_bytes / 128;
323 /* ... Unless that would be more than 5000000 bytes, in
324 * which case send the next after the next 5000000
325 * bytes. (Another arbitrary number.) */
326 if (progress->write_streams.completed_bytes + 5000000 <
327 progress_data->next_progress)
328 progress_data->next_progress =
329 progress->write_streams.completed_bytes + 5000000;
331 /* ... But always send a message as soon as we're
332 * completely done. */
333 if (progress->write_streams.total_bytes <
334 progress_data->next_progress)
335 progress_data->next_progress =
336 progress->write_streams.total_bytes;
342 struct write_streams_ctx {
343 /* File descriptor the streams are being written to. */
344 struct filedes *out_fd;
346 /* Lookup table for the WIMStruct on whose behalf the streams are being
348 struct wim_lookup_table *lookup_table;
350 /* Compression format to use. */
353 /* Maximum uncompressed chunk size in compressed resources to use. */
356 /* Flags that affect how the streams will be written. */
357 int write_resource_flags;
359 /* Data used for issuing WRITE_STREAMS progress. */
360 struct write_streams_progress_data progress_data;
362 struct filter_context *filter_ctx;
364 /* Upper bound on the total number of bytes that need to be compressed.
366 u64 num_bytes_to_compress;
368 /* Pointer to the chunk_compressor implementation being used for
369 * compressing chunks of data, or NULL if chunks are being written
371 struct chunk_compressor *compressor;
373 /* Buffer for dividing the read data into chunks of size
374 * @out_chunk_size. */
377 /* Number of bytes in @chunk_buf that are currently filled. */
378 size_t chunk_buf_filled;
380 /* List of streams that currently have chunks being compressed. */
381 struct list_head pending_streams;
383 /* List of streams in the resource pack. Streams are moved here after
384 * @pending_streams only when writing a packed resource. */
385 struct list_head pack_streams;
387 /* Set to true if the stream currently being read was a duplicate, and
388 * therefore the corresponding stream entry needs to be freed once the
389 * read finishes. (In this case we add the duplicate entry to
390 * pending_streams rather than the entry being read.) */
391 bool stream_was_duplicate;
393 /* Current uncompressed offset in the stream being read. */
394 u64 cur_read_stream_offset;
396 /* Uncompressed size of the stream currently being read. */
397 u64 cur_read_stream_size;
399 /* Current uncompressed offset in the stream being written. */
400 u64 cur_write_stream_offset;
402 /* Uncompressed size of resource currently being written. */
403 u64 cur_write_res_size;
405 /* Array that is filled in with compressed chunk sizes as a resource is
409 /* Index of next entry in @chunk_csizes to fill in. */
412 /* Number of entries in @chunk_csizes currently allocated. */
413 size_t num_alloc_chunks;
415 /* Offset in the output file of the start of the chunks of the resource
416 * currently being written. */
417 u64 chunks_start_offset;
420 /* Reserve space for the chunk table and prepare to accumulate the chunk table
423 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
425 u64 expected_num_chunks;
426 u64 expected_num_chunk_entries;
430 /* Calculate the number of chunks and chunk entries that should be
431 * needed for the resource. These normally will be the final values,
432 * but in PACKED_STREAMS mode some of the streams we're planning to
433 * write into the resource may be duplicates, and therefore discarded,
434 * potentially decreasing the number of chunk entries needed. */
435 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
436 expected_num_chunk_entries = expected_num_chunks;
437 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
438 expected_num_chunk_entries--;
440 /* Make sure the chunk_csizes array is long enough to store the
441 * compressed size of each chunk. */
442 if (expected_num_chunks > ctx->num_alloc_chunks) {
443 u64 new_length = expected_num_chunks + 50;
445 if ((size_t)new_length != new_length) {
446 ERROR("Resource size too large (%"PRIu64" bytes!",
448 return WIMLIB_ERR_NOMEM;
451 FREE(ctx->chunk_csizes);
452 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
453 if (ctx->chunk_csizes == NULL) {
454 ctx->num_alloc_chunks = 0;
455 return WIMLIB_ERR_NOMEM;
457 ctx->num_alloc_chunks = new_length;
460 ctx->chunk_index = 0;
462 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
463 /* Reserve space for the chunk table in the output file. In the
464 * case of packed resources this reserves the upper bound for
465 * the needed space, not necessarily the exact space which will
466 * prove to be needed. At this point, we just use @chunk_csizes
467 * for a buffer of 0's because the actual compressed chunk sizes
469 reserve_size = expected_num_chunk_entries *
470 get_chunk_entry_size(res_expected_size,
471 0 != (ctx->write_resource_flags &
472 WRITE_RESOURCE_FLAG_PACK_STREAMS));
473 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
474 reserve_size += sizeof(struct alt_chunk_table_header_disk);
475 memset(ctx->chunk_csizes, 0, reserve_size);
476 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
484 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
488 wimlib_assert(res_expected_size != 0);
490 if (ctx->compressor != NULL) {
491 ret = begin_chunk_table(ctx, res_expected_size);
496 /* Output file descriptor is now positioned at the offset at which to
497 * write the first chunk of the resource. */
498 ctx->chunks_start_offset = ctx->out_fd->offset;
499 ctx->cur_write_stream_offset = 0;
500 ctx->cur_write_res_size = res_expected_size;
505 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
506 u64 *res_start_offset_ret, u64 *res_store_size_ret)
508 size_t actual_num_chunks;
509 size_t actual_num_chunk_entries;
510 size_t chunk_entry_size;
513 actual_num_chunks = ctx->chunk_index;
514 actual_num_chunk_entries = actual_num_chunks;
515 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
516 actual_num_chunk_entries--;
518 chunk_entry_size = get_chunk_entry_size(res_actual_size,
519 0 != (ctx->write_resource_flags &
520 WRITE_RESOURCE_FLAG_PACK_STREAMS));
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_XPRESS != 1);
580 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 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 u32 flags, 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(!(flags & BEGIN_STREAM_FLAG_PARTIAL_RESOURCE));
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 ret = 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);
699 return BEGIN_STREAM_STATUS_SKIP_STREAM;
701 /* The duplicate stream can validly be written,
702 * but was not marked as such. Discard the
703 * current stream entry and use the duplicate,
704 * but actually freeing the current entry must
705 * wait until read_stream_list() has finished
706 * reading its data. */
707 DEBUG("Stream duplicate, but not already "
708 "selected for writing.");
709 list_replace(<e->write_streams_list,
710 <e_new->write_streams_list);
711 list_replace(<e->lookup_table_list,
712 <e_new->lookup_table_list);
713 lte_new->out_refcnt = lte->out_refcnt;
714 lte_new->will_be_in_output_wim = 1;
715 ctx->stream_was_duplicate = true;
720 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
724 /* Rewrite a stream that was just written compressed as uncompressed instead.
725 * This function is optional, but if a stream did not compress to less than its
726 * original size, it might as well be written uncompressed. */
728 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
729 struct filedes *out_fd)
732 u64 begin_offset = lte->out_reshdr.offset_in_wim;
733 u64 end_offset = out_fd->offset;
735 if (filedes_seek(out_fd, begin_offset) == -1)
738 ret = extract_full_stream_to_fd(lte, out_fd);
740 /* Error reading the uncompressed data. */
741 if (out_fd->offset == begin_offset &&
742 filedes_seek(out_fd, end_offset) != -1)
744 /* Nothing was actually written yet, and we successfully
745 * seeked to the end of the compressed resource, so
746 * don't issue a hard error; just keep the compressed
747 * resource instead. */
748 WARNING("Recovered compressed stream of "
749 "size %"PRIu64", continuing on.",
756 wimlib_assert(out_fd->offset - begin_offset == lte->size);
758 if (out_fd->offset < end_offset &&
759 0 != ftruncate(out_fd->fd, out_fd->offset))
761 ERROR_WITH_ERRNO("Can't truncate output file to "
762 "offset %"PRIu64, out_fd->offset);
763 return WIMLIB_ERR_WRITE;
766 lte->out_reshdr.size_in_wim = lte->size;
767 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
768 WIM_RESHDR_FLAG_PACKED_STREAMS);
772 /* Write the next chunk of (typically compressed) data to the output WIM,
773 * handling the writing of the chunk table. */
775 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
776 size_t csize, size_t usize)
780 struct wim_lookup_table_entry *lte;
781 u32 completed_stream_count;
784 lte = list_entry(ctx->pending_streams.next,
785 struct wim_lookup_table_entry, write_streams_list);
787 if (ctx->cur_write_stream_offset == 0 &&
788 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
790 /* Starting to write a new stream in non-packed mode. */
792 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
793 int additional_reshdr_flags = 0;
794 if (ctx->compressor != NULL)
795 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
797 DEBUG("Writing pipable WIM stream header "
798 "(offset=%"PRIu64")", ctx->out_fd->offset);
800 ret = write_pwm_stream_header(lte, ctx->out_fd,
801 additional_reshdr_flags);
806 ret = begin_write_resource(ctx, lte->size);
811 if (ctx->compressor != NULL) {
812 /* Record the compresed chunk size. */
813 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
814 ctx->chunk_csizes[ctx->chunk_index++] = csize;
816 /* If writing a pipable WIM, before the chunk data write a chunk
817 * header that provides the compressed chunk size. */
818 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
819 struct pwm_chunk_hdr chunk_hdr = {
820 .compressed_size = cpu_to_le32(csize),
822 ret = full_write(ctx->out_fd, &chunk_hdr,
829 /* Write the chunk data. */
830 ret = full_write(ctx->out_fd, cchunk, csize);
834 ctx->cur_write_stream_offset += usize;
836 completed_size = usize;
837 completed_stream_count = 0;
838 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
839 /* Wrote chunk in packed mode. It may have finished multiple
841 while (ctx->cur_write_stream_offset > lte->size) {
842 struct wim_lookup_table_entry *next;
844 ctx->cur_write_stream_offset -= lte->size;
846 wimlib_assert(!list_is_singular(&ctx->pending_streams) &&
847 !list_empty(&ctx->pending_streams));
848 next = list_entry(lte->write_streams_list.next,
849 struct wim_lookup_table_entry,
851 list_move_tail(<e->write_streams_list,
854 completed_stream_count++;
856 if (ctx->cur_write_stream_offset == lte->size) {
857 ctx->cur_write_stream_offset = 0;
858 list_move_tail(<e->write_streams_list,
860 completed_stream_count++;
863 /* Wrote chunk in non-packed mode. It may have finished a
865 if (ctx->cur_write_stream_offset == lte->size) {
867 completed_stream_count++;
869 list_del(<e->write_streams_list);
871 wimlib_assert(ctx->cur_write_stream_offset ==
872 ctx->cur_write_res_size);
874 ret = end_write_resource(ctx, <e->out_reshdr);
878 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
879 if (ctx->compressor != NULL)
880 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
882 if (ctx->compressor != NULL &&
883 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
884 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) &&
885 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
887 /* Stream did not compress to less than its original
888 * size. If we're not writing a pipable WIM (which
889 * could mean the output file descriptor is
890 * non-seekable), and the stream isn't located in a
891 * resource pack (which would make reading it again
892 * costly), truncate the file to the start of the stream
893 * and write it uncompressed instead. */
894 DEBUG("Stream of size %"PRIu64" did not compress to "
895 "less than original size; writing uncompressed.",
897 ret = write_stream_uncompressed(lte, ctx->out_fd);
901 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
903 ctx->cur_write_stream_offset = 0;
907 return do_write_streams_progress(&ctx->progress_data, lte,
908 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;
1073 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1074 * rather than compressed. Delete these streams from @stream_list and move them
1075 * to @raw_copy_streams. Return the total uncompressed size of the streams that
1076 * need to be compressed. */
1078 find_raw_copy_streams(struct list_head *stream_list,
1079 int write_resource_flags,
1082 struct list_head *raw_copy_streams)
1084 struct wim_lookup_table_entry *lte, *tmp;
1085 u64 num_bytes_to_compress = 0;
1087 INIT_LIST_HEAD(raw_copy_streams);
1089 /* Initialize temporary raw_copy_ok flag. */
1090 list_for_each_entry(lte, stream_list, write_streams_list)
1091 if (lte->resource_location == RESOURCE_IN_WIM)
1092 lte->rspec->raw_copy_ok = 0;
1094 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1095 if (lte->resource_location == RESOURCE_IN_WIM &&
1096 lte->rspec->raw_copy_ok)
1098 list_move_tail(<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,
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 in other WIM file(s) to the
1177 * WIM file being written. */
1179 write_raw_copy_resources(struct list_head *raw_copy_streams,
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_streams, write_streams_list)
1187 lte->rspec->raw_copy_ok = 1;
1189 list_for_each_entry(lte, raw_copy_streams, write_streams_list) {
1190 if (lte->rspec->raw_copy_ok) {
1191 /* Write each packed resource only one time, no matter
1192 * how many streams reference it. */
1193 ret = write_raw_copy_resource(lte->rspec, out_fd);
1196 lte->rspec->raw_copy_ok = 0;
1198 ret = do_write_streams_progress(progress_data, lte, lte->size,
1206 /* Wait for and write all chunks pending in the compressor. */
1208 finish_remaining_chunks(struct write_streams_ctx *ctx)
1215 if (ctx->compressor == NULL)
1218 if (ctx->chunk_buf_filled != 0) {
1219 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1220 ctx->chunk_buf_filled);
1225 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1226 ret = write_chunk(ctx, cdata, csize, usize);
1234 remove_zero_length_streams(struct list_head *stream_list)
1236 struct wim_lookup_table_entry *lte, *tmp;
1238 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1239 wimlib_assert(lte->will_be_in_output_wim);
1240 if (lte->size == 0) {
1241 list_del(<e->write_streams_list);
1242 lte->out_reshdr.offset_in_wim = 0;
1243 lte->out_reshdr.size_in_wim = 0;
1244 lte->out_reshdr.uncompressed_size = 0;
1245 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1251 * Write a list of streams to the output WIM file.
1254 * The list of streams to write, specified by a list of `struct
1255 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1258 * The file descriptor, opened for writing, to which to write the streams.
1260 * @write_resource_flags
1261 * Flags to modify how the streams are written:
1263 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1264 * Force compression of all resources, even if they could otherwise
1265 * be re-used by copying the raw data, due to being located in a WIM
1266 * file with compatible compression parameters.
1268 * WRITE_RESOURCE_FLAG_PIPABLE:
1269 * Write the resources in the wimlib-specific pipable format, and
1270 * furthermore do so in such a way that no seeking backwards in
1271 * @out_fd will be performed (so it may be a pipe).
1273 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1274 * Pack all the streams into a single resource rather than writing
1275 * them in separate resources. This flag is only valid if the WIM
1276 * version number has been, or will be, set to
1277 * WIM_VERSION_PACKED_STREAMS. This flag may not be combined with
1278 * WRITE_RESOURCE_FLAG_PIPABLE.
1281 * Compression format to use to write the output streams, specified as one
1282 * of the WIMLIB_COMPRESSION_TYPE_* constants.
1283 * WIMLIB_COMPRESSION_TYPE_NONE is allowed.
1286 * Chunk size to use to write the streams. It must be a valid chunk size
1287 * for the specified compression format @out_ctype, unless @out_ctype is
1288 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1291 * Number of threads to use to compress data. If 0, a default number of
1292 * threads will be chosen. The number of threads still may be decreased
1293 * from the specified value if insufficient memory is detected.
1296 * If on-the-fly deduplication of unhashed streams is desired, this
1297 * parameter must be pointer to the lookup table for the WIMStruct on whose
1298 * behalf the streams are being written. Otherwise, this parameter can be
1302 * If on-the-fly deduplication of unhashed streams is desired, this
1303 * parameter can be a pointer to a context for stream filtering used to
1304 * detect whether the duplicate stream has been hard-filtered or not. If
1305 * no streams are hard-filtered or no streams are unhashed, this parameter
1308 * This function will write the streams in @stream_list to resources in
1309 * consecutive positions in the output WIM file, or to a single packed resource
1310 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1311 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1312 * each stream written will be updated to specify its location, size, and flags
1313 * in the output WIM. In the packed resource case,
1314 * WIM_RESHDR_FLAG_PACKED_STREAMS will be set in the @flags field of each
1315 * @out_reshdr, and furthermore @out_res_offset_in_wim and @out_res_size_in_wim
1316 * of each @out_reshdr will be set to the offset and size, respectively, in the
1317 * output WIM of the packed resource containing the corresponding stream.
1319 * Each of the streams to write may be in any location supported by the
1320 * resource-handling code (specifically, read_stream_list()), such as the
1321 * contents of external file that has been logically added to the output WIM, or
1322 * a stream in another WIM file that has been imported, or even a stream in the
1323 * "same" WIM file of which a modified copy is being written. In the case that
1324 * a stream is already in a WIM file and uses compatible compression parameters,
1325 * by default this function will re-use the raw data instead of decompressing
1326 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1327 * specified in @write_resource_flags, this is not done.
1329 * As a further requirement, this function requires that the
1330 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1331 * well as any other streams not in @stream_list that will be in the output WIM
1332 * file, but set to 0 on any other streams in the output WIM's lookup table or
1333 * sharing a packed resource with a stream in @stream_list. Still furthermore,
1334 * if on-the-fly deduplication of streams is possible, then all streams in
1335 * @stream_list must also be linked by @lookup_table_list along with any other
1336 * streams that have @will_be_in_output_wim set.
1338 * This function handles on-the-fly deduplication of streams for which SHA1
1339 * message digests have not yet been calculated. Such streams may or may not
1340 * need to be written. If @lookup_table is non-NULL, then each stream in
1341 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1342 * immediately before it would otherwise be read for writing in order to
1343 * determine if it is identical to another stream already being written or one
1344 * that would be filtered out of the output WIM using stream_filtered() with the
1345 * context @filter_ctx. Each such duplicate stream will be removed from
1346 * @stream_list, its reference count transfered to the pre-existing duplicate
1347 * stream, its memory freed, and will not be written. Alternatively, if a
1348 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1349 * has not been marked for writing or would not be hard-filtered, it is freed
1350 * and the pre-existing duplicate is written instead, taking ownership of the
1351 * reference count and slot in the @lookup_table_list.
1353 * Returns 0 if every stream was either written successfully or did not need to
1354 * be written; otherwise returns a non-zero error code.
1357 write_stream_list(struct list_head *stream_list,
1358 struct filedes *out_fd,
1359 int write_resource_flags,
1362 unsigned num_threads,
1363 struct wim_lookup_table *lookup_table,
1364 struct filter_context *filter_ctx,
1365 wimlib_progress_func_t progfunc,
1369 struct write_streams_ctx ctx;
1370 struct list_head raw_copy_streams;
1372 wimlib_assert((write_resource_flags &
1373 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1374 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1375 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1376 WRITE_RESOURCE_FLAG_PIPABLE));
1378 remove_zero_length_streams(stream_list);
1380 if (list_empty(stream_list)) {
1381 DEBUG("No streams to write.");
1385 memset(&ctx, 0, sizeof(ctx));
1387 /* Pre-sorting the streams is required for compute_stream_list_stats().
1388 * Afterwards, read_stream_list() need not sort them again. */
1389 ret = sort_stream_list_by_sequential_order(stream_list,
1390 offsetof(struct wim_lookup_table_entry,
1391 write_streams_list));
1395 ctx.out_fd = out_fd;
1396 ctx.lookup_table = lookup_table;
1397 ctx.out_ctype = out_ctype;
1398 ctx.out_chunk_size = out_chunk_size;
1399 ctx.write_resource_flags = write_resource_flags;
1400 ctx.filter_ctx = filter_ctx;
1402 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1403 wimlib_assert(out_chunk_size != 0);
1404 if (out_chunk_size <= STACK_MAX) {
1405 ctx.chunk_buf = alloca(out_chunk_size);
1407 ctx.chunk_buf = MALLOC(out_chunk_size);
1408 if (ctx.chunk_buf == NULL) {
1409 ret = WIMLIB_ERR_NOMEM;
1410 goto out_destroy_context;
1414 ctx.chunk_buf_filled = 0;
1416 compute_stream_list_stats(stream_list, &ctx);
1418 ctx.progress_data.progfunc = progfunc;
1419 ctx.progress_data.progctx = progctx;
1421 ctx.num_bytes_to_compress = find_raw_copy_streams(stream_list,
1422 write_resource_flags,
1427 DEBUG("Writing stream list "
1428 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1429 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1430 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1431 out_fd->offset, write_resource_flags,
1432 out_ctype, out_chunk_size, num_threads,
1433 ctx.progress_data.progress.write_streams.total_bytes,
1434 ctx.num_bytes_to_compress);
1436 if (ctx.num_bytes_to_compress == 0) {
1437 DEBUG("No compression needed; skipping to raw copy!");
1438 goto out_write_raw_copy_resources;
1441 /* Unless uncompressed output was required, allocate a chunk_compressor
1442 * to do compression. There are serial and parallel implementations of
1443 * the chunk_compressor interface. We default to parallel using the
1444 * specified number of threads, unless the upper bound on the number
1445 * bytes needing to be compressed is less than a heuristic value. */
1446 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1448 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1449 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1450 ret = new_parallel_chunk_compressor(out_ctype,
1455 DEBUG("Couldn't create parallel chunk compressor "
1456 "(status %d)", ret);
1461 if (ctx.compressor == NULL) {
1462 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1465 goto out_destroy_context;
1470 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1472 ctx.progress_data.progress.write_streams.num_threads = 1;
1474 DEBUG("Actually using %u threads",
1475 ctx.progress_data.progress.write_streams.num_threads);
1477 INIT_LIST_HEAD(&ctx.pending_streams);
1478 INIT_LIST_HEAD(&ctx.pack_streams);
1480 ret = call_progress(ctx.progress_data.progfunc,
1481 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1482 &ctx.progress_data.progress,
1483 ctx.progress_data.progctx);
1485 goto out_destroy_context;
1487 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1488 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1490 goto out_destroy_context;
1493 /* Read the list of streams needing to be compressed, using the
1494 * specified callbacks to execute processing of the data. */
1496 struct read_stream_list_callbacks cbs = {
1497 .begin_stream = write_stream_begin_read,
1498 .begin_stream_ctx = &ctx,
1499 .consume_chunk = write_stream_process_chunk,
1500 .consume_chunk_ctx = &ctx,
1501 .end_stream = write_stream_end_read,
1502 .end_stream_ctx = &ctx,
1505 ret = read_stream_list(stream_list,
1506 offsetof(struct wim_lookup_table_entry, write_streams_list),
1508 STREAM_LIST_ALREADY_SORTED |
1509 VERIFY_STREAM_HASHES |
1510 COMPUTE_MISSING_STREAM_HASHES);
1513 goto out_destroy_context;
1515 ret = finish_remaining_chunks(&ctx);
1517 goto out_destroy_context;
1519 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1520 struct wim_reshdr reshdr;
1521 struct wim_lookup_table_entry *lte;
1524 ret = end_write_resource(&ctx, &reshdr);
1526 goto out_destroy_context;
1528 DEBUG("Ending packed resource: %lu %lu %lu.",
1529 reshdr.offset_in_wim,
1531 reshdr.uncompressed_size);
1534 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1535 lte->out_reshdr.size_in_wim = lte->size;
1536 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1537 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1538 lte->out_reshdr.uncompressed_size = 0;
1539 lte->out_reshdr.offset_in_wim = offset_in_res;
1540 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1541 lte->out_res_size_in_wim = reshdr.size_in_wim;
1542 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1543 offset_in_res += lte->size;
1545 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1548 out_write_raw_copy_resources:
1549 /* Copy any compressed resources for which the raw data can be reused
1550 * without decompression. */
1551 ret = write_raw_copy_resources(&raw_copy_streams, ctx.out_fd,
1552 &ctx.progress_data);
1554 out_destroy_context:
1555 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1556 FREE(ctx.chunk_buf);
1557 FREE(ctx.chunk_csizes);
1559 ctx.compressor->destroy(ctx.compressor);
1560 DEBUG("Done (ret=%d)", ret);
1565 is_stream_packed(struct wim_lookup_table_entry *lte, void *_ignore)
1567 return lte_is_partial(lte);
1571 wim_has_packed_streams(WIMStruct *wim)
1573 return for_lookup_table_entry(wim->lookup_table, is_stream_packed, NULL);
1577 wim_write_stream_list(WIMStruct *wim,
1578 struct list_head *stream_list,
1580 unsigned num_threads,
1581 struct filter_context *filter_ctx)
1585 int write_resource_flags;
1587 write_resource_flags = write_flags_to_resource_flags(write_flags);
1589 /* wimlib v1.7.0: pack streams by default if the WIM version has been
1590 * set to WIM_VERSION_PACKED_STREAMS and at least one stream in the
1591 * WIM's lookup table is located in a packed resource (may be the same
1592 * WIM, or a different one in the case of export). */
1593 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS &&
1594 wim_has_packed_streams(wim))
1596 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
1599 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1600 out_chunk_size = wim->out_pack_chunk_size;
1601 out_ctype = wim->out_pack_compression_type;
1603 out_chunk_size = wim->out_chunk_size;
1604 out_ctype = wim->out_compression_type;
1607 return write_stream_list(stream_list,
1609 write_resource_flags,
1620 write_wim_resource(struct wim_lookup_table_entry *lte,
1621 struct filedes *out_fd,
1624 int write_resource_flags)
1626 LIST_HEAD(stream_list);
1627 list_add(<e->write_streams_list, &stream_list);
1628 lte->will_be_in_output_wim = 1;
1629 return write_stream_list(&stream_list,
1631 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1642 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1643 int reshdr_flags, struct filedes *out_fd,
1646 struct wim_reshdr *out_reshdr,
1648 int write_resource_flags)
1651 struct wim_lookup_table_entry *lte;
1653 /* Set up a temporary lookup table entry to provide to
1654 * write_wim_resource(). */
1656 lte = new_lookup_table_entry();
1658 return WIMLIB_ERR_NOMEM;
1660 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1661 lte->attached_buffer = (void*)buf;
1662 lte->size = buf_size;
1663 lte->flags = reshdr_flags;
1665 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1666 sha1_buffer(buf, buf_size, lte->hash);
1672 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1673 write_resource_flags);
1677 copy_reshdr(out_reshdr, <e->out_reshdr);
1680 copy_hash(hash, lte->hash);
1683 lte->resource_location = RESOURCE_NONEXISTENT;
1684 free_lookup_table_entry(lte);
1688 struct stream_size_table {
1689 struct hlist_head *array;
1695 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1697 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1698 if (tab->array == NULL)
1699 return WIMLIB_ERR_NOMEM;
1700 tab->num_entries = 0;
1701 tab->capacity = capacity;
1706 destroy_stream_size_table(struct stream_size_table *tab)
1712 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1714 struct stream_size_table *tab = _tab;
1716 struct wim_lookup_table_entry *same_size_lte;
1717 struct hlist_node *tmp;
1719 pos = hash_u64(lte->size) % tab->capacity;
1720 lte->unique_size = 1;
1721 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1722 if (same_size_lte->size == lte->size) {
1723 lte->unique_size = 0;
1724 same_size_lte->unique_size = 0;
1729 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1734 struct find_streams_ctx {
1737 struct list_head stream_list;
1738 struct stream_size_table stream_size_tab;
1742 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1743 struct list_head *stream_list, u32 nref)
1745 if (!lte->will_be_in_output_wim) {
1746 lte->out_refcnt = 0;
1747 list_add_tail(<e->write_streams_list, stream_list);
1748 lte->will_be_in_output_wim = 1;
1750 lte->out_refcnt += nref;
1754 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1757 struct list_head *stream_list = _stream_list;
1758 lte->will_be_in_output_wim = 0;
1759 reference_stream_for_write(lte, stream_list, lte->refcnt);
1764 inode_find_streams_to_reference(const struct wim_inode *inode,
1765 const struct wim_lookup_table *table,
1766 struct list_head *stream_list)
1768 struct wim_lookup_table_entry *lte;
1771 wimlib_assert(inode->i_nlink > 0);
1773 for (i = 0; i <= inode->i_num_ads; i++) {
1774 lte = inode_stream_lte(inode, i, table);
1776 reference_stream_for_write(lte, stream_list,
1778 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1779 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1785 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1787 lte->will_be_in_output_wim = 0;
1792 image_find_streams_to_reference(WIMStruct *wim)
1794 struct wim_image_metadata *imd;
1795 struct wim_inode *inode;
1796 struct wim_lookup_table_entry *lte;
1797 struct list_head *stream_list;
1800 imd = wim_get_current_image_metadata(wim);
1802 image_for_each_unhashed_stream(lte, imd)
1803 lte->will_be_in_output_wim = 0;
1805 stream_list = wim->private;
1806 image_for_each_inode(inode, imd) {
1807 ret = inode_find_streams_to_reference(inode,
1817 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1820 struct list_head *stream_list_ret)
1824 INIT_LIST_HEAD(stream_list_ret);
1826 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1827 (image == 1 && wim->hdr.image_count == 1)))
1829 /* Fast case: Assume that all streams are being written and
1830 * that the reference counts are correct. */
1831 struct wim_lookup_table_entry *lte;
1832 struct wim_image_metadata *imd;
1835 for_lookup_table_entry(wim->lookup_table,
1836 fully_reference_stream_for_write,
1839 for (i = 0; i < wim->hdr.image_count; i++) {
1840 imd = wim->image_metadata[i];
1841 image_for_each_unhashed_stream(lte, imd)
1842 fully_reference_stream_for_write(lte, stream_list_ret);
1845 /* Slow case: Walk through the images being written and
1846 * determine the streams referenced. */
1847 for_lookup_table_entry(wim->lookup_table,
1848 do_stream_set_not_in_output_wim, NULL);
1849 wim->private = stream_list_ret;
1850 ret = for_image(wim, image, image_find_streams_to_reference);
1858 struct insert_other_if_hard_filtered_ctx {
1859 struct stream_size_table *tab;
1860 struct filter_context *filter_ctx;
1864 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1866 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1868 if (!lte->will_be_in_output_wim &&
1869 stream_hard_filtered(lte, ctx->filter_ctx))
1870 stream_size_table_insert(lte, ctx->tab);
1875 determine_stream_size_uniquity(struct list_head *stream_list,
1876 struct wim_lookup_table *lt,
1877 struct filter_context *filter_ctx)
1880 struct stream_size_table tab;
1881 struct wim_lookup_table_entry *lte;
1883 ret = init_stream_size_table(&tab, 9001);
1887 if (may_hard_filter_streams(filter_ctx)) {
1888 struct insert_other_if_hard_filtered_ctx ctx = {
1890 .filter_ctx = filter_ctx,
1892 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1895 list_for_each_entry(lte, stream_list, write_streams_list)
1896 stream_size_table_insert(lte, &tab);
1898 destroy_stream_size_table(&tab);
1903 filter_stream_list_for_write(struct list_head *stream_list,
1904 struct filter_context *filter_ctx)
1906 struct wim_lookup_table_entry *lte, *tmp;
1908 list_for_each_entry_safe(lte, tmp,
1909 stream_list, write_streams_list)
1911 int status = stream_filtered(lte, filter_ctx);
1918 /* Soft filtered. */
1920 /* Hard filtered. */
1921 lte->will_be_in_output_wim = 0;
1922 list_del(<e->lookup_table_list);
1924 list_del(<e->write_streams_list);
1930 * prepare_stream_list_for_write() -
1932 * Prepare the list of streams to write for writing a WIM containing the
1933 * specified image(s) with the specified write flags.
1936 * The WIMStruct on whose behalf the write is occurring.
1939 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1942 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1944 * STREAMS_OK: For writes of all images, assume that all streams in the
1945 * lookup table of @wim and the per-image lists of unhashed streams should
1946 * be taken as-is, and image metadata should not be searched for
1947 * references. This does not exclude filtering with OVERWRITE and
1948 * SKIP_EXTERNAL_WIMS, below.
1950 * OVERWRITE: Streams already present in @wim shall not be returned in
1953 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1954 * @wim, shall be returned in neither @stream_list_ret nor
1955 * @lookup_table_list_ret.
1958 * List of streams, linked by write_streams_list, that need to be written
1959 * will be returned here.
1961 * Note that this function assumes that unhashed streams will be written;
1962 * it does not take into account that they may become duplicates when
1965 * @lookup_table_list_ret
1966 * List of streams, linked by lookup_table_list, that need to be included
1967 * in the WIM's lookup table will be returned here. This will be a
1968 * superset of the streams in @stream_list_ret.
1970 * This list will be a proper superset of @stream_list_ret if and only if
1971 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1972 * the streams that would otherwise need to be written were already located
1975 * All streams in this list will have @out_refcnt set to the number of
1976 * references to the stream in the output WIM. If
1977 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1978 * may be as low as 0.
1981 * A context for queries of stream filter status with stream_filtered() is
1982 * returned in this location.
1984 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1985 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1986 * lookup table of @wim not inserted into @lookup_table_list_ret.
1988 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1989 * @stream_list_ret that have unique size among all stream entries in
1990 * @stream_list_ret and among all stream entries in the lookup table of @wim
1991 * that are ineligible for being written due to filtering.
1993 * Returns 0 on success; nonzero on read error, memory allocation error, or
1997 prepare_stream_list_for_write(WIMStruct *wim, int image,
1999 struct list_head *stream_list_ret,
2000 struct list_head *lookup_table_list_ret,
2001 struct filter_context *filter_ctx_ret)
2004 struct wim_lookup_table_entry *lte;
2006 filter_ctx_ret->write_flags = write_flags;
2007 filter_ctx_ret->wim = wim;
2009 ret = prepare_unfiltered_list_of_streams_in_output_wim(
2012 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2017 INIT_LIST_HEAD(lookup_table_list_ret);
2018 list_for_each_entry(lte, stream_list_ret, write_streams_list)
2019 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2021 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
2026 if (may_filter_streams(filter_ctx_ret))
2027 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2033 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2034 unsigned num_threads,
2035 struct list_head *stream_list_override,
2036 struct list_head *lookup_table_list_ret)
2039 struct list_head _stream_list;
2040 struct list_head *stream_list;
2041 struct wim_lookup_table_entry *lte;
2042 struct filter_context _filter_ctx;
2043 struct filter_context *filter_ctx;
2045 if (stream_list_override == NULL) {
2046 /* Normal case: prepare stream list from image(s) being written.
2048 stream_list = &_stream_list;
2049 filter_ctx = &_filter_ctx;
2050 ret = prepare_stream_list_for_write(wim, image, write_flags,
2052 lookup_table_list_ret,
2057 /* Currently only as a result of wimlib_split() being called:
2058 * use stream list already explicitly provided. Use existing
2059 * reference counts. */
2060 stream_list = stream_list_override;
2062 INIT_LIST_HEAD(lookup_table_list_ret);
2063 list_for_each_entry(lte, stream_list, write_streams_list) {
2064 lte->out_refcnt = lte->refcnt;
2065 lte->will_be_in_output_wim = 1;
2066 lte->unique_size = 0;
2067 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2071 return wim_write_stream_list(wim,
2079 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags)
2084 int write_resource_flags;
2086 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2087 DEBUG("Not writing any metadata resources.");
2091 write_resource_flags = write_flags_to_resource_flags(write_flags);
2093 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2095 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2096 wim->out_fd.offset);
2098 ret = call_progress(wim->progfunc,
2099 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2100 NULL, wim->progctx);
2104 if (image == WIMLIB_ALL_IMAGES) {
2106 end_image = wim->hdr.image_count;
2108 start_image = image;
2112 for (int i = start_image; i <= end_image; i++) {
2113 struct wim_image_metadata *imd;
2115 imd = wim->image_metadata[i - 1];
2116 /* Build a new metadata resource only if image was modified from
2117 * the original (or was newly added). Otherwise just copy the
2119 if (imd->modified) {
2120 DEBUG("Image %u was modified; building and writing new "
2121 "metadata resource", i);
2122 ret = write_metadata_resource(wim, i,
2123 write_resource_flags);
2124 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2125 DEBUG("Image %u was not modified; re-using existing "
2126 "metadata resource.", i);
2127 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2130 DEBUG("Image %u was not modified; copying existing "
2131 "metadata resource.", i);
2132 ret = write_wim_resource(imd->metadata_lte,
2134 wim->out_compression_type,
2135 wim->out_chunk_size,
2136 write_resource_flags);
2142 return call_progress(wim->progfunc,
2143 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2144 NULL, wim->progctx);
2148 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2151 DEBUG("Opening \"%"TS"\" for writing.", path);
2153 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2155 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2156 return WIMLIB_ERR_OPEN;
2158 filedes_init(&wim->out_fd, raw_fd);
2163 close_wim_writable(WIMStruct *wim, int write_flags)
2167 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2168 DEBUG("Closing WIM file.");
2169 if (filedes_valid(&wim->out_fd))
2170 if (filedes_close(&wim->out_fd))
2171 ret = WIMLIB_ERR_WRITE;
2173 filedes_invalidate(&wim->out_fd);
2178 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2180 const struct wim_lookup_table_entry *lte1, *lte2;
2182 lte1 = *(const struct wim_lookup_table_entry**)p1;
2183 lte2 = *(const struct wim_lookup_table_entry**)p2;
2185 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2186 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2187 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2188 return cmp_u64(lte1->out_res_offset_in_wim,
2189 lte2->out_res_offset_in_wim);
2194 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2197 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2198 lte2->out_reshdr.offset_in_wim);
2202 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2203 struct wim_reshdr *out_reshdr,
2204 struct list_head *lookup_table_list)
2208 /* Set output resource metadata for streams already present in WIM. */
2209 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2210 struct wim_lookup_table_entry *lte;
2211 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2213 if (lte->resource_location == RESOURCE_IN_WIM &&
2214 lte->rspec->wim == wim)
2216 stream_set_out_reshdr_for_reuse(lte);
2221 ret = sort_stream_list(lookup_table_list,
2222 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2223 cmp_streams_by_out_rspec);
2227 /* Add entries for metadata resources. */
2228 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2232 if (image == WIMLIB_ALL_IMAGES) {
2234 end_image = wim->hdr.image_count;
2236 start_image = image;
2240 /* Push metadata resource lookup table entries onto the front of
2241 * the list in reverse order, so that they're written in order.
2243 for (int i = end_image; i >= start_image; i--) {
2244 struct wim_lookup_table_entry *metadata_lte;
2246 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2247 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2248 metadata_lte->out_refcnt = 1;
2249 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2253 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2255 wim->hdr.part_number,
2257 write_flags_to_resource_flags(write_flags));
2263 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2264 * table, then overwrite the WIM header. By default, closes the WIM file
2265 * descriptor (@wim->out_fd) if successful.
2267 * write_flags is a bitwise OR of the following:
2269 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2270 * Include an integrity table.
2272 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2273 * fsync() the output file before closing it.
2275 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2276 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2277 * stream headers before the lookup table and XML data, and also
2278 * write the WIM header at the end instead of seeking to the
2279 * beginning. Can't be combined with
2280 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2282 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2283 * Don't write the lookup table.
2285 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2286 * After writing the XML data but before writing the integrity
2287 * table, write a temporary WIM header and flush the stream so that
2288 * the WIM is less likely to become corrupted upon abrupt program
2290 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2291 * Instead of overwriting the WIM header at the beginning of the
2292 * file, simply append it to the end of the file. (Used when
2294 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2295 * Do not close the file descriptor @wim->out_fd on either success
2297 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2298 * Use the existing <TOTALBYTES> stored in the in-memory XML
2299 * information, rather than setting it to the offset of the XML
2300 * data being written.
2301 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2302 * The existing WIM file is being updated in-place. The entries
2303 * from its integrity table may be re-used.
2306 finish_write(WIMStruct *wim, int image, int write_flags,
2307 struct list_head *lookup_table_list)
2311 int write_resource_flags;
2312 off_t old_lookup_table_end = 0;
2313 off_t new_lookup_table_end;
2315 struct integrity_table *old_integrity_table = NULL;
2317 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2319 write_resource_flags = write_flags_to_resource_flags(write_flags);
2321 /* In the WIM header, there is room for the resource entry for a
2322 * metadata resource labeled as the "boot metadata". This entry should
2323 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2324 * it should be a copy of the resource entry for the image that is
2325 * marked as bootable. This is not well documented... */
2326 if (wim->hdr.boot_idx == 0) {
2327 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2329 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2330 &wim->image_metadata[
2331 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2334 /* If overwriting the WIM file containing an integrity table in-place,
2335 * we'd like to re-use the information in the old integrity table
2336 * instead of recalculating it. But we might overwrite the old
2337 * integrity table when we expand the XML data. Read it into memory
2339 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2340 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2341 (WIMLIB_WRITE_FLAG_OVERWRITE |
2342 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2343 && wim_has_integrity_table(wim))
2345 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2346 wim->hdr.lookup_table_reshdr.size_in_wim;
2347 (void)read_integrity_table(wim,
2348 old_lookup_table_end - WIM_HEADER_DISK_SIZE,
2349 &old_integrity_table);
2350 /* If we couldn't read the old integrity table, we can still
2351 * re-calculate the full integrity table ourselves. Hence the
2352 * ignoring of the return value. */
2355 /* Write lookup table. */
2356 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2357 ret = write_wim_lookup_table(wim, image, write_flags,
2358 &wim->hdr.lookup_table_reshdr,
2361 free_integrity_table(old_integrity_table);
2366 /* Write XML data. */
2367 xml_totalbytes = wim->out_fd.offset;
2368 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2369 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2370 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2371 &wim->hdr.xml_data_reshdr,
2372 write_resource_flags);
2374 free_integrity_table(old_integrity_table);
2378 /* Write integrity table (optional). */
2379 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2380 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2381 struct wim_header checkpoint_hdr;
2382 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2383 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2384 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2385 ret = write_wim_header_at_offset(&checkpoint_hdr,
2388 free_integrity_table(old_integrity_table);
2393 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2394 wim->hdr.lookup_table_reshdr.size_in_wim;
2396 ret = write_integrity_table(wim,
2397 new_lookup_table_end,
2398 old_lookup_table_end,
2399 old_integrity_table);
2400 free_integrity_table(old_integrity_table);
2404 /* No integrity table. */
2405 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2408 /* Now that all information in the WIM header has been determined, the
2409 * preliminary header written earlier can be overwritten, the header of
2410 * the existing WIM file can be overwritten, or the final header can be
2411 * written to the end of the pipable WIM. */
2412 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2414 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2415 hdr_offset = wim->out_fd.offset;
2416 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2417 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2421 /* Possibly sync file data to disk before closing. On POSIX systems, it
2422 * is necessary to do this before using rename() to overwrite an
2423 * existing file with a new file. Otherwise, data loss would occur if
2424 * the system is abruptly terminated when the metadata for the rename
2425 * operation has been written to disk, but the new file data has not.
2427 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2428 DEBUG("Syncing WIM file.");
2429 if (fsync(wim->out_fd.fd)) {
2430 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2431 return WIMLIB_ERR_WRITE;
2435 if (close_wim_writable(wim, write_flags)) {
2436 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2437 return WIMLIB_ERR_WRITE;
2443 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2445 /* Set advisory lock on WIM file (if not already done so) */
2447 lock_wim_for_append(WIMStruct *wim)
2449 if (wim->locked_for_append)
2451 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2452 wim->locked_for_append = 1;
2455 if (errno != EWOULDBLOCK)
2457 return WIMLIB_ERR_ALREADY_LOCKED;
2460 /* Remove advisory lock on WIM file (if present) */
2462 unlock_wim_for_append(WIMStruct *wim)
2464 if (wim->locked_for_append) {
2465 flock(wim->in_fd.fd, LOCK_UN);
2466 wim->locked_for_append = 0;
2472 * write_pipable_wim():
2474 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2475 * capable of being applied from a pipe).
2477 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2478 * images can be applied from them sequentially when the file data is sent over
2479 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2480 * The modifications made to the WIM format for pipable WIMs are:
2482 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2483 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2484 * stops other software from trying to read the file as a normal WIM.
2486 * - The header at the beginning of the file does not contain all the normal
2487 * information; in particular it will have all 0's for the lookup table and
2488 * XML data resource entries. This is because this information cannot be
2489 * determined until the lookup table and XML data have been written.
2490 * Consequently, wimlib will write the full header at the very end of the
2491 * file. The header at the end, however, is only used when reading the WIM
2492 * from a seekable file (not a pipe).
2494 * - An extra copy of the XML data is placed directly after the header. This
2495 * allows image names and sizes to be determined at an appropriate time when
2496 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2497 * WIM is read from a seekable file (not a pipe).
2499 * - The format of resources, or streams, has been modified to allow them to be
2500 * used before the "lookup table" has been read. Each stream is prefixed with
2501 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2502 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2503 * uncompressed stream size, and flags that indicate whether the stream is
2504 * compressed. The data of uncompressed streams then follows literally, while
2505 * the data of compressed streams follows in a modified format. Compressed
2506 * streams do not begin with a chunk table, since the chunk table cannot be
2507 * written until all chunks have been compressed. Instead, each compressed
2508 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2509 * Furthermore, the chunk table is written at the end of the resource instead
2510 * of the start. Note: chunk offsets are given in the chunk table as if the
2511 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2512 * used if the WIM is being read from a seekable file (not a pipe).
2514 * - Metadata resources always come before other file resources (streams).
2515 * (This does not by itself constitute an incompatibility with normal WIMs,
2516 * since this is valid in normal WIMs.)
2518 * - At least up to the end of the file resources, all components must be packed
2519 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2520 * not by itself consititute an incompatibility with normal WIMs, since this
2521 * is valid in normal WIMs.)
2523 * Note: the lookup table, XML data, and header at the end are not used when
2524 * applying from a pipe. They exist to support functionality such as image
2525 * application and export when the WIM is *not* read from a pipe.
2527 * Layout of pipable WIM:
2529 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2530 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2531 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2533 * Layout of normal WIM:
2535 * +--------+-----------------------------+-------------------------+
2536 * | Header | File and metadata resources | Lookup table | XML data |
2537 * +--------+-----------------------------+-------------------------+
2539 * An optional integrity table can follow the final XML data in both normal and
2540 * pipable WIMs. However, due to implementation details, wimlib currently can
2541 * only include an integrity table in a pipable WIM when writing it to a
2542 * seekable file (not a pipe).
2544 * Do note that since pipable WIMs are not supported by Microsoft's software,
2545 * wimlib does not create them unless explicitly requested (with
2546 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2547 * characters to identify the file.
2550 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2551 unsigned num_threads,
2552 struct list_head *stream_list_override,
2553 struct list_head *lookup_table_list_ret)
2556 struct wim_reshdr xml_reshdr;
2558 WARNING("Creating a pipable WIM, which will "
2560 " with Microsoft's software (wimgapi/imagex/Dism).");
2562 /* At this point, the header at the beginning of the file has already
2565 /* For efficiency, when wimlib adds an image to the WIM with
2566 * wimlib_add_image(), the SHA1 message digests of files is not
2567 * calculated; instead, they are calculated while the files are being
2568 * written. However, this does not work when writing a pipable WIM,
2569 * since when writing a stream to a pipable WIM, its SHA1 message digest
2570 * needs to be known before the stream data is written. Therefore,
2571 * before getting much farther, we need to pre-calculate the SHA1
2572 * message digests of all streams that will be written. */
2573 ret = wim_checksum_unhashed_streams(wim);
2577 /* Write extra copy of the XML data. */
2578 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2580 WRITE_RESOURCE_FLAG_PIPABLE);
2584 /* Write metadata resources for the image(s) being included in the
2586 ret = write_wim_metadata_resources(wim, image, write_flags);
2590 /* Write streams needed for the image(s) being included in the output
2591 * WIM, or streams needed for the split WIM part. */
2592 return write_wim_streams(wim, image, write_flags, num_threads,
2593 stream_list_override, lookup_table_list_ret);
2595 /* The lookup table, XML data, and header at end are handled by
2596 * finish_write(). */
2599 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2602 write_wim_part(WIMStruct *wim,
2603 const void *path_or_fd,
2606 unsigned num_threads,
2607 unsigned part_number,
2608 unsigned total_parts,
2609 struct list_head *stream_list_override,
2613 struct wim_header hdr_save;
2614 struct list_head lookup_table_list;
2616 if (total_parts == 1)
2617 DEBUG("Writing standalone WIM.");
2619 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2620 if (image == WIMLIB_ALL_IMAGES)
2621 DEBUG("Including all images.");
2623 DEBUG("Including image %d only.", image);
2624 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2625 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2627 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2628 DEBUG("Write flags: 0x%08x", write_flags);
2630 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2631 DEBUG("\tCHECK_INTEGRITY");
2633 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2634 DEBUG("\tNO_CHECK_INTEGRITY");
2636 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2639 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2640 DEBUG("\tNOT_PIPABLE");
2642 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2643 DEBUG("\tRECOMPRESS");
2645 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2648 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2651 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2652 DEBUG("\tSOFT_DELETE");
2654 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2655 DEBUG("\tIGNORE_READONLY_FLAG");
2657 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2658 DEBUG("\tSKIP_EXTERNAL_WIMS");
2660 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2661 DEBUG("\tSTREAMS_OK");
2663 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2664 DEBUG("\tRETAIN_GUID");
2666 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2667 DEBUG("\tPACK_STREAMS");
2669 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2670 DEBUG("\tFILE_DESCRIPTOR");
2672 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2673 DEBUG("\tNO_METADATA");
2675 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2676 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2678 if (num_threads == 0)
2679 DEBUG("Number of threads: autodetect");
2681 DEBUG("Number of threads: %u", num_threads);
2682 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2683 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2684 DEBUG("GUID: %s", (write_flags &
2685 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2686 : guid ? "explicit" : "generate new");
2688 /* Internally, this is always called with a valid part number and total
2690 wimlib_assert(total_parts >= 1);
2691 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2693 /* A valid image (or all images) must be specified. */
2694 if (image != WIMLIB_ALL_IMAGES &&
2695 (image < 1 || image > wim->hdr.image_count))
2696 return WIMLIB_ERR_INVALID_IMAGE;
2698 /* If we need to write metadata resources, make sure the ::WIMStruct has
2699 * the needed information attached (e.g. is not a resource-only WIM,
2700 * such as a non-first part of a split WIM). */
2701 if (!wim_has_metadata(wim) &&
2702 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2703 return WIMLIB_ERR_METADATA_NOT_FOUND;
2705 /* Check for contradictory flags. */
2706 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2707 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2708 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2709 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2710 return WIMLIB_ERR_INVALID_PARAM;
2712 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2713 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2714 == (WIMLIB_WRITE_FLAG_PIPABLE |
2715 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2716 return WIMLIB_ERR_INVALID_PARAM;
2718 /* Save previous header, then start initializing the new one. */
2719 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2721 /* Set default integrity, pipable, and packed stream flags. */
2722 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2723 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2724 if (wim_is_pipable(wim)) {
2725 DEBUG("WIM is pipable; default to PIPABLE.");
2726 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2729 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2730 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2731 if (wim_has_integrity_table(wim)) {
2732 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2733 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2736 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2737 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2738 == (WIMLIB_WRITE_FLAG_PIPABLE |
2739 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2741 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2742 return WIMLIB_ERR_INVALID_PARAM;
2745 /* Set appropriate magic number. */
2746 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2747 wim->hdr.magic = PWM_MAGIC;
2749 wim->hdr.magic = WIM_MAGIC;
2751 /* Set appropriate version number. */
2752 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2753 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2754 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2756 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2758 /* Clear header flags that will be set automatically. */
2759 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2760 WIM_HDR_FLAG_RESOURCE_ONLY |
2761 WIM_HDR_FLAG_SPANNED |
2762 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2764 /* Set SPANNED header flag if writing part of a split WIM. */
2765 if (total_parts != 1)
2766 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2768 /* Set part number and total parts of split WIM. This will be 1 and 1
2769 * if the WIM is standalone. */
2770 wim->hdr.part_number = part_number;
2771 wim->hdr.total_parts = total_parts;
2773 /* Set compression type if different. */
2774 if (wim->compression_type != wim->out_compression_type) {
2775 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2776 wimlib_assert(ret == 0);
2779 /* Set chunk size if different. */
2780 wim->hdr.chunk_size = wim->out_chunk_size;
2783 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2785 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2787 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2790 /* Clear references to resources that have not been written yet. */
2791 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2792 zero_reshdr(&wim->hdr.xml_data_reshdr);
2793 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2794 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2796 /* Set image count and boot index correctly for single image writes. */
2797 if (image != WIMLIB_ALL_IMAGES) {
2798 wim->hdr.image_count = 1;
2799 if (wim->hdr.boot_idx == image)
2800 wim->hdr.boot_idx = 1;
2802 wim->hdr.boot_idx = 0;
2805 /* Split WIMs can't be bootable. */
2806 if (total_parts != 1)
2807 wim->hdr.boot_idx = 0;
2809 /* Initialize output file descriptor. */
2810 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2811 /* File descriptor was explicitly provided. Return error if
2812 * file descriptor is not seekable, unless writing a pipable WIM
2814 wim->out_fd.fd = *(const int*)path_or_fd;
2815 wim->out_fd.offset = 0;
2816 if (!filedes_is_seekable(&wim->out_fd)) {
2817 ret = WIMLIB_ERR_INVALID_PARAM;
2818 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2819 goto out_restore_hdr;
2820 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2821 ERROR("Can't include integrity check when "
2822 "writing pipable WIM to pipe!");
2823 goto out_restore_hdr;
2828 /* Filename of WIM to write was provided; open file descriptor
2830 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2831 O_TRUNC | O_CREAT | O_RDWR);
2833 goto out_restore_hdr;
2836 /* Write initial header. This is merely a "dummy" header since it
2837 * doesn't have all the information yet, so it will be overwritten later
2838 * (unless writing a pipable WIM). */
2839 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2840 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2841 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2842 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2844 goto out_restore_hdr;
2846 /* Write metadata resources and streams. */
2847 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2848 /* Default case: create a normal (non-pipable) WIM. */
2849 ret = write_wim_streams(wim, image, write_flags, num_threads,
2850 stream_list_override,
2851 &lookup_table_list);
2853 goto out_restore_hdr;
2855 ret = write_wim_metadata_resources(wim, image, write_flags);
2857 goto out_restore_hdr;
2859 /* Non-default case: create pipable WIM. */
2860 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2861 stream_list_override,
2862 &lookup_table_list);
2864 goto out_restore_hdr;
2865 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2869 /* Write lookup table, XML data, and (optional) integrity table. */
2870 ret = finish_write(wim, image, write_flags, &lookup_table_list);
2872 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2873 (void)close_wim_writable(wim, write_flags);
2874 DEBUG("ret=%d", ret);
2878 /* Write a standalone WIM to a file or file descriptor. */
2880 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2881 int image, int write_flags, unsigned num_threads)
2883 return write_wim_part(wim, path_or_fd, image, write_flags,
2884 num_threads, 1, 1, NULL, NULL);
2887 /* API function documented in wimlib.h */
2889 wimlib_write(WIMStruct *wim, const tchar *path,
2890 int image, int write_flags, unsigned num_threads)
2892 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2893 return WIMLIB_ERR_INVALID_PARAM;
2895 if (path == NULL || path[0] == T('\0'))
2896 return WIMLIB_ERR_INVALID_PARAM;
2898 return write_standalone_wim(wim, path, image, write_flags, num_threads);
2901 /* API function documented in wimlib.h */
2903 wimlib_write_to_fd(WIMStruct *wim, int fd,
2904 int image, int write_flags, unsigned num_threads)
2906 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
2907 return WIMLIB_ERR_INVALID_PARAM;
2910 return WIMLIB_ERR_INVALID_PARAM;
2912 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2914 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
2918 any_images_modified(WIMStruct *wim)
2920 for (int i = 0; i < wim->hdr.image_count; i++)
2921 if (wim->image_metadata[i]->modified)
2927 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2929 const WIMStruct *wim = _wim;
2930 off_t end_offset = *(const off_t*)wim->private;
2932 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2933 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2934 return WIMLIB_ERR_RESOURCE_ORDER;
2938 /* Make sure no file or metadata resources are located after the XML data (or
2939 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2940 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2942 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2947 wim->private = &end_offset;
2948 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2952 for (i = 0; i < wim->hdr.image_count; i++) {
2953 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2961 * Overwrite a WIM, possibly appending streams to it.
2963 * A WIM looks like (or is supposed to look like) the following:
2965 * Header (212 bytes)
2966 * Streams and metadata resources (variable size)
2967 * Lookup table (variable size)
2968 * XML data (variable size)
2969 * Integrity table (optional) (variable size)
2971 * If we are not adding any streams or metadata resources, the lookup table is
2972 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2973 * header. This operation is potentially unsafe if the program is abruptly
2974 * terminated while the XML data or integrity table are being overwritten, but
2975 * before the new header has been written. To partially alleviate this problem,
2976 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2977 * finish_write() to cause a temporary WIM header to be written after the XML
2978 * data has been written. This may prevent the WIM from becoming corrupted if
2979 * the program is terminated while the integrity table is being calculated (but
2980 * no guarantees, due to write re-ordering...).
2982 * If we are adding new streams or images (metadata resources), the lookup table
2983 * needs to be changed, and those streams need to be written. In this case, we
2984 * try to perform a safe update of the WIM file by writing the streams *after*
2985 * the end of the previous WIM, then writing the new lookup table, XML data, and
2986 * (optionally) integrity table following the new streams. This will produce a
2987 * layout like the following:
2989 * Header (212 bytes)
2990 * (OLD) Streams and metadata resources (variable size)
2991 * (OLD) Lookup table (variable size)
2992 * (OLD) XML data (variable size)
2993 * (OLD) Integrity table (optional) (variable size)
2994 * (NEW) Streams and metadata resources (variable size)
2995 * (NEW) Lookup table (variable size)
2996 * (NEW) XML data (variable size)
2997 * (NEW) Integrity table (optional) (variable size)
2999 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3000 * the header is overwritten to point to the new lookup table, XML data, and
3001 * integrity table, to produce the following layout:
3003 * Header (212 bytes)
3004 * Streams and metadata resources (variable size)
3005 * Nothing (variable size)
3006 * More Streams and metadata resources (variable size)
3007 * Lookup table (variable size)
3008 * XML data (variable size)
3009 * Integrity table (optional) (variable size)
3011 * This method allows an image to be appended to a large WIM very quickly, and
3012 * is crash-safe except in the case of write re-ordering, but the
3013 * disadvantage is that a small hole is left in the WIM where the old lookup
3014 * table, xml data, and integrity table were. (These usually only take up a
3015 * small amount of space compared to the streams, however.)
3018 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3022 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
3023 struct wim_header hdr_save;
3024 struct list_head stream_list;
3025 struct list_head lookup_table_list;
3026 struct filter_context filter_ctx;
3028 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3030 /* Save original header so it can be restored in case of error */
3031 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3033 /* Set default integrity flag. */
3034 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3035 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3036 if (wim_has_integrity_table(wim))
3037 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3039 /* Set WIM version if adding packed streams. */
3040 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
3041 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
3043 /* Set additional flags for overwrite. */
3044 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3045 WIMLIB_WRITE_FLAG_STREAMS_OK;
3047 /* Make sure that the integrity table (if present) is after the XML
3048 * data, and that there are no stream resources, metadata resources, or
3049 * lookup tables after the XML data. Otherwise, these data would be
3051 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3052 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3053 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
3054 wim->hdr.lookup_table_reshdr.size_in_wim;
3055 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3056 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3057 WARNING("Didn't expect the integrity table to be before the XML data");
3058 ret = WIMLIB_ERR_RESOURCE_ORDER;
3059 goto out_restore_memory_hdr;
3062 if (old_lookup_table_end > old_xml_begin) {
3063 WARNING("Didn't expect the lookup table to be after the XML data");
3064 ret = WIMLIB_ERR_RESOURCE_ORDER;
3065 goto out_restore_memory_hdr;
3068 /* Set @old_wim_end, which indicates the point beyond which we don't
3069 * allow any file and metadata resources to appear without returning
3070 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3071 * overwrite these resources). */
3072 if (!wim->deletion_occurred && !any_images_modified(wim)) {
3073 /* If no images have been modified and no images have been
3074 * deleted, a new lookup table does not need to be written. We
3075 * shall write the new XML data and optional integrity table
3076 * immediately after the lookup table. Note that this may
3077 * overwrite an existing integrity table. */
3078 DEBUG("Skipping writing lookup table "
3079 "(no images modified or deleted)");
3080 old_wim_end = old_lookup_table_end;
3081 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3082 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3083 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3084 /* Old WIM has an integrity table; begin writing new streams
3086 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3087 wim->hdr.integrity_table_reshdr.size_in_wim;
3089 /* No existing integrity table; begin writing new streams after
3090 * the old XML data. */
3091 old_wim_end = old_xml_end;
3094 ret = check_resource_offsets(wim, old_wim_end);
3096 goto out_restore_memory_hdr;
3098 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3099 &stream_list, &lookup_table_list,
3102 goto out_restore_memory_hdr;
3104 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3106 goto out_restore_memory_hdr;
3108 ret = lock_wim_for_append(wim);
3112 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3113 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3114 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3116 ERROR_WITH_ERRNO("Error updating WIM header flags");
3117 goto out_unlock_wim;
3120 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3121 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3122 ret = WIMLIB_ERR_WRITE;
3123 goto out_restore_physical_hdr;
3126 ret = wim_write_stream_list(wim,
3134 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3138 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3139 &lookup_table_list);
3143 unlock_wim_for_append(wim);
3147 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3148 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3149 wim->filename, old_wim_end);
3150 /* Return value of ftruncate() is ignored because this is
3151 * already an error path. */
3152 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3154 out_restore_physical_hdr:
3155 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3157 unlock_wim_for_append(wim);
3159 (void)close_wim_writable(wim, write_flags);
3160 out_restore_memory_hdr:
3161 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3166 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3168 size_t wim_name_len;
3171 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3173 /* Write the WIM to a temporary file in the same directory as the
3175 wim_name_len = tstrlen(wim->filename);
3176 tchar tmpfile[wim_name_len + 10];
3177 tmemcpy(tmpfile, wim->filename, wim_name_len);
3178 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3179 tmpfile[wim_name_len + 9] = T('\0');
3181 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3183 WIMLIB_WRITE_FLAG_FSYNC |
3184 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3191 if (filedes_valid(&wim->in_fd)) {
3192 filedes_close(&wim->in_fd);
3193 filedes_invalidate(&wim->in_fd);
3196 /* Rename the new WIM file to the original WIM file. Note: on Windows
3197 * this actually calls win32_rename_replacement(), not _wrename(), so
3198 * that removing the existing destination file can be handled. */
3199 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3200 ret = trename(tmpfile, wim->filename);
3202 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3203 tmpfile, wim->filename);
3210 return WIMLIB_ERR_RENAME;
3213 union wimlib_progress_info progress;
3214 progress.rename.from = tmpfile;
3215 progress.rename.to = wim->filename;
3216 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3217 &progress, wim->progctx);
3220 /* Determine if the specified WIM file may be updated by appending in-place
3221 * rather than writing and replacing it with an entirely new file. */
3223 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3225 /* REBUILD flag forces full rebuild. */
3226 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3229 /* Deletions cause full rebuild by default. */
3230 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3233 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3234 * turned into a pipable WIM in-place. */
3235 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3238 /* The default compression type and compression chunk size selected for
3239 * the output WIM must be the same as those currently used for the WIM.
3241 if (wim->compression_type != wim->out_compression_type)
3243 if (wim->chunk_size != wim->out_chunk_size)
3249 /* API function documented in wimlib.h */
3251 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3256 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3257 return WIMLIB_ERR_INVALID_PARAM;
3260 return WIMLIB_ERR_NO_FILENAME;
3262 orig_hdr_flags = wim->hdr.flags;
3263 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3264 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3265 ret = can_modify_wim(wim);
3266 wim->hdr.flags = orig_hdr_flags;
3270 if (can_overwrite_wim_inplace(wim, write_flags)) {
3271 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3272 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3274 WARNING("Falling back to re-building entire WIM");
3276 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);