4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/compress_chunks.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/integrity.h"
43 #include "wimlib/lookup_table.h"
44 #include "wimlib/metadata.h"
45 #include "wimlib/resource.h"
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");
273 seek_and_truncate(struct filedes *out_fd, off_t offset)
275 if (filedes_seek(out_fd, offset) == -1 ||
276 ftruncate(out_fd->fd, offset))
278 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
279 return WIMLIB_ERR_WRITE;
285 struct write_streams_progress_data {
286 wimlib_progress_func_t progress_func;
287 union wimlib_progress_info progress;
288 uint64_t next_progress;
289 WIMStruct *prev_wim_part;
293 do_write_streams_progress(struct write_streams_progress_data *progress_data,
296 struct wim_lookup_table_entry *cur_stream)
298 union wimlib_progress_info *progress = &progress_data->progress;
302 progress->write_streams.total_bytes -= size;
303 if (progress_data->next_progress != ~(uint64_t)0 &&
304 progress_data->next_progress > progress->write_streams.total_bytes)
306 progress_data->next_progress = progress->write_streams.total_bytes;
309 progress->write_streams.completed_bytes += size;
311 new_wim_part = false;
312 if (cur_stream->resource_location == RESOURCE_IN_WIM &&
313 cur_stream->rspec->wim != progress_data->prev_wim_part)
315 if (progress_data->prev_wim_part) {
317 progress->write_streams.completed_parts++;
319 progress_data->prev_wim_part = cur_stream->rspec->wim;
321 progress->write_streams.completed_streams++;
322 if (progress_data->progress_func
323 && (progress->write_streams.completed_bytes >= progress_data->next_progress
326 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
328 if (progress_data->next_progress == progress->write_streams.total_bytes) {
329 progress_data->next_progress = ~(uint64_t)0;
331 progress_data->next_progress =
332 min(progress->write_streams.total_bytes,
333 progress->write_streams.completed_bytes +
334 progress->write_streams.total_bytes / 100);
339 struct write_streams_ctx {
340 /* File descriptor the streams are being written to. */
341 struct filedes *out_fd;
343 /* Lookup table for the WIMStruct on whose behalf the streams are being
345 struct wim_lookup_table *lookup_table;
347 /* Compression format to use. */
350 /* Maximum uncompressed chunk size in compressed resources to use. */
353 /* Flags that affect how the streams will be written. */
354 int write_resource_flags;
356 /* Data used for issuing WRITE_STREAMS progress. */
357 struct write_streams_progress_data progress_data;
359 struct filter_context *filter_ctx;
361 /* Upper bound on the total number of bytes that need to be compressed.
363 u64 num_bytes_to_compress;
365 /* Pointer to the chunk_compressor implementation being used for
366 * compressing chunks of data, or NULL if chunks are being written
368 struct chunk_compressor *compressor;
370 /* Buffer for dividing the read data into chunks of size
371 * @out_chunk_size. */
374 /* Number of bytes in @chunk_buf that are currently filled. */
375 size_t chunk_buf_filled;
377 /* List of streams that currently have chunks being compressed. */
378 struct list_head pending_streams;
380 /* Set to true if the stream currently being read was a duplicate, and
381 * therefore the corresponding stream entry needs to be freed once the
382 * read finishes. (In this case we add the duplicate entry to
383 * pending_streams rather than the entry being read.) */
384 bool stream_was_duplicate;
386 /* Current uncompressed offset in the resource being read. */
387 u64 cur_read_res_offset;
389 /* Uncompressed size of the resource currently being read. */
390 u64 cur_read_res_size;
392 /* Current uncompressed offset in the resource being written. */
393 u64 cur_write_res_offset;
395 /* Uncompressed size of resource currently being written. */
396 u64 cur_write_res_size;
398 /* Array that is filled in with compressed chunk sizes as a resource is
402 /* Index of next entry in @chunk_csizes to fill in. */
405 /* Number of entries in @chunk_csizes currently allocated. */
406 size_t num_alloc_chunks;
408 /* Offset in the output file of the start of the chunks of the resource
409 * currently being written. */
410 u64 chunks_start_offset;
414 get_chunk_entry_size(u64 res_size, int write_resource_flags)
416 if (res_size <= UINT32_MAX ||
417 (write_resource_flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
423 /* Reserve space for the chunk table and prepare to accumulate the chunk table
426 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
428 u64 expected_num_chunks;
429 u64 expected_num_chunk_entries;
433 /* Calculate the number of chunks and chunk entries that should be
434 * needed for the resource. These normally will be the final values,
435 * but in PACKED_STREAMS mode some of the streams we're planning to
436 * write into the resource may be duplicates, and therefore discarded,
437 * potentially decreasing the number of chunk entries needed. */
438 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
439 expected_num_chunk_entries = expected_num_chunks;
440 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
441 expected_num_chunk_entries--;
443 /* Make sure the chunk_csizes array is long enough to store the
444 * compressed size of each chunk. */
445 if (expected_num_chunks > ctx->num_alloc_chunks) {
446 u64 new_length = expected_num_chunks + 50;
448 if ((size_t)new_length != new_length) {
449 ERROR("Resource size too large (%"PRIu64" bytes!",
451 return WIMLIB_ERR_NOMEM;
454 FREE(ctx->chunk_csizes);
455 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
456 if (ctx->chunk_csizes == NULL) {
457 ctx->num_alloc_chunks = 0;
458 return WIMLIB_ERR_NOMEM;
460 ctx->num_alloc_chunks = new_length;
463 ctx->chunk_index = 0;
465 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
466 /* Reserve space for the chunk table in the output file. In the
467 * case of packed resources this reserves the upper bound for
468 * the needed space, not necessarily the exact space which will
469 * prove to be needed. At this point, we just use @chunk_csizes
470 * for a buffer of 0's because the actual compressed chunk sizes
472 reserve_size = expected_num_chunk_entries *
473 get_chunk_entry_size(res_expected_size,
474 ctx->write_resource_flags);
475 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
476 reserve_size += sizeof(struct alt_chunk_table_header_disk);
477 memset(ctx->chunk_csizes, 0, reserve_size);
478 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
486 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
490 wimlib_assert(res_expected_size != 0);
492 if (ctx->compressor != NULL) {
493 ret = begin_chunk_table(ctx, res_expected_size);
498 /* Output file descriptor is now positioned at the offset at which to
499 * write the first chunk of the resource. */
500 ctx->chunks_start_offset = ctx->out_fd->offset;
501 ctx->cur_write_res_offset = 0;
502 ctx->cur_write_res_size = res_expected_size;
507 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
508 u64 *res_start_offset_ret, u64 *res_store_size_ret)
510 size_t actual_num_chunks;
511 size_t actual_num_chunk_entries;
512 size_t chunk_entry_size;
515 actual_num_chunks = ctx->chunk_index;
516 actual_num_chunk_entries = actual_num_chunks;
517 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
518 actual_num_chunk_entries--;
520 chunk_entry_size = get_chunk_entry_size(res_actual_size,
521 ctx->write_resource_flags);
523 typedef le64 __attribute__((may_alias)) aliased_le64_t;
524 typedef le32 __attribute__((may_alias)) aliased_le32_t;
526 if (chunk_entry_size == 4) {
527 aliased_le32_t *entries = (aliased_le32_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_le32(ctx->chunk_csizes[i]);
533 u32 offset = ctx->chunk_csizes[0];
534 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
535 u32 next_size = ctx->chunk_csizes[i + 1];
536 entries[i] = cpu_to_le32(offset);
541 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
543 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
544 for (size_t i = 0; i < actual_num_chunk_entries; i++)
545 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
547 u64 offset = ctx->chunk_csizes[0];
548 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
549 u64 next_size = ctx->chunk_csizes[i + 1];
550 entries[i] = cpu_to_le64(offset);
556 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
557 u64 res_start_offset;
560 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
561 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
564 res_end_offset = ctx->out_fd->offset;
565 res_start_offset = ctx->chunks_start_offset;
567 res_end_offset = ctx->out_fd->offset;
569 u64 chunk_table_offset;
571 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
573 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
574 struct alt_chunk_table_header_disk hdr;
576 hdr.res_usize = cpu_to_le64(res_actual_size);
577 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
578 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
580 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
581 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
582 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
584 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
585 chunk_table_offset - sizeof(hdr));
588 res_start_offset = chunk_table_offset - sizeof(hdr);
590 res_start_offset = chunk_table_offset;
593 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
594 chunk_table_size, chunk_table_offset);
599 *res_start_offset_ret = res_start_offset;
600 *res_store_size_ret = res_end_offset - res_start_offset;
605 ERROR_WITH_ERRNO("Write error");
609 /* Finish writing a WIM resource by writing or updating the chunk table (if not
610 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
612 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
616 u64 res_uncompressed_size;
617 u64 res_offset_in_wim;
619 wimlib_assert(ctx->cur_write_res_size == ctx->cur_write_res_offset);
620 res_uncompressed_size = ctx->cur_write_res_size;
622 if (ctx->compressor) {
623 ret = end_chunk_table(ctx, res_uncompressed_size,
624 &res_offset_in_wim, &res_size_in_wim);
628 res_offset_in_wim = ctx->chunks_start_offset;
629 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
631 out_reshdr->uncompressed_size = res_uncompressed_size;
632 out_reshdr->size_in_wim = res_size_in_wim;
633 out_reshdr->offset_in_wim = res_offset_in_wim;
634 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
635 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
639 /* Begin processing a stream for writing. */
641 write_stream_begin_read(struct wim_lookup_table_entry *lte,
642 bool is_partial_res, void *_ctx)
644 struct write_streams_ctx *ctx = _ctx;
647 wimlib_assert(lte->size > 0);
649 ctx->cur_read_res_offset = 0;
650 ctx->cur_read_res_size = lte->size;
652 /* As an optimization, we allow some streams to be "unhashed", meaning
653 * their SHA1 message digests are unknown. This is the case with
654 * streams that are added by scanning a directry tree with
655 * wimlib_add_image(), for example. Since WIM uses single-instance
656 * streams, we don't know whether such each such stream really need to
657 * written until it is actually checksummed, unless it has a unique
658 * size. In such cases we read and checksum the stream in this
659 * function, thereby advancing ahead of read_stream_list(), which will
660 * still provide the data again to write_stream_process_chunk(). This
661 * is okay because an unhashed stream cannot be in a WIM resource, which
662 * might be costly to decompress. */
663 ctx->stream_was_duplicate = false;
664 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
666 wimlib_assert(!is_partial_res);
668 struct wim_lookup_table_entry *lte_new;
670 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
673 if (lte_new != lte) {
674 /* Duplicate stream detected. */
676 if (lte_new->will_be_in_output_wim ||
677 stream_filtered(lte_new, ctx->filter_ctx))
679 /* The duplicate stream is already being
680 * included in the output WIM, or it would be
681 * filtered out if it had been. Skip writing
682 * this stream (and reading it again) entirely,
683 * passing its output reference count to the
684 * duplicate stream in the former case. */
685 DEBUG("Discarding duplicate stream of "
686 "length %"PRIu64, lte->size);
687 do_write_streams_progress(&ctx->progress_data,
688 lte->size, true, lte);
689 list_del(<e->write_streams_list);
690 list_del(<e->lookup_table_list);
691 if (lte_new->will_be_in_output_wim)
692 lte_new->out_refcnt += lte->out_refcnt;
693 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
694 ctx->cur_write_res_size -= lte->size;
695 free_lookup_table_entry(lte);
696 return BEGIN_STREAM_STATUS_SKIP_STREAM;
698 /* The duplicate stream can validly be written,
699 * but was not marked as such. Discard the
700 * current stream entry and use the duplicate,
701 * but actually freeing the current entry must
702 * wait until read_stream_list() has finished
703 * reading its data. */
704 DEBUG("Stream duplicate, but not already "
705 "selected for writing.");
706 list_replace(<e->write_streams_list,
707 <e_new->write_streams_list);
708 list_replace(<e->lookup_table_list,
709 <e_new->lookup_table_list);
710 lte_new->out_refcnt = lte->out_refcnt;
711 lte_new->will_be_in_output_wim = 1;
712 ctx->stream_was_duplicate = true;
717 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
721 /* Write the next chunk of (typically compressed) data to the output WIM,
722 * handling the writing of the chunk table. */
724 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
725 size_t csize, size_t usize)
729 struct wim_lookup_table_entry *lte;
731 lte = list_entry(ctx->pending_streams.next,
732 struct wim_lookup_table_entry, write_streams_list);
734 if (ctx->cur_write_res_offset == 0 &&
735 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
737 /* Starting to write a new stream in non-packed mode. */
739 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
740 int additional_reshdr_flags = 0;
741 if (ctx->compressor != NULL)
742 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
744 DEBUG("Writing pipable WIM stream header "
745 "(offset=%"PRIu64")", ctx->out_fd->offset);
747 ret = write_pwm_stream_header(lte, ctx->out_fd,
748 additional_reshdr_flags);
753 ret = begin_write_resource(ctx, lte->size);
758 if (ctx->compressor != NULL) {
759 /* Record the compresed chunk size. */
760 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
761 ctx->chunk_csizes[ctx->chunk_index++] = csize;
763 /* If writing a pipable WIM, before the chunk data write a chunk
764 * header that provides the compressed chunk size. */
765 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
766 struct pwm_chunk_hdr chunk_hdr = {
767 .compressed_size = cpu_to_le32(csize),
769 ret = full_write(ctx->out_fd, &chunk_hdr,
776 /* Write the chunk data. */
777 ret = full_write(ctx->out_fd, cchunk, csize);
781 ctx->cur_write_res_offset += usize;
783 do_write_streams_progress(&ctx->progress_data,
786 if (ctx->cur_write_res_offset == ctx->cur_write_res_size &&
787 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
789 struct wim_lookup_table_entry *lte;
791 lte = list_entry(ctx->pending_streams.next,
792 struct wim_lookup_table_entry, write_streams_list);
793 wimlib_assert(ctx->cur_write_res_offset == lte->size);
795 /* Finished writing a stream in non-packed mode. */
797 ret = end_write_resource(ctx, <e->out_reshdr);
801 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
803 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
804 if (ctx->compressor != NULL)
805 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
807 list_del(<e->write_streams_list);
808 ctx->cur_write_res_offset = 0;
814 ERROR_WITH_ERRNO("Write error");
819 submit_chunk_for_compression(struct write_streams_ctx *ctx,
820 const void *chunk, size_t size)
822 /* While we are unable to submit the chunk for compression (due to too
823 * many chunks already outstanding), retrieve and write the next
824 * compressed chunk. */
825 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
832 bret = ctx->compressor->get_chunk(ctx->compressor,
833 &cchunk, &csize, &usize);
837 ret = write_chunk(ctx, cchunk, csize, usize);
844 /* Process the next chunk of data to be written to a WIM resource. */
846 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
848 struct write_streams_ctx *ctx = _ctx;
850 const u8 *chunkptr, *chunkend;
852 wimlib_assert(size != 0);
854 if (ctx->compressor == NULL) {
855 /* Write chunk uncompressed. */
856 ret = write_chunk(ctx, chunk, size, size);
859 ctx->cur_read_res_offset += size;
863 /* Submit the chunk for compression, but take into account that the
864 * @size the chunk was provided in may not correspond to the
865 * @out_chunk_size being used for compression. */
867 chunkend = chunkptr + size;
869 const u8 *resized_chunk;
870 size_t needed_chunk_size;
872 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
873 needed_chunk_size = ctx->out_chunk_size;
875 u64 res_bytes_remaining;
877 res_bytes_remaining = ctx->cur_read_res_size -
878 ctx->cur_read_res_offset;
879 needed_chunk_size = min(ctx->out_chunk_size,
880 ctx->chunk_buf_filled +
881 res_bytes_remaining);
884 if (ctx->chunk_buf_filled == 0 &&
885 chunkend - chunkptr >= needed_chunk_size)
887 /* No intermediate buffering needed. */
888 resized_chunk = chunkptr;
889 chunkptr += needed_chunk_size;
890 ctx->cur_read_res_offset += needed_chunk_size;
892 /* Intermediate buffering needed. */
893 size_t bytes_consumed;
895 bytes_consumed = min(chunkend - chunkptr,
896 needed_chunk_size - ctx->chunk_buf_filled);
898 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
899 chunkptr, bytes_consumed);
901 resized_chunk = ctx->chunk_buf;
903 chunkptr += bytes_consumed;
904 ctx->cur_read_res_offset += bytes_consumed;
905 ctx->chunk_buf_filled += bytes_consumed;
906 if (ctx->chunk_buf_filled == needed_chunk_size) {
907 resized_chunk = ctx->chunk_buf;
908 ctx->chunk_buf_filled = 0;
915 ret = submit_chunk_for_compression(ctx, resized_chunk,
920 } while (chunkptr != chunkend);
924 /* Finish processing a stream for writing. It may not have been completely
925 * written yet, as the chunk_compressor implementation may still have chunks
926 * buffered or being compressed. */
928 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
930 struct write_streams_ctx *ctx = _ctx;
932 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
933 if (ctx->stream_was_duplicate) {
934 free_lookup_table_entry(lte);
935 } else if (lte->unhashed && ctx->lookup_table != NULL) {
936 list_del(<e->unhashed_list);
937 lookup_table_insert(ctx->lookup_table, lte);
943 /* Compute statistics about a list of streams that will be written.
945 * Assumes the streams are sorted such that all streams located in each distinct
946 * WIM (specified by WIMStruct) are together. */
948 compute_stream_list_stats(struct list_head *stream_list,
949 struct write_streams_ctx *ctx)
951 struct wim_lookup_table_entry *lte;
955 WIMStruct *prev_wim_part = NULL;
957 list_for_each_entry(lte, stream_list, write_streams_list) {
959 total_bytes += lte->size;
960 if (lte->resource_location == RESOURCE_IN_WIM) {
961 if (prev_wim_part != lte->rspec->wim) {
962 prev_wim_part = lte->rspec->wim;
967 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
968 ctx->progress_data.progress.write_streams.total_streams = num_streams;
969 ctx->progress_data.progress.write_streams.completed_bytes = 0;
970 ctx->progress_data.progress.write_streams.completed_streams = 0;
971 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
972 ctx->progress_data.progress.write_streams.total_parts = total_parts;
973 ctx->progress_data.progress.write_streams.completed_parts = 0;
974 ctx->progress_data.next_progress = 0;
975 ctx->progress_data.prev_wim_part = NULL;
978 /* Find streams in @stream_list that can be copied to the output WIM in raw form
979 * rather than compressed. Delete these streams from @stream_list, and move one
980 * per resource to @raw_copy_resources. Return the total uncompressed size of
981 * the streams that need to be compressed. */
983 find_raw_copy_resources(struct list_head *stream_list,
984 int write_resource_flags,
987 struct list_head *raw_copy_resources)
989 struct wim_lookup_table_entry *lte, *tmp;
990 u64 num_bytes_to_compress = 0;
992 INIT_LIST_HEAD(raw_copy_resources);
994 /* Initialize temporary raw_copy_ok flag. */
995 list_for_each_entry(lte, stream_list, write_streams_list)
996 if (lte->resource_location == RESOURCE_IN_WIM)
997 lte->rspec->raw_copy_ok = 0;
999 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1000 if (lte->resource_location == RESOURCE_IN_WIM &&
1001 lte->rspec->raw_copy_ok)
1003 list_del(<e->write_streams_list);
1004 } else if (can_raw_copy(lte, write_resource_flags,
1005 out_ctype, out_chunk_size))
1007 lte->rspec->raw_copy_ok = 1;
1008 list_move_tail(<e->write_streams_list,
1009 raw_copy_resources);
1011 num_bytes_to_compress += lte->size;
1015 return num_bytes_to_compress;
1018 /* Copy a raw compressed resource located in another WIM file to the WIM file
1021 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1022 struct filedes *out_fd)
1024 u64 cur_read_offset;
1025 u64 end_read_offset;
1026 u8 buf[BUFFER_SIZE];
1027 size_t bytes_to_read;
1029 struct filedes *in_fd;
1030 struct wim_lookup_table_entry *lte;
1031 u64 out_offset_in_wim;
1033 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1034 "uncompressed_size=%"PRIu64")",
1035 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1037 /* Copy the raw data. */
1038 cur_read_offset = in_rspec->offset_in_wim;
1039 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1041 out_offset_in_wim = out_fd->offset;
1043 if (in_rspec->is_pipable) {
1044 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1045 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1046 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1047 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1049 in_fd = &in_rspec->wim->in_fd;
1050 while (cur_read_offset != end_read_offset) {
1052 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1054 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1058 ret = full_write(out_fd, buf, bytes_to_read);
1062 cur_read_offset += bytes_to_read;
1065 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1066 if (lte->will_be_in_output_wim) {
1067 stream_set_out_reshdr_for_reuse(lte);
1068 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1069 lte->out_res_offset_in_wim = out_offset_in_wim;
1071 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1078 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1079 * file being written. */
1081 write_raw_copy_resources(struct list_head *raw_copy_resources,
1082 struct filedes *out_fd)
1084 struct wim_lookup_table_entry *lte;
1087 list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1088 ret = write_raw_copy_resource(lte->rspec, out_fd);
1095 /* Wait for and write all chunks pending in the compressor. */
1097 finish_remaining_chunks(struct write_streams_ctx *ctx)
1104 if (ctx->compressor == NULL)
1107 if (ctx->chunk_buf_filled != 0) {
1108 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1109 ctx->chunk_buf_filled);
1114 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1115 ret = write_chunk(ctx, cdata, csize, usize);
1123 remove_zero_length_streams(struct list_head *stream_list)
1125 struct wim_lookup_table_entry *lte, *tmp;
1127 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1128 wimlib_assert(lte->will_be_in_output_wim);
1129 if (lte->size == 0) {
1130 list_del(<e->write_streams_list);
1131 lte->out_reshdr.offset_in_wim = 0;
1132 lte->out_reshdr.size_in_wim = 0;
1133 lte->out_reshdr.uncompressed_size = 0;
1134 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1140 * Write a list of streams to the output WIM file.
1143 * The list of streams to write, specifies a list of `struct
1144 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1147 * The file descriptor, opened for writing, to which to write the streams.
1149 * @write_resource_flags
1150 * Flags to modify how the streams are written:
1152 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1153 * Force compression of all resources, even if they could otherwise
1154 * be re-used by caping the raw data, due to being located in a WIM
1155 * file with compatible compression parameters.
1157 * WRITE_RESOURCE_FLAG_PIPABLE:
1158 * Write the resources in the wimlib-specific pipable format, and
1159 * furthermore do so in such a way that no seeking backwards in
1160 * @out_fd will be performed (so it may be a pipe, contrary to the
1161 * default behavior).
1163 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1164 * Pack all the streams into a single resource rather than writing
1165 * them in separate resources. This format is only valid if the
1166 * WIM version number is WIM_VERSION_PACKED_STREAMS. This flag
1167 * currently may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1170 * Compression format to use to write the output streams, specified as one
1171 * of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1172 * WIMLIB_COMPRESSION_TYPE_INVALID but including
1173 * WIMLIB_COMPRESSION_TYPE_NONE.
1176 * Chunk size to use to write the streams. It must be a valid chunk size
1177 * for the specified compression format @out_ctype, unless @out_ctype is
1178 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1181 * Number of threads to use to compress data. If 0, a default number of
1182 * threads will be chosen. The number of threads still may be decreased
1183 * from the specified value if insufficient memory is detected.
1186 * If on-the-fly deduplication of unhashed streams is desired, this
1187 * parameter must be pointer to the lookup table for the WIMStruct on whose
1188 * behalf the streams are being written. Otherwise, this parameter can be
1192 * If on-the-fly deduplication of unhashed streams is desired, this
1193 * parameter can be a pointer to a context for stream filtering used to
1194 * detect whether the duplicate stream has been hard-filtered or not. If
1195 * no streams are hard-filtered or no streams are unhashed, this parameter
1199 * A location in which to allocate the pointer to the default LZX
1200 * compression context. This will only be used if @out_ctype is
1201 * WIMLIB_COMPRESSION_TYPE_LZX.
1204 * If non-NULL, a progress function that will be called periodically with
1205 * WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages. Note that on-the-fly
1206 * deduplication of unhashed streams may result in the total bytes provided
1207 * in the progress data to decrease from one message to the next.
1209 * This function will write the streams in @stream_list to resources in
1210 * consecutive positions in the output WIM file, or to a single packed resource
1211 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1212 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1213 * each stream written will be updated to specify its location, size, and flags
1214 * in the output WIM. In the packed resource case,
1215 * WIM_RESHDR_FLAG_PACKED_STREAMS shall be set in the @flags field of the
1216 * @out_reshdr, and @out_res_offset_in_wim and @out_res_size_in_wim will also
1217 * be set to the offset and size, respectively, in the output WIM of the full
1218 * packed resource containing the corresponding stream.
1220 * Each of the streams to write may be in any location supported by the
1221 * resource-handling code (specifically, read_stream_list()), such as the
1222 * contents of external file that has been logically added to the output WIM, or
1223 * a stream in another WIM file that has been imported, or even stream in the
1224 * "same" WIM file of which a modified copy is being written. In the case that
1225 * a stream is already in a WIM file and uses compatible compression parameters,
1226 * by default this function will re-use the raw data instead of decompressing
1227 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1228 * specified in @write_resource_flags, this is not done.
1230 * As a further requirement, this function requires that the
1231 * @will_be_in_output_wim member be set on all streams in @stream_list as well
1232 * as any other streams not in @stream_list that will be in the output WIM file,
1233 * but not on any other streams in the output WIM's lookup table or sharing a
1234 * packed resource with a stream in @stream_list. Still furthermore, if
1235 * on-the-fly deduplication of streams is possible, then all streams in
1236 * @stream_list must also be linked by @lookup_table_list along with any other
1237 * streams that have @will_be_in_output_wim set.
1239 * This function handles on-the-fly deduplication of streams for which SHA1
1240 * message digests have not yet been calculated and it is therefore known
1241 * whether such streams are already in @stream_list or in the WIM's lookup table
1242 * at all. If @lookup_table is non-NULL, then each stream in @stream_list that
1243 * has @unhashed set but not @unique_size set is checksummed immediately before
1244 * it would otherwise be read for writing in order to determine if it is
1245 * identical to another stream already being written or one that would be
1246 * filtered out of the output WIM using stream_filtered() with the context
1247 * @filter_ctx. Each such duplicate stream will be removed from @stream_list, its
1248 * reference count transfered to the pre-existing duplicate stream, its memory
1249 * freed, and will not be written. Alternatively, if a stream in @stream_list
1250 * is a duplicate with any stream in @lookup_table that has not been marked for
1251 * writing or would not be hard-filtered, it is freed and the pre-existing
1252 * duplicate is written instead, taking ownership of the reference count and
1253 * slot in the @lookup_table_list.
1255 * Returns 0 if all streams were written successfully (or did not need to be
1256 * written); otherwise a non-zero error code.
1259 write_stream_list(struct list_head *stream_list,
1260 struct filedes *out_fd,
1261 int write_resource_flags,
1264 unsigned num_threads,
1265 struct wim_lookup_table *lookup_table,
1266 struct filter_context *filter_ctx,
1267 struct wimlib_lzx_context **comp_ctx,
1268 wimlib_progress_func_t progress_func)
1271 struct write_streams_ctx ctx;
1272 struct list_head raw_copy_resources;
1274 wimlib_assert((write_resource_flags &
1275 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1276 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1277 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1278 WRITE_RESOURCE_FLAG_PIPABLE));
1280 remove_zero_length_streams(stream_list);
1282 if (list_empty(stream_list)) {
1283 DEBUG("No streams to write.");
1287 memset(&ctx, 0, sizeof(ctx));
1289 /* Pre-sorting the streams is required for compute_stream_list_stats().
1290 * Afterwards, read_stream_list() need not sort them again. */
1291 ret = sort_stream_list_by_sequential_order(stream_list,
1292 offsetof(struct wim_lookup_table_entry,
1293 write_streams_list));
1297 ctx.out_fd = out_fd;
1298 ctx.lookup_table = lookup_table;
1299 ctx.out_ctype = out_ctype;
1300 ctx.out_chunk_size = out_chunk_size;
1301 ctx.write_resource_flags = write_resource_flags;
1302 ctx.filter_ctx = filter_ctx;
1304 if (out_chunk_size != 0) {
1305 if (out_chunk_size <= STACK_MAX) {
1306 ctx.chunk_buf = alloca(out_chunk_size);
1308 ctx.chunk_buf = MALLOC(out_chunk_size);
1309 if (ctx.chunk_buf == NULL) {
1310 ret = WIMLIB_ERR_NOMEM;
1311 goto out_destroy_context;
1315 ctx.chunk_buf_filled = 0;
1317 compute_stream_list_stats(stream_list, &ctx);
1319 ctx.progress_data.progress_func = progress_func;
1321 ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1322 write_resource_flags,
1325 &raw_copy_resources);
1327 DEBUG("Writing stream list "
1328 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1329 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1330 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1331 out_fd->offset, write_resource_flags,
1332 out_ctype, out_chunk_size, num_threads,
1333 ctx.progress_data.progress.write_streams.total_bytes,
1334 ctx.num_bytes_to_compress);
1336 if (ctx.num_bytes_to_compress == 0) {
1337 DEBUG("No compression needed; skipping to raw copy!");
1338 goto out_write_raw_copy_resources;
1341 /* Unless uncompressed output was required, allocate a chunk_compressor
1342 * to do compression. There are serial and parallel implementations of
1343 * the chunk_compressor interface. We default to parallel using the
1344 * specified number of threads, unless the upper bound on the number
1345 * bytes needing to be compressed is less 2000000 (heuristic value). */
1346 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1348 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZMS &&
1349 ctx.lookup_table != NULL) {
1350 WARNING("LZMS compression not implemented; data will "
1351 "actually be written uncompressed.");
1354 if (ctx.num_bytes_to_compress >= 2000000) {
1355 ret = new_parallel_chunk_compressor(out_ctype,
1360 DEBUG("Couldn't create parallel chunk compressor "
1361 "(status %d)", ret);
1365 if (ctx.compressor == NULL) {
1366 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1367 ret = wimlib_lzx_alloc_context(out_chunk_size,
1371 goto out_destroy_context;
1373 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1374 *comp_ctx, &ctx.compressor);
1376 goto out_destroy_context;
1381 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1383 ctx.progress_data.progress.write_streams.num_threads = 1;
1385 DEBUG("Actually using %u threads",
1386 ctx.progress_data.progress.write_streams.num_threads);
1388 INIT_LIST_HEAD(&ctx.pending_streams);
1390 if (ctx.progress_data.progress_func) {
1391 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1392 &ctx.progress_data.progress);
1395 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1396 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1398 goto out_destroy_context;
1401 /* Read the list of streams needing to be compressed, using the
1402 * specified callbacks to execute processing of the data. */
1404 struct read_stream_list_callbacks cbs = {
1405 .begin_stream = write_stream_begin_read,
1406 .begin_stream_ctx = &ctx,
1407 .consume_chunk = write_stream_process_chunk,
1408 .consume_chunk_ctx = &ctx,
1409 .end_stream = write_stream_end_read,
1410 .end_stream_ctx = &ctx,
1413 ret = read_stream_list(stream_list,
1414 offsetof(struct wim_lookup_table_entry, write_streams_list),
1416 STREAM_LIST_ALREADY_SORTED |
1417 VERIFY_STREAM_HASHES |
1418 COMPUTE_MISSING_STREAM_HASHES);
1421 goto out_destroy_context;
1423 ret = finish_remaining_chunks(&ctx);
1425 goto out_destroy_context;
1427 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1428 struct wim_reshdr reshdr;
1429 struct wim_lookup_table_entry *lte;
1432 ret = end_write_resource(&ctx, &reshdr);
1434 goto out_destroy_context;
1436 DEBUG("Ending packed resource: %lu %lu %lu.",
1437 reshdr.offset_in_wim,
1439 reshdr.uncompressed_size);
1442 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1443 lte->out_reshdr.size_in_wim = lte->size;
1444 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1445 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1446 lte->out_reshdr.uncompressed_size = 0;
1447 lte->out_reshdr.offset_in_wim = offset_in_res;
1448 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1449 lte->out_res_size_in_wim = reshdr.size_in_wim;
1450 /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1451 offset_in_res += lte->size;
1453 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1456 out_write_raw_copy_resources:
1457 /* Copy any compressed resources for which the raw data can be reused
1458 * without decompression. */
1459 ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd);
1461 out_destroy_context:
1462 if (out_chunk_size > STACK_MAX)
1463 FREE(ctx.chunk_buf);
1464 FREE(ctx.chunk_csizes);
1466 ctx.compressor->destroy(ctx.compressor);
1467 DEBUG("Done (ret=%d)", ret);
1472 write_wim_resource(struct wim_lookup_table_entry *lte,
1473 struct filedes *out_fd,
1476 int write_resource_flags,
1477 struct wimlib_lzx_context **comp_ctx)
1479 LIST_HEAD(stream_list);
1480 list_add(<e->write_streams_list, &stream_list);
1481 lte->will_be_in_output_wim = 1;
1482 return write_stream_list(&stream_list,
1484 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1495 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1496 int reshdr_flags, struct filedes *out_fd,
1499 struct wim_reshdr *out_reshdr,
1501 int write_resource_flags,
1502 struct wimlib_lzx_context **comp_ctx)
1505 struct wim_lookup_table_entry *lte;
1507 /* Set up a temporary lookup table entry to provide to
1508 * write_wim_resource(). */
1510 lte = new_lookup_table_entry();
1512 return WIMLIB_ERR_NOMEM;
1514 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1515 lte->attached_buffer = (void*)buf;
1516 lte->size = buf_size;
1517 lte->flags = reshdr_flags;
1519 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1520 sha1_buffer(buf, buf_size, lte->hash);
1526 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1527 write_resource_flags, comp_ctx);
1531 copy_reshdr(out_reshdr, <e->out_reshdr);
1534 copy_hash(hash, lte->hash);
1537 lte->resource_location = RESOURCE_NONEXISTENT;
1538 free_lookup_table_entry(lte);
1542 struct stream_size_table {
1543 struct hlist_head *array;
1549 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1551 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1552 if (tab->array == NULL)
1553 return WIMLIB_ERR_NOMEM;
1554 tab->num_entries = 0;
1555 tab->capacity = capacity;
1560 destroy_stream_size_table(struct stream_size_table *tab)
1566 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1568 struct stream_size_table *tab = _tab;
1570 struct wim_lookup_table_entry *same_size_lte;
1571 struct hlist_node *tmp;
1573 pos = hash_u64(lte->size) % tab->capacity;
1574 lte->unique_size = 1;
1575 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1576 if (same_size_lte->size == lte->size) {
1577 lte->unique_size = 0;
1578 same_size_lte->unique_size = 0;
1583 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1588 struct find_streams_ctx {
1591 struct list_head stream_list;
1592 struct stream_size_table stream_size_tab;
1596 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1597 struct list_head *stream_list, u32 nref)
1599 if (!lte->will_be_in_output_wim) {
1600 lte->out_refcnt = 0;
1601 list_add_tail(<e->write_streams_list, stream_list);
1602 lte->will_be_in_output_wim = 1;
1604 lte->out_refcnt += nref;
1608 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1611 struct list_head *stream_list = _stream_list;
1612 lte->will_be_in_output_wim = 0;
1613 reference_stream_for_write(lte, stream_list, lte->refcnt);
1618 inode_find_streams_to_reference(const struct wim_inode *inode,
1619 const struct wim_lookup_table *table,
1620 struct list_head *stream_list)
1622 struct wim_lookup_table_entry *lte;
1625 wimlib_assert(inode->i_nlink > 0);
1627 for (i = 0; i <= inode->i_num_ads; i++) {
1628 lte = inode_stream_lte(inode, i, table);
1630 reference_stream_for_write(lte, stream_list,
1632 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1633 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1639 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1641 lte->will_be_in_output_wim = 0;
1646 image_find_streams_to_reference(WIMStruct *wim)
1648 struct wim_image_metadata *imd;
1649 struct wim_inode *inode;
1650 struct wim_lookup_table_entry *lte;
1651 struct list_head *stream_list;
1654 imd = wim_get_current_image_metadata(wim);
1656 image_for_each_unhashed_stream(lte, imd)
1657 lte->will_be_in_output_wim = 0;
1659 stream_list = wim->private;
1660 image_for_each_inode(inode, imd) {
1661 ret = inode_find_streams_to_reference(inode,
1671 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1674 struct list_head *stream_list_ret)
1678 INIT_LIST_HEAD(stream_list_ret);
1680 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1681 (image == 1 && wim->hdr.image_count == 1)))
1683 /* Fast case: Assume that all streams are being written and
1684 * that the reference counts are correct. */
1685 struct wim_lookup_table_entry *lte;
1686 struct wim_image_metadata *imd;
1689 for_lookup_table_entry(wim->lookup_table,
1690 fully_reference_stream_for_write,
1693 for (i = 0; i < wim->hdr.image_count; i++) {
1694 imd = wim->image_metadata[i];
1695 image_for_each_unhashed_stream(lte, imd)
1696 fully_reference_stream_for_write(lte, stream_list_ret);
1699 /* Slow case: Walk through the images being written and
1700 * determine the streams referenced. */
1701 for_lookup_table_entry(wim->lookup_table,
1702 do_stream_set_not_in_output_wim, NULL);
1703 wim->private = stream_list_ret;
1704 ret = for_image(wim, image, image_find_streams_to_reference);
1712 struct insert_other_if_hard_filtered_ctx {
1713 struct stream_size_table *tab;
1714 struct filter_context *filter_ctx;
1718 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1720 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1722 if (!lte->will_be_in_output_wim &&
1723 stream_hard_filtered(lte, ctx->filter_ctx))
1724 stream_size_table_insert(lte, ctx->tab);
1729 determine_stream_size_uniquity(struct list_head *stream_list,
1730 struct wim_lookup_table *lt,
1731 struct filter_context *filter_ctx)
1734 struct stream_size_table tab;
1735 struct wim_lookup_table_entry *lte;
1737 ret = init_stream_size_table(&tab, lt->capacity);
1741 if (may_hard_filter_streams(filter_ctx)) {
1742 struct insert_other_if_hard_filtered_ctx ctx = {
1744 .filter_ctx = filter_ctx,
1746 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1749 list_for_each_entry(lte, stream_list, write_streams_list)
1750 stream_size_table_insert(lte, &tab);
1752 destroy_stream_size_table(&tab);
1757 filter_stream_list_for_write(struct list_head *stream_list,
1758 struct filter_context *filter_ctx)
1760 struct wim_lookup_table_entry *lte, *tmp;
1762 list_for_each_entry_safe(lte, tmp,
1763 stream_list, write_streams_list)
1765 int status = stream_filtered(lte, filter_ctx);
1772 /* Soft filtered. */
1774 /* Hard filtered. */
1775 lte->will_be_in_output_wim = 0;
1776 list_del(<e->lookup_table_list);
1778 list_del(<e->write_streams_list);
1784 * prepare_stream_list_for_write() -
1786 * Prepare the list of streams to write for writing a WIM containing the
1787 * specified image(s) with the specified write flags.
1790 * The WIMStruct on whose behalf the write is occurring.
1793 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1796 * WIMLIB_WRITE_FLAG_* flags for the write operation:
1798 * STREAMS_OK: For writes of all images, assume that all streams in the
1799 * lookup table of @wim and the per-image lists of unhashed streams should
1800 * be taken as-is, and image metadata should not be searched for
1801 * references. This does not exclude filtering with OVERWRITE and
1802 * SKIP_EXTERNAL_WIMS, below.
1804 * OVERWRITE: Streams already present in @wim shall not be returned in
1807 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
1808 * @wim, shall be be returned in neither @stream_list_ret nor
1809 * @lookup_table_list_ret.
1812 * List of streams, linked by write_streams_list, that need to be written
1813 * will be returned here.
1815 * Note that this function assumes that unhashed streams will be written;
1816 * it does not take into account that they may become duplicates when
1819 * @lookup_table_list_ret
1820 * List of streams, linked by lookup_table_list, that need to be included
1821 * in the WIM's lookup table will be returned here. This will be a
1822 * superset of the streams in @stream_list_ret.
1824 * This list will be a proper superset of @stream_list_ret if and only if
1825 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1826 * the streams that would otherwise need to be written were already located
1829 * All streams in this list will have @out_refcnt set to the number of
1830 * references to the stream in the output WIM. If
1831 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1832 * may be as low as 0.
1835 * A context for queries of stream filter status with stream_filtered() is
1836 * returned in this location.
1838 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1839 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1840 * lookup table of @wim not inserted into @lookup_table_list_ret.
1842 * Still furthermore, @unique_size will be set to 1 on all stream entries in
1843 * @stream_list_ret that have unique size among all stream entries in
1844 * @stream_list_ret and among all stream entries in the lookup table of @wim
1845 * that are ineligible for being written due to filtering.
1847 * Returns 0 on success; nonzero on read error, memory allocation error, or
1851 prepare_stream_list_for_write(WIMStruct *wim, int image,
1853 struct list_head *stream_list_ret,
1854 struct list_head *lookup_table_list_ret,
1855 struct filter_context *filter_ctx_ret)
1858 struct wim_lookup_table_entry *lte;
1860 filter_ctx_ret->write_flags = write_flags;
1861 filter_ctx_ret->wim = wim;
1863 ret = prepare_unfiltered_list_of_streams_in_output_wim(
1866 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1871 INIT_LIST_HEAD(lookup_table_list_ret);
1872 list_for_each_entry(lte, stream_list_ret, write_streams_list)
1873 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1875 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1880 if (may_filter_streams(filter_ctx_ret))
1881 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1887 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1888 unsigned num_threads,
1889 wimlib_progress_func_t progress_func,
1890 struct list_head *stream_list_override,
1891 struct list_head *lookup_table_list_ret)
1894 struct list_head _stream_list;
1895 struct list_head *stream_list;
1896 struct wim_lookup_table_entry *lte;
1897 struct filter_context _filter_ctx;
1898 struct filter_context *filter_ctx;
1900 if (stream_list_override == NULL) {
1901 /* Normal case: prepare stream list from image(s) being written.
1903 stream_list = &_stream_list;
1904 filter_ctx = &_filter_ctx;
1905 ret = prepare_stream_list_for_write(wim, image, write_flags,
1907 lookup_table_list_ret,
1912 /* Currently only as a result of wimlib_split() being called:
1913 * use stream list already explicitly provided. Use existing
1914 * reference counts. */
1915 stream_list = stream_list_override;
1917 INIT_LIST_HEAD(lookup_table_list_ret);
1918 list_for_each_entry(lte, stream_list, write_streams_list) {
1919 lte->out_refcnt = lte->refcnt;
1920 lte->will_be_in_output_wim = 1;
1921 lte->unique_size = 0;
1922 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
1926 return write_stream_list(stream_list,
1928 write_flags_to_resource_flags(write_flags),
1929 wim->out_compression_type,
1930 wim->out_chunk_size,
1939 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1940 wimlib_progress_func_t progress_func)
1945 int write_resource_flags;
1947 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1948 DEBUG("Not writing any metadata resources.");
1952 write_resource_flags = write_flags_to_resource_flags(write_flags);
1954 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
1956 DEBUG("Writing metadata resources (offset=%"PRIu64")",
1957 wim->out_fd.offset);
1960 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1962 if (image == WIMLIB_ALL_IMAGES) {
1964 end_image = wim->hdr.image_count;
1966 start_image = image;
1970 for (int i = start_image; i <= end_image; i++) {
1971 struct wim_image_metadata *imd;
1973 imd = wim->image_metadata[i - 1];
1974 /* Build a new metadata resource only if image was modified from
1975 * the original (or was newly added). Otherwise just copy the
1977 if (imd->modified) {
1978 DEBUG("Image %u was modified; building and writing new "
1979 "metadata resource", i);
1980 ret = write_metadata_resource(wim, i,
1981 write_resource_flags);
1982 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1983 DEBUG("Image %u was not modified; re-using existing "
1984 "metadata resource.", i);
1985 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
1988 DEBUG("Image %u was not modified; copying existing "
1989 "metadata resource.", i);
1990 ret = write_wim_resource(imd->metadata_lte,
1992 wim->out_compression_type,
1993 wim->out_chunk_size,
1994 write_resource_flags,
2001 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2006 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2009 DEBUG("Opening \"%"TS"\" for writing.", path);
2011 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2013 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2014 return WIMLIB_ERR_OPEN;
2016 filedes_init(&wim->out_fd, raw_fd);
2021 close_wim_writable(WIMStruct *wim, int write_flags)
2025 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2026 DEBUG("Closing WIM file.");
2027 if (filedes_valid(&wim->out_fd))
2028 if (filedes_close(&wim->out_fd))
2029 ret = WIMLIB_ERR_WRITE;
2031 filedes_invalidate(&wim->out_fd);
2036 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2038 const struct wim_lookup_table_entry *lte1, *lte2;
2040 lte1 = *(const struct wim_lookup_table_entry**)p1;
2041 lte2 = *(const struct wim_lookup_table_entry**)p2;
2043 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2044 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2045 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2046 return cmp_u64(lte1->out_res_offset_in_wim,
2047 lte2->out_res_offset_in_wim);
2052 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2055 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2056 lte2->out_reshdr.offset_in_wim);
2060 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2061 struct wim_reshdr *out_reshdr,
2062 struct list_head *lookup_table_list)
2066 /* Set output resource metadata for streams already present in WIM. */
2067 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2068 struct wim_lookup_table_entry *lte;
2069 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2071 if (lte->resource_location == RESOURCE_IN_WIM &&
2072 lte->rspec->wim == wim)
2074 stream_set_out_reshdr_for_reuse(lte);
2079 ret = sort_stream_list(lookup_table_list,
2080 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2081 cmp_streams_by_out_rspec);
2085 /* Add entries for metadata resources. */
2086 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2090 if (image == WIMLIB_ALL_IMAGES) {
2092 end_image = wim->hdr.image_count;
2094 start_image = image;
2098 /* Push metadata resource lookup table entries onto the front of
2099 * the list in reverse order, so that they're written in order.
2101 for (int i = end_image; i >= start_image; i--) {
2102 struct wim_lookup_table_entry *metadata_lte;
2104 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2105 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2106 metadata_lte->out_refcnt = 1;
2107 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2111 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2113 wim->hdr.part_number,
2115 write_flags_to_resource_flags(write_flags),
2122 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2123 * table, then overwrite the WIM header. By default, closes the WIM file
2124 * descriptor (@wim->out_fd) if successful.
2126 * write_flags is a bitwise OR of the following:
2128 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2129 * Include an integrity table.
2131 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2132 * fsync() the output file before closing it.
2134 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2135 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2136 * stream headers before the lookup table and XML data, and also
2137 * write the WIM header at the end instead of seeking to the
2138 * beginning. Can't be combined with
2139 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2141 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2142 * Don't write the lookup table.
2144 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2145 * When (if) writing the integrity table, re-use entries from the
2146 * existing integrity table, if possible.
2148 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2149 * After writing the XML data but before writing the integrity
2150 * table, write a temporary WIM header and flush the stream so that
2151 * the WIM is less likely to become corrupted upon abrupt program
2153 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2154 * Instead of overwriting the WIM header at the beginning of the
2155 * file, simply append it to the end of the file. (Used when
2157 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2158 * Do not close the file descriptor @wim->out_fd on either success
2160 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2161 * Use the existing <TOTALBYTES> stored in the in-memory XML
2162 * information, rather than setting it to the offset of the XML
2163 * data being written.
2166 finish_write(WIMStruct *wim, int image, int write_flags,
2167 wimlib_progress_func_t progress_func,
2168 struct list_head *lookup_table_list)
2172 int write_resource_flags;
2173 off_t old_lookup_table_end;
2174 off_t new_lookup_table_end;
2177 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2179 write_resource_flags = write_flags_to_resource_flags(write_flags);
2181 /* In the WIM header, there is room for the resource entry for a
2182 * metadata resource labeled as the "boot metadata". This entry should
2183 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2184 * it should be a copy of the resource entry for the image that is
2185 * marked as bootable. This is not well documented... */
2186 if (wim->hdr.boot_idx == 0) {
2187 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2189 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2190 &wim->image_metadata[
2191 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2194 /* Write lookup table. (Save old position first.) */
2195 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2196 wim->hdr.lookup_table_reshdr.size_in_wim;
2197 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2198 ret = write_wim_lookup_table(wim, image, write_flags,
2199 &wim->hdr.lookup_table_reshdr,
2205 /* Write XML data. */
2206 xml_totalbytes = wim->out_fd.offset;
2207 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2208 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2209 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2210 &wim->hdr.xml_data_reshdr,
2211 write_resource_flags);
2215 /* Write integrity table (optional). */
2216 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2217 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2218 struct wim_header checkpoint_hdr;
2219 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2220 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2221 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2222 ret = write_wim_header_at_offset(&checkpoint_hdr,
2228 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2229 old_lookup_table_end = 0;
2231 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2232 wim->hdr.lookup_table_reshdr.size_in_wim;
2234 ret = write_integrity_table(wim,
2235 new_lookup_table_end,
2236 old_lookup_table_end,
2241 /* No integrity table. */
2242 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2245 /* Now that all information in the WIM header has been determined, the
2246 * preliminary header written earlier can be overwritten, the header of
2247 * the existing WIM file can be overwritten, or the final header can be
2248 * written to the end of the pipable WIM. */
2249 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2251 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2252 hdr_offset = wim->out_fd.offset;
2253 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2254 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2258 /* Possibly sync file data to disk before closing. On POSIX systems, it
2259 * is necessary to do this before using rename() to overwrite an
2260 * existing file with a new file. Otherwise, data loss would occur if
2261 * the system is abruptly terminated when the metadata for the rename
2262 * operation has been written to disk, but the new file data has not.
2264 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2265 DEBUG("Syncing WIM file.");
2266 if (fsync(wim->out_fd.fd)) {
2267 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2268 return WIMLIB_ERR_WRITE;
2272 if (close_wim_writable(wim, write_flags)) {
2273 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2274 return WIMLIB_ERR_WRITE;
2280 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2282 lock_wim(WIMStruct *wim, int fd)
2285 if (fd != -1 && !wim->wim_locked) {
2286 ret = flock(fd, LOCK_EX | LOCK_NB);
2288 if (errno == EWOULDBLOCK) {
2289 ERROR("`%"TS"' is already being modified or has been "
2290 "mounted read-write\n"
2291 " by another process!", wim->filename);
2292 ret = WIMLIB_ERR_ALREADY_LOCKED;
2294 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2299 wim->wim_locked = 1;
2307 * write_pipable_wim():
2309 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2310 * capable of being applied from a pipe).
2312 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2313 * images can be applied from them sequentially when the file data is sent over
2314 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2315 * The modifications made to the WIM format for pipable WIMs are:
2317 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2318 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2319 * stops other software from trying to read the file as a normal WIM.
2321 * - The header at the beginning of the file does not contain all the normal
2322 * information; in particular it will have all 0's for the lookup table and
2323 * XML data resource entries. This is because this information cannot be
2324 * determined until the lookup table and XML data have been written.
2325 * Consequently, wimlib will write the full header at the very end of the
2326 * file. The header at the end, however, is only used when reading the WIM
2327 * from a seekable file (not a pipe).
2329 * - An extra copy of the XML data is placed directly after the header. This
2330 * allows image names and sizes to be determined at an appropriate time when
2331 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2332 * WIM is read from a seekable file (not a pipe).
2334 * - The format of resources, or streams, has been modified to allow them to be
2335 * used before the "lookup table" has been read. Each stream is prefixed with
2336 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2337 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2338 * uncompressed stream size, and flags that indicate whether the stream is
2339 * compressed. The data of uncompressed streams then follows literally, while
2340 * the data of compressed streams follows in a modified format. Compressed
2341 * streams do not begin with a chunk table, since the chunk table cannot be
2342 * written until all chunks have been compressed. Instead, each compressed
2343 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2344 * Furthermore, the chunk table is written at the end of the resource instead
2345 * of the start. Note: chunk offsets are given in the chunk table as if the
2346 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2347 * used if the WIM is being read from a seekable file (not a pipe).
2349 * - Metadata resources always come before other file resources (streams).
2350 * (This does not by itself constitute an incompatibility with normal WIMs,
2351 * since this is valid in normal WIMs.)
2353 * - At least up to the end of the file resources, all components must be packed
2354 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2355 * not by itself consititute an incompatibility with normal WIMs, since this
2356 * is valid in normal WIMs.)
2358 * Note: the lookup table, XML data, and header at the end are not used when
2359 * applying from a pipe. They exist to support functionality such as image
2360 * application and export when the WIM is *not* read from a pipe.
2362 * Layout of pipable WIM:
2364 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2365 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2366 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2368 * Layout of normal WIM:
2370 * +--------+-----------------------------+-------------------------+
2371 * | Header | File and metadata resources | Lookup table | XML data |
2372 * +--------+-----------------------------+-------------------------+
2374 * An optional integrity table can follow the final XML data in both normal and
2375 * pipable WIMs. However, due to implementation details, wimlib currently can
2376 * only include an integrity table in a pipable WIM when writing it to a
2377 * seekable file (not a pipe).
2379 * Do note that since pipable WIMs are not supported by Microsoft's software,
2380 * wimlib does not create them unless explicitly requested (with
2381 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2382 * characters to identify the file.
2385 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2386 unsigned num_threads, wimlib_progress_func_t progress_func,
2387 struct list_head *stream_list_override,
2388 struct list_head *lookup_table_list_ret)
2391 struct wim_reshdr xml_reshdr;
2393 WARNING("Creating a pipable WIM, which will "
2395 " with Microsoft's software (wimgapi/imagex/Dism).");
2397 /* At this point, the header at the beginning of the file has already
2400 /* For efficiency, when wimlib adds an image to the WIM with
2401 * wimlib_add_image(), the SHA1 message digests of files is not
2402 * calculated; instead, they are calculated while the files are being
2403 * written. However, this does not work when writing a pipable WIM,
2404 * since when writing a stream to a pipable WIM, its SHA1 message digest
2405 * needs to be known before the stream data is written. Therefore,
2406 * before getting much farther, we need to pre-calculate the SHA1
2407 * message digests of all streams that will be written. */
2408 ret = wim_checksum_unhashed_streams(wim);
2412 /* Write extra copy of the XML data. */
2413 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2415 WRITE_RESOURCE_FLAG_PIPABLE);
2419 /* Write metadata resources for the image(s) being included in the
2421 ret = write_wim_metadata_resources(wim, image, write_flags,
2426 /* Write streams needed for the image(s) being included in the output
2427 * WIM, or streams needed for the split WIM part. */
2428 return write_wim_streams(wim, image, write_flags, num_threads,
2429 progress_func, stream_list_override,
2430 lookup_table_list_ret);
2432 /* The lookup table, XML data, and header at end are handled by
2433 * finish_write(). */
2436 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2439 write_wim_part(WIMStruct *wim,
2440 const void *path_or_fd,
2443 unsigned num_threads,
2444 wimlib_progress_func_t progress_func,
2445 unsigned part_number,
2446 unsigned total_parts,
2447 struct list_head *stream_list_override,
2451 struct wim_header hdr_save;
2452 struct list_head lookup_table_list;
2454 if (total_parts == 1)
2455 DEBUG("Writing standalone WIM.");
2457 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2458 if (image == WIMLIB_ALL_IMAGES)
2459 DEBUG("Including all images.");
2461 DEBUG("Including image %d only.", image);
2462 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2463 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2465 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2466 DEBUG("Write flags: 0x%08x", write_flags);
2468 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2469 DEBUG("\tCHECK_INTEGRITY");
2471 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2474 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2475 DEBUG("\tRECOMPRESS");
2477 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2480 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2483 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2484 DEBUG("\tIGNORE_READONLY_FLAG");
2486 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2489 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2490 DEBUG("\tNOT_PIPABLE");
2492 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2493 DEBUG("\tPACK_STREAMS");
2495 if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2496 DEBUG("\tNO_PACK_STREAMS");
2498 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2499 DEBUG("\tFILE_DESCRIPTOR");
2501 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2502 DEBUG("\tNO_METADATA");
2504 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2505 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2507 if (num_threads == 0)
2508 DEBUG("Number of threads: autodetect");
2510 DEBUG("Number of threads: %u", num_threads);
2511 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2512 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2513 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2514 "specified" : "generate new"));
2516 /* Internally, this is always called with a valid part number and total
2518 wimlib_assert(total_parts >= 1);
2519 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2521 /* A valid image (or all images) must be specified. */
2522 if (image != WIMLIB_ALL_IMAGES &&
2523 (image < 1 || image > wim->hdr.image_count))
2524 return WIMLIB_ERR_INVALID_IMAGE;
2526 /* If we need to write metadata resources, make sure the ::WIMStruct has
2527 * the needed information attached (e.g. is not a resource-only WIM,
2528 * such as a non-first part of a split WIM). */
2529 if (!wim_has_metadata(wim) &&
2530 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2531 return WIMLIB_ERR_METADATA_NOT_FOUND;
2533 /* Check for contradictory flags. */
2534 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2535 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2536 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2537 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2538 return WIMLIB_ERR_INVALID_PARAM;
2540 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2541 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2542 == (WIMLIB_WRITE_FLAG_PIPABLE |
2543 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2544 return WIMLIB_ERR_INVALID_PARAM;
2546 if ((write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2547 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2548 == (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2549 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2550 return WIMLIB_ERR_INVALID_PARAM;
2552 /* Save previous header, then start initializing the new one. */
2553 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2555 /* Set default integrity, pipable, and packed stream flags. */
2556 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2557 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2558 if (wim_is_pipable(wim)) {
2559 DEBUG("WIM is pipable; default to PIPABLE.");
2560 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2563 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2564 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2565 if (wim_has_integrity_table(wim)) {
2566 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2567 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2570 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2571 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2572 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS) {
2573 DEBUG("WIM version 3584; default to PACK_STREAMS.");
2574 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2577 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2578 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2579 == (WIMLIB_WRITE_FLAG_PIPABLE |
2580 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2581 return WIMLIB_ERR_INVALID_PARAM;
2583 /* Set appropriate magic number. */
2584 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2585 wim->hdr.magic = PWM_MAGIC;
2587 wim->hdr.magic = WIM_MAGIC;
2589 /* Set appropriate version number. */
2590 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2591 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2593 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2595 /* Clear header flags that will be set automatically. */
2596 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2597 WIM_HDR_FLAG_RESOURCE_ONLY |
2598 WIM_HDR_FLAG_SPANNED |
2599 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2601 /* Set SPANNED header flag if writing part of a split WIM. */
2602 if (total_parts != 1)
2603 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2605 /* Set part number and total parts of split WIM. This will be 1 and 1
2606 * if the WIM is standalone. */
2607 wim->hdr.part_number = part_number;
2608 wim->hdr.total_parts = total_parts;
2610 /* Set compression type if different. */
2611 if (wim->compression_type != wim->out_compression_type) {
2612 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2613 wimlib_assert(ret == 0);
2616 /* Set chunk size if different. */
2617 wim->hdr.chunk_size = wim->out_chunk_size;
2619 /* Use GUID if specified; otherwise generate a new one. */
2621 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2622 else if (!wim->guid_set_explicitly)
2623 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2625 /* Clear references to resources that have not been written yet. */
2626 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2627 zero_reshdr(&wim->hdr.xml_data_reshdr);
2628 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2629 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2631 /* Set image count and boot index correctly for single image writes. */
2632 if (image != WIMLIB_ALL_IMAGES) {
2633 wim->hdr.image_count = 1;
2634 if (wim->hdr.boot_idx == image)
2635 wim->hdr.boot_idx = 1;
2637 wim->hdr.boot_idx = 0;
2640 /* Split WIMs can't be bootable. */
2641 if (total_parts != 1)
2642 wim->hdr.boot_idx = 0;
2644 /* Initialize output file descriptor. */
2645 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2646 /* File descriptor was explicitly provided. Return error if
2647 * file descriptor is not seekable, unless writing a pipable WIM
2649 wim->out_fd.fd = *(const int*)path_or_fd;
2650 wim->out_fd.offset = 0;
2651 if (!filedes_is_seekable(&wim->out_fd)) {
2652 ret = WIMLIB_ERR_INVALID_PARAM;
2653 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2654 goto out_restore_hdr;
2655 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2656 ERROR("Can't include integrity check when "
2657 "writing pipable WIM to pipe!");
2658 goto out_restore_hdr;
2663 /* Filename of WIM to write was provided; open file descriptor
2665 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2666 O_TRUNC | O_CREAT | O_RDWR);
2668 goto out_restore_hdr;
2671 /* Write initial header. This is merely a "dummy" header since it
2672 * doesn't have all the information yet, so it will be overwritten later
2673 * (unless writing a pipable WIM). */
2674 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2675 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2676 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2677 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2679 goto out_restore_hdr;
2681 /* Write metadata resources and streams. */
2682 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2683 /* Default case: create a normal (non-pipable) WIM. */
2684 ret = write_wim_streams(wim, image, write_flags, num_threads,
2685 progress_func, stream_list_override,
2686 &lookup_table_list);
2688 goto out_restore_hdr;
2690 ret = write_wim_metadata_resources(wim, image, write_flags,
2693 goto out_restore_hdr;
2695 /* Non-default case: create pipable WIM. */
2696 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2697 progress_func, stream_list_override,
2698 &lookup_table_list);
2700 goto out_restore_hdr;
2701 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2705 /* Write lookup table, XML data, and (optional) integrity table. */
2706 ret = finish_write(wim, image, write_flags, progress_func,
2707 &lookup_table_list);
2709 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2710 (void)close_wim_writable(wim, write_flags);
2711 DEBUG("ret=%d", ret);
2715 /* Write a standalone WIM to a file or file descriptor. */
2717 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2718 int image, int write_flags, unsigned num_threads,
2719 wimlib_progress_func_t progress_func)
2721 return write_wim_part(wim, path_or_fd, image, write_flags,
2722 num_threads, progress_func, 1, 1, NULL, NULL);
2725 /* API function documented in wimlib.h */
2727 wimlib_write(WIMStruct *wim, const tchar *path,
2728 int image, int write_flags, unsigned num_threads,
2729 wimlib_progress_func_t progress_func)
2732 return WIMLIB_ERR_INVALID_PARAM;
2734 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2736 return write_standalone_wim(wim, path, image, write_flags,
2737 num_threads, progress_func);
2740 /* API function documented in wimlib.h */
2742 wimlib_write_to_fd(WIMStruct *wim, int fd,
2743 int image, int write_flags, unsigned num_threads,
2744 wimlib_progress_func_t progress_func)
2747 return WIMLIB_ERR_INVALID_PARAM;
2749 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2750 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2752 return write_standalone_wim(wim, &fd, image, write_flags,
2753 num_threads, progress_func);
2757 any_images_modified(WIMStruct *wim)
2759 for (int i = 0; i < wim->hdr.image_count; i++)
2760 if (wim->image_metadata[i]->modified)
2766 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2768 const WIMStruct *wim = _wim;
2769 off_t end_offset = *(const off_t*)wim->private;
2771 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2772 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2773 return WIMLIB_ERR_RESOURCE_ORDER;
2777 /* Make sure no file or metadata resources are located after the XML data (or
2778 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2779 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2781 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2786 wim->private = &end_offset;
2787 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2791 for (i = 0; i < wim->hdr.image_count; i++) {
2792 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2800 * Overwrite a WIM, possibly appending streams to it.
2802 * A WIM looks like (or is supposed to look like) the following:
2804 * Header (212 bytes)
2805 * Streams and metadata resources (variable size)
2806 * Lookup table (variable size)
2807 * XML data (variable size)
2808 * Integrity table (optional) (variable size)
2810 * If we are not adding any streams or metadata resources, the lookup table is
2811 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2812 * header. This operation is potentially unsafe if the program is abruptly
2813 * terminated while the XML data or integrity table are being overwritten, but
2814 * before the new header has been written. To partially alleviate this problem,
2815 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2816 * finish_write() to cause a temporary WIM header to be written after the XML
2817 * data has been written. This may prevent the WIM from becoming corrupted if
2818 * the program is terminated while the integrity table is being calculated (but
2819 * no guarantees, due to write re-ordering...).
2821 * If we are adding new streams or images (metadata resources), the lookup table
2822 * needs to be changed, and those streams need to be written. In this case, we
2823 * try to perform a safe update of the WIM file by writing the streams *after*
2824 * the end of the previous WIM, then writing the new lookup table, XML data, and
2825 * (optionally) integrity table following the new streams. This will produce a
2826 * layout like the following:
2828 * Header (212 bytes)
2829 * (OLD) Streams and metadata resources (variable size)
2830 * (OLD) Lookup table (variable size)
2831 * (OLD) XML data (variable size)
2832 * (OLD) Integrity table (optional) (variable size)
2833 * (NEW) Streams and metadata resources (variable size)
2834 * (NEW) Lookup table (variable size)
2835 * (NEW) XML data (variable size)
2836 * (NEW) Integrity table (optional) (variable size)
2838 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2839 * the header is overwritten to point to the new lookup table, XML data, and
2840 * integrity table, to produce the following layout:
2842 * Header (212 bytes)
2843 * Streams and metadata resources (variable size)
2844 * Nothing (variable size)
2845 * More Streams and metadata resources (variable size)
2846 * Lookup table (variable size)
2847 * XML data (variable size)
2848 * Integrity table (optional) (variable size)
2850 * This method allows an image to be appended to a large WIM very quickly, and
2851 * is is crash-safe except in the case of write re-ordering, but the
2852 * disadvantage is that a small hole is left in the WIM where the old lookup
2853 * table, xml data, and integrity table were. (These usually only take up a
2854 * small amount of space compared to the streams, however.)
2857 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2858 unsigned num_threads,
2859 wimlib_progress_func_t progress_func)
2863 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2864 struct wim_header hdr_save;
2865 struct list_head stream_list;
2866 struct list_head lookup_table_list;
2867 struct filter_context filter_ctx;
2869 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2871 /* Save original header so it can be restored in case of error */
2872 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2874 /* Set default integrity flag. */
2875 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2876 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2877 if (wim_has_integrity_table(wim))
2878 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2880 /* Set default packed flag. */
2881 if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2882 WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2884 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
2885 write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2886 } else if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) {
2887 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2890 /* Set additional flags for overwrite. */
2891 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2892 WIMLIB_WRITE_FLAG_STREAMS_OK;
2894 /* Make sure that the integrity table (if present) is after the XML
2895 * data, and that there are no stream resources, metadata resources, or
2896 * lookup tables after the XML data. Otherwise, these data would be
2898 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2899 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2900 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2901 wim->hdr.lookup_table_reshdr.size_in_wim;
2902 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2903 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2904 WARNING("Didn't expect the integrity table to be before the XML data");
2905 ret = WIMLIB_ERR_RESOURCE_ORDER;
2906 goto out_restore_memory_hdr;
2909 if (old_lookup_table_end > old_xml_begin) {
2910 WARNING("Didn't expect the lookup table to be after the XML data");
2911 ret = WIMLIB_ERR_RESOURCE_ORDER;
2912 goto out_restore_memory_hdr;
2915 /* Set @old_wim_end, which indicates the point beyond which we don't
2916 * allow any file and metadata resources to appear without returning
2917 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2918 * overwrite these resources). */
2919 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2920 /* If no images have been modified and no images have been
2921 * deleted, a new lookup table does not need to be written. We
2922 * shall write the new XML data and optional integrity table
2923 * immediately after the lookup table. Note that this may
2924 * overwrite an existing integrity table. */
2925 DEBUG("Skipping writing lookup table "
2926 "(no images modified or deleted)");
2927 old_wim_end = old_lookup_table_end;
2928 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2929 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2930 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2931 /* Old WIM has an integrity table; begin writing new streams
2933 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2934 wim->hdr.integrity_table_reshdr.size_in_wim;
2936 /* No existing integrity table; begin writing new streams after
2937 * the old XML data. */
2938 old_wim_end = old_xml_end;
2941 ret = check_resource_offsets(wim, old_wim_end);
2943 goto out_restore_memory_hdr;
2945 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2946 &stream_list, &lookup_table_list,
2949 goto out_restore_memory_hdr;
2951 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2953 goto out_restore_memory_hdr;
2955 ret = lock_wim(wim, wim->out_fd.fd);
2959 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2960 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2961 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2963 ERROR_WITH_ERRNO("Error updating WIM header flags");
2964 goto out_unlock_wim;
2967 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2968 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2969 ret = WIMLIB_ERR_WRITE;
2970 goto out_restore_physical_hdr;
2973 ret = write_stream_list(&stream_list,
2975 write_flags_to_resource_flags(write_flags),
2976 wim->compression_type,
2986 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2987 write_flags, progress_func);
2991 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2992 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2993 progress_func, &lookup_table_list);
2997 wim->wim_locked = 0;
3001 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3002 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3003 wim->filename, old_wim_end);
3004 /* Return value of ftruncate() is ignored because this is
3005 * already an error path. */
3006 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3008 out_restore_physical_hdr:
3009 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3011 wim->wim_locked = 0;
3013 (void)close_wim_writable(wim, write_flags);
3014 out_restore_memory_hdr:
3015 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3020 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3021 unsigned num_threads,
3022 wimlib_progress_func_t progress_func)
3024 size_t wim_name_len;
3027 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3029 /* Write the WIM to a temporary file in the same directory as the
3031 wim_name_len = tstrlen(wim->filename);
3032 tchar tmpfile[wim_name_len + 10];
3033 tmemcpy(tmpfile, wim->filename, wim_name_len);
3034 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3035 tmpfile[wim_name_len + 9] = T('\0');
3037 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3038 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3039 num_threads, progress_func);
3047 /* Rename the new WIM file to the original WIM file. Note: on Windows
3048 * this actually calls win32_rename_replacement(), not _wrename(), so
3049 * that removing the existing destination file can be handled. */
3050 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3051 ret = trename(tmpfile, wim->filename);
3053 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3054 tmpfile, wim->filename);
3061 return WIMLIB_ERR_RENAME;
3064 if (progress_func) {
3065 union wimlib_progress_info progress;
3066 progress.rename.from = tmpfile;
3067 progress.rename.to = wim->filename;
3068 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3074 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3076 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3079 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3082 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3085 if (wim->compression_type != wim->out_compression_type)
3087 if (wim->chunk_size != wim->out_chunk_size)
3093 /* API function documented in wimlib.h */
3095 wimlib_overwrite(WIMStruct *wim, int write_flags,
3096 unsigned num_threads,
3097 wimlib_progress_func_t progress_func)
3102 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3104 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3105 return WIMLIB_ERR_INVALID_PARAM;
3108 return WIMLIB_ERR_NO_FILENAME;
3110 orig_hdr_flags = wim->hdr.flags;
3111 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3112 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3113 ret = can_modify_wim(wim);
3114 wim->hdr.flags = orig_hdr_flags;
3118 if (can_overwrite_wim_inplace(wim, write_flags)) {
3119 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3121 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3123 WARNING("Falling back to re-building entire WIM");
3125 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,