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 free software; you can redistribute it and/or modify it under
12 * the terms of the GNU Lesser General Public License as published by the Free
13 * Software Foundation; either version 3 of the License, or (at your option) any
16 * This file is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this file; if not, see http://www.gnu.org/licenses/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
31 * overwrite the LIST_HEAD macro. */
32 # include <sys/file.h>
35 #include "wimlib/chunk_compressor.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/file_io.h"
39 #include "wimlib/header.h"
40 #include "wimlib/inode.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/lookup_table.h"
43 #include "wimlib/metadata.h"
44 #include "wimlib/paths.h"
45 #include "wimlib/progress.h"
46 #include "wimlib/resource.h"
48 # include "wimlib/win32.h" /* win32_rename_replacement() */
50 #include "wimlib/write.h"
51 #include "wimlib/xml.h"
62 /* wimlib internal flags used when writing resources. */
63 #define WRITE_RESOURCE_FLAG_RECOMPRESS 0x00000001
64 #define WRITE_RESOURCE_FLAG_PIPABLE 0x00000002
65 #define WRITE_RESOURCE_FLAG_PACK_STREAMS 0x00000004
66 #define WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE 0x00000008
69 write_flags_to_resource_flags(int write_flags)
71 int write_resource_flags = 0;
73 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
74 write_resource_flags |= WRITE_RESOURCE_FLAG_RECOMPRESS;
75 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
76 write_resource_flags |= WRITE_RESOURCE_FLAG_PIPABLE;
77 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
78 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
79 if (write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)
80 write_resource_flags |= WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE;
81 return write_resource_flags;
84 struct filter_context {
89 /* Determine specified stream should be filtered out from the write.
93 * < 0 : The stream should be hard-filtered; that is, not included in the
95 * 0 : The stream should not be filtered out.
96 * > 0 : The stream should be soft-filtered; that is, it already exists in the
97 * WIM file and may not need to be written again.
100 stream_filtered(const struct wim_lookup_table_entry *lte,
101 const struct filter_context *ctx)
109 write_flags = ctx->write_flags;
112 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
113 lte->resource_location == RESOURCE_IN_WIM &&
114 lte->rspec->wim == wim)
117 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
118 lte->resource_location == RESOURCE_IN_WIM &&
119 lte->rspec->wim != wim)
126 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
127 struct filter_context *ctx)
129 return stream_filtered(lte, ctx) < 0;
133 may_soft_filter_streams(const struct filter_context *ctx)
137 return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
141 may_hard_filter_streams(const struct filter_context *ctx)
145 return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
149 may_filter_streams(const struct filter_context *ctx)
151 return (may_soft_filter_streams(ctx) ||
152 may_hard_filter_streams(ctx));
156 /* Return true if the specified resource is compressed and the compressed data
157 * can be reused with the specified output parameters. */
159 can_raw_copy(const struct wim_lookup_table_entry *lte,
160 int write_resource_flags, int out_ctype, u32 out_chunk_size)
162 const struct wim_resource_spec *rspec;
164 if (write_resource_flags & WRITE_RESOURCE_FLAG_RECOMPRESS)
167 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
170 if (lte->resource_location != RESOURCE_IN_WIM)
175 if (rspec->is_pipable != !!(write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE))
178 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
179 /* Normal compressed resource: Must use same compression type
181 return (rspec->compression_type == out_ctype &&
182 rspec->chunk_size == out_chunk_size);
185 if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
186 (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
188 /* Packed resource: Such resources may contain multiple streams,
189 * and in general only a subset of them need to be written. As
190 * a heuristic, re-use the raw data if more than two-thirds the
191 * uncompressed size is being written. */
193 /* Note: packed resources contain a header that specifies the
194 * compression type and chunk size; therefore we don't need to
195 * check if they are compatible with @out_ctype and
196 * @out_chunk_size. */
198 struct wim_lookup_table_entry *res_stream;
201 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
202 if (res_stream->will_be_in_output_wim)
203 write_size += res_stream->size;
205 return (write_size > rspec->uncompressed_size * 2 / 3);
212 filter_resource_flags(u8 flags)
214 return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
215 WIM_RESHDR_FLAG_COMPRESSED |
216 WIM_RESHDR_FLAG_SPANNED |
217 WIM_RESHDR_FLAG_FREE));
221 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
223 const struct wim_resource_spec *rspec;
225 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
228 if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
230 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
232 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
233 lte->out_reshdr.uncompressed_size = 0;
234 lte->out_reshdr.size_in_wim = lte->size;
236 lte->out_res_offset_in_wim = rspec->offset_in_wim;
237 lte->out_res_size_in_wim = rspec->size_in_wim;
238 lte->out_res_uncompressed_size = rspec->uncompressed_size;
240 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
242 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
243 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
244 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
246 lte->out_reshdr.flags = lte->flags;
250 /* Write the header for a stream in a pipable WIM. */
252 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
253 struct filedes *out_fd,
254 int additional_reshdr_flags)
256 struct pwm_stream_hdr stream_hdr;
260 stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
261 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
262 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
263 zero_out_hash(stream_hdr.hash);
265 wimlib_assert(!lte->unhashed);
266 copy_hash(stream_hdr.hash, lte->hash);
269 reshdr_flags = filter_resource_flags(lte->flags);
270 reshdr_flags |= additional_reshdr_flags;
271 stream_hdr.flags = cpu_to_le32(reshdr_flags);
272 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
274 ERROR_WITH_ERRNO("Write error");
278 struct write_streams_progress_data {
279 wimlib_progress_func_t progfunc;
281 union wimlib_progress_info progress;
282 uint64_t next_progress;
286 do_write_streams_progress(struct write_streams_progress_data *progress_data,
287 struct wim_lookup_table_entry *cur_stream,
292 union wimlib_progress_info *progress = &progress_data->progress;
296 progress->write_streams.total_bytes -= complete_size;
297 progress->write_streams.total_streams -= complete_count;
298 if (progress_data->next_progress != ~(uint64_t)0 &&
299 progress_data->next_progress > progress->write_streams.total_bytes)
301 progress_data->next_progress = progress->write_streams.total_bytes;
304 progress->write_streams.completed_bytes += complete_size;
305 progress->write_streams.completed_streams += complete_count;
308 if (progress->write_streams.completed_bytes >= progress_data->next_progress)
310 ret = call_progress(progress_data->progfunc,
311 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
313 progress_data->progctx);
317 if (progress_data->next_progress == progress->write_streams.total_bytes) {
318 progress_data->next_progress = ~(uint64_t)0;
320 /* Handle rate-limiting of messages */
322 /* Send new message as soon as another 1/128 of the
323 * total has been written. (Arbitrary number.) */
324 progress_data->next_progress =
325 progress->write_streams.completed_bytes +
326 progress->write_streams.total_bytes / 128;
328 /* ... Unless that would be more than 5000000 bytes, in
329 * which case send the next after the next 5000000
330 * bytes. (Another arbitrary number.) */
331 if (progress->write_streams.completed_bytes + 5000000 <
332 progress_data->next_progress)
333 progress_data->next_progress =
334 progress->write_streams.completed_bytes + 5000000;
336 /* ... But always send a message as soon as we're
337 * completely done. */
338 if (progress->write_streams.total_bytes <
339 progress_data->next_progress)
340 progress_data->next_progress =
341 progress->write_streams.total_bytes;
347 struct write_streams_ctx {
348 /* File descriptor the streams are being written to. */
349 struct filedes *out_fd;
351 /* Lookup table for the WIMStruct on whose behalf the streams are being
353 struct wim_lookup_table *lookup_table;
355 /* Compression format to use. */
358 /* Maximum uncompressed chunk size in compressed resources to use. */
361 /* Flags that affect how the streams will be written. */
362 int write_resource_flags;
364 /* Data used for issuing WRITE_STREAMS progress. */
365 struct write_streams_progress_data progress_data;
367 struct filter_context *filter_ctx;
369 /* Upper bound on the total number of bytes that need to be compressed.
371 u64 num_bytes_to_compress;
373 /* Pointer to the chunk_compressor implementation being used for
374 * compressing chunks of data, or NULL if chunks are being written
376 struct chunk_compressor *compressor;
378 /* Buffer for dividing the read data into chunks of size
379 * @out_chunk_size. */
382 /* Number of bytes in @chunk_buf that are currently filled. */
383 size_t chunk_buf_filled;
385 /* List of streams that currently have chunks being compressed. */
386 struct list_head pending_streams;
388 /* List of streams in the resource pack. Streams are moved here after
389 * @pending_streams only when writing a packed resource. */
390 struct list_head pack_streams;
392 /* Set to true if the stream currently being read was a duplicate, and
393 * therefore the corresponding stream entry needs to be freed once the
394 * read finishes. (In this case we add the duplicate entry to
395 * pending_streams rather than the entry being read.) */
396 bool stream_was_duplicate;
398 struct wim_inode *stream_inode;
400 /* Current uncompressed offset in the stream being read. */
401 u64 cur_read_stream_offset;
403 /* Uncompressed size of the stream currently being read. */
404 u64 cur_read_stream_size;
406 /* Current uncompressed offset in the stream being written. */
407 u64 cur_write_stream_offset;
409 /* Uncompressed size of resource currently being written. */
410 u64 cur_write_res_size;
412 /* Array that is filled in with compressed chunk sizes as a resource is
416 /* Index of next entry in @chunk_csizes to fill in. */
419 /* Number of entries in @chunk_csizes currently allocated. */
420 size_t num_alloc_chunks;
422 /* Offset in the output file of the start of the chunks of the resource
423 * currently being written. */
424 u64 chunks_start_offset;
427 /* Reserve space for the chunk table and prepare to accumulate the chunk table
430 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
432 u64 expected_num_chunks;
433 u64 expected_num_chunk_entries;
437 /* Calculate the number of chunks and chunk entries that should be
438 * needed for the resource. These normally will be the final values,
439 * but in PACKED_STREAMS mode some of the streams we're planning to
440 * write into the resource may be duplicates, and therefore discarded,
441 * potentially decreasing the number of chunk entries needed. */
442 expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
443 expected_num_chunk_entries = expected_num_chunks;
444 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
445 expected_num_chunk_entries--;
447 /* Make sure the chunk_csizes array is long enough to store the
448 * compressed size of each chunk. */
449 if (expected_num_chunks > ctx->num_alloc_chunks) {
450 u64 new_length = expected_num_chunks + 50;
452 if ((size_t)new_length != new_length) {
453 ERROR("Resource size too large (%"PRIu64" bytes!",
455 return WIMLIB_ERR_NOMEM;
458 FREE(ctx->chunk_csizes);
459 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
460 if (ctx->chunk_csizes == NULL) {
461 ctx->num_alloc_chunks = 0;
462 return WIMLIB_ERR_NOMEM;
464 ctx->num_alloc_chunks = new_length;
467 ctx->chunk_index = 0;
469 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE)) {
470 /* Reserve space for the chunk table in the output file. In the
471 * case of packed resources this reserves the upper bound for
472 * the needed space, not necessarily the exact space which will
473 * prove to be needed. At this point, we just use @chunk_csizes
474 * for a buffer of 0's because the actual compressed chunk sizes
476 reserve_size = expected_num_chunk_entries *
477 get_chunk_entry_size(res_expected_size,
478 0 != (ctx->write_resource_flags &
479 WRITE_RESOURCE_FLAG_PACK_STREAMS));
480 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
481 reserve_size += sizeof(struct alt_chunk_table_header_disk);
482 memset(ctx->chunk_csizes, 0, reserve_size);
483 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
491 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
495 wimlib_assert(res_expected_size != 0);
497 if (ctx->compressor != NULL) {
498 ret = begin_chunk_table(ctx, res_expected_size);
503 /* Output file descriptor is now positioned at the offset at which to
504 * write the first chunk of the resource. */
505 ctx->chunks_start_offset = ctx->out_fd->offset;
506 ctx->cur_write_stream_offset = 0;
507 ctx->cur_write_res_size = res_expected_size;
512 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
513 u64 *res_start_offset_ret, u64 *res_store_size_ret)
515 size_t actual_num_chunks;
516 size_t actual_num_chunk_entries;
517 size_t chunk_entry_size;
520 actual_num_chunks = ctx->chunk_index;
521 actual_num_chunk_entries = actual_num_chunks;
522 if (!(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
523 actual_num_chunk_entries--;
525 chunk_entry_size = get_chunk_entry_size(res_actual_size,
526 0 != (ctx->write_resource_flags &
527 WRITE_RESOURCE_FLAG_PACK_STREAMS));
529 typedef le64 __attribute__((may_alias)) aliased_le64_t;
530 typedef le32 __attribute__((may_alias)) aliased_le32_t;
532 if (chunk_entry_size == 4) {
533 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
535 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
536 for (size_t i = 0; i < actual_num_chunk_entries; i++)
537 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
539 u32 offset = ctx->chunk_csizes[0];
540 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
541 u32 next_size = ctx->chunk_csizes[i + 1];
542 entries[i] = cpu_to_le32(offset);
547 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
549 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
550 for (size_t i = 0; i < actual_num_chunk_entries; i++)
551 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
553 u64 offset = ctx->chunk_csizes[0];
554 for (size_t i = 0; i < actual_num_chunk_entries; i++) {
555 u64 next_size = ctx->chunk_csizes[i + 1];
556 entries[i] = cpu_to_le64(offset);
562 size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
563 u64 res_start_offset;
566 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
567 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
570 res_end_offset = ctx->out_fd->offset;
571 res_start_offset = ctx->chunks_start_offset;
573 res_end_offset = ctx->out_fd->offset;
575 u64 chunk_table_offset;
577 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
579 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
580 struct alt_chunk_table_header_disk hdr;
582 hdr.res_usize = cpu_to_le64(res_actual_size);
583 hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
584 hdr.compression_format = cpu_to_le32(ctx->out_ctype);
586 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
587 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
588 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
590 ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
591 chunk_table_offset - sizeof(hdr));
594 res_start_offset = chunk_table_offset - sizeof(hdr);
596 res_start_offset = chunk_table_offset;
599 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
600 chunk_table_size, chunk_table_offset);
605 *res_start_offset_ret = res_start_offset;
606 *res_store_size_ret = res_end_offset - res_start_offset;
611 ERROR_WITH_ERRNO("Write error");
615 /* Finish writing a WIM resource by writing or updating the chunk table (if not
616 * writing the data uncompressed) and loading its metadata into @out_reshdr. */
618 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
622 u64 res_uncompressed_size;
623 u64 res_offset_in_wim;
625 wimlib_assert(ctx->cur_write_stream_offset == ctx->cur_write_res_size ||
626 (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS));
627 res_uncompressed_size = ctx->cur_write_res_size;
629 if (ctx->compressor) {
630 ret = end_chunk_table(ctx, res_uncompressed_size,
631 &res_offset_in_wim, &res_size_in_wim);
635 res_offset_in_wim = ctx->chunks_start_offset;
636 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
638 out_reshdr->uncompressed_size = res_uncompressed_size;
639 out_reshdr->size_in_wim = res_size_in_wim;
640 out_reshdr->offset_in_wim = res_offset_in_wim;
641 DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
642 res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
646 /* No more data streams of the file at @path are needed. */
648 done_with_file(const tchar *path, wimlib_progress_func_t progfunc, void *progctx)
650 union wimlib_progress_info info;
652 info.done_with_file.path_to_file = path;
654 return call_progress(progfunc, WIMLIB_PROGRESS_MSG_DONE_WITH_FILE,
658 /* Handle WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES mode. */
660 done_with_stream(struct wim_lookup_table_entry *stream,
661 wimlib_progress_func_t progfunc, void *progctx,
662 struct wim_inode *inode)
664 if (stream->resource_location == RESOURCE_IN_FILE_ON_DISK
666 || stream->resource_location == RESOURCE_IN_WINNT_FILE_ON_DISK
667 || stream->resource_location == RESOURCE_WIN32_ENCRYPTED
673 wimlib_assert(inode->num_unread_streams > 0);
674 if (--inode->num_unread_streams > 0)
678 /* XXX: This logic really should be somewhere else. */
680 /* We want the path to the file, but stream->file_on_disk might
681 * actually refer to a named data stream. Temporarily strip the
682 * named data stream from the path. */
683 wchar_t *p_colon = NULL;
684 wchar_t *p_question_mark = NULL;
685 const wchar_t *p_stream_name;
687 p_stream_name = path_stream_name(stream->file_on_disk);
688 if (unlikely(p_stream_name)) {
689 p_colon = (wchar_t *)(p_stream_name - 1);
690 wimlib_assert(*p_colon == L':');
694 /* We also should use a fake Win32 path instead of a NT path */
695 if (!wcsncmp(stream->file_on_disk, L"\\??\\", 4)) {
696 p_question_mark = &stream->file_on_disk[1];
697 *p_question_mark = L'\\';
701 ret = done_with_file(stream->file_on_disk, progfunc, progctx);
707 *p_question_mark = L'?';
714 /* Begin processing a stream for writing. */
716 write_stream_begin_read(struct wim_lookup_table_entry *lte, void *_ctx)
718 struct write_streams_ctx *ctx = _ctx;
721 wimlib_assert(lte->size > 0);
723 ctx->cur_read_stream_offset = 0;
724 ctx->cur_read_stream_size = lte->size;
727 ctx->stream_inode = lte->back_inode;
729 ctx->stream_inode = NULL;
731 /* As an optimization, we allow some streams to be "unhashed", meaning
732 * their SHA1 message digests are unknown. This is the case with
733 * streams that are added by scanning a directry tree with
734 * wimlib_add_image(), for example. Since WIM uses single-instance
735 * streams, we don't know whether such each such stream really need to
736 * written until it is actually checksummed, unless it has a unique
737 * size. In such cases we read and checksum the stream in this
738 * function, thereby advancing ahead of read_stream_list(), which will
739 * still provide the data again to write_stream_process_chunk(). This
740 * is okay because an unhashed stream cannot be in a WIM resource, which
741 * might be costly to decompress. */
742 ctx->stream_was_duplicate = false;
743 if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
745 struct wim_lookup_table_entry *lte_new;
747 ret = hash_unhashed_stream(lte, ctx->lookup_table, <e_new);
750 if (lte_new != lte) {
751 /* Duplicate stream detected. */
753 if (lte_new->will_be_in_output_wim ||
754 stream_filtered(lte_new, ctx->filter_ctx))
756 /* The duplicate stream is already being
757 * included in the output WIM, or it would be
758 * filtered out if it had been. Skip writing
759 * this stream (and reading it again) entirely,
760 * passing its output reference count to the
761 * duplicate stream in the former case. */
762 DEBUG("Discarding duplicate stream of "
763 "length %"PRIu64, lte->size);
764 ret = do_write_streams_progress(&ctx->progress_data,
767 list_del(<e->write_streams_list);
768 list_del(<e->lookup_table_list);
769 if (lte_new->will_be_in_output_wim)
770 lte_new->out_refcnt += lte->out_refcnt;
771 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS)
772 ctx->cur_write_res_size -= lte->size;
773 if (!ret && unlikely(ctx->write_resource_flags &
774 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE))
776 ret = done_with_stream(lte,
777 ctx->progress_data.progfunc,
778 ctx->progress_data.progctx,
781 free_lookup_table_entry(lte);
784 return BEGIN_STREAM_STATUS_SKIP_STREAM;
786 /* The duplicate stream can validly be written,
787 * but was not marked as such. Discard the
788 * current stream entry and use the duplicate,
789 * but actually freeing the current entry must
790 * wait until read_stream_list() has finished
791 * reading its data. */
792 DEBUG("Stream duplicate, but not already "
793 "selected for writing.");
794 list_replace(<e->write_streams_list,
795 <e_new->write_streams_list);
796 list_replace(<e->lookup_table_list,
797 <e_new->lookup_table_list);
798 lte_new->out_refcnt = lte->out_refcnt;
799 lte_new->will_be_in_output_wim = 1;
800 ctx->stream_was_duplicate = true;
805 list_move_tail(<e->write_streams_list, &ctx->pending_streams);
809 /* Rewrite a stream that was just written compressed as uncompressed instead.
810 * This function is optional, but if a stream did not compress to less than its
811 * original size, it might as well be written uncompressed. */
813 write_stream_uncompressed(struct wim_lookup_table_entry *lte,
814 struct filedes *out_fd)
817 u64 begin_offset = lte->out_reshdr.offset_in_wim;
818 u64 end_offset = out_fd->offset;
820 if (filedes_seek(out_fd, begin_offset) == -1)
823 ret = extract_full_stream_to_fd(lte, out_fd);
825 /* Error reading the uncompressed data. */
826 if (out_fd->offset == begin_offset &&
827 filedes_seek(out_fd, end_offset) != -1)
829 /* Nothing was actually written yet, and we successfully
830 * seeked to the end of the compressed resource, so
831 * don't issue a hard error; just keep the compressed
832 * resource instead. */
833 WARNING("Recovered compressed stream of "
834 "size %"PRIu64", continuing on.",
841 wimlib_assert(out_fd->offset - begin_offset == lte->size);
843 if (out_fd->offset < end_offset &&
844 0 != ftruncate(out_fd->fd, out_fd->offset))
846 ERROR_WITH_ERRNO("Can't truncate output file to "
847 "offset %"PRIu64, out_fd->offset);
848 return WIMLIB_ERR_WRITE;
851 lte->out_reshdr.size_in_wim = lte->size;
852 lte->out_reshdr.flags &= ~(WIM_RESHDR_FLAG_COMPRESSED |
853 WIM_RESHDR_FLAG_PACKED_STREAMS);
857 /* Write the next chunk of (typically compressed) data to the output WIM,
858 * handling the writing of the chunk table. */
860 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
861 size_t csize, size_t usize)
865 struct wim_lookup_table_entry *lte;
866 u32 completed_stream_count;
869 lte = list_entry(ctx->pending_streams.next,
870 struct wim_lookup_table_entry, write_streams_list);
872 if (ctx->cur_write_stream_offset == 0 &&
873 !(ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS))
875 /* Starting to write a new stream in non-packed mode. */
877 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
878 int additional_reshdr_flags = 0;
879 if (ctx->compressor != NULL)
880 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
882 DEBUG("Writing pipable WIM stream header "
883 "(offset=%"PRIu64")", ctx->out_fd->offset);
885 ret = write_pwm_stream_header(lte, ctx->out_fd,
886 additional_reshdr_flags);
891 ret = begin_write_resource(ctx, lte->size);
896 if (ctx->compressor != NULL) {
897 /* Record the compresed chunk size. */
898 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
899 ctx->chunk_csizes[ctx->chunk_index++] = csize;
901 /* If writing a pipable WIM, before the chunk data write a chunk
902 * header that provides the compressed chunk size. */
903 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
904 struct pwm_chunk_hdr chunk_hdr = {
905 .compressed_size = cpu_to_le32(csize),
907 ret = full_write(ctx->out_fd, &chunk_hdr,
914 /* Write the chunk data. */
915 ret = full_write(ctx->out_fd, cchunk, csize);
919 ctx->cur_write_stream_offset += usize;
921 completed_size = usize;
922 completed_stream_count = 0;
923 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
924 /* Wrote chunk in packed mode. It may have finished multiple
926 while (ctx->cur_write_stream_offset > lte->size) {
927 struct wim_lookup_table_entry *next;
929 ctx->cur_write_stream_offset -= lte->size;
931 wimlib_assert(!list_is_singular(&ctx->pending_streams) &&
932 !list_empty(&ctx->pending_streams));
933 next = list_entry(lte->write_streams_list.next,
934 struct wim_lookup_table_entry,
936 list_move_tail(<e->write_streams_list,
939 completed_stream_count++;
941 if (ctx->cur_write_stream_offset == lte->size) {
942 ctx->cur_write_stream_offset = 0;
943 list_move_tail(<e->write_streams_list,
945 completed_stream_count++;
948 /* Wrote chunk in non-packed mode. It may have finished a
950 if (ctx->cur_write_stream_offset == lte->size) {
952 completed_stream_count++;
954 list_del(<e->write_streams_list);
956 wimlib_assert(ctx->cur_write_stream_offset ==
957 ctx->cur_write_res_size);
959 ret = end_write_resource(ctx, <e->out_reshdr);
963 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
964 if (ctx->compressor != NULL)
965 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
967 if (ctx->compressor != NULL &&
968 lte->out_reshdr.size_in_wim >= lte->out_reshdr.uncompressed_size &&
969 !(ctx->write_resource_flags & (WRITE_RESOURCE_FLAG_PIPABLE |
970 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE)) &&
971 !(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
973 /* Stream did not compress to less than its original
974 * size. If we're not writing a pipable WIM (which
975 * could mean the output file descriptor is
976 * non-seekable), and the stream isn't located in a
977 * resource pack (which would make reading it again
978 * costly), truncate the file to the start of the stream
979 * and write it uncompressed instead. */
980 DEBUG("Stream of size %"PRIu64" did not compress to "
981 "less than original size; writing uncompressed.",
983 ret = write_stream_uncompressed(lte, ctx->out_fd);
987 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
989 ctx->cur_write_stream_offset = 0;
993 return do_write_streams_progress(&ctx->progress_data, lte,
994 completed_size, completed_stream_count,
998 ERROR_WITH_ERRNO("Write error");
1003 submit_chunk_for_compression(struct write_streams_ctx *ctx,
1004 const void *chunk, size_t size)
1006 /* While we are unable to submit the chunk for compression (due to too
1007 * many chunks already outstanding), retrieve and write the next
1008 * compressed chunk. */
1009 while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
1016 bret = ctx->compressor->get_chunk(ctx->compressor,
1017 &cchunk, &csize, &usize);
1019 wimlib_assert(bret);
1021 ret = write_chunk(ctx, cchunk, csize, usize);
1028 /* Process the next chunk of data to be written to a WIM resource. */
1030 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
1032 struct write_streams_ctx *ctx = _ctx;
1034 const u8 *chunkptr, *chunkend;
1036 wimlib_assert(size != 0);
1038 if (ctx->compressor == NULL) {
1039 /* Write chunk uncompressed. */
1040 ret = write_chunk(ctx, chunk, size, size);
1043 ctx->cur_read_stream_offset += size;
1047 /* Submit the chunk for compression, but take into account that the
1048 * @size the chunk was provided in may not correspond to the
1049 * @out_chunk_size being used for compression. */
1051 chunkend = chunkptr + size;
1053 const u8 *resized_chunk;
1054 size_t needed_chunk_size;
1056 if (ctx->write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1057 needed_chunk_size = ctx->out_chunk_size;
1059 u64 res_bytes_remaining;
1061 res_bytes_remaining = ctx->cur_read_stream_size -
1062 ctx->cur_read_stream_offset;
1063 needed_chunk_size = min(ctx->out_chunk_size,
1064 ctx->chunk_buf_filled +
1065 res_bytes_remaining);
1068 if (ctx->chunk_buf_filled == 0 &&
1069 chunkend - chunkptr >= needed_chunk_size)
1071 /* No intermediate buffering needed. */
1072 resized_chunk = chunkptr;
1073 chunkptr += needed_chunk_size;
1074 ctx->cur_read_stream_offset += needed_chunk_size;
1076 /* Intermediate buffering needed. */
1077 size_t bytes_consumed;
1079 bytes_consumed = min(chunkend - chunkptr,
1080 needed_chunk_size - ctx->chunk_buf_filled);
1082 memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
1083 chunkptr, bytes_consumed);
1085 chunkptr += bytes_consumed;
1086 ctx->cur_read_stream_offset += bytes_consumed;
1087 ctx->chunk_buf_filled += bytes_consumed;
1088 if (ctx->chunk_buf_filled == needed_chunk_size) {
1089 resized_chunk = ctx->chunk_buf;
1090 ctx->chunk_buf_filled = 0;
1097 ret = submit_chunk_for_compression(ctx, resized_chunk,
1102 } while (chunkptr != chunkend);
1106 /* Finish processing a stream for writing. It may not have been completely
1107 * written yet, as the chunk_compressor implementation may still have chunks
1108 * buffered or being compressed. */
1110 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1112 struct write_streams_ctx *ctx = _ctx;
1116 wimlib_assert(ctx->cur_read_stream_offset == ctx->cur_read_stream_size);
1118 if (unlikely(ctx->write_resource_flags &
1119 WRITE_RESOURCE_FLAG_SEND_DONE_WITH_FILE) &&
1120 ctx->stream_inode != NULL)
1122 status = done_with_stream(lte,
1123 ctx->progress_data.progfunc,
1124 ctx->progress_data.progctx,
1128 if (!ctx->stream_was_duplicate && lte->unhashed &&
1129 ctx->lookup_table != NULL)
1131 list_del(<e->unhashed_list);
1132 lookup_table_insert(ctx->lookup_table, lte);
1136 if (ctx->stream_was_duplicate)
1137 free_lookup_table_entry(lte);
1141 /* Compute statistics about a list of streams that will be written.
1143 * Assumes the streams are sorted such that all streams located in each distinct
1144 * WIM (specified by WIMStruct) are together. */
1146 compute_stream_list_stats(struct list_head *stream_list,
1147 struct write_streams_ctx *ctx)
1149 struct wim_lookup_table_entry *lte;
1150 u64 total_bytes = 0;
1151 u64 num_streams = 0;
1152 u64 total_parts = 0;
1153 WIMStruct *prev_wim_part = NULL;
1155 list_for_each_entry(lte, stream_list, write_streams_list) {
1157 total_bytes += lte->size;
1158 if (lte->resource_location == RESOURCE_IN_WIM) {
1159 if (prev_wim_part != lte->rspec->wim) {
1160 prev_wim_part = lte->rspec->wim;
1165 ctx->progress_data.progress.write_streams.total_bytes = total_bytes;
1166 ctx->progress_data.progress.write_streams.total_streams = num_streams;
1167 ctx->progress_data.progress.write_streams.completed_bytes = 0;
1168 ctx->progress_data.progress.write_streams.completed_streams = 0;
1169 ctx->progress_data.progress.write_streams.compression_type = ctx->out_ctype;
1170 ctx->progress_data.progress.write_streams.total_parts = total_parts;
1171 ctx->progress_data.progress.write_streams.completed_parts = 0;
1172 ctx->progress_data.next_progress = 0;
1175 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1176 * rather than compressed. Delete these streams from @stream_list and move them
1177 * to @raw_copy_streams. Return the total uncompressed size of the streams that
1178 * need to be compressed. */
1180 find_raw_copy_streams(struct list_head *stream_list,
1181 int write_resource_flags,
1184 struct list_head *raw_copy_streams)
1186 struct wim_lookup_table_entry *lte, *tmp;
1187 u64 num_bytes_to_compress = 0;
1189 INIT_LIST_HEAD(raw_copy_streams);
1191 /* Initialize temporary raw_copy_ok flag. */
1192 list_for_each_entry(lte, stream_list, write_streams_list)
1193 if (lte->resource_location == RESOURCE_IN_WIM)
1194 lte->rspec->raw_copy_ok = 0;
1196 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1197 if (lte->resource_location == RESOURCE_IN_WIM &&
1198 lte->rspec->raw_copy_ok)
1200 list_move_tail(<e->write_streams_list,
1202 } else if (can_raw_copy(lte, write_resource_flags,
1203 out_ctype, out_chunk_size))
1205 lte->rspec->raw_copy_ok = 1;
1206 list_move_tail(<e->write_streams_list,
1209 num_bytes_to_compress += lte->size;
1213 return num_bytes_to_compress;
1216 /* Copy a raw compressed resource located in another WIM file to the WIM file
1219 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1220 struct filedes *out_fd)
1222 u64 cur_read_offset;
1223 u64 end_read_offset;
1224 u8 buf[BUFFER_SIZE];
1225 size_t bytes_to_read;
1227 struct filedes *in_fd;
1228 struct wim_lookup_table_entry *lte;
1229 u64 out_offset_in_wim;
1231 DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1232 "uncompressed_size=%"PRIu64")",
1233 in_rspec->size_in_wim, in_rspec->uncompressed_size);
1235 /* Copy the raw data. */
1236 cur_read_offset = in_rspec->offset_in_wim;
1237 end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1239 out_offset_in_wim = out_fd->offset;
1241 if (in_rspec->is_pipable) {
1242 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1243 return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1244 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1245 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1247 in_fd = &in_rspec->wim->in_fd;
1248 wimlib_assert(cur_read_offset != end_read_offset);
1251 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1253 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1257 ret = full_write(out_fd, buf, bytes_to_read);
1261 cur_read_offset += bytes_to_read;
1263 } while (cur_read_offset != end_read_offset);
1265 list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1266 if (lte->will_be_in_output_wim) {
1267 stream_set_out_reshdr_for_reuse(lte);
1268 if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1269 lte->out_res_offset_in_wim = out_offset_in_wim;
1271 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1278 /* Copy a list of raw compressed resources located in other WIM file(s) to the
1279 * WIM file being written. */
1281 write_raw_copy_resources(struct list_head *raw_copy_streams,
1282 struct filedes *out_fd,
1283 struct write_streams_progress_data *progress_data)
1285 struct wim_lookup_table_entry *lte;
1288 list_for_each_entry(lte, raw_copy_streams, write_streams_list)
1289 lte->rspec->raw_copy_ok = 1;
1291 list_for_each_entry(lte, raw_copy_streams, write_streams_list) {
1292 if (lte->rspec->raw_copy_ok) {
1293 /* Write each packed resource only one time, no matter
1294 * how many streams reference it. */
1295 ret = write_raw_copy_resource(lte->rspec, out_fd);
1298 lte->rspec->raw_copy_ok = 0;
1300 ret = do_write_streams_progress(progress_data, lte, lte->size,
1308 /* Wait for and write all chunks pending in the compressor. */
1310 finish_remaining_chunks(struct write_streams_ctx *ctx)
1317 if (ctx->compressor == NULL)
1320 if (ctx->chunk_buf_filled != 0) {
1321 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1322 ctx->chunk_buf_filled);
1327 while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1328 ret = write_chunk(ctx, cdata, csize, usize);
1336 remove_zero_length_streams(struct list_head *stream_list)
1338 struct wim_lookup_table_entry *lte, *tmp;
1340 list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1341 wimlib_assert(lte->will_be_in_output_wim);
1342 if (lte->size == 0) {
1343 list_del(<e->write_streams_list);
1344 lte->out_reshdr.offset_in_wim = 0;
1345 lte->out_reshdr.size_in_wim = 0;
1346 lte->out_reshdr.uncompressed_size = 0;
1347 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1353 * Write a list of streams to the output WIM file.
1356 * The list of streams to write, specified by a list of `struct
1357 * wim_lookup_table_entry's linked by the 'write_streams_list' member.
1360 * The file descriptor, opened for writing, to which to write the streams.
1362 * @write_resource_flags
1363 * Flags to modify how the streams are written:
1365 * WRITE_RESOURCE_FLAG_RECOMPRESS:
1366 * Force compression of all resources, even if they could otherwise
1367 * be re-used by copying the raw data, due to being located in a WIM
1368 * file with compatible compression parameters.
1370 * WRITE_RESOURCE_FLAG_PIPABLE:
1371 * Write the resources in the wimlib-specific pipable format, and
1372 * furthermore do so in such a way that no seeking backwards in
1373 * @out_fd will be performed (so it may be a pipe).
1375 * WRITE_RESOURCE_FLAG_PACK_STREAMS:
1376 * Pack all the streams into a single resource rather than writing
1377 * them in separate resources. This flag is only valid if the WIM
1378 * version number has been, or will be, set to
1379 * WIM_VERSION_PACKED_STREAMS. This flag may not be combined with
1380 * WRITE_RESOURCE_FLAG_PIPABLE.
1383 * Compression format to use to write the output streams, specified as one
1384 * of the WIMLIB_COMPRESSION_TYPE_* constants.
1385 * WIMLIB_COMPRESSION_TYPE_NONE is allowed.
1388 * Chunk size to use to write the streams. It must be a valid chunk size
1389 * for the specified compression format @out_ctype, unless @out_ctype is
1390 * WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1393 * Number of threads to use to compress data. If 0, a default number of
1394 * threads will be chosen. The number of threads still may be decreased
1395 * from the specified value if insufficient memory is detected.
1398 * If on-the-fly deduplication of unhashed streams is desired, this
1399 * parameter must be pointer to the lookup table for the WIMStruct on whose
1400 * behalf the streams are being written. Otherwise, this parameter can be
1404 * If on-the-fly deduplication of unhashed streams is desired, this
1405 * parameter can be a pointer to a context for stream filtering used to
1406 * detect whether the duplicate stream has been hard-filtered or not. If
1407 * no streams are hard-filtered or no streams are unhashed, this parameter
1410 * This function will write the streams in @stream_list to resources in
1411 * consecutive positions in the output WIM file, or to a single packed resource
1412 * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1413 * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1414 * each stream written will be updated to specify its location, size, and flags
1415 * in the output WIM. In the packed resource case,
1416 * WIM_RESHDR_FLAG_PACKED_STREAMS will be set in the @flags field of each
1417 * @out_reshdr, and furthermore @out_res_offset_in_wim and @out_res_size_in_wim
1418 * of each @out_reshdr will be set to the offset and size, respectively, in the
1419 * output WIM of the packed resource containing the corresponding stream.
1421 * Each of the streams to write may be in any location supported by the
1422 * resource-handling code (specifically, read_stream_list()), such as the
1423 * contents of external file that has been logically added to the output WIM, or
1424 * a stream in another WIM file that has been imported, or even a stream in the
1425 * "same" WIM file of which a modified copy is being written. In the case that
1426 * a stream is already in a WIM file and uses compatible compression parameters,
1427 * by default this function will re-use the raw data instead of decompressing
1428 * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1429 * specified in @write_resource_flags, this is not done.
1431 * As a further requirement, this function requires that the
1432 * @will_be_in_output_wim member be set to 1 on all streams in @stream_list as
1433 * well as any other streams not in @stream_list that will be in the output WIM
1434 * file, but set to 0 on any other streams in the output WIM's lookup table or
1435 * sharing a packed resource with a stream in @stream_list. Still furthermore,
1436 * if on-the-fly deduplication of streams is possible, then all streams in
1437 * @stream_list must also be linked by @lookup_table_list along with any other
1438 * streams that have @will_be_in_output_wim set.
1440 * This function handles on-the-fly deduplication of streams for which SHA1
1441 * message digests have not yet been calculated. Such streams may or may not
1442 * need to be written. If @lookup_table is non-NULL, then each stream in
1443 * @stream_list that has @unhashed set but not @unique_size set is checksummed
1444 * immediately before it would otherwise be read for writing in order to
1445 * determine if it is identical to another stream already being written or one
1446 * that would be filtered out of the output WIM using stream_filtered() with the
1447 * context @filter_ctx. Each such duplicate stream will be removed from
1448 * @stream_list, its reference count transfered to the pre-existing duplicate
1449 * stream, its memory freed, and will not be written. Alternatively, if a
1450 * stream in @stream_list is a duplicate with any stream in @lookup_table that
1451 * has not been marked for writing or would not be hard-filtered, it is freed
1452 * and the pre-existing duplicate is written instead, taking ownership of the
1453 * reference count and slot in the @lookup_table_list.
1455 * Returns 0 if every stream was either written successfully or did not need to
1456 * be written; otherwise returns a non-zero error code.
1459 write_stream_list(struct list_head *stream_list,
1460 struct filedes *out_fd,
1461 int write_resource_flags,
1464 unsigned num_threads,
1465 struct wim_lookup_table *lookup_table,
1466 struct filter_context *filter_ctx,
1467 wimlib_progress_func_t progfunc,
1471 struct write_streams_ctx ctx;
1472 struct list_head raw_copy_streams;
1474 wimlib_assert((write_resource_flags &
1475 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1476 WRITE_RESOURCE_FLAG_PIPABLE)) !=
1477 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1478 WRITE_RESOURCE_FLAG_PIPABLE));
1480 remove_zero_length_streams(stream_list);
1482 if (list_empty(stream_list)) {
1483 DEBUG("No streams to write.");
1487 memset(&ctx, 0, sizeof(ctx));
1489 /* Pre-sorting the streams is required for compute_stream_list_stats().
1490 * Afterwards, read_stream_list() need not sort them again. */
1491 ret = sort_stream_list_by_sequential_order(stream_list,
1492 offsetof(struct wim_lookup_table_entry,
1493 write_streams_list));
1497 ctx.out_fd = out_fd;
1498 ctx.lookup_table = lookup_table;
1499 ctx.out_ctype = out_ctype;
1500 ctx.out_chunk_size = out_chunk_size;
1501 ctx.write_resource_flags = write_resource_flags;
1502 ctx.filter_ctx = filter_ctx;
1504 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1505 wimlib_assert(out_chunk_size != 0);
1506 if (out_chunk_size <= STACK_MAX) {
1507 ctx.chunk_buf = alloca(out_chunk_size);
1509 ctx.chunk_buf = MALLOC(out_chunk_size);
1510 if (ctx.chunk_buf == NULL) {
1511 ret = WIMLIB_ERR_NOMEM;
1512 goto out_destroy_context;
1516 ctx.chunk_buf_filled = 0;
1518 compute_stream_list_stats(stream_list, &ctx);
1520 ctx.progress_data.progfunc = progfunc;
1521 ctx.progress_data.progctx = progctx;
1523 ctx.num_bytes_to_compress = find_raw_copy_streams(stream_list,
1524 write_resource_flags,
1529 DEBUG("Writing stream list "
1530 "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1531 "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1532 "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1533 out_fd->offset, write_resource_flags,
1534 out_ctype, out_chunk_size, num_threads,
1535 ctx.progress_data.progress.write_streams.total_bytes,
1536 ctx.num_bytes_to_compress);
1538 if (ctx.num_bytes_to_compress == 0) {
1539 DEBUG("No compression needed; skipping to raw copy!");
1540 goto out_write_raw_copy_resources;
1543 /* Unless uncompressed output was required, allocate a chunk_compressor
1544 * to do compression. There are serial and parallel implementations of
1545 * the chunk_compressor interface. We default to parallel using the
1546 * specified number of threads, unless the upper bound on the number
1547 * bytes needing to be compressed is less than a heuristic value. */
1548 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1550 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1551 if (ctx.num_bytes_to_compress > max(2000000, out_chunk_size)) {
1552 ret = new_parallel_chunk_compressor(out_ctype,
1557 DEBUG("Couldn't create parallel chunk compressor "
1558 "(status %d)", ret);
1563 if (ctx.compressor == NULL) {
1564 ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1567 goto out_destroy_context;
1572 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1574 ctx.progress_data.progress.write_streams.num_threads = 1;
1576 DEBUG("Actually using %u threads",
1577 ctx.progress_data.progress.write_streams.num_threads);
1579 INIT_LIST_HEAD(&ctx.pending_streams);
1580 INIT_LIST_HEAD(&ctx.pack_streams);
1582 ret = call_progress(ctx.progress_data.progfunc,
1583 WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1584 &ctx.progress_data.progress,
1585 ctx.progress_data.progctx);
1587 goto out_destroy_context;
1589 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1590 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1592 goto out_destroy_context;
1595 /* Read the list of streams needing to be compressed, using the
1596 * specified callbacks to execute processing of the data. */
1598 struct read_stream_list_callbacks cbs = {
1599 .begin_stream = write_stream_begin_read,
1600 .begin_stream_ctx = &ctx,
1601 .consume_chunk = write_stream_process_chunk,
1602 .consume_chunk_ctx = &ctx,
1603 .end_stream = write_stream_end_read,
1604 .end_stream_ctx = &ctx,
1607 ret = read_stream_list(stream_list,
1608 offsetof(struct wim_lookup_table_entry, write_streams_list),
1610 STREAM_LIST_ALREADY_SORTED |
1611 VERIFY_STREAM_HASHES |
1612 COMPUTE_MISSING_STREAM_HASHES);
1615 goto out_destroy_context;
1617 ret = finish_remaining_chunks(&ctx);
1619 goto out_destroy_context;
1621 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1622 struct wim_reshdr reshdr;
1623 struct wim_lookup_table_entry *lte;
1626 ret = end_write_resource(&ctx, &reshdr);
1628 goto out_destroy_context;
1630 DEBUG("Ending packed resource: %lu %lu %lu.",
1631 reshdr.offset_in_wim,
1633 reshdr.uncompressed_size);
1636 list_for_each_entry(lte, &ctx.pack_streams, write_streams_list) {
1637 lte->out_reshdr.size_in_wim = lte->size;
1638 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1639 lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1640 lte->out_reshdr.uncompressed_size = 0;
1641 lte->out_reshdr.offset_in_wim = offset_in_res;
1642 lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1643 lte->out_res_size_in_wim = reshdr.size_in_wim;
1644 lte->out_res_uncompressed_size = reshdr.uncompressed_size;
1645 offset_in_res += lte->size;
1647 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1650 out_write_raw_copy_resources:
1651 /* Copy any compressed resources for which the raw data can be reused
1652 * without decompression. */
1653 ret = write_raw_copy_resources(&raw_copy_streams, ctx.out_fd,
1654 &ctx.progress_data);
1656 out_destroy_context:
1657 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1658 FREE(ctx.chunk_buf);
1659 FREE(ctx.chunk_csizes);
1661 ctx.compressor->destroy(ctx.compressor);
1662 DEBUG("Done (ret=%d)", ret);
1667 is_stream_packed(struct wim_lookup_table_entry *lte, void *_ignore)
1669 return lte_is_partial(lte);
1673 wim_has_packed_streams(WIMStruct *wim)
1675 return for_lookup_table_entry(wim->lookup_table, is_stream_packed, NULL);
1679 wim_write_stream_list(WIMStruct *wim,
1680 struct list_head *stream_list,
1682 unsigned num_threads,
1683 struct filter_context *filter_ctx)
1687 int write_resource_flags;
1689 write_resource_flags = write_flags_to_resource_flags(write_flags);
1691 /* wimlib v1.7.0: pack streams by default if the WIM version has been
1692 * set to WIM_VERSION_PACKED_STREAMS and at least one stream in the
1693 * WIM's lookup table is located in a packed resource (may be the same
1694 * WIM, or a different one in the case of export). */
1695 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS &&
1696 wim_has_packed_streams(wim))
1698 write_resource_flags |= WRITE_RESOURCE_FLAG_PACK_STREAMS;
1701 if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1702 out_chunk_size = wim->out_pack_chunk_size;
1703 out_ctype = wim->out_pack_compression_type;
1705 out_chunk_size = wim->out_chunk_size;
1706 out_ctype = wim->out_compression_type;
1709 return write_stream_list(stream_list,
1711 write_resource_flags,
1722 write_wim_resource(struct wim_lookup_table_entry *lte,
1723 struct filedes *out_fd,
1726 int write_resource_flags)
1728 LIST_HEAD(stream_list);
1729 list_add(<e->write_streams_list, &stream_list);
1730 lte->will_be_in_output_wim = 1;
1731 return write_stream_list(&stream_list,
1733 write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1744 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1745 int reshdr_flags, struct filedes *out_fd,
1748 struct wim_reshdr *out_reshdr,
1750 int write_resource_flags)
1753 struct wim_lookup_table_entry *lte;
1755 /* Set up a temporary lookup table entry to provide to
1756 * write_wim_resource(). */
1758 lte = new_lookup_table_entry();
1760 return WIMLIB_ERR_NOMEM;
1762 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1763 lte->attached_buffer = (void*)buf;
1764 lte->size = buf_size;
1765 lte->flags = reshdr_flags;
1767 if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1768 sha1_buffer(buf, buf_size, lte->hash);
1774 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1775 write_resource_flags);
1779 copy_reshdr(out_reshdr, <e->out_reshdr);
1782 copy_hash(hash, lte->hash);
1785 lte->resource_location = RESOURCE_NONEXISTENT;
1786 free_lookup_table_entry(lte);
1790 struct stream_size_table {
1791 struct hlist_head *array;
1797 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1799 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1800 if (tab->array == NULL)
1801 return WIMLIB_ERR_NOMEM;
1802 tab->num_entries = 0;
1803 tab->capacity = capacity;
1808 destroy_stream_size_table(struct stream_size_table *tab)
1814 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1816 struct stream_size_table *tab = _tab;
1818 struct wim_lookup_table_entry *same_size_lte;
1819 struct hlist_node *tmp;
1821 pos = hash_u64(lte->size) % tab->capacity;
1822 lte->unique_size = 1;
1823 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1824 if (same_size_lte->size == lte->size) {
1825 lte->unique_size = 0;
1826 same_size_lte->unique_size = 0;
1831 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1836 struct find_streams_ctx {
1839 struct list_head stream_list;
1840 struct stream_size_table stream_size_tab;
1844 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1845 struct list_head *stream_list, u32 nref)
1847 if (!lte->will_be_in_output_wim) {
1848 lte->out_refcnt = 0;
1849 list_add_tail(<e->write_streams_list, stream_list);
1850 lte->will_be_in_output_wim = 1;
1852 lte->out_refcnt += nref;
1856 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1859 struct list_head *stream_list = _stream_list;
1860 lte->will_be_in_output_wim = 0;
1861 reference_stream_for_write(lte, stream_list, lte->refcnt);
1866 inode_find_streams_to_reference(const struct wim_inode *inode,
1867 const struct wim_lookup_table *table,
1868 struct list_head *stream_list)
1870 struct wim_lookup_table_entry *lte;
1873 wimlib_assert(inode->i_nlink > 0);
1875 for (i = 0; i <= inode->i_num_ads; i++) {
1876 lte = inode_stream_lte(inode, i, table);
1878 reference_stream_for_write(lte, stream_list,
1880 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1881 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1887 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1889 lte->will_be_in_output_wim = 0;
1894 image_find_streams_to_reference(WIMStruct *wim)
1896 struct wim_image_metadata *imd;
1897 struct wim_inode *inode;
1898 struct wim_lookup_table_entry *lte;
1899 struct list_head *stream_list;
1902 imd = wim_get_current_image_metadata(wim);
1904 image_for_each_unhashed_stream(lte, imd)
1905 lte->will_be_in_output_wim = 0;
1907 stream_list = wim->private;
1908 image_for_each_inode(inode, imd) {
1909 ret = inode_find_streams_to_reference(inode,
1919 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1922 struct list_head *stream_list_ret)
1926 INIT_LIST_HEAD(stream_list_ret);
1928 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1929 (image == 1 && wim->hdr.image_count == 1)))
1931 /* Fast case: Assume that all streams are being written and
1932 * that the reference counts are correct. */
1933 struct wim_lookup_table_entry *lte;
1934 struct wim_image_metadata *imd;
1937 for_lookup_table_entry(wim->lookup_table,
1938 fully_reference_stream_for_write,
1941 for (i = 0; i < wim->hdr.image_count; i++) {
1942 imd = wim->image_metadata[i];
1943 image_for_each_unhashed_stream(lte, imd)
1944 fully_reference_stream_for_write(lte, stream_list_ret);
1947 /* Slow case: Walk through the images being written and
1948 * determine the streams referenced. */
1949 for_lookup_table_entry(wim->lookup_table,
1950 do_stream_set_not_in_output_wim, NULL);
1951 wim->private = stream_list_ret;
1952 ret = for_image(wim, image, image_find_streams_to_reference);
1960 struct insert_other_if_hard_filtered_ctx {
1961 struct stream_size_table *tab;
1962 struct filter_context *filter_ctx;
1966 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1968 struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1970 if (!lte->will_be_in_output_wim &&
1971 stream_hard_filtered(lte, ctx->filter_ctx))
1972 stream_size_table_insert(lte, ctx->tab);
1977 determine_stream_size_uniquity(struct list_head *stream_list,
1978 struct wim_lookup_table *lt,
1979 struct filter_context *filter_ctx)
1982 struct stream_size_table tab;
1983 struct wim_lookup_table_entry *lte;
1985 ret = init_stream_size_table(&tab, 9001);
1989 if (may_hard_filter_streams(filter_ctx)) {
1990 struct insert_other_if_hard_filtered_ctx ctx = {
1992 .filter_ctx = filter_ctx,
1994 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1997 list_for_each_entry(lte, stream_list, write_streams_list)
1998 stream_size_table_insert(lte, &tab);
2000 destroy_stream_size_table(&tab);
2005 filter_stream_list_for_write(struct list_head *stream_list,
2006 struct filter_context *filter_ctx)
2008 struct wim_lookup_table_entry *lte, *tmp;
2010 list_for_each_entry_safe(lte, tmp,
2011 stream_list, write_streams_list)
2013 int status = stream_filtered(lte, filter_ctx);
2020 /* Soft filtered. */
2022 /* Hard filtered. */
2023 lte->will_be_in_output_wim = 0;
2024 list_del(<e->lookup_table_list);
2026 list_del(<e->write_streams_list);
2032 * prepare_stream_list_for_write() -
2034 * Prepare the list of streams to write for writing a WIM containing the
2035 * specified image(s) with the specified write flags.
2038 * The WIMStruct on whose behalf the write is occurring.
2041 * Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
2044 * WIMLIB_WRITE_FLAG_* flags for the write operation:
2046 * STREAMS_OK: For writes of all images, assume that all streams in the
2047 * lookup table of @wim and the per-image lists of unhashed streams should
2048 * be taken as-is, and image metadata should not be searched for
2049 * references. This does not exclude filtering with OVERWRITE and
2050 * SKIP_EXTERNAL_WIMS, below.
2052 * OVERWRITE: Streams already present in @wim shall not be returned in
2055 * SKIP_EXTERNAL_WIMS: Streams already present in a WIM file, but not
2056 * @wim, shall be returned in neither @stream_list_ret nor
2057 * @lookup_table_list_ret.
2060 * List of streams, linked by write_streams_list, that need to be written
2061 * will be returned here.
2063 * Note that this function assumes that unhashed streams will be written;
2064 * it does not take into account that they may become duplicates when
2067 * @lookup_table_list_ret
2068 * List of streams, linked by lookup_table_list, that need to be included
2069 * in the WIM's lookup table will be returned here. This will be a
2070 * superset of the streams in @stream_list_ret.
2072 * This list will be a proper superset of @stream_list_ret if and only if
2073 * WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
2074 * the streams that would otherwise need to be written were already located
2077 * All streams in this list will have @out_refcnt set to the number of
2078 * references to the stream in the output WIM. If
2079 * WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
2080 * may be as low as 0.
2083 * A context for queries of stream filter status with stream_filtered() is
2084 * returned in this location.
2086 * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
2087 * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
2088 * lookup table of @wim not inserted into @lookup_table_list_ret.
2090 * Still furthermore, @unique_size will be set to 1 on all stream entries in
2091 * @stream_list_ret that have unique size among all stream entries in
2092 * @stream_list_ret and among all stream entries in the lookup table of @wim
2093 * that are ineligible for being written due to filtering.
2095 * Returns 0 on success; nonzero on read error, memory allocation error, or
2099 prepare_stream_list_for_write(WIMStruct *wim, int image,
2101 struct list_head *stream_list_ret,
2102 struct list_head *lookup_table_list_ret,
2103 struct filter_context *filter_ctx_ret)
2106 struct wim_lookup_table_entry *lte;
2108 filter_ctx_ret->write_flags = write_flags;
2109 filter_ctx_ret->wim = wim;
2111 ret = prepare_unfiltered_list_of_streams_in_output_wim(
2114 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
2119 INIT_LIST_HEAD(lookup_table_list_ret);
2120 list_for_each_entry(lte, stream_list_ret, write_streams_list)
2121 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2123 ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
2128 if (may_filter_streams(filter_ctx_ret))
2129 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
2135 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2136 unsigned num_threads,
2137 struct list_head *stream_list_override,
2138 struct list_head *lookup_table_list_ret)
2141 struct list_head _stream_list;
2142 struct list_head *stream_list;
2143 struct wim_lookup_table_entry *lte;
2144 struct filter_context _filter_ctx;
2145 struct filter_context *filter_ctx;
2147 if (stream_list_override == NULL) {
2148 /* Normal case: prepare stream list from image(s) being written.
2150 stream_list = &_stream_list;
2151 filter_ctx = &_filter_ctx;
2152 ret = prepare_stream_list_for_write(wim, image, write_flags,
2154 lookup_table_list_ret,
2159 /* Currently only as a result of wimlib_split() being called:
2160 * use stream list already explicitly provided. Use existing
2161 * reference counts. */
2162 stream_list = stream_list_override;
2164 INIT_LIST_HEAD(lookup_table_list_ret);
2165 list_for_each_entry(lte, stream_list, write_streams_list) {
2166 lte->out_refcnt = lte->refcnt;
2167 lte->will_be_in_output_wim = 1;
2168 lte->unique_size = 0;
2169 list_add_tail(<e->lookup_table_list, lookup_table_list_ret);
2173 /* If needed, set auxiliary information so that we can detect when
2174 * wimlib has finished using each external file. */
2175 if (unlikely(write_flags & WIMLIB_WRITE_FLAG_SEND_DONE_WITH_FILE_MESSAGES)) {
2176 list_for_each_entry(lte, stream_list, write_streams_list)
2178 lte->back_inode->num_unread_streams = 0;
2179 list_for_each_entry(lte, stream_list, write_streams_list)
2181 lte->back_inode->num_unread_streams++;
2184 return wim_write_stream_list(wim,
2192 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags)
2197 int write_resource_flags;
2199 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2200 DEBUG("Not writing any metadata resources.");
2204 write_resource_flags = write_flags_to_resource_flags(write_flags);
2206 write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2208 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2209 wim->out_fd.offset);
2211 ret = call_progress(wim->progfunc,
2212 WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN,
2213 NULL, wim->progctx);
2217 if (image == WIMLIB_ALL_IMAGES) {
2219 end_image = wim->hdr.image_count;
2221 start_image = image;
2225 for (int i = start_image; i <= end_image; i++) {
2226 struct wim_image_metadata *imd;
2228 imd = wim->image_metadata[i - 1];
2229 /* Build a new metadata resource only if image was modified from
2230 * the original (or was newly added). Otherwise just copy the
2232 if (imd->modified) {
2233 DEBUG("Image %u was modified; building and writing new "
2234 "metadata resource", i);
2235 ret = write_metadata_resource(wim, i,
2236 write_resource_flags);
2237 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2238 DEBUG("Image %u was not modified; re-using existing "
2239 "metadata resource.", i);
2240 stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2243 DEBUG("Image %u was not modified; copying existing "
2244 "metadata resource.", i);
2245 ret = write_wim_resource(imd->metadata_lte,
2247 wim->out_compression_type,
2248 wim->out_chunk_size,
2249 write_resource_flags);
2255 return call_progress(wim->progfunc,
2256 WIMLIB_PROGRESS_MSG_WRITE_METADATA_END,
2257 NULL, wim->progctx);
2261 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2264 DEBUG("Opening \"%"TS"\" for writing.", path);
2266 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2268 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2269 return WIMLIB_ERR_OPEN;
2271 filedes_init(&wim->out_fd, raw_fd);
2276 close_wim_writable(WIMStruct *wim, int write_flags)
2280 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2281 DEBUG("Closing WIM file.");
2282 if (filedes_valid(&wim->out_fd))
2283 if (filedes_close(&wim->out_fd))
2284 ret = WIMLIB_ERR_WRITE;
2286 filedes_invalidate(&wim->out_fd);
2291 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2293 const struct wim_lookup_table_entry *lte1, *lte2;
2295 lte1 = *(const struct wim_lookup_table_entry**)p1;
2296 lte2 = *(const struct wim_lookup_table_entry**)p2;
2298 if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2299 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2300 if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2301 return cmp_u64(lte1->out_res_offset_in_wim,
2302 lte2->out_res_offset_in_wim);
2307 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2310 return cmp_u64(lte1->out_reshdr.offset_in_wim,
2311 lte2->out_reshdr.offset_in_wim);
2315 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2316 struct wim_reshdr *out_reshdr,
2317 struct list_head *lookup_table_list)
2321 /* Set output resource metadata for streams already present in WIM. */
2322 if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2323 struct wim_lookup_table_entry *lte;
2324 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2326 if (lte->resource_location == RESOURCE_IN_WIM &&
2327 lte->rspec->wim == wim)
2329 stream_set_out_reshdr_for_reuse(lte);
2334 ret = sort_stream_list(lookup_table_list,
2335 offsetof(struct wim_lookup_table_entry, lookup_table_list),
2336 cmp_streams_by_out_rspec);
2340 /* Add entries for metadata resources. */
2341 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2345 if (image == WIMLIB_ALL_IMAGES) {
2347 end_image = wim->hdr.image_count;
2349 start_image = image;
2353 /* Push metadata resource lookup table entries onto the front of
2354 * the list in reverse order, so that they're written in order.
2356 for (int i = end_image; i >= start_image; i--) {
2357 struct wim_lookup_table_entry *metadata_lte;
2359 metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2360 wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2361 metadata_lte->out_refcnt = 1;
2362 list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2366 return write_wim_lookup_table_from_stream_list(lookup_table_list,
2368 wim->hdr.part_number,
2370 write_flags_to_resource_flags(write_flags));
2376 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2377 * table, then overwrite the WIM header. By default, closes the WIM file
2378 * descriptor (@wim->out_fd) if successful.
2380 * write_flags is a bitwise OR of the following:
2382 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2383 * Include an integrity table.
2385 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2386 * fsync() the output file before closing it.
2388 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2389 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2390 * stream headers before the lookup table and XML data, and also
2391 * write the WIM header at the end instead of seeking to the
2392 * beginning. Can't be combined with
2393 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2395 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2396 * Don't write the lookup table.
2398 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2399 * After writing the XML data but before writing the integrity
2400 * table, write a temporary WIM header and flush the stream so that
2401 * the WIM is less likely to become corrupted upon abrupt program
2403 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2404 * Instead of overwriting the WIM header at the beginning of the
2405 * file, simply append it to the end of the file. (Used when
2407 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2408 * Do not close the file descriptor @wim->out_fd on either success
2410 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2411 * Use the existing <TOTALBYTES> stored in the in-memory XML
2412 * information, rather than setting it to the offset of the XML
2413 * data being written.
2414 * (private) WIMLIB_WRITE_FLAG_OVERWRITE
2415 * The existing WIM file is being updated in-place. The entries
2416 * from its integrity table may be re-used.
2419 finish_write(WIMStruct *wim, int image, int write_flags,
2420 struct list_head *lookup_table_list)
2424 int write_resource_flags;
2425 off_t old_lookup_table_end = 0;
2426 off_t new_lookup_table_end;
2428 struct integrity_table *old_integrity_table = NULL;
2430 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2432 write_resource_flags = write_flags_to_resource_flags(write_flags);
2434 /* In the WIM header, there is room for the resource entry for a
2435 * metadata resource labeled as the "boot metadata". This entry should
2436 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2437 * it should be a copy of the resource entry for the image that is
2438 * marked as bootable. This is not well documented... */
2439 if (wim->hdr.boot_idx == 0) {
2440 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2442 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2443 &wim->image_metadata[
2444 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2447 /* If overwriting the WIM file containing an integrity table in-place,
2448 * we'd like to re-use the information in the old integrity table
2449 * instead of recalculating it. But we might overwrite the old
2450 * integrity table when we expand the XML data. Read it into memory
2452 if ((write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2453 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)) ==
2454 (WIMLIB_WRITE_FLAG_OVERWRITE |
2455 WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2456 && wim_has_integrity_table(wim))
2458 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2459 wim->hdr.lookup_table_reshdr.size_in_wim;
2460 (void)read_integrity_table(wim,
2461 old_lookup_table_end - WIM_HEADER_DISK_SIZE,
2462 &old_integrity_table);
2463 /* If we couldn't read the old integrity table, we can still
2464 * re-calculate the full integrity table ourselves. Hence the
2465 * ignoring of the return value. */
2468 /* Write lookup table. */
2469 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2470 ret = write_wim_lookup_table(wim, image, write_flags,
2471 &wim->hdr.lookup_table_reshdr,
2474 free_integrity_table(old_integrity_table);
2479 /* Write XML data. */
2480 xml_totalbytes = wim->out_fd.offset;
2481 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2482 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2483 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2484 &wim->hdr.xml_data_reshdr,
2485 write_resource_flags);
2487 free_integrity_table(old_integrity_table);
2491 /* Write integrity table (optional). */
2492 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2493 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2494 struct wim_header checkpoint_hdr;
2495 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2496 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2497 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2498 ret = write_wim_header_at_offset(&checkpoint_hdr,
2501 free_integrity_table(old_integrity_table);
2506 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2507 wim->hdr.lookup_table_reshdr.size_in_wim;
2509 ret = write_integrity_table(wim,
2510 new_lookup_table_end,
2511 old_lookup_table_end,
2512 old_integrity_table);
2513 free_integrity_table(old_integrity_table);
2517 /* No integrity table. */
2518 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2521 /* Now that all information in the WIM header has been determined, the
2522 * preliminary header written earlier can be overwritten, the header of
2523 * the existing WIM file can be overwritten, or the final header can be
2524 * written to the end of the pipable WIM. */
2525 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2527 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2528 hdr_offset = wim->out_fd.offset;
2529 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2530 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2534 /* Possibly sync file data to disk before closing. On POSIX systems, it
2535 * is necessary to do this before using rename() to overwrite an
2536 * existing file with a new file. Otherwise, data loss would occur if
2537 * the system is abruptly terminated when the metadata for the rename
2538 * operation has been written to disk, but the new file data has not.
2540 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2541 DEBUG("Syncing WIM file.");
2542 if (fsync(wim->out_fd.fd)) {
2543 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2544 return WIMLIB_ERR_WRITE;
2548 if (close_wim_writable(wim, write_flags)) {
2549 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2550 return WIMLIB_ERR_WRITE;
2556 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2558 /* Set advisory lock on WIM file (if not already done so) */
2560 lock_wim_for_append(WIMStruct *wim)
2562 if (wim->locked_for_append)
2564 if (!flock(wim->in_fd.fd, LOCK_EX | LOCK_NB)) {
2565 wim->locked_for_append = 1;
2568 if (errno != EWOULDBLOCK)
2570 return WIMLIB_ERR_ALREADY_LOCKED;
2573 /* Remove advisory lock on WIM file (if present) */
2575 unlock_wim_for_append(WIMStruct *wim)
2577 if (wim->locked_for_append) {
2578 flock(wim->in_fd.fd, LOCK_UN);
2579 wim->locked_for_append = 0;
2585 * write_pipable_wim():
2587 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2588 * capable of being applied from a pipe).
2590 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2591 * images can be applied from them sequentially when the file data is sent over
2592 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2593 * The modifications made to the WIM format for pipable WIMs are:
2595 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2596 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2597 * stops other software from trying to read the file as a normal WIM.
2599 * - The header at the beginning of the file does not contain all the normal
2600 * information; in particular it will have all 0's for the lookup table and
2601 * XML data resource entries. This is because this information cannot be
2602 * determined until the lookup table and XML data have been written.
2603 * Consequently, wimlib will write the full header at the very end of the
2604 * file. The header at the end, however, is only used when reading the WIM
2605 * from a seekable file (not a pipe).
2607 * - An extra copy of the XML data is placed directly after the header. This
2608 * allows image names and sizes to be determined at an appropriate time when
2609 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2610 * WIM is read from a seekable file (not a pipe).
2612 * - The format of resources, or streams, has been modified to allow them to be
2613 * used before the "lookup table" has been read. Each stream is prefixed with
2614 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2615 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2616 * uncompressed stream size, and flags that indicate whether the stream is
2617 * compressed. The data of uncompressed streams then follows literally, while
2618 * the data of compressed streams follows in a modified format. Compressed
2619 * streams do not begin with a chunk table, since the chunk table cannot be
2620 * written until all chunks have been compressed. Instead, each compressed
2621 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2622 * Furthermore, the chunk table is written at the end of the resource instead
2623 * of the start. Note: chunk offsets are given in the chunk table as if the
2624 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2625 * used if the WIM is being read from a seekable file (not a pipe).
2627 * - Metadata resources always come before other file resources (streams).
2628 * (This does not by itself constitute an incompatibility with normal WIMs,
2629 * since this is valid in normal WIMs.)
2631 * - At least up to the end of the file resources, all components must be packed
2632 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2633 * not by itself consititute an incompatibility with normal WIMs, since this
2634 * is valid in normal WIMs.)
2636 * Note: the lookup table, XML data, and header at the end are not used when
2637 * applying from a pipe. They exist to support functionality such as image
2638 * application and export when the WIM is *not* read from a pipe.
2640 * Layout of pipable WIM:
2642 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2643 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2644 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2646 * Layout of normal WIM:
2648 * +--------+-----------------------------+-------------------------+
2649 * | Header | File and metadata resources | Lookup table | XML data |
2650 * +--------+-----------------------------+-------------------------+
2652 * An optional integrity table can follow the final XML data in both normal and
2653 * pipable WIMs. However, due to implementation details, wimlib currently can
2654 * only include an integrity table in a pipable WIM when writing it to a
2655 * seekable file (not a pipe).
2657 * Do note that since pipable WIMs are not supported by Microsoft's software,
2658 * wimlib does not create them unless explicitly requested (with
2659 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2660 * characters to identify the file.
2663 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2664 unsigned num_threads,
2665 struct list_head *stream_list_override,
2666 struct list_head *lookup_table_list_ret)
2669 struct wim_reshdr xml_reshdr;
2671 WARNING("Creating a pipable WIM, which will "
2673 " with Microsoft's software (wimgapi/imagex/Dism).");
2675 /* At this point, the header at the beginning of the file has already
2678 /* For efficiency, when wimlib adds an image to the WIM with
2679 * wimlib_add_image(), the SHA1 message digests of files is not
2680 * calculated; instead, they are calculated while the files are being
2681 * written. However, this does not work when writing a pipable WIM,
2682 * since when writing a stream to a pipable WIM, its SHA1 message digest
2683 * needs to be known before the stream data is written. Therefore,
2684 * before getting much farther, we need to pre-calculate the SHA1
2685 * message digests of all streams that will be written. */
2686 ret = wim_checksum_unhashed_streams(wim);
2690 /* Write extra copy of the XML data. */
2691 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2693 WRITE_RESOURCE_FLAG_PIPABLE);
2697 /* Write metadata resources for the image(s) being included in the
2699 ret = write_wim_metadata_resources(wim, image, write_flags);
2703 /* Write streams needed for the image(s) being included in the output
2704 * WIM, or streams needed for the split WIM part. */
2705 return write_wim_streams(wim, image, write_flags, num_threads,
2706 stream_list_override, lookup_table_list_ret);
2708 /* The lookup table, XML data, and header at end are handled by
2709 * finish_write(). */
2712 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2715 write_wim_part(WIMStruct *wim,
2716 const void *path_or_fd,
2719 unsigned num_threads,
2720 unsigned part_number,
2721 unsigned total_parts,
2722 struct list_head *stream_list_override,
2726 struct wim_header hdr_save;
2727 struct list_head lookup_table_list;
2729 if (total_parts == 1)
2730 DEBUG("Writing standalone WIM.");
2732 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2733 if (image == WIMLIB_ALL_IMAGES)
2734 DEBUG("Including all images.");
2736 DEBUG("Including image %d only.", image);
2737 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2738 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2740 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2741 DEBUG("Write flags: 0x%08x", write_flags);
2743 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2744 DEBUG("\tCHECK_INTEGRITY");
2746 if (write_flags & WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)
2747 DEBUG("\tNO_CHECK_INTEGRITY");
2749 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2752 if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2753 DEBUG("\tNOT_PIPABLE");
2755 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2756 DEBUG("\tRECOMPRESS");
2758 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2761 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2764 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2765 DEBUG("\tSOFT_DELETE");
2767 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2768 DEBUG("\tIGNORE_READONLY_FLAG");
2770 if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)
2771 DEBUG("\tSKIP_EXTERNAL_WIMS");
2773 if (write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK)
2774 DEBUG("\tSTREAMS_OK");
2776 if (write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)
2777 DEBUG("\tRETAIN_GUID");
2779 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2780 DEBUG("\tPACK_STREAMS");
2782 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2783 DEBUG("\tFILE_DESCRIPTOR");
2785 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2786 DEBUG("\tNO_METADATA");
2788 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2789 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2791 if (num_threads == 0)
2792 DEBUG("Number of threads: autodetect");
2794 DEBUG("Number of threads: %u", num_threads);
2795 DEBUG("Progress function: %s", (wim->progfunc ? "yes" : "no"));
2796 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2797 DEBUG("GUID: %s", (write_flags &
2798 WIMLIB_WRITE_FLAG_RETAIN_GUID) ? "retain"
2799 : guid ? "explicit" : "generate new");
2801 /* Internally, this is always called with a valid part number and total
2803 wimlib_assert(total_parts >= 1);
2804 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2806 /* A valid image (or all images) must be specified. */
2807 if (image != WIMLIB_ALL_IMAGES &&
2808 (image < 1 || image > wim->hdr.image_count))
2809 return WIMLIB_ERR_INVALID_IMAGE;
2811 /* If we need to write metadata resources, make sure the ::WIMStruct has
2812 * the needed information attached (e.g. is not a resource-only WIM,
2813 * such as a non-first part of a split WIM). */
2814 if (!wim_has_metadata(wim) &&
2815 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2816 return WIMLIB_ERR_METADATA_NOT_FOUND;
2818 /* Check for contradictory flags. */
2819 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2820 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2821 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2822 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2823 return WIMLIB_ERR_INVALID_PARAM;
2825 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2826 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2827 == (WIMLIB_WRITE_FLAG_PIPABLE |
2828 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2829 return WIMLIB_ERR_INVALID_PARAM;
2831 /* Save previous header, then start initializing the new one. */
2832 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2834 /* Set default integrity, pipable, and packed stream flags. */
2835 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2836 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2837 if (wim_is_pipable(wim)) {
2838 DEBUG("WIM is pipable; default to PIPABLE.");
2839 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2842 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2843 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2844 if (wim_has_integrity_table(wim)) {
2845 DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2846 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2849 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2850 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2851 == (WIMLIB_WRITE_FLAG_PIPABLE |
2852 WIMLIB_WRITE_FLAG_PACK_STREAMS))
2854 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2855 return WIMLIB_ERR_INVALID_PARAM;
2858 /* Set appropriate magic number. */
2859 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2860 wim->hdr.magic = PWM_MAGIC;
2862 wim->hdr.magic = WIM_MAGIC;
2864 /* Set appropriate version number. */
2865 if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2866 wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2867 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2869 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2871 /* Clear header flags that will be set automatically. */
2872 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2873 WIM_HDR_FLAG_RESOURCE_ONLY |
2874 WIM_HDR_FLAG_SPANNED |
2875 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2877 /* Set SPANNED header flag if writing part of a split WIM. */
2878 if (total_parts != 1)
2879 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2881 /* Set part number and total parts of split WIM. This will be 1 and 1
2882 * if the WIM is standalone. */
2883 wim->hdr.part_number = part_number;
2884 wim->hdr.total_parts = total_parts;
2886 /* Set compression type if different. */
2887 if (wim->compression_type != wim->out_compression_type) {
2888 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2889 wimlib_assert(ret == 0);
2892 /* Set chunk size if different. */
2893 wim->hdr.chunk_size = wim->out_chunk_size;
2896 if (!(write_flags & WIMLIB_WRITE_FLAG_RETAIN_GUID)) {
2898 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2900 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2903 /* Clear references to resources that have not been written yet. */
2904 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2905 zero_reshdr(&wim->hdr.xml_data_reshdr);
2906 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2907 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2909 /* Set image count and boot index correctly for single image writes. */
2910 if (image != WIMLIB_ALL_IMAGES) {
2911 wim->hdr.image_count = 1;
2912 if (wim->hdr.boot_idx == image)
2913 wim->hdr.boot_idx = 1;
2915 wim->hdr.boot_idx = 0;
2918 /* Split WIMs can't be bootable. */
2919 if (total_parts != 1)
2920 wim->hdr.boot_idx = 0;
2922 /* Initialize output file descriptor. */
2923 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2924 /* File descriptor was explicitly provided. Return error if
2925 * file descriptor is not seekable, unless writing a pipable WIM
2927 wim->out_fd.fd = *(const int*)path_or_fd;
2928 wim->out_fd.offset = 0;
2929 if (!filedes_is_seekable(&wim->out_fd)) {
2930 ret = WIMLIB_ERR_INVALID_PARAM;
2931 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2932 goto out_restore_hdr;
2933 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2934 ERROR("Can't include integrity check when "
2935 "writing pipable WIM to pipe!");
2936 goto out_restore_hdr;
2941 /* Filename of WIM to write was provided; open file descriptor
2943 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2944 O_TRUNC | O_CREAT | O_RDWR);
2946 goto out_restore_hdr;
2949 /* Write initial header. This is merely a "dummy" header since it
2950 * doesn't have all the information yet, so it will be overwritten later
2951 * (unless writing a pipable WIM). */
2952 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2953 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2954 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2955 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2957 goto out_restore_hdr;
2959 /* Write metadata resources and streams. */
2960 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2961 /* Default case: create a normal (non-pipable) WIM. */
2962 ret = write_wim_streams(wim, image, write_flags, num_threads,
2963 stream_list_override,
2964 &lookup_table_list);
2966 goto out_restore_hdr;
2968 ret = write_wim_metadata_resources(wim, image, write_flags);
2970 goto out_restore_hdr;
2972 /* Non-default case: create pipable WIM. */
2973 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2974 stream_list_override,
2975 &lookup_table_list);
2977 goto out_restore_hdr;
2978 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2982 /* Write lookup table, XML data, and (optional) integrity table. */
2983 ret = finish_write(wim, image, write_flags, &lookup_table_list);
2985 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2986 (void)close_wim_writable(wim, write_flags);
2987 DEBUG("ret=%d", ret);
2991 /* Write a standalone WIM to a file or file descriptor. */
2993 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2994 int image, int write_flags, unsigned num_threads)
2996 return write_wim_part(wim, path_or_fd, image, write_flags,
2997 num_threads, 1, 1, NULL, NULL);
3000 /* API function documented in wimlib.h */
3002 wimlib_write(WIMStruct *wim, const tchar *path,
3003 int image, int write_flags, unsigned num_threads)
3005 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3006 return WIMLIB_ERR_INVALID_PARAM;
3008 if (path == NULL || path[0] == T('\0'))
3009 return WIMLIB_ERR_INVALID_PARAM;
3011 return write_standalone_wim(wim, path, image, write_flags, num_threads);
3014 /* API function documented in wimlib.h */
3016 wimlib_write_to_fd(WIMStruct *wim, int fd,
3017 int image, int write_flags, unsigned num_threads)
3019 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3020 return WIMLIB_ERR_INVALID_PARAM;
3023 return WIMLIB_ERR_INVALID_PARAM;
3025 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
3027 return write_standalone_wim(wim, &fd, image, write_flags, num_threads);
3031 any_images_modified(WIMStruct *wim)
3033 for (int i = 0; i < wim->hdr.image_count; i++)
3034 if (wim->image_metadata[i]->modified)
3040 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
3042 const WIMStruct *wim = _wim;
3043 off_t end_offset = *(const off_t*)wim->private;
3045 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
3046 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
3047 return WIMLIB_ERR_RESOURCE_ORDER;
3051 /* Make sure no file or metadata resources are located after the XML data (or
3052 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
3053 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
3055 check_resource_offsets(WIMStruct *wim, off_t end_offset)
3060 wim->private = &end_offset;
3061 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
3065 for (i = 0; i < wim->hdr.image_count; i++) {
3066 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
3074 * Overwrite a WIM, possibly appending streams to it.
3076 * A WIM looks like (or is supposed to look like) the following:
3078 * Header (212 bytes)
3079 * Streams and metadata resources (variable size)
3080 * Lookup table (variable size)
3081 * XML data (variable size)
3082 * Integrity table (optional) (variable size)
3084 * If we are not adding any streams or metadata resources, the lookup table is
3085 * unchanged--- so we only need to overwrite the XML data, integrity table, and
3086 * header. This operation is potentially unsafe if the program is abruptly
3087 * terminated while the XML data or integrity table are being overwritten, but
3088 * before the new header has been written. To partially alleviate this problem,
3089 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
3090 * finish_write() to cause a temporary WIM header to be written after the XML
3091 * data has been written. This may prevent the WIM from becoming corrupted if
3092 * the program is terminated while the integrity table is being calculated (but
3093 * no guarantees, due to write re-ordering...).
3095 * If we are adding new streams or images (metadata resources), the lookup table
3096 * needs to be changed, and those streams need to be written. In this case, we
3097 * try to perform a safe update of the WIM file by writing the streams *after*
3098 * the end of the previous WIM, then writing the new lookup table, XML data, and
3099 * (optionally) integrity table following the new streams. This will produce a
3100 * layout like the following:
3102 * Header (212 bytes)
3103 * (OLD) Streams and metadata resources (variable size)
3104 * (OLD) Lookup table (variable size)
3105 * (OLD) XML data (variable size)
3106 * (OLD) Integrity table (optional) (variable size)
3107 * (NEW) Streams and metadata resources (variable size)
3108 * (NEW) Lookup table (variable size)
3109 * (NEW) XML data (variable size)
3110 * (NEW) Integrity table (optional) (variable size)
3112 * At all points, the WIM is valid as nothing points to the new data yet. Then,
3113 * the header is overwritten to point to the new lookup table, XML data, and
3114 * integrity table, to produce the following layout:
3116 * Header (212 bytes)
3117 * Streams and metadata resources (variable size)
3118 * Nothing (variable size)
3119 * More Streams and metadata resources (variable size)
3120 * Lookup table (variable size)
3121 * XML data (variable size)
3122 * Integrity table (optional) (variable size)
3124 * This method allows an image to be appended to a large WIM very quickly, and
3125 * is crash-safe except in the case of write re-ordering, but the
3126 * disadvantage is that a small hole is left in the WIM where the old lookup
3127 * table, xml data, and integrity table were. (These usually only take up a
3128 * small amount of space compared to the streams, however.)
3131 overwrite_wim_inplace(WIMStruct *wim, int write_flags, unsigned num_threads)
3135 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
3136 struct wim_header hdr_save;
3137 struct list_head stream_list;
3138 struct list_head lookup_table_list;
3139 struct filter_context filter_ctx;
3141 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
3143 /* Save original header so it can be restored in case of error */
3144 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3146 /* Set default integrity flag. */
3147 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
3148 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
3149 if (wim_has_integrity_table(wim))
3150 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3152 /* Set WIM version if adding packed streams. */
3153 if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
3154 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
3156 /* Set additional flags for overwrite. */
3157 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
3158 WIMLIB_WRITE_FLAG_STREAMS_OK;
3160 /* Make sure that the integrity table (if present) is after the XML
3161 * data, and that there are no stream resources, metadata resources, or
3162 * lookup tables after the XML data. Otherwise, these data would be
3164 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
3165 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
3166 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
3167 wim->hdr.lookup_table_reshdr.size_in_wim;
3168 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
3169 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
3170 WARNING("Didn't expect the integrity table to be before the XML data");
3171 ret = WIMLIB_ERR_RESOURCE_ORDER;
3172 goto out_restore_memory_hdr;
3175 if (old_lookup_table_end > old_xml_begin) {
3176 WARNING("Didn't expect the lookup table to be after the XML data");
3177 ret = WIMLIB_ERR_RESOURCE_ORDER;
3178 goto out_restore_memory_hdr;
3181 /* Set @old_wim_end, which indicates the point beyond which we don't
3182 * allow any file and metadata resources to appear without returning
3183 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
3184 * overwrite these resources). */
3185 if (!wim->deletion_occurred && !any_images_modified(wim)) {
3186 /* If no images have been modified and no images have been
3187 * deleted, a new lookup table does not need to be written. We
3188 * shall write the new XML data and optional integrity table
3189 * immediately after the lookup table. Note that this may
3190 * overwrite an existing integrity table. */
3191 DEBUG("Skipping writing lookup table "
3192 "(no images modified or deleted)");
3193 old_wim_end = old_lookup_table_end;
3194 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
3195 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
3196 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
3197 /* Old WIM has an integrity table; begin writing new streams
3199 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
3200 wim->hdr.integrity_table_reshdr.size_in_wim;
3202 /* No existing integrity table; begin writing new streams after
3203 * the old XML data. */
3204 old_wim_end = old_xml_end;
3207 ret = check_resource_offsets(wim, old_wim_end);
3209 goto out_restore_memory_hdr;
3211 ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3212 &stream_list, &lookup_table_list,
3215 goto out_restore_memory_hdr;
3217 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3219 goto out_restore_memory_hdr;
3221 ret = lock_wim_for_append(wim);
3225 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3226 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3227 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3229 ERROR_WITH_ERRNO("Error updating WIM header flags");
3230 goto out_unlock_wim;
3233 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3234 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3235 ret = WIMLIB_ERR_WRITE;
3236 goto out_restore_physical_hdr;
3239 ret = wim_write_stream_list(wim,
3247 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES, write_flags);
3251 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3252 &lookup_table_list);
3256 unlock_wim_for_append(wim);
3260 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3261 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3262 wim->filename, old_wim_end);
3263 /* Return value of ftruncate() is ignored because this is
3264 * already an error path. */
3265 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3267 out_restore_physical_hdr:
3268 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3270 unlock_wim_for_append(wim);
3272 (void)close_wim_writable(wim, write_flags);
3273 out_restore_memory_hdr:
3274 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3279 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags, unsigned num_threads)
3281 size_t wim_name_len;
3284 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3286 /* Write the WIM to a temporary file in the same directory as the
3288 wim_name_len = tstrlen(wim->filename);
3289 tchar tmpfile[wim_name_len + 10];
3290 tmemcpy(tmpfile, wim->filename, wim_name_len);
3291 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3292 tmpfile[wim_name_len + 9] = T('\0');
3294 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3296 WIMLIB_WRITE_FLAG_FSYNC |
3297 WIMLIB_WRITE_FLAG_RETAIN_GUID,
3304 if (filedes_valid(&wim->in_fd)) {
3305 filedes_close(&wim->in_fd);
3306 filedes_invalidate(&wim->in_fd);
3309 /* Rename the new WIM file to the original WIM file. Note: on Windows
3310 * this actually calls win32_rename_replacement(), not _wrename(), so
3311 * that removing the existing destination file can be handled. */
3312 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3313 ret = trename(tmpfile, wim->filename);
3315 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3316 tmpfile, wim->filename);
3323 return WIMLIB_ERR_RENAME;
3326 union wimlib_progress_info progress;
3327 progress.rename.from = tmpfile;
3328 progress.rename.to = wim->filename;
3329 return call_progress(wim->progfunc, WIMLIB_PROGRESS_MSG_RENAME,
3330 &progress, wim->progctx);
3333 /* Determine if the specified WIM file may be updated by appending in-place
3334 * rather than writing and replacing it with an entirely new file. */
3336 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3338 /* REBUILD flag forces full rebuild. */
3339 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3342 /* Deletions cause full rebuild by default. */
3343 if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3346 /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3347 * turned into a pipable WIM in-place. */
3348 if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3351 /* The default compression type and compression chunk size selected for
3352 * the output WIM must be the same as those currently used for the WIM.
3354 if (wim->compression_type != wim->out_compression_type)
3356 if (wim->chunk_size != wim->out_chunk_size)
3362 /* API function documented in wimlib.h */
3364 wimlib_overwrite(WIMStruct *wim, int write_flags, unsigned num_threads)
3369 if (write_flags & ~WIMLIB_WRITE_MASK_PUBLIC)
3370 return WIMLIB_ERR_INVALID_PARAM;
3373 return WIMLIB_ERR_NO_FILENAME;
3375 orig_hdr_flags = wim->hdr.flags;
3376 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3377 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3378 ret = can_modify_wim(wim);
3379 wim->hdr.flags = orig_hdr_flags;
3383 if (can_overwrite_wim_inplace(wim, write_flags)) {
3384 ret = overwrite_wim_inplace(wim, write_flags, num_threads);
3385 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3387 WARNING("Falling back to re-building entire WIM");
3389 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads);