4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/header.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/lookup_table.h"
43 #include "wimlib/metadata.h"
44 #include "wimlib/resource.h"
45 #include "wimlib/write.h"
46 #include "wimlib/xml.h"
49 # include "wimlib/win32.h" /* win32_get_number_of_processors() */
52 #ifdef ENABLE_MULTITHREADED_COMPRESSION
69 # include <sys/uio.h> /* for `struct iovec' */
72 /* Chunk table that's located at the beginning of each compressed resource in
73 * the WIM. (This is not the on-disk format; the on-disk format just has an
74 * array of offsets.) */
76 u64 original_resource_size;
79 unsigned bytes_per_chunk_entry;
85 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
86 * integers, including the first offset of 0, which will not be written.
88 u8 offsets[] _aligned_attribute(8);
91 /* Allocate and initializes a chunk table, then reserve space for it in the
92 * output file unless writing a pipable resource. */
94 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
95 struct filedes *out_fd,
96 struct chunk_table **chunk_tab_ret,
101 unsigned bytes_per_chunk_entry;
103 struct chunk_table *chunk_tab;
106 size = wim_resource_size(lte);
107 num_chunks = wim_resource_chunks(lte);
108 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
109 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
110 chunk_tab = CALLOC(1, alloc_size);
113 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
115 return WIMLIB_ERR_NOMEM;
117 chunk_tab->num_chunks = num_chunks;
118 chunk_tab->original_resource_size = size;
119 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
120 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
122 chunk_tab->cur_offset_p = chunk_tab->offsets;
124 /* We don't know the correct offsets yet; so just write zeroes to
125 * reserve space for the table, so we can go back to it later after
126 * we've written the compressed chunks following it.
128 * Special case: if writing a pipable WIM, compressed resources are in a
129 * modified format (see comment above write_pipable_wim()) and do not
130 * have a chunk table at the beginning, so don't reserve any space for
132 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
133 ret = full_write(out_fd, chunk_tab->offsets,
134 chunk_tab->table_disk_size);
136 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
142 *chunk_tab_ret = chunk_tab;
146 /* Add the offset for the next chunk to the chunk table being constructed for a
147 * compressed stream. */
149 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
151 if (chunk_tab->bytes_per_chunk_entry == 4) {
152 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
153 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
154 chunk_tab->cur_offset_u32 += out_chunk_size;
156 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
157 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
158 chunk_tab->cur_offset_u64 += out_chunk_size;
163 * compress_func_t- Pointer to a function to compresses a chunk
164 * of a WIM resource. This may be either
165 * wimlib_xpress_compress() (xpress-compress.c) or
166 * wimlib_lzx_compress() (lzx-compress.c).
168 * @chunk: Uncompressed data of the chunk.
169 * @chunk_size: Size of the uncompressed chunk, in bytes.
170 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
172 * Returns the size of the compressed data written to @out in bytes, or 0 if the
173 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
175 * As a special requirement, the compression code is optimized for the WIM
176 * format and therefore requires (@chunk_size <= 32768).
178 * As another special requirement, the compression code will read up to 8 bytes
179 * off the end of the @chunk array for performance reasons. The values of these
180 * bytes will not affect the output of the compression, but the calling code
181 * must make sure that the buffer holding the uncompressed chunk is actually at
182 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
183 * mapped memory that will not cause a memory access violation if accessed.
185 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
188 static compress_func_t
189 get_compress_func(int out_ctype)
191 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
192 return wimlib_lzx_compress;
194 return wimlib_xpress_compress;
197 /* Finishes a WIM chunk table and writes it to the output file at the correct
200 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
201 struct filedes *out_fd,
202 off_t res_start_offset,
203 int write_resource_flags)
207 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
208 ret = full_write(out_fd,
210 chunk_tab->bytes_per_chunk_entry,
211 chunk_tab->table_disk_size);
213 ret = full_pwrite(out_fd,
215 chunk_tab->bytes_per_chunk_entry,
216 chunk_tab->table_disk_size,
220 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
226 /* Write the header for a stream in a pipable WIM.
229 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
230 struct filedes *out_fd,
231 int additional_reshdr_flags)
233 struct pwm_stream_hdr stream_hdr;
237 stream_hdr.magic = PWM_STREAM_MAGIC;
238 stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
239 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
240 zero_out_hash(stream_hdr.hash);
242 wimlib_assert(!lte->unhashed);
243 copy_hash(stream_hdr.hash, lte->hash);
246 reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
247 reshdr_flags |= additional_reshdr_flags;
248 stream_hdr.flags = cpu_to_le32(reshdr_flags);
249 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
251 ERROR_WITH_ERRNO("Error writing stream header");
256 seek_and_truncate(struct filedes *out_fd, off_t offset)
258 if (filedes_seek(out_fd, offset) == -1 ||
259 ftruncate(out_fd->fd, offset))
261 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
262 return WIMLIB_ERR_WRITE;
268 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
270 u8 md[SHA1_HASH_SIZE];
272 sha1_final(md, sha_ctx);
274 copy_hash(lte->hash, md);
275 } else if (!hashes_equal(md, lte->hash)) {
276 ERROR("WIM resource has incorrect hash!");
277 if (lte_filename_valid(lte)) {
278 ERROR("We were reading it from \"%"TS"\"; maybe "
279 "it changed while we were reading it.",
282 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
287 struct write_resource_ctx {
288 compress_func_t compress;
289 struct chunk_table *chunk_tab;
290 struct filedes *out_fd;
297 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
299 struct write_resource_ctx *ctx = _ctx;
300 const void *out_chunk;
301 unsigned out_chunk_size;
305 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
308 out_chunk_size = chunk_size;
310 void *compressed_chunk;
311 unsigned compressed_size;
313 /* Compress the chunk. */
314 compressed_chunk = alloca(chunk_size);
315 compressed_size = (*ctx->compress)(chunk, chunk_size,
318 /* Use compressed data if compression to less than input size
320 if (compressed_size) {
321 out_chunk = compressed_chunk;
322 out_chunk_size = compressed_size;
326 if (ctx->chunk_tab) {
327 /* Update chunk table accounting. */
328 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
330 /* If writing compressed chunks to a pipable WIM, before the
331 * chunk data write a chunk header that provides the compressed
333 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
334 struct pwm_chunk_hdr chunk_hdr = {
335 .compressed_size = cpu_to_le32(out_chunk_size),
337 ret = full_write(ctx->out_fd, &chunk_hdr,
344 /* Write the chunk data. */
345 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
351 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
356 * write_wim_resource()-
358 * Write a resource to an output WIM.
361 * Lookup table entry for the resource, which could be in another WIM, in
362 * an external file, or in another location.
365 * File descriptor opened to the output WIM.
368 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
369 * compression algorithm to use.
372 * On success, this is filled in with the offset, flags, compressed size,
373 * and uncompressed size of the resource in the output WIM.
375 * @write_resource_flags:
376 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
377 * if it could otherwise be copied directly from the input;
378 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
379 * (and the output file descriptor may be a pipe).
381 * Additional notes: The SHA1 message digest of the uncompressed data is
382 * calculated (except when doing a raw copy --- see below). If the @unhashed
383 * flag is set on the lookup table entry, this message digest is simply copied
384 * to it; otherwise, the message digest is compared with the existing one, and
385 * the function will fail if they do not match.
388 write_wim_resource(struct wim_lookup_table_entry *lte,
389 struct filedes *out_fd, int out_ctype,
390 struct resource_entry *out_res_entry,
393 struct write_resource_ctx write_ctx;
394 off_t res_start_offset;
398 /* Mask out any irrelevant flags, since this function also uses this
399 * variable to store WIMLIB_READ_RESOURCE flags. */
400 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
402 /* Get current position in output WIM. */
403 res_start_offset = out_fd->offset;
405 /* If we are not forcing the data to be recompressed, and the input
406 * resource is located in a WIM with the same compression type as that
407 * desired other than no compression, we can simply copy the compressed
408 * data without recompressing it. This also means we must skip
409 * calculating the SHA1, as we never will see the uncompressed data. */
410 if (lte->resource_location == RESOURCE_IN_WIM &&
411 out_ctype == wim_resource_compression_type(lte) &&
412 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
413 !(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS))
415 /* Normally we can request a RAW_FULL read, but if we're reading
416 * from a pipable resource and writing a non-pipable resource or
417 * vice versa, then a RAW_CHUNKS read needs to be requested so
418 * that the written resource can be appropriately formatted.
419 * However, in neither case is any actual decompression needed.
421 if (lte->is_pipable == !!(resource_flags &
422 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
423 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
425 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
426 write_ctx.doing_sha = false;
427 read_size = lte->resource_entry.size;
429 write_ctx.doing_sha = true;
430 sha1_init(&write_ctx.sha_ctx);
431 read_size = lte->resource_entry.original_size;
434 /* If the output resource is to be compressed, initialize the chunk
435 * table and set the function to use for chunk compression. Exceptions:
436 * no compression function is needed if doing a raw copy; also, no chunk
437 * table is needed if doing a *full* (not per-chunk) raw copy. */
438 write_ctx.compress = NULL;
439 write_ctx.chunk_tab = NULL;
440 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
441 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW))
442 write_ctx.compress = get_compress_func(out_ctype);
443 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
444 ret = begin_wim_resource_chunk_tab(lte, out_fd,
445 &write_ctx.chunk_tab,
452 /* If writing a pipable resource, write the stream header and update
453 * @res_start_offset to be the end of the stream header. */
454 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
455 int reshdr_flags = 0;
456 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
457 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
458 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
460 goto out_free_chunk_tab;
461 res_start_offset = out_fd->offset;
464 /* Write the entire resource by reading the entire resource and feeding
465 * the data through the write_resource_cb function. */
466 write_ctx.out_fd = out_fd;
467 write_ctx.resource_flags = resource_flags;
469 ret = read_resource_prefix(lte, read_size,
470 write_resource_cb, &write_ctx, resource_flags);
472 goto out_free_chunk_tab;
474 /* Verify SHA1 message digest of the resource, or set the hash for the
476 if (write_ctx.doing_sha) {
477 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
479 goto out_free_chunk_tab;
482 /* Write chunk table if needed. */
483 if (write_ctx.chunk_tab) {
484 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
489 goto out_free_chunk_tab;
492 /* Fill in out_res_entry with information about the newly written
494 out_res_entry->size = out_fd->offset - res_start_offset;
495 out_res_entry->flags = lte->resource_entry.flags;
496 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
497 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
499 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
500 out_res_entry->offset = res_start_offset;
501 out_res_entry->original_size = wim_resource_size(lte);
503 /* Check for resources compressed to greater than their original size
504 * and write them uncompressed instead. (But never do this if writing
505 * to a pipe, and don't bother if we did a raw copy.) */
506 if (out_res_entry->size > out_res_entry->original_size &&
507 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
508 WIMLIB_READ_RESOURCE_FLAG_RAW)))
510 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
511 "writing uncompressed instead",
512 out_res_entry->original_size, out_res_entry->size);
513 ret = seek_and_truncate(out_fd, res_start_offset);
515 goto out_free_chunk_tab;
516 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
517 FREE(write_ctx.chunk_tab);
518 write_ctx.compress = NULL;
519 write_ctx.chunk_tab = NULL;
520 write_ctx.doing_sha = false;
521 goto try_write_again;
523 if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
524 DEBUG("Copied raw compressed data "
525 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
526 out_res_entry->original_size, out_res_entry->size,
527 out_res_entry->offset, out_res_entry->flags);
528 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
529 DEBUG("Wrote compressed resource "
530 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
531 out_res_entry->original_size, out_res_entry->size,
532 out_res_entry->offset, out_res_entry->flags);
534 DEBUG("Wrote uncompressed resource "
535 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
536 out_res_entry->original_size,
537 out_res_entry->offset, out_res_entry->flags);
541 FREE(write_ctx.chunk_tab);
546 /* Like write_wim_resource(), but the resource is specified by a buffer of
547 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
548 * the buffer to @hash_ret. */
550 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
551 int reshdr_flags, struct filedes *out_fd,
553 struct resource_entry *out_res_entry,
554 u8 *hash_ret, int write_resource_flags)
556 /* Set up a temporary lookup table entry to provide to
557 * write_wim_resource(). */
558 struct wim_lookup_table_entry lte;
561 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
562 lte.attached_buffer = (void*)buf;
563 lte.resource_entry.original_size = buf_size;
564 lte.resource_entry.flags = reshdr_flags;
566 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
567 sha1_buffer(buf, buf_size, lte.hash);
573 ret = write_wim_resource(<e, out_fd, out_ctype, out_res_entry,
574 write_resource_flags);
578 copy_hash(hash_ret, lte.hash);
583 #ifdef ENABLE_MULTITHREADED_COMPRESSION
585 /* Blocking shared queue (solves the producer-consumer problem) */
586 struct shared_queue {
590 unsigned filled_slots;
592 pthread_mutex_t lock;
593 pthread_cond_t msg_avail_cond;
594 pthread_cond_t space_avail_cond;
598 shared_queue_init(struct shared_queue *q, unsigned size)
600 wimlib_assert(size != 0);
601 q->array = CALLOC(sizeof(q->array[0]), size);
608 if (pthread_mutex_init(&q->lock, NULL)) {
609 ERROR_WITH_ERRNO("Failed to initialize mutex");
612 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
613 ERROR_WITH_ERRNO("Failed to initialize condition variable");
614 goto err_destroy_lock;
616 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
617 ERROR_WITH_ERRNO("Failed to initialize condition variable");
618 goto err_destroy_msg_avail_cond;
621 err_destroy_msg_avail_cond:
622 pthread_cond_destroy(&q->msg_avail_cond);
624 pthread_mutex_destroy(&q->lock);
626 return WIMLIB_ERR_NOMEM;
630 shared_queue_destroy(struct shared_queue *q)
633 pthread_mutex_destroy(&q->lock);
634 pthread_cond_destroy(&q->msg_avail_cond);
635 pthread_cond_destroy(&q->space_avail_cond);
639 shared_queue_put(struct shared_queue *q, void *obj)
641 pthread_mutex_lock(&q->lock);
642 while (q->filled_slots == q->size)
643 pthread_cond_wait(&q->space_avail_cond, &q->lock);
645 q->back = (q->back + 1) % q->size;
646 q->array[q->back] = obj;
649 pthread_cond_broadcast(&q->msg_avail_cond);
650 pthread_mutex_unlock(&q->lock);
654 shared_queue_get(struct shared_queue *q)
658 pthread_mutex_lock(&q->lock);
659 while (q->filled_slots == 0)
660 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
662 obj = q->array[q->front];
663 q->array[q->front] = NULL;
664 q->front = (q->front + 1) % q->size;
667 pthread_cond_broadcast(&q->space_avail_cond);
668 pthread_mutex_unlock(&q->lock);
672 struct compressor_thread_params {
673 struct shared_queue *res_to_compress_queue;
674 struct shared_queue *compressed_res_queue;
675 compress_func_t compress;
678 #define MAX_CHUNKS_PER_MSG 2
681 struct wim_lookup_table_entry *lte;
682 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
683 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
684 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
685 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
686 size_t total_out_bytes;
688 struct list_head list;
694 compress_chunks(struct message *msg, compress_func_t compress)
696 msg->total_out_bytes = 0;
697 for (unsigned i = 0; i < msg->num_chunks; i++) {
698 unsigned len = compress(msg->uncompressed_chunks[i],
699 msg->uncompressed_chunk_sizes[i],
700 msg->compressed_chunks[i]);
704 /* To be written compressed */
705 out_chunk = msg->compressed_chunks[i];
708 /* To be written uncompressed */
709 out_chunk = msg->uncompressed_chunks[i];
710 out_len = msg->uncompressed_chunk_sizes[i];
712 msg->out_chunks[i].iov_base = out_chunk;
713 msg->out_chunks[i].iov_len = out_len;
714 msg->total_out_bytes += out_len;
718 /* Compressor thread routine. This is a lot simpler than the main thread
719 * routine: just repeatedly get a group of chunks from the
720 * res_to_compress_queue, compress them, and put them in the
721 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
724 compressor_thread_proc(void *arg)
726 struct compressor_thread_params *params = arg;
727 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
728 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
729 compress_func_t compress = params->compress;
732 DEBUG("Compressor thread ready");
733 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
734 compress_chunks(msg, compress);
735 shared_queue_put(compressed_res_queue, msg);
737 DEBUG("Compressor thread terminating");
740 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
743 do_write_streams_progress(union wimlib_progress_info *progress,
744 wimlib_progress_func_t progress_func,
746 bool stream_discarded)
748 if (stream_discarded) {
749 progress->write_streams.total_bytes -= size_added;
750 if (progress->write_streams._private != ~(uint64_t)0 &&
751 progress->write_streams._private > progress->write_streams.total_bytes)
753 progress->write_streams._private = progress->write_streams.total_bytes;
756 progress->write_streams.completed_bytes += size_added;
758 progress->write_streams.completed_streams++;
760 progress->write_streams.completed_bytes >= progress->write_streams._private)
762 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
764 if (progress->write_streams._private == progress->write_streams.total_bytes) {
765 progress->write_streams._private = ~(uint64_t)0;
767 progress->write_streams._private =
768 min(progress->write_streams.total_bytes,
769 progress->write_streams.completed_bytes +
770 progress->write_streams.total_bytes / 100);
775 struct serial_write_stream_ctx {
776 struct filedes *out_fd;
778 int write_resource_flags;
782 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
784 struct serial_write_stream_ctx *ctx = _ctx;
785 return write_wim_resource(lte, ctx->out_fd,
786 ctx->out_ctype, <e->output_resource_entry,
787 ctx->write_resource_flags);
790 /* Write a list of streams, taking into account that some streams may be
791 * duplicates that are checksummed and discarded on the fly, and also delegating
792 * the actual writing of a stream to a function @write_stream_cb, which is
793 * passed the context @write_stream_ctx. */
795 do_write_stream_list(struct list_head *stream_list,
796 struct wim_lookup_table *lookup_table,
797 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
798 void *write_stream_ctx,
799 wimlib_progress_func_t progress_func,
800 union wimlib_progress_info *progress)
803 struct wim_lookup_table_entry *lte;
804 bool stream_discarded;
806 /* For each stream in @stream_list ... */
807 while (!list_empty(stream_list)) {
808 stream_discarded = false;
809 lte = container_of(stream_list->next,
810 struct wim_lookup_table_entry,
812 list_del(<e->write_streams_list);
813 if (lte->unhashed && !lte->unique_size) {
814 /* Unhashed stream that shares a size with some other
815 * stream in the WIM we are writing. The stream must be
816 * checksummed to know if we need to write it or not. */
817 struct wim_lookup_table_entry *tmp;
818 u32 orig_refcnt = lte->out_refcnt;
820 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
825 /* We found a duplicate stream. */
826 if (orig_refcnt != tmp->out_refcnt) {
827 /* We have already written, or are going
828 * to write, the duplicate stream. So
829 * just skip to the next stream. */
830 DEBUG("Discarding duplicate stream of length %"PRIu64,
831 wim_resource_size(lte));
832 lte->no_progress = 0;
833 stream_discarded = true;
834 goto skip_to_progress;
839 /* Here, @lte is either a hashed stream or an unhashed stream
840 * with a unique size. In either case we know that the stream
841 * has to be written. In either case the SHA1 message digest
842 * will be calculated over the stream while writing it; however,
843 * in the former case this is done merely to check the data,
844 * while in the latter case this is done because we do not have
845 * the SHA1 message digest yet. */
846 wimlib_assert(lte->out_refcnt != 0);
848 lte->no_progress = 0;
849 ret = (*write_stream_cb)(lte, write_stream_ctx);
852 /* In parallel mode, some streams are deferred for later,
853 * serialized processing; ignore them here. */
857 list_del(<e->unhashed_list);
858 lookup_table_insert(lookup_table, lte);
862 if (!lte->no_progress) {
863 do_write_streams_progress(progress,
865 wim_resource_size(lte),
873 do_write_stream_list_serial(struct list_head *stream_list,
874 struct wim_lookup_table *lookup_table,
875 struct filedes *out_fd,
877 int write_resource_flags,
878 wimlib_progress_func_t progress_func,
879 union wimlib_progress_info *progress)
881 struct serial_write_stream_ctx ctx = {
883 .out_ctype = out_ctype,
884 .write_resource_flags = write_resource_flags,
886 return do_write_stream_list(stream_list,
895 write_flags_to_resource_flags(int write_flags)
897 int resource_flags = 0;
899 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
900 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
901 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
902 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
903 return resource_flags;
907 write_stream_list_serial(struct list_head *stream_list,
908 struct wim_lookup_table *lookup_table,
909 struct filedes *out_fd,
911 int write_resource_flags,
912 wimlib_progress_func_t progress_func,
913 union wimlib_progress_info *progress)
915 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
916 progress->write_streams.total_streams);
917 progress->write_streams.num_threads = 1;
919 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
920 return do_write_stream_list_serial(stream_list,
924 write_resource_flags,
929 #ifdef ENABLE_MULTITHREADED_COMPRESSION
931 write_wim_chunks(struct message *msg, struct filedes *out_fd,
932 struct chunk_table *chunk_tab,
933 int write_resource_flags)
936 struct pwm_chunk_hdr *chunk_hdrs;
941 for (unsigned i = 0; i < msg->num_chunks; i++)
942 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
944 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
945 nvecs = msg->num_chunks;
946 vecs = msg->out_chunks;
947 nbytes = msg->total_out_bytes;
949 /* Special case: If writing a compressed resource to a pipable
950 * WIM, prefix each compressed chunk with a header that gives
951 * its compressed size. */
952 nvecs = msg->num_chunks * 2;
953 vecs = alloca(nvecs * sizeof(vecs[0]));
954 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
956 for (unsigned i = 0; i < msg->num_chunks; i++) {
957 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
958 vecs[i * 2].iov_base = &chunk_hdrs[i];
959 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
960 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
961 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
963 nbytes = msg->total_out_bytes + msg->num_chunks * sizeof(chunk_hdrs[0]);
965 ret = full_writev(out_fd, vecs, nvecs);
967 ERROR_WITH_ERRNO("Failed to write WIM chunks");
971 struct main_writer_thread_ctx {
972 struct list_head *stream_list;
973 struct wim_lookup_table *lookup_table;
974 struct filedes *out_fd;
975 off_t res_start_offset;
977 int write_resource_flags;
978 struct shared_queue *res_to_compress_queue;
979 struct shared_queue *compressed_res_queue;
981 wimlib_progress_func_t progress_func;
982 union wimlib_progress_info *progress;
984 struct list_head available_msgs;
985 struct list_head outstanding_streams;
986 struct list_head serial_streams;
987 size_t num_outstanding_messages;
989 SHA_CTX next_sha_ctx;
992 struct wim_lookup_table_entry *next_lte;
994 struct message *msgs;
995 struct message *next_msg;
996 struct chunk_table *cur_chunk_tab;
1000 init_message(struct message *msg)
1002 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1003 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1004 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1005 if (msg->compressed_chunks[i] == NULL ||
1006 msg->uncompressed_chunks[i] == NULL)
1007 return WIMLIB_ERR_NOMEM;
1013 destroy_message(struct message *msg)
1015 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1016 FREE(msg->compressed_chunks[i]);
1017 FREE(msg->uncompressed_chunks[i]);
1022 free_messages(struct message *msgs, size_t num_messages)
1025 for (size_t i = 0; i < num_messages; i++)
1026 destroy_message(&msgs[i]);
1031 static struct message *
1032 allocate_messages(size_t num_messages)
1034 struct message *msgs;
1036 msgs = CALLOC(num_messages, sizeof(struct message));
1039 for (size_t i = 0; i < num_messages; i++) {
1040 if (init_message(&msgs[i])) {
1041 free_messages(msgs, num_messages);
1049 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1051 while (ctx->num_outstanding_messages--)
1052 shared_queue_get(ctx->compressed_res_queue);
1053 free_messages(ctx->msgs, ctx->num_messages);
1054 FREE(ctx->cur_chunk_tab);
1058 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1060 /* Pre-allocate all the buffers that will be needed to do the chunk
1062 ctx->msgs = allocate_messages(ctx->num_messages);
1064 return WIMLIB_ERR_NOMEM;
1066 /* Initially, all the messages are available to use. */
1067 INIT_LIST_HEAD(&ctx->available_msgs);
1068 for (size_t i = 0; i < ctx->num_messages; i++)
1069 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1071 /* outstanding_streams is the list of streams that currently have had
1072 * chunks sent off for compression.
1074 * The first stream in outstanding_streams is the stream that is
1075 * currently being written.
1077 * The last stream in outstanding_streams is the stream that is
1078 * currently being read and having chunks fed to the compressor threads.
1080 INIT_LIST_HEAD(&ctx->outstanding_streams);
1081 ctx->num_outstanding_messages = 0;
1083 ctx->next_msg = NULL;
1085 /* Resources that don't need any chunks compressed are added to this
1086 * list and written directly by the main thread. */
1087 INIT_LIST_HEAD(&ctx->serial_streams);
1089 ctx->cur_chunk_tab = NULL;
1095 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1097 struct message *msg;
1098 struct wim_lookup_table_entry *cur_lte;
1101 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1102 wimlib_assert(ctx->num_outstanding_messages != 0);
1104 cur_lte = container_of(ctx->outstanding_streams.next,
1105 struct wim_lookup_table_entry,
1106 being_compressed_list);
1108 /* Get the next message from the queue and process it.
1109 * The message will contain 1 or more data chunks that have been
1111 msg = shared_queue_get(ctx->compressed_res_queue);
1112 msg->complete = true;
1113 --ctx->num_outstanding_messages;
1115 /* Is this the next chunk in the current resource? If it's not
1116 * (i.e., an earlier chunk in a same or different resource
1117 * hasn't been compressed yet), do nothing, and keep this
1118 * message around until all earlier chunks are received.
1120 * Otherwise, write all the chunks we can. */
1121 while (cur_lte != NULL &&
1122 !list_empty(&cur_lte->msg_list)
1123 && (msg = container_of(cur_lte->msg_list.next,
1127 list_move(&msg->list, &ctx->available_msgs);
1128 if (msg->begin_chunk == 0) {
1129 /* First set of chunks. */
1131 /* Write pipable WIM stream header if needed. */
1132 if (ctx->write_resource_flags &
1133 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1135 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1136 WIM_RESHDR_FLAG_COMPRESSED);
1141 /* Save current offset. */
1142 ctx->res_start_offset = ctx->out_fd->offset;
1144 /* Begin building the chunk table, and leave space for
1146 ret = begin_wim_resource_chunk_tab(cur_lte,
1148 &ctx->cur_chunk_tab,
1149 ctx->write_resource_flags);
1155 /* Write the compressed chunks from the message. */
1156 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1157 ctx->write_resource_flags);
1161 /* Was this the last chunk of the stream? If so, finish
1163 if (list_empty(&cur_lte->msg_list) &&
1164 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1168 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1170 ctx->res_start_offset,
1171 ctx->write_resource_flags);
1175 list_del(&cur_lte->being_compressed_list);
1177 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1179 FREE(ctx->cur_chunk_tab);
1180 ctx->cur_chunk_tab = NULL;
1182 /* Check for resources compressed to greater than or
1183 * equal to their original size and write them
1184 * uncompressed instead. (But never do this if writing
1186 if (res_csize >= wim_resource_size(cur_lte) &&
1187 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1189 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1190 "writing uncompressed instead",
1191 wim_resource_size(cur_lte), res_csize);
1192 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1195 ret = write_wim_resource(cur_lte,
1197 WIMLIB_COMPRESSION_TYPE_NONE,
1198 &cur_lte->output_resource_entry,
1199 ctx->write_resource_flags);
1203 cur_lte->output_resource_entry.size =
1206 cur_lte->output_resource_entry.original_size =
1207 cur_lte->resource_entry.original_size;
1209 cur_lte->output_resource_entry.offset =
1210 ctx->res_start_offset;
1212 cur_lte->output_resource_entry.flags =
1213 cur_lte->resource_entry.flags |
1214 WIM_RESHDR_FLAG_COMPRESSED;
1216 DEBUG("Wrote compressed resource "
1217 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1218 cur_lte->output_resource_entry.original_size,
1219 cur_lte->output_resource_entry.size,
1220 cur_lte->output_resource_entry.offset,
1221 cur_lte->output_resource_entry.flags);
1224 do_write_streams_progress(ctx->progress,
1226 wim_resource_size(cur_lte),
1229 /* Since we just finished writing a stream, write any
1230 * streams that have been added to the serial_streams
1231 * list for direct writing by the main thread (e.g.
1232 * resources that don't need to be compressed because
1233 * the desired compression type is the same as the
1234 * previous compression type). */
1235 if (!list_empty(&ctx->serial_streams)) {
1236 ret = do_write_stream_list_serial(&ctx->serial_streams,
1240 ctx->write_resource_flags,
1247 /* Advance to the next stream to write. */
1248 if (list_empty(&ctx->outstanding_streams)) {
1251 cur_lte = container_of(ctx->outstanding_streams.next,
1252 struct wim_lookup_table_entry,
1253 being_compressed_list);
1260 /* Called when the main thread has read a new chunk of data. */
1262 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1264 struct main_writer_thread_ctx *ctx = _ctx;
1266 struct message *next_msg;
1267 u64 next_chunk_in_msg;
1269 /* Update SHA1 message digest for the stream currently being read by the
1271 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1273 /* We send chunks of data to the compressor chunks in batches which we
1274 * refer to as "messages". @next_msg is the message that is currently
1275 * being prepared to send off. If it is NULL, that indicates that we
1276 * need to start a new message. */
1277 next_msg = ctx->next_msg;
1279 /* We need to start a new message. First check to see if there
1280 * is a message available in the list of available messages. If
1281 * so, we can just take one. If not, all the messages (there is
1282 * a fixed number of them, proportional to the number of
1283 * threads) have been sent off to the compressor threads, so we
1284 * receive messages from the compressor threads containing
1285 * compressed chunks of data.
1287 * We may need to receive multiple messages before one is
1288 * actually available to use because messages received that are
1289 * *not* for the very next set of chunks to compress must be
1290 * buffered until it's time to write those chunks. */
1291 while (list_empty(&ctx->available_msgs)) {
1292 ret = receive_compressed_chunks(ctx);
1297 next_msg = container_of(ctx->available_msgs.next,
1298 struct message, list);
1299 list_del(&next_msg->list);
1300 next_msg->complete = false;
1301 next_msg->begin_chunk = ctx->next_chunk;
1302 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1303 ctx->next_num_chunks - ctx->next_chunk);
1304 ctx->next_msg = next_msg;
1307 /* Fill in the next chunk to compress */
1308 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1310 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1311 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1314 if (++next_chunk_in_msg == next_msg->num_chunks) {
1315 /* Send off an array of chunks to compress */
1316 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1317 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1318 ++ctx->num_outstanding_messages;
1319 ctx->next_msg = NULL;
1325 main_writer_thread_finish(void *_ctx)
1327 struct main_writer_thread_ctx *ctx = _ctx;
1329 while (ctx->num_outstanding_messages != 0) {
1330 ret = receive_compressed_chunks(ctx);
1334 wimlib_assert(list_empty(&ctx->outstanding_streams));
1335 return do_write_stream_list_serial(&ctx->serial_streams,
1339 ctx->write_resource_flags,
1345 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1346 struct main_writer_thread_ctx *ctx)
1350 /* Read the entire stream @lte, feeding its data chunks to the
1351 * compressor threads. Also SHA1-sum the stream; this is required in
1352 * the case that @lte is unhashed, and a nice additional verification
1353 * when @lte is already hashed. */
1354 sha1_init(&ctx->next_sha_ctx);
1355 ctx->next_chunk = 0;
1356 ctx->next_num_chunks = wim_resource_chunks(lte);
1357 ctx->next_lte = lte;
1358 INIT_LIST_HEAD(<e->msg_list);
1359 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1360 ret = read_resource_prefix(lte, wim_resource_size(lte),
1361 main_writer_thread_cb, ctx, 0);
1364 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1365 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1369 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1371 struct main_writer_thread_ctx *ctx = _ctx;
1374 if (wim_resource_size(lte) < 1000 ||
1375 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1376 (lte->resource_location == RESOURCE_IN_WIM &&
1377 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS) &&
1378 lte->wim->compression_type == ctx->out_ctype))
1380 /* Stream is too small or isn't being compressed. Process it by
1381 * the main thread when we have a chance. We can't necessarily
1382 * process it right here, as the main thread could be in the
1383 * middle of writing a different stream. */
1384 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1388 ret = submit_stream_for_compression(lte, ctx);
1390 lte->no_progress = 1;
1395 get_default_num_threads(void)
1398 return win32_get_number_of_processors();
1400 return sysconf(_SC_NPROCESSORS_ONLN);
1404 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1405 * parameter and will perform compression using that many threads. Falls
1406 * back to write_stream_list_serial() on certain errors, such as a failure to
1407 * create the number of threads requested.
1409 * High level description of the algorithm for writing compressed streams in
1410 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1411 * rather than on full files. The currently executing thread becomes the main
1412 * thread and is entirely in charge of reading the data to compress (which may
1413 * be in any location understood by the resource code--- such as in an external
1414 * file being captured, or in another WIM file from which an image is being
1415 * exported) and actually writing the compressed data to the output file.
1416 * Additional threads are "compressor threads" and all execute the
1417 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1418 * the main thread, compress them, and hand them back to the main thread.
1420 * Certain streams, such as streams that do not need to be compressed (e.g.
1421 * input compression type same as output compression type) or streams of very
1422 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1423 * handled entirely by the main thread at an appropriate time.
1425 * At any given point in time, multiple streams may be having chunks compressed
1426 * concurrently. The stream that the main thread is currently *reading* may be
1427 * later in the list that the stream that the main thread is currently
1431 write_stream_list_parallel(struct list_head *stream_list,
1432 struct wim_lookup_table *lookup_table,
1433 struct filedes *out_fd,
1435 int write_resource_flags,
1436 wimlib_progress_func_t progress_func,
1437 union wimlib_progress_info *progress,
1438 unsigned num_threads)
1441 struct shared_queue res_to_compress_queue;
1442 struct shared_queue compressed_res_queue;
1443 pthread_t *compressor_threads = NULL;
1445 if (num_threads == 0) {
1446 long nthreads = get_default_num_threads();
1447 if (nthreads < 1 || nthreads > UINT_MAX) {
1448 WARNING("Could not determine number of processors! Assuming 1");
1450 } else if (nthreads == 1) {
1451 goto out_serial_quiet;
1453 num_threads = nthreads;
1457 DEBUG("Writing stream list of size %"PRIu64" "
1458 "(parallel version, num_threads=%u)",
1459 progress->write_streams.total_streams, num_threads);
1461 progress->write_streams.num_threads = num_threads;
1463 static const size_t MESSAGES_PER_THREAD = 2;
1464 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1466 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1468 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1472 ret = shared_queue_init(&compressed_res_queue, queue_size);
1474 goto out_destroy_res_to_compress_queue;
1476 struct compressor_thread_params params;
1477 params.res_to_compress_queue = &res_to_compress_queue;
1478 params.compressed_res_queue = &compressed_res_queue;
1479 params.compress = get_compress_func(out_ctype);
1481 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1482 if (!compressor_threads) {
1483 ret = WIMLIB_ERR_NOMEM;
1484 goto out_destroy_compressed_res_queue;
1487 for (unsigned i = 0; i < num_threads; i++) {
1488 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1489 ret = pthread_create(&compressor_threads[i], NULL,
1490 compressor_thread_proc, ¶ms);
1493 ERROR_WITH_ERRNO("Failed to create compressor "
1495 i + 1, num_threads);
1502 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1504 struct main_writer_thread_ctx ctx;
1505 ctx.stream_list = stream_list;
1506 ctx.lookup_table = lookup_table;
1507 ctx.out_fd = out_fd;
1508 ctx.out_ctype = out_ctype;
1509 ctx.res_to_compress_queue = &res_to_compress_queue;
1510 ctx.compressed_res_queue = &compressed_res_queue;
1511 ctx.num_messages = queue_size;
1512 ctx.write_resource_flags = write_resource_flags;
1513 ctx.progress_func = progress_func;
1514 ctx.progress = progress;
1515 ret = main_writer_thread_init_ctx(&ctx);
1518 ret = do_write_stream_list(stream_list, lookup_table,
1519 main_thread_process_next_stream,
1520 &ctx, progress_func, progress);
1522 goto out_destroy_ctx;
1524 /* The main thread has finished reading all streams that are going to be
1525 * compressed in parallel, and it now needs to wait for all remaining
1526 * chunks to be compressed so that the remaining streams can actually be
1527 * written to the output file. Furthermore, any remaining streams that
1528 * had processing deferred to the main thread need to be handled. These
1529 * tasks are done by the main_writer_thread_finish() function. */
1530 ret = main_writer_thread_finish(&ctx);
1532 main_writer_thread_destroy_ctx(&ctx);
1534 for (unsigned i = 0; i < num_threads; i++)
1535 shared_queue_put(&res_to_compress_queue, NULL);
1537 for (unsigned i = 0; i < num_threads; i++) {
1538 if (pthread_join(compressor_threads[i], NULL)) {
1539 WARNING_WITH_ERRNO("Failed to join compressor "
1541 i + 1, num_threads);
1544 FREE(compressor_threads);
1545 out_destroy_compressed_res_queue:
1546 shared_queue_destroy(&compressed_res_queue);
1547 out_destroy_res_to_compress_queue:
1548 shared_queue_destroy(&res_to_compress_queue);
1549 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1552 WARNING("Falling back to single-threaded compression");
1554 return write_stream_list_serial(stream_list,
1558 write_resource_flags,
1566 * Write a list of streams to a WIM (@out_fd) using the compression type
1567 * @out_ctype and up to @num_threads compressor threads.
1570 write_stream_list(struct list_head *stream_list,
1571 struct wim_lookup_table *lookup_table,
1572 struct filedes *out_fd, int out_ctype, int write_flags,
1573 unsigned num_threads, wimlib_progress_func_t progress_func)
1575 struct wim_lookup_table_entry *lte;
1576 size_t num_streams = 0;
1577 u64 total_bytes = 0;
1578 u64 total_compression_bytes = 0;
1579 union wimlib_progress_info progress;
1581 int write_resource_flags;
1583 if (list_empty(stream_list))
1586 write_resource_flags = write_flags_to_resource_flags(write_flags);
1588 DEBUG("write_resource_flags=0x%08x", write_resource_flags);
1590 /* Calculate the total size of the streams to be written. Note: this
1591 * will be the uncompressed size, as we may not know the compressed size
1592 * yet, and also this will assume that every unhashed stream will be
1593 * written (which will not necessarily be the case). */
1594 list_for_each_entry(lte, stream_list, write_streams_list) {
1596 total_bytes += wim_resource_size(lte);
1597 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1598 && (wim_resource_compression_type(lte) != out_ctype ||
1599 (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)))
1601 total_compression_bytes += wim_resource_size(lte);
1604 progress.write_streams.total_bytes = total_bytes;
1605 progress.write_streams.total_streams = num_streams;
1606 progress.write_streams.completed_bytes = 0;
1607 progress.write_streams.completed_streams = 0;
1608 progress.write_streams.num_threads = num_threads;
1609 progress.write_streams.compression_type = out_ctype;
1610 progress.write_streams._private = 0;
1612 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1613 if (total_compression_bytes >= 2000000 && num_threads != 1)
1614 ret = write_stream_list_parallel(stream_list,
1618 write_resource_flags,
1624 ret = write_stream_list_serial(stream_list,
1628 write_resource_flags,
1632 DEBUG("Successfully wrote stream list.");
1634 DEBUG("Failed to write stream list.");
1638 struct stream_size_table {
1639 struct hlist_head *array;
1645 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1647 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1649 return WIMLIB_ERR_NOMEM;
1650 tab->num_entries = 0;
1651 tab->capacity = capacity;
1656 destroy_stream_size_table(struct stream_size_table *tab)
1662 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1664 struct stream_size_table *tab = _tab;
1666 struct wim_lookup_table_entry *same_size_lte;
1667 struct hlist_node *tmp;
1669 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1670 lte->unique_size = 1;
1671 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1672 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1673 lte->unique_size = 0;
1674 same_size_lte->unique_size = 0;
1679 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1685 struct lte_overwrite_prepare_args {
1688 struct list_head stream_list;
1689 struct stream_size_table stream_size_tab;
1692 /* First phase of preparing streams for an in-place overwrite. This is called
1693 * on all streams, both hashed and unhashed, except the metadata resources. */
1695 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1697 struct lte_overwrite_prepare_args *args = _args;
1699 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1700 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1701 list_add_tail(<e->write_streams_list, &args->stream_list);
1702 lte->out_refcnt = lte->refcnt;
1703 stream_size_table_insert(lte, &args->stream_size_tab);
1707 /* Second phase of preparing streams for an in-place overwrite. This is called
1708 * on existing metadata resources and hashed streams, but not unhashed streams.
1710 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1711 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1712 * the latter uses lte->hash_list_2, while the former expects to set
1713 * lte->output_resource_entry. */
1715 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1717 struct lte_overwrite_prepare_args *args = _args;
1719 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1720 /* We can't do an in place overwrite on the WIM if there are
1721 * streams after the XML data. */
1722 if (lte->resource_entry.offset +
1723 lte->resource_entry.size > args->end_offset)
1725 if (wimlib_print_errors) {
1726 ERROR("The following resource is after the XML data:");
1727 print_lookup_table_entry(lte, stderr);
1729 return WIMLIB_ERR_RESOURCE_ORDER;
1731 copy_resource_entry(<e->output_resource_entry,
1732 <e->resource_entry);
1737 /* Given a WIM that we are going to overwrite in place with zero or more
1738 * additional streams added, construct a list the list of new unique streams
1739 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1740 * streams that need to be added but may be identical to other hashed or
1741 * unhashed streams. These unhashed streams are checksummed while the streams
1742 * are being written. To aid this process, the member @unique_size is set to 1
1743 * on streams that have a unique size and therefore must be written.
1745 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1746 * indicate the number of times the stream is referenced in only the streams
1747 * that are being written; this may still be adjusted later when unhashed
1748 * streams are being resolved.
1751 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1752 struct list_head *stream_list)
1755 struct lte_overwrite_prepare_args args;
1759 args.end_offset = end_offset;
1760 ret = init_stream_size_table(&args.stream_size_tab,
1761 wim->lookup_table->capacity);
1765 INIT_LIST_HEAD(&args.stream_list);
1766 for (i = 0; i < wim->hdr.image_count; i++) {
1767 struct wim_image_metadata *imd;
1768 struct wim_lookup_table_entry *lte;
1770 imd = wim->image_metadata[i];
1771 image_for_each_unhashed_stream(lte, imd)
1772 lte_overwrite_prepare(lte, &args);
1774 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1775 list_transfer(&args.stream_list, stream_list);
1777 for (i = 0; i < wim->hdr.image_count; i++) {
1778 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1781 goto out_destroy_stream_size_table;
1783 ret = for_lookup_table_entry(wim->lookup_table,
1784 lte_overwrite_prepare_2, &args);
1785 out_destroy_stream_size_table:
1786 destroy_stream_size_table(&args.stream_size_tab);
1791 struct find_streams_ctx {
1792 struct list_head stream_list;
1793 struct stream_size_table stream_size_tab;
1797 inode_find_streams_to_write(struct wim_inode *inode,
1798 struct wim_lookup_table *table,
1799 struct list_head *stream_list,
1800 struct stream_size_table *tab)
1802 struct wim_lookup_table_entry *lte;
1803 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1804 lte = inode_stream_lte(inode, i, table);
1806 if (lte->out_refcnt == 0) {
1808 stream_size_table_insert(lte, tab);
1809 list_add_tail(<e->write_streams_list, stream_list);
1811 lte->out_refcnt += inode->i_nlink;
1817 image_find_streams_to_write(WIMStruct *wim)
1819 struct find_streams_ctx *ctx;
1820 struct wim_image_metadata *imd;
1821 struct wim_inode *inode;
1822 struct wim_lookup_table_entry *lte;
1825 imd = wim_get_current_image_metadata(wim);
1827 image_for_each_unhashed_stream(lte, imd)
1828 lte->out_refcnt = 0;
1830 /* Go through this image's inodes to find any streams that have not been
1832 image_for_each_inode(inode, imd) {
1833 inode_find_streams_to_write(inode, wim->lookup_table,
1835 &ctx->stream_size_tab);
1840 /* Given a WIM that from which one or all of the images is being written, build
1841 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1842 * written, plus any unhashed streams that need to be written but may be
1843 * identical to other hashed or unhashed streams being written. These unhashed
1844 * streams are checksummed while the streams are being written. To aid this
1845 * process, the member @unique_size is set to 1 on streams that have a unique
1846 * size and therefore must be written.
1848 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1849 * indicate the number of times the stream is referenced in only the streams
1850 * that are being written; this may still be adjusted later when unhashed
1851 * streams are being resolved.
1854 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1857 struct find_streams_ctx ctx;
1859 DEBUG("Preparing list of streams to write for image %d.", image);
1861 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1862 ret = init_stream_size_table(&ctx.stream_size_tab,
1863 wim->lookup_table->capacity);
1866 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1867 &ctx.stream_size_tab);
1868 INIT_LIST_HEAD(&ctx.stream_list);
1869 wim->private = &ctx;
1870 ret = for_image(wim, image, image_find_streams_to_write);
1871 destroy_stream_size_table(&ctx.stream_size_tab);
1874 list_transfer(&ctx.stream_list, stream_list);
1878 /* Writes the streams for the specified @image in @wim to @wim->out_fd.
1879 * Alternatively, if @stream_list_override is specified, it is taken to be the
1880 * list of streams to write (connected with 'write_streams_list') and @image is
1883 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1884 unsigned num_threads,
1885 wimlib_progress_func_t progress_func,
1886 struct list_head *stream_list_override)
1889 struct list_head _stream_list;
1890 struct list_head *stream_list;
1891 struct wim_lookup_table_entry *lte;
1893 if (stream_list_override) {
1894 stream_list = stream_list_override;
1895 list_for_each_entry(lte, stream_list, write_streams_list) {
1897 lte->out_refcnt = lte->refcnt;
1899 lte->out_refcnt = 1;
1902 stream_list = &_stream_list;
1903 ret = prepare_stream_list(wim, image, stream_list);
1907 list_for_each_entry(lte, stream_list, write_streams_list)
1908 lte->part_number = wim->hdr.part_number;
1909 return write_stream_list(stream_list,
1912 wim->compression_type,
1919 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1920 wimlib_progress_func_t progress_func)
1925 int write_resource_flags;
1927 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
1930 write_resource_flags = write_flags_to_resource_flags(write_flags);
1932 DEBUG("Writing metadata resources (offset=%"PRIu64")",
1933 wim->out_fd.offset);
1936 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1938 if (image == WIMLIB_ALL_IMAGES) {
1940 end_image = wim->hdr.image_count;
1942 start_image = image;
1946 for (int i = start_image; i <= end_image; i++) {
1947 struct wim_image_metadata *imd;
1949 imd = wim->image_metadata[i - 1];
1950 if (imd->modified) {
1951 ret = write_metadata_resource(wim, i,
1952 write_resource_flags);
1954 ret = write_wim_resource(imd->metadata_lte,
1956 wim->compression_type,
1957 &imd->metadata_lte->output_resource_entry,
1958 write_resource_flags);
1964 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1969 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
1972 DEBUG("Opening \"%"TS"\" for writing.", path);
1974 raw_fd = topen(path, open_flags | O_BINARY, 0644);
1976 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
1977 return WIMLIB_ERR_OPEN;
1979 filedes_init(&wim->out_fd, raw_fd);
1984 close_wim_writable(WIMStruct *wim, int write_flags)
1988 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
1989 if (filedes_valid(&wim->out_fd))
1990 if (filedes_close(&wim->out_fd))
1991 ret = WIMLIB_ERR_WRITE;
1992 filedes_invalidate(&wim->out_fd);
1997 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1998 * table, then overwrite the WIM header. Always closes the WIM file descriptor
2001 * write_flags is a bitwise OR of the following:
2003 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2004 * Include an integrity table.
2006 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2007 * fsync() the output file before closing it.
2009 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2010 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2011 * stream headers before the lookup table and XML data, and also
2012 * write the WIM header at the end instead of seeking to the
2013 * beginning. Can't be combined with
2014 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2016 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2017 * Don't write the lookup table.
2019 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2020 * When (if) writing the integrity table, re-use entries from the
2021 * existing integrity table, if possible.
2023 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2024 * After writing the XML data but before writing the integrity
2025 * table, write a temporary WIM header and flush the stream so that
2026 * the WIM is less likely to become corrupted upon abrupt program
2028 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2029 * Instead of overwriting the WIM header at the beginning of the
2030 * file, simply append it to the end of the file. (Used when
2032 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2033 * Use the existing <TOTALBYTES> stored in the in-memory XML
2034 * information, rather than setting it to the offset of the XML
2035 * data being written.
2038 finish_write(WIMStruct *wim, int image, int write_flags,
2039 wimlib_progress_func_t progress_func,
2040 struct list_head *stream_list_override)
2044 int write_resource_flags;
2045 off_t old_lookup_table_end;
2046 off_t new_lookup_table_end;
2049 write_resource_flags = write_flags_to_resource_flags(write_flags);
2051 /* In the WIM header, there is room for the resource entry for a
2052 * metadata resource labeled as the "boot metadata". This entry should
2053 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2054 * it should be a copy of the resource entry for the image that is
2055 * marked as bootable. This is not well documented... */
2056 if (wim->hdr.boot_idx == 0) {
2057 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2059 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2060 &wim->image_metadata[wim->hdr.boot_idx- 1
2061 ]->metadata_lte->output_resource_entry);
2064 /* Write lookup table. (Save old position first.) */
2065 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2066 wim->hdr.lookup_table_res_entry.size;
2067 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2068 ret = write_wim_lookup_table(wim, image, write_flags,
2069 &wim->hdr.lookup_table_res_entry,
2070 stream_list_override);
2075 /* Write XML data. */
2076 xml_totalbytes = wim->out_fd.offset;
2077 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2078 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2079 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2080 &wim->hdr.xml_res_entry,
2081 write_resource_flags);
2085 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2086 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2087 struct wim_header checkpoint_hdr;
2088 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2089 zero_resource_entry(&checkpoint_hdr.integrity);
2090 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2091 ret = write_wim_header_at_offset(&checkpoint_hdr,
2097 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2098 old_lookup_table_end = 0;
2100 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2101 wim->hdr.lookup_table_res_entry.size;
2103 ret = write_integrity_table(wim,
2104 new_lookup_table_end,
2105 old_lookup_table_end,
2110 zero_resource_entry(&wim->hdr.integrity);
2113 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2115 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2116 hdr_offset = wim->out_fd.offset;
2117 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2121 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2122 if (fsync(wim->out_fd.fd)) {
2123 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2124 ret = WIMLIB_ERR_WRITE;
2131 if (close_wim_writable(wim, write_flags)) {
2133 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2134 ret = WIMLIB_ERR_WRITE;
2140 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2142 lock_wim(WIMStruct *wim, int fd)
2145 if (fd != -1 && !wim->wim_locked) {
2146 ret = flock(fd, LOCK_EX | LOCK_NB);
2148 if (errno == EWOULDBLOCK) {
2149 ERROR("`%"TS"' is already being modified or has been "
2150 "mounted read-write\n"
2151 " by another process!", wim->filename);
2152 ret = WIMLIB_ERR_ALREADY_LOCKED;
2154 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2159 wim->wim_locked = 1;
2167 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2168 * capable of being applied from a pipe). Such a WIM looks like:
2170 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2171 * images can be applied from them sequentially when the file data is sent over
2172 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2173 * The modifications made to the WIM format for pipable WIMs are:
2175 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2176 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2177 * should stop other software from trying to read the file as a normal WIM.
2179 * - The header at the beginning of the file does not contain all the normal
2180 * information; in particular it will have all 0's for the lookup table and
2181 * XML data resource entries. This is because this information cannot be
2182 * determined until the lookup table and XML data have been written.
2183 * Consequently, wimlib will write the full header at the very end of the
2184 * file. The header at the end, however, is only used when reading the WIM
2185 * from a seekable file (not a pipe).
2187 * - An extra copy of the XML data is placed directly after the header. This
2188 * allows image names and sizes to be determined at an appropriate time when
2189 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2190 * WIM is read from a seekable file (not a pipe).
2192 * - The format of resources, or streams, has been modified to allow them to be
2193 * used before the "lookup table" has been read. Each stream is prefixed with
2194 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2195 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2196 * uncompressed stream size, and flags that indicate whether the stream is
2197 * compressed. The data of uncompressed streams then follows literally, while
2198 * the data of compressed streams follows in a modified format. Compressed
2199 * streams have no chunk table, since the chunk table cannot be written until
2200 * all chunks have been compressed; instead, each compressed chunk is prefixed
2201 * by a `struct pwm_chunk_hdr' that gives its size. However, the offsets are
2202 * given in the chunk table as if these chunk headers were not present.
2204 * - Metadata resources always come before other file resources (streams).
2205 * (This does not by itself constitute an incompatibility with normal WIMs,
2206 * since this is valid in normal WIMs.)
2208 * - At least up to the end of the file resources, all components must be packed
2209 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2210 * not by itself consititute an incompatibility with normal WIMs, since this
2211 * is valid in normal WIMs.)
2213 * Note: the lookup table, XML data, and header at the end are not used when
2214 * applying from a pipe. They exist to support functionality such as image
2215 * application and export when the WIM is *not* read from a pipe.
2217 * Layout of pipable WIM:
2219 * ----------+----------+--------------------+----------------+--------------+------------+--------+
2220 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2221 * ----------+----------+--------------------+----------------+--------------+------------+--------+
2223 * Layout of normal WIM:
2225 * +---------+--------------------+----------------+--------------+----------+
2226 * | Header | Metadata resources | File resources | Lookup table | XML data |
2227 * +---------+--------------------+----------------+--------------+----------+
2229 * Do note that since pipable WIMs are not supported by Microsoft's software,
2230 * wimlib does not create them unless explicitly requested (with
2231 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2232 * characters to identify the file.
2235 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2236 unsigned num_threads, wimlib_progress_func_t progress_func,
2237 struct list_head *stream_list_override)
2240 struct resource_entry xml_res_entry;
2242 WARNING("Creating a pipable WIM, which will "
2244 " with Microsoft's software (wimgapi/imagex/Dism).");
2246 /* At this point, the header at the beginning of the file has already
2249 /* For efficiency, when wimlib adds an image to the WIM with
2250 * wimlib_add_image(), the SHA1 message digests of files is not
2251 * calculated; instead, they are calculated while the files are being
2252 * written. However, this does not work when writing a pipable WIM,
2253 * since when writing a stream to a pipable WIM, its SHA1 message digest
2254 * needs to be known before the stream data is written. Therefore,
2255 * before getting much farther, we need to pre-calculate the SHA1
2256 * message digests of all streams that will be written. */
2257 ret = wim_checksum_unhashed_streams(wim);
2261 /* Write extra copy of the XML data. */
2262 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2264 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2268 /* Write metadata resources for the image(s) being included in the
2270 ret = write_wim_metadata_resources(wim, image, write_flags,
2275 /* Write streams needed for the image(s) being included in the output
2276 * WIM, or streams needed for the split WIM part. */
2277 return write_wim_streams(wim, image, write_flags, num_threads,
2278 progress_func, stream_list_override);
2280 /* The lookup table, XML data, and header at end are handled by
2281 * finish_write(). */
2284 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2287 write_wim_part(WIMStruct *wim,
2288 const void *path_or_fd,
2291 unsigned num_threads,
2292 wimlib_progress_func_t progress_func,
2293 unsigned part_number,
2294 unsigned total_parts,
2295 struct list_head *stream_list_override,
2299 struct wim_header hdr_save;
2300 struct list_head lt_stream_list_override;
2302 if (total_parts == 1)
2303 DEBUG("Writing standalone WIM.");
2305 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2306 if (image == WIMLIB_ALL_IMAGES)
2307 DEBUG("Including all images.");
2309 DEBUG("Including image %d only.", image);
2310 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2311 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2313 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2314 DEBUG("Write flags: 0x%08x", write_flags);
2315 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2316 DEBUG("\tCHECK_INTEGRITY");
2317 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2319 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2320 DEBUG("\tRECOMPRESS");
2321 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2323 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2325 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2326 DEBUG("\tIGNORE_READONLY_FLAG");
2327 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2329 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2330 DEBUG("\tFILE_DESCRIPTOR");
2331 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2332 DEBUG("\tNO_METADATA");
2333 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2334 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2335 if (num_threads == 0)
2336 DEBUG("Number of threads: autodetect");
2338 DEBUG("Number of threads: %u", num_threads);
2339 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2340 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2341 DEBUG("GUID: %s", (guid ? "specified" : "generate new"));
2343 /* Internally, this is always called with a valid part number and total
2345 wimlib_assert(total_parts >= 1);
2346 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2348 /* A valid image (or all images) must be specified. */
2349 if (image != WIMLIB_ALL_IMAGES &&
2350 (image < 1 || image > wim->hdr.image_count))
2351 return WIMLIB_ERR_INVALID_IMAGE;
2353 /* @wim must specify a standalone WIM. */
2354 if (wim->hdr.total_parts != 1)
2355 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2357 /* Check for contradictory flags. */
2358 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2359 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2360 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2361 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2362 return WIMLIB_ERR_INVALID_PARAM;
2364 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2365 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2366 == (WIMLIB_WRITE_FLAG_PIPABLE |
2367 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2368 return WIMLIB_ERR_INVALID_PARAM;
2370 /* Save previous header, then start initializing the new one. */
2371 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2373 /* Set default integrity and pipable flags. */
2374 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2375 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2376 if (wim_is_pipable(wim))
2377 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2379 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2380 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2381 if (wim_has_integrity_table(wim))
2382 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2384 /* Set appropriate magic number. */
2385 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2386 wim->hdr.magic = PWM_MAGIC;
2388 wim->hdr.magic = WIM_MAGIC;
2390 /* Clear header flags that will be set automatically. */
2391 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2392 WIM_HDR_FLAG_RESOURCE_ONLY |
2393 WIM_HDR_FLAG_SPANNED |
2394 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2396 /* Set SPANNED header flag if writing part of a split WIM. */
2397 if (total_parts != 1)
2398 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2400 /* Set part number and total parts of split WIM. This will be 1 and 1
2401 * if the WIM is standalone. */
2402 wim->hdr.part_number = part_number;
2403 wim->hdr.total_parts = total_parts;
2405 /* Use GUID if specified; otherwise generate a new one. */
2407 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2409 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2411 /* Clear references to resources that have not been written yet. */
2412 zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2413 zero_resource_entry(&wim->hdr.xml_res_entry);
2414 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2415 zero_resource_entry(&wim->hdr.integrity);
2417 /* Set image count and boot index correctly for single image writes. */
2418 if (image != WIMLIB_ALL_IMAGES) {
2419 wim->hdr.image_count = 1;
2420 if (wim->hdr.boot_idx == image)
2421 wim->hdr.boot_idx = 1;
2423 wim->hdr.boot_idx = 0;
2426 /* Split WIMs can't be bootable. */
2427 if (total_parts != 1)
2428 wim->hdr.boot_idx = 0;
2430 /* Initialize output file descriptor. */
2431 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2432 /* File descriptor was explicitly provided. Return error if
2433 * file descriptor is not seekable, unless writing a pipable WIM
2435 wim->out_fd.fd = *(const int*)path_or_fd;
2436 wim->out_fd.offset = 0;
2437 if (!filedes_is_seekable(&wim->out_fd)) {
2438 ret = WIMLIB_ERR_INVALID_PARAM;
2439 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2440 goto out_restore_hdr;
2441 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2442 ERROR("Can't include integrity check when "
2443 "writing pipable WIM to pipe!");
2444 goto out_restore_hdr;
2449 /* Filename of WIM to write was provided; open file descriptor
2451 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2452 O_TRUNC | O_CREAT | O_RDWR);
2454 goto out_restore_hdr;
2457 /* Write initial header. This is merely a "dummy" header since it
2458 * doesn't have all the information yet, so it will be overwritten later
2459 * (unless writing a pipable WIM). */
2460 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2461 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2462 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2463 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2465 goto out_restore_hdr;
2467 if (stream_list_override) {
2468 struct wim_lookup_table_entry *lte;
2469 INIT_LIST_HEAD(<_stream_list_override);
2470 list_for_each_entry(lte, stream_list_override,
2473 list_add_tail(<e->lookup_table_list,
2474 <_stream_list_override);
2478 /* Write metadata resources and streams. */
2479 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2480 /* Default case: create a normal (non-pipable) WIM. */
2481 ret = write_wim_streams(wim, image, write_flags, num_threads,
2482 progress_func, stream_list_override);
2484 goto out_restore_hdr;
2486 ret = write_wim_metadata_resources(wim, image, write_flags,
2489 goto out_restore_hdr;
2491 /* Non-default case: create pipable WIM. */
2492 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2493 progress_func, stream_list_override);
2495 goto out_restore_hdr;
2496 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2499 if (stream_list_override)
2500 stream_list_override = <_stream_list_override;
2502 /* Write lookup table, XML data, and (optional) integrity table. */
2503 ret = finish_write(wim, image, write_flags, progress_func,
2504 stream_list_override);
2506 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2507 close_wim_writable(wim, write_flags);
2511 /* Write a standalone WIM to a file or file descriptor. */
2513 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2514 int image, int write_flags, unsigned num_threads,
2515 wimlib_progress_func_t progress_func)
2517 return write_wim_part(wim, path_or_fd, image, write_flags,
2518 num_threads, progress_func, 1, 1, NULL, NULL);
2521 /* API function documented in wimlib.h */
2523 wimlib_write(WIMStruct *wim, const tchar *path,
2524 int image, int write_flags, unsigned num_threads,
2525 wimlib_progress_func_t progress_func)
2528 return WIMLIB_ERR_INVALID_PARAM;
2530 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2532 return write_standalone_wim(wim, path, image, write_flags,
2533 num_threads, progress_func);
2536 /* API function documented in wimlib.h */
2538 wimlib_write_to_fd(WIMStruct *wim, int fd,
2539 int image, int write_flags, unsigned num_threads,
2540 wimlib_progress_func_t progress_func)
2543 return WIMLIB_ERR_INVALID_PARAM;
2545 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2546 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2548 return write_standalone_wim(wim, &fd, image, write_flags,
2549 num_threads, progress_func);
2553 any_images_modified(WIMStruct *wim)
2555 for (int i = 0; i < wim->hdr.image_count; i++)
2556 if (wim->image_metadata[i]->modified)
2562 * Overwrite a WIM, possibly appending streams to it.
2564 * A WIM looks like (or is supposed to look like) the following:
2566 * Header (212 bytes)
2567 * Streams and metadata resources (variable size)
2568 * Lookup table (variable size)
2569 * XML data (variable size)
2570 * Integrity table (optional) (variable size)
2572 * If we are not adding any streams or metadata resources, the lookup table is
2573 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2574 * header. This operation is potentially unsafe if the program is abruptly
2575 * terminated while the XML data or integrity table are being overwritten, but
2576 * before the new header has been written. To partially alleviate this problem,
2577 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2578 * finish_write() to cause a temporary WIM header to be written after the XML
2579 * data has been written. This may prevent the WIM from becoming corrupted if
2580 * the program is terminated while the integrity table is being calculated (but
2581 * no guarantees, due to write re-ordering...).
2583 * If we are adding new streams or images (metadata resources), the lookup table
2584 * needs to be changed, and those streams need to be written. In this case, we
2585 * try to perform a safe update of the WIM file by writing the streams *after*
2586 * the end of the previous WIM, then writing the new lookup table, XML data, and
2587 * (optionally) integrity table following the new streams. This will produce a
2588 * layout like the following:
2590 * Header (212 bytes)
2591 * (OLD) Streams and metadata resources (variable size)
2592 * (OLD) Lookup table (variable size)
2593 * (OLD) XML data (variable size)
2594 * (OLD) Integrity table (optional) (variable size)
2595 * (NEW) Streams and metadata resources (variable size)
2596 * (NEW) Lookup table (variable size)
2597 * (NEW) XML data (variable size)
2598 * (NEW) Integrity table (optional) (variable size)
2600 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2601 * the header is overwritten to point to the new lookup table, XML data, and
2602 * integrity table, to produce the following layout:
2604 * Header (212 bytes)
2605 * Streams and metadata resources (variable size)
2606 * Nothing (variable size)
2607 * More Streams and metadata resources (variable size)
2608 * Lookup table (variable size)
2609 * XML data (variable size)
2610 * Integrity table (optional) (variable size)
2612 * This method allows an image to be appended to a large WIM very quickly, and
2613 * is is crash-safe except in the case of write re-ordering, but the
2614 * disadvantage is that a small hole is left in the WIM where the old lookup
2615 * table, xml data, and integrity table were. (These usually only take up a
2616 * small amount of space compared to the streams, however.)
2619 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2620 unsigned num_threads,
2621 wimlib_progress_func_t progress_func)
2624 struct list_head stream_list;
2626 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2629 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2631 /* Set default integrity flag. */
2632 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2633 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2634 if (wim_has_integrity_table(wim))
2635 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2637 /* Make sure that the integrity table (if present) is after the XML
2638 * data, and that there are no stream resources, metadata resources, or
2639 * lookup tables after the XML data. Otherwise, these data would be
2641 old_xml_begin = wim->hdr.xml_res_entry.offset;
2642 old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2643 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2644 wim->hdr.lookup_table_res_entry.size;
2645 if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2646 ERROR("Didn't expect the integrity table to be before the XML data");
2647 return WIMLIB_ERR_RESOURCE_ORDER;
2650 if (old_lookup_table_end > old_xml_begin) {
2651 ERROR("Didn't expect the lookup table to be after the XML data");
2652 return WIMLIB_ERR_RESOURCE_ORDER;
2655 /* Set @old_wim_end, which indicates the point beyond which we don't
2656 * allow any file and metadata resources to appear without returning
2657 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2658 * overwrite these resources). */
2659 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2660 /* If no images have been modified and no images have been
2661 * deleted, a new lookup table does not need to be written. We
2662 * shall write the new XML data and optional integrity table
2663 * immediately after the lookup table. Note that this may
2664 * overwrite an existing integrity table. */
2665 DEBUG("Skipping writing lookup table "
2666 "(no images modified or deleted)");
2667 old_wim_end = old_lookup_table_end;
2668 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2669 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2670 } else if (wim->hdr.integrity.offset) {
2671 /* Old WIM has an integrity table; begin writing new streams
2673 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2675 /* No existing integrity table; begin writing new streams after
2676 * the old XML data. */
2677 old_wim_end = old_xml_end;
2680 ret = prepare_streams_for_overwrite(wim, old_wim_end, &stream_list);
2684 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2688 ret = lock_wim(wim, wim->out_fd.fd);
2690 close_wim_writable(wim, write_flags);
2694 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2695 ret = write_wim_header_flags(wim->hdr.flags | WIM_HDR_FLAG_WRITE_IN_PROGRESS,
2698 ERROR_WITH_ERRNO("Error updating WIM header flags");
2699 close_wim_writable(wim, write_flags);
2700 goto out_unlock_wim;
2703 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2704 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2705 close_wim_writable(wim, write_flags);
2706 ret = WIMLIB_ERR_WRITE;
2707 goto out_unlock_wim;
2710 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2712 ret = write_stream_list(&stream_list,
2715 wim->compression_type,
2722 for (unsigned i = 1; i <= wim->hdr.image_count; i++) {
2723 if (wim->image_metadata[i - 1]->modified) {
2724 ret = write_metadata_resource(wim, i, 0);
2729 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2730 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2731 progress_func, NULL);
2733 close_wim_writable(wim, write_flags);
2734 if (ret && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2735 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2736 wim->filename, old_wim_end);
2737 /* Return value of truncate() is ignored because this is already
2739 (void)ttruncate(wim->filename, old_wim_end);
2742 wim->wim_locked = 0;
2747 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2748 unsigned num_threads,
2749 wimlib_progress_func_t progress_func)
2751 size_t wim_name_len;
2754 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2756 /* Write the WIM to a temporary file in the same directory as the
2758 wim_name_len = tstrlen(wim->filename);
2759 tchar tmpfile[wim_name_len + 10];
2760 tmemcpy(tmpfile, wim->filename, wim_name_len);
2761 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2762 tmpfile[wim_name_len + 9] = T('\0');
2764 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2765 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2766 num_threads, progress_func);
2772 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
2773 /* Rename the new file to the old file .*/
2774 if (trename(tmpfile, wim->filename) != 0) {
2775 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2776 tmpfile, wim->filename);
2777 ret = WIMLIB_ERR_RENAME;
2781 if (progress_func) {
2782 union wimlib_progress_info progress;
2783 progress.rename.from = tmpfile;
2784 progress.rename.to = wim->filename;
2785 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2790 /* Remove temporary file. */
2795 /* API function documented in wimlib.h */
2797 wimlib_overwrite(WIMStruct *wim, int write_flags,
2798 unsigned num_threads,
2799 wimlib_progress_func_t progress_func)
2804 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2806 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2807 return WIMLIB_ERR_INVALID_PARAM;
2810 return WIMLIB_ERR_NO_FILENAME;
2812 orig_hdr_flags = wim->hdr.flags;
2813 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2814 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
2815 ret = can_modify_wim(wim);
2816 wim->hdr.flags = orig_hdr_flags;
2820 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2821 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
2822 WIMLIB_WRITE_FLAG_PIPABLE))
2823 && !(wim_is_pipable(wim)))
2825 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
2827 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
2829 WARNING("Falling back to re-building entire WIM");
2831 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,