4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/header.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/lookup_table.h"
43 #include "wimlib/metadata.h"
44 #include "wimlib/resource.h"
45 #include "wimlib/write.h"
46 #include "wimlib/xml.h"
49 # include "wimlib/win32.h" /* win32_get_number_of_processors() */
52 #ifdef ENABLE_MULTITHREADED_COMPRESSION
62 # include <ntfs-3g/attrib.h>
63 # include <ntfs-3g/inode.h>
64 # include <ntfs-3g/dir.h>
76 # include <sys/uio.h> /* for `struct iovec' */
79 /* Chunk table that's located at the beginning of each compressed resource in
80 * the WIM. (This is not the on-disk format; the on-disk format just has an
81 * array of offsets.) */
84 u64 original_resource_size;
87 unsigned bytes_per_chunk_entry;
93 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
94 * integers, including the first offset of 0, which will not be written.
96 u8 offsets[] _aligned_attribute(8);
100 * Allocates and initializes a chunk table, and reserves space for it in the
104 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
107 struct chunk_table **chunk_tab_ret)
109 u64 size = wim_resource_size(lte);
110 u64 num_chunks = wim_resource_chunks(lte);
111 unsigned bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
112 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
113 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
115 DEBUG("Beginning chunk table for stream with size %"PRIu64, size);
118 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
120 return WIMLIB_ERR_NOMEM;
122 chunk_tab->file_offset = file_offset;
123 chunk_tab->num_chunks = num_chunks;
124 chunk_tab->original_resource_size = size;
125 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
126 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
128 chunk_tab->cur_offset_p = chunk_tab->offsets;
130 /* We don't know the correct offsets yet; this just writes zeroes to
131 * reserve space for the table, so we can go back to it later after
132 * we've written the compressed chunks following it. */
133 if (full_write(out_fd, chunk_tab->offsets,
134 chunk_tab->table_disk_size) != chunk_tab->table_disk_size)
136 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
139 return WIMLIB_ERR_WRITE;
141 *chunk_tab_ret = chunk_tab;
145 /* Add the offset for the next chunk to the chunk table being constructed for a
146 * compressed stream. */
148 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
150 if (chunk_tab->bytes_per_chunk_entry == 4) {
151 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
152 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
153 chunk_tab->cur_offset_u32 += out_chunk_size;
155 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
156 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
157 chunk_tab->cur_offset_u64 += out_chunk_size;
162 * compress_func_t- Pointer to a function to compresses a chunk
163 * of a WIM resource. This may be either
164 * wimlib_xpress_compress() (xpress-compress.c) or
165 * wimlib_lzx_compress() (lzx-compress.c).
167 * @chunk: Uncompressed data of the chunk.
168 * @chunk_size: Size of the uncompressed chunk, in bytes.
169 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
171 * Returns the size of the compressed data written to @out in bytes, or 0 if the
172 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
174 * As a special requirement, the compression code is optimized for the WIM
175 * format and therefore requires (@chunk_size <= 32768).
177 * As another special requirement, the compression code will read up to 8 bytes
178 * off the end of the @chunk array for performance reasons. The values of these
179 * bytes will not affect the output of the compression, but the calling code
180 * must make sure that the buffer holding the uncompressed chunk is actually at
181 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
182 * mapped memory that will not cause a memory access violation if accessed.
184 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
187 static compress_func_t
188 get_compress_func(int out_ctype)
190 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
191 return wimlib_lzx_compress;
193 return wimlib_xpress_compress;
197 * Writes a chunk of a WIM resource to an output file.
199 * @chunk: Uncompressed data of the chunk.
200 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
201 * @out_fd: File descriptor to write the chunk to.
202 * @compress: Compression function to use (NULL if writing uncompressed
204 * @chunk_tab: Pointer to chunk table being created. It is updated with the
205 * offset of the chunk we write.
207 * Returns 0 on success; nonzero on failure.
210 write_wim_resource_chunk(const void * restrict chunk,
213 compress_func_t compress,
214 struct chunk_table * restrict chunk_tab)
216 const void *out_chunk;
217 unsigned out_chunk_size;
219 void *compressed_chunk = alloca(chunk_size);
221 out_chunk_size = (*compress)(chunk, chunk_size, compressed_chunk);
222 if (out_chunk_size) {
223 /* Write compressed */
224 out_chunk = compressed_chunk;
226 /* Write uncompressed */
228 out_chunk_size = chunk_size;
230 chunk_tab_record_chunk(chunk_tab, out_chunk_size);
232 /* Write uncompressed */
234 out_chunk_size = chunk_size;
236 if (full_write(out_fd, out_chunk, out_chunk_size) != out_chunk_size) {
237 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
238 return WIMLIB_ERR_WRITE;
244 * Finishes a WIM chunk table and writes it to the output file at the correct
247 * The final size of the full compressed resource is returned in the
248 * @compressed_size_p.
251 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
252 int out_fd, u64 *compressed_size_p)
254 size_t bytes_written;
256 bytes_written = full_pwrite(out_fd,
257 chunk_tab->offsets + chunk_tab->bytes_per_chunk_entry,
258 chunk_tab->table_disk_size,
259 chunk_tab->file_offset);
260 if (bytes_written != chunk_tab->table_disk_size) {
261 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
263 return WIMLIB_ERR_WRITE;
265 if (chunk_tab->bytes_per_chunk_entry == 4)
266 *compressed_size_p = chunk_tab->cur_offset_u32 + chunk_tab->table_disk_size;
268 *compressed_size_p = chunk_tab->cur_offset_u64 + chunk_tab->table_disk_size;
273 seek_and_truncate(int out_fd, off_t offset)
275 if (lseek(out_fd, offset, SEEK_SET) == -1 ||
276 ftruncate(out_fd, offset))
278 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
279 return WIMLIB_ERR_WRITE;
286 finalize_and_check_sha1(SHA_CTX * restrict sha_ctx,
287 struct wim_lookup_table_entry * restrict lte)
289 u8 md[SHA1_HASH_SIZE];
290 sha1_final(md, sha_ctx);
292 copy_hash(lte->hash, md);
293 } else if (!hashes_equal(md, lte->hash)) {
294 ERROR("WIM resource has incorrect hash!");
295 if (lte_filename_valid(lte)) {
296 ERROR("We were reading it from \"%"TS"\"; maybe "
297 "it changed while we were reading it.",
300 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
306 struct write_resource_ctx {
307 compress_func_t compress;
308 struct chunk_table *chunk_tab;
315 write_resource_cb(const void *restrict chunk, size_t chunk_size,
318 struct write_resource_ctx *ctx = _ctx;
321 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
322 return write_wim_resource_chunk(chunk, chunk_size,
323 ctx->out_fd, ctx->compress,
328 * Write a resource to an output WIM.
330 * @lte: Lookup table entry for the resource, which could be in another WIM,
331 * in an external file, or in another location.
333 * @out_fd: File descriptor opened to the output WIM.
335 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
336 * which compression algorithm to use.
338 * @out_res_entry: On success, this is filled in with the offset, flags,
339 * compressed size, and uncompressed size of the resource
342 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
343 * even if it could otherwise be copied directly from the input.
345 * Additional notes: The SHA1 message digest of the uncompressed data is
346 * calculated (except when doing a raw copy --- see below). If the @unhashed
347 * flag is set on the lookup table entry, this message digest is simply copied
348 * to it; otherwise, the message digest is compared with the existing one, and
349 * the function will fail if they do not match.
352 write_wim_resource(struct wim_lookup_table_entry *lte,
353 int out_fd, int out_ctype,
354 struct resource_entry *out_res_entry,
357 struct write_resource_ctx write_ctx;
363 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
365 /* Get current position in output WIM */
366 offset = filedes_offset(out_fd);
368 ERROR_WITH_ERRNO("Can't get position in output WIM");
369 return WIMLIB_ERR_WRITE;
372 /* If we are not forcing the data to be recompressed, and the input
373 * resource is located in a WIM with the same compression type as that
374 * desired other than no compression, we can simply copy the compressed
375 * data without recompressing it. This also means we must skip
376 * calculating the SHA1, as we never will see the uncompressed data. */
377 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
378 lte->resource_location == RESOURCE_IN_WIM &&
379 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
380 lte->wim->compression_type == out_ctype)
382 flags |= WIMLIB_RESOURCE_FLAG_RAW;
383 write_ctx.doing_sha = false;
384 read_size = lte->resource_entry.size;
386 write_ctx.doing_sha = true;
387 sha1_init(&write_ctx.sha_ctx);
388 read_size = lte->resource_entry.original_size;
391 /* Initialize the chunk table and set the compression function if
392 * compressing the resource. */
393 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
394 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
395 write_ctx.compress = NULL;
396 write_ctx.chunk_tab = NULL;
398 write_ctx.compress = get_compress_func(out_ctype);
399 ret = begin_wim_resource_chunk_tab(lte, out_fd,
401 &write_ctx.chunk_tab);
406 /* Write the entire resource by reading the entire resource and feeding
407 * the data through the write_resource_cb function. */
408 write_ctx.out_fd = out_fd;
410 ret = read_resource_prefix(lte, read_size,
411 write_resource_cb, &write_ctx, flags);
413 goto out_free_chunk_tab;
415 /* Verify SHA1 message digest of the resource, or set the hash for the
417 if (write_ctx.doing_sha) {
418 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
420 goto out_free_chunk_tab;
423 out_res_entry->flags = lte->resource_entry.flags;
424 out_res_entry->original_size = wim_resource_size(lte);
425 out_res_entry->offset = offset;
426 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
427 /* Doing a raw write: The new compressed size is the same as
428 * the compressed size in the other WIM. */
429 new_size = lte->resource_entry.size;
430 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
431 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
432 * is the original size. */
433 new_size = lte->resource_entry.original_size;
434 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
436 /* Using a different compression type: Call
437 * finish_wim_resource_chunk_tab() and it will provide the new
438 * compressed size. */
439 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fd,
442 goto out_free_chunk_tab;
443 if (new_size >= wim_resource_size(lte)) {
444 /* Oops! We compressed the resource to larger than the original
445 * size. Write the resource uncompressed instead. */
446 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
447 "writing uncompressed instead",
448 wim_resource_size(lte), new_size);
449 ret = seek_and_truncate(out_fd, offset);
451 goto out_free_chunk_tab;
452 write_ctx.compress = NULL;
453 write_ctx.doing_sha = false;
454 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
455 goto try_write_again;
457 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
459 out_res_entry->size = new_size;
462 FREE(write_ctx.chunk_tab);
466 #ifdef ENABLE_MULTITHREADED_COMPRESSION
468 /* Blocking shared queue (solves the producer-consumer problem) */
469 struct shared_queue {
473 unsigned filled_slots;
475 pthread_mutex_t lock;
476 pthread_cond_t msg_avail_cond;
477 pthread_cond_t space_avail_cond;
481 shared_queue_init(struct shared_queue *q, unsigned size)
483 wimlib_assert(size != 0);
484 q->array = CALLOC(sizeof(q->array[0]), size);
491 if (pthread_mutex_init(&q->lock, NULL)) {
492 ERROR_WITH_ERRNO("Failed to initialize mutex");
495 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
496 ERROR_WITH_ERRNO("Failed to initialize condition variable");
497 goto err_destroy_lock;
499 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
500 ERROR_WITH_ERRNO("Failed to initialize condition variable");
501 goto err_destroy_msg_avail_cond;
504 err_destroy_msg_avail_cond:
505 pthread_cond_destroy(&q->msg_avail_cond);
507 pthread_mutex_destroy(&q->lock);
509 return WIMLIB_ERR_NOMEM;
513 shared_queue_destroy(struct shared_queue *q)
516 pthread_mutex_destroy(&q->lock);
517 pthread_cond_destroy(&q->msg_avail_cond);
518 pthread_cond_destroy(&q->space_avail_cond);
522 shared_queue_put(struct shared_queue *q, void *obj)
524 pthread_mutex_lock(&q->lock);
525 while (q->filled_slots == q->size)
526 pthread_cond_wait(&q->space_avail_cond, &q->lock);
528 q->back = (q->back + 1) % q->size;
529 q->array[q->back] = obj;
532 pthread_cond_broadcast(&q->msg_avail_cond);
533 pthread_mutex_unlock(&q->lock);
537 shared_queue_get(struct shared_queue *q)
541 pthread_mutex_lock(&q->lock);
542 while (q->filled_slots == 0)
543 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
545 obj = q->array[q->front];
546 q->array[q->front] = NULL;
547 q->front = (q->front + 1) % q->size;
550 pthread_cond_broadcast(&q->space_avail_cond);
551 pthread_mutex_unlock(&q->lock);
555 struct compressor_thread_params {
556 struct shared_queue *res_to_compress_queue;
557 struct shared_queue *compressed_res_queue;
558 compress_func_t compress;
561 #define MAX_CHUNKS_PER_MSG 2
564 struct wim_lookup_table_entry *lte;
565 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
566 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
567 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
568 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
569 size_t total_out_bytes;
571 struct list_head list;
577 compress_chunks(struct message *msg, compress_func_t compress)
579 msg->total_out_bytes = 0;
580 for (unsigned i = 0; i < msg->num_chunks; i++) {
581 unsigned len = compress(msg->uncompressed_chunks[i],
582 msg->uncompressed_chunk_sizes[i],
583 msg->compressed_chunks[i]);
587 /* To be written compressed */
588 out_chunk = msg->compressed_chunks[i];
591 /* To be written uncompressed */
592 out_chunk = msg->uncompressed_chunks[i];
593 out_len = msg->uncompressed_chunk_sizes[i];
595 msg->out_chunks[i].iov_base = out_chunk;
596 msg->out_chunks[i].iov_len = out_len;
597 msg->total_out_bytes += out_len;
601 /* Compressor thread routine. This is a lot simpler than the main thread
602 * routine: just repeatedly get a group of chunks from the
603 * res_to_compress_queue, compress them, and put them in the
604 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
607 compressor_thread_proc(void *arg)
609 struct compressor_thread_params *params = arg;
610 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
611 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
612 compress_func_t compress = params->compress;
615 DEBUG("Compressor thread ready");
616 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
617 compress_chunks(msg, compress);
618 shared_queue_put(compressed_res_queue, msg);
620 DEBUG("Compressor thread terminating");
623 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
626 do_write_streams_progress(union wimlib_progress_info *progress,
627 wimlib_progress_func_t progress_func,
629 bool stream_discarded)
631 if (stream_discarded) {
632 progress->write_streams.total_bytes -= size_added;
633 if (progress->write_streams._private != ~(uint64_t)0 &&
634 progress->write_streams._private > progress->write_streams.total_bytes)
636 progress->write_streams._private = progress->write_streams.total_bytes;
639 progress->write_streams.completed_bytes += size_added;
641 progress->write_streams.completed_streams++;
643 progress->write_streams.completed_bytes >= progress->write_streams._private)
645 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
647 if (progress->write_streams._private == progress->write_streams.total_bytes) {
648 progress->write_streams._private = ~(uint64_t)0;
650 progress->write_streams._private =
651 min(progress->write_streams.total_bytes,
652 progress->write_streams.completed_bytes +
653 progress->write_streams.total_bytes / 100);
658 struct serial_write_stream_ctx {
661 int write_resource_flags;
665 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
667 struct serial_write_stream_ctx *ctx = _ctx;
668 return write_wim_resource(lte, ctx->out_fd,
669 ctx->out_ctype, <e->output_resource_entry,
670 ctx->write_resource_flags);
673 /* Write a list of streams, taking into account that some streams may be
674 * duplicates that are checksummed and discarded on the fly, and also delegating
675 * the actual writing of a stream to a function @write_stream_cb, which is
676 * passed the context @write_stream_ctx. */
678 do_write_stream_list(struct list_head *stream_list,
679 struct wim_lookup_table *lookup_table,
680 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
681 void *write_stream_ctx,
682 wimlib_progress_func_t progress_func,
683 union wimlib_progress_info *progress)
686 struct wim_lookup_table_entry *lte;
687 bool stream_discarded;
689 /* For each stream in @stream_list ... */
690 while (!list_empty(stream_list)) {
691 stream_discarded = false;
692 lte = container_of(stream_list->next,
693 struct wim_lookup_table_entry,
695 list_del(<e->write_streams_list);
696 if (lte->unhashed && !lte->unique_size) {
697 /* Unhashed stream that shares a size with some other
698 * stream in the WIM we are writing. The stream must be
699 * checksummed to know if we need to write it or not. */
700 struct wim_lookup_table_entry *tmp;
701 u32 orig_refcnt = lte->out_refcnt;
703 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
708 /* We found a duplicate stream. */
709 if (orig_refcnt != tmp->out_refcnt) {
710 /* We have already written, or are going
711 * to write, the duplicate stream. So
712 * just skip to the next stream. */
713 DEBUG("Discarding duplicate stream of length %"PRIu64,
714 wim_resource_size(lte));
715 lte->no_progress = 0;
716 stream_discarded = true;
717 goto skip_to_progress;
722 /* Here, @lte is either a hashed stream or an unhashed stream
723 * with a unique size. In either case we know that the stream
724 * has to be written. In either case the SHA1 message digest
725 * will be calculated over the stream while writing it; however,
726 * in the former case this is done merely to check the data,
727 * while in the latter case this is done because we do not have
728 * the SHA1 message digest yet. */
729 wimlib_assert(lte->out_refcnt != 0);
731 lte->no_progress = 0;
732 ret = (*write_stream_cb)(lte, write_stream_ctx);
735 /* In parallel mode, some streams are deferred for later,
736 * serialized processing; ignore them here. */
740 list_del(<e->unhashed_list);
741 lookup_table_insert(lookup_table, lte);
745 if (!lte->no_progress) {
746 do_write_streams_progress(progress,
748 wim_resource_size(lte),
756 do_write_stream_list_serial(struct list_head *stream_list,
757 struct wim_lookup_table *lookup_table,
760 int write_resource_flags,
761 wimlib_progress_func_t progress_func,
762 union wimlib_progress_info *progress)
764 struct serial_write_stream_ctx ctx = {
766 .out_ctype = out_ctype,
767 .write_resource_flags = write_resource_flags,
769 return do_write_stream_list(stream_list,
778 write_flags_to_resource_flags(int write_flags)
780 int resource_flags = 0;
782 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
783 resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
784 return resource_flags;
788 write_stream_list_serial(struct list_head *stream_list,
789 struct wim_lookup_table *lookup_table,
792 int write_resource_flags,
793 wimlib_progress_func_t progress_func,
794 union wimlib_progress_info *progress)
796 DEBUG("Writing stream list (serial version)");
797 progress->write_streams.num_threads = 1;
799 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
800 return do_write_stream_list_serial(stream_list,
804 write_resource_flags,
809 #ifdef ENABLE_MULTITHREADED_COMPRESSION
811 write_wim_chunks(struct message *msg, int out_fd,
812 struct chunk_table *chunk_tab)
814 for (unsigned i = 0; i < msg->num_chunks; i++)
815 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
816 if (full_writev(out_fd, msg->out_chunks,
817 msg->num_chunks) != msg->total_out_bytes)
819 ERROR_WITH_ERRNO("Failed to write WIM chunks");
820 return WIMLIB_ERR_WRITE;
825 struct main_writer_thread_ctx {
826 struct list_head *stream_list;
827 struct wim_lookup_table *lookup_table;
830 int write_resource_flags;
831 struct shared_queue *res_to_compress_queue;
832 struct shared_queue *compressed_res_queue;
834 wimlib_progress_func_t progress_func;
835 union wimlib_progress_info *progress;
837 struct list_head available_msgs;
838 struct list_head outstanding_streams;
839 struct list_head serial_streams;
840 size_t num_outstanding_messages;
842 SHA_CTX next_sha_ctx;
845 struct wim_lookup_table_entry *next_lte;
847 struct message *msgs;
848 struct message *next_msg;
849 struct chunk_table *cur_chunk_tab;
853 init_message(struct message *msg)
855 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
856 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
857 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
858 if (msg->compressed_chunks[i] == NULL ||
859 msg->uncompressed_chunks[i] == NULL)
860 return WIMLIB_ERR_NOMEM;
866 destroy_message(struct message *msg)
868 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
869 FREE(msg->compressed_chunks[i]);
870 FREE(msg->uncompressed_chunks[i]);
875 free_messages(struct message *msgs, size_t num_messages)
878 for (size_t i = 0; i < num_messages; i++)
879 destroy_message(&msgs[i]);
884 static struct message *
885 allocate_messages(size_t num_messages)
887 struct message *msgs;
889 msgs = CALLOC(num_messages, sizeof(struct message));
892 for (size_t i = 0; i < num_messages; i++) {
893 if (init_message(&msgs[i])) {
894 free_messages(msgs, num_messages);
902 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
904 while (ctx->num_outstanding_messages--)
905 shared_queue_get(ctx->compressed_res_queue);
906 free_messages(ctx->msgs, ctx->num_messages);
907 FREE(ctx->cur_chunk_tab);
911 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
913 /* Pre-allocate all the buffers that will be needed to do the chunk
915 ctx->msgs = allocate_messages(ctx->num_messages);
917 return WIMLIB_ERR_NOMEM;
919 /* Initially, all the messages are available to use. */
920 INIT_LIST_HEAD(&ctx->available_msgs);
921 for (size_t i = 0; i < ctx->num_messages; i++)
922 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
924 /* outstanding_streams is the list of streams that currently have had
925 * chunks sent off for compression.
927 * The first stream in outstanding_streams is the stream that is
928 * currently being written.
930 * The last stream in outstanding_streams is the stream that is
931 * currently being read and having chunks fed to the compressor threads.
933 INIT_LIST_HEAD(&ctx->outstanding_streams);
934 ctx->num_outstanding_messages = 0;
936 ctx->next_msg = NULL;
938 /* Resources that don't need any chunks compressed are added to this
939 * list and written directly by the main thread. */
940 INIT_LIST_HEAD(&ctx->serial_streams);
942 ctx->cur_chunk_tab = NULL;
948 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
951 struct wim_lookup_table_entry *cur_lte;
954 wimlib_assert(!list_empty(&ctx->outstanding_streams));
955 wimlib_assert(ctx->num_outstanding_messages != 0);
957 cur_lte = container_of(ctx->outstanding_streams.next,
958 struct wim_lookup_table_entry,
959 being_compressed_list);
961 /* Get the next message from the queue and process it.
962 * The message will contain 1 or more data chunks that have been
964 msg = shared_queue_get(ctx->compressed_res_queue);
965 msg->complete = true;
966 --ctx->num_outstanding_messages;
968 /* Is this the next chunk in the current resource? If it's not
969 * (i.e., an earlier chunk in a same or different resource
970 * hasn't been compressed yet), do nothing, and keep this
971 * message around until all earlier chunks are received.
973 * Otherwise, write all the chunks we can. */
974 while (cur_lte != NULL &&
975 !list_empty(&cur_lte->msg_list)
976 && (msg = container_of(cur_lte->msg_list.next,
980 list_move(&msg->list, &ctx->available_msgs);
981 if (msg->begin_chunk == 0) {
982 /* This is the first set of chunks. Leave space
983 * for the chunk table in the output file. */
984 off_t cur_offset = filedes_offset(ctx->out_fd);
985 if (cur_offset == -1)
986 return WIMLIB_ERR_WRITE;
987 ret = begin_wim_resource_chunk_tab(cur_lte,
990 &ctx->cur_chunk_tab);
995 /* Write the compressed chunks from the message. */
996 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab);
1000 /* Was this the last chunk of the stream? If so, finish
1002 if (list_empty(&cur_lte->msg_list) &&
1003 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1008 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1014 list_del(&cur_lte->being_compressed_list);
1016 /* Grab the offset of this stream in the output file
1017 * from the chunk table before we free it. */
1018 offset = ctx->cur_chunk_tab->file_offset;
1020 FREE(ctx->cur_chunk_tab);
1021 ctx->cur_chunk_tab = NULL;
1023 if (res_csize >= wim_resource_size(cur_lte)) {
1024 /* Oops! We compressed the resource to
1025 * larger than the original size. Write
1026 * the resource uncompressed instead. */
1027 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1028 "writing uncompressed instead",
1029 wim_resource_size(cur_lte), res_csize);
1030 ret = seek_and_truncate(ctx->out_fd, offset);
1033 ret = write_wim_resource(cur_lte,
1035 WIMLIB_COMPRESSION_TYPE_NONE,
1036 &cur_lte->output_resource_entry,
1037 ctx->write_resource_flags);
1041 cur_lte->output_resource_entry.size =
1044 cur_lte->output_resource_entry.original_size =
1045 cur_lte->resource_entry.original_size;
1047 cur_lte->output_resource_entry.offset =
1050 cur_lte->output_resource_entry.flags =
1051 cur_lte->resource_entry.flags |
1052 WIM_RESHDR_FLAG_COMPRESSED;
1055 do_write_streams_progress(ctx->progress,
1057 wim_resource_size(cur_lte),
1060 /* Since we just finished writing a stream, write any
1061 * streams that have been added to the serial_streams
1062 * list for direct writing by the main thread (e.g.
1063 * resources that don't need to be compressed because
1064 * the desired compression type is the same as the
1065 * previous compression type). */
1066 if (!list_empty(&ctx->serial_streams)) {
1067 ret = do_write_stream_list_serial(&ctx->serial_streams,
1071 ctx->write_resource_flags,
1078 /* Advance to the next stream to write. */
1079 if (list_empty(&ctx->outstanding_streams)) {
1082 cur_lte = container_of(ctx->outstanding_streams.next,
1083 struct wim_lookup_table_entry,
1084 being_compressed_list);
1091 /* Called when the main thread has read a new chunk of data. */
1093 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1095 struct main_writer_thread_ctx *ctx = _ctx;
1097 struct message *next_msg;
1098 u64 next_chunk_in_msg;
1100 /* Update SHA1 message digest for the stream currently being read by the
1102 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1104 /* We send chunks of data to the compressor chunks in batches which we
1105 * refer to as "messages". @next_msg is the message that is currently
1106 * being prepared to send off. If it is NULL, that indicates that we
1107 * need to start a new message. */
1108 next_msg = ctx->next_msg;
1110 /* We need to start a new message. First check to see if there
1111 * is a message available in the list of available messages. If
1112 * so, we can just take one. If not, all the messages (there is
1113 * a fixed number of them, proportional to the number of
1114 * threads) have been sent off to the compressor threads, so we
1115 * receive messages from the compressor threads containing
1116 * compressed chunks of data.
1118 * We may need to receive multiple messages before one is
1119 * actually available to use because messages received that are
1120 * *not* for the very next set of chunks to compress must be
1121 * buffered until it's time to write those chunks. */
1122 while (list_empty(&ctx->available_msgs)) {
1123 ret = receive_compressed_chunks(ctx);
1128 next_msg = container_of(ctx->available_msgs.next,
1129 struct message, list);
1130 list_del(&next_msg->list);
1131 next_msg->complete = false;
1132 next_msg->begin_chunk = ctx->next_chunk;
1133 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1134 ctx->next_num_chunks - ctx->next_chunk);
1135 ctx->next_msg = next_msg;
1138 /* Fill in the next chunk to compress */
1139 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1141 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1142 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1145 if (++next_chunk_in_msg == next_msg->num_chunks) {
1146 /* Send off an array of chunks to compress */
1147 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1148 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1149 ++ctx->num_outstanding_messages;
1150 ctx->next_msg = NULL;
1156 main_writer_thread_finish(void *_ctx)
1158 struct main_writer_thread_ctx *ctx = _ctx;
1160 while (ctx->num_outstanding_messages != 0) {
1161 ret = receive_compressed_chunks(ctx);
1165 wimlib_assert(list_empty(&ctx->outstanding_streams));
1166 return do_write_stream_list_serial(&ctx->serial_streams,
1170 ctx->write_resource_flags,
1176 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1177 struct main_writer_thread_ctx *ctx)
1181 /* Read the entire stream @lte, feeding its data chunks to the
1182 * compressor threads. Also SHA1-sum the stream; this is required in
1183 * the case that @lte is unhashed, and a nice additional verification
1184 * when @lte is already hashed. */
1185 sha1_init(&ctx->next_sha_ctx);
1186 ctx->next_chunk = 0;
1187 ctx->next_num_chunks = wim_resource_chunks(lte);
1188 ctx->next_lte = lte;
1189 INIT_LIST_HEAD(<e->msg_list);
1190 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1191 ret = read_resource_prefix(lte, wim_resource_size(lte),
1192 main_writer_thread_cb, ctx, 0);
1194 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1195 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1201 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1203 struct main_writer_thread_ctx *ctx = _ctx;
1206 if (wim_resource_size(lte) < 1000 ||
1207 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1208 (lte->resource_location == RESOURCE_IN_WIM &&
1209 !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1210 lte->wim->compression_type == ctx->out_ctype))
1212 /* Stream is too small or isn't being compressed. Process it by
1213 * the main thread when we have a chance. We can't necessarily
1214 * process it right here, as the main thread could be in the
1215 * middle of writing a different stream. */
1216 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1220 ret = submit_stream_for_compression(lte, ctx);
1222 lte->no_progress = 1;
1227 get_default_num_threads(void)
1230 return win32_get_number_of_processors();
1232 return sysconf(_SC_NPROCESSORS_ONLN);
1236 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1237 * parameter and will perform compression using that many threads. Falls
1238 * back to write_stream_list_serial() on certain errors, such as a failure to
1239 * create the number of threads requested.
1241 * High level description of the algorithm for writing compressed streams in
1242 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1243 * rather than on full files. The currently executing thread becomes the main
1244 * thread and is entirely in charge of reading the data to compress (which may
1245 * be in any location understood by the resource code--- such as in an external
1246 * file being captured, or in another WIM file from which an image is being
1247 * exported) and actually writing the compressed data to the output file.
1248 * Additional threads are "compressor threads" and all execute the
1249 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1250 * the main thread, compress them, and hand them back to the main thread.
1252 * Certain streams, such as streams that do not need to be compressed (e.g.
1253 * input compression type same as output compression type) or streams of very
1254 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1255 * handled entirely by the main thread at an appropriate time.
1257 * At any given point in time, multiple streams may be having chunks compressed
1258 * concurrently. The stream that the main thread is currently *reading* may be
1259 * later in the list that the stream that the main thread is currently
1263 write_stream_list_parallel(struct list_head *stream_list,
1264 struct wim_lookup_table *lookup_table,
1267 int write_resource_flags,
1268 wimlib_progress_func_t progress_func,
1269 union wimlib_progress_info *progress,
1270 unsigned num_threads)
1273 struct shared_queue res_to_compress_queue;
1274 struct shared_queue compressed_res_queue;
1275 pthread_t *compressor_threads = NULL;
1277 if (num_threads == 0) {
1278 long nthreads = get_default_num_threads();
1279 if (nthreads < 1 || nthreads > UINT_MAX) {
1280 WARNING("Could not determine number of processors! Assuming 1");
1282 } else if (nthreads == 1) {
1283 goto out_serial_quiet;
1285 num_threads = nthreads;
1289 DEBUG("Writing stream list (parallel version, num_threads=%u)",
1292 progress->write_streams.num_threads = num_threads;
1294 static const size_t MESSAGES_PER_THREAD = 2;
1295 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1297 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1299 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1303 ret = shared_queue_init(&compressed_res_queue, queue_size);
1305 goto out_destroy_res_to_compress_queue;
1307 struct compressor_thread_params params;
1308 params.res_to_compress_queue = &res_to_compress_queue;
1309 params.compressed_res_queue = &compressed_res_queue;
1310 params.compress = get_compress_func(out_ctype);
1312 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1313 if (!compressor_threads) {
1314 ret = WIMLIB_ERR_NOMEM;
1315 goto out_destroy_compressed_res_queue;
1318 for (unsigned i = 0; i < num_threads; i++) {
1319 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1320 ret = pthread_create(&compressor_threads[i], NULL,
1321 compressor_thread_proc, ¶ms);
1324 ERROR_WITH_ERRNO("Failed to create compressor "
1326 i + 1, num_threads);
1333 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1335 struct main_writer_thread_ctx ctx;
1336 ctx.stream_list = stream_list;
1337 ctx.lookup_table = lookup_table;
1338 ctx.out_fd = out_fd;
1339 ctx.out_ctype = out_ctype;
1340 ctx.res_to_compress_queue = &res_to_compress_queue;
1341 ctx.compressed_res_queue = &compressed_res_queue;
1342 ctx.num_messages = queue_size;
1343 ctx.write_resource_flags = write_resource_flags;
1344 ctx.progress_func = progress_func;
1345 ctx.progress = progress;
1346 ret = main_writer_thread_init_ctx(&ctx);
1349 ret = do_write_stream_list(stream_list, lookup_table,
1350 main_thread_process_next_stream,
1351 &ctx, progress_func, progress);
1353 goto out_destroy_ctx;
1355 /* The main thread has finished reading all streams that are going to be
1356 * compressed in parallel, and it now needs to wait for all remaining
1357 * chunks to be compressed so that the remaining streams can actually be
1358 * written to the output file. Furthermore, any remaining streams that
1359 * had processing deferred to the main thread need to be handled. These
1360 * tasks are done by the main_writer_thread_finish() function. */
1361 ret = main_writer_thread_finish(&ctx);
1363 main_writer_thread_destroy_ctx(&ctx);
1365 for (unsigned i = 0; i < num_threads; i++)
1366 shared_queue_put(&res_to_compress_queue, NULL);
1368 for (unsigned i = 0; i < num_threads; i++) {
1369 if (pthread_join(compressor_threads[i], NULL)) {
1370 WARNING_WITH_ERRNO("Failed to join compressor "
1372 i + 1, num_threads);
1375 FREE(compressor_threads);
1376 out_destroy_compressed_res_queue:
1377 shared_queue_destroy(&compressed_res_queue);
1378 out_destroy_res_to_compress_queue:
1379 shared_queue_destroy(&res_to_compress_queue);
1380 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1383 WARNING("Falling back to single-threaded compression");
1385 return write_stream_list_serial(stream_list,
1389 write_resource_flags,
1397 * Write a list of streams to a WIM (@out_fd) using the compression type
1398 * @out_ctype and up to @num_threads compressor threads.
1401 write_stream_list(struct list_head *stream_list,
1402 struct wim_lookup_table *lookup_table,
1403 int out_fd, int out_ctype, int write_flags,
1404 unsigned num_threads, wimlib_progress_func_t progress_func)
1406 struct wim_lookup_table_entry *lte;
1407 size_t num_streams = 0;
1408 u64 total_bytes = 0;
1409 u64 total_compression_bytes = 0;
1410 union wimlib_progress_info progress;
1412 int write_resource_flags;
1414 if (list_empty(stream_list))
1417 write_resource_flags = write_flags_to_resource_flags(write_flags);
1419 /* Calculate the total size of the streams to be written. Note: this
1420 * will be the uncompressed size, as we may not know the compressed size
1421 * yet, and also this will assume that every unhashed stream will be
1422 * written (which will not necessarily be the case). */
1423 list_for_each_entry(lte, stream_list, write_streams_list) {
1425 total_bytes += wim_resource_size(lte);
1426 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1427 && (wim_resource_compression_type(lte) != out_ctype ||
1428 (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1430 total_compression_bytes += wim_resource_size(lte);
1433 progress.write_streams.total_bytes = total_bytes;
1434 progress.write_streams.total_streams = num_streams;
1435 progress.write_streams.completed_bytes = 0;
1436 progress.write_streams.completed_streams = 0;
1437 progress.write_streams.num_threads = num_threads;
1438 progress.write_streams.compression_type = out_ctype;
1439 progress.write_streams._private = 0;
1441 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1442 if (total_compression_bytes >= 2000000 && num_threads != 1)
1443 ret = write_stream_list_parallel(stream_list,
1447 write_resource_flags,
1453 ret = write_stream_list_serial(stream_list,
1457 write_resource_flags,
1463 struct stream_size_table {
1464 struct hlist_head *array;
1470 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1472 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1474 return WIMLIB_ERR_NOMEM;
1475 tab->num_entries = 0;
1476 tab->capacity = capacity;
1481 destroy_stream_size_table(struct stream_size_table *tab)
1487 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1489 struct stream_size_table *tab = _tab;
1491 struct wim_lookup_table_entry *same_size_lte;
1492 struct hlist_node *tmp;
1494 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1495 lte->unique_size = 1;
1496 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1497 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1498 lte->unique_size = 0;
1499 same_size_lte->unique_size = 0;
1504 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1510 struct lte_overwrite_prepare_args {
1513 struct list_head stream_list;
1514 struct stream_size_table stream_size_tab;
1517 /* First phase of preparing streams for an in-place overwrite. This is called
1518 * on all streams, both hashed and unhashed, except the metadata resources. */
1520 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1522 struct lte_overwrite_prepare_args *args = _args;
1524 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1525 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1526 list_add_tail(<e->write_streams_list, &args->stream_list);
1527 lte->out_refcnt = lte->refcnt;
1528 stream_size_table_insert(lte, &args->stream_size_tab);
1532 /* Second phase of preparing streams for an in-place overwrite. This is called
1533 * on existing metadata resources and hashed streams, but not unhashed streams.
1535 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1536 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1537 * the latter uses lte->hash_list_2, while the former expects to set
1538 * lte->output_resource_entry. */
1540 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1542 struct lte_overwrite_prepare_args *args = _args;
1544 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1545 /* We can't do an in place overwrite on the WIM if there are
1546 * streams after the XML data. */
1547 if (lte->resource_entry.offset +
1548 lte->resource_entry.size > args->end_offset)
1550 if (wimlib_print_errors) {
1551 ERROR("The following resource is after the XML data:");
1552 print_lookup_table_entry(lte, stderr);
1554 return WIMLIB_ERR_RESOURCE_ORDER;
1556 copy_resource_entry(<e->output_resource_entry,
1557 <e->resource_entry);
1562 /* Given a WIM that we are going to overwrite in place with zero or more
1563 * additional streams added, construct a list the list of new unique streams
1564 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1565 * streams that need to be added but may be identical to other hashed or
1566 * unhashed streams. These unhashed streams are checksummed while the streams
1567 * are being written. To aid this process, the member @unique_size is set to 1
1568 * on streams that have a unique size and therefore must be written.
1570 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1571 * indicate the number of times the stream is referenced in only the streams
1572 * that are being written; this may still be adjusted later when unhashed
1573 * streams are being resolved.
1576 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1577 struct list_head *stream_list)
1580 struct lte_overwrite_prepare_args args;
1584 args.end_offset = end_offset;
1585 ret = init_stream_size_table(&args.stream_size_tab,
1586 wim->lookup_table->capacity);
1590 INIT_LIST_HEAD(&args.stream_list);
1591 for (i = 0; i < wim->hdr.image_count; i++) {
1592 struct wim_image_metadata *imd;
1593 struct wim_lookup_table_entry *lte;
1595 imd = wim->image_metadata[i];
1596 image_for_each_unhashed_stream(lte, imd)
1597 lte_overwrite_prepare(lte, &args);
1599 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1600 list_transfer(&args.stream_list, stream_list);
1602 for (i = 0; i < wim->hdr.image_count; i++) {
1603 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1606 goto out_destroy_stream_size_table;
1608 ret = for_lookup_table_entry(wim->lookup_table,
1609 lte_overwrite_prepare_2, &args);
1610 out_destroy_stream_size_table:
1611 destroy_stream_size_table(&args.stream_size_tab);
1616 struct find_streams_ctx {
1617 struct list_head stream_list;
1618 struct stream_size_table stream_size_tab;
1622 inode_find_streams_to_write(struct wim_inode *inode,
1623 struct wim_lookup_table *table,
1624 struct list_head *stream_list,
1625 struct stream_size_table *tab)
1627 struct wim_lookup_table_entry *lte;
1628 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1629 lte = inode_stream_lte(inode, i, table);
1631 if (lte->out_refcnt == 0) {
1633 stream_size_table_insert(lte, tab);
1634 list_add_tail(<e->write_streams_list, stream_list);
1636 lte->out_refcnt += inode->i_nlink;
1642 image_find_streams_to_write(WIMStruct *w)
1644 struct find_streams_ctx *ctx;
1645 struct wim_image_metadata *imd;
1646 struct wim_inode *inode;
1647 struct wim_lookup_table_entry *lte;
1650 imd = wim_get_current_image_metadata(w);
1652 image_for_each_unhashed_stream(lte, imd)
1653 lte->out_refcnt = 0;
1655 /* Go through this image's inodes to find any streams that have not been
1657 image_for_each_inode(inode, imd) {
1658 inode_find_streams_to_write(inode, w->lookup_table,
1660 &ctx->stream_size_tab);
1665 /* Given a WIM that from which one or all of the images is being written, build
1666 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1667 * written, plus any unhashed streams that need to be written but may be
1668 * identical to other hashed or unhashed streams being written. These unhashed
1669 * streams are checksummed while the streams are being written. To aid this
1670 * process, the member @unique_size is set to 1 on streams that have a unique
1671 * size and therefore must be written.
1673 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1674 * indicate the number of times the stream is referenced in only the streams
1675 * that are being written; this may still be adjusted later when unhashed
1676 * streams are being resolved.
1679 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1682 struct find_streams_ctx ctx;
1684 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1685 ret = init_stream_size_table(&ctx.stream_size_tab,
1686 wim->lookup_table->capacity);
1689 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1690 &ctx.stream_size_tab);
1691 INIT_LIST_HEAD(&ctx.stream_list);
1692 wim->private = &ctx;
1693 ret = for_image(wim, image, image_find_streams_to_write);
1694 destroy_stream_size_table(&ctx.stream_size_tab);
1696 list_transfer(&ctx.stream_list, stream_list);
1700 /* Writes the streams for the specified @image in @wim to @wim->out_fd.
1703 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1704 unsigned num_threads,
1705 wimlib_progress_func_t progress_func)
1708 struct list_head stream_list;
1710 ret = prepare_stream_list(wim, image, &stream_list);
1713 return write_stream_list(&stream_list,
1716 wim->compression_type,
1723 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1724 * table (optional), then overwrite the WIM header.
1726 * write_flags is a bitwise OR of the following:
1728 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1729 * Include an integrity table.
1731 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1732 * Don't write the lookup table.
1734 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1735 * When (if) writing the integrity table, re-use entries from the
1736 * existing integrity table, if possible.
1738 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1739 * After writing the XML data but before writing the integrity
1740 * table, write a temporary WIM header and flush the stream so that
1741 * the WIM is less likely to become corrupted upon abrupt program
1744 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1745 * fsync() the output file before closing it.
1749 finish_write(WIMStruct *w, int image, int write_flags,
1750 wimlib_progress_func_t progress_func)
1753 struct wim_header hdr;
1755 /* @hdr will be the header for the new WIM. First copy all the data
1756 * from the header in the WIMStruct; then set all the fields that may
1757 * have changed, including the resource entries, boot index, and image
1759 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1761 /* Set image count and boot index correctly for single image writes */
1762 if (image != WIMLIB_ALL_IMAGES) {
1763 hdr.image_count = 1;
1764 if (hdr.boot_idx == image)
1770 /* In the WIM header, there is room for the resource entry for a
1771 * metadata resource labeled as the "boot metadata". This entry should
1772 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1773 * it should be a copy of the resource entry for the image that is
1774 * marked as bootable. This is not well documented... */
1775 if (hdr.boot_idx == 0) {
1776 zero_resource_entry(&hdr.boot_metadata_res_entry);
1778 copy_resource_entry(&hdr.boot_metadata_res_entry,
1779 &w->image_metadata[ hdr.boot_idx- 1
1780 ]->metadata_lte->output_resource_entry);
1783 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1784 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1789 ret = write_xml_data(w->wim_info, image, w->out_fd,
1790 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1791 wim_info_get_total_bytes(w->wim_info) : 0,
1792 &hdr.xml_res_entry);
1796 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1797 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1798 struct wim_header checkpoint_hdr;
1799 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1800 zero_resource_entry(&checkpoint_hdr.integrity);
1801 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
1802 ret = write_header(&checkpoint_hdr, w->out_fd);
1807 off_t old_lookup_table_end;
1808 off_t new_lookup_table_end;
1809 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1810 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1811 w->hdr.lookup_table_res_entry.size;
1813 old_lookup_table_end = 0;
1815 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1816 hdr.lookup_table_res_entry.size;
1818 ret = write_integrity_table(w->out_fd,
1820 new_lookup_table_end,
1821 old_lookup_table_end,
1826 zero_resource_entry(&hdr.integrity);
1829 hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
1830 ret = write_header(&hdr, w->out_fd);
1834 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1835 if (fsync(w->out_fd)) {
1836 ERROR_WITH_ERRNO("Error syncing data to WIM file");
1837 ret = WIMLIB_ERR_WRITE;
1841 if (close(w->out_fd)) {
1842 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1844 ret = WIMLIB_ERR_WRITE;
1850 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1852 lock_wim(WIMStruct *w, int fd)
1855 if (fd != -1 && !w->wim_locked) {
1856 ret = flock(fd, LOCK_EX | LOCK_NB);
1858 if (errno == EWOULDBLOCK) {
1859 ERROR("`%"TS"' is already being modified or has been "
1860 "mounted read-write\n"
1861 " by another process!", w->filename);
1862 ret = WIMLIB_ERR_ALREADY_LOCKED;
1864 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1877 open_wim_writable(WIMStruct *w, const tchar *path, int open_flags)
1879 w->out_fd = topen(path, open_flags | O_BINARY, 0644);
1880 if (w->out_fd == -1) {
1881 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1882 return WIMLIB_ERR_OPEN;
1889 close_wim_writable(WIMStruct *w)
1891 if (w->out_fd != -1) {
1892 if (close(w->out_fd))
1893 WARNING_WITH_ERRNO("Failed to close output WIM");
1898 /* Open file stream and write dummy header for WIM. */
1900 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1903 int open_flags = O_TRUNC | O_CREAT;
1904 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1905 open_flags |= O_RDWR;
1907 open_flags |= O_WRONLY;
1908 ret = open_wim_writable(w, path, open_flags);
1911 /* Write dummy header. It will be overwritten later. */
1912 w->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
1913 ret = write_header(&w->hdr, w->out_fd);
1914 w->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
1917 if (lseek(w->out_fd, WIM_HEADER_DISK_SIZE, SEEK_SET) == -1) {
1918 ERROR_WITH_ERRNO("Failed to seek to end of WIM header");
1919 return WIMLIB_ERR_WRITE;
1924 /* Writes a stand-alone WIM to a file. */
1926 wimlib_write(WIMStruct *w, const tchar *path,
1927 int image, int write_flags, unsigned num_threads,
1928 wimlib_progress_func_t progress_func)
1933 return WIMLIB_ERR_INVALID_PARAM;
1935 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1937 if (image != WIMLIB_ALL_IMAGES &&
1938 (image < 1 || image > w->hdr.image_count))
1939 return WIMLIB_ERR_INVALID_IMAGE;
1941 if (w->hdr.total_parts != 1) {
1942 ERROR("Cannot call wimlib_write() on part of a split WIM");
1943 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1946 ret = begin_write(w, path, write_flags);
1950 ret = write_wim_streams(w, image, write_flags, num_threads,
1956 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1958 ret = for_image(w, image, write_metadata_resource);
1963 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1965 ret = finish_write(w, image, write_flags, progress_func);
1966 /* finish_write() closed the WIM for us */
1969 close_wim_writable(w);
1971 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1976 any_images_modified(WIMStruct *w)
1978 for (int i = 0; i < w->hdr.image_count; i++)
1979 if (w->image_metadata[i]->modified)
1985 * Overwrite a WIM, possibly appending streams to it.
1987 * A WIM looks like (or is supposed to look like) the following:
1989 * Header (212 bytes)
1990 * Streams and metadata resources (variable size)
1991 * Lookup table (variable size)
1992 * XML data (variable size)
1993 * Integrity table (optional) (variable size)
1995 * If we are not adding any streams or metadata resources, the lookup table is
1996 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1997 * header. This operation is potentially unsafe if the program is abruptly
1998 * terminated while the XML data or integrity table are being overwritten, but
1999 * before the new header has been written. To partially alleviate this problem,
2000 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2001 * finish_write() to cause a temporary WIM header to be written after the XML
2002 * data has been written. This may prevent the WIM from becoming corrupted if
2003 * the program is terminated while the integrity table is being calculated (but
2004 * no guarantees, due to write re-ordering...).
2006 * If we are adding new streams or images (metadata resources), the lookup table
2007 * needs to be changed, and those streams need to be written. In this case, we
2008 * try to perform a safe update of the WIM file by writing the streams *after*
2009 * the end of the previous WIM, then writing the new lookup table, XML data, and
2010 * (optionally) integrity table following the new streams. This will produce a
2011 * layout like the following:
2013 * Header (212 bytes)
2014 * (OLD) Streams and metadata resources (variable size)
2015 * (OLD) Lookup table (variable size)
2016 * (OLD) XML data (variable size)
2017 * (OLD) Integrity table (optional) (variable size)
2018 * (NEW) Streams and metadata resources (variable size)
2019 * (NEW) Lookup table (variable size)
2020 * (NEW) XML data (variable size)
2021 * (NEW) Integrity table (optional) (variable size)
2023 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2024 * the header is overwritten to point to the new lookup table, XML data, and
2025 * integrity table, to produce the following layout:
2027 * Header (212 bytes)
2028 * Streams and metadata resources (variable size)
2029 * Nothing (variable size)
2030 * More Streams and metadata resources (variable size)
2031 * Lookup table (variable size)
2032 * XML data (variable size)
2033 * Integrity table (optional) (variable size)
2035 * This method allows an image to be appended to a large WIM very quickly, and
2036 * is is crash-safe except in the case of write re-ordering, but the
2037 * disadvantage is that a small hole is left in the WIM where the old lookup
2038 * table, xml data, and integrity table were. (These usually only take up a
2039 * small amount of space compared to the streams, however.)
2042 overwrite_wim_inplace(WIMStruct *w, int write_flags,
2043 unsigned num_threads,
2044 wimlib_progress_func_t progress_func)
2047 struct list_head stream_list;
2049 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2052 DEBUG("Overwriting `%"TS"' in-place", w->filename);
2054 /* Make sure that the integrity table (if present) is after the XML
2055 * data, and that there are no stream resources, metadata resources, or
2056 * lookup tables after the XML data. Otherwise, these data would be
2058 old_xml_begin = w->hdr.xml_res_entry.offset;
2059 old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
2060 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
2061 w->hdr.lookup_table_res_entry.size;
2062 if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
2063 ERROR("Didn't expect the integrity table to be before the XML data");
2064 return WIMLIB_ERR_RESOURCE_ORDER;
2067 if (old_lookup_table_end > old_xml_begin) {
2068 ERROR("Didn't expect the lookup table to be after the XML data");
2069 return WIMLIB_ERR_RESOURCE_ORDER;
2072 /* Set @old_wim_end, which indicates the point beyond which we don't
2073 * allow any file and metadata resources to appear without returning
2074 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2075 * overwrite these resources). */
2076 if (!w->deletion_occurred && !any_images_modified(w)) {
2077 /* If no images have been modified and no images have been
2078 * deleted, a new lookup table does not need to be written. We
2079 * shall write the new XML data and optional integrity table
2080 * immediately after the lookup table. Note that this may
2081 * overwrite an existing integrity table. */
2082 DEBUG("Skipping writing lookup table "
2083 "(no images modified or deleted)");
2084 old_wim_end = old_lookup_table_end;
2085 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2086 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2087 } else if (w->hdr.integrity.offset) {
2088 /* Old WIM has an integrity table; begin writing new streams
2090 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2092 /* No existing integrity table; begin writing new streams after
2093 * the old XML data. */
2094 old_wim_end = old_xml_end;
2097 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2102 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2103 open_flags |= O_RDWR;
2105 open_flags |= O_WRONLY;
2106 ret = open_wim_writable(w, w->filename, open_flags);
2110 ret = lock_wim(w, w->out_fd);
2112 close_wim_writable(w);
2116 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2117 ret = write_header_flags(w->hdr.flags | WIM_HDR_FLAG_WRITE_IN_PROGRESS,
2120 ERROR_WITH_ERRNO("Error updating WIM header flags");
2121 close_wim_writable(w);
2122 goto out_unlock_wim;
2125 if (lseek(w->out_fd, old_wim_end, SEEK_SET) == -1) {
2126 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2127 close_wim_writable(w);
2128 ret = WIMLIB_ERR_WRITE;
2129 goto out_unlock_wim;
2132 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2134 ret = write_stream_list(&stream_list,
2137 w->compression_type,
2144 for (int i = 0; i < w->hdr.image_count; i++) {
2145 if (w->image_metadata[i]->modified) {
2146 select_wim_image(w, i + 1);
2147 ret = write_metadata_resource(w);
2152 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2153 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2156 close_wim_writable(w);
2157 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2158 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2159 w->filename, old_wim_end);
2160 /* Return value of truncate() is ignored because this is already
2162 (void)ttruncate(w->filename, old_wim_end);
2170 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2171 unsigned num_threads,
2172 wimlib_progress_func_t progress_func)
2174 size_t wim_name_len;
2177 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2179 /* Write the WIM to a temporary file in the same directory as the
2181 wim_name_len = tstrlen(w->filename);
2182 tchar tmpfile[wim_name_len + 10];
2183 tmemcpy(tmpfile, w->filename, wim_name_len);
2184 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2185 tmpfile[wim_name_len + 9] = T('\0');
2187 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2188 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2189 num_threads, progress_func);
2191 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2197 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2198 /* Rename the new file to the old file .*/
2199 if (trename(tmpfile, w->filename) != 0) {
2200 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2201 tmpfile, w->filename);
2202 ret = WIMLIB_ERR_RENAME;
2206 if (progress_func) {
2207 union wimlib_progress_info progress;
2208 progress.rename.from = tmpfile;
2209 progress.rename.to = w->filename;
2210 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2214 /* Remove temporary file. */
2215 if (tunlink(tmpfile) != 0)
2216 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2222 * Writes a WIM file to the original file that it was read from, overwriting it.
2225 wimlib_overwrite(WIMStruct *w, int write_flags,
2226 unsigned num_threads,
2227 wimlib_progress_func_t progress_func)
2231 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2234 return WIMLIB_ERR_NO_FILENAME;
2236 ret = can_modify_wim(w);
2240 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2241 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2244 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2246 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2247 WARNING("Falling back to re-building entire WIM");
2251 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,