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/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "list.h" so that "list.h" can
31 * overwrite the LIST_HEAD macro. */
32 # include <sys/file.h>
40 #include "wimlib_internal.h"
41 #include "buffer_io.h"
43 #include "lookup_table.h"
46 #ifdef ENABLE_MULTITHREADED_COMPRESSION
56 # include <ntfs-3g/attrib.h>
57 # include <ntfs-3g/inode.h>
58 # include <ntfs-3g/dir.h>
70 # include <sys/uio.h> /* for `struct iovec' */
73 /* Chunk table that's located at the beginning of each compressed resource in
74 * the WIM. (This is not the on-disk format; the on-disk format just has an
75 * array of offsets.) */
79 u64 original_resource_size;
80 u64 bytes_per_chunk_entry;
88 * Allocates and initializes a chunk table, and reserves space for it in the
92 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
95 struct chunk_table **chunk_tab_ret)
97 u64 size = wim_resource_size(lte);
98 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
99 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
100 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
102 DEBUG("Begin chunk table for stream with size %"PRIu64, size);
105 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
107 return WIMLIB_ERR_NOMEM;
109 chunk_tab->file_offset = file_offset;
110 chunk_tab->num_chunks = num_chunks;
111 chunk_tab->original_resource_size = size;
112 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
113 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
115 chunk_tab->cur_offset = 0;
116 chunk_tab->cur_offset_p = chunk_tab->offsets;
118 if (full_write(out_fd, chunk_tab,
119 chunk_tab->table_disk_size) != chunk_tab->table_disk_size)
121 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
124 return WIMLIB_ERR_WRITE;
126 *chunk_tab_ret = chunk_tab;
131 * compress_func_t- Pointer to a function to compresses a chunk
132 * of a WIM resource. This may be either
133 * wimlib_xpress_compress() (xpress-compress.c) or
134 * wimlib_lzx_compress() (lzx-compress.c).
136 * @chunk: Uncompressed data of the chunk.
137 * @chunk_size: Size of the uncompressed chunk, in bytes.
138 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
140 * Returns the size of the compressed data written to @out in bytes, or 0 if the
141 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
143 * As a special requirement, the compression code is optimized for the WIM
144 * format and therefore requires (@chunk_size <= 32768).
146 * As another special requirement, the compression code will read up to 8 bytes
147 * off the end of the @chunk array for performance reasons. The values of these
148 * bytes will not affect the output of the compression, but the calling code
149 * must make sure that the buffer holding the uncompressed chunk is actually at
150 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
151 * mapped memory that will not cause a memory access violation if accessed.
153 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
156 static compress_func_t
157 get_compress_func(int out_ctype)
159 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
160 return wimlib_lzx_compress;
162 return wimlib_xpress_compress;
166 * Writes a chunk of a WIM resource to an output file.
168 * @chunk: Uncompressed data of the chunk.
169 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
170 * @out_fd: File descriptor to write the chunk to.
171 * @compress: Compression function to use (NULL if writing uncompressed
173 * @chunk_tab: Pointer to chunk table being created. It is updated with the
174 * offset of the chunk we write.
176 * Returns 0 on success; nonzero on failure.
179 write_wim_resource_chunk(const void * restrict chunk,
182 compress_func_t compress,
183 struct chunk_table * restrict chunk_tab)
185 const void *out_chunk;
186 unsigned out_chunk_size;
188 void *compressed_chunk = alloca(chunk_size);
190 out_chunk_size = (*compress)(chunk, chunk_size, compressed_chunk);
191 if (out_chunk_size) {
192 /* Write compressed */
193 out_chunk = compressed_chunk;
195 /* Write uncompressed */
197 out_chunk_size = chunk_size;
199 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
200 chunk_tab->cur_offset += out_chunk_size;
202 /* Write uncompressed */
204 out_chunk_size = chunk_size;
206 if (full_write(out_fd, out_chunk, out_chunk_size) != out_chunk_size) {
207 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
208 return WIMLIB_ERR_WRITE;
214 * Finishes a WIM chunk table and writes it to the output file at the correct
217 * The final size of the full compressed resource is returned in the
218 * @compressed_size_p.
221 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
222 int out_fd, u64 *compressed_size_p)
224 size_t bytes_written;
226 if (chunk_tab->bytes_per_chunk_entry == 8) {
227 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
229 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
230 ((u32*)chunk_tab->offsets)[i] =
231 cpu_to_le32(chunk_tab->offsets[i]);
233 bytes_written = full_pwrite(out_fd,
234 (u8*)chunk_tab->offsets + chunk_tab->bytes_per_chunk_entry,
235 chunk_tab->table_disk_size,
236 chunk_tab->file_offset);
237 if (bytes_written != chunk_tab->table_disk_size) {
238 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
240 return WIMLIB_ERR_WRITE;
242 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
247 seek_and_truncate(int out_fd, off_t offset)
249 if (lseek(out_fd, offset, SEEK_SET) == -1 ||
250 ftruncate(out_fd, offset))
252 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
253 return WIMLIB_ERR_WRITE;
260 finalize_and_check_sha1(SHA_CTX * restrict sha_ctx,
261 struct wim_lookup_table_entry * restrict lte)
263 u8 md[SHA1_HASH_SIZE];
264 sha1_final(md, sha_ctx);
266 copy_hash(lte->hash, md);
267 } else if (!hashes_equal(md, lte->hash)) {
268 ERROR("WIM resource has incorrect hash!");
269 if (lte_filename_valid(lte)) {
270 ERROR("We were reading it from \"%"TS"\"; maybe "
271 "it changed while we were reading it.",
274 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
280 struct write_resource_ctx {
281 compress_func_t compress;
282 struct chunk_table *chunk_tab;
289 write_resource_cb(const void *restrict chunk, size_t chunk_size,
292 struct write_resource_ctx *ctx = _ctx;
295 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
296 return write_wim_resource_chunk(chunk, chunk_size,
297 ctx->out_fd, ctx->compress,
302 * Write a resource to an output WIM.
304 * @lte: Lookup table entry for the resource, which could be in another WIM,
305 * in an external file, or in another location.
307 * @out_fd: File descriptor opened to the output WIM.
309 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
310 * which compression algorithm to use.
312 * @out_res_entry: On success, this is filled in with the offset, flags,
313 * compressed size, and uncompressed size of the resource
316 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
317 * even if it could otherwise be copied directly from the input.
319 * Additional notes: The SHA1 message digest of the uncompressed data is
320 * calculated (except when doing a raw copy --- see below). If the @unhashed
321 * flag is set on the lookup table entry, this message digest is simply copied
322 * to it; otherwise, the message digest is compared with the existing one, and
323 * the function will fail if they do not match.
326 write_wim_resource(struct wim_lookup_table_entry *lte,
327 int out_fd, int out_ctype,
328 struct resource_entry *out_res_entry,
331 struct write_resource_ctx write_ctx;
337 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
339 /* Get current position in output WIM */
340 offset = filedes_offset(out_fd);
342 ERROR_WITH_ERRNO("Can't get position in output WIM");
343 return WIMLIB_ERR_WRITE;
346 /* If we are not forcing the data to be recompressed, and the input
347 * resource is located in a WIM with the same compression type as that
348 * desired other than no compression, we can simply copy the compressed
349 * data without recompressing it. This also means we must skip
350 * calculating the SHA1, as we never will see the uncompressed data. */
351 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
352 lte->resource_location == RESOURCE_IN_WIM &&
353 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
354 wimlib_get_compression_type(lte->wim) == out_ctype)
356 flags |= WIMLIB_RESOURCE_FLAG_RAW;
357 write_ctx.doing_sha = false;
358 read_size = lte->resource_entry.size;
360 write_ctx.doing_sha = true;
361 sha1_init(&write_ctx.sha_ctx);
362 read_size = lte->resource_entry.original_size;
365 /* Initialize the chunk table and set the compression function if
366 * compressing the resource. */
367 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
368 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
369 write_ctx.compress = NULL;
370 write_ctx.chunk_tab = NULL;
372 write_ctx.compress = get_compress_func(out_ctype);
373 ret = begin_wim_resource_chunk_tab(lte, out_fd,
375 &write_ctx.chunk_tab);
380 /* Write the entire resource by reading the entire resource and feeding
381 * the data through the write_resource_cb function. */
382 write_ctx.out_fd = out_fd;
384 ret = read_resource_prefix(lte, read_size,
385 write_resource_cb, &write_ctx, flags);
387 goto out_free_chunk_tab;
389 /* Verify SHA1 message digest of the resource, or set the hash for the
391 if (write_ctx.doing_sha) {
392 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
394 goto out_free_chunk_tab;
397 out_res_entry->flags = lte->resource_entry.flags;
398 out_res_entry->original_size = wim_resource_size(lte);
399 out_res_entry->offset = offset;
400 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
401 /* Doing a raw write: The new compressed size is the same as
402 * the compressed size in the other WIM. */
403 new_size = lte->resource_entry.size;
404 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
405 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
406 * is the original size. */
407 new_size = lte->resource_entry.original_size;
408 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
410 /* Using a different compression type: Call
411 * finish_wim_resource_chunk_tab() and it will provide the new
412 * compressed size. */
413 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fd,
416 goto out_free_chunk_tab;
417 if (new_size >= wim_resource_size(lte)) {
418 /* Oops! We compressed the resource to larger than the original
419 * size. Write the resource uncompressed instead. */
420 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
421 "writing uncompressed instead",
422 wim_resource_size(lte), new_size);
423 ret = seek_and_truncate(out_fd, offset);
425 goto out_free_chunk_tab;
426 write_ctx.compress = NULL;
427 write_ctx.doing_sha = false;
428 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
429 goto try_write_again;
431 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
433 out_res_entry->size = new_size;
436 FREE(write_ctx.chunk_tab);
440 #ifdef ENABLE_MULTITHREADED_COMPRESSION
442 /* Blocking shared queue (solves the producer-consumer problem) */
443 struct shared_queue {
447 unsigned filled_slots;
449 pthread_mutex_t lock;
450 pthread_cond_t msg_avail_cond;
451 pthread_cond_t space_avail_cond;
455 shared_queue_init(struct shared_queue *q, unsigned size)
457 wimlib_assert(size != 0);
458 q->array = CALLOC(sizeof(q->array[0]), size);
465 if (pthread_mutex_init(&q->lock, NULL)) {
466 ERROR_WITH_ERRNO("Failed to initialize mutex");
469 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
470 ERROR_WITH_ERRNO("Failed to initialize condition variable");
471 goto err_destroy_lock;
473 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
474 ERROR_WITH_ERRNO("Failed to initialize condition variable");
475 goto err_destroy_msg_avail_cond;
478 err_destroy_msg_avail_cond:
479 pthread_cond_destroy(&q->msg_avail_cond);
481 pthread_mutex_destroy(&q->lock);
483 return WIMLIB_ERR_NOMEM;
487 shared_queue_destroy(struct shared_queue *q)
490 pthread_mutex_destroy(&q->lock);
491 pthread_cond_destroy(&q->msg_avail_cond);
492 pthread_cond_destroy(&q->space_avail_cond);
496 shared_queue_put(struct shared_queue *q, void *obj)
498 pthread_mutex_lock(&q->lock);
499 while (q->filled_slots == q->size)
500 pthread_cond_wait(&q->space_avail_cond, &q->lock);
502 q->back = (q->back + 1) % q->size;
503 q->array[q->back] = obj;
506 pthread_cond_broadcast(&q->msg_avail_cond);
507 pthread_mutex_unlock(&q->lock);
511 shared_queue_get(struct shared_queue *q)
515 pthread_mutex_lock(&q->lock);
516 while (q->filled_slots == 0)
517 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
519 obj = q->array[q->front];
520 q->array[q->front] = NULL;
521 q->front = (q->front + 1) % q->size;
524 pthread_cond_broadcast(&q->space_avail_cond);
525 pthread_mutex_unlock(&q->lock);
529 struct compressor_thread_params {
530 struct shared_queue *res_to_compress_queue;
531 struct shared_queue *compressed_res_queue;
532 compress_func_t compress;
535 #define MAX_CHUNKS_PER_MSG 2
538 struct wim_lookup_table_entry *lte;
539 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
540 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
541 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
542 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
543 size_t total_out_bytes;
545 struct list_head list;
551 compress_chunks(struct message *msg, compress_func_t compress)
553 msg->total_out_bytes = 0;
554 for (unsigned i = 0; i < msg->num_chunks; i++) {
555 unsigned len = compress(msg->uncompressed_chunks[i],
556 msg->uncompressed_chunk_sizes[i],
557 msg->compressed_chunks[i]);
561 /* To be written compressed */
562 out_chunk = msg->compressed_chunks[i];
565 /* To be written uncompressed */
566 out_chunk = msg->uncompressed_chunks[i];
567 out_len = msg->uncompressed_chunk_sizes[i];
569 msg->out_chunks[i].iov_base = out_chunk;
570 msg->out_chunks[i].iov_len = out_len;
571 msg->total_out_bytes += out_len;
575 /* Compressor thread routine. This is a lot simpler than the main thread
576 * routine: just repeatedly get a group of chunks from the
577 * res_to_compress_queue, compress them, and put them in the
578 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
581 compressor_thread_proc(void *arg)
583 struct compressor_thread_params *params = arg;
584 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
585 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
586 compress_func_t compress = params->compress;
589 DEBUG("Compressor thread ready");
590 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
591 compress_chunks(msg, compress);
592 shared_queue_put(compressed_res_queue, msg);
594 DEBUG("Compressor thread terminating");
597 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
600 do_write_streams_progress(union wimlib_progress_info *progress,
601 wimlib_progress_func_t progress_func,
604 progress->write_streams.completed_bytes += size_added;
605 progress->write_streams.completed_streams++;
607 progress->write_streams.completed_bytes >= progress->write_streams._private)
609 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
611 if (progress->write_streams._private == progress->write_streams.total_bytes) {
612 progress->write_streams._private = ~0;
614 progress->write_streams._private =
615 min(progress->write_streams.total_bytes,
616 progress->write_streams.completed_bytes +
617 progress->write_streams.total_bytes / 100);
622 struct serial_write_stream_ctx {
625 int write_resource_flags;
629 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
631 struct serial_write_stream_ctx *ctx = _ctx;
632 return write_wim_resource(lte, ctx->out_fd,
633 ctx->out_ctype, <e->output_resource_entry,
634 ctx->write_resource_flags);
637 /* Write a list of streams, taking into account that some streams may be
638 * duplicates that are checksummed and discarded on the fly, and also delegating
639 * the actual writing of a stream to a function @write_stream_cb, which is
640 * passed the context @write_stream_ctx. */
642 do_write_stream_list(struct list_head *stream_list,
643 struct wim_lookup_table *lookup_table,
644 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
645 void *write_stream_ctx,
646 wimlib_progress_func_t progress_func,
647 union wimlib_progress_info *progress)
650 struct wim_lookup_table_entry *lte;
652 /* For each stream in @stream_list ... */
653 while (!list_empty(stream_list)) {
654 lte = container_of(stream_list->next,
655 struct wim_lookup_table_entry,
657 list_del(<e->write_streams_list);
658 if (lte->unhashed && !lte->unique_size) {
659 /* Unhashed stream that shares a size with some other
660 * stream in the WIM we are writing. The stream must be
661 * checksummed to know if we need to write it or not. */
662 struct wim_lookup_table_entry *tmp;
663 u32 orig_refcnt = lte->out_refcnt;
665 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
670 /* We found a duplicate stream. */
671 if (orig_refcnt != tmp->out_refcnt) {
672 /* We have already written, or are going
673 * to write, the duplicate stream. So
674 * just skip to the next stream. */
675 DEBUG("Discarding duplicate stream of length %"PRIu64,
676 wim_resource_size(lte));
677 lte->no_progress = 0;
678 goto skip_to_progress;
683 /* Here, @lte is either a hashed stream or an unhashed stream
684 * with a unique size. In either case we know that the stream
685 * has to be written. In either case the SHA1 message digest
686 * will be calculated over the stream while writing it; however,
687 * in the former case this is done merely to check the data,
688 * while in the latter case this is done because we do not have
689 * the SHA1 message digest yet. */
690 wimlib_assert(lte->out_refcnt != 0);
692 lte->no_progress = 0;
693 ret = (*write_stream_cb)(lte, write_stream_ctx);
696 /* In parallel mode, some streams are deferred for later,
697 * serialized processing; ignore them here. */
701 list_del(<e->unhashed_list);
702 lookup_table_insert(lookup_table, lte);
706 if (!lte->no_progress) {
707 do_write_streams_progress(progress,
709 wim_resource_size(lte));
716 do_write_stream_list_serial(struct list_head *stream_list,
717 struct wim_lookup_table *lookup_table,
720 int write_resource_flags,
721 wimlib_progress_func_t progress_func,
722 union wimlib_progress_info *progress)
724 struct serial_write_stream_ctx ctx = {
726 .out_ctype = out_ctype,
727 .write_resource_flags = write_resource_flags,
729 return do_write_stream_list(stream_list,
738 write_flags_to_resource_flags(int write_flags)
740 int resource_flags = 0;
742 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
743 resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
744 return resource_flags;
748 write_stream_list_serial(struct list_head *stream_list,
749 struct wim_lookup_table *lookup_table,
752 int write_resource_flags,
753 wimlib_progress_func_t progress_func,
754 union wimlib_progress_info *progress)
756 DEBUG("Writing stream list (serial version)");
757 progress->write_streams.num_threads = 1;
759 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
760 return do_write_stream_list_serial(stream_list,
764 write_resource_flags,
769 #ifdef ENABLE_MULTITHREADED_COMPRESSION
771 write_wim_chunks(struct message *msg, int out_fd,
772 struct chunk_table *chunk_tab)
774 for (unsigned i = 0; i < msg->num_chunks; i++) {
775 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
776 chunk_tab->cur_offset += msg->out_chunks[i].iov_len;
778 if (full_writev(out_fd, msg->out_chunks,
779 msg->num_chunks) != msg->total_out_bytes)
781 ERROR_WITH_ERRNO("Failed to write WIM chunks");
782 return WIMLIB_ERR_WRITE;
787 struct main_writer_thread_ctx {
788 struct list_head *stream_list;
789 struct wim_lookup_table *lookup_table;
792 int write_resource_flags;
793 struct shared_queue *res_to_compress_queue;
794 struct shared_queue *compressed_res_queue;
796 wimlib_progress_func_t progress_func;
797 union wimlib_progress_info *progress;
799 struct list_head available_msgs;
800 struct list_head outstanding_streams;
801 struct list_head serial_streams;
802 size_t num_outstanding_messages;
804 SHA_CTX next_sha_ctx;
807 struct wim_lookup_table_entry *next_lte;
809 struct message *msgs;
810 struct message *next_msg;
811 struct chunk_table *cur_chunk_tab;
815 init_message(struct message *msg)
817 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
818 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
819 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
820 if (msg->compressed_chunks[i] == NULL ||
821 msg->uncompressed_chunks[i] == NULL)
822 return WIMLIB_ERR_NOMEM;
828 destroy_message(struct message *msg)
830 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
831 FREE(msg->compressed_chunks[i]);
832 FREE(msg->uncompressed_chunks[i]);
837 free_messages(struct message *msgs, size_t num_messages)
840 for (size_t i = 0; i < num_messages; i++)
841 destroy_message(&msgs[i]);
846 static struct message *
847 allocate_messages(size_t num_messages)
849 struct message *msgs;
851 msgs = CALLOC(num_messages, sizeof(struct message));
854 for (size_t i = 0; i < num_messages; i++) {
855 if (init_message(&msgs[i])) {
856 free_messages(msgs, num_messages);
864 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
866 while (ctx->num_outstanding_messages--)
867 shared_queue_get(ctx->compressed_res_queue);
868 free_messages(ctx->msgs, ctx->num_messages);
869 FREE(ctx->cur_chunk_tab);
873 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
875 /* Pre-allocate all the buffers that will be needed to do the chunk
877 ctx->msgs = allocate_messages(ctx->num_messages);
879 return WIMLIB_ERR_NOMEM;
881 /* Initially, all the messages are available to use. */
882 INIT_LIST_HEAD(&ctx->available_msgs);
883 for (size_t i = 0; i < ctx->num_messages; i++)
884 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
886 /* outstanding_streams is the list of streams that currently have had
887 * chunks sent off for compression.
889 * The first stream in outstanding_streams is the stream that is
890 * currently being written.
892 * The last stream in outstanding_streams is the stream that is
893 * currently being read and having chunks fed to the compressor threads.
895 INIT_LIST_HEAD(&ctx->outstanding_streams);
896 ctx->num_outstanding_messages = 0;
898 ctx->next_msg = NULL;
900 /* Resources that don't need any chunks compressed are added to this
901 * list and written directly by the main thread. */
902 INIT_LIST_HEAD(&ctx->serial_streams);
904 ctx->cur_chunk_tab = NULL;
910 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
913 struct wim_lookup_table_entry *cur_lte;
916 wimlib_assert(!list_empty(&ctx->outstanding_streams));
917 wimlib_assert(ctx->num_outstanding_messages != 0);
919 cur_lte = container_of(ctx->outstanding_streams.next,
920 struct wim_lookup_table_entry,
921 being_compressed_list);
923 /* Get the next message from the queue and process it.
924 * The message will contain 1 or more data chunks that have been
926 msg = shared_queue_get(ctx->compressed_res_queue);
927 msg->complete = true;
928 --ctx->num_outstanding_messages;
930 /* Is this the next chunk in the current resource? If it's not
931 * (i.e., an earlier chunk in a same or different resource
932 * hasn't been compressed yet), do nothing, and keep this
933 * message around until all earlier chunks are received.
935 * Otherwise, write all the chunks we can. */
936 while (cur_lte != NULL &&
937 !list_empty(&cur_lte->msg_list)
938 && (msg = container_of(cur_lte->msg_list.next,
942 list_move(&msg->list, &ctx->available_msgs);
943 if (msg->begin_chunk == 0) {
944 /* This is the first set of chunks. Leave space
945 * for the chunk table in the output file. */
946 off_t cur_offset = filedes_offset(ctx->out_fd);
947 if (cur_offset == -1)
948 return WIMLIB_ERR_WRITE;
949 ret = begin_wim_resource_chunk_tab(cur_lte,
952 &ctx->cur_chunk_tab);
957 /* Write the compressed chunks from the message. */
958 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab);
962 /* Was this the last chunk of the stream? If so, finish
964 if (list_empty(&cur_lte->msg_list) &&
965 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
970 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
976 list_del(&cur_lte->being_compressed_list);
978 /* Grab the offset of this stream in the output file
979 * from the chunk table before we free it. */
980 offset = ctx->cur_chunk_tab->file_offset;
982 FREE(ctx->cur_chunk_tab);
983 ctx->cur_chunk_tab = NULL;
985 if (res_csize >= wim_resource_size(cur_lte)) {
986 /* Oops! We compressed the resource to
987 * larger than the original size. Write
988 * the resource uncompressed instead. */
989 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
990 "writing uncompressed instead",
991 wim_resource_size(cur_lte), res_csize);
992 ret = seek_and_truncate(ctx->out_fd, offset);
995 ret = write_wim_resource(cur_lte,
997 WIMLIB_COMPRESSION_TYPE_NONE,
998 &cur_lte->output_resource_entry,
999 ctx->write_resource_flags);
1003 cur_lte->output_resource_entry.size =
1006 cur_lte->output_resource_entry.original_size =
1007 cur_lte->resource_entry.original_size;
1009 cur_lte->output_resource_entry.offset =
1012 cur_lte->output_resource_entry.flags =
1013 cur_lte->resource_entry.flags |
1014 WIM_RESHDR_FLAG_COMPRESSED;
1017 do_write_streams_progress(ctx->progress,
1019 wim_resource_size(cur_lte));
1021 /* Since we just finished writing a stream, write any
1022 * streams that have been added to the serial_streams
1023 * list for direct writing by the main thread (e.g.
1024 * resources that don't need to be compressed because
1025 * the desired compression type is the same as the
1026 * previous compression type). */
1027 if (!list_empty(&ctx->serial_streams)) {
1028 ret = do_write_stream_list_serial(&ctx->serial_streams,
1032 ctx->write_resource_flags,
1039 /* Advance to the next stream to write. */
1040 if (list_empty(&ctx->outstanding_streams)) {
1043 cur_lte = container_of(ctx->outstanding_streams.next,
1044 struct wim_lookup_table_entry,
1045 being_compressed_list);
1052 /* Called when the main thread has read a new chunk of data. */
1054 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1056 struct main_writer_thread_ctx *ctx = _ctx;
1058 struct message *next_msg;
1059 u64 next_chunk_in_msg;
1061 /* Update SHA1 message digest for the stream currently being read by the
1063 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1065 /* We send chunks of data to the compressor chunks in batches which we
1066 * refer to as "messages". @next_msg is the message that is currently
1067 * being prepared to send off. If it is NULL, that indicates that we
1068 * need to start a new message. */
1069 next_msg = ctx->next_msg;
1071 /* We need to start a new message. First check to see if there
1072 * is a message available in the list of available messages. If
1073 * so, we can just take one. If not, all the messages (there is
1074 * a fixed number of them, proportional to the number of
1075 * threads) have been sent off to the compressor threads, so we
1076 * receive messages from the compressor threads containing
1077 * compressed chunks of data.
1079 * We may need to receive multiple messages before one is
1080 * actually available to use because messages received that are
1081 * *not* for the very next set of chunks to compress must be
1082 * buffered until it's time to write those chunks. */
1083 while (list_empty(&ctx->available_msgs)) {
1084 ret = receive_compressed_chunks(ctx);
1089 next_msg = container_of(ctx->available_msgs.next,
1090 struct message, list);
1091 list_del(&next_msg->list);
1092 next_msg->complete = false;
1093 next_msg->begin_chunk = ctx->next_chunk;
1094 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1095 ctx->next_num_chunks - ctx->next_chunk);
1096 ctx->next_msg = next_msg;
1099 /* Fill in the next chunk to compress */
1100 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1102 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1103 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1106 if (++next_chunk_in_msg == next_msg->num_chunks) {
1107 /* Send off an array of chunks to compress */
1108 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1109 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1110 ++ctx->num_outstanding_messages;
1111 ctx->next_msg = NULL;
1117 main_writer_thread_finish(void *_ctx)
1119 struct main_writer_thread_ctx *ctx = _ctx;
1121 while (ctx->num_outstanding_messages != 0) {
1122 ret = receive_compressed_chunks(ctx);
1126 wimlib_assert(list_empty(&ctx->outstanding_streams));
1127 return do_write_stream_list_serial(&ctx->serial_streams,
1131 ctx->write_resource_flags,
1137 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1138 struct main_writer_thread_ctx *ctx)
1142 /* Read the entire stream @lte, feeding its data chunks to the
1143 * compressor threads. Also SHA1-sum the stream; this is required in
1144 * the case that @lte is unhashed, and a nice additional verification
1145 * when @lte is already hashed. */
1146 sha1_init(&ctx->next_sha_ctx);
1147 ctx->next_chunk = 0;
1148 ctx->next_num_chunks = wim_resource_chunks(lte);
1149 ctx->next_lte = lte;
1150 INIT_LIST_HEAD(<e->msg_list);
1151 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1152 ret = read_resource_prefix(lte, wim_resource_size(lte),
1153 main_writer_thread_cb, ctx, 0);
1155 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1156 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1162 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1164 struct main_writer_thread_ctx *ctx = _ctx;
1167 if (wim_resource_size(lte) < 1000 ||
1168 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1169 (lte->resource_location == RESOURCE_IN_WIM &&
1170 !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1171 wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
1173 /* Stream is too small or isn't being compressed. Process it by
1174 * the main thread when we have a chance. We can't necessarily
1175 * process it right here, as the main thread could be in the
1176 * middle of writing a different stream. */
1177 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1181 ret = submit_stream_for_compression(lte, ctx);
1183 lte->no_progress = 1;
1188 get_default_num_threads()
1191 return win32_get_number_of_processors();
1193 return sysconf(_SC_NPROCESSORS_ONLN);
1197 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1198 * parameter and will perform compression using that many threads. Falls
1199 * back to write_stream_list_serial() on certain errors, such as a failure to
1200 * create the number of threads requested.
1202 * High level description of the algorithm for writing compressed streams in
1203 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1204 * rather than on full files. The currently executing thread becomes the main
1205 * thread and is entirely in charge of reading the data to compress (which may
1206 * be in any location understood by the resource code--- such as in an external
1207 * file being captured, or in another WIM file from which an image is being
1208 * exported) and actually writing the compressed data to the output file.
1209 * Additional threads are "compressor threads" and all execute the
1210 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1211 * the main thread, compress them, and hand them back to the main thread.
1213 * Certain streams, such as streams that do not need to be compressed (e.g.
1214 * input compression type same as output compression type) or streams of very
1215 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1216 * handled entirely by the main thread at an appropriate time.
1218 * At any given point in time, multiple streams may be having chunks compressed
1219 * concurrently. The stream that the main thread is currently *reading* may be
1220 * later in the list that the stream that the main thread is currently
1224 write_stream_list_parallel(struct list_head *stream_list,
1225 struct wim_lookup_table *lookup_table,
1228 int write_resource_flags,
1229 wimlib_progress_func_t progress_func,
1230 union wimlib_progress_info *progress,
1231 unsigned num_threads)
1234 struct shared_queue res_to_compress_queue;
1235 struct shared_queue compressed_res_queue;
1236 pthread_t *compressor_threads = NULL;
1238 if (num_threads == 0) {
1239 long nthreads = get_default_num_threads();
1240 if (nthreads < 1 || nthreads > UINT_MAX) {
1241 WARNING("Could not determine number of processors! Assuming 1");
1243 } else if (nthreads == 1) {
1244 goto out_serial_quiet;
1246 num_threads = nthreads;
1250 DEBUG("Writing stream list (parallel version, num_threads=%u)",
1253 progress->write_streams.num_threads = num_threads;
1255 static const size_t MESSAGES_PER_THREAD = 2;
1256 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1258 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1260 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1264 ret = shared_queue_init(&compressed_res_queue, queue_size);
1266 goto out_destroy_res_to_compress_queue;
1268 struct compressor_thread_params params;
1269 params.res_to_compress_queue = &res_to_compress_queue;
1270 params.compressed_res_queue = &compressed_res_queue;
1271 params.compress = get_compress_func(out_ctype);
1273 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1274 if (!compressor_threads) {
1275 ret = WIMLIB_ERR_NOMEM;
1276 goto out_destroy_compressed_res_queue;
1279 for (unsigned i = 0; i < num_threads; i++) {
1280 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1281 ret = pthread_create(&compressor_threads[i], NULL,
1282 compressor_thread_proc, ¶ms);
1285 ERROR_WITH_ERRNO("Failed to create compressor "
1287 i + 1, num_threads);
1294 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1296 struct main_writer_thread_ctx ctx;
1297 ctx.stream_list = stream_list;
1298 ctx.lookup_table = lookup_table;
1299 ctx.out_fd = out_fd;
1300 ctx.out_ctype = out_ctype;
1301 ctx.res_to_compress_queue = &res_to_compress_queue;
1302 ctx.compressed_res_queue = &compressed_res_queue;
1303 ctx.num_messages = queue_size;
1304 ctx.write_resource_flags = write_resource_flags;
1305 ctx.progress_func = progress_func;
1306 ctx.progress = progress;
1307 ret = main_writer_thread_init_ctx(&ctx);
1310 ret = do_write_stream_list(stream_list, lookup_table,
1311 main_thread_process_next_stream,
1312 &ctx, progress_func, progress);
1314 goto out_destroy_ctx;
1316 /* The main thread has finished reading all streams that are going to be
1317 * compressed in parallel, and it now needs to wait for all remaining
1318 * chunks to be compressed so that the remaining streams can actually be
1319 * written to the output file. Furthermore, any remaining streams that
1320 * had processing deferred to the main thread need to be handled. These
1321 * tasks are done by the main_writer_thread_finish() function. */
1322 ret = main_writer_thread_finish(&ctx);
1324 main_writer_thread_destroy_ctx(&ctx);
1326 for (unsigned i = 0; i < num_threads; i++)
1327 shared_queue_put(&res_to_compress_queue, NULL);
1329 for (unsigned i = 0; i < num_threads; i++) {
1330 if (pthread_join(compressor_threads[i], NULL)) {
1331 WARNING_WITH_ERRNO("Failed to join compressor "
1333 i + 1, num_threads);
1336 FREE(compressor_threads);
1337 out_destroy_compressed_res_queue:
1338 shared_queue_destroy(&compressed_res_queue);
1339 out_destroy_res_to_compress_queue:
1340 shared_queue_destroy(&res_to_compress_queue);
1341 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1344 WARNING("Falling back to single-threaded compression");
1346 return write_stream_list_serial(stream_list,
1350 write_resource_flags,
1358 * Write a list of streams to a WIM (@out_fd) using the compression type
1359 * @out_ctype and up to @num_threads compressor threads.
1362 write_stream_list(struct list_head *stream_list,
1363 struct wim_lookup_table *lookup_table,
1364 int out_fd, int out_ctype, int write_flags,
1365 unsigned num_threads, wimlib_progress_func_t progress_func)
1367 struct wim_lookup_table_entry *lte;
1368 size_t num_streams = 0;
1369 u64 total_bytes = 0;
1370 u64 total_compression_bytes = 0;
1371 union wimlib_progress_info progress;
1373 int write_resource_flags;
1375 if (list_empty(stream_list))
1378 write_resource_flags = write_flags_to_resource_flags(write_flags);
1380 /* Calculate the total size of the streams to be written. Note: this
1381 * will be the uncompressed size, as we may not know the compressed size
1382 * yet, and also this will assume that every unhashed stream will be
1383 * written (which will not necessarily be the case). */
1384 list_for_each_entry(lte, stream_list, write_streams_list) {
1386 total_bytes += wim_resource_size(lte);
1387 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1388 && (wim_resource_compression_type(lte) != out_ctype ||
1389 (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1391 total_compression_bytes += wim_resource_size(lte);
1394 progress.write_streams.total_bytes = total_bytes;
1395 progress.write_streams.total_streams = num_streams;
1396 progress.write_streams.completed_bytes = 0;
1397 progress.write_streams.completed_streams = 0;
1398 progress.write_streams.num_threads = num_threads;
1399 progress.write_streams.compression_type = out_ctype;
1400 progress.write_streams._private = 0;
1402 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1403 if (total_compression_bytes >= 1000000 && num_threads != 1)
1404 ret = write_stream_list_parallel(stream_list,
1408 write_resource_flags,
1414 ret = write_stream_list_serial(stream_list,
1418 write_resource_flags,
1424 struct stream_size_table {
1425 struct hlist_head *array;
1431 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1433 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1435 return WIMLIB_ERR_NOMEM;
1436 tab->num_entries = 0;
1437 tab->capacity = capacity;
1442 destroy_stream_size_table(struct stream_size_table *tab)
1448 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1450 struct stream_size_table *tab = _tab;
1452 struct wim_lookup_table_entry *same_size_lte;
1453 struct hlist_node *tmp;
1455 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1456 lte->unique_size = 1;
1457 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1458 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1459 lte->unique_size = 0;
1460 same_size_lte->unique_size = 0;
1465 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1471 struct lte_overwrite_prepare_args {
1474 struct list_head stream_list;
1475 struct stream_size_table stream_size_tab;
1478 /* First phase of preparing streams for an in-place overwrite. This is called
1479 * on all streams, both hashed and unhashed, except the metadata resources. */
1481 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1483 struct lte_overwrite_prepare_args *args = _args;
1485 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1486 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1487 list_add_tail(<e->write_streams_list, &args->stream_list);
1488 lte->out_refcnt = lte->refcnt;
1489 stream_size_table_insert(lte, &args->stream_size_tab);
1493 /* Second phase of preparing streams for an in-place overwrite. This is called
1494 * on existing metadata resources and hashed streams, but not unhashed streams.
1496 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1497 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1498 * the latter uses lte->hash_list_2, while the former expects to set
1499 * lte->output_resource_entry. */
1501 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1503 struct lte_overwrite_prepare_args *args = _args;
1505 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1506 /* We can't do an in place overwrite on the WIM if there are
1507 * streams after the XML data. */
1508 if (lte->resource_entry.offset +
1509 lte->resource_entry.size > args->end_offset)
1511 #ifdef ENABLE_ERROR_MESSAGES
1512 ERROR("The following resource is after the XML data:");
1513 print_lookup_table_entry(lte, stderr);
1515 return WIMLIB_ERR_RESOURCE_ORDER;
1517 copy_resource_entry(<e->output_resource_entry,
1518 <e->resource_entry);
1523 /* Given a WIM that we are going to overwrite in place with zero or more
1524 * additional streams added, construct a list the list of new unique streams
1525 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1526 * streams that need to be added but may be identical to other hashed or
1527 * unhashed streams. These unhashed streams are checksummed while the streams
1528 * are being written. To aid this process, the member @unique_size is set to 1
1529 * on streams that have a unique size and therefore must be written.
1531 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1532 * indicate the number of times the stream is referenced in only the streams
1533 * that are being written; this may still be adjusted later when unhashed
1534 * streams are being resolved.
1537 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1538 struct list_head *stream_list)
1541 struct lte_overwrite_prepare_args args;
1545 args.end_offset = end_offset;
1546 ret = init_stream_size_table(&args.stream_size_tab,
1547 wim->lookup_table->capacity);
1551 INIT_LIST_HEAD(&args.stream_list);
1552 for (i = 0; i < wim->hdr.image_count; i++) {
1553 struct wim_image_metadata *imd;
1554 struct wim_lookup_table_entry *lte;
1556 imd = wim->image_metadata[i];
1557 image_for_each_unhashed_stream(lte, imd)
1558 lte_overwrite_prepare(lte, &args);
1560 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1561 list_transfer(&args.stream_list, stream_list);
1563 for (i = 0; i < wim->hdr.image_count; i++) {
1564 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1567 goto out_destroy_stream_size_table;
1569 ret = for_lookup_table_entry(wim->lookup_table,
1570 lte_overwrite_prepare_2, &args);
1571 out_destroy_stream_size_table:
1572 destroy_stream_size_table(&args.stream_size_tab);
1577 struct find_streams_ctx {
1578 struct list_head stream_list;
1579 struct stream_size_table stream_size_tab;
1583 inode_find_streams_to_write(struct wim_inode *inode,
1584 struct wim_lookup_table *table,
1585 struct list_head *stream_list,
1586 struct stream_size_table *tab)
1588 struct wim_lookup_table_entry *lte;
1589 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1590 lte = inode_stream_lte(inode, i, table);
1592 if (lte->out_refcnt == 0) {
1594 stream_size_table_insert(lte, tab);
1595 list_add_tail(<e->write_streams_list, stream_list);
1597 lte->out_refcnt += inode->i_nlink;
1603 image_find_streams_to_write(WIMStruct *w)
1605 struct find_streams_ctx *ctx;
1606 struct wim_image_metadata *imd;
1607 struct wim_inode *inode;
1608 struct wim_lookup_table_entry *lte;
1611 imd = wim_get_current_image_metadata(w);
1613 image_for_each_unhashed_stream(lte, imd)
1614 lte->out_refcnt = 0;
1616 /* Go through this image's inodes to find any streams that have not been
1618 image_for_each_inode(inode, imd) {
1619 inode_find_streams_to_write(inode, w->lookup_table,
1621 &ctx->stream_size_tab);
1626 /* Given a WIM that from which one or all of the images is being written, build
1627 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1628 * written, plus any unhashed streams that need to be written but may be
1629 * identical to other hashed or unhashed streams being written. These unhashed
1630 * streams are checksummed while the streams are being written. To aid this
1631 * process, the member @unique_size is set to 1 on streams that have a unique
1632 * size and therefore must be written.
1634 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1635 * indicate the number of times the stream is referenced in only the streams
1636 * that are being written; this may still be adjusted later when unhashed
1637 * streams are being resolved.
1640 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1643 struct find_streams_ctx ctx;
1645 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1646 ret = init_stream_size_table(&ctx.stream_size_tab,
1647 wim->lookup_table->capacity);
1650 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1651 &ctx.stream_size_tab);
1652 INIT_LIST_HEAD(&ctx.stream_list);
1653 wim->private = &ctx;
1654 ret = for_image(wim, image, image_find_streams_to_write);
1655 destroy_stream_size_table(&ctx.stream_size_tab);
1657 list_transfer(&ctx.stream_list, stream_list);
1661 /* Writes the streams for the specified @image in @wim to @wim->out_fd.
1664 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1665 unsigned num_threads,
1666 wimlib_progress_func_t progress_func)
1669 struct list_head stream_list;
1671 ret = prepare_stream_list(wim, image, &stream_list);
1674 return write_stream_list(&stream_list,
1677 wimlib_get_compression_type(wim),
1684 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1685 * table (optional), then overwrite the WIM header.
1687 * write_flags is a bitwise OR of the following:
1689 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1690 * Include an integrity table.
1692 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1693 * Show progress information when (if) writing the integrity table.
1695 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1696 * Don't write the lookup table.
1698 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1699 * When (if) writing the integrity table, re-use entries from the
1700 * existing integrity table, if possible.
1702 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1703 * After writing the XML data but before writing the integrity
1704 * table, write a temporary WIM header and flush the stream so that
1705 * the WIM is less likely to become corrupted upon abrupt program
1708 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1709 * fsync() the output file before closing it.
1713 finish_write(WIMStruct *w, int image, int write_flags,
1714 wimlib_progress_func_t progress_func)
1717 struct wim_header hdr;
1719 /* @hdr will be the header for the new WIM. First copy all the data
1720 * from the header in the WIMStruct; then set all the fields that may
1721 * have changed, including the resource entries, boot index, and image
1723 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1725 /* Set image count and boot index correctly for single image writes */
1726 if (image != WIMLIB_ALL_IMAGES) {
1727 hdr.image_count = 1;
1728 if (hdr.boot_idx == image)
1734 /* In the WIM header, there is room for the resource entry for a
1735 * metadata resource labeled as the "boot metadata". This entry should
1736 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1737 * it should be a copy of the resource entry for the image that is
1738 * marked as bootable. This is not well documented... */
1739 if (hdr.boot_idx == 0) {
1740 zero_resource_entry(&hdr.boot_metadata_res_entry);
1742 copy_resource_entry(&hdr.boot_metadata_res_entry,
1743 &w->image_metadata[ hdr.boot_idx- 1
1744 ]->metadata_lte->output_resource_entry);
1747 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1748 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1753 ret = write_xml_data(w->wim_info, image, w->out_fd,
1754 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1755 wim_info_get_total_bytes(w->wim_info) : 0,
1756 &hdr.xml_res_entry);
1760 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1761 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1762 struct wim_header checkpoint_hdr;
1763 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1764 zero_resource_entry(&checkpoint_hdr.integrity);
1765 ret = write_header(&checkpoint_hdr, w->out_fd);
1770 off_t old_lookup_table_end;
1771 off_t new_lookup_table_end;
1772 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1773 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1774 w->hdr.lookup_table_res_entry.size;
1776 old_lookup_table_end = 0;
1778 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1779 hdr.lookup_table_res_entry.size;
1781 ret = write_integrity_table(w->out_fd,
1783 new_lookup_table_end,
1784 old_lookup_table_end,
1789 zero_resource_entry(&hdr.integrity);
1792 ret = write_header(&hdr, w->out_fd);
1796 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1797 if (fsync(w->out_fd)) {
1798 ERROR_WITH_ERRNO("Error syncing data to WIM file");
1799 ret = WIMLIB_ERR_WRITE;
1803 if (close(w->out_fd)) {
1804 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1806 ret = WIMLIB_ERR_WRITE;
1812 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1814 lock_wim(WIMStruct *w, int fd)
1817 if (fd != -1 && !w->wim_locked) {
1818 ret = flock(fd, LOCK_EX | LOCK_NB);
1820 if (errno == EWOULDBLOCK) {
1821 ERROR("`%"TS"' is already being modified or has been "
1822 "mounted read-write\n"
1823 " by another process!", w->filename);
1824 ret = WIMLIB_ERR_ALREADY_LOCKED;
1826 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1839 open_wim_writable(WIMStruct *w, const tchar *path, int open_flags)
1841 w->out_fd = topen(path, open_flags | O_BINARY, 0644);
1842 if (w->out_fd == -1) {
1843 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1844 return WIMLIB_ERR_OPEN;
1851 close_wim_writable(WIMStruct *w)
1853 if (w->out_fd != -1) {
1854 if (close(w->out_fd))
1855 WARNING_WITH_ERRNO("Failed to close output WIM");
1860 /* Open file stream and write dummy header for WIM. */
1862 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1865 int open_flags = O_TRUNC | O_CREAT;
1866 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1867 open_flags |= O_RDWR;
1869 open_flags |= O_WRONLY;
1870 ret = open_wim_writable(w, path, open_flags);
1873 /* Write dummy header. It will be overwritten later. */
1874 ret = write_header(&w->hdr, w->out_fd);
1877 if (lseek(w->out_fd, WIM_HEADER_DISK_SIZE, SEEK_SET) == -1) {
1878 ERROR_WITH_ERRNO("Failed to seek to end of WIM header");
1879 return WIMLIB_ERR_WRITE;
1884 /* Writes a stand-alone WIM to a file. */
1886 wimlib_write(WIMStruct *w, const tchar *path,
1887 int image, int write_flags, unsigned num_threads,
1888 wimlib_progress_func_t progress_func)
1893 return WIMLIB_ERR_INVALID_PARAM;
1895 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1897 if (image != WIMLIB_ALL_IMAGES &&
1898 (image < 1 || image > w->hdr.image_count))
1899 return WIMLIB_ERR_INVALID_IMAGE;
1901 if (w->hdr.total_parts != 1) {
1902 ERROR("Cannot call wimlib_write() on part of a split WIM");
1903 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1906 ret = begin_write(w, path, write_flags);
1910 ret = write_wim_streams(w, image, write_flags, num_threads,
1916 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1918 ret = for_image(w, image, write_metadata_resource);
1923 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1925 ret = finish_write(w, image, write_flags, progress_func);
1926 /* finish_write() closed the WIM for us */
1929 close_wim_writable(w);
1931 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1936 any_images_modified(WIMStruct *w)
1938 for (int i = 0; i < w->hdr.image_count; i++)
1939 if (w->image_metadata[i]->modified)
1945 * Overwrite a WIM, possibly appending streams to it.
1947 * A WIM looks like (or is supposed to look like) the following:
1949 * Header (212 bytes)
1950 * Streams and metadata resources (variable size)
1951 * Lookup table (variable size)
1952 * XML data (variable size)
1953 * Integrity table (optional) (variable size)
1955 * If we are not adding any streams or metadata resources, the lookup table is
1956 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1957 * header. This operation is potentially unsafe if the program is abruptly
1958 * terminated while the XML data or integrity table are being overwritten, but
1959 * before the new header has been written. To partially alleviate this problem,
1960 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1961 * finish_write() to cause a temporary WIM header to be written after the XML
1962 * data has been written. This may prevent the WIM from becoming corrupted if
1963 * the program is terminated while the integrity table is being calculated (but
1964 * no guarantees, due to write re-ordering...).
1966 * If we are adding new streams or images (metadata resources), the lookup table
1967 * needs to be changed, and those streams need to be written. In this case, we
1968 * try to perform a safe update of the WIM file by writing the streams *after*
1969 * the end of the previous WIM, then writing the new lookup table, XML data, and
1970 * (optionally) integrity table following the new streams. This will produce a
1971 * layout like the following:
1973 * Header (212 bytes)
1974 * (OLD) Streams and metadata resources (variable size)
1975 * (OLD) Lookup table (variable size)
1976 * (OLD) XML data (variable size)
1977 * (OLD) Integrity table (optional) (variable size)
1978 * (NEW) Streams and metadata resources (variable size)
1979 * (NEW) Lookup table (variable size)
1980 * (NEW) XML data (variable size)
1981 * (NEW) Integrity table (optional) (variable size)
1983 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1984 * the header is overwritten to point to the new lookup table, XML data, and
1985 * integrity table, to produce the following layout:
1987 * Header (212 bytes)
1988 * Streams and metadata resources (variable size)
1989 * Nothing (variable size)
1990 * More Streams and metadata resources (variable size)
1991 * Lookup table (variable size)
1992 * XML data (variable size)
1993 * Integrity table (optional) (variable size)
1995 * This method allows an image to be appended to a large WIM very quickly, and
1996 * is is crash-safe except in the case of write re-ordering, but the
1997 * disadvantage is that a small hole is left in the WIM where the old lookup
1998 * table, xml data, and integrity table were. (These usually only take up a
1999 * small amount of space compared to the streams, however.)
2002 overwrite_wim_inplace(WIMStruct *w, int write_flags,
2003 unsigned num_threads,
2004 wimlib_progress_func_t progress_func)
2007 struct list_head stream_list;
2009 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2012 DEBUG("Overwriting `%"TS"' in-place", w->filename);
2014 /* Make sure that the integrity table (if present) is after the XML
2015 * data, and that there are no stream resources, metadata resources, or
2016 * lookup tables after the XML data. Otherwise, these data would be
2018 old_xml_begin = w->hdr.xml_res_entry.offset;
2019 old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
2020 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
2021 w->hdr.lookup_table_res_entry.size;
2022 if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
2023 ERROR("Didn't expect the integrity table to be before the XML data");
2024 return WIMLIB_ERR_RESOURCE_ORDER;
2027 if (old_lookup_table_end > old_xml_begin) {
2028 ERROR("Didn't expect the lookup table to be after the XML data");
2029 return WIMLIB_ERR_RESOURCE_ORDER;
2032 /* Set @old_wim_end, which indicates the point beyond which we don't
2033 * allow any file and metadata resources to appear without returning
2034 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2035 * overwrite these resources). */
2036 if (!w->deletion_occurred && !any_images_modified(w)) {
2037 /* If no images have been modified and no images have been
2038 * deleted, a new lookup table does not need to be written. We
2039 * shall write the new XML data and optional integrity table
2040 * immediately after the lookup table. Note that this may
2041 * overwrite an existing integrity table. */
2042 DEBUG("Skipping writing lookup table "
2043 "(no images modified or deleted)");
2044 old_wim_end = old_lookup_table_end;
2045 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2046 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2047 } else if (w->hdr.integrity.offset) {
2048 /* Old WIM has an integrity table; begin writing new streams
2050 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2052 /* No existing integrity table; begin writing new streams after
2053 * the old XML data. */
2054 old_wim_end = old_xml_end;
2057 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2062 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2063 open_flags |= O_RDWR;
2065 open_flags |= O_WRONLY;
2066 ret = open_wim_writable(w, w->filename, open_flags);
2070 ret = lock_wim(w, w->out_fd);
2072 close_wim_writable(w);
2076 if (lseek(w->out_fd, old_wim_end, SEEK_SET) == -1) {
2077 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2078 close_wim_writable(w);
2080 return WIMLIB_ERR_WRITE;
2083 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2085 ret = write_stream_list(&stream_list,
2088 wimlib_get_compression_type(w),
2095 for (int i = 0; i < w->hdr.image_count; i++) {
2096 if (w->image_metadata[i]->modified) {
2097 select_wim_image(w, i + 1);
2098 ret = write_metadata_resource(w);
2103 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2104 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2107 close_wim_writable(w);
2108 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2109 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2110 w->filename, old_wim_end);
2111 /* Return value of truncate() is ignored because this is already
2113 (void)ttruncate(w->filename, old_wim_end);
2120 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2121 unsigned num_threads,
2122 wimlib_progress_func_t progress_func)
2124 size_t wim_name_len;
2127 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2129 /* Write the WIM to a temporary file in the same directory as the
2131 wim_name_len = tstrlen(w->filename);
2132 tchar tmpfile[wim_name_len + 10];
2133 tmemcpy(tmpfile, w->filename, wim_name_len);
2134 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2135 tmpfile[wim_name_len + 9] = T('\0');
2137 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2138 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2139 num_threads, progress_func);
2141 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2147 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2148 /* Rename the new file to the old file .*/
2149 if (trename(tmpfile, w->filename) != 0) {
2150 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2151 tmpfile, w->filename);
2152 ret = WIMLIB_ERR_RENAME;
2156 if (progress_func) {
2157 union wimlib_progress_info progress;
2158 progress.rename.from = tmpfile;
2159 progress.rename.to = w->filename;
2160 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2164 /* Remove temporary file. */
2165 if (tunlink(tmpfile) != 0)
2166 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2172 * Writes a WIM file to the original file that it was read from, overwriting it.
2175 wimlib_overwrite(WIMStruct *w, int write_flags,
2176 unsigned num_threads,
2177 wimlib_progress_func_t progress_func)
2179 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2182 return WIMLIB_ERR_NO_FILENAME;
2184 if (w->hdr.total_parts != 1) {
2185 ERROR("Cannot modify a split WIM");
2186 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2189 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2190 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2193 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2195 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2196 WARNING("Falling back to re-building entire WIM");
2200 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,