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
55 # include <ntfs-3g/attrib.h>
56 # include <ntfs-3g/inode.h>
57 # include <ntfs-3g/dir.h>
68 #include <sys/uio.h> /* writev() */
70 /* Chunk table that's located at the beginning of each compressed resource in
71 * the WIM. (This is not the on-disk format; the on-disk format just has an
72 * array of offsets.) */
76 u64 original_resource_size;
77 u64 bytes_per_chunk_entry;
85 * Allocates and initializes a chunk table, and reserves space for it in the
89 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
92 struct chunk_table **chunk_tab_ret)
94 u64 size = wim_resource_size(lte);
95 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
96 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
97 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
99 DEBUG("Begin chunk table for stream with size %"PRIu64, size);
102 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
104 return WIMLIB_ERR_NOMEM;
106 chunk_tab->file_offset = file_offset;
107 chunk_tab->num_chunks = num_chunks;
108 chunk_tab->original_resource_size = size;
109 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
110 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
112 chunk_tab->cur_offset = 0;
113 chunk_tab->cur_offset_p = chunk_tab->offsets;
115 if (full_write(out_fd, chunk_tab,
116 chunk_tab->table_disk_size) != chunk_tab->table_disk_size)
118 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
121 return WIMLIB_ERR_WRITE;
123 *chunk_tab_ret = chunk_tab;
128 * compress_func_t- Pointer to a function to compresses a chunk
129 * of a WIM resource. This may be either
130 * wimlib_xpress_compress() (xpress-compress.c) or
131 * wimlib_lzx_compress() (lzx-compress.c).
133 * @chunk: Uncompressed data of the chunk.
134 * @chunk_size: Size of the uncompressed chunk, in bytes.
135 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
137 * Returns the size of the compressed data written to @out in bytes, or 0 if the
138 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
140 * As a special requirement, the compression code is optimized for the WIM
141 * format and therefore requires (@chunk_size <= 32768).
143 * As another special requirement, the compression code will read up to 8 bytes
144 * off the end of the @chunk array for performance reasons. The values of these
145 * bytes will not affect the output of the compression, but the calling code
146 * must make sure that the buffer holding the uncompressed chunk is actually at
147 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
148 * mapped memory that will not cause a memory access violation if accessed.
150 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
153 static compress_func_t
154 get_compress_func(int out_ctype)
156 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
157 return wimlib_lzx_compress;
159 return wimlib_xpress_compress;
163 * Writes a chunk of a WIM resource to an output file.
165 * @chunk: Uncompressed data of the chunk.
166 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
167 * @out_fd: FILE descriptor to write the chunk to.
168 * @compress: Compression function to use (NULL if writing uncompressed
170 * @chunk_tab: Pointer to chunk table being created. It is updated with the
171 * offset of the chunk we write.
173 * Returns 0 on success; nonzero on failure.
176 write_wim_resource_chunk(const void * restrict chunk,
179 compress_func_t compress,
180 struct chunk_table * restrict chunk_tab)
182 const void *out_chunk;
183 unsigned out_chunk_size;
185 void *compressed_chunk = alloca(chunk_size);
187 out_chunk_size = (*compress)(chunk, chunk_size, compressed_chunk);
188 if (out_chunk_size) {
189 /* Write compressed */
190 out_chunk = compressed_chunk;
192 /* Write uncompressed */
194 out_chunk_size = chunk_size;
196 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
197 chunk_tab->cur_offset += out_chunk_size;
199 /* Write uncompressed */
201 out_chunk_size = chunk_size;
203 if (full_write(out_fd, out_chunk, out_chunk_size) != out_chunk_size) {
204 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
205 return WIMLIB_ERR_WRITE;
211 * Finishes a WIM chunk table and writes it to the output file at the correct
214 * The final size of the full compressed resource is returned in the
215 * @compressed_size_p.
218 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
219 filedes_t out_fd, u64 *compressed_size_p)
221 size_t bytes_written;
223 if (chunk_tab->bytes_per_chunk_entry == 8) {
224 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
226 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
227 ((u32*)chunk_tab->offsets)[i] =
228 cpu_to_le32(chunk_tab->offsets[i]);
230 bytes_written = full_pwrite(out_fd,
231 (u8*)chunk_tab->offsets + chunk_tab->bytes_per_chunk_entry,
232 chunk_tab->table_disk_size,
233 chunk_tab->file_offset);
234 if (bytes_written != chunk_tab->table_disk_size) {
235 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
237 return WIMLIB_ERR_WRITE;
239 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
244 seek_and_truncate(filedes_t out_fd, off_t offset)
246 if (lseek(out_fd, offset, SEEK_SET) == -1 ||
247 ftruncate(out_fd, offset))
249 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
250 return WIMLIB_ERR_WRITE;
257 finalize_and_check_sha1(SHA_CTX * restrict sha_ctx,
258 struct wim_lookup_table_entry * restrict lte)
260 u8 md[SHA1_HASH_SIZE];
261 sha1_final(md, sha_ctx);
263 copy_hash(lte->hash, md);
264 } else if (!hashes_equal(md, lte->hash)) {
265 ERROR("WIM resource has incorrect hash!");
266 if (lte_filename_valid(lte)) {
267 ERROR("We were reading it from \"%"TS"\"; maybe "
268 "it changed while we were reading it.",
271 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
277 struct write_resource_ctx {
278 compress_func_t compress;
279 struct chunk_table *chunk_tab;
286 write_resource_cb(const void *restrict chunk, size_t chunk_size,
289 struct write_resource_ctx *ctx = _ctx;
292 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
293 return write_wim_resource_chunk(chunk, chunk_size,
294 ctx->out_fd, ctx->compress,
299 * Write a resource to an output WIM.
301 * @lte: Lookup table entry for the resource, which could be in another WIM,
302 * in an external file, or in another location.
304 * @out_fp: File descriptor opened to the output WIM.
306 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
307 * which compression algorithm to use.
309 * @out_res_entry: On success, this is filled in with the offset, flags,
310 * compressed size, and uncompressed size of the resource
313 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
314 * even if it could otherwise be copied directly from the input.
316 * Additional notes: The SHA1 message digest of the uncompressed data is
317 * calculated (except when doing a raw copy --- see below). If the @unhashed
318 * flag is set on the lookup table entry, this message digest is simply copied
319 * to it; otherwise, the message digest is compared with the existing one, and
320 * the function will fail if they do not match.
323 write_wim_resource(struct wim_lookup_table_entry *lte,
324 filedes_t out_fd, int out_ctype,
325 struct resource_entry *out_res_entry,
328 struct write_resource_ctx write_ctx;
334 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
336 /* Get current position in output WIM */
337 offset = filedes_offset(out_fd);
339 ERROR_WITH_ERRNO("Can't get position in output WIM");
340 return WIMLIB_ERR_WRITE;
343 /* If we are not forcing the data to be recompressed, and the input
344 * resource is located in a WIM with the same compression type as that
345 * desired other than no compression, we can simply copy the compressed
346 * data without recompressing it. This also means we must skip
347 * calculating the SHA1, as we never will see the uncompressed data. */
348 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
349 lte->resource_location == RESOURCE_IN_WIM &&
350 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
351 wimlib_get_compression_type(lte->wim) == out_ctype)
353 flags |= WIMLIB_RESOURCE_FLAG_RAW;
354 write_ctx.doing_sha = false;
355 read_size = lte->resource_entry.size;
357 write_ctx.doing_sha = true;
358 sha1_init(&write_ctx.sha_ctx);
359 read_size = lte->resource_entry.original_size;
362 /* Initialize the chunk table and set the compression function if
363 * compressing the resource. */
364 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
365 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
366 write_ctx.compress = NULL;
367 write_ctx.chunk_tab = NULL;
369 write_ctx.compress = get_compress_func(out_ctype);
370 ret = begin_wim_resource_chunk_tab(lte, out_fd,
372 &write_ctx.chunk_tab);
377 /* Write the entire resource by reading the entire resource and feeding
378 * the data through the write_resource_cb function. */
379 write_ctx.out_fd = out_fd;
381 ret = read_resource_prefix(lte, read_size,
382 write_resource_cb, &write_ctx, flags);
384 goto out_free_chunk_tab;
386 /* Verify SHA1 message digest of the resource, or set the hash for the
388 if (write_ctx.doing_sha) {
389 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
391 goto out_free_chunk_tab;
394 out_res_entry->flags = lte->resource_entry.flags;
395 out_res_entry->original_size = wim_resource_size(lte);
396 out_res_entry->offset = offset;
397 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
398 /* Doing a raw write: The new compressed size is the same as
399 * the compressed size in the other WIM. */
400 new_size = lte->resource_entry.size;
401 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
402 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
403 * is the original size. */
404 new_size = lte->resource_entry.original_size;
405 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
407 /* Using a different compression type: Call
408 * finish_wim_resource_chunk_tab() and it will provide the new
409 * compressed size. */
410 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fd,
413 goto out_free_chunk_tab;
414 if (new_size >= wim_resource_size(lte)) {
415 /* Oops! We compressed the resource to larger than the original
416 * size. Write the resource uncompressed instead. */
417 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
418 "writing uncompressed instead",
419 wim_resource_size(lte), new_size);
420 ret = seek_and_truncate(out_fd, offset);
422 goto out_free_chunk_tab;
423 write_ctx.compress = NULL;
424 write_ctx.doing_sha = false;
425 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
426 goto try_write_again;
428 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
430 out_res_entry->size = new_size;
433 FREE(write_ctx.chunk_tab);
437 #ifdef ENABLE_MULTITHREADED_COMPRESSION
439 /* Blocking shared queue (solves the producer-consumer problem) */
440 struct shared_queue {
444 unsigned filled_slots;
446 pthread_mutex_t lock;
447 pthread_cond_t msg_avail_cond;
448 pthread_cond_t space_avail_cond;
452 shared_queue_init(struct shared_queue *q, unsigned size)
454 wimlib_assert(size != 0);
455 q->array = CALLOC(sizeof(q->array[0]), size);
462 if (pthread_mutex_init(&q->lock, NULL)) {
463 ERROR_WITH_ERRNO("Failed to initialize mutex");
466 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
467 ERROR_WITH_ERRNO("Failed to initialize condition variable");
468 goto err_destroy_lock;
470 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
471 ERROR_WITH_ERRNO("Failed to initialize condition variable");
472 goto err_destroy_msg_avail_cond;
475 err_destroy_msg_avail_cond:
476 pthread_cond_destroy(&q->msg_avail_cond);
478 pthread_mutex_destroy(&q->lock);
480 return WIMLIB_ERR_NOMEM;
484 shared_queue_destroy(struct shared_queue *q)
487 pthread_mutex_destroy(&q->lock);
488 pthread_cond_destroy(&q->msg_avail_cond);
489 pthread_cond_destroy(&q->space_avail_cond);
493 shared_queue_put(struct shared_queue *q, void *obj)
495 pthread_mutex_lock(&q->lock);
496 while (q->filled_slots == q->size)
497 pthread_cond_wait(&q->space_avail_cond, &q->lock);
499 q->back = (q->back + 1) % q->size;
500 q->array[q->back] = obj;
503 pthread_cond_broadcast(&q->msg_avail_cond);
504 pthread_mutex_unlock(&q->lock);
508 shared_queue_get(struct shared_queue *q)
512 pthread_mutex_lock(&q->lock);
513 while (q->filled_slots == 0)
514 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
516 obj = q->array[q->front];
517 q->array[q->front] = NULL;
518 q->front = (q->front + 1) % q->size;
521 pthread_cond_broadcast(&q->space_avail_cond);
522 pthread_mutex_unlock(&q->lock);
526 struct compressor_thread_params {
527 struct shared_queue *res_to_compress_queue;
528 struct shared_queue *compressed_res_queue;
529 compress_func_t compress;
532 #define MAX_CHUNKS_PER_MSG 2
535 struct wim_lookup_table_entry *lte;
536 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
537 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
538 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
539 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
540 size_t total_out_bytes;
542 struct list_head list;
548 compress_chunks(struct message *msg, compress_func_t compress)
550 msg->total_out_bytes = 0;
551 for (unsigned i = 0; i < msg->num_chunks; i++) {
552 unsigned len = compress(msg->uncompressed_chunks[i],
553 msg->uncompressed_chunk_sizes[i],
554 msg->compressed_chunks[i]);
558 /* To be written compressed */
559 out_chunk = msg->compressed_chunks[i];
562 /* To be written uncompressed */
563 out_chunk = msg->uncompressed_chunks[i];
564 out_len = msg->uncompressed_chunk_sizes[i];
566 msg->out_chunks[i].iov_base = out_chunk;
567 msg->out_chunks[i].iov_len = out_len;
568 msg->total_out_bytes += out_len;
572 /* Compressor thread routine. This is a lot simpler than the main thread
573 * routine: just repeatedly get a group of chunks from the
574 * res_to_compress_queue, compress them, and put them in the
575 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
578 compressor_thread_proc(void *arg)
580 struct compressor_thread_params *params = arg;
581 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
582 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
583 compress_func_t compress = params->compress;
586 DEBUG("Compressor thread ready");
587 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
588 compress_chunks(msg, compress);
589 shared_queue_put(compressed_res_queue, msg);
591 DEBUG("Compressor thread terminating");
594 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
597 do_write_streams_progress(union wimlib_progress_info *progress,
598 wimlib_progress_func_t progress_func,
601 progress->write_streams.completed_bytes += size_added;
602 progress->write_streams.completed_streams++;
604 progress->write_streams.completed_bytes >= progress->write_streams._private)
606 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
608 if (progress->write_streams._private == progress->write_streams.total_bytes) {
609 progress->write_streams._private = ~0;
611 progress->write_streams._private =
612 min(progress->write_streams.total_bytes,
613 progress->write_streams.completed_bytes +
614 progress->write_streams.total_bytes / 100);
619 struct serial_write_stream_ctx {
622 int write_resource_flags;
626 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
628 struct serial_write_stream_ctx *ctx = _ctx;
629 return write_wim_resource(lte, ctx->out_fd,
630 ctx->out_ctype, <e->output_resource_entry,
631 ctx->write_resource_flags);
634 /* Write a list of streams, taking into account that some streams may be
635 * duplicates that are checksummed and discarded on the fly, and also delegating
636 * the actual writing of a stream to a function @write_stream_cb, which is
637 * passed the context @write_stream_ctx. */
639 do_write_stream_list(struct list_head *stream_list,
640 struct wim_lookup_table *lookup_table,
641 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
642 void *write_stream_ctx,
643 wimlib_progress_func_t progress_func,
644 union wimlib_progress_info *progress)
647 struct wim_lookup_table_entry *lte;
649 /* For each stream in @stream_list ... */
650 while (!list_empty(stream_list)) {
651 lte = container_of(stream_list->next,
652 struct wim_lookup_table_entry,
654 list_del(<e->write_streams_list);
655 if (lte->unhashed && !lte->unique_size) {
656 /* Unhashed stream that shares a size with some other
657 * stream in the WIM we are writing. The stream must be
658 * checksummed to know if we need to write it or not. */
659 struct wim_lookup_table_entry *tmp;
660 u32 orig_refcnt = lte->out_refcnt;
662 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
667 /* We found a duplicate stream. */
668 if (orig_refcnt != tmp->out_refcnt) {
669 /* We have already written, or are going
670 * to write, the duplicate stream. So
671 * just skip to the next stream. */
672 DEBUG("Discarding duplicate stream of length %"PRIu64,
673 wim_resource_size(lte));
674 lte->no_progress = 0;
675 goto skip_to_progress;
680 /* Here, @lte is either a hashed stream or an unhashed stream
681 * with a unique size. In either case we know that the stream
682 * has to be written. In either case the SHA1 message digest
683 * will be calculated over the stream while writing it; however,
684 * in the former case this is done merely to check the data,
685 * while in the latter case this is done because we do not have
686 * the SHA1 message digest yet. */
687 wimlib_assert(lte->out_refcnt != 0);
689 lte->no_progress = 0;
690 ret = (*write_stream_cb)(lte, write_stream_ctx);
693 /* In parallel mode, some streams are deferred for later,
694 * serialized processing; ignore them here. */
698 list_del(<e->unhashed_list);
699 lookup_table_insert(lookup_table, lte);
703 if (!lte->no_progress) {
704 do_write_streams_progress(progress,
706 wim_resource_size(lte));
713 do_write_stream_list_serial(struct list_head *stream_list,
714 struct wim_lookup_table *lookup_table,
717 int write_resource_flags,
718 wimlib_progress_func_t progress_func,
719 union wimlib_progress_info *progress)
721 struct serial_write_stream_ctx ctx = {
723 .out_ctype = out_ctype,
724 .write_resource_flags = write_resource_flags,
726 return do_write_stream_list(stream_list,
735 write_flags_to_resource_flags(int write_flags)
737 int resource_flags = 0;
739 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
740 resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
741 return resource_flags;
745 write_stream_list_serial(struct list_head *stream_list,
746 struct wim_lookup_table *lookup_table,
749 int write_resource_flags,
750 wimlib_progress_func_t progress_func,
751 union wimlib_progress_info *progress)
753 DEBUG("Writing stream list (serial version)");
754 progress->write_streams.num_threads = 1;
756 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
757 return do_write_stream_list_serial(stream_list,
761 write_resource_flags,
766 #ifdef ENABLE_MULTITHREADED_COMPRESSION
768 write_wim_chunks(struct message *msg, filedes_t out_fd,
769 struct chunk_table *chunk_tab)
771 ssize_t bytes_remaining = msg->total_out_bytes;
772 struct iovec *vecs = msg->out_chunks;
773 unsigned nvecs = msg->num_chunks;
776 wimlib_assert(nvecs != 0);
777 wimlib_assert(msg->total_out_bytes != 0);
779 for (unsigned i = 0; i < msg->num_chunks; i++) {
780 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
781 chunk_tab->cur_offset += vecs[i].iov_len;
784 ssize_t bytes_written;
786 bytes_written = writev(out_fd, vecs, nvecs);
787 if (bytes_written <= 0) {
788 if (bytes_written < 0 && errno == EINTR)
790 else if (bytes_written == 0)
792 ERROR_WITH_ERRNO("Failed to write WIM chunks");
793 ret = WIMLIB_ERR_WRITE;
796 bytes_remaining -= bytes_written;
797 if (bytes_remaining <= 0) {
801 while (bytes_written >= 0) {
802 wimlib_assert(nvecs != 0);
803 if (bytes_written >= vecs[0].iov_len) {
806 bytes_written -= vecs[0].iov_len;
808 vecs[0].iov_base += bytes_written;
809 vecs[0].iov_len -= bytes_written;
817 struct main_writer_thread_ctx {
818 struct list_head *stream_list;
819 struct wim_lookup_table *lookup_table;
822 int write_resource_flags;
823 struct shared_queue *res_to_compress_queue;
824 struct shared_queue *compressed_res_queue;
826 wimlib_progress_func_t progress_func;
827 union wimlib_progress_info *progress;
829 struct list_head available_msgs;
830 struct list_head outstanding_streams;
831 struct list_head serial_streams;
832 size_t num_outstanding_messages;
834 SHA_CTX next_sha_ctx;
837 struct wim_lookup_table_entry *next_lte;
839 struct message *msgs;
840 struct message *next_msg;
841 struct chunk_table *cur_chunk_tab;
845 init_message(struct message *msg)
847 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
848 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
849 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
850 if (msg->compressed_chunks[i] == NULL ||
851 msg->uncompressed_chunks[i] == NULL)
852 return WIMLIB_ERR_NOMEM;
858 destroy_message(struct message *msg)
860 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
861 FREE(msg->compressed_chunks[i]);
862 FREE(msg->uncompressed_chunks[i]);
867 free_messages(struct message *msgs, size_t num_messages)
870 for (size_t i = 0; i < num_messages; i++)
871 destroy_message(&msgs[i]);
876 static struct message *
877 allocate_messages(size_t num_messages)
879 struct message *msgs;
881 msgs = CALLOC(num_messages, sizeof(struct message));
884 for (size_t i = 0; i < num_messages; i++) {
885 if (init_message(&msgs[i])) {
886 free_messages(msgs, num_messages);
894 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
896 while (ctx->num_outstanding_messages--)
897 shared_queue_get(ctx->compressed_res_queue);
898 free_messages(ctx->msgs, ctx->num_messages);
899 FREE(ctx->cur_chunk_tab);
903 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
905 /* Pre-allocate all the buffers that will be needed to do the chunk
907 ctx->msgs = allocate_messages(ctx->num_messages);
909 return WIMLIB_ERR_NOMEM;
911 /* Initially, all the messages are available to use. */
912 INIT_LIST_HEAD(&ctx->available_msgs);
913 for (size_t i = 0; i < ctx->num_messages; i++)
914 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
916 /* outstanding_streams is the list of streams that currently have had
917 * chunks sent off for compression.
919 * The first stream in outstanding_streams is the stream that is
920 * currently being written.
922 * The last stream in outstanding_streams is the stream that is
923 * currently being read and having chunks fed to the compressor threads.
925 INIT_LIST_HEAD(&ctx->outstanding_streams);
926 ctx->num_outstanding_messages = 0;
928 ctx->next_msg = NULL;
930 /* Resources that don't need any chunks compressed are added to this
931 * list and written directly by the main thread. */
932 INIT_LIST_HEAD(&ctx->serial_streams);
934 ctx->cur_chunk_tab = NULL;
940 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
943 struct wim_lookup_table_entry *cur_lte;
946 wimlib_assert(!list_empty(&ctx->outstanding_streams));
947 wimlib_assert(ctx->num_outstanding_messages != 0);
949 cur_lte = container_of(ctx->outstanding_streams.next,
950 struct wim_lookup_table_entry,
951 being_compressed_list);
953 /* Get the next message from the queue and process it.
954 * The message will contain 1 or more data chunks that have been
956 msg = shared_queue_get(ctx->compressed_res_queue);
957 msg->complete = true;
958 --ctx->num_outstanding_messages;
960 /* Is this the next chunk in the current resource? If it's not
961 * (i.e., an earlier chunk in a same or different resource
962 * hasn't been compressed yet), do nothing, and keep this
963 * message around until all earlier chunks are received.
965 * Otherwise, write all the chunks we can. */
966 while (cur_lte != NULL &&
967 !list_empty(&cur_lte->msg_list)
968 && (msg = container_of(cur_lte->msg_list.next,
972 list_move(&msg->list, &ctx->available_msgs);
973 if (msg->begin_chunk == 0) {
974 /* This is the first set of chunks. Leave space
975 * for the chunk table in the output file. */
976 off_t cur_offset = filedes_offset(ctx->out_fd);
977 if (cur_offset == -1)
978 return WIMLIB_ERR_WRITE;
979 ret = begin_wim_resource_chunk_tab(cur_lte,
982 &ctx->cur_chunk_tab);
987 /* Write the compressed chunks from the message. */
988 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab);
992 /* Was this the last chunk of the stream? If so, finish
994 if (list_empty(&cur_lte->msg_list) &&
995 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1000 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1006 list_del(&cur_lte->being_compressed_list);
1008 /* Grab the offset of this stream in the output file
1009 * from the chunk table before we free it. */
1010 offset = ctx->cur_chunk_tab->file_offset;
1012 FREE(ctx->cur_chunk_tab);
1013 ctx->cur_chunk_tab = NULL;
1015 if (res_csize >= wim_resource_size(cur_lte)) {
1016 /* Oops! We compressed the resource to
1017 * larger than the original size. Write
1018 * the resource uncompressed instead. */
1019 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1020 "writing uncompressed instead",
1021 wim_resource_size(cur_lte), res_csize);
1022 ret = seek_and_truncate(ctx->out_fd, offset);
1025 ret = write_wim_resource(cur_lte,
1027 WIMLIB_COMPRESSION_TYPE_NONE,
1028 &cur_lte->output_resource_entry,
1029 ctx->write_resource_flags);
1033 cur_lte->output_resource_entry.size =
1036 cur_lte->output_resource_entry.original_size =
1037 cur_lte->resource_entry.original_size;
1039 cur_lte->output_resource_entry.offset =
1042 cur_lte->output_resource_entry.flags =
1043 cur_lte->resource_entry.flags |
1044 WIM_RESHDR_FLAG_COMPRESSED;
1047 do_write_streams_progress(ctx->progress,
1049 wim_resource_size(cur_lte));
1051 /* Since we just finished writing a stream, write any
1052 * streams that have been added to the serial_streams
1053 * list for direct writing by the main thread (e.g.
1054 * resources that don't need to be compressed because
1055 * the desired compression type is the same as the
1056 * previous compression type). */
1057 if (!list_empty(&ctx->serial_streams)) {
1058 ret = do_write_stream_list_serial(&ctx->serial_streams,
1062 ctx->write_resource_flags,
1069 /* Advance to the next stream to write. */
1070 if (list_empty(&ctx->outstanding_streams)) {
1073 cur_lte = container_of(ctx->outstanding_streams.next,
1074 struct wim_lookup_table_entry,
1075 being_compressed_list);
1082 /* Called when the main thread has read a new chunk of data. */
1084 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1086 struct main_writer_thread_ctx *ctx = _ctx;
1088 struct message *next_msg;
1089 u64 next_chunk_in_msg;
1091 /* Update SHA1 message digest for the stream currently being read by the
1093 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1095 /* We send chunks of data to the compressor chunks in batches which we
1096 * refer to as "messages". @next_msg is the message that is currently
1097 * being prepared to send off. If it is NULL, that indicates that we
1098 * need to start a new message. */
1099 next_msg = ctx->next_msg;
1101 /* We need to start a new message. First check to see if there
1102 * is a message available in the list of available messages. If
1103 * so, we can just take one. If not, all the messages (there is
1104 * a fixed number of them, proportional to the number of
1105 * threads) have been sent off to the compressor threads, so we
1106 * receive messages from the compressor threads containing
1107 * compressed chunks of data.
1109 * We may need to receive multiple messages before one is
1110 * actually available to use because messages received that are
1111 * *not* for the very next set of chunks to compress must be
1112 * buffered until it's time to write those chunks. */
1113 while (list_empty(&ctx->available_msgs)) {
1114 ret = receive_compressed_chunks(ctx);
1119 next_msg = container_of(ctx->available_msgs.next,
1120 struct message, list);
1121 list_del(&next_msg->list);
1122 next_msg->complete = false;
1123 next_msg->begin_chunk = ctx->next_chunk;
1124 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1125 ctx->next_num_chunks - ctx->next_chunk);
1126 ctx->next_msg = next_msg;
1129 /* Fill in the next chunk to compress */
1130 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1132 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1133 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1136 if (++next_chunk_in_msg == next_msg->num_chunks) {
1137 /* Send off an array of chunks to compress */
1138 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1139 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1140 ++ctx->num_outstanding_messages;
1141 ctx->next_msg = NULL;
1147 main_writer_thread_finish(void *_ctx)
1149 struct main_writer_thread_ctx *ctx = _ctx;
1151 while (ctx->num_outstanding_messages != 0) {
1152 ret = receive_compressed_chunks(ctx);
1156 wimlib_assert(list_empty(&ctx->outstanding_streams));
1157 return do_write_stream_list_serial(&ctx->serial_streams,
1161 ctx->write_resource_flags,
1167 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1168 struct main_writer_thread_ctx *ctx)
1172 /* Read the entire stream @lte, feeding its data chunks to the
1173 * compressor threads. Also SHA1-sum the stream; this is required in
1174 * the case that @lte is unhashed, and a nice additional verification
1175 * when @lte is already hashed. */
1176 sha1_init(&ctx->next_sha_ctx);
1177 ctx->next_chunk = 0;
1178 ctx->next_num_chunks = wim_resource_chunks(lte);
1179 ctx->next_lte = lte;
1180 INIT_LIST_HEAD(<e->msg_list);
1181 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1182 ret = read_resource_prefix(lte, wim_resource_size(lte),
1183 main_writer_thread_cb, ctx, 0);
1185 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1186 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1192 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1194 struct main_writer_thread_ctx *ctx = _ctx;
1197 if (wim_resource_size(lte) < 1000 ||
1198 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1199 (lte->resource_location == RESOURCE_IN_WIM &&
1200 !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1201 wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
1203 /* Stream is too small or isn't being compressed. Process it by
1204 * the main thread when we have a chance. We can't necessarily
1205 * process it right here, as the main thread could be in the
1206 * middle of writing a different stream. */
1207 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1211 ret = submit_stream_for_compression(lte, ctx);
1213 lte->no_progress = 1;
1218 get_default_num_threads()
1221 return win32_get_number_of_processors();
1223 return sysconf(_SC_NPROCESSORS_ONLN);
1227 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1228 * parameter and will perform compression using that many threads. Falls
1229 * back to write_stream_list_serial() on certain errors, such as a failure to
1230 * create the number of threads requested.
1232 * High level description of the algorithm for writing compressed streams in
1233 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1234 * rather than on full files. The currently executing thread becomes the main
1235 * thread and is entirely in charge of reading the data to compress (which may
1236 * be in any location understood by the resource code--- such as in an external
1237 * file being captured, or in another WIM file from which an image is being
1238 * exported) and actually writing the compressed data to the output file.
1239 * Additional threads are "compressor threads" and all execute the
1240 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1241 * the main thread, compress them, and hand them back to the main thread.
1243 * Certain streams, such as streams that do not need to be compressed (e.g.
1244 * input compression type same as output compression type) or streams of very
1245 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1246 * handled entirely by the main thread at an appropriate time.
1248 * At any given point in time, multiple streams may be having chunks compressed
1249 * concurrently. The stream that the main thread is currently *reading* may be
1250 * later in the list that the stream that the main thread is currently
1254 write_stream_list_parallel(struct list_head *stream_list,
1255 struct wim_lookup_table *lookup_table,
1258 int write_resource_flags,
1259 wimlib_progress_func_t progress_func,
1260 union wimlib_progress_info *progress,
1261 unsigned num_threads)
1264 struct shared_queue res_to_compress_queue;
1265 struct shared_queue compressed_res_queue;
1266 pthread_t *compressor_threads = NULL;
1268 if (num_threads == 0) {
1269 long nthreads = get_default_num_threads();
1270 if (nthreads < 1 || nthreads > UINT_MAX) {
1271 WARNING("Could not determine number of processors! Assuming 1");
1273 } else if (nthreads == 1) {
1274 goto out_serial_quiet;
1276 num_threads = nthreads;
1280 DEBUG("Writing stream list (parallel version, num_threads=%u)",
1283 progress->write_streams.num_threads = num_threads;
1285 static const size_t MESSAGES_PER_THREAD = 2;
1286 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1288 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1290 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1294 ret = shared_queue_init(&compressed_res_queue, queue_size);
1296 goto out_destroy_res_to_compress_queue;
1298 struct compressor_thread_params params;
1299 params.res_to_compress_queue = &res_to_compress_queue;
1300 params.compressed_res_queue = &compressed_res_queue;
1301 params.compress = get_compress_func(out_ctype);
1303 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1304 if (!compressor_threads) {
1305 ret = WIMLIB_ERR_NOMEM;
1306 goto out_destroy_compressed_res_queue;
1309 for (unsigned i = 0; i < num_threads; i++) {
1310 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1311 ret = pthread_create(&compressor_threads[i], NULL,
1312 compressor_thread_proc, ¶ms);
1315 ERROR_WITH_ERRNO("Failed to create compressor "
1317 i + 1, num_threads);
1324 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1326 struct main_writer_thread_ctx ctx;
1327 ctx.stream_list = stream_list;
1328 ctx.lookup_table = lookup_table;
1329 ctx.out_fd = out_fd;
1330 ctx.out_ctype = out_ctype;
1331 ctx.res_to_compress_queue = &res_to_compress_queue;
1332 ctx.compressed_res_queue = &compressed_res_queue;
1333 ctx.num_messages = queue_size;
1334 ctx.write_resource_flags = write_resource_flags;
1335 ctx.progress_func = progress_func;
1336 ctx.progress = progress;
1337 ret = main_writer_thread_init_ctx(&ctx);
1340 ret = do_write_stream_list(stream_list, lookup_table,
1341 main_thread_process_next_stream,
1342 &ctx, progress_func, progress);
1344 goto out_destroy_ctx;
1346 /* The main thread has finished reading all streams that are going to be
1347 * compressed in parallel, and it now needs to wait for all remaining
1348 * chunks to be compressed so that the remaining streams can actually be
1349 * written to the output file. Furthermore, any remaining streams that
1350 * had processing deferred to the main thread need to be handled. These
1351 * tasks are done by the main_writer_thread_finish() function. */
1352 ret = main_writer_thread_finish(&ctx);
1354 main_writer_thread_destroy_ctx(&ctx);
1356 for (unsigned i = 0; i < num_threads; i++)
1357 shared_queue_put(&res_to_compress_queue, NULL);
1359 for (unsigned i = 0; i < num_threads; i++) {
1360 if (pthread_join(compressor_threads[i], NULL)) {
1361 WARNING_WITH_ERRNO("Failed to join compressor "
1363 i + 1, num_threads);
1366 FREE(compressor_threads);
1367 out_destroy_compressed_res_queue:
1368 shared_queue_destroy(&compressed_res_queue);
1369 out_destroy_res_to_compress_queue:
1370 shared_queue_destroy(&res_to_compress_queue);
1371 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1374 WARNING("Falling back to single-threaded compression");
1376 return write_stream_list_serial(stream_list,
1380 write_resource_flags,
1388 * Write a list of streams to a WIM (@out_fd) using the compression type
1389 * @out_ctype and up to @num_threads compressor threads.
1392 write_stream_list(struct list_head *stream_list,
1393 struct wim_lookup_table *lookup_table,
1394 filedes_t out_fd, int out_ctype, int write_flags,
1395 unsigned num_threads, wimlib_progress_func_t progress_func)
1397 struct wim_lookup_table_entry *lte;
1398 size_t num_streams = 0;
1399 u64 total_bytes = 0;
1400 u64 total_compression_bytes = 0;
1401 union wimlib_progress_info progress;
1403 int write_resource_flags;
1405 if (list_empty(stream_list))
1408 write_resource_flags = write_flags_to_resource_flags(write_flags);
1410 /* Calculate the total size of the streams to be written. Note: this
1411 * will be the uncompressed size, as we may not know the compressed size
1412 * yet, and also this will assume that every unhashed stream will be
1413 * written (which will not necessarily be the case). */
1414 list_for_each_entry(lte, stream_list, write_streams_list) {
1416 total_bytes += wim_resource_size(lte);
1417 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1418 && (wim_resource_compression_type(lte) != out_ctype ||
1419 (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1421 total_compression_bytes += wim_resource_size(lte);
1424 progress.write_streams.total_bytes = total_bytes;
1425 progress.write_streams.total_streams = num_streams;
1426 progress.write_streams.completed_bytes = 0;
1427 progress.write_streams.completed_streams = 0;
1428 progress.write_streams.num_threads = num_threads;
1429 progress.write_streams.compression_type = out_ctype;
1430 progress.write_streams._private = 0;
1432 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1433 if (total_compression_bytes >= 1000000 && num_threads != 1)
1434 ret = write_stream_list_parallel(stream_list,
1438 write_resource_flags,
1444 ret = write_stream_list_serial(stream_list,
1448 write_resource_flags,
1454 struct stream_size_table {
1455 struct hlist_head *array;
1461 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1463 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1465 return WIMLIB_ERR_NOMEM;
1466 tab->num_entries = 0;
1467 tab->capacity = capacity;
1472 destroy_stream_size_table(struct stream_size_table *tab)
1478 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1480 struct stream_size_table *tab = _tab;
1482 struct wim_lookup_table_entry *same_size_lte;
1483 struct hlist_node *tmp;
1485 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1486 lte->unique_size = 1;
1487 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1488 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1489 lte->unique_size = 0;
1490 same_size_lte->unique_size = 0;
1495 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1501 struct lte_overwrite_prepare_args {
1504 struct list_head stream_list;
1505 struct stream_size_table stream_size_tab;
1508 /* First phase of preparing streams for an in-place overwrite. This is called
1509 * on all streams, both hashed and unhashed, except the metadata resources. */
1511 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1513 struct lte_overwrite_prepare_args *args = _args;
1515 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1516 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1517 list_add_tail(<e->write_streams_list, &args->stream_list);
1518 lte->out_refcnt = lte->refcnt;
1519 stream_size_table_insert(lte, &args->stream_size_tab);
1523 /* Second phase of preparing streams for an in-place overwrite. This is called
1524 * on existing metadata resources and hashed streams, but not unhashed streams.
1526 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1527 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1528 * the latter uses lte->hash_list_2, while the former expects to set
1529 * lte->output_resource_entry. */
1531 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1533 struct lte_overwrite_prepare_args *args = _args;
1535 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1536 /* We can't do an in place overwrite on the WIM if there are
1537 * streams after the XML data. */
1538 if (lte->resource_entry.offset +
1539 lte->resource_entry.size > args->end_offset)
1541 #ifdef ENABLE_ERROR_MESSAGES
1542 ERROR("The following resource is after the XML data:");
1543 print_lookup_table_entry(lte, stderr);
1545 return WIMLIB_ERR_RESOURCE_ORDER;
1547 copy_resource_entry(<e->output_resource_entry,
1548 <e->resource_entry);
1553 /* Given a WIM that we are going to overwrite in place with zero or more
1554 * additional streams added, construct a list the list of new unique streams
1555 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1556 * streams that need to be added but may be identical to other hashed or
1557 * unhashed streams. These unhashed streams are checksummed while the streams
1558 * are being written. To aid this process, the member @unique_size is set to 1
1559 * on streams that have a unique size and therefore must be written.
1561 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1562 * indicate the number of times the stream is referenced in only the streams
1563 * that are being written; this may still be adjusted later when unhashed
1564 * streams are being resolved.
1567 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1568 struct list_head *stream_list)
1571 struct lte_overwrite_prepare_args args;
1575 args.end_offset = end_offset;
1576 ret = init_stream_size_table(&args.stream_size_tab,
1577 wim->lookup_table->capacity);
1581 INIT_LIST_HEAD(&args.stream_list);
1582 for (i = 0; i < wim->hdr.image_count; i++) {
1583 struct wim_image_metadata *imd;
1584 struct wim_lookup_table_entry *lte;
1586 imd = wim->image_metadata[i];
1587 image_for_each_unhashed_stream(lte, imd)
1588 lte_overwrite_prepare(lte, &args);
1590 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1591 list_transfer(&args.stream_list, stream_list);
1593 for (i = 0; i < wim->hdr.image_count; i++) {
1594 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1597 goto out_destroy_stream_size_table;
1599 ret = for_lookup_table_entry(wim->lookup_table,
1600 lte_overwrite_prepare_2, &args);
1601 out_destroy_stream_size_table:
1602 destroy_stream_size_table(&args.stream_size_tab);
1607 struct find_streams_ctx {
1608 struct list_head stream_list;
1609 struct stream_size_table stream_size_tab;
1613 inode_find_streams_to_write(struct wim_inode *inode,
1614 struct wim_lookup_table *table,
1615 struct list_head *stream_list,
1616 struct stream_size_table *tab)
1618 struct wim_lookup_table_entry *lte;
1619 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1620 lte = inode_stream_lte(inode, i, table);
1622 if (lte->out_refcnt == 0) {
1624 stream_size_table_insert(lte, tab);
1625 list_add_tail(<e->write_streams_list, stream_list);
1627 lte->out_refcnt += inode->i_nlink;
1633 image_find_streams_to_write(WIMStruct *w)
1635 struct find_streams_ctx *ctx;
1636 struct wim_image_metadata *imd;
1637 struct wim_inode *inode;
1638 struct wim_lookup_table_entry *lte;
1641 imd = wim_get_current_image_metadata(w);
1643 image_for_each_unhashed_stream(lte, imd)
1644 lte->out_refcnt = 0;
1646 /* Go through this image's inodes to find any streams that have not been
1648 image_for_each_inode(inode, imd) {
1649 inode_find_streams_to_write(inode, w->lookup_table,
1651 &ctx->stream_size_tab);
1656 /* Given a WIM that from which one or all of the images is being written, build
1657 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1658 * written, plus any unhashed streams that need to be written but may be
1659 * identical to other hashed or unhashed streams being written. These unhashed
1660 * streams are checksummed while the streams are being written. To aid this
1661 * process, the member @unique_size is set to 1 on streams that have a unique
1662 * size and therefore must be written.
1664 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1665 * indicate the number of times the stream is referenced in only the streams
1666 * that are being written; this may still be adjusted later when unhashed
1667 * streams are being resolved.
1670 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1673 struct find_streams_ctx ctx;
1675 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1676 ret = init_stream_size_table(&ctx.stream_size_tab,
1677 wim->lookup_table->capacity);
1680 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1681 &ctx.stream_size_tab);
1682 INIT_LIST_HEAD(&ctx.stream_list);
1683 wim->private = &ctx;
1684 ret = for_image(wim, image, image_find_streams_to_write);
1685 destroy_stream_size_table(&ctx.stream_size_tab);
1687 list_transfer(&ctx.stream_list, stream_list);
1691 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1694 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1695 unsigned num_threads,
1696 wimlib_progress_func_t progress_func)
1699 struct list_head stream_list;
1701 ret = prepare_stream_list(wim, image, &stream_list);
1704 return write_stream_list(&stream_list,
1707 wimlib_get_compression_type(wim),
1714 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1715 * table (optional), then overwrite the WIM header.
1717 * write_flags is a bitwise OR of the following:
1719 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1720 * Include an integrity table.
1722 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1723 * Show progress information when (if) writing the integrity table.
1725 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1726 * Don't write the lookup table.
1728 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1729 * When (if) writing the integrity table, re-use entries from the
1730 * existing integrity table, if possible.
1732 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1733 * After writing the XML data but before writing the integrity
1734 * table, write a temporary WIM header and flush the stream so that
1735 * the WIM is less likely to become corrupted upon abrupt program
1738 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1739 * fsync() the output file before closing it.
1743 finish_write(WIMStruct *w, int image, int write_flags,
1744 wimlib_progress_func_t progress_func)
1747 struct wim_header hdr;
1749 /* @hdr will be the header for the new WIM. First copy all the data
1750 * from the header in the WIMStruct; then set all the fields that may
1751 * have changed, including the resource entries, boot index, and image
1753 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1755 /* Set image count and boot index correctly for single image writes */
1756 if (image != WIMLIB_ALL_IMAGES) {
1757 hdr.image_count = 1;
1758 if (hdr.boot_idx == image)
1764 /* In the WIM header, there is room for the resource entry for a
1765 * metadata resource labeled as the "boot metadata". This entry should
1766 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1767 * it should be a copy of the resource entry for the image that is
1768 * marked as bootable. This is not well documented... */
1769 if (hdr.boot_idx == 0) {
1770 zero_resource_entry(&hdr.boot_metadata_res_entry);
1772 copy_resource_entry(&hdr.boot_metadata_res_entry,
1773 &w->image_metadata[ hdr.boot_idx- 1
1774 ]->metadata_lte->output_resource_entry);
1777 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1778 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1783 ret = write_xml_data(w->wim_info, image, w->out_fd,
1784 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1785 wim_info_get_total_bytes(w->wim_info) : 0,
1786 &hdr.xml_res_entry);
1790 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1791 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1792 struct wim_header checkpoint_hdr;
1793 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1794 zero_resource_entry(&checkpoint_hdr.integrity);
1795 ret = write_header(&checkpoint_hdr, w->out_fd);
1800 off_t old_lookup_table_end;
1801 off_t new_lookup_table_end;
1802 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1803 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1804 w->hdr.lookup_table_res_entry.size;
1806 old_lookup_table_end = 0;
1808 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1809 hdr.lookup_table_res_entry.size;
1811 ret = write_integrity_table(w->out_fd,
1813 new_lookup_table_end,
1814 old_lookup_table_end,
1819 zero_resource_entry(&hdr.integrity);
1822 ret = write_header(&hdr, w->out_fd);
1826 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1827 if (fsync(w->out_fd)) {
1828 ERROR_WITH_ERRNO("Error syncing data to WIM file");
1829 ret = WIMLIB_ERR_WRITE;
1833 if (close(w->out_fd)) {
1834 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1836 ret = WIMLIB_ERR_WRITE;
1838 w->out_fd = INVALID_FILEDES;
1842 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1844 lock_wim(WIMStruct *w, filedes_t fd)
1847 if (fd != INVALID_FILEDES && !w->wim_locked) {
1848 ret = flock(fd, LOCK_EX | LOCK_NB);
1850 if (errno == EWOULDBLOCK) {
1851 ERROR("`%"TS"' is already being modified or has been "
1852 "mounted read-write\n"
1853 " by another process!", w->filename);
1854 ret = WIMLIB_ERR_ALREADY_LOCKED;
1856 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1869 open_wim_writable(WIMStruct *w, const tchar *path, int open_flags)
1871 wimlib_assert(w->out_fd == INVALID_FILEDES);
1872 w->out_fd = open(path, open_flags, 0644);
1873 if (w->out_fd == INVALID_FILEDES) {
1874 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1875 return WIMLIB_ERR_OPEN;
1882 close_wim_writable(WIMStruct *w)
1884 if (w->out_fd != INVALID_FILEDES) {
1885 if (close(w->out_fd))
1886 WARNING_WITH_ERRNO("Failed to close output WIM");
1887 w->out_fd = INVALID_FILEDES;
1891 /* Open file stream and write dummy header for WIM. */
1893 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1896 int open_flags = O_TRUNC | O_CREAT;
1897 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1898 open_flags |= O_RDWR;
1900 open_flags |= O_WRONLY;
1901 ret = open_wim_writable(w, path, open_flags);
1904 /* Write dummy header. It will be overwritten later. */
1905 ret = write_header(&w->hdr, w->out_fd);
1908 if (lseek(w->out_fd, 0, SEEK_END) == -1) {
1909 ERROR_WITH_ERRNO("Failed to seek to end of WIM");
1910 return WIMLIB_ERR_WRITE;
1915 /* Writes a stand-alone WIM to a file. */
1917 wimlib_write(WIMStruct *w, const tchar *path,
1918 int image, int write_flags, unsigned num_threads,
1919 wimlib_progress_func_t progress_func)
1924 return WIMLIB_ERR_INVALID_PARAM;
1926 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1928 if (image != WIMLIB_ALL_IMAGES &&
1929 (image < 1 || image > w->hdr.image_count))
1930 return WIMLIB_ERR_INVALID_IMAGE;
1932 if (w->hdr.total_parts != 1) {
1933 ERROR("Cannot call wimlib_write() on part of a split WIM");
1934 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1937 ret = begin_write(w, path, write_flags);
1941 ret = write_wim_streams(w, image, write_flags, num_threads,
1947 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1949 ret = for_image(w, image, write_metadata_resource);
1954 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1956 ret = finish_write(w, image, write_flags, progress_func);
1957 /* finish_write() closed the WIM for us */
1960 close_wim_writable(w);
1962 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1967 any_images_modified(WIMStruct *w)
1969 for (int i = 0; i < w->hdr.image_count; i++)
1970 if (w->image_metadata[i]->modified)
1976 * Overwrite a WIM, possibly appending streams to it.
1978 * A WIM looks like (or is supposed to look like) the following:
1980 * Header (212 bytes)
1981 * Streams and metadata resources (variable size)
1982 * Lookup table (variable size)
1983 * XML data (variable size)
1984 * Integrity table (optional) (variable size)
1986 * If we are not adding any streams or metadata resources, the lookup table is
1987 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1988 * header. This operation is potentially unsafe if the program is abruptly
1989 * terminated while the XML data or integrity table are being overwritten, but
1990 * before the new header has been written. To partially alleviate this problem,
1991 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1992 * finish_write() to cause a temporary WIM header to be written after the XML
1993 * data has been written. This may prevent the WIM from becoming corrupted if
1994 * the program is terminated while the integrity table is being calculated (but
1995 * no guarantees, due to write re-ordering...).
1997 * If we are adding new streams or images (metadata resources), the lookup table
1998 * needs to be changed, and those streams need to be written. In this case, we
1999 * try to perform a safe update of the WIM file by writing the streams *after*
2000 * the end of the previous WIM, then writing the new lookup table, XML data, and
2001 * (optionally) integrity table following the new streams. This will produce a
2002 * layout like the following:
2004 * Header (212 bytes)
2005 * (OLD) Streams and metadata resources (variable size)
2006 * (OLD) Lookup table (variable size)
2007 * (OLD) XML data (variable size)
2008 * (OLD) Integrity table (optional) (variable size)
2009 * (NEW) Streams and metadata resources (variable size)
2010 * (NEW) Lookup table (variable size)
2011 * (NEW) XML data (variable size)
2012 * (NEW) Integrity table (optional) (variable size)
2014 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2015 * the header is overwritten to point to the new lookup table, XML data, and
2016 * integrity table, to produce the following layout:
2018 * Header (212 bytes)
2019 * Streams and metadata resources (variable size)
2020 * Nothing (variable size)
2021 * More Streams and metadata resources (variable size)
2022 * Lookup table (variable size)
2023 * XML data (variable size)
2024 * Integrity table (optional) (variable size)
2026 * This method allows an image to be appended to a large WIM very quickly, and
2027 * is is crash-safe except in the case of write re-ordering, but the
2028 * disadvantage is that a small hole is left in the WIM where the old lookup
2029 * table, xml data, and integrity table were. (These usually only take up a
2030 * small amount of space compared to the streams, however.)
2033 overwrite_wim_inplace(WIMStruct *w, int write_flags,
2034 unsigned num_threads,
2035 wimlib_progress_func_t progress_func)
2038 struct list_head stream_list;
2040 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2043 DEBUG("Overwriting `%"TS"' in-place", w->filename);
2045 /* Make sure that the integrity table (if present) is after the XML
2046 * data, and that there are no stream resources, metadata resources, or
2047 * lookup tables after the XML data. Otherwise, these data would be
2049 old_xml_begin = w->hdr.xml_res_entry.offset;
2050 old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
2051 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
2052 w->hdr.lookup_table_res_entry.size;
2053 if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
2054 ERROR("Didn't expect the integrity table to be before the XML data");
2055 return WIMLIB_ERR_RESOURCE_ORDER;
2058 if (old_lookup_table_end > old_xml_begin) {
2059 ERROR("Didn't expect the lookup table to be after the XML data");
2060 return WIMLIB_ERR_RESOURCE_ORDER;
2063 /* Set @old_wim_end, which indicates the point beyond which we don't
2064 * allow any file and metadata resources to appear without returning
2065 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2066 * overwrite these resources). */
2067 if (!w->deletion_occurred && !any_images_modified(w)) {
2068 /* If no images have been modified and no images have been
2069 * deleted, a new lookup table does not need to be written. We
2070 * shall write the new XML data and optional integrity table
2071 * immediately after the lookup table. Note that this may
2072 * overwrite an existing integrity table. */
2073 DEBUG("Skipping writing lookup table "
2074 "(no images modified or deleted)");
2075 old_wim_end = old_lookup_table_end;
2076 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2077 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2078 } else if (w->hdr.integrity.offset) {
2079 /* Old WIM has an integrity table; begin writing new streams
2081 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2083 /* No existing integrity table; begin writing new streams after
2084 * the old XML data. */
2085 old_wim_end = old_xml_end;
2088 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2093 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2094 open_flags |= O_RDWR;
2096 open_flags |= O_WRONLY;
2097 ret = open_wim_writable(w, w->filename, open_flags);
2101 ret = lock_wim(w, w->out_fd);
2103 close_wim_writable(w);
2107 if (lseek(w->out_fd, old_wim_end, SEEK_SET) == -1) {
2108 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2109 close_wim_writable(w);
2111 return WIMLIB_ERR_WRITE;
2114 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2116 ret = write_stream_list(&stream_list,
2119 wimlib_get_compression_type(w),
2126 for (int i = 0; i < w->hdr.image_count; i++) {
2127 if (w->image_metadata[i]->modified) {
2128 select_wim_image(w, i + 1);
2129 ret = write_metadata_resource(w);
2134 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2135 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2138 close_wim_writable(w);
2139 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2140 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2141 w->filename, old_wim_end);
2142 /* Return value of truncate() is ignored because this is already
2144 (void)ttruncate(w->filename, old_wim_end);
2151 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2152 unsigned num_threads,
2153 wimlib_progress_func_t progress_func)
2155 size_t wim_name_len;
2158 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2160 /* Write the WIM to a temporary file in the same directory as the
2162 wim_name_len = tstrlen(w->filename);
2163 tchar tmpfile[wim_name_len + 10];
2164 tmemcpy(tmpfile, w->filename, wim_name_len);
2165 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2166 tmpfile[wim_name_len + 9] = T('\0');
2168 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2169 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2170 num_threads, progress_func);
2172 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2176 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2179 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2180 * specified to CreateFile(). The WIM was opened with fopen(), which
2181 * didn't provided this flag to CreateFile, so the handle must be closed
2182 * before executing the rename(). */
2183 if (w->fp != NULL) {
2189 /* Rename the new file to the old file .*/
2190 if (trename(tmpfile, w->filename) != 0) {
2191 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2192 tmpfile, w->filename);
2193 ret = WIMLIB_ERR_RENAME;
2197 if (progress_func) {
2198 union wimlib_progress_info progress;
2199 progress.rename.from = tmpfile;
2200 progress.rename.to = w->filename;
2201 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2205 /* Remove temporary file. */
2206 if (tunlink(tmpfile) != 0)
2207 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2213 * Writes a WIM file to the original file that it was read from, overwriting it.
2216 wimlib_overwrite(WIMStruct *w, int write_flags,
2217 unsigned num_threads,
2218 wimlib_progress_func_t progress_func)
2220 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2223 return WIMLIB_ERR_NO_FILENAME;
2225 if (w->hdr.total_parts != 1) {
2226 ERROR("Cannot modify a split WIM");
2227 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2230 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2231 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2234 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2236 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2237 WARNING("Falling back to re-building entire WIM");
2241 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,