4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/chunk_compressor.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/integrity.h"
43 #include "wimlib/lookup_table.h"
44 #include "wimlib/metadata.h"
45 #include "wimlib/resource.h"
47 # include "wimlib/win32.h" /* win32_rename_replacement() */
49 #include "wimlib/write.h"
50 #include "wimlib/xml.h"
61 /* wimlib internal flags used when writing resources. */
62 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
63 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
64 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
67 write_flags_to_resource_flags(int write_flags)
69 int write_resource_flags = 0;
71 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
72 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
73 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
74 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
75 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
77 return write_resource_flags;
80 struct filter_context {
85 /* Determine specified stream should be filtered out from the write.
89 * < 0 : The stream should be hard-filtered; that is, not included in the
91 * 0 : The stream should not be filtered out.
92 * > 0 : The stream should be soft-filtered; that is, it already exists in the
93 * WIM file and may not need to be written again.
96 stream_filtered(const struct wim_lookup_table_entry *lte,
97 const struct filter_context *ctx)
99 int write_flags = ctx->write_flags;
100 WIMStruct *wim = ctx->wim;
105 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
106 lte->resource_location == RESOURCE_IN_WIM &&
107 lte->rspec->wim == wim)
110 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
111 lte->resource_location == RESOURCE_IN_WIM &&
112 lte->rspec->wim != wim)
119 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
120 struct filter_context *ctx)
122 return stream_filtered(lte, ctx) < 0;
126 may_soft_filter_streams(const struct filter_context *ctx)
130 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
134 may_hard_filter_streams(const struct filter_context *ctx)
138 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
142 may_filter_streams(const struct filter_context *ctx)
144 return (may_soft_filter_streams(ctx) ||
145 may_hard_filter_streams(ctx));
149 /* Return true if the specified resource is compressed and the compressed data
150 * can be reused with the specified output parameters. */
152 can_raw_copy(const struct wim_lookup_table_entry *lte,
153 int write_resource_flags, int out_ctype, u32 out_chunk_size)
155 const struct wim_resource_spec *rspec;
157 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
160 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
163 if (lte->resource_location != RESOURCE_IN_WIM)
168 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
172 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
173 /* Normal compressed resource: Must use same compression type
175 return (rspec->wim->compression_type == out_ctype &&
176 rspec->wim->chunk_size == out_chunk_size);
179 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
180 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
182 /* Packed resource: Such resources may contain multiple streams,
183 * and in general only a subset of them need to be written. As
184 * a heuristic, re-use the raw data if at least half the
185 * uncompressed size is being written. */
187 /* Note: packed resources contain a header that specifies the
188 * compression type and chunk size; therefore we don't need to
189 * check if they are compatible with @out_ctype and
190 * @out_chunk_size. */
192 struct wim_lookup_table_entry *res_stream;
195 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
196 if (res_stream->will_be_in_output_wim)
197 write_size += res_stream->size;
199 return (write_size > rspec->uncompressed_size / 2);
205 filter_resource_flags(u8 flags)
207 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
208 WIM_RESHDR_FLAG_COMPRESSED |
209 WIM_RESHDR_FLAG_SPANNED |
210 WIM_RESHDR_FLAG_FREE));
214 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
216 const struct wim_resource_spec *rspec;
218 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
221 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
223 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
225 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
226 lte->out_reshdr.uncompressed_size = 0;
227 lte->out_reshdr.size_in_wim = lte->size;
229 lte->out_res_offset_in_wim = rspec->offset_in_wim;
230 lte->out_res_size_in_wim = rspec->size_in_wim;
231 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
233 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
235 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
236 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
237 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
239 lte->out_reshdr.flags = lte->flags;
243 /* Write the header for a stream in a pipable WIM. */
245 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
246 struct filedes *out_fd,
247 int additional_reshdr_flags)
249 struct pwm_stream_hdr stream_hdr;
253 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
254 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
255 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
256 zero_out_hash(stream_hdr.hash);
258 wimlib_assert(!lte->unhashed);
259 copy_hash(stream_hdr.hash, lte->hash);
262 reshdr_flags = filter_resource_flags(lte->flags);
263 reshdr_flags |= additional_reshdr_flags;
264 stream_hdr.flags = cpu_to_le32(reshdr_flags);
265 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
267 ERROR_WITH_ERRNO("Write error");
271 struct write_streams_progress_data {
272 wimlib_progress_func_t progress_func;
273 union wimlib_progress_info progress;
274 uint64_t next_progress;
275 WIMStruct *prev_wim_part;
279 do_write_streams_progress(struct write_streams_progress_data *progress_data,
282 struct wim_lookup_table_entry *cur_stream)
284 union wimlib_progress_info *progress = &progress_data->progress;
288 progress->write_streams.total_bytes -= size;
289 if (progress_data->next_progress != ~(uint64_t)0 &&
290 progress_data->next_progress > progress->write_streams.total_bytes)
292 progress_data->next_progress = progress->write_streams.total_bytes;
295 progress->write_streams.completed_bytes += size;
297 new_wim_part = false;
298 if (cur_stream->resource_location == RESOURCE_IN_WIM &&
299 cur_stream->rspec->wim != progress_data->prev_wim_part)
301 if (progress_data->prev_wim_part) {
303 progress->write_streams.completed_parts++;
305 progress_data->prev_wim_part = cur_stream->rspec->wim;
307 progress->write_streams.completed_streams++;
308 if (progress_data->progress_func
309 && (progress->write_streams.completed_bytes >= progress_data->next_progress
312 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
314 if (progress_data->next_progress == progress->write_streams.total_bytes) {
315 progress_data->next_progress = ~(uint64_t)0;
317 progress_data->next_progress =
318 min(progress->write_streams.total_bytes,
319 progress->write_streams.completed_bytes +
320 progress->write_streams.total_bytes / 100);
325 struct write_streams_ctx {
326 /* File descriptor the streams are being written to. */
327 struct filedes *out_fd;
329 /* Lookup table for the WIMStruct on whose behalf the streams are being
331 struct wim_lookup_table *lookup_table;
333 /* Compression format to use. */
336 /* Maximum uncompressed chunk size in compressed resources to use. */
339 /* Flags that affect how the streams will be written. */
340 int write_resource_flags;
342 /* Data used for issuing WRITE_STREAMS progress. */
343 struct write_streams_progress_data progress_data;
345 struct filter_context *filter_ctx;
347 /* Upper bound on the total number of bytes that need to be compressed.
349 u64 num_bytes_to_compress;
351 /* Pointer to the chunk_compressor implementation being used for
352 * compressing chunks of data, or NULL if chunks are being written
354 struct chunk_compressor *compressor;
356 /* Buffer for dividing the read data into chunks of size
357 * @out_chunk_size. */
360 /* Number of bytes in @chunk_buf that are currently filled. */
361 size_t chunk_buf_filled;
363 /* List of streams that currently have chunks being compressed. */
364 struct list_head pending_streams;
366 /* Set to true if the stream currently being read was a duplicate, and
367 * therefore the corresponding stream entry needs to be freed once the
368 * read finishes. (In this case we add the duplicate entry to
369 * pending_streams rather than the entry being read.) */
370 bool stream_was_duplicate;
372 /* Current uncompressed offset in the resource being read. */
373 u64 cur_read_res_offset;
375 /* Uncompressed size of the resource currently being read. */
376 u64 cur_read_res_size;
378 /* Current uncompressed offset in the resource being written. */
379 u64 cur_write_res_offset;
381 /* Uncompressed size of resource currently being written. */
382 u64 cur_write_res_size;
384 /* Array that is filled in with compressed chunk sizes as a resource is
388 /* Index of next entry in @chunk_csizes to fill in. */
391 /* Number of entries in @chunk_csizes currently allocated. */
392 size_t num_alloc_chunks;
394 /* Offset in the output file of the start of the chunks of the resource
395 * currently being written. */
396 u64 chunks_start_offset;
400 get_chunk_entry_size(u64 res_size, int write_resource_flags)
402 if (res_size <= UINT32_MAX ||
403 (write_resource_flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
409 /* Reserve space for the chunk table and prepare to accumulate the chunk table
412 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
414 u64 expected_num_chunks;
415 u64 expected_num_chunk_entries;
419 /* Calculate the number of chunks and chunk entries that should be
420 * needed for the resource. These normally will be the final values,
421 * but in PACKED_STREAMS mode some of the streams we're planning to
422 * write into the resource may be duplicates, and therefore discarded,
423 * potentially decreasing the number of chunk entries needed. */
424 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
425 expected_num_chunk_entries = expected_num_chunks;
426 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
427 expected_num_chunk_entries--;
429 /* Make sure the chunk_csizes array is long enough to store the
430 * compressed size of each chunk. */
431 if (expected_num_chunks > ctx->num_alloc_chunks) {
432 u64 new_length = expected_num_chunks + 50;
434 if ((size_t)new_length != new_length) {
435 ERROR("Resource size too large (%"PRIu64" bytes!",
437 return WIMLIB_ERR_NOMEM;
440 FREE(ctx->chunk_csizes);
441 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
442 if (ctx->chunk_csizes == NULL) {
443 ctx->num_alloc_chunks = 0;
444 return WIMLIB_ERR_NOMEM;
446 ctx->num_alloc_chunks = new_length;
449 ctx->chunk_index = 0;
451 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
452 /* Reserve space for the chunk table in the output file. In the
453 * case of packed resources this reserves the upper bound for
454 * the needed space, not necessarily the exact space which will
455 * prove to be needed. At this point, we just use @chunk_csizes
456 * for a buffer of 0's because the actual compressed chunk sizes
458 reserve_size = expected_num_chunk_entries *
459 get_chunk_entry_size(res_expected_size,
460 ctx->write_resource_flags);
461 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
462 reserve_size += sizeof(struct alt_chunk_table_header_disk);
463 memset(ctx->chunk_csizes, 0, reserve_size);
464 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
472 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
476 wimlib_assert(res_expected_size != 0);
478 if (ctx->compressor != NULL) {
479 ret = begin_chunk_table(ctx, res_expected_size);
484 /* Output file descriptor is now positioned at the offset at which to
485 * write the first chunk of the resource. */
486 ctx->chunks_start_offset = ctx->out_fd->offset;
487 ctx->cur_write_res_offset = 0;
488 ctx->cur_write_res_size = res_expected_size;
493 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
494 u64 *res_start_offset_ret, u64 *res_store_size_ret)
496 size_t actual_num_chunks;
497 size_t actual_num_chunk_entries;
498 size_t chunk_entry_size;
501 actual_num_chunks = ctx->chunk_index;
502 actual_num_chunk_entries = actual_num_chunks;
503 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
504 actual_num_chunk_entries--;
506 chunk_entry_size = get_chunk_entry_size(res_actual_size,
507 ctx->write_resource_flags);
509 typedef le64 __attribute__((may_alias)) aliased_le64_t;
510 typedef le32 __attribute__((may_alias)) aliased_le32_t;
512 if (chunk_entry_size == 4) {
513 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
515 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
516 for (size_t i = 0; i < actual_num_chunk_entries; i++)
517 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
519 u32 offset = ctx->chunk_csizes[0];
520 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
521 u32 next_size = ctx->chunk_csizes[i + 1];
522 entries[i] = cpu_to_le32(offset);
527 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
529 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
530 for (size_t i = 0; i < actual_num_chunk_entries; i++)
531 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
533 u64 offset = ctx->chunk_csizes[0];
534 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
535 u64 next_size = ctx->chunk_csizes[i + 1];
536 entries[i] = cpu_to_le64(offset);
542 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
543 u64 res_start_offset;
546 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
547 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
550 res_end_offset = ctx->out_fd->offset;
551 res_start_offset = ctx->chunks_start_offset;
553 res_end_offset = ctx->out_fd->offset;
555 u64 chunk_table_offset;
557 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
559 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
560 struct alt_chunk_table_header_disk hdr;
562 hdr.res_usize = cpu_to_le64(res_actual_size);
563 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
564 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
566 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
567 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
568 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
570 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
571 chunk_table_offset - sizeof(hdr));
574 res_start_offset = chunk_table_offset - sizeof(hdr);
576 res_start_offset = chunk_table_offset;
579 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
580 chunk_table_size, chunk_table_offset);
585 *res_start_offset_ret = res_start_offset;
586 *res_store_size_ret = res_end_offset - res_start_offset;
591 ERROR_WITH_ERRNO("Write error");
595 /* Finish writing a WIM resource by writing or updating the chunk table (if not
596 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
598 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
602 u64 res_uncompressed_size;
603 u64 res_offset_in_wim;
605 wimlib_assert(ctx->cur_write_res_size == ctx->cur_write_res_offset);
606 res_uncompressed_size = ctx->cur_write_res_size;
608 if (ctx->compressor) {
609 ret = end_chunk_table(ctx, res_uncompressed_size,
610 &res_offset_in_wim, &res_size_in_wim);
614 res_offset_in_wim = ctx->chunks_start_offset;
615 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
617 out_reshdr->uncompressed_size = res_uncompressed_size;
618 out_reshdr->size_in_wim = res_size_in_wim;
619 out_reshdr->offset_in_wim = res_offset_in_wim;
620 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
621 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
625 /* Begin processing a stream for writing. */
627 write_stream_begin_read(struct wim_lookup_table_entry *lte,
628 bool is_partial_res, void *_ctx)
630 struct write_streams_ctx *ctx = _ctx;
633 wimlib_assert(lte->size > 0);
635 ctx->cur_read_res_offset = 0;
636 ctx->cur_read_res_size = lte->size;
638 /* As an optimization, we allow some streams to be "unhashed", meaning
639 * their SHA1 message digests are unknown. This is the case with
640 * streams that are added by scanning a directry tree with
641 * wimlib_add_image(), for example. Since WIM uses single-instance
642 * streams, we don't know whether such each such stream really need to
643 * written until it is actually checksummed, unless it has a unique
644 * size. In such cases we read and checksum the stream in this
645 * function, thereby advancing ahead of read_stream_list(), which will
646 * still provide the data again to write_stream_process_chunk(). This
647 * is okay because an unhashed stream cannot be in a WIM resource, which
648 * might be costly to decompress. */
649 ctx->stream_was_duplicate = false;
650 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
652 wimlib_assert(!is_partial_res);
654 struct wim_lookup_table_entry *lte_new;
656 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
659 if (lte_new != lte) {
660 /* Duplicate stream detected. */
662 if (lte_new->will_be_in_output_wim ||
663 stream_filtered(lte_new, ctx->filter_ctx))
665 /* The duplicate stream is already being
666 * included in the output WIM, or it would be
667 * filtered out if it had been. Skip writing
668 * this stream (and reading it again) entirely,
669 * passing its output reference count to the
670 * duplicate stream in the former case. */
671 DEBUG("Discarding duplicate stream of "
672 "length %"PRIu64, lte->size);
673 do_write_streams_progress(&ctx->progress_data,
674 lte->size, true, lte);
675 list_del(<e->write_streams_list);
676 list_del(<e->lookup_table_list);
677 if (lte_new->will_be_in_output_wim)
678 lte_new->out_refcnt += lte->out_refcnt;
679 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
680 ctx->cur_write_res_size -= lte->size;
681 free_lookup_table_entry(lte);
682 return BEGIN_STREAM_STATUS_SKIP_STREAM;
684 /* The duplicate stream can validly be written,
685 * but was not marked as such. Discard the
686 * current stream entry and use the duplicate,
687 * but actually freeing the current entry must
688 * wait until read_stream_list() has finished
689 * reading its data. */
690 DEBUG("Stream duplicate, but not already "
691 "selected for writing.");
692 list_replace(<e->write_streams_list,
693 <e_new->write_streams_list);
694 list_replace(<e->lookup_table_list,
695 <e_new->lookup_table_list);
696 lte_new->out_refcnt = lte->out_refcnt;
697 lte_new->will_be_in_output_wim = 1;
698 ctx->stream_was_duplicate = true;
703 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
708 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
709 struct filedes *out_fd)
713 if (-1 == lseek(out_fd->fd, lte->out_reshdr.offset_in_wim, SEEK_SET) ||
714 0 != ftruncate(out_fd->fd, lte->out_reshdr.offset_in_wim))
716 ERROR_WITH_ERRNO("Can't truncate output file to "
717 "offset %"PRIu64, lte->out_reshdr.offset_in_wim);
718 return WIMLIB_ERR_WRITE;
721 out_fd->offset = lte->out_reshdr.offset_in_wim;
723 ret = extract_stream_to_fd(lte, out_fd, lte->size);
727 wimlib_assert(out_fd->offset - lte->out_reshdr.offset_in_wim == lte->size);
728 lte->out_reshdr.size_in_wim = lte->size;
729 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
730 WIM_RESHDR_FLAG_PACKED_STREAMS);
734 /* Write the next chunk of (typically compressed) data to the output WIM,
735 * handling the writing of the chunk table. */
737 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
738 size_t csize, size_t usize)
742 struct wim_lookup_table_entry *lte;
744 lte = list_entry(ctx->pending_streams.next,
745 struct wim_lookup_table_entry, write_streams_list);
747 if (ctx->cur_write_res_offset == 0 &&
748 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
750 /* Starting to write a new stream in non-packed mode. */
752 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
753 int additional_reshdr_flags = 0;
754 if (ctx->compressor != NULL)
755 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
757 DEBUG("Writing pipable WIM stream header "
758 "(offset=%"PRIu64")", ctx->out_fd->offset);
760 ret = write_pwm_stream_header(lte, ctx->out_fd,
761 additional_reshdr_flags);
766 ret = begin_write_resource(ctx, lte->size);
771 if (ctx->compressor != NULL) {
772 /* Record the compresed chunk size. */
773 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
774 ctx->chunk_csizes[ctx->chunk_index++] = csize;
776 /* If writing a pipable WIM, before the chunk data write a chunk
777 * header that provides the compressed chunk size. */
778 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
779 struct pwm_chunk_hdr chunk_hdr = {
780 .compressed_size = cpu_to_le32(csize),
782 ret = full_write(ctx->out_fd, &chunk_hdr,
789 /* Write the chunk data. */
790 ret = full_write(ctx->out_fd, cchunk, csize);
794 ctx->cur_write_res_offset += usize;
796 do_write_streams_progress(&ctx->progress_data,
799 if (ctx->cur_write_res_offset == ctx->cur_write_res_size &&
800 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
802 struct wim_lookup_table_entry *lte;
804 lte = list_entry(ctx->pending_streams.next,
805 struct wim_lookup_table_entry, write_streams_list);
806 wimlib_assert(ctx->cur_write_res_offset == lte->size);
808 /* Finished writing a stream in non-packed mode. */
810 ret = end_write_resource(ctx, <e->out_reshdr);
814 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
815 if (ctx->compressor != NULL)
816 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
818 if (ctx->compressor != NULL &&
819 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
820 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) &&
821 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
823 /* Stream did not compress to less than its original
824 * size. If we're not writing a pipable WIM (which
825 * could mean the output file descriptor is
826 * non-seekable), and the stream isn't located in a
827 * resource pack (which would make reading it again
828 * costly), truncate the file to the start of the stream
829 * and write it uncompressed instead. */
830 DEBUG("Stream of size %"PRIu64" did not compress to "
831 "less than original size; writing uncompressed.",
833 ret = write_stream_uncompressed(lte, ctx->out_fd);
838 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
840 list_del(<e->write_streams_list);
841 ctx->cur_write_res_offset = 0;
847 ERROR_WITH_ERRNO("Write error");
852 submit_chunk_for_compression(struct write_streams_ctx *ctx,
853 const void *chunk, size_t size)
855 /* While we are unable to submit the chunk for compression (due to too
856 * many chunks already outstanding), retrieve and write the next
857 * compressed chunk. */
858 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
865 bret = ctx->compressor->get_chunk(ctx->compressor,
866 &cchunk, &csize, &usize);
870 ret = write_chunk(ctx, cchunk, csize, usize);
877 /* Process the next chunk of data to be written to a WIM resource. */
879 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
881 struct write_streams_ctx *ctx = _ctx;
883 const u8 *chunkptr, *chunkend;
885 wimlib_assert(size != 0);
887 if (ctx->compressor == NULL) {
888 /* Write chunk uncompressed. */
889 ret = write_chunk(ctx, chunk, size, size);
892 ctx->cur_read_res_offset += size;
896 /* Submit the chunk for compression, but take into account that the
897 * @size the chunk was provided in may not correspond to the
898 * @out_chunk_size being used for compression. */
900 chunkend = chunkptr + size;
902 const u8 *resized_chunk;
903 size_t needed_chunk_size;
905 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
906 needed_chunk_size = ctx->out_chunk_size;
908 u64 res_bytes_remaining;
910 res_bytes_remaining = ctx->cur_read_res_size -
911 ctx->cur_read_res_offset;
912 needed_chunk_size = min(ctx->out_chunk_size,
913 ctx->chunk_buf_filled +
914 res_bytes_remaining);
917 if (ctx->chunk_buf_filled == 0 &&
918 chunkend - chunkptr >= needed_chunk_size)
920 /* No intermediate buffering needed. */
921 resized_chunk = chunkptr;
922 chunkptr += needed_chunk_size;
923 ctx->cur_read_res_offset += needed_chunk_size;
925 /* Intermediate buffering needed. */
926 size_t bytes_consumed;
928 bytes_consumed = min(chunkend - chunkptr,
929 needed_chunk_size - ctx->chunk_buf_filled);
931 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
932 chunkptr, bytes_consumed);
934 resized_chunk = ctx->chunk_buf;
936 chunkptr += bytes_consumed;
937 ctx->cur_read_res_offset += bytes_consumed;
938 ctx->chunk_buf_filled += bytes_consumed;
939 if (ctx->chunk_buf_filled == needed_chunk_size) {
940 resized_chunk = ctx->chunk_buf;
941 ctx->chunk_buf_filled = 0;
948 ret = submit_chunk_for_compression(ctx, resized_chunk,
953 } while (chunkptr != chunkend);
957 /* Finish processing a stream for writing. It may not have been completely
958 * written yet, as the chunk_compressor implementation may still have chunks
959 * buffered or being compressed. */
961 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
963 struct write_streams_ctx *ctx = _ctx;
965 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
966 if (ctx->stream_was_duplicate) {
967 free_lookup_table_entry(lte);
968 } else if (lte->unhashed && ctx->lookup_table != NULL) {
969 list_del(<e->unhashed_list);
970 lookup_table_insert(ctx->lookup_table, lte);
976 /* Compute statistics about a list of streams that will be written.
978 * Assumes the streams are sorted such that all streams located in each distinct
979 * WIM (specified by WIMStruct) are together. */
981 compute_stream_list_stats(struct list_head *stream_list,
982 struct write_streams_ctx *ctx)
984 struct wim_lookup_table_entry *lte;
988 WIMStruct *prev_wim_part = NULL;
990 list_for_each_entry(lte, stream_list, write_streams_list) {
992 total_bytes += lte->size;
993 if (lte->resource_location == RESOURCE_IN_WIM) {
994 if (prev_wim_part != lte->rspec->wim) {
995 prev_wim_part = lte->rspec->wim;
1000 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1001 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1002 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1003 ctx->progress_data.progress.write_streams.completed_streams = 0;
1004 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1005 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1006 ctx->progress_data.progress.write_streams.completed_parts = 0;
1007 ctx->progress_data.next_progress = 0;
1008 ctx->progress_data.prev_wim_part = NULL;
1011 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1012 * rather than compressed. Delete these streams from @stream_list, and move one
1013 * per resource to @raw_copy_resources. Return the total uncompressed size of
1014 * the streams that need to be compressed. */
1016 find_raw_copy_resources(struct list_head *stream_list,
1017 int write_resource_flags,
1020 struct list_head *raw_copy_resources)
1022 struct wim_lookup_table_entry *lte, *tmp;
1023 u64 num_bytes_to_compress = 0;
1025 INIT_LIST_HEAD(raw_copy_resources);
1027 /* Initialize temporary raw_copy_ok flag. */
1028 list_for_each_entry(lte, stream_list, write_streams_list)
1029 if (lte->resource_location == RESOURCE_IN_WIM)
1030 lte->rspec->raw_copy_ok = 0;
1032 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1033 if (lte->resource_location == RESOURCE_IN_WIM &&
1034 lte->rspec->raw_copy_ok)
1036 list_del(<e->write_streams_list);
1037 } else if (can_raw_copy(lte, write_resource_flags,
1038 out_ctype, out_chunk_size))
1040 lte->rspec->raw_copy_ok = 1;
1041 list_move_tail(<e->write_streams_list,
1042 raw_copy_resources);
1044 num_bytes_to_compress += lte->size;
1048 return num_bytes_to_compress;
1051 /* Copy a raw compressed resource located in another WIM file to the WIM file
1054 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1055 struct filedes *out_fd)
1057 u64 cur_read_offset;
1058 u64 end_read_offset;
1059 u8 buf[BUFFER_SIZE];
1060 size_t bytes_to_read;
1062 struct filedes *in_fd;
1063 struct wim_lookup_table_entry *lte;
1064 u64 out_offset_in_wim;
1066 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1067 "uncompressed_size=%"PRIu64")",
1068 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1070 /* Copy the raw data. */
1071 cur_read_offset = in_rspec->offset_in_wim;
1072 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1074 out_offset_in_wim = out_fd->offset;
1076 if (in_rspec->is_pipable) {
1077 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1078 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1079 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1080 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1082 in_fd = &in_rspec->wim->in_fd;
1083 wimlib_assert(cur_read_offset != end_read_offset);
1086 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1088 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1092 ret = full_write(out_fd, buf, bytes_to_read);
1096 cur_read_offset += bytes_to_read;
1098 } while (cur_read_offset != end_read_offset);
1100 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1101 if (lte->will_be_in_output_wim) {
1102 stream_set_out_reshdr_for_reuse(lte);
1103 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1104 lte->out_res_offset_in_wim = out_offset_in_wim;
1106 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1113 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1114 * file being written. */
1116 write_raw_copy_resources(struct list_head *raw_copy_resources,
1117 struct filedes *out_fd,
1118 struct write_streams_progress_data *progress_data)
1120 struct wim_lookup_table_entry *lte;
1123 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1124 ret = write_raw_copy_resource(lte->rspec, out_fd);
1127 do_write_streams_progress(progress_data, lte->size, false, lte);
1132 /* Wait for and write all chunks pending in the compressor. */
1134 finish_remaining_chunks(struct write_streams_ctx *ctx)
1141 if (ctx->compressor == NULL)
1144 if (ctx->chunk_buf_filled != 0) {
1145 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1146 ctx->chunk_buf_filled);
1151 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1152 ret = write_chunk(ctx, cdata, csize, usize);
1160 remove_zero_length_streams(struct list_head *stream_list)
1162 struct wim_lookup_table_entry *lte, *tmp;
1164 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1165 wimlib_assert(lte->will_be_in_output_wim);
1166 if (lte->size == 0) {
1167 list_del(<e->write_streams_list);
1168 lte->out_reshdr.offset_in_wim = 0;
1169 lte->out_reshdr.size_in_wim = 0;
1170 lte->out_reshdr.uncompressed_size = 0;
1171 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1177 * Write a list of streams to the output WIM file.
1180 * The list of streams to write, specifies a list of `struct
1181 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1184 * The file descriptor, opened for writing, to which to write the streams.
1186 * @write_resource_flags
1187 * Flags to modify how the streams are written:
1189 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1190 * Force compression of all resources, even if they could otherwise
1191 * be re-used by caping the raw data, due to being located in a WIM
1192 * file with compatible compression parameters.
1194 * WRITE_RESOURCE_FLAG_PIPABLE:
1195 * Write the resources in the wimlib-specific pipable format, and
1196 * furthermore do so in such a way that no seeking backwards in
1197 * @out_fd will be performed (so it may be a pipe, contrary to the
1198 * default behavior).
1200 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1201 * Pack all the streams into a single resource rather than writing
1202 * them in separate resources. This format is only valid if the
1203 * WIM version number is WIM_VERSION_PACKED_STREAMS. This flag
1204 * currently may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1207 * Compression format to use to write the output streams, specified as one
1208 * of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1209 * WIMLIB_COMPRESSION_TYPE_INVALID but including
1210 * WIMLIB_COMPRESSION_TYPE_NONE.
1213 * Chunk size to use to write the streams. It must be a valid chunk size
1214 * for the specified compression format @out_ctype, unless @out_ctype is
1215 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1218 * Number of threads to use to compress data. If 0, a default number of
1219 * threads will be chosen. The number of threads still may be decreased
1220 * from the specified value if insufficient memory is detected.
1223 * If on-the-fly deduplication of unhashed streams is desired, this
1224 * parameter must be pointer to the lookup table for the WIMStruct on whose
1225 * behalf the streams are being written. Otherwise, this parameter can be
1229 * If on-the-fly deduplication of unhashed streams is desired, this
1230 * parameter can be a pointer to a context for stream filtering used to
1231 * detect whether the duplicate stream has been hard-filtered or not. If
1232 * no streams are hard-filtered or no streams are unhashed, this parameter
1236 * If non-NULL, a progress function that will be called periodically with
1237 * WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages. Note that on-the-fly
1238 * deduplication of unhashed streams may result in the total bytes provided
1239 * in the progress data to decrease from one message to the next.
1241 * This function will write the streams in @stream_list to resources in
1242 * consecutive positions in the output WIM file, or to a single packed resource
1243 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1244 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1245 * each stream written will be updated to specify its location, size, and flags
1246 * in the output WIM. In the packed resource case,
1247 * WIM_RESHDR_FLAG_PACKED_STREAMS shall be set in the @flags field of the
1248 * @out_reshdr, and @out_res_offset_in_wim and @out_res_size_in_wim will also
1249 * be set to the offset and size, respectively, in the output WIM of the full
1250 * packed resource containing the corresponding stream.
1252 * Each of the streams to write may be in any location supported by the
1253 * resource-handling code (specifically, read_stream_list()), such as the
1254 * contents of external file that has been logically added to the output WIM, or
1255 * a stream in another WIM file that has been imported, or even stream in the
1256 * "same" WIM file of which a modified copy is being written. In the case that
1257 * a stream is already in a WIM file and uses compatible compression parameters,
1258 * by default this function will re-use the raw data instead of decompressing
1259 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1260 * specified in @write_resource_flags, this is not done.
1262 * As a further requirement, this function requires that the
1263 * @will_be_in_output_wim member be set on all streams in @stream_list as well
1264 * as any other streams not in @stream_list that will be in the output WIM file,
1265 * but not on any other streams in the output WIM's lookup table or sharing a
1266 * packed resource with a stream in @stream_list. Still furthermore, if
1267 * on-the-fly deduplication of streams is possible, then all streams in
1268 * @stream_list must also be linked by @lookup_table_list along with any other
1269 * streams that have @will_be_in_output_wim set.
1271 * This function handles on-the-fly deduplication of streams for which SHA1
1272 * message digests have not yet been calculated and it is therefore known
1273 * whether such streams are already in @stream_list or in the WIM's lookup table
1274 * at all. If @lookup_table is non-NULL, then each stream in @stream_list that
1275 * has @unhashed set but not @unique_size set is checksummed immediately before
1276 * it would otherwise be read for writing in order to determine if it is
1277 * identical to another stream already being written or one that would be
1278 * filtered out of the output WIM using stream_filtered() with the context
1279 * @filter_ctx. Each such duplicate stream will be removed from @stream_list, its
1280 * reference count transfered to the pre-existing duplicate stream, its memory
1281 * freed, and will not be written. Alternatively, if a stream in @stream_list
1282 * is a duplicate with any stream in @lookup_table that has not been marked for
1283 * writing or would not be hard-filtered, it is freed and the pre-existing
1284 * duplicate is written instead, taking ownership of the reference count and
1285 * slot in the @lookup_table_list.
1287 * Returns 0 if all streams were written successfully (or did not need to be
1288 * written); otherwise a non-zero error code.
1291 write_stream_list(struct list_head *stream_list,
1292 struct filedes *out_fd,
1293 int write_resource_flags,
1296 unsigned num_threads,
1297 struct wim_lookup_table *lookup_table,
1298 struct filter_context *filter_ctx,
1299 wimlib_progress_func_t progress_func)
1302 struct write_streams_ctx ctx;
1303 struct list_head raw_copy_resources;
1305 wimlib_assert((write_resource_flags &
1306 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1307 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1308 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1309 WRITE_RESOURCE_FLAG_PIPABLE));
1311 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
1312 out_chunk_size = 1U << 26;
1314 remove_zero_length_streams(stream_list);
1316 if (list_empty(stream_list)) {
1317 DEBUG("No streams to write.");
1321 memset(&ctx, 0, sizeof(ctx));
1323 /* Pre-sorting the streams is required for compute_stream_list_stats().
1324 * Afterwards, read_stream_list() need not sort them again. */
1325 ret = sort_stream_list_by_sequential_order(stream_list,
1326 offsetof(struct wim_lookup_table_entry,
1327 write_streams_list));
1331 ctx.out_fd = out_fd;
1332 ctx.lookup_table = lookup_table;
1333 ctx.out_ctype = out_ctype;
1334 ctx.out_chunk_size = out_chunk_size;
1335 ctx.write_resource_flags = write_resource_flags;
1336 ctx.filter_ctx = filter_ctx;
1338 if (out_chunk_size != 0) {
1339 if (out_chunk_size <= STACK_MAX) {
1340 ctx.chunk_buf = alloca(out_chunk_size);
1342 ctx.chunk_buf = MALLOC(out_chunk_size);
1343 if (ctx.chunk_buf == NULL) {
1344 ret = WIMLIB_ERR_NOMEM;
1345 goto out_destroy_context;
1349 ctx.chunk_buf_filled = 0;
1351 compute_stream_list_stats(stream_list, &ctx);
1353 ctx.progress_data.progress_func = progress_func;
1355 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1356 write_resource_flags,
1359 &raw_copy_resources);
1361 DEBUG("Writing stream list "
1362 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1363 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1364 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1365 out_fd->offset, write_resource_flags,
1366 out_ctype, out_chunk_size, num_threads,
1367 ctx.progress_data.progress.write_streams.total_bytes,
1368 ctx.num_bytes_to_compress);
1370 if (ctx.num_bytes_to_compress == 0) {
1371 DEBUG("No compression needed; skipping to raw copy!");
1372 goto out_write_raw_copy_resources;
1375 /* Unless uncompressed output was required, allocate a chunk_compressor
1376 * to do compression. There are serial and parallel implementations of
1377 * the chunk_compressor interface. We default to parallel using the
1378 * specified number of threads, unless the upper bound on the number
1379 * bytes needing to be compressed is less 2000000 (heuristic value). */
1380 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1382 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1383 if (ctx.num_bytes_to_compress >= 2000000) {
1384 ret = new_parallel_chunk_compressor(out_ctype,
1389 DEBUG("Couldn't create parallel chunk compressor "
1390 "(status %d)", ret);
1395 if (ctx.compressor == NULL) {
1396 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1399 goto out_destroy_context;
1404 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1406 ctx.progress_data.progress.write_streams.num_threads = 1;
1408 DEBUG("Actually using %u threads",
1409 ctx.progress_data.progress.write_streams.num_threads);
1411 INIT_LIST_HEAD(&ctx.pending_streams);
1413 if (ctx.progress_data.progress_func) {
1414 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1415 &ctx.progress_data.progress);
1418 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1419 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1421 goto out_destroy_context;
1424 /* Read the list of streams needing to be compressed, using the
1425 * specified callbacks to execute processing of the data. */
1427 struct read_stream_list_callbacks cbs = {
1428 .begin_stream = write_stream_begin_read,
1429 .begin_stream_ctx = &ctx,
1430 .consume_chunk = write_stream_process_chunk,
1431 .consume_chunk_ctx = &ctx,
1432 .end_stream = write_stream_end_read,
1433 .end_stream_ctx = &ctx,
1436 ret = read_stream_list(stream_list,
1437 offsetof(struct wim_lookup_table_entry, write_streams_list),
1439 STREAM_LIST_ALREADY_SORTED |
1440 VERIFY_STREAM_HASHES |
1441 COMPUTE_MISSING_STREAM_HASHES);
1444 goto out_destroy_context;
1446 ret = finish_remaining_chunks(&ctx);
1448 goto out_destroy_context;
1450 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1451 struct wim_reshdr reshdr;
1452 struct wim_lookup_table_entry *lte;
1455 ret = end_write_resource(&ctx, &reshdr);
1457 goto out_destroy_context;
1459 DEBUG("Ending packed resource: %lu %lu %lu.",
1460 reshdr.offset_in_wim,
1462 reshdr.uncompressed_size);
1465 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1466 lte->out_reshdr.size_in_wim = lte->size;
1467 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1468 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1469 lte->out_reshdr.uncompressed_size = 0;
1470 lte->out_reshdr.offset_in_wim = offset_in_res;
1471 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1472 lte->out_res_size_in_wim = reshdr.size_in_wim;
1473 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1474 offset_in_res += lte->size;
1476 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1479 out_write_raw_copy_resources:
1480 /* Copy any compressed resources for which the raw data can be reused
1481 * without decompression. */
1482 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1483 &ctx.progress_data);
1485 out_destroy_context:
1486 if (out_chunk_size > STACK_MAX)
1487 FREE(ctx.chunk_buf);
1488 FREE(ctx.chunk_csizes);
1490 ctx.compressor->destroy(ctx.compressor);
1491 DEBUG("Done (ret=%d)", ret);
1496 write_wim_resource(struct wim_lookup_table_entry *lte,
1497 struct filedes *out_fd,
1500 int write_resource_flags)
1502 LIST_HEAD(stream_list);
1503 list_add(<e->write_streams_list, &stream_list);
1504 lte->will_be_in_output_wim = 1;
1505 return write_stream_list(&stream_list,
1507 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1517 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1518 int reshdr_flags, struct filedes *out_fd,
1521 struct wim_reshdr *out_reshdr,
1523 int write_resource_flags)
1526 struct wim_lookup_table_entry *lte;
1528 /* Set up a temporary lookup table entry to provide to
1529 * write_wim_resource(). */
1531 lte = new_lookup_table_entry();
1533 return WIMLIB_ERR_NOMEM;
1535 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1536 lte->attached_buffer = (void*)buf;
1537 lte->size = buf_size;
1538 lte->flags = reshdr_flags;
1540 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1541 sha1_buffer(buf, buf_size, lte->hash);
1547 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1548 write_resource_flags);
1552 copy_reshdr(out_reshdr, <e->out_reshdr);
1555 copy_hash(hash, lte->hash);
1558 lte->resource_location = RESOURCE_NONEXISTENT;
1559 free_lookup_table_entry(lte);
1563 struct stream_size_table {
1564 struct hlist_head *array;
1570 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1572 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1573 if (tab->array == NULL)
1574 return WIMLIB_ERR_NOMEM;
1575 tab->num_entries = 0;
1576 tab->capacity = capacity;
1581 destroy_stream_size_table(struct stream_size_table *tab)
1587 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1589 struct stream_size_table *tab = _tab;
1591 struct wim_lookup_table_entry *same_size_lte;
1592 struct hlist_node *tmp;
1594 pos = hash_u64(lte->size) % tab->capacity;
1595 lte->unique_size = 1;
1596 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1597 if (same_size_lte->size == lte->size) {
1598 lte->unique_size = 0;
1599 same_size_lte->unique_size = 0;
1604 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1609 struct find_streams_ctx {
1612 struct list_head stream_list;
1613 struct stream_size_table stream_size_tab;
1617 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1618 struct list_head *stream_list, u32 nref)
1620 if (!lte->will_be_in_output_wim) {
1621 lte->out_refcnt = 0;
1622 list_add_tail(<e->write_streams_list, stream_list);
1623 lte->will_be_in_output_wim = 1;
1625 lte->out_refcnt += nref;
1629 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1632 struct list_head *stream_list = _stream_list;
1633 lte->will_be_in_output_wim = 0;
1634 reference_stream_for_write(lte, stream_list, lte->refcnt);
1639 inode_find_streams_to_reference(const struct wim_inode *inode,
1640 const struct wim_lookup_table *table,
1641 struct list_head *stream_list)
1643 struct wim_lookup_table_entry *lte;
1646 wimlib_assert(inode->i_nlink > 0);
1648 for (i = 0; i <= inode->i_num_ads; i++) {
1649 lte = inode_stream_lte(inode, i, table);
1651 reference_stream_for_write(lte, stream_list,
1653 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1654 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1660 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1662 lte->will_be_in_output_wim = 0;
1667 image_find_streams_to_reference(WIMStruct *wim)
1669 struct wim_image_metadata *imd;
1670 struct wim_inode *inode;
1671 struct wim_lookup_table_entry *lte;
1672 struct list_head *stream_list;
1675 imd = wim_get_current_image_metadata(wim);
1677 image_for_each_unhashed_stream(lte, imd)
1678 lte->will_be_in_output_wim = 0;
1680 stream_list = wim->private;
1681 image_for_each_inode(inode, imd) {
1682 ret = inode_find_streams_to_reference(inode,
1692 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1695 struct list_head *stream_list_ret)
1699 INIT_LIST_HEAD(stream_list_ret);
1701 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1702 (image == 1 && wim->hdr.image_count == 1)))
1704 /* Fast case: Assume that all streams are being written and
1705 * that the reference counts are correct. */
1706 struct wim_lookup_table_entry *lte;
1707 struct wim_image_metadata *imd;
1710 for_lookup_table_entry(wim->lookup_table,
1711 fully_reference_stream_for_write,
1714 for (i = 0; i < wim->hdr.image_count; i++) {
1715 imd = wim->image_metadata[i];
1716 image_for_each_unhashed_stream(lte, imd)
1717 fully_reference_stream_for_write(lte, stream_list_ret);
1720 /* Slow case: Walk through the images being written and
1721 * determine the streams referenced. */
1722 for_lookup_table_entry(wim->lookup_table,
1723 do_stream_set_not_in_output_wim, NULL);
1724 wim->private = stream_list_ret;
1725 ret = for_image(wim, image, image_find_streams_to_reference);
1733 struct insert_other_if_hard_filtered_ctx {
1734 struct stream_size_table *tab;
1735 struct filter_context *filter_ctx;
1739 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1741 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1743 if (!lte->will_be_in_output_wim &&
1744 stream_hard_filtered(lte, ctx->filter_ctx))
1745 stream_size_table_insert(lte, ctx->tab);
1750 determine_stream_size_uniquity(struct list_head *stream_list,
1751 struct wim_lookup_table *lt,
1752 struct filter_context *filter_ctx)
1755 struct stream_size_table tab;
1756 struct wim_lookup_table_entry *lte;
1758 ret = init_stream_size_table(&tab, lt->capacity);
1762 if (may_hard_filter_streams(filter_ctx)) {
1763 struct insert_other_if_hard_filtered_ctx ctx = {
1765 .filter_ctx = filter_ctx,
1767 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1770 list_for_each_entry(lte, stream_list, write_streams_list)
1771 stream_size_table_insert(lte, &tab);
1773 destroy_stream_size_table(&tab);
1778 filter_stream_list_for_write(struct list_head *stream_list,
1779 struct filter_context *filter_ctx)
1781 struct wim_lookup_table_entry *lte, *tmp;
1783 list_for_each_entry_safe(lte, tmp,
1784 stream_list, write_streams_list)
1786 int status = stream_filtered(lte, filter_ctx);
1793 /* Soft filtered. */
1795 /* Hard filtered. */
1796 lte->will_be_in_output_wim = 0;
1797 list_del(<e->lookup_table_list);
1799 list_del(<e->write_streams_list);
1805 * prepare_stream_list_for_write() -
1807 * Prepare the list of streams to write for writing a WIM containing the
1808 * specified image(s) with the specified write flags.
1811 * The WIMStruct on whose behalf the write is occurring.
1814 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1817 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1819 * STREAMS_OK: For writes of all images, assume that all streams in the
1820 * lookup table of @wim and the per-image lists of unhashed streams should
1821 * be taken as-is, and image metadata should not be searched for
1822 * references. This does not exclude filtering with OVERWRITE and
1823 * SKIP_EXTERNAL_WIMS, below.
1825 * OVERWRITE: Streams already present in @wim shall not be returned in
1828 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1829 * @wim, shall be be returned in neither @stream_list_ret nor
1830 * @lookup_table_list_ret.
1833 * List of streams, linked by write_streams_list, that need to be written
1834 * will be returned here.
1836 * Note that this function assumes that unhashed streams will be written;
1837 * it does not take into account that they may become duplicates when
1840 * @lookup_table_list_ret
1841 * List of streams, linked by lookup_table_list, that need to be included
1842 * in the WIM's lookup table will be returned here. This will be a
1843 * superset of the streams in @stream_list_ret.
1845 * This list will be a proper superset of @stream_list_ret if and only if
1846 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1847 * the streams that would otherwise need to be written were already located
1850 * All streams in this list will have @out_refcnt set to the number of
1851 * references to the stream in the output WIM. If
1852 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1853 * may be as low as 0.
1856 * A context for queries of stream filter status with stream_filtered() is
1857 * returned in this location.
1859 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1860 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1861 * lookup table of @wim not inserted into @lookup_table_list_ret.
1863 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1864 * @stream_list_ret that have unique size among all stream entries in
1865 * @stream_list_ret and among all stream entries in the lookup table of @wim
1866 * that are ineligible for being written due to filtering.
1868 * Returns 0 on success; nonzero on read error, memory allocation error, or
1872 prepare_stream_list_for_write(WIMStruct *wim, int image,
1874 struct list_head *stream_list_ret,
1875 struct list_head *lookup_table_list_ret,
1876 struct filter_context *filter_ctx_ret)
1879 struct wim_lookup_table_entry *lte;
1881 filter_ctx_ret->write_flags = write_flags;
1882 filter_ctx_ret->wim = wim;
1884 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1887 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1892 INIT_LIST_HEAD(lookup_table_list_ret);
1893 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1894 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1896 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1901 if (may_filter_streams(filter_ctx_ret))
1902 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1908 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1909 unsigned num_threads,
1910 wimlib_progress_func_t progress_func,
1911 struct list_head *stream_list_override,
1912 struct list_head *lookup_table_list_ret)
1915 struct list_head _stream_list;
1916 struct list_head *stream_list;
1917 struct wim_lookup_table_entry *lte;
1918 struct filter_context _filter_ctx;
1919 struct filter_context *filter_ctx;
1921 if (stream_list_override == NULL) {
1922 /* Normal case: prepare stream list from image(s) being written.
1924 stream_list = &_stream_list;
1925 filter_ctx = &_filter_ctx;
1926 ret = prepare_stream_list_for_write(wim, image, write_flags,
1928 lookup_table_list_ret,
1933 /* Currently only as a result of wimlib_split() being called:
1934 * use stream list already explicitly provided. Use existing
1935 * reference counts. */
1936 stream_list = stream_list_override;
1938 INIT_LIST_HEAD(lookup_table_list_ret);
1939 list_for_each_entry(lte, stream_list, write_streams_list) {
1940 lte->out_refcnt = lte->refcnt;
1941 lte->will_be_in_output_wim = 1;
1942 lte->unique_size = 0;
1943 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1947 return write_stream_list(stream_list,
1949 write_flags_to_resource_flags(write_flags),
1950 wim->out_compression_type,
1951 wim->out_chunk_size,
1959 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1960 wimlib_progress_func_t progress_func)
1965 int write_resource_flags;
1967 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1968 DEBUG("Not writing any metadata resources.");
1972 write_resource_flags = write_flags_to_resource_flags(write_flags);
1974 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
1976 DEBUG("Writing metadata resources (offset=%"PRIu64")",
1977 wim->out_fd.offset);
1980 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1982 if (image == WIMLIB_ALL_IMAGES) {
1984 end_image = wim->hdr.image_count;
1986 start_image = image;
1990 for (int i = start_image; i <= end_image; i++) {
1991 struct wim_image_metadata *imd;
1993 imd = wim->image_metadata[i - 1];
1994 /* Build a new metadata resource only if image was modified from
1995 * the original (or was newly added). Otherwise just copy the
1997 if (imd->modified) {
1998 DEBUG("Image %u was modified; building and writing new "
1999 "metadata resource", i);
2000 ret = write_metadata_resource(wim, i,
2001 write_resource_flags);
2002 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2003 DEBUG("Image %u was not modified; re-using existing "
2004 "metadata resource.", i);
2005 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2008 DEBUG("Image %u was not modified; copying existing "
2009 "metadata resource.", i);
2010 ret = write_wim_resource(imd->metadata_lte,
2012 wim->out_compression_type,
2013 wim->out_chunk_size,
2014 write_resource_flags);
2020 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2025 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2028 DEBUG("Opening \"%"TS"\" for writing.", path);
2030 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2032 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2033 return WIMLIB_ERR_OPEN;
2035 filedes_init(&wim->out_fd, raw_fd);
2040 close_wim_writable(WIMStruct *wim, int write_flags)
2044 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2045 DEBUG("Closing WIM file.");
2046 if (filedes_valid(&wim->out_fd))
2047 if (filedes_close(&wim->out_fd))
2048 ret = WIMLIB_ERR_WRITE;
2050 filedes_invalidate(&wim->out_fd);
2055 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2057 const struct wim_lookup_table_entry *lte1, *lte2;
2059 lte1 = *(const struct wim_lookup_table_entry**)p1;
2060 lte2 = *(const struct wim_lookup_table_entry**)p2;
2062 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2063 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2064 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2065 return cmp_u64(lte1->out_res_offset_in_wim,
2066 lte2->out_res_offset_in_wim);
2071 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2074 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2075 lte2->out_reshdr.offset_in_wim);
2079 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2080 struct wim_reshdr *out_reshdr,
2081 struct list_head *lookup_table_list)
2085 /* Set output resource metadata for streams already present in WIM. */
2086 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2087 struct wim_lookup_table_entry *lte;
2088 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2090 if (lte->resource_location == RESOURCE_IN_WIM &&
2091 lte->rspec->wim == wim)
2093 stream_set_out_reshdr_for_reuse(lte);
2098 ret = sort_stream_list(lookup_table_list,
2099 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2100 cmp_streams_by_out_rspec);
2104 /* Add entries for metadata resources. */
2105 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2109 if (image == WIMLIB_ALL_IMAGES) {
2111 end_image = wim->hdr.image_count;
2113 start_image = image;
2117 /* Push metadata resource lookup table entries onto the front of
2118 * the list in reverse order, so that they're written in order.
2120 for (int i = end_image; i >= start_image; i--) {
2121 struct wim_lookup_table_entry *metadata_lte;
2123 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2124 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2125 metadata_lte->out_refcnt = 1;
2126 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2130 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2132 wim->hdr.part_number,
2134 write_flags_to_resource_flags(write_flags));
2140 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2141 * table, then overwrite the WIM header. By default, closes the WIM file
2142 * descriptor (@wim->out_fd) if successful.
2144 * write_flags is a bitwise OR of the following:
2146 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2147 * Include an integrity table.
2149 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2150 * fsync() the output file before closing it.
2152 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2153 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2154 * stream headers before the lookup table and XML data, and also
2155 * write the WIM header at the end instead of seeking to the
2156 * beginning. Can't be combined with
2157 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2159 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2160 * Don't write the lookup table.
2162 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2163 * When (if) writing the integrity table, re-use entries from the
2164 * existing integrity table, if possible.
2166 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2167 * After writing the XML data but before writing the integrity
2168 * table, write a temporary WIM header and flush the stream so that
2169 * the WIM is less likely to become corrupted upon abrupt program
2171 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2172 * Instead of overwriting the WIM header at the beginning of the
2173 * file, simply append it to the end of the file. (Used when
2175 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2176 * Do not close the file descriptor @wim->out_fd on either success
2178 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2179 * Use the existing <TOTALBYTES> stored in the in-memory XML
2180 * information, rather than setting it to the offset of the XML
2181 * data being written.
2184 finish_write(WIMStruct *wim, int image, int write_flags,
2185 wimlib_progress_func_t progress_func,
2186 struct list_head *lookup_table_list)
2190 int write_resource_flags;
2191 off_t old_lookup_table_end;
2192 off_t new_lookup_table_end;
2195 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2197 write_resource_flags = write_flags_to_resource_flags(write_flags);
2199 /* In the WIM header, there is room for the resource entry for a
2200 * metadata resource labeled as the "boot metadata". This entry should
2201 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2202 * it should be a copy of the resource entry for the image that is
2203 * marked as bootable. This is not well documented... */
2204 if (wim->hdr.boot_idx == 0) {
2205 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2207 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2208 &wim->image_metadata[
2209 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2212 /* Write lookup table. (Save old position first.) */
2213 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2214 wim->hdr.lookup_table_reshdr.size_in_wim;
2215 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2216 ret = write_wim_lookup_table(wim, image, write_flags,
2217 &wim->hdr.lookup_table_reshdr,
2223 /* Write XML data. */
2224 xml_totalbytes = wim->out_fd.offset;
2225 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2226 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2227 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2228 &wim->hdr.xml_data_reshdr,
2229 write_resource_flags);
2233 /* Write integrity table (optional). */
2234 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2235 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2236 struct wim_header checkpoint_hdr;
2237 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2238 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2239 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2240 ret = write_wim_header_at_offset(&checkpoint_hdr,
2246 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2247 old_lookup_table_end = 0;
2249 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2250 wim->hdr.lookup_table_reshdr.size_in_wim;
2252 ret = write_integrity_table(wim,
2253 new_lookup_table_end,
2254 old_lookup_table_end,
2259 /* No integrity table. */
2260 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2263 /* Now that all information in the WIM header has been determined, the
2264 * preliminary header written earlier can be overwritten, the header of
2265 * the existing WIM file can be overwritten, or the final header can be
2266 * written to the end of the pipable WIM. */
2267 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2269 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2270 hdr_offset = wim->out_fd.offset;
2271 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2272 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2276 /* Possibly sync file data to disk before closing. On POSIX systems, it
2277 * is necessary to do this before using rename() to overwrite an
2278 * existing file with a new file. Otherwise, data loss would occur if
2279 * the system is abruptly terminated when the metadata for the rename
2280 * operation has been written to disk, but the new file data has not.
2282 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2283 DEBUG("Syncing WIM file.");
2284 if (fsync(wim->out_fd.fd)) {
2285 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2286 return WIMLIB_ERR_WRITE;
2290 if (close_wim_writable(wim, write_flags)) {
2291 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2292 return WIMLIB_ERR_WRITE;
2298 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2300 lock_wim(WIMStruct *wim, int fd)
2303 if (fd != -1 && !wim->wim_locked) {
2304 ret = flock(fd, LOCK_EX | LOCK_NB);
2306 if (errno == EWOULDBLOCK) {
2307 ERROR("`%"TS"' is already being modified or has been "
2308 "mounted read-write\n"
2309 " by another process!", wim->filename);
2310 ret = WIMLIB_ERR_ALREADY_LOCKED;
2312 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2317 wim->wim_locked = 1;
2325 * write_pipable_wim():
2327 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2328 * capable of being applied from a pipe).
2330 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2331 * images can be applied from them sequentially when the file data is sent over
2332 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2333 * The modifications made to the WIM format for pipable WIMs are:
2335 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2336 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2337 * stops other software from trying to read the file as a normal WIM.
2339 * - The header at the beginning of the file does not contain all the normal
2340 * information; in particular it will have all 0's for the lookup table and
2341 * XML data resource entries. This is because this information cannot be
2342 * determined until the lookup table and XML data have been written.
2343 * Consequently, wimlib will write the full header at the very end of the
2344 * file. The header at the end, however, is only used when reading the WIM
2345 * from a seekable file (not a pipe).
2347 * - An extra copy of the XML data is placed directly after the header. This
2348 * allows image names and sizes to be determined at an appropriate time when
2349 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2350 * WIM is read from a seekable file (not a pipe).
2352 * - The format of resources, or streams, has been modified to allow them to be
2353 * used before the "lookup table" has been read. Each stream is prefixed with
2354 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2355 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2356 * uncompressed stream size, and flags that indicate whether the stream is
2357 * compressed. The data of uncompressed streams then follows literally, while
2358 * the data of compressed streams follows in a modified format. Compressed
2359 * streams do not begin with a chunk table, since the chunk table cannot be
2360 * written until all chunks have been compressed. Instead, each compressed
2361 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2362 * Furthermore, the chunk table is written at the end of the resource instead
2363 * of the start. Note: chunk offsets are given in the chunk table as if the
2364 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2365 * used if the WIM is being read from a seekable file (not a pipe).
2367 * - Metadata resources always come before other file resources (streams).
2368 * (This does not by itself constitute an incompatibility with normal WIMs,
2369 * since this is valid in normal WIMs.)
2371 * - At least up to the end of the file resources, all components must be packed
2372 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2373 * not by itself consititute an incompatibility with normal WIMs, since this
2374 * is valid in normal WIMs.)
2376 * Note: the lookup table, XML data, and header at the end are not used when
2377 * applying from a pipe. They exist to support functionality such as image
2378 * application and export when the WIM is *not* read from a pipe.
2380 * Layout of pipable WIM:
2382 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2383 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2384 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2386 * Layout of normal WIM:
2388 * +--------+-----------------------------+-------------------------+
2389 * | Header | File and metadata resources | Lookup table | XML data |
2390 * +--------+-----------------------------+-------------------------+
2392 * An optional integrity table can follow the final XML data in both normal and
2393 * pipable WIMs. However, due to implementation details, wimlib currently can
2394 * only include an integrity table in a pipable WIM when writing it to a
2395 * seekable file (not a pipe).
2397 * Do note that since pipable WIMs are not supported by Microsoft's software,
2398 * wimlib does not create them unless explicitly requested (with
2399 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2400 * characters to identify the file.
2403 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2404 unsigned num_threads, wimlib_progress_func_t progress_func,
2405 struct list_head *stream_list_override,
2406 struct list_head *lookup_table_list_ret)
2409 struct wim_reshdr xml_reshdr;
2411 WARNING("Creating a pipable WIM, which will "
2413 " with Microsoft's software (wimgapi/imagex/Dism).");
2415 /* At this point, the header at the beginning of the file has already
2418 /* For efficiency, when wimlib adds an image to the WIM with
2419 * wimlib_add_image(), the SHA1 message digests of files is not
2420 * calculated; instead, they are calculated while the files are being
2421 * written. However, this does not work when writing a pipable WIM,
2422 * since when writing a stream to a pipable WIM, its SHA1 message digest
2423 * needs to be known before the stream data is written. Therefore,
2424 * before getting much farther, we need to pre-calculate the SHA1
2425 * message digests of all streams that will be written. */
2426 ret = wim_checksum_unhashed_streams(wim);
2430 /* Write extra copy of the XML data. */
2431 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2433 WRITE_RESOURCE_FLAG_PIPABLE);
2437 /* Write metadata resources for the image(s) being included in the
2439 ret = write_wim_metadata_resources(wim, image, write_flags,
2444 /* Write streams needed for the image(s) being included in the output
2445 * WIM, or streams needed for the split WIM part. */
2446 return write_wim_streams(wim, image, write_flags, num_threads,
2447 progress_func, stream_list_override,
2448 lookup_table_list_ret);
2450 /* The lookup table, XML data, and header at end are handled by
2451 * finish_write(). */
2454 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2457 write_wim_part(WIMStruct *wim,
2458 const void *path_or_fd,
2461 unsigned num_threads,
2462 wimlib_progress_func_t progress_func,
2463 unsigned part_number,
2464 unsigned total_parts,
2465 struct list_head *stream_list_override,
2469 struct wim_header hdr_save;
2470 struct list_head lookup_table_list;
2472 if (total_parts == 1)
2473 DEBUG("Writing standalone WIM.");
2475 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2476 if (image == WIMLIB_ALL_IMAGES)
2477 DEBUG("Including all images.");
2479 DEBUG("Including image %d only.", image);
2480 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2481 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2483 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2484 DEBUG("Write flags: 0x%08x", write_flags);
2486 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2487 DEBUG("\tCHECK_INTEGRITY");
2489 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2492 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2493 DEBUG("\tRECOMPRESS");
2495 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2498 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2501 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2502 DEBUG("\tIGNORE_READONLY_FLAG");
2504 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2507 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2508 DEBUG("\tNOT_PIPABLE");
2510 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2511 DEBUG("\tPACK_STREAMS");
2513 if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2514 DEBUG("\tNO_PACK_STREAMS");
2516 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2517 DEBUG("\tFILE_DESCRIPTOR");
2519 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2520 DEBUG("\tNO_METADATA");
2522 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2523 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2525 if (num_threads == 0)
2526 DEBUG("Number of threads: autodetect");
2528 DEBUG("Number of threads: %u", num_threads);
2529 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2530 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2531 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2532 "specified" : "generate new"));
2534 /* Internally, this is always called with a valid part number and total
2536 wimlib_assert(total_parts >= 1);
2537 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2539 /* A valid image (or all images) must be specified. */
2540 if (image != WIMLIB_ALL_IMAGES &&
2541 (image < 1 || image > wim->hdr.image_count))
2542 return WIMLIB_ERR_INVALID_IMAGE;
2544 /* If we need to write metadata resources, make sure the ::WIMStruct has
2545 * the needed information attached (e.g. is not a resource-only WIM,
2546 * such as a non-first part of a split WIM). */
2547 if (!wim_has_metadata(wim) &&
2548 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2549 return WIMLIB_ERR_METADATA_NOT_FOUND;
2551 /* Check for contradictory flags. */
2552 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2553 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2554 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2555 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2556 return WIMLIB_ERR_INVALID_PARAM;
2558 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2559 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2560 == (WIMLIB_WRITE_FLAG_PIPABLE |
2561 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2562 return WIMLIB_ERR_INVALID_PARAM;
2564 if ((write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2565 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2566 == (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2567 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2568 return WIMLIB_ERR_INVALID_PARAM;
2570 /* Save previous header, then start initializing the new one. */
2571 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2573 /* Set default integrity, pipable, and packed stream flags. */
2574 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2575 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2576 if (wim_is_pipable(wim)) {
2577 DEBUG("WIM is pipable; default to PIPABLE.");
2578 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2581 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2582 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2583 if (wim_has_integrity_table(wim)) {
2584 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2585 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2588 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2589 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2590 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS) {
2591 DEBUG("WIM version 3584; default to PACK_STREAMS.");
2592 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2595 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2596 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2597 == (WIMLIB_WRITE_FLAG_PIPABLE |
2598 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2600 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2601 return WIMLIB_ERR_INVALID_PARAM;
2604 /* Set appropriate magic number. */
2605 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2606 wim->hdr.magic = PWM_MAGIC;
2608 wim->hdr.magic = WIM_MAGIC;
2610 /* Set appropriate version number. */
2611 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2612 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2614 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2616 /* Clear header flags that will be set automatically. */
2617 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2618 WIM_HDR_FLAG_RESOURCE_ONLY |
2619 WIM_HDR_FLAG_SPANNED |
2620 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2622 /* Set SPANNED header flag if writing part of a split WIM. */
2623 if (total_parts != 1)
2624 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2626 /* Set part number and total parts of split WIM. This will be 1 and 1
2627 * if the WIM is standalone. */
2628 wim->hdr.part_number = part_number;
2629 wim->hdr.total_parts = total_parts;
2631 /* Set compression type if different. */
2632 if (wim->compression_type != wim->out_compression_type) {
2633 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2634 wimlib_assert(ret == 0);
2637 /* Set chunk size if different. */
2638 wim->hdr.chunk_size = wim->out_chunk_size;
2640 /* Use GUID if specified; otherwise generate a new one. */
2642 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2643 else if (!wim->guid_set_explicitly)
2644 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2646 /* Clear references to resources that have not been written yet. */
2647 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2648 zero_reshdr(&wim->hdr.xml_data_reshdr);
2649 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2650 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2652 /* Set image count and boot index correctly for single image writes. */
2653 if (image != WIMLIB_ALL_IMAGES) {
2654 wim->hdr.image_count = 1;
2655 if (wim->hdr.boot_idx == image)
2656 wim->hdr.boot_idx = 1;
2658 wim->hdr.boot_idx = 0;
2661 /* Split WIMs can't be bootable. */
2662 if (total_parts != 1)
2663 wim->hdr.boot_idx = 0;
2665 /* Initialize output file descriptor. */
2666 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2667 /* File descriptor was explicitly provided. Return error if
2668 * file descriptor is not seekable, unless writing a pipable WIM
2670 wim->out_fd.fd = *(const int*)path_or_fd;
2671 wim->out_fd.offset = 0;
2672 if (!filedes_is_seekable(&wim->out_fd)) {
2673 ret = WIMLIB_ERR_INVALID_PARAM;
2674 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2675 goto out_restore_hdr;
2676 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2677 ERROR("Can't include integrity check when "
2678 "writing pipable WIM to pipe!");
2679 goto out_restore_hdr;
2684 /* Filename of WIM to write was provided; open file descriptor
2686 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2687 O_TRUNC | O_CREAT | O_RDWR);
2689 goto out_restore_hdr;
2692 /* Write initial header. This is merely a "dummy" header since it
2693 * doesn't have all the information yet, so it will be overwritten later
2694 * (unless writing a pipable WIM). */
2695 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2696 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2697 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2698 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2700 goto out_restore_hdr;
2702 /* Write metadata resources and streams. */
2703 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2704 /* Default case: create a normal (non-pipable) WIM. */
2705 ret = write_wim_streams(wim, image, write_flags, num_threads,
2706 progress_func, stream_list_override,
2707 &lookup_table_list);
2709 goto out_restore_hdr;
2711 ret = write_wim_metadata_resources(wim, image, write_flags,
2714 goto out_restore_hdr;
2716 /* Non-default case: create pipable WIM. */
2717 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2718 progress_func, stream_list_override,
2719 &lookup_table_list);
2721 goto out_restore_hdr;
2722 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2726 /* Write lookup table, XML data, and (optional) integrity table. */
2727 ret = finish_write(wim, image, write_flags, progress_func,
2728 &lookup_table_list);
2730 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2731 (void)close_wim_writable(wim, write_flags);
2732 DEBUG("ret=%d", ret);
2736 /* Write a standalone WIM to a file or file descriptor. */
2738 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2739 int image, int write_flags, unsigned num_threads,
2740 wimlib_progress_func_t progress_func)
2742 return write_wim_part(wim, path_or_fd, image, write_flags,
2743 num_threads, progress_func, 1, 1, NULL, NULL);
2746 /* API function documented in wimlib.h */
2748 wimlib_write(WIMStruct *wim, const tchar *path,
2749 int image, int write_flags, unsigned num_threads,
2750 wimlib_progress_func_t progress_func)
2753 return WIMLIB_ERR_INVALID_PARAM;
2755 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2757 return write_standalone_wim(wim, path, image, write_flags,
2758 num_threads, progress_func);
2761 /* API function documented in wimlib.h */
2763 wimlib_write_to_fd(WIMStruct *wim, int fd,
2764 int image, int write_flags, unsigned num_threads,
2765 wimlib_progress_func_t progress_func)
2768 return WIMLIB_ERR_INVALID_PARAM;
2770 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2771 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2773 return write_standalone_wim(wim, &fd, image, write_flags,
2774 num_threads, progress_func);
2778 any_images_modified(WIMStruct *wim)
2780 for (int i = 0; i < wim->hdr.image_count; i++)
2781 if (wim->image_metadata[i]->modified)
2787 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2789 const WIMStruct *wim = _wim;
2790 off_t end_offset = *(const off_t*)wim->private;
2792 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2793 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2794 return WIMLIB_ERR_RESOURCE_ORDER;
2798 /* Make sure no file or metadata resources are located after the XML data (or
2799 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2800 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2802 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2807 wim->private = &end_offset;
2808 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2812 for (i = 0; i < wim->hdr.image_count; i++) {
2813 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2821 * Overwrite a WIM, possibly appending streams to it.
2823 * A WIM looks like (or is supposed to look like) the following:
2825 * Header (212 bytes)
2826 * Streams and metadata resources (variable size)
2827 * Lookup table (variable size)
2828 * XML data (variable size)
2829 * Integrity table (optional) (variable size)
2831 * If we are not adding any streams or metadata resources, the lookup table is
2832 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2833 * header. This operation is potentially unsafe if the program is abruptly
2834 * terminated while the XML data or integrity table are being overwritten, but
2835 * before the new header has been written. To partially alleviate this problem,
2836 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2837 * finish_write() to cause a temporary WIM header to be written after the XML
2838 * data has been written. This may prevent the WIM from becoming corrupted if
2839 * the program is terminated while the integrity table is being calculated (but
2840 * no guarantees, due to write re-ordering...).
2842 * If we are adding new streams or images (metadata resources), the lookup table
2843 * needs to be changed, and those streams need to be written. In this case, we
2844 * try to perform a safe update of the WIM file by writing the streams *after*
2845 * the end of the previous WIM, then writing the new lookup table, XML data, and
2846 * (optionally) integrity table following the new streams. This will produce a
2847 * layout like the following:
2849 * Header (212 bytes)
2850 * (OLD) Streams and metadata resources (variable size)
2851 * (OLD) Lookup table (variable size)
2852 * (OLD) XML data (variable size)
2853 * (OLD) Integrity table (optional) (variable size)
2854 * (NEW) Streams and metadata resources (variable size)
2855 * (NEW) Lookup table (variable size)
2856 * (NEW) XML data (variable size)
2857 * (NEW) Integrity table (optional) (variable size)
2859 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2860 * the header is overwritten to point to the new lookup table, XML data, and
2861 * integrity table, to produce the following layout:
2863 * Header (212 bytes)
2864 * Streams and metadata resources (variable size)
2865 * Nothing (variable size)
2866 * More Streams and metadata resources (variable size)
2867 * Lookup table (variable size)
2868 * XML data (variable size)
2869 * Integrity table (optional) (variable size)
2871 * This method allows an image to be appended to a large WIM very quickly, and
2872 * is is crash-safe except in the case of write re-ordering, but the
2873 * disadvantage is that a small hole is left in the WIM where the old lookup
2874 * table, xml data, and integrity table were. (These usually only take up a
2875 * small amount of space compared to the streams, however.)
2878 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2879 unsigned num_threads,
2880 wimlib_progress_func_t progress_func)
2884 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2885 struct wim_header hdr_save;
2886 struct list_head stream_list;
2887 struct list_head lookup_table_list;
2888 struct filter_context filter_ctx;
2890 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2892 /* Save original header so it can be restored in case of error */
2893 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2895 /* Set default integrity flag. */
2896 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2897 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2898 if (wim_has_integrity_table(wim))
2899 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2901 /* Set default packed flag. */
2902 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2903 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2906 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
2907 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2909 /* wimlib allows multiple packs in a single WIM, but they don't
2910 * seem to be compatible with WIMGAPI. Write new streams
2912 } else if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) {
2913 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2916 /* Set additional flags for overwrite. */
2917 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2918 WIMLIB_WRITE_FLAG_STREAMS_OK;
2920 /* Make sure that the integrity table (if present) is after the XML
2921 * data, and that there are no stream resources, metadata resources, or
2922 * lookup tables after the XML data. Otherwise, these data would be
2924 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2925 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2926 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2927 wim->hdr.lookup_table_reshdr.size_in_wim;
2928 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2929 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2930 WARNING("Didn't expect the integrity table to be before the XML data");
2931 ret = WIMLIB_ERR_RESOURCE_ORDER;
2932 goto out_restore_memory_hdr;
2935 if (old_lookup_table_end > old_xml_begin) {
2936 WARNING("Didn't expect the lookup table to be after the XML data");
2937 ret = WIMLIB_ERR_RESOURCE_ORDER;
2938 goto out_restore_memory_hdr;
2941 /* Set @old_wim_end, which indicates the point beyond which we don't
2942 * allow any file and metadata resources to appear without returning
2943 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2944 * overwrite these resources). */
2945 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2946 /* If no images have been modified and no images have been
2947 * deleted, a new lookup table does not need to be written. We
2948 * shall write the new XML data and optional integrity table
2949 * immediately after the lookup table. Note that this may
2950 * overwrite an existing integrity table. */
2951 DEBUG("Skipping writing lookup table "
2952 "(no images modified or deleted)");
2953 old_wim_end = old_lookup_table_end;
2954 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2955 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2956 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2957 /* Old WIM has an integrity table; begin writing new streams
2959 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2960 wim->hdr.integrity_table_reshdr.size_in_wim;
2962 /* No existing integrity table; begin writing new streams after
2963 * the old XML data. */
2964 old_wim_end = old_xml_end;
2967 ret = check_resource_offsets(wim, old_wim_end);
2969 goto out_restore_memory_hdr;
2971 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2972 &stream_list, &lookup_table_list,
2975 goto out_restore_memory_hdr;
2977 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2979 goto out_restore_memory_hdr;
2981 ret = lock_wim(wim, wim->out_fd.fd);
2985 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2986 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2987 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2989 ERROR_WITH_ERRNO("Error updating WIM header flags");
2990 goto out_unlock_wim;
2993 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2994 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2995 ret = WIMLIB_ERR_WRITE;
2996 goto out_restore_physical_hdr;
2999 ret = write_stream_list(&stream_list,
3001 write_flags_to_resource_flags(write_flags),
3002 wim->compression_type,
3011 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3012 write_flags, progress_func);
3016 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3017 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3018 progress_func, &lookup_table_list);
3022 wim->wim_locked = 0;
3026 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3027 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3028 wim->filename, old_wim_end);
3029 /* Return value of ftruncate() is ignored because this is
3030 * already an error path. */
3031 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3033 out_restore_physical_hdr:
3034 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3036 wim->wim_locked = 0;
3038 (void)close_wim_writable(wim, write_flags);
3039 out_restore_memory_hdr:
3040 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3045 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3046 unsigned num_threads,
3047 wimlib_progress_func_t progress_func)
3049 size_t wim_name_len;
3052 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3054 /* Write the WIM to a temporary file in the same directory as the
3056 wim_name_len = tstrlen(wim->filename);
3057 tchar tmpfile[wim_name_len + 10];
3058 tmemcpy(tmpfile, wim->filename, wim_name_len);
3059 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3060 tmpfile[wim_name_len + 9] = T('\0');
3062 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3063 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3064 num_threads, progress_func);
3072 /* Rename the new WIM file to the original WIM file. Note: on Windows
3073 * this actually calls win32_rename_replacement(), not _wrename(), so
3074 * that removing the existing destination file can be handled. */
3075 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3076 ret = trename(tmpfile, wim->filename);
3078 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3079 tmpfile, wim->filename);
3086 return WIMLIB_ERR_RENAME;
3089 if (progress_func) {
3090 union wimlib_progress_info progress;
3091 progress.rename.from = tmpfile;
3092 progress.rename.to = wim->filename;
3093 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3098 /* Determine if the specified WIM file may be updated by appending in-place
3099 * rather than writing and replacing it with an entirely new file. */
3101 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3103 /* REBUILD flag forces full rebuild. */
3104 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3107 /* Deletions cause full rebuild by default. */
3108 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3111 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3112 * turned into a pipable WIM in-place. */
3113 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3116 /* wimlib allows multiple packs in a single WIM, but they don't seem to
3117 * be compatible with WIMGAPI, so force all streams to be repacked if
3118 * the WIM already may have contained a pack and PACK_STREAMS was
3120 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3121 wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3124 /* The default compression type and compression chunk size selected for
3125 * the output WIM must be the same as those currently used for the WIM.
3127 if (wim->compression_type != wim->out_compression_type)
3129 if (wim->chunk_size != wim->out_chunk_size)
3135 /* API function documented in wimlib.h */
3137 wimlib_overwrite(WIMStruct *wim, int write_flags,
3138 unsigned num_threads,
3139 wimlib_progress_func_t progress_func)
3144 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3146 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3147 return WIMLIB_ERR_INVALID_PARAM;
3150 return WIMLIB_ERR_NO_FILENAME;
3152 orig_hdr_flags = wim->hdr.flags;
3153 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3154 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3155 ret = can_modify_wim(wim);
3156 wim->hdr.flags = orig_hdr_flags;
3160 if (can_overwrite_wim_inplace(wim, write_flags)) {
3161 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3163 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3165 WARNING("Falling back to re-building entire WIM");
3167 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,