4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013, 2014 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/chunk_compressor.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/inode.h"
43 #include "wimlib/integrity.h"
44 #include "wimlib/lookup_table.h"
45 #include "wimlib/metadata.h"
46 #include "wimlib/paths.h"
47 #include "wimlib/progress.h"
48 #include "wimlib/resource.h"
50 # include "wimlib/win32.h" /* win32_rename_replacement() */
52 #include "wimlib/write.h"
53 #include "wimlib/xml.h"
64 /* wimlib internal flags used when writing resources. */
65 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
66 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
67 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
68 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
71 write_flags_to_resource_flags(int write_flags)
73 int write_resource_flags = 0;
75 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
77 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
78 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
79 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
80 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
81 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
82 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
83 return write_resource_flags;
86 struct filter_context {
91 /* Determine specified stream should be filtered out from the write.
95 * < 0 : The stream should be hard-filtered; that is, not included in the
97 * 0 : The stream should not be filtered out.
98 * > 0 : The stream should be soft-filtered; that is, it already exists in the
99 * WIM file and may not need to be written again.
102 stream_filtered(const struct wim_lookup_table_entry *lte,
103 const struct filter_context *ctx)
111 write_flags = ctx->write_flags;
114 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
115 lte->resource_location == RESOURCE_IN_WIM &&
116 lte->rspec->wim == wim)
119 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
120 lte->resource_location == RESOURCE_IN_WIM &&
121 lte->rspec->wim != wim)
128 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
129 struct filter_context *ctx)
131 return stream_filtered(lte, ctx) < 0;
135 may_soft_filter_streams(const struct filter_context *ctx)
139 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
143 may_hard_filter_streams(const struct filter_context *ctx)
147 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
151 may_filter_streams(const struct filter_context *ctx)
153 return (may_soft_filter_streams(ctx) ||
154 may_hard_filter_streams(ctx));
158 /* Return true if the specified resource is compressed and the compressed data
159 * can be reused with the specified output parameters. */
161 can_raw_copy(const struct wim_lookup_table_entry *lte,
162 int write_resource_flags, int out_ctype, u32 out_chunk_size)
164 const struct wim_resource_spec *rspec;
166 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
169 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
172 if (lte->resource_location != RESOURCE_IN_WIM)
177 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
180 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
181 /* Normal compressed resource: Must use same compression type
183 return (rspec->compression_type == out_ctype &&
184 rspec->chunk_size == out_chunk_size);
187 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
188 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
190 /* Packed resource: Such resources may contain multiple streams,
191 * and in general only a subset of them need to be written. As
192 * a heuristic, re-use the raw data if more than two-thirds the
193 * uncompressed size is being written. */
195 /* Note: packed resources contain a header that specifies the
196 * compression type and chunk size; therefore we don't need to
197 * check if they are compatible with @out_ctype and
198 * @out_chunk_size. */
200 struct wim_lookup_table_entry *res_stream;
203 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
204 if (res_stream->will_be_in_output_wim)
205 write_size += res_stream->size;
207 return (write_size > rspec->uncompressed_size * 2 / 3);
214 filter_resource_flags(u8 flags)
216 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
217 WIM_RESHDR_FLAG_COMPRESSED |
218 WIM_RESHDR_FLAG_SPANNED |
219 WIM_RESHDR_FLAG_FREE));
223 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
225 const struct wim_resource_spec *rspec;
227 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
230 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
232 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
234 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
235 lte->out_reshdr.uncompressed_size = 0;
236 lte->out_reshdr.size_in_wim = lte->size;
238 lte->out_res_offset_in_wim = rspec->offset_in_wim;
239 lte->out_res_size_in_wim = rspec->size_in_wim;
240 lte->out_res_uncompressed_size = rspec->uncompressed_size;
242 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
244 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
245 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
246 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
248 lte->out_reshdr.flags = lte->flags;
252 /* Write the header for a stream in a pipable WIM. */
254 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
255 struct filedes *out_fd,
256 int additional_reshdr_flags)
258 struct pwm_stream_hdr stream_hdr;
262 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
263 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
264 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
265 zero_out_hash(stream_hdr.hash);
267 wimlib_assert(!lte->unhashed);
268 copy_hash(stream_hdr.hash, lte->hash);
271 reshdr_flags = filter_resource_flags(lte->flags);
272 reshdr_flags |= additional_reshdr_flags;
273 stream_hdr.flags = cpu_to_le32(reshdr_flags);
274 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
276 ERROR_WITH_ERRNO("Write error");
280 struct write_streams_progress_data {
281 wimlib_progress_func_t progfunc;
283 union wimlib_progress_info progress;
284 uint64_t next_progress;
288 do_write_streams_progress(struct write_streams_progress_data *progress_data,
289 struct wim_lookup_table_entry *cur_stream,
294 union wimlib_progress_info *progress = &progress_data->progress;
298 progress->write_streams.total_bytes -= complete_size;
299 progress->write_streams.total_streams -= complete_count;
300 if (progress_data->next_progress != ~(uint64_t)0 &&
301 progress_data->next_progress > progress->write_streams.total_bytes)
303 progress_data->next_progress = progress->write_streams.total_bytes;
306 progress->write_streams.completed_bytes += complete_size;
307 progress->write_streams.completed_streams += complete_count;
310 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
312 ret = call_progress(progress_data->progfunc,
313 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
315 progress_data->progctx);
319 if (progress_data->next_progress == progress->write_streams.total_bytes) {
320 progress_data->next_progress = ~(uint64_t)0;
322 /* Handle rate-limiting of messages */
324 /* Send new message as soon as another 1/128 of the
325 * total has been written. (Arbitrary number.) */
326 progress_data->next_progress =
327 progress->write_streams.completed_bytes +
328 progress->write_streams.total_bytes / 128;
330 /* ... Unless that would be more than 5000000 bytes, in
331 * which case send the next after the next 5000000
332 * bytes. (Another arbitrary number.) */
333 if (progress->write_streams.completed_bytes + 5000000 <
334 progress_data->next_progress)
335 progress_data->next_progress =
336 progress->write_streams.completed_bytes + 5000000;
338 /* ... But always send a message as soon as we're
339 * completely done. */
340 if (progress->write_streams.total_bytes <
341 progress_data->next_progress)
342 progress_data->next_progress =
343 progress->write_streams.total_bytes;
349 struct write_streams_ctx {
350 /* File descriptor the streams are being written to. */
351 struct filedes *out_fd;
353 /* Lookup table for the WIMStruct on whose behalf the streams are being
355 struct wim_lookup_table *lookup_table;
357 /* Compression format to use. */
360 /* Maximum uncompressed chunk size in compressed resources to use. */
363 /* Flags that affect how the streams will be written. */
364 int write_resource_flags;
366 /* Data used for issuing WRITE_STREAMS progress. */
367 struct write_streams_progress_data progress_data;
369 struct filter_context *filter_ctx;
371 /* Upper bound on the total number of bytes that need to be compressed.
373 u64 num_bytes_to_compress;
375 /* Pointer to the chunk_compressor implementation being used for
376 * compressing chunks of data, or NULL if chunks are being written
378 struct chunk_compressor *compressor;
380 /* Buffer for dividing the read data into chunks of size
381 * @out_chunk_size. */
384 /* Number of bytes in @chunk_buf that are currently filled. */
385 size_t chunk_buf_filled;
387 /* List of streams that currently have chunks being compressed. */
388 struct list_head pending_streams;
390 /* List of streams in the resource pack. Streams are moved here after
391 * @pending_streams only when writing a packed resource. */
392 struct list_head pack_streams;
394 /* Set to true if the stream currently being read was a duplicate, and
395 * therefore the corresponding stream entry needs to be freed once the
396 * read finishes. (In this case we add the duplicate entry to
397 * pending_streams rather than the entry being read.) */
398 bool stream_was_duplicate;
400 struct wim_inode *stream_inode;
402 /* Current uncompressed offset in the stream being read. */
403 u64 cur_read_stream_offset;
405 /* Uncompressed size of the stream currently being read. */
406 u64 cur_read_stream_size;
408 /* Current uncompressed offset in the stream being written. */
409 u64 cur_write_stream_offset;
411 /* Uncompressed size of resource currently being written. */
412 u64 cur_write_res_size;
414 /* Array that is filled in with compressed chunk sizes as a resource is
418 /* Index of next entry in @chunk_csizes to fill in. */
421 /* Number of entries in @chunk_csizes currently allocated. */
422 size_t num_alloc_chunks;
424 /* Offset in the output file of the start of the chunks of the resource
425 * currently being written. */
426 u64 chunks_start_offset;
429 /* Reserve space for the chunk table and prepare to accumulate the chunk table
432 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
434 u64 expected_num_chunks;
435 u64 expected_num_chunk_entries;
439 /* Calculate the number of chunks and chunk entries that should be
440 * needed for the resource. These normally will be the final values,
441 * but in PACKED_STREAMS mode some of the streams we're planning to
442 * write into the resource may be duplicates, and therefore discarded,
443 * potentially decreasing the number of chunk entries needed. */
444 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
445 expected_num_chunk_entries = expected_num_chunks;
446 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
447 expected_num_chunk_entries--;
449 /* Make sure the chunk_csizes array is long enough to store the
450 * compressed size of each chunk. */
451 if (expected_num_chunks > ctx->num_alloc_chunks) {
452 u64 new_length = expected_num_chunks + 50;
454 if ((size_t)new_length != new_length) {
455 ERROR("Resource size too large (%"PRIu64" bytes!",
457 return WIMLIB_ERR_NOMEM;
460 FREE(ctx->chunk_csizes);
461 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
462 if (ctx->chunk_csizes == NULL) {
463 ctx->num_alloc_chunks = 0;
464 return WIMLIB_ERR_NOMEM;
466 ctx->num_alloc_chunks = new_length;
469 ctx->chunk_index = 0;
471 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
472 /* Reserve space for the chunk table in the output file. In the
473 * case of packed resources this reserves the upper bound for
474 * the needed space, not necessarily the exact space which will
475 * prove to be needed. At this point, we just use @chunk_csizes
476 * for a buffer of 0's because the actual compressed chunk sizes
478 reserve_size = expected_num_chunk_entries *
479 get_chunk_entry_size(res_expected_size,
480 0 != (ctx->write_resource_flags &
481 WRITE_RESOURCE_FLAG_PACK_STREAMS));
482 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
483 reserve_size += sizeof(struct alt_chunk_table_header_disk);
484 memset(ctx->chunk_csizes, 0, reserve_size);
485 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
493 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
497 wimlib_assert(res_expected_size != 0);
499 if (ctx->compressor != NULL) {
500 ret = begin_chunk_table(ctx, res_expected_size);
505 /* Output file descriptor is now positioned at the offset at which to
506 * write the first chunk of the resource. */
507 ctx->chunks_start_offset = ctx->out_fd->offset;
508 ctx->cur_write_stream_offset = 0;
509 ctx->cur_write_res_size = res_expected_size;
514 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
515 u64 *res_start_offset_ret, u64 *res_store_size_ret)
517 size_t actual_num_chunks;
518 size_t actual_num_chunk_entries;
519 size_t chunk_entry_size;
522 actual_num_chunks = ctx->chunk_index;
523 actual_num_chunk_entries = actual_num_chunks;
524 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
525 actual_num_chunk_entries--;
527 chunk_entry_size = get_chunk_entry_size(res_actual_size,
528 0 != (ctx->write_resource_flags &
529 WRITE_RESOURCE_FLAG_PACK_STREAMS));
531 typedef le64 __attribute__((may_alias)) aliased_le64_t;
532 typedef le32 __attribute__((may_alias)) aliased_le32_t;
534 if (chunk_entry_size == 4) {
535 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
537 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
538 for (size_t i = 0; i < actual_num_chunk_entries; i++)
539 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
541 u32 offset = ctx->chunk_csizes[0];
542 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
543 u32 next_size = ctx->chunk_csizes[i + 1];
544 entries[i] = cpu_to_le32(offset);
549 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
551 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
552 for (size_t i = 0; i < actual_num_chunk_entries; i++)
553 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
555 u64 offset = ctx->chunk_csizes[0];
556 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
557 u64 next_size = ctx->chunk_csizes[i + 1];
558 entries[i] = cpu_to_le64(offset);
564 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
565 u64 res_start_offset;
568 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
569 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
572 res_end_offset = ctx->out_fd->offset;
573 res_start_offset = ctx->chunks_start_offset;
575 res_end_offset = ctx->out_fd->offset;
577 u64 chunk_table_offset;
579 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
581 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
582 struct alt_chunk_table_header_disk hdr;
584 hdr.res_usize = cpu_to_le64(res_actual_size);
585 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
586 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
588 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
589 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
590 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
592 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
593 chunk_table_offset - sizeof(hdr));
596 res_start_offset = chunk_table_offset - sizeof(hdr);
598 res_start_offset = chunk_table_offset;
601 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
602 chunk_table_size, chunk_table_offset);
607 *res_start_offset_ret = res_start_offset;
608 *res_store_size_ret = res_end_offset - res_start_offset;
613 ERROR_WITH_ERRNO("Write error");
617 /* Finish writing a WIM resource by writing or updating the chunk table (if not
618 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
620 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
624 u64 res_uncompressed_size;
625 u64 res_offset_in_wim;
627 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
628 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS));
629 res_uncompressed_size = ctx->cur_write_res_size;
631 if (ctx->compressor) {
632 ret = end_chunk_table(ctx, res_uncompressed_size,
633 &res_offset_in_wim, &res_size_in_wim);
637 res_offset_in_wim = ctx->chunks_start_offset;
638 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
640 out_reshdr->uncompressed_size = res_uncompressed_size;
641 out_reshdr->size_in_wim = res_size_in_wim;
642 out_reshdr->offset_in_wim = res_offset_in_wim;
643 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
644 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
648 /* No more data streams of the file at @path are needed. */
650 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
652 union wimlib_progress_info info;
654 info.done_with_file.path_to_file = path;
656 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
660 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
662 done_with_stream(struct wim_lookup_table_entry *stream,
663 wimlib_progress_func_t progfunc, void *progctx,
664 struct wim_inode *inode)
666 if (stream->resource_location == RESOURCE_IN_FILE_ON_DISK
668 || stream->resource_location == RESOURCE_IN_WINNT_FILE_ON_DISK
669 || stream->resource_location == RESOURCE_WIN32_ENCRYPTED
675 wimlib_assert(inode->num_unread_streams > 0);
676 if (--inode->num_unread_streams > 0)
680 /* XXX: This logic really should be somewhere else. */
682 /* We want the path to the file, but stream->file_on_disk might
683 * actually refer to a named data stream. Temporarily strip the
684 * named data stream from the path. */
685 wchar_t *p_colon = NULL;
686 wchar_t *p_question_mark = NULL;
687 const wchar_t *p_stream_name;
689 p_stream_name = path_stream_name(stream->file_on_disk);
690 if (unlikely(p_stream_name)) {
691 p_colon = (wchar_t *)(p_stream_name - 1);
692 wimlib_assert(*p_colon == L':');
696 /* We also should use a fake Win32 path instead of a NT path */
697 if (!wcsncmp(stream->file_on_disk, L"\\??\\", 4)) {
698 p_question_mark = &stream->file_on_disk[1];
699 *p_question_mark = L'\\';
703 ret = done_with_file(stream->file_on_disk, progfunc, progctx);
709 *p_question_mark = L'?';
716 /* Begin processing a stream for writing. */
718 write_stream_begin_read(struct wim_lookup_table_entry *lte, void *_ctx)
720 struct write_streams_ctx *ctx = _ctx;
723 wimlib_assert(lte->size > 0);
725 ctx->cur_read_stream_offset = 0;
726 ctx->cur_read_stream_size = lte->size;
729 ctx->stream_inode = lte->back_inode;
731 ctx->stream_inode = NULL;
733 /* As an optimization, we allow some streams to be "unhashed", meaning
734 * their SHA1 message digests are unknown. This is the case with
735 * streams that are added by scanning a directry tree with
736 * wimlib_add_image(), for example. Since WIM uses single-instance
737 * streams, we don't know whether such each such stream really need to
738 * written until it is actually checksummed, unless it has a unique
739 * size. In such cases we read and checksum the stream in this
740 * function, thereby advancing ahead of read_stream_list(), which will
741 * still provide the data again to write_stream_process_chunk(). This
742 * is okay because an unhashed stream cannot be in a WIM resource, which
743 * might be costly to decompress. */
744 ctx->stream_was_duplicate = false;
745 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
747 struct wim_lookup_table_entry *lte_new;
749 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
752 if (lte_new != lte) {
753 /* Duplicate stream detected. */
755 if (lte_new->will_be_in_output_wim ||
756 stream_filtered(lte_new, ctx->filter_ctx))
758 /* The duplicate stream is already being
759 * included in the output WIM, or it would be
760 * filtered out if it had been. Skip writing
761 * this stream (and reading it again) entirely,
762 * passing its output reference count to the
763 * duplicate stream in the former case. */
764 DEBUG("Discarding duplicate stream of "
765 "length %"PRIu64, lte->size);
766 ret = do_write_streams_progress(&ctx->progress_data,
769 list_del(<e->write_streams_list);
770 list_del(<e->lookup_table_list);
771 if (lte_new->will_be_in_output_wim)
772 lte_new->out_refcnt += lte->out_refcnt;
773 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
774 ctx->cur_write_res_size -= lte->size;
775 if (!ret && unlikely(ctx->write_resource_flags &
776 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
778 ret = done_with_stream(lte,
779 ctx->progress_data.progfunc,
780 ctx->progress_data.progctx,
783 free_lookup_table_entry(lte);
786 return BEGIN_STREAM_STATUS_SKIP_STREAM;
788 /* The duplicate stream can validly be written,
789 * but was not marked as such. Discard the
790 * current stream entry and use the duplicate,
791 * but actually freeing the current entry must
792 * wait until read_stream_list() has finished
793 * reading its data. */
794 DEBUG("Stream duplicate, but not already "
795 "selected for writing.");
796 list_replace(<e->write_streams_list,
797 <e_new->write_streams_list);
798 list_replace(<e->lookup_table_list,
799 <e_new->lookup_table_list);
800 lte_new->out_refcnt = lte->out_refcnt;
801 lte_new->will_be_in_output_wim = 1;
802 ctx->stream_was_duplicate = true;
807 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
811 /* Rewrite a stream that was just written compressed as uncompressed instead.
812 * This function is optional, but if a stream did not compress to less than its
813 * original size, it might as well be written uncompressed. */
815 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
816 struct filedes *out_fd)
819 u64 begin_offset = lte->out_reshdr.offset_in_wim;
820 u64 end_offset = out_fd->offset;
822 if (filedes_seek(out_fd, begin_offset) == -1)
825 ret = extract_full_stream_to_fd(lte, out_fd);
827 /* Error reading the uncompressed data. */
828 if (out_fd->offset == begin_offset &&
829 filedes_seek(out_fd, end_offset) != -1)
831 /* Nothing was actually written yet, and we successfully
832 * seeked to the end of the compressed resource, so
833 * don't issue a hard error; just keep the compressed
834 * resource instead. */
835 WARNING("Recovered compressed stream of "
836 "size %"PRIu64", continuing on.",
843 wimlib_assert(out_fd->offset - begin_offset == lte->size);
845 if (out_fd->offset < end_offset &&
846 0 != ftruncate(out_fd->fd, out_fd->offset))
848 ERROR_WITH_ERRNO("Can't truncate output file to "
849 "offset %"PRIu64, out_fd->offset);
850 return WIMLIB_ERR_WRITE;
853 lte->out_reshdr.size_in_wim = lte->size;
854 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
855 WIM_RESHDR_FLAG_PACKED_STREAMS);
859 /* Write the next chunk of (typically compressed) data to the output WIM,
860 * handling the writing of the chunk table. */
862 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
863 size_t csize, size_t usize)
867 struct wim_lookup_table_entry *lte;
868 u32 completed_stream_count;
871 lte = list_entry(ctx->pending_streams.next,
872 struct wim_lookup_table_entry, write_streams_list);
874 if (ctx->cur_write_stream_offset == 0 &&
875 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
877 /* Starting to write a new stream in non-packed mode. */
879 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
880 int additional_reshdr_flags = 0;
881 if (ctx->compressor != NULL)
882 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
884 DEBUG("Writing pipable WIM stream header "
885 "(offset=%"PRIu64")", ctx->out_fd->offset);
887 ret = write_pwm_stream_header(lte, ctx->out_fd,
888 additional_reshdr_flags);
893 ret = begin_write_resource(ctx, lte->size);
898 if (ctx->compressor != NULL) {
899 /* Record the compresed chunk size. */
900 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
901 ctx->chunk_csizes[ctx->chunk_index++] = csize;
903 /* If writing a pipable WIM, before the chunk data write a chunk
904 * header that provides the compressed chunk size. */
905 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
906 struct pwm_chunk_hdr chunk_hdr = {
907 .compressed_size = cpu_to_le32(csize),
909 ret = full_write(ctx->out_fd, &chunk_hdr,
916 /* Write the chunk data. */
917 ret = full_write(ctx->out_fd, cchunk, csize);
921 ctx->cur_write_stream_offset += usize;
923 completed_size = usize;
924 completed_stream_count = 0;
925 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
926 /* Wrote chunk in packed mode. It may have finished multiple
928 while (ctx->cur_write_stream_offset > lte->size) {
929 struct wim_lookup_table_entry *next;
931 ctx->cur_write_stream_offset -= lte->size;
933 wimlib_assert(!list_is_singular(&ctx->pending_streams) &&
934 !list_empty(&ctx->pending_streams));
935 next = list_entry(lte->write_streams_list.next,
936 struct wim_lookup_table_entry,
938 list_move_tail(<e->write_streams_list,
941 completed_stream_count++;
943 if (ctx->cur_write_stream_offset == lte->size) {
944 ctx->cur_write_stream_offset = 0;
945 list_move_tail(<e->write_streams_list,
947 completed_stream_count++;
950 /* Wrote chunk in non-packed mode. It may have finished a
952 if (ctx->cur_write_stream_offset == lte->size) {
954 completed_stream_count++;
956 list_del(<e->write_streams_list);
958 wimlib_assert(ctx->cur_write_stream_offset ==
959 ctx->cur_write_res_size);
961 ret = end_write_resource(ctx, <e->out_reshdr);
965 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
966 if (ctx->compressor != NULL)
967 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
969 if (ctx->compressor != NULL &&
970 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
971 !(ctx->write_resource_flags & (WRITE_RESOURCE_FLAG_PIPABLE |
972 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)) &&
973 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
975 /* Stream did not compress to less than its original
976 * size. If we're not writing a pipable WIM (which
977 * could mean the output file descriptor is
978 * non-seekable), and the stream isn't located in a
979 * resource pack (which would make reading it again
980 * costly), truncate the file to the start of the stream
981 * and write it uncompressed instead. */
982 DEBUG("Stream of size %"PRIu64" did not compress to "
983 "less than original size; writing uncompressed.",
985 ret = write_stream_uncompressed(lte, ctx->out_fd);
989 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
991 ctx->cur_write_stream_offset = 0;
995 return do_write_streams_progress(&ctx->progress_data, lte,
996 completed_size, completed_stream_count,
1000 ERROR_WITH_ERRNO("Write error");
1005 submit_chunk_for_compression(struct write_streams_ctx *ctx,
1006 const void *chunk, size_t size)
1008 /* While we are unable to submit the chunk for compression (due to too
1009 * many chunks already outstanding), retrieve and write the next
1010 * compressed chunk. */
1011 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
1018 bret = ctx->compressor->get_chunk(ctx->compressor,
1019 &cchunk, &csize, &usize);
1021 wimlib_assert(bret);
1023 ret = write_chunk(ctx, cchunk, csize, usize);
1030 /* Process the next chunk of data to be written to a WIM resource. */
1032 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
1034 struct write_streams_ctx *ctx = _ctx;
1036 const u8 *chunkptr, *chunkend;
1038 wimlib_assert(size != 0);
1040 if (ctx->compressor == NULL) {
1041 /* Write chunk uncompressed. */
1042 ret = write_chunk(ctx, chunk, size, size);
1045 ctx->cur_read_stream_offset += size;
1049 /* Submit the chunk for compression, but take into account that the
1050 * @size the chunk was provided in may not correspond to the
1051 * @out_chunk_size being used for compression. */
1053 chunkend = chunkptr + size;
1055 const u8 *resized_chunk;
1056 size_t needed_chunk_size;
1058 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1059 needed_chunk_size = ctx->out_chunk_size;
1061 u64 res_bytes_remaining;
1063 res_bytes_remaining = ctx->cur_read_stream_size -
1064 ctx->cur_read_stream_offset;
1065 needed_chunk_size = min(ctx->out_chunk_size,
1066 ctx->chunk_buf_filled +
1067 res_bytes_remaining);
1070 if (ctx->chunk_buf_filled == 0 &&
1071 chunkend - chunkptr >= needed_chunk_size)
1073 /* No intermediate buffering needed. */
1074 resized_chunk = chunkptr;
1075 chunkptr += needed_chunk_size;
1076 ctx->cur_read_stream_offset += needed_chunk_size;
1078 /* Intermediate buffering needed. */
1079 size_t bytes_consumed;
1081 bytes_consumed = min(chunkend - chunkptr,
1082 needed_chunk_size - ctx->chunk_buf_filled);
1084 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
1085 chunkptr, bytes_consumed);
1087 chunkptr += bytes_consumed;
1088 ctx->cur_read_stream_offset += bytes_consumed;
1089 ctx->chunk_buf_filled += bytes_consumed;
1090 if (ctx->chunk_buf_filled == needed_chunk_size) {
1091 resized_chunk = ctx->chunk_buf;
1092 ctx->chunk_buf_filled = 0;
1099 ret = submit_chunk_for_compression(ctx, resized_chunk,
1104 } while (chunkptr != chunkend);
1108 /* Finish processing a stream for writing. It may not have been completely
1109 * written yet, as the chunk_compressor implementation may still have chunks
1110 * buffered or being compressed. */
1112 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1114 struct write_streams_ctx *ctx = _ctx;
1118 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size);
1120 if (unlikely(ctx->write_resource_flags &
1121 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE) &&
1122 ctx->stream_inode != NULL)
1124 status = done_with_stream(lte,
1125 ctx->progress_data.progfunc,
1126 ctx->progress_data.progctx,
1130 if (!ctx->stream_was_duplicate && lte->unhashed &&
1131 ctx->lookup_table != NULL)
1133 list_del(<e->unhashed_list);
1134 lookup_table_insert(ctx->lookup_table, lte);
1138 if (ctx->stream_was_duplicate)
1139 free_lookup_table_entry(lte);
1143 /* Compute statistics about a list of streams that will be written.
1145 * Assumes the streams are sorted such that all streams located in each distinct
1146 * WIM (specified by WIMStruct) are together. */
1148 compute_stream_list_stats(struct list_head *stream_list,
1149 struct write_streams_ctx *ctx)
1151 struct wim_lookup_table_entry *lte;
1152 u64 total_bytes = 0;
1153 u64 num_streams = 0;
1154 u64 total_parts = 0;
1155 WIMStruct *prev_wim_part = NULL;
1157 list_for_each_entry(lte, stream_list, write_streams_list) {
1159 total_bytes += lte->size;
1160 if (lte->resource_location == RESOURCE_IN_WIM) {
1161 if (prev_wim_part != lte->rspec->wim) {
1162 prev_wim_part = lte->rspec->wim;
1167 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1168 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1169 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1170 ctx->progress_data.progress.write_streams.completed_streams = 0;
1171 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1172 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1173 ctx->progress_data.progress.write_streams.completed_parts = 0;
1174 ctx->progress_data.next_progress = 0;
1177 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1178 * rather than compressed. Delete these streams from @stream_list and move them
1179 * to @raw_copy_streams. Return the total uncompressed size of the streams that
1180 * need to be compressed. */
1182 find_raw_copy_streams(struct list_head *stream_list,
1183 int write_resource_flags,
1186 struct list_head *raw_copy_streams)
1188 struct wim_lookup_table_entry *lte, *tmp;
1189 u64 num_bytes_to_compress = 0;
1191 INIT_LIST_HEAD(raw_copy_streams);
1193 /* Initialize temporary raw_copy_ok flag. */
1194 list_for_each_entry(lte, stream_list, write_streams_list)
1195 if (lte->resource_location == RESOURCE_IN_WIM)
1196 lte->rspec->raw_copy_ok = 0;
1198 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1199 if (lte->resource_location == RESOURCE_IN_WIM &&
1200 lte->rspec->raw_copy_ok)
1202 list_move_tail(<e->write_streams_list,
1204 } else if (can_raw_copy(lte, write_resource_flags,
1205 out_ctype, out_chunk_size))
1207 lte->rspec->raw_copy_ok = 1;
1208 list_move_tail(<e->write_streams_list,
1211 num_bytes_to_compress += lte->size;
1215 return num_bytes_to_compress;
1218 /* Copy a raw compressed resource located in another WIM file to the WIM file
1221 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1222 struct filedes *out_fd)
1224 u64 cur_read_offset;
1225 u64 end_read_offset;
1226 u8 buf[BUFFER_SIZE];
1227 size_t bytes_to_read;
1229 struct filedes *in_fd;
1230 struct wim_lookup_table_entry *lte;
1231 u64 out_offset_in_wim;
1233 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1234 "uncompressed_size=%"PRIu64")",
1235 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1237 /* Copy the raw data. */
1238 cur_read_offset = in_rspec->offset_in_wim;
1239 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1241 out_offset_in_wim = out_fd->offset;
1243 if (in_rspec->is_pipable) {
1244 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1245 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1246 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1247 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1249 in_fd = &in_rspec->wim->in_fd;
1250 wimlib_assert(cur_read_offset != end_read_offset);
1253 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1255 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1259 ret = full_write(out_fd, buf, bytes_to_read);
1263 cur_read_offset += bytes_to_read;
1265 } while (cur_read_offset != end_read_offset);
1267 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1268 if (lte->will_be_in_output_wim) {
1269 stream_set_out_reshdr_for_reuse(lte);
1270 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1271 lte->out_res_offset_in_wim = out_offset_in_wim;
1273 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1280 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1281 * WIM file being written. */
1283 write_raw_copy_resources(struct list_head *raw_copy_streams,
1284 struct filedes *out_fd,
1285 struct write_streams_progress_data *progress_data)
1287 struct wim_lookup_table_entry *lte;
1290 list_for_each_entry(lte, raw_copy_streams, write_streams_list)
1291 lte->rspec->raw_copy_ok = 1;
1293 list_for_each_entry(lte, raw_copy_streams, write_streams_list) {
1294 if (lte->rspec->raw_copy_ok) {
1295 /* Write each packed resource only one time, no matter
1296 * how many streams reference it. */
1297 ret = write_raw_copy_resource(lte->rspec, out_fd);
1300 lte->rspec->raw_copy_ok = 0;
1302 ret = do_write_streams_progress(progress_data, lte, lte->size,
1310 /* Wait for and write all chunks pending in the compressor. */
1312 finish_remaining_chunks(struct write_streams_ctx *ctx)
1319 if (ctx->compressor == NULL)
1322 if (ctx->chunk_buf_filled != 0) {
1323 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1324 ctx->chunk_buf_filled);
1329 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1330 ret = write_chunk(ctx, cdata, csize, usize);
1338 remove_zero_length_streams(struct list_head *stream_list)
1340 struct wim_lookup_table_entry *lte, *tmp;
1342 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1343 wimlib_assert(lte->will_be_in_output_wim);
1344 if (lte->size == 0) {
1345 list_del(<e->write_streams_list);
1346 lte->out_reshdr.offset_in_wim = 0;
1347 lte->out_reshdr.size_in_wim = 0;
1348 lte->out_reshdr.uncompressed_size = 0;
1349 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1355 * Write a list of streams to the output WIM file.
1358 * The list of streams to write, specified by a list of `struct
1359 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1362 * The file descriptor, opened for writing, to which to write the streams.
1364 * @write_resource_flags
1365 * Flags to modify how the streams are written:
1367 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1368 * Force compression of all resources, even if they could otherwise
1369 * be re-used by copying the raw data, due to being located in a WIM
1370 * file with compatible compression parameters.
1372 * WRITE_RESOURCE_FLAG_PIPABLE:
1373 * Write the resources in the wimlib-specific pipable format, and
1374 * furthermore do so in such a way that no seeking backwards in
1375 * @out_fd will be performed (so it may be a pipe).
1377 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1378 * Pack all the streams into a single resource rather than writing
1379 * them in separate resources. This flag is only valid if the WIM
1380 * version number has been, or will be, set to
1381 * WIM_VERSION_PACKED_STREAMS. This flag may not be combined with
1382 * WRITE_RESOURCE_FLAG_PIPABLE.
1385 * Compression format to use to write the output streams, specified as one
1386 * of the WIMLIB_COMPRESSION_TYPE_* constants.
1387 * WIMLIB_COMPRESSION_TYPE_NONE is allowed.
1390 * Chunk size to use to write the streams. It must be a valid chunk size
1391 * for the specified compression format @out_ctype, unless @out_ctype is
1392 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1395 * Number of threads to use to compress data. If 0, a default number of
1396 * threads will be chosen. The number of threads still may be decreased
1397 * from the specified value if insufficient memory is detected.
1400 * If on-the-fly deduplication of unhashed streams is desired, this
1401 * parameter must be pointer to the lookup table for the WIMStruct on whose
1402 * behalf the streams are being written. Otherwise, this parameter can be
1406 * If on-the-fly deduplication of unhashed streams is desired, this
1407 * parameter can be a pointer to a context for stream filtering used to
1408 * detect whether the duplicate stream has been hard-filtered or not. If
1409 * no streams are hard-filtered or no streams are unhashed, this parameter
1412 * This function will write the streams in @stream_list to resources in
1413 * consecutive positions in the output WIM file, or to a single packed resource
1414 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1415 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1416 * each stream written will be updated to specify its location, size, and flags
1417 * in the output WIM. In the packed resource case,
1418 * WIM_RESHDR_FLAG_PACKED_STREAMS will be set in the @flags field of each
1419 * @out_reshdr, and furthermore @out_res_offset_in_wim and @out_res_size_in_wim
1420 * of each @out_reshdr will be set to the offset and size, respectively, in the
1421 * output WIM of the packed resource containing the corresponding stream.
1423 * Each of the streams to write may be in any location supported by the
1424 * resource-handling code (specifically, read_stream_list()), such as the
1425 * contents of external file that has been logically added to the output WIM, or
1426 * a stream in another WIM file that has been imported, or even a stream in the
1427 * "same" WIM file of which a modified copy is being written. In the case that
1428 * a stream is already in a WIM file and uses compatible compression parameters,
1429 * by default this function will re-use the raw data instead of decompressing
1430 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1431 * specified in @write_resource_flags, this is not done.
1433 * As a further requirement, this function requires that the
1434 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1435 * well as any other streams not in @stream_list that will be in the output WIM
1436 * file, but set to 0 on any other streams in the output WIM's lookup table or
1437 * sharing a packed resource with a stream in @stream_list. Still furthermore,
1438 * if on-the-fly deduplication of streams is possible, then all streams in
1439 * @stream_list must also be linked by @lookup_table_list along with any other
1440 * streams that have @will_be_in_output_wim set.
1442 * This function handles on-the-fly deduplication of streams for which SHA1
1443 * message digests have not yet been calculated. Such streams may or may not
1444 * need to be written. If @lookup_table is non-NULL, then each stream in
1445 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1446 * immediately before it would otherwise be read for writing in order to
1447 * determine if it is identical to another stream already being written or one
1448 * that would be filtered out of the output WIM using stream_filtered() with the
1449 * context @filter_ctx. Each such duplicate stream will be removed from
1450 * @stream_list, its reference count transfered to the pre-existing duplicate
1451 * stream, its memory freed, and will not be written. Alternatively, if a
1452 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1453 * has not been marked for writing or would not be hard-filtered, it is freed
1454 * and the pre-existing duplicate is written instead, taking ownership of the
1455 * reference count and slot in the @lookup_table_list.
1457 * Returns 0 if every stream was either written successfully or did not need to
1458 * be written; otherwise returns a non-zero error code.
1461 write_stream_list(struct list_head *stream_list,
1462 struct filedes *out_fd,
1463 int write_resource_flags,
1466 unsigned num_threads,
1467 struct wim_lookup_table *lookup_table,
1468 struct filter_context *filter_ctx,
1469 wimlib_progress_func_t progfunc,
1473 struct write_streams_ctx ctx;
1474 struct list_head raw_copy_streams;
1476 wimlib_assert((write_resource_flags &
1477 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1478 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1479 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1480 WRITE_RESOURCE_FLAG_PIPABLE));
1482 remove_zero_length_streams(stream_list);
1484 if (list_empty(stream_list)) {
1485 DEBUG("No streams to write.");
1489 memset(&ctx, 0, sizeof(ctx));
1491 /* Pre-sorting the streams is required for compute_stream_list_stats().
1492 * Afterwards, read_stream_list() need not sort them again. */
1493 ret = sort_stream_list_by_sequential_order(stream_list,
1494 offsetof(struct wim_lookup_table_entry,
1495 write_streams_list));
1499 ctx.out_fd = out_fd;
1500 ctx.lookup_table = lookup_table;
1501 ctx.out_ctype = out_ctype;
1502 ctx.out_chunk_size = out_chunk_size;
1503 ctx.write_resource_flags = write_resource_flags;
1504 ctx.filter_ctx = filter_ctx;
1506 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1507 wimlib_assert(out_chunk_size != 0);
1508 if (out_chunk_size <= STACK_MAX) {
1509 ctx.chunk_buf = alloca(out_chunk_size);
1511 ctx.chunk_buf = MALLOC(out_chunk_size);
1512 if (ctx.chunk_buf == NULL) {
1513 ret = WIMLIB_ERR_NOMEM;
1514 goto out_destroy_context;
1518 ctx.chunk_buf_filled = 0;
1520 compute_stream_list_stats(stream_list, &ctx);
1522 ctx.progress_data.progfunc = progfunc;
1523 ctx.progress_data.progctx = progctx;
1525 ctx.num_bytes_to_compress = find_raw_copy_streams(stream_list,
1526 write_resource_flags,
1531 DEBUG("Writing stream list "
1532 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1533 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1534 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1535 out_fd->offset, write_resource_flags,
1536 out_ctype, out_chunk_size, num_threads,
1537 ctx.progress_data.progress.write_streams.total_bytes,
1538 ctx.num_bytes_to_compress);
1540 if (ctx.num_bytes_to_compress == 0) {
1541 DEBUG("No compression needed; skipping to raw copy!");
1542 goto out_write_raw_copy_resources;
1545 /* Unless uncompressed output was required, allocate a chunk_compressor
1546 * to do compression. There are serial and parallel implementations of
1547 * the chunk_compressor interface. We default to parallel using the
1548 * specified number of threads, unless the upper bound on the number
1549 * bytes needing to be compressed is less than a heuristic value. */
1550 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1552 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1553 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1554 ret = new_parallel_chunk_compressor(out_ctype,
1559 DEBUG("Couldn't create parallel chunk compressor "
1560 "(status %d)", ret);
1565 if (ctx.compressor == NULL) {
1566 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1569 goto out_destroy_context;
1574 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1576 ctx.progress_data.progress.write_streams.num_threads = 1;
1578 DEBUG("Actually using %u threads",
1579 ctx.progress_data.progress.write_streams.num_threads);
1581 INIT_LIST_HEAD(&ctx.pending_streams);
1582 INIT_LIST_HEAD(&ctx.pack_streams);
1584 ret = call_progress(ctx.progress_data.progfunc,
1585 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1586 &ctx.progress_data.progress,
1587 ctx.progress_data.progctx);
1589 goto out_destroy_context;
1591 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1592 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1594 goto out_destroy_context;
1597 /* Read the list of streams needing to be compressed, using the
1598 * specified callbacks to execute processing of the data. */
1600 struct read_stream_list_callbacks cbs = {
1601 .begin_stream = write_stream_begin_read,
1602 .begin_stream_ctx = &ctx,
1603 .consume_chunk = write_stream_process_chunk,
1604 .consume_chunk_ctx = &ctx,
1605 .end_stream = write_stream_end_read,
1606 .end_stream_ctx = &ctx,
1609 ret = read_stream_list(stream_list,
1610 offsetof(struct wim_lookup_table_entry, write_streams_list),
1612 STREAM_LIST_ALREADY_SORTED |
1613 VERIFY_STREAM_HASHES |
1614 COMPUTE_MISSING_STREAM_HASHES);
1617 goto out_destroy_context;
1619 ret = finish_remaining_chunks(&ctx);
1621 goto out_destroy_context;
1623 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1624 struct wim_reshdr reshdr;
1625 struct wim_lookup_table_entry *lte;
1628 ret = end_write_resource(&ctx, &reshdr);
1630 goto out_destroy_context;
1632 DEBUG("Ending packed resource: %lu %lu %lu.",
1633 reshdr.offset_in_wim,
1635 reshdr.uncompressed_size);
1638 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1639 lte->out_reshdr.size_in_wim = lte->size;
1640 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1641 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1642 lte->out_reshdr.uncompressed_size = 0;
1643 lte->out_reshdr.offset_in_wim = offset_in_res;
1644 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1645 lte->out_res_size_in_wim = reshdr.size_in_wim;
1646 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1647 offset_in_res += lte->size;
1649 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1652 out_write_raw_copy_resources:
1653 /* Copy any compressed resources for which the raw data can be reused
1654 * without decompression. */
1655 ret = write_raw_copy_resources(&raw_copy_streams, ctx.out_fd,
1656 &ctx.progress_data);
1658 out_destroy_context:
1659 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1660 FREE(ctx.chunk_buf);
1661 FREE(ctx.chunk_csizes);
1663 ctx.compressor->destroy(ctx.compressor);
1664 DEBUG("Done (ret=%d)", ret);
1669 is_stream_packed(struct wim_lookup_table_entry *lte, void *_ignore)
1671 return lte_is_partial(lte);
1675 wim_has_packed_streams(WIMStruct *wim)
1677 return for_lookup_table_entry(wim->lookup_table, is_stream_packed, NULL);
1681 wim_write_stream_list(WIMStruct *wim,
1682 struct list_head *stream_list,
1684 unsigned num_threads,
1685 struct filter_context *filter_ctx)
1689 int write_resource_flags;
1691 write_resource_flags = write_flags_to_resource_flags(write_flags);
1693 /* wimlib v1.7.0: pack streams by default if the WIM version has been
1694 * set to WIM_VERSION_PACKED_STREAMS and at least one stream in the
1695 * WIM's lookup table is located in a packed resource (may be the same
1696 * WIM, or a different one in the case of export). */
1697 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS &&
1698 wim_has_packed_streams(wim))
1700 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
1703 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1704 out_chunk_size = wim->out_pack_chunk_size;
1705 out_ctype = wim->out_pack_compression_type;
1707 out_chunk_size = wim->out_chunk_size;
1708 out_ctype = wim->out_compression_type;
1711 return write_stream_list(stream_list,
1713 write_resource_flags,
1724 write_wim_resource(struct wim_lookup_table_entry *lte,
1725 struct filedes *out_fd,
1728 int write_resource_flags)
1730 LIST_HEAD(stream_list);
1731 list_add(<e->write_streams_list, &stream_list);
1732 lte->will_be_in_output_wim = 1;
1733 return write_stream_list(&stream_list,
1735 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1746 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1747 int reshdr_flags, struct filedes *out_fd,
1750 struct wim_reshdr *out_reshdr,
1752 int write_resource_flags)
1755 struct wim_lookup_table_entry *lte;
1757 /* Set up a temporary lookup table entry to provide to
1758 * write_wim_resource(). */
1760 lte = new_lookup_table_entry();
1762 return WIMLIB_ERR_NOMEM;
1764 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1765 lte->attached_buffer = (void*)buf;
1766 lte->size = buf_size;
1767 lte->flags = reshdr_flags;
1769 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1770 sha1_buffer(buf, buf_size, lte->hash);
1776 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1777 write_resource_flags);
1781 copy_reshdr(out_reshdr, <e->out_reshdr);
1784 copy_hash(hash, lte->hash);
1787 lte->resource_location = RESOURCE_NONEXISTENT;
1788 free_lookup_table_entry(lte);
1792 struct stream_size_table {
1793 struct hlist_head *array;
1799 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1801 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1802 if (tab->array == NULL)
1803 return WIMLIB_ERR_NOMEM;
1804 tab->num_entries = 0;
1805 tab->capacity = capacity;
1810 destroy_stream_size_table(struct stream_size_table *tab)
1816 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1818 struct stream_size_table *tab = _tab;
1820 struct wim_lookup_table_entry *same_size_lte;
1821 struct hlist_node *tmp;
1823 pos = hash_u64(lte->size) % tab->capacity;
1824 lte->unique_size = 1;
1825 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1826 if (same_size_lte->size == lte->size) {
1827 lte->unique_size = 0;
1828 same_size_lte->unique_size = 0;
1833 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1838 struct find_streams_ctx {
1841 struct list_head stream_list;
1842 struct stream_size_table stream_size_tab;
1846 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1847 struct list_head *stream_list, u32 nref)
1849 if (!lte->will_be_in_output_wim) {
1850 lte->out_refcnt = 0;
1851 list_add_tail(<e->write_streams_list, stream_list);
1852 lte->will_be_in_output_wim = 1;
1854 lte->out_refcnt += nref;
1858 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1861 struct list_head *stream_list = _stream_list;
1862 lte->will_be_in_output_wim = 0;
1863 reference_stream_for_write(lte, stream_list, lte->refcnt);
1868 inode_find_streams_to_reference(const struct wim_inode *inode,
1869 const struct wim_lookup_table *table,
1870 struct list_head *stream_list)
1872 struct wim_lookup_table_entry *lte;
1875 wimlib_assert(inode->i_nlink > 0);
1877 for (i = 0; i <= inode->i_num_ads; i++) {
1878 lte = inode_stream_lte(inode, i, table);
1880 reference_stream_for_write(lte, stream_list,
1882 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1883 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1889 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1891 lte->will_be_in_output_wim = 0;
1896 image_find_streams_to_reference(WIMStruct *wim)
1898 struct wim_image_metadata *imd;
1899 struct wim_inode *inode;
1900 struct wim_lookup_table_entry *lte;
1901 struct list_head *stream_list;
1904 imd = wim_get_current_image_metadata(wim);
1906 image_for_each_unhashed_stream(lte, imd)
1907 lte->will_be_in_output_wim = 0;
1909 stream_list = wim->private;
1910 image_for_each_inode(inode, imd) {
1911 ret = inode_find_streams_to_reference(inode,
1921 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1924 struct list_head *stream_list_ret)
1928 INIT_LIST_HEAD(stream_list_ret);
1930 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1931 (image == 1 && wim->hdr.image_count == 1)))
1933 /* Fast case: Assume that all streams are being written and
1934 * that the reference counts are correct. */
1935 struct wim_lookup_table_entry *lte;
1936 struct wim_image_metadata *imd;
1939 for_lookup_table_entry(wim->lookup_table,
1940 fully_reference_stream_for_write,
1943 for (i = 0; i < wim->hdr.image_count; i++) {
1944 imd = wim->image_metadata[i];
1945 image_for_each_unhashed_stream(lte, imd)
1946 fully_reference_stream_for_write(lte, stream_list_ret);
1949 /* Slow case: Walk through the images being written and
1950 * determine the streams referenced. */
1951 for_lookup_table_entry(wim->lookup_table,
1952 do_stream_set_not_in_output_wim, NULL);
1953 wim->private = stream_list_ret;
1954 ret = for_image(wim, image, image_find_streams_to_reference);
1962 struct insert_other_if_hard_filtered_ctx {
1963 struct stream_size_table *tab;
1964 struct filter_context *filter_ctx;
1968 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1970 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1972 if (!lte->will_be_in_output_wim &&
1973 stream_hard_filtered(lte, ctx->filter_ctx))
1974 stream_size_table_insert(lte, ctx->tab);
1979 determine_stream_size_uniquity(struct list_head *stream_list,
1980 struct wim_lookup_table *lt,
1981 struct filter_context *filter_ctx)
1984 struct stream_size_table tab;
1985 struct wim_lookup_table_entry *lte;
1987 ret = init_stream_size_table(&tab, 9001);
1991 if (may_hard_filter_streams(filter_ctx)) {
1992 struct insert_other_if_hard_filtered_ctx ctx = {
1994 .filter_ctx = filter_ctx,
1996 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1999 list_for_each_entry(lte, stream_list, write_streams_list)
2000 stream_size_table_insert(lte, &tab);
2002 destroy_stream_size_table(&tab);
2007 filter_stream_list_for_write(struct list_head *stream_list,
2008 struct filter_context *filter_ctx)
2010 struct wim_lookup_table_entry *lte, *tmp;
2012 list_for_each_entry_safe(lte, tmp,
2013 stream_list, write_streams_list)
2015 int status = stream_filtered(lte, filter_ctx);
2022 /* Soft filtered. */
2024 /* Hard filtered. */
2025 lte->will_be_in_output_wim = 0;
2026 list_del(<e->lookup_table_list);
2028 list_del(<e->write_streams_list);
2034 * prepare_stream_list_for_write() -
2036 * Prepare the list of streams to write for writing a WIM containing the
2037 * specified image(s) with the specified write flags.
2040 * The WIMStruct on whose behalf the write is occurring.
2043 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2046 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2048 * STREAMS_OK: For writes of all images, assume that all streams in the
2049 * lookup table of @wim and the per-image lists of unhashed streams should
2050 * be taken as-is, and image metadata should not be searched for
2051 * references. This does not exclude filtering with OVERWRITE and
2052 * SKIP_EXTERNAL_WIMS, below.
2054 * OVERWRITE: Streams already present in @wim shall not be returned in
2057 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
2058 * @wim, shall be returned in neither @stream_list_ret nor
2059 * @lookup_table_list_ret.
2062 * List of streams, linked by write_streams_list, that need to be written
2063 * will be returned here.
2065 * Note that this function assumes that unhashed streams will be written;
2066 * it does not take into account that they may become duplicates when
2069 * @lookup_table_list_ret
2070 * List of streams, linked by lookup_table_list, that need to be included
2071 * in the WIM's lookup table will be returned here. This will be a
2072 * superset of the streams in @stream_list_ret.
2074 * This list will be a proper superset of @stream_list_ret if and only if
2075 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2076 * the streams that would otherwise need to be written were already located
2079 * All streams in this list will have @out_refcnt set to the number of
2080 * references to the stream in the output WIM. If
2081 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2082 * may be as low as 0.
2085 * A context for queries of stream filter status with stream_filtered() is
2086 * returned in this location.
2088 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
2089 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
2090 * lookup table of @wim not inserted into @lookup_table_list_ret.
2092 * Still furthermore, @unique_size will be set to 1 on all stream entries in
2093 * @stream_list_ret that have unique size among all stream entries in
2094 * @stream_list_ret and among all stream entries in the lookup table of @wim
2095 * that are ineligible for being written due to filtering.
2097 * Returns 0 on success; nonzero on read error, memory allocation error, or
2101 prepare_stream_list_for_write(WIMStruct *wim, int image,
2103 struct list_head *stream_list_ret,
2104 struct list_head *lookup_table_list_ret,
2105 struct filter_context *filter_ctx_ret)
2108 struct wim_lookup_table_entry *lte;
2110 filter_ctx_ret->write_flags = write_flags;
2111 filter_ctx_ret->wim = wim;
2113 ret = prepare_unfiltered_list_of_streams_in_output_wim(
2116 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2121 INIT_LIST_HEAD(lookup_table_list_ret);
2122 list_for_each_entry(lte, stream_list_ret, write_streams_list)
2123 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2125 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
2130 if (may_filter_streams(filter_ctx_ret))
2131 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2137 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2138 unsigned num_threads,
2139 struct list_head *stream_list_override,
2140 struct list_head *lookup_table_list_ret)
2143 struct list_head _stream_list;
2144 struct list_head *stream_list;
2145 struct wim_lookup_table_entry *lte;
2146 struct filter_context _filter_ctx;
2147 struct filter_context *filter_ctx;
2149 if (stream_list_override == NULL) {
2150 /* Normal case: prepare stream list from image(s) being written.
2152 stream_list = &_stream_list;
2153 filter_ctx = &_filter_ctx;
2154 ret = prepare_stream_list_for_write(wim, image, write_flags,
2156 lookup_table_list_ret,
2161 /* Currently only as a result of wimlib_split() being called:
2162 * use stream list already explicitly provided. Use existing
2163 * reference counts. */
2164 stream_list = stream_list_override;
2166 INIT_LIST_HEAD(lookup_table_list_ret);
2167 list_for_each_entry(lte, stream_list, write_streams_list) {
2168 lte->out_refcnt = lte->refcnt;
2169 lte->will_be_in_output_wim = 1;
2170 lte->unique_size = 0;
2171 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2175 /* If needed, set auxiliary information so that we can detect when
2176 * wimlib has finished using each external file. */
2177 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)) {
2178 list_for_each_entry(lte, stream_list, write_streams_list)
2180 lte->back_inode->num_unread_streams = 0;
2181 list_for_each_entry(lte, stream_list, write_streams_list)
2183 lte->back_inode->num_unread_streams++;
2186 return wim_write_stream_list(wim,
2194 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags)
2199 int write_resource_flags;
2201 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2202 DEBUG("Not writing any metadata resources.");
2206 write_resource_flags = write_flags_to_resource_flags(write_flags);
2208 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2210 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2211 wim->out_fd.offset);
2213 ret = call_progress(wim->progfunc,
2214 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2215 NULL, wim->progctx);
2219 if (image == WIMLIB_ALL_IMAGES) {
2221 end_image = wim->hdr.image_count;
2223 start_image = image;
2227 for (int i = start_image; i <= end_image; i++) {
2228 struct wim_image_metadata *imd;
2230 imd = wim->image_metadata[i - 1];
2231 /* Build a new metadata resource only if image was modified from
2232 * the original (or was newly added). Otherwise just copy the
2234 if (imd->modified) {
2235 DEBUG("Image %u was modified; building and writing new "
2236 "metadata resource", i);
2237 ret = write_metadata_resource(wim, i,
2238 write_resource_flags);
2239 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2240 DEBUG("Image %u was not modified; re-using existing "
2241 "metadata resource.", i);
2242 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2245 DEBUG("Image %u was not modified; copying existing "
2246 "metadata resource.", i);
2247 ret = write_wim_resource(imd->metadata_lte,
2249 wim->out_compression_type,
2250 wim->out_chunk_size,
2251 write_resource_flags);
2257 return call_progress(wim->progfunc,
2258 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2259 NULL, wim->progctx);
2263 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2266 DEBUG("Opening \"%"TS"\" for writing.", path);
2268 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2270 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2271 return WIMLIB_ERR_OPEN;
2273 filedes_init(&wim->out_fd, raw_fd);
2278 close_wim_writable(WIMStruct *wim, int write_flags)
2282 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2283 DEBUG("Closing WIM file.");
2284 if (filedes_valid(&wim->out_fd))
2285 if (filedes_close(&wim->out_fd))
2286 ret = WIMLIB_ERR_WRITE;
2288 filedes_invalidate(&wim->out_fd);
2293 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2295 const struct wim_lookup_table_entry *lte1, *lte2;
2297 lte1 = *(const struct wim_lookup_table_entry**)p1;
2298 lte2 = *(const struct wim_lookup_table_entry**)p2;
2300 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2301 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2302 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2303 return cmp_u64(lte1->out_res_offset_in_wim,
2304 lte2->out_res_offset_in_wim);
2309 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2312 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2313 lte2->out_reshdr.offset_in_wim);
2317 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2318 struct wim_reshdr *out_reshdr,
2319 struct list_head *lookup_table_list)
2323 /* Set output resource metadata for streams already present in WIM. */
2324 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2325 struct wim_lookup_table_entry *lte;
2326 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2328 if (lte->resource_location == RESOURCE_IN_WIM &&
2329 lte->rspec->wim == wim)
2331 stream_set_out_reshdr_for_reuse(lte);
2336 ret = sort_stream_list(lookup_table_list,
2337 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2338 cmp_streams_by_out_rspec);
2342 /* Add entries for metadata resources. */
2343 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2347 if (image == WIMLIB_ALL_IMAGES) {
2349 end_image = wim->hdr.image_count;
2351 start_image = image;
2355 /* Push metadata resource lookup table entries onto the front of
2356 * the list in reverse order, so that they're written in order.
2358 for (int i = end_image; i >= start_image; i--) {
2359 struct wim_lookup_table_entry *metadata_lte;
2361 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2362 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2363 metadata_lte->out_refcnt = 1;
2364 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2368 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2370 wim->hdr.part_number,
2372 write_flags_to_resource_flags(write_flags));
2378 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2379 * table, then overwrite the WIM header. By default, closes the WIM file
2380 * descriptor (@wim->out_fd) if successful.
2382 * write_flags is a bitwise OR of the following:
2384 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2385 * Include an integrity table.
2387 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2388 * fsync() the output file before closing it.
2390 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2391 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2392 * stream headers before the lookup table and XML data, and also
2393 * write the WIM header at the end instead of seeking to the
2394 * beginning. Can't be combined with
2395 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2397 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2398 * Don't write the lookup table.
2400 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2401 * After writing the XML data but before writing the integrity
2402 * table, write a temporary WIM header and flush the stream so that
2403 * the WIM is less likely to become corrupted upon abrupt program
2405 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2406 * Instead of overwriting the WIM header at the beginning of the
2407 * file, simply append it to the end of the file. (Used when
2409 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2410 * Do not close the file descriptor @wim->out_fd on either success
2412 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2413 * Use the existing <TOTALBYTES> stored in the in-memory XML
2414 * information, rather than setting it to the offset of the XML
2415 * data being written.
2416 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2417 * The existing WIM file is being updated in-place. The entries
2418 * from its integrity table may be re-used.
2421 finish_write(WIMStruct *wim, int image, int write_flags,
2422 struct list_head *lookup_table_list)
2426 int write_resource_flags;
2427 off_t old_lookup_table_end = 0;
2428 off_t new_lookup_table_end;
2430 struct integrity_table *old_integrity_table = NULL;
2432 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2434 write_resource_flags = write_flags_to_resource_flags(write_flags);
2436 /* In the WIM header, there is room for the resource entry for a
2437 * metadata resource labeled as the "boot metadata". This entry should
2438 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2439 * it should be a copy of the resource entry for the image that is
2440 * marked as bootable. This is not well documented... */
2441 if (wim->hdr.boot_idx == 0) {
2442 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2444 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2445 &wim->image_metadata[
2446 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2449 /* If overwriting the WIM file containing an integrity table in-place,
2450 * we'd like to re-use the information in the old integrity table
2451 * instead of recalculating it. But we might overwrite the old
2452 * integrity table when we expand the XML data. Read it into memory
2454 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2455 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2456 (WIMLIB_WRITE_FLAG_OVERWRITE |
2457 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2458 && wim_has_integrity_table(wim))
2460 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2461 wim->hdr.lookup_table_reshdr.size_in_wim;
2462 (void)read_integrity_table(wim,
2463 old_lookup_table_end - WIM_HEADER_DISK_SIZE,
2464 &old_integrity_table);
2465 /* If we couldn't read the old integrity table, we can still
2466 * re-calculate the full integrity table ourselves. Hence the
2467 * ignoring of the return value. */
2470 /* Write lookup table. */
2471 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2472 ret = write_wim_lookup_table(wim, image, write_flags,
2473 &wim->hdr.lookup_table_reshdr,
2476 free_integrity_table(old_integrity_table);
2481 /* Write XML data. */
2482 xml_totalbytes = wim->out_fd.offset;
2483 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2484 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2485 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2486 &wim->hdr.xml_data_reshdr,
2487 write_resource_flags);
2489 free_integrity_table(old_integrity_table);
2493 /* Write integrity table (optional). */
2494 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2495 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2496 struct wim_header checkpoint_hdr;
2497 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2498 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2499 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2500 ret = write_wim_header_at_offset(&checkpoint_hdr,
2503 free_integrity_table(old_integrity_table);
2508 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2509 wim->hdr.lookup_table_reshdr.size_in_wim;
2511 ret = write_integrity_table(wim,
2512 new_lookup_table_end,
2513 old_lookup_table_end,
2514 old_integrity_table);
2515 free_integrity_table(old_integrity_table);
2519 /* No integrity table. */
2520 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2523 /* Now that all information in the WIM header has been determined, the
2524 * preliminary header written earlier can be overwritten, the header of
2525 * the existing WIM file can be overwritten, or the final header can be
2526 * written to the end of the pipable WIM. */
2527 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2529 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2530 hdr_offset = wim->out_fd.offset;
2531 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2532 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2536 /* Possibly sync file data to disk before closing. On POSIX systems, it
2537 * is necessary to do this before using rename() to overwrite an
2538 * existing file with a new file. Otherwise, data loss would occur if
2539 * the system is abruptly terminated when the metadata for the rename
2540 * operation has been written to disk, but the new file data has not.
2542 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2543 DEBUG("Syncing WIM file.");
2544 if (fsync(wim->out_fd.fd)) {
2545 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2546 return WIMLIB_ERR_WRITE;
2550 if (close_wim_writable(wim, write_flags)) {
2551 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2552 return WIMLIB_ERR_WRITE;
2558 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2560 /* Set advisory lock on WIM file (if not already done so) */
2562 lock_wim_for_append(WIMStruct *wim)
2564 if (wim->locked_for_append)
2566 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2567 wim->locked_for_append = 1;
2570 if (errno != EWOULDBLOCK)
2572 return WIMLIB_ERR_ALREADY_LOCKED;
2575 /* Remove advisory lock on WIM file (if present) */
2577 unlock_wim_for_append(WIMStruct *wim)
2579 if (wim->locked_for_append) {
2580 flock(wim->in_fd.fd, LOCK_UN);
2581 wim->locked_for_append = 0;
2587 * write_pipable_wim():
2589 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2590 * capable of being applied from a pipe).
2592 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2593 * images can be applied from them sequentially when the file data is sent over
2594 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2595 * The modifications made to the WIM format for pipable WIMs are:
2597 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2598 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2599 * stops other software from trying to read the file as a normal WIM.
2601 * - The header at the beginning of the file does not contain all the normal
2602 * information; in particular it will have all 0's for the lookup table and
2603 * XML data resource entries. This is because this information cannot be
2604 * determined until the lookup table and XML data have been written.
2605 * Consequently, wimlib will write the full header at the very end of the
2606 * file. The header at the end, however, is only used when reading the WIM
2607 * from a seekable file (not a pipe).
2609 * - An extra copy of the XML data is placed directly after the header. This
2610 * allows image names and sizes to be determined at an appropriate time when
2611 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2612 * WIM is read from a seekable file (not a pipe).
2614 * - The format of resources, or streams, has been modified to allow them to be
2615 * used before the "lookup table" has been read. Each stream is prefixed with
2616 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2617 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2618 * uncompressed stream size, and flags that indicate whether the stream is
2619 * compressed. The data of uncompressed streams then follows literally, while
2620 * the data of compressed streams follows in a modified format. Compressed
2621 * streams do not begin with a chunk table, since the chunk table cannot be
2622 * written until all chunks have been compressed. Instead, each compressed
2623 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2624 * Furthermore, the chunk table is written at the end of the resource instead
2625 * of the start. Note: chunk offsets are given in the chunk table as if the
2626 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2627 * used if the WIM is being read from a seekable file (not a pipe).
2629 * - Metadata resources always come before other file resources (streams).
2630 * (This does not by itself constitute an incompatibility with normal WIMs,
2631 * since this is valid in normal WIMs.)
2633 * - At least up to the end of the file resources, all components must be packed
2634 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2635 * not by itself consititute an incompatibility with normal WIMs, since this
2636 * is valid in normal WIMs.)
2638 * Note: the lookup table, XML data, and header at the end are not used when
2639 * applying from a pipe. They exist to support functionality such as image
2640 * application and export when the WIM is *not* read from a pipe.
2642 * Layout of pipable WIM:
2644 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2645 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2646 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2648 * Layout of normal WIM:
2650 * +--------+-----------------------------+-------------------------+
2651 * | Header | File and metadata resources | Lookup table | XML data |
2652 * +--------+-----------------------------+-------------------------+
2654 * An optional integrity table can follow the final XML data in both normal and
2655 * pipable WIMs. However, due to implementation details, wimlib currently can
2656 * only include an integrity table in a pipable WIM when writing it to a
2657 * seekable file (not a pipe).
2659 * Do note that since pipable WIMs are not supported by Microsoft's software,
2660 * wimlib does not create them unless explicitly requested (with
2661 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2662 * characters to identify the file.
2665 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2666 unsigned num_threads,
2667 struct list_head *stream_list_override,
2668 struct list_head *lookup_table_list_ret)
2671 struct wim_reshdr xml_reshdr;
2673 WARNING("Creating a pipable WIM, which will "
2675 " with Microsoft's software (wimgapi/imagex/Dism).");
2677 /* At this point, the header at the beginning of the file has already
2680 /* For efficiency, when wimlib adds an image to the WIM with
2681 * wimlib_add_image(), the SHA1 message digests of files is not
2682 * calculated; instead, they are calculated while the files are being
2683 * written. However, this does not work when writing a pipable WIM,
2684 * since when writing a stream to a pipable WIM, its SHA1 message digest
2685 * needs to be known before the stream data is written. Therefore,
2686 * before getting much farther, we need to pre-calculate the SHA1
2687 * message digests of all streams that will be written. */
2688 ret = wim_checksum_unhashed_streams(wim);
2692 /* Write extra copy of the XML data. */
2693 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2695 WRITE_RESOURCE_FLAG_PIPABLE);
2699 /* Write metadata resources for the image(s) being included in the
2701 ret = write_wim_metadata_resources(wim, image, write_flags);
2705 /* Write streams needed for the image(s) being included in the output
2706 * WIM, or streams needed for the split WIM part. */
2707 return write_wim_streams(wim, image, write_flags, num_threads,
2708 stream_list_override, lookup_table_list_ret);
2710 /* The lookup table, XML data, and header at end are handled by
2711 * finish_write(). */
2714 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2717 write_wim_part(WIMStruct *wim,
2718 const void *path_or_fd,
2721 unsigned num_threads,
2722 unsigned part_number,
2723 unsigned total_parts,
2724 struct list_head *stream_list_override,
2728 struct wim_header hdr_save;
2729 struct list_head lookup_table_list;
2731 if (total_parts == 1)
2732 DEBUG("Writing standalone WIM.");
2734 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2735 if (image == WIMLIB_ALL_IMAGES)
2736 DEBUG("Including all images.");
2738 DEBUG("Including image %d only.", image);
2739 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2740 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2742 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2743 DEBUG("Write flags: 0x%08x", write_flags);
2745 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2746 DEBUG("\tCHECK_INTEGRITY");
2748 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2749 DEBUG("\tNO_CHECK_INTEGRITY");
2751 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2754 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2755 DEBUG("\tNOT_PIPABLE");
2757 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2758 DEBUG("\tRECOMPRESS");
2760 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2763 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2766 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2767 DEBUG("\tSOFT_DELETE");
2769 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2770 DEBUG("\tIGNORE_READONLY_FLAG");
2772 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2773 DEBUG("\tSKIP_EXTERNAL_WIMS");
2775 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2776 DEBUG("\tSTREAMS_OK");
2778 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2779 DEBUG("\tRETAIN_GUID");
2781 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2782 DEBUG("\tPACK_STREAMS");
2784 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2785 DEBUG("\tFILE_DESCRIPTOR");
2787 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2788 DEBUG("\tNO_METADATA");
2790 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2791 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2793 if (num_threads == 0)
2794 DEBUG("Number of threads: autodetect");
2796 DEBUG("Number of threads: %u", num_threads);
2797 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2798 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2799 DEBUG("GUID: %s", (write_flags &
2800 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2801 : guid ? "explicit" : "generate new");
2803 /* Internally, this is always called with a valid part number and total
2805 wimlib_assert(total_parts >= 1);
2806 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2808 /* A valid image (or all images) must be specified. */
2809 if (image != WIMLIB_ALL_IMAGES &&
2810 (image < 1 || image > wim->hdr.image_count))
2811 return WIMLIB_ERR_INVALID_IMAGE;
2813 /* If we need to write metadata resources, make sure the ::WIMStruct has
2814 * the needed information attached (e.g. is not a resource-only WIM,
2815 * such as a non-first part of a split WIM). */
2816 if (!wim_has_metadata(wim) &&
2817 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2818 return WIMLIB_ERR_METADATA_NOT_FOUND;
2820 /* Check for contradictory flags. */
2821 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2822 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2823 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2824 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2825 return WIMLIB_ERR_INVALID_PARAM;
2827 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2828 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2829 == (WIMLIB_WRITE_FLAG_PIPABLE |
2830 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2831 return WIMLIB_ERR_INVALID_PARAM;
2833 /* Save previous header, then start initializing the new one. */
2834 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2836 /* Set default integrity, pipable, and packed stream flags. */
2837 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2838 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2839 if (wim_is_pipable(wim)) {
2840 DEBUG("WIM is pipable; default to PIPABLE.");
2841 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2844 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2845 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2846 if (wim_has_integrity_table(wim)) {
2847 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2848 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2851 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2852 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2853 == (WIMLIB_WRITE_FLAG_PIPABLE |
2854 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2856 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2857 return WIMLIB_ERR_INVALID_PARAM;
2860 /* Set appropriate magic number. */
2861 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2862 wim->hdr.magic = PWM_MAGIC;
2864 wim->hdr.magic = WIM_MAGIC;
2866 /* Set appropriate version number. */
2867 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2868 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2869 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2871 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2873 /* Clear header flags that will be set automatically. */
2874 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2875 WIM_HDR_FLAG_RESOURCE_ONLY |
2876 WIM_HDR_FLAG_SPANNED |
2877 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2879 /* Set SPANNED header flag if writing part of a split WIM. */
2880 if (total_parts != 1)
2881 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2883 /* Set part number and total parts of split WIM. This will be 1 and 1
2884 * if the WIM is standalone. */
2885 wim->hdr.part_number = part_number;
2886 wim->hdr.total_parts = total_parts;
2888 /* Set compression type if different. */
2889 if (wim->compression_type != wim->out_compression_type) {
2890 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2891 wimlib_assert(ret == 0);
2894 /* Set chunk size if different. */
2895 wim->hdr.chunk_size = wim->out_chunk_size;
2898 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2900 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2902 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2905 /* Clear references to resources that have not been written yet. */
2906 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2907 zero_reshdr(&wim->hdr.xml_data_reshdr);
2908 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2909 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2911 /* Set image count and boot index correctly for single image writes. */
2912 if (image != WIMLIB_ALL_IMAGES) {
2913 wim->hdr.image_count = 1;
2914 if (wim->hdr.boot_idx == image)
2915 wim->hdr.boot_idx = 1;
2917 wim->hdr.boot_idx = 0;
2920 /* Split WIMs can't be bootable. */
2921 if (total_parts != 1)
2922 wim->hdr.boot_idx = 0;
2924 /* Initialize output file descriptor. */
2925 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2926 /* File descriptor was explicitly provided. Return error if
2927 * file descriptor is not seekable, unless writing a pipable WIM
2929 wim->out_fd.fd = *(const int*)path_or_fd;
2930 wim->out_fd.offset = 0;
2931 if (!filedes_is_seekable(&wim->out_fd)) {
2932 ret = WIMLIB_ERR_INVALID_PARAM;
2933 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2934 goto out_restore_hdr;
2935 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2936 ERROR("Can't include integrity check when "
2937 "writing pipable WIM to pipe!");
2938 goto out_restore_hdr;
2943 /* Filename of WIM to write was provided; open file descriptor
2945 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2946 O_TRUNC | O_CREAT | O_RDWR);
2948 goto out_restore_hdr;
2951 /* Write initial header. This is merely a "dummy" header since it
2952 * doesn't have all the information yet, so it will be overwritten later
2953 * (unless writing a pipable WIM). */
2954 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2955 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2956 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2957 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2959 goto out_restore_hdr;
2961 /* Write metadata resources and streams. */
2962 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2963 /* Default case: create a normal (non-pipable) WIM. */
2964 ret = write_wim_streams(wim, image, write_flags, num_threads,
2965 stream_list_override,
2966 &lookup_table_list);
2968 goto out_restore_hdr;
2970 ret = write_wim_metadata_resources(wim, image, write_flags);
2972 goto out_restore_hdr;
2974 /* Non-default case: create pipable WIM. */
2975 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2976 stream_list_override,
2977 &lookup_table_list);
2979 goto out_restore_hdr;
2980 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2984 /* Write lookup table, XML data, and (optional) integrity table. */
2985 ret = finish_write(wim, image, write_flags, &lookup_table_list);
2987 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2988 (void)close_wim_writable(wim, write_flags);
2989 DEBUG("ret=%d", ret);
2993 /* Write a standalone WIM to a file or file descriptor. */
2995 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2996 int image, int write_flags, unsigned num_threads)
2998 return write_wim_part(wim, path_or_fd, image, write_flags,
2999 num_threads, 1, 1, NULL, NULL);
3002 /* API function documented in wimlib.h */
3004 wimlib_write(WIMStruct *wim, const tchar *path,
3005 int image, int write_flags, unsigned num_threads)
3007 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3008 return WIMLIB_ERR_INVALID_PARAM;
3010 if (path == NULL || path[0] == T('\0'))
3011 return WIMLIB_ERR_INVALID_PARAM;
3013 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3016 /* API function documented in wimlib.h */
3018 wimlib_write_to_fd(WIMStruct *wim, int fd,
3019 int image, int write_flags, unsigned num_threads)
3021 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3022 return WIMLIB_ERR_INVALID_PARAM;
3025 return WIMLIB_ERR_INVALID_PARAM;
3027 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3029 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3033 any_images_modified(WIMStruct *wim)
3035 for (int i = 0; i < wim->hdr.image_count; i++)
3036 if (wim->image_metadata[i]->modified)
3042 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
3044 const WIMStruct *wim = _wim;
3045 off_t end_offset = *(const off_t*)wim->private;
3047 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
3048 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
3049 return WIMLIB_ERR_RESOURCE_ORDER;
3053 /* Make sure no file or metadata resources are located after the XML data (or
3054 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3055 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3057 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3062 wim->private = &end_offset;
3063 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
3067 for (i = 0; i < wim->hdr.image_count; i++) {
3068 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
3076 * Overwrite a WIM, possibly appending streams to it.
3078 * A WIM looks like (or is supposed to look like) the following:
3080 * Header (212 bytes)
3081 * Streams and metadata resources (variable size)
3082 * Lookup table (variable size)
3083 * XML data (variable size)
3084 * Integrity table (optional) (variable size)
3086 * If we are not adding any streams or metadata resources, the lookup table is
3087 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3088 * header. This operation is potentially unsafe if the program is abruptly
3089 * terminated while the XML data or integrity table are being overwritten, but
3090 * before the new header has been written. To partially alleviate this problem,
3091 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3092 * finish_write() to cause a temporary WIM header to be written after the XML
3093 * data has been written. This may prevent the WIM from becoming corrupted if
3094 * the program is terminated while the integrity table is being calculated (but
3095 * no guarantees, due to write re-ordering...).
3097 * If we are adding new streams or images (metadata resources), the lookup table
3098 * needs to be changed, and those streams need to be written. In this case, we
3099 * try to perform a safe update of the WIM file by writing the streams *after*
3100 * the end of the previous WIM, then writing the new lookup table, XML data, and
3101 * (optionally) integrity table following the new streams. This will produce a
3102 * layout like the following:
3104 * Header (212 bytes)
3105 * (OLD) Streams and metadata resources (variable size)
3106 * (OLD) Lookup table (variable size)
3107 * (OLD) XML data (variable size)
3108 * (OLD) Integrity table (optional) (variable size)
3109 * (NEW) Streams and metadata resources (variable size)
3110 * (NEW) Lookup table (variable size)
3111 * (NEW) XML data (variable size)
3112 * (NEW) Integrity table (optional) (variable size)
3114 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3115 * the header is overwritten to point to the new lookup table, XML data, and
3116 * integrity table, to produce the following layout:
3118 * Header (212 bytes)
3119 * Streams and metadata resources (variable size)
3120 * Nothing (variable size)
3121 * More Streams and metadata resources (variable size)
3122 * Lookup table (variable size)
3123 * XML data (variable size)
3124 * Integrity table (optional) (variable size)
3126 * This method allows an image to be appended to a large WIM very quickly, and
3127 * is crash-safe except in the case of write re-ordering, but the
3128 * disadvantage is that a small hole is left in the WIM where the old lookup
3129 * table, xml data, and integrity table were. (These usually only take up a
3130 * small amount of space compared to the streams, however.)
3133 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3137 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
3138 struct wim_header hdr_save;
3139 struct list_head stream_list;
3140 struct list_head lookup_table_list;
3141 struct filter_context filter_ctx;
3143 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3145 /* Save original header so it can be restored in case of error */
3146 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3148 /* Set default integrity flag. */
3149 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3150 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3151 if (wim_has_integrity_table(wim))
3152 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3154 /* Set WIM version if adding packed streams. */
3155 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
3156 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
3158 /* Set additional flags for overwrite. */
3159 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3160 WIMLIB_WRITE_FLAG_STREAMS_OK;
3162 /* Make sure that the integrity table (if present) is after the XML
3163 * data, and that there are no stream resources, metadata resources, or
3164 * lookup tables after the XML data. Otherwise, these data would be
3166 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3167 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3168 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
3169 wim->hdr.lookup_table_reshdr.size_in_wim;
3170 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3171 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3172 WARNING("Didn't expect the integrity table to be before the XML data");
3173 ret = WIMLIB_ERR_RESOURCE_ORDER;
3174 goto out_restore_memory_hdr;
3177 if (old_lookup_table_end > old_xml_begin) {
3178 WARNING("Didn't expect the lookup table to be after the XML data");
3179 ret = WIMLIB_ERR_RESOURCE_ORDER;
3180 goto out_restore_memory_hdr;
3183 /* Set @old_wim_end, which indicates the point beyond which we don't
3184 * allow any file and metadata resources to appear without returning
3185 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3186 * overwrite these resources). */
3187 if (!wim->deletion_occurred && !any_images_modified(wim)) {
3188 /* If no images have been modified and no images have been
3189 * deleted, a new lookup table does not need to be written. We
3190 * shall write the new XML data and optional integrity table
3191 * immediately after the lookup table. Note that this may
3192 * overwrite an existing integrity table. */
3193 DEBUG("Skipping writing lookup table "
3194 "(no images modified or deleted)");
3195 old_wim_end = old_lookup_table_end;
3196 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3197 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3198 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3199 /* Old WIM has an integrity table; begin writing new streams
3201 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3202 wim->hdr.integrity_table_reshdr.size_in_wim;
3204 /* No existing integrity table; begin writing new streams after
3205 * the old XML data. */
3206 old_wim_end = old_xml_end;
3209 ret = check_resource_offsets(wim, old_wim_end);
3211 goto out_restore_memory_hdr;
3213 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3214 &stream_list, &lookup_table_list,
3217 goto out_restore_memory_hdr;
3219 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3221 goto out_restore_memory_hdr;
3223 ret = lock_wim_for_append(wim);
3227 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3228 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3229 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3231 ERROR_WITH_ERRNO("Error updating WIM header flags");
3232 goto out_unlock_wim;
3235 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3236 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3237 ret = WIMLIB_ERR_WRITE;
3238 goto out_restore_physical_hdr;
3241 ret = wim_write_stream_list(wim,
3249 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3253 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3254 &lookup_table_list);
3258 unlock_wim_for_append(wim);
3262 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3263 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3264 wim->filename, old_wim_end);
3265 /* Return value of ftruncate() is ignored because this is
3266 * already an error path. */
3267 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3269 out_restore_physical_hdr:
3270 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3272 unlock_wim_for_append(wim);
3274 (void)close_wim_writable(wim, write_flags);
3275 out_restore_memory_hdr:
3276 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3281 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3283 size_t wim_name_len;
3286 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3288 /* Write the WIM to a temporary file in the same directory as the
3290 wim_name_len = tstrlen(wim->filename);
3291 tchar tmpfile[wim_name_len + 10];
3292 tmemcpy(tmpfile, wim->filename, wim_name_len);
3293 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3294 tmpfile[wim_name_len + 9] = T('\0');
3296 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3298 WIMLIB_WRITE_FLAG_FSYNC |
3299 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3306 if (filedes_valid(&wim->in_fd)) {
3307 filedes_close(&wim->in_fd);
3308 filedes_invalidate(&wim->in_fd);
3311 /* Rename the new WIM file to the original WIM file. Note: on Windows
3312 * this actually calls win32_rename_replacement(), not _wrename(), so
3313 * that removing the existing destination file can be handled. */
3314 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3315 ret = trename(tmpfile, wim->filename);
3317 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3318 tmpfile, wim->filename);
3325 return WIMLIB_ERR_RENAME;
3328 union wimlib_progress_info progress;
3329 progress.rename.from = tmpfile;
3330 progress.rename.to = wim->filename;
3331 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3332 &progress, wim->progctx);
3335 /* Determine if the specified WIM file may be updated by appending in-place
3336 * rather than writing and replacing it with an entirely new file. */
3338 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3340 /* REBUILD flag forces full rebuild. */
3341 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3344 /* Deletions cause full rebuild by default. */
3345 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3348 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3349 * turned into a pipable WIM in-place. */
3350 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3353 /* The default compression type and compression chunk size selected for
3354 * the output WIM must be the same as those currently used for the WIM.
3356 if (wim->compression_type != wim->out_compression_type)
3358 if (wim->chunk_size != wim->out_chunk_size)
3364 /* API function documented in wimlib.h */
3366 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3371 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3372 return WIMLIB_ERR_INVALID_PARAM;
3375 return WIMLIB_ERR_NO_FILENAME;
3377 orig_hdr_flags = wim->hdr.flags;
3378 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3379 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3380 ret = can_modify_wim(wim);
3381 wim->hdr.flags = orig_hdr_flags;
3385 if (can_overwrite_wim_inplace(wim, write_flags)) {
3386 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3387 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3389 WARNING("Falling back to re-building entire WIM");
3391 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);