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 #if defined(__WIN32__) && !defined(INVALID_HANDLE_VALUE)
69 # define INVALID_HANDLE_VALUE ((HANDLE)(-1))
72 /* Chunk table that's located at the beginning of each compressed resource in
73 * the WIM. (This is not the on-disk format; the on-disk format just has an
74 * array of offsets.) */
78 u64 original_resource_size;
79 u64 bytes_per_chunk_entry;
87 * Allocates and initializes a chunk table, and reserves space for it in the
91 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
94 struct chunk_table **chunk_tab_ret)
96 u64 size = wim_resource_size(lte);
97 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
98 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
99 struct chunk_table *chunk_tab = CALLOC(1, alloc_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 (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
116 chunk_tab->table_disk_size) {
117 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
120 return WIMLIB_ERR_WRITE;
122 *chunk_tab_ret = chunk_tab;
127 * compress_func_t- Pointer to a function to compresses a chunk
128 * of a WIM resource. This may be either
129 * wimlib_xpress_compress() (xpress-compress.c) or
130 * wimlib_lzx_compress() (lzx-compress.c).
132 * @chunk: Uncompressed data of the chunk.
133 * @chunk_size: Size of the uncompressed chunk, in bytes.
134 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
136 * Returns the size of the compressed data written to @out in bytes, or 0 if the
137 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
139 * As a special requirement, the compression code is optimized for the WIM
140 * format and therefore requires (@chunk_size <= 32768).
142 * As another special requirement, the compression code will read up to 8 bytes
143 * off the end of the @chunk array for performance reasons. The values of these
144 * bytes will not affect the output of the compression, but the calling code
145 * must make sure that the buffer holding the uncompressed chunk is actually at
146 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
147 * mapped memory that will not cause a memory access violation if accessed.
149 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
152 static compress_func_t
153 get_compress_func(int out_ctype)
155 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
156 return wimlib_lzx_compress;
158 return wimlib_xpress_compress;
162 * Writes a chunk of a WIM resource to an output file.
164 * @chunk: Uncompressed data of the chunk.
165 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
166 * @out_fp: FILE * to write the chunk to.
167 * @compress: Compression function to use (NULL if writing uncompressed
169 * @chunk_tab: Pointer to chunk table being created. It is updated with the
170 * offset of the chunk we write.
172 * Returns 0 on success; nonzero on failure.
175 write_wim_resource_chunk(const void *chunk, unsigned chunk_size,
176 FILE *out_fp, compress_func_t compress,
177 struct chunk_table *chunk_tab)
180 unsigned out_chunk_size;
182 u8 *compressed_chunk = alloca(chunk_size);
184 out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
185 if (out_chunk_size) {
186 /* Write compressed */
187 out_chunk = compressed_chunk;
189 /* Write uncompressed */
191 out_chunk_size = chunk_size;
193 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
194 chunk_tab->cur_offset += out_chunk_size;
196 /* Write uncompressed */
198 out_chunk_size = chunk_size;
200 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
201 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
202 return WIMLIB_ERR_WRITE;
208 * Finishes a WIM chunk table and writes it to the output file at the correct
211 * The final size of the full compressed resource is returned in the
212 * @compressed_size_p.
215 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
216 FILE *out_fp, u64 *compressed_size_p)
218 size_t bytes_written;
219 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
220 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
221 "WIM file", chunk_tab->file_offset);
222 return WIMLIB_ERR_WRITE;
225 if (chunk_tab->bytes_per_chunk_entry == 8) {
226 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
228 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
229 ((u32*)chunk_tab->offsets)[i] =
230 cpu_to_le32(chunk_tab->offsets[i]);
232 bytes_written = fwrite((u8*)chunk_tab->offsets +
233 chunk_tab->bytes_per_chunk_entry,
234 1, chunk_tab->table_disk_size, out_fp);
235 if (bytes_written != chunk_tab->table_disk_size) {
236 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
238 return WIMLIB_ERR_WRITE;
240 if (fseeko(out_fp, 0, SEEK_END) != 0) {
241 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
242 return WIMLIB_ERR_WRITE;
244 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
249 fflush_and_ftruncate(FILE *out_fp, off_t offset)
251 if (fseeko(out_fp, offset, SEEK_SET) ||
253 ftruncate(fileno(out_fp), offset))
255 ERROR_WITH_ERRNO("Failed to flush and/or truncate "
257 return WIMLIB_ERR_WRITE;
264 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
266 u8 md[SHA1_HASH_SIZE];
267 sha1_final(md, sha_ctx);
269 copy_hash(lte->hash, md);
270 } else if (!hashes_equal(md, lte->hash)) {
271 ERROR("WIM resource has incorrect hash!");
272 if (lte_filename_valid(lte)) {
273 ERROR("We were reading it from \"%"TS"\"; maybe "
274 "it changed while we were reading it.",
277 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
283 struct write_resource_ctx {
284 compress_func_t compress;
285 struct chunk_table *chunk_tab;
292 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
294 struct write_resource_ctx *ctx = _ctx;
297 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
300 return write_wim_resource_chunk(chunk, chunk_size,
301 ctx->out_fp, ctx->compress,
304 if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
305 ERROR_WITH_ERRNO("Error writing to output WIM");
306 return WIMLIB_ERR_WRITE;
314 * Write a resource to an output WIM.
316 * @lte: Lookup table entry for the resource, which could be in another WIM,
317 * in an external file, or in another location.
319 * @out_fp: FILE * opened to the output WIM.
321 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
322 * which compression algorithm to use.
324 * @out_res_entry: On success, this is filled in with the offset, flags,
325 * compressed size, and uncompressed size of the resource
328 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
329 * even if it could otherwise be copied directly from the input.
331 * Additional notes: The SHA1 message digest of the uncompressed data is
332 * calculated (except when doing a raw copy --- see below). If the @unhashed
333 * flag is set on the lookup table entry, this message digest is simply copied
334 * to it; otherwise, the message digest is compared with the existing one, and
335 * the function will fail if they do not match.
338 write_wim_resource(struct wim_lookup_table_entry *lte,
339 FILE *out_fp, int out_ctype,
340 struct resource_entry *out_res_entry,
343 struct write_resource_ctx write_ctx;
349 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
351 /* Get current position in output WIM */
352 offset = ftello(out_fp);
354 ERROR_WITH_ERRNO("Can't get position in output WIM");
355 return WIMLIB_ERR_WRITE;
358 /* If we are not forcing the data to be recompressed, and the input
359 * resource is located in a WIM with the same compression type as that
360 * desired other than no compression, we can simply copy the compressed
361 * data without recompressing it. This also means we must skip
362 * calculating the SHA1, as we never will see the uncompressed data. */
363 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
364 lte->resource_location == RESOURCE_IN_WIM &&
365 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
366 wimlib_get_compression_type(lte->wim) == out_ctype)
368 flags |= WIMLIB_RESOURCE_FLAG_RAW;
369 write_ctx.doing_sha = false;
370 read_size = lte->resource_entry.size;
372 write_ctx.doing_sha = true;
373 sha1_init(&write_ctx.sha_ctx);
374 read_size = lte->resource_entry.original_size;
377 /* Initialize the chunk table and set the compression function if
378 * compressing the resource. */
379 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
380 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
381 write_ctx.compress = NULL;
382 write_ctx.chunk_tab = NULL;
384 write_ctx.compress = get_compress_func(out_ctype);
385 ret = begin_wim_resource_chunk_tab(lte, out_fp,
387 &write_ctx.chunk_tab);
392 /* Write the entire resource by reading the entire resource and feeding
393 * the data through the write_resource_cb function. */
394 write_ctx.out_fp = out_fp;
396 ret = read_resource_prefix(lte, read_size,
397 write_resource_cb, &write_ctx, flags);
399 goto out_free_chunk_tab;
401 /* Verify SHA1 message digest of the resource, or set the hash for the
403 if (write_ctx.doing_sha) {
404 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
406 goto out_free_chunk_tab;
409 out_res_entry->flags = lte->resource_entry.flags;
410 out_res_entry->original_size = wim_resource_size(lte);
411 out_res_entry->offset = offset;
412 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
413 /* Doing a raw write: The new compressed size is the same as
414 * the compressed size in the other WIM. */
415 new_size = lte->resource_entry.size;
416 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
417 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
418 * is the original size. */
419 new_size = lte->resource_entry.original_size;
420 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
422 /* Using a different compression type: Call
423 * finish_wim_resource_chunk_tab() and it will provide the new
424 * compressed size. */
425 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
428 goto out_free_chunk_tab;
429 if (new_size >= wim_resource_size(lte)) {
430 /* Oops! We compressed the resource to larger than the original
431 * size. Write the resource uncompressed instead. */
432 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
433 "writing uncompressed instead",
434 wim_resource_size(lte), new_size);
435 ret = fflush_and_ftruncate(out_fp, offset);
437 goto out_free_chunk_tab;
438 write_ctx.compress = NULL;
439 write_ctx.doing_sha = false;
440 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
441 goto try_write_again;
443 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
445 out_res_entry->size = new_size;
448 FREE(write_ctx.chunk_tab);
452 #ifdef ENABLE_MULTITHREADED_COMPRESSION
454 /* Blocking shared queue (solves the producer-consumer problem) */
455 struct shared_queue {
459 unsigned filled_slots;
461 pthread_mutex_t lock;
462 pthread_cond_t msg_avail_cond;
463 pthread_cond_t space_avail_cond;
467 shared_queue_init(struct shared_queue *q, unsigned size)
469 wimlib_assert(size != 0);
470 q->array = CALLOC(sizeof(q->array[0]), size);
477 if (pthread_mutex_init(&q->lock, NULL)) {
478 ERROR_WITH_ERRNO("Failed to initialize mutex");
481 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
482 ERROR_WITH_ERRNO("Failed to initialize condition variable");
483 goto err_destroy_lock;
485 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
486 ERROR_WITH_ERRNO("Failed to initialize condition variable");
487 goto err_destroy_msg_avail_cond;
490 err_destroy_msg_avail_cond:
491 pthread_cond_destroy(&q->msg_avail_cond);
493 pthread_mutex_destroy(&q->lock);
495 return WIMLIB_ERR_NOMEM;
499 shared_queue_destroy(struct shared_queue *q)
502 pthread_mutex_destroy(&q->lock);
503 pthread_cond_destroy(&q->msg_avail_cond);
504 pthread_cond_destroy(&q->space_avail_cond);
508 shared_queue_put(struct shared_queue *q, void *obj)
510 pthread_mutex_lock(&q->lock);
511 while (q->filled_slots == q->size)
512 pthread_cond_wait(&q->space_avail_cond, &q->lock);
514 q->back = (q->back + 1) % q->size;
515 q->array[q->back] = obj;
518 pthread_cond_broadcast(&q->msg_avail_cond);
519 pthread_mutex_unlock(&q->lock);
523 shared_queue_get(struct shared_queue *q)
527 pthread_mutex_lock(&q->lock);
528 while (q->filled_slots == 0)
529 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
531 obj = q->array[q->front];
532 q->array[q->front] = NULL;
533 q->front = (q->front + 1) % q->size;
536 pthread_cond_broadcast(&q->space_avail_cond);
537 pthread_mutex_unlock(&q->lock);
541 struct compressor_thread_params {
542 struct shared_queue *res_to_compress_queue;
543 struct shared_queue *compressed_res_queue;
544 compress_func_t compress;
547 #define MAX_CHUNKS_PER_MSG 2
550 struct wim_lookup_table_entry *lte;
551 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
552 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
553 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
554 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
555 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
557 struct list_head list;
563 compress_chunks(struct message *msg, compress_func_t compress)
565 for (unsigned i = 0; i < msg->num_chunks; i++) {
566 unsigned len = compress(msg->uncompressed_chunks[i],
567 msg->uncompressed_chunk_sizes[i],
568 msg->compressed_chunks[i]);
570 /* To be written compressed */
571 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
572 msg->compressed_chunk_sizes[i] = len;
574 /* To be written uncompressed */
575 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
576 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
582 /* Compressor thread routine. This is a lot simpler than the main thread
583 * routine: just repeatedly get a group of chunks from the
584 * res_to_compress_queue, compress them, and put them in the
585 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
588 compressor_thread_proc(void *arg)
590 struct compressor_thread_params *params = arg;
591 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
592 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
593 compress_func_t compress = params->compress;
596 DEBUG("Compressor thread ready");
597 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
598 compress_chunks(msg, compress);
599 shared_queue_put(compressed_res_queue, msg);
601 DEBUG("Compressor thread terminating");
604 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
607 do_write_streams_progress(union wimlib_progress_info *progress,
608 wimlib_progress_func_t progress_func,
611 progress->write_streams.completed_bytes += size_added;
612 progress->write_streams.completed_streams++;
614 progress->write_streams.completed_bytes >= progress->write_streams._private)
616 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
618 if (progress->write_streams._private == progress->write_streams.total_bytes) {
619 progress->write_streams._private = ~0;
621 progress->write_streams._private =
622 min(progress->write_streams.total_bytes,
623 progress->write_streams.completed_bytes +
624 progress->write_streams.total_bytes / 100);
629 struct serial_write_stream_ctx {
632 int write_resource_flags;
636 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
638 struct serial_write_stream_ctx *ctx = _ctx;
639 return write_wim_resource(lte, ctx->out_fp,
640 ctx->out_ctype, <e->output_resource_entry,
641 ctx->write_resource_flags);
644 /* Write a list of streams, taking into account that some streams may be
645 * duplicates that are checksummed and discarded on the fly, and also delegating
646 * the actual writing of a stream to a function @write_stream_cb, which is
647 * passed the context @write_stream_ctx. */
649 do_write_stream_list(struct list_head *stream_list,
650 struct wim_lookup_table *lookup_table,
651 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
652 void *write_stream_ctx,
653 wimlib_progress_func_t progress_func,
654 union wimlib_progress_info *progress)
657 struct wim_lookup_table_entry *lte;
659 /* For each stream in @stream_list ... */
660 while (!list_empty(stream_list)) {
661 lte = container_of(stream_list->next,
662 struct wim_lookup_table_entry,
664 list_del(<e->write_streams_list);
665 if (lte->unhashed && !lte->unique_size) {
666 /* Unhashed stream that shares a size with some other
667 * stream in the WIM we are writing. The stream must be
668 * checksummed to know if we need to write it or not. */
669 struct wim_lookup_table_entry *tmp;
670 u32 orig_refcnt = lte->out_refcnt;
672 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
677 /* We found a duplicate stream. */
678 if (orig_refcnt != tmp->out_refcnt) {
679 /* We have already written, or are going
680 * to write, the duplicate stream. So
681 * just skip to the next stream. */
682 DEBUG("Discarding duplicate stream of length %"PRIu64,
683 wim_resource_size(lte));
684 goto skip_to_progress;
689 /* Here, @lte is either a hashed stream or an unhashed stream
690 * with a unique size. In either case we know that the stream
691 * has to be written. In either case the SHA1 message digest
692 * will be calculated over the stream while writing it; however,
693 * in the former case this is done merely to check the data,
694 * while in the latter case this is done because we do not have
695 * the SHA1 message digest yet. */
696 wimlib_assert(lte->out_refcnt != 0);
698 ret = (*write_stream_cb)(lte, write_stream_ctx);
701 /* In parallel mode, some streams are deferred for later,
702 * serialized processing; ignore them here. */
706 list_del(<e->unhashed_list);
707 lookup_table_insert(lookup_table, lte);
712 do_write_streams_progress(progress,
714 wim_resource_size(lte));
721 do_write_stream_list_serial(struct list_head *stream_list,
722 struct wim_lookup_table *lookup_table,
725 int write_resource_flags,
726 wimlib_progress_func_t progress_func,
727 union wimlib_progress_info *progress)
729 struct serial_write_stream_ctx ctx = {
731 .out_ctype = out_ctype,
732 .write_resource_flags = write_resource_flags,
734 return do_write_stream_list(stream_list,
743 write_flags_to_resource_flags(int write_flags)
745 return (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS) ?
746 WIMLIB_RESOURCE_FLAG_RECOMPRESS : 0;
750 write_stream_list_serial(struct list_head *stream_list,
751 struct wim_lookup_table *lookup_table,
754 int write_resource_flags,
755 wimlib_progress_func_t progress_func,
756 union wimlib_progress_info *progress)
758 DEBUG("Writing stream list (serial version)");
759 progress->write_streams.num_threads = 1;
761 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
762 return do_write_stream_list_serial(stream_list,
766 write_resource_flags,
771 #ifdef ENABLE_MULTITHREADED_COMPRESSION
773 write_wim_chunks(struct message *msg, FILE *out_fp,
774 struct chunk_table *chunk_tab)
776 for (unsigned i = 0; i < msg->num_chunks; i++) {
777 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
779 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
782 ERROR_WITH_ERRNO("Failed to write WIM chunk");
783 return WIMLIB_ERR_WRITE;
786 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
787 chunk_tab->cur_offset += chunk_csize;
792 struct main_writer_thread_ctx {
793 struct list_head *stream_list;
794 struct wim_lookup_table *lookup_table;
797 int write_resource_flags;
798 struct shared_queue *res_to_compress_queue;
799 struct shared_queue *compressed_res_queue;
801 wimlib_progress_func_t progress_func;
802 union wimlib_progress_info *progress;
804 struct list_head available_msgs;
805 struct list_head outstanding_streams;
806 struct list_head serial_streams;
807 size_t num_outstanding_messages;
809 SHA_CTX next_sha_ctx;
812 struct wim_lookup_table_entry *next_lte;
814 struct message *msgs;
815 struct message *next_msg;
816 struct chunk_table *cur_chunk_tab;
820 init_message(struct message *msg)
822 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
823 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
824 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
825 if (msg->compressed_chunks[i] == NULL ||
826 msg->uncompressed_chunks[i] == NULL)
827 return WIMLIB_ERR_NOMEM;
833 destroy_message(struct message *msg)
835 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
836 FREE(msg->compressed_chunks[i]);
837 FREE(msg->uncompressed_chunks[i]);
842 free_messages(struct message *msgs, size_t num_messages)
845 for (size_t i = 0; i < num_messages; i++)
846 destroy_message(&msgs[i]);
851 static struct message *
852 allocate_messages(size_t num_messages)
854 struct message *msgs;
856 msgs = CALLOC(num_messages, sizeof(struct message));
859 for (size_t i = 0; i < num_messages; i++) {
860 if (init_message(&msgs[i])) {
861 free_messages(msgs, num_messages);
869 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
871 while (ctx->num_outstanding_messages--)
872 shared_queue_get(ctx->compressed_res_queue);
873 free_messages(ctx->msgs, ctx->num_messages);
874 FREE(ctx->cur_chunk_tab);
878 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
880 /* Pre-allocate all the buffers that will be needed to do the chunk
882 ctx->msgs = allocate_messages(ctx->num_messages);
884 return WIMLIB_ERR_NOMEM;
886 /* Initially, all the messages are available to use. */
887 INIT_LIST_HEAD(&ctx->available_msgs);
888 for (size_t i = 0; i < ctx->num_messages; i++)
889 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
891 /* outstanding_streams is the list of streams that currently have had
892 * chunks sent off for compression.
894 * The first stream in outstanding_streams is the stream that is
895 * currently being written.
897 * The last stream in outstanding_streams is the stream that is
898 * currently being read and having chunks fed to the compressor threads.
900 INIT_LIST_HEAD(&ctx->outstanding_streams);
901 ctx->num_outstanding_messages = 0;
903 ctx->next_msg = NULL;
905 /* Resources that don't need any chunks compressed are added to this
906 * list and written directly by the main thread. */
907 INIT_LIST_HEAD(&ctx->serial_streams);
909 ctx->cur_chunk_tab = NULL;
915 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
918 struct wim_lookup_table_entry *cur_lte;
921 wimlib_assert(!list_empty(&ctx->outstanding_streams));
922 wimlib_assert(ctx->num_outstanding_messages != 0);
924 cur_lte = container_of(ctx->outstanding_streams.next,
925 struct wim_lookup_table_entry,
926 being_compressed_list);
928 /* Get the next message from the queue and process it.
929 * The message will contain 1 or more data chunks that have been
931 msg = shared_queue_get(ctx->compressed_res_queue);
932 msg->complete = true;
933 --ctx->num_outstanding_messages;
935 /* Is this the next chunk in the current resource? If it's not
936 * (i.e., an earlier chunk in a same or different resource
937 * hasn't been compressed yet), do nothing, and keep this
938 * message around until all earlier chunks are received.
940 * Otherwise, write all the chunks we can. */
941 while (cur_lte != NULL &&
942 !list_empty(&cur_lte->msg_list)
943 && (msg = container_of(cur_lte->msg_list.next,
947 list_move(&msg->list, &ctx->available_msgs);
948 if (msg->begin_chunk == 0) {
949 /* This is the first set of chunks. Leave space
950 * for the chunk table in the output file. */
951 off_t cur_offset = ftello(ctx->out_fp);
952 if (cur_offset == -1)
953 return WIMLIB_ERR_WRITE;
954 ret = begin_wim_resource_chunk_tab(cur_lte,
957 &ctx->cur_chunk_tab);
962 /* Write the compressed chunks from the message. */
963 ret = write_wim_chunks(msg, ctx->out_fp, ctx->cur_chunk_tab);
967 /* Was this the last chunk of the stream? If so, finish
969 if (list_empty(&cur_lte->msg_list) &&
970 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
975 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
981 list_del(&cur_lte->being_compressed_list);
983 /* Grab the offset of this stream in the output file
984 * from the chunk table before we free it. */
985 offset = ctx->cur_chunk_tab->file_offset;
987 FREE(ctx->cur_chunk_tab);
988 ctx->cur_chunk_tab = NULL;
990 if (res_csize >= wim_resource_size(cur_lte)) {
991 /* Oops! We compressed the resource to
992 * larger than the original size. Write
993 * the resource uncompressed instead. */
994 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
995 "writing uncompressed instead",
996 wim_resource_size(cur_lte), res_csize);
997 ret = fflush_and_ftruncate(ctx->out_fp, offset);
1000 ret = write_wim_resource(cur_lte,
1002 WIMLIB_COMPRESSION_TYPE_NONE,
1003 &cur_lte->output_resource_entry,
1004 ctx->write_resource_flags);
1008 cur_lte->output_resource_entry.size =
1011 cur_lte->output_resource_entry.original_size =
1012 cur_lte->resource_entry.original_size;
1014 cur_lte->output_resource_entry.offset =
1017 cur_lte->output_resource_entry.flags =
1018 cur_lte->resource_entry.flags |
1019 WIM_RESHDR_FLAG_COMPRESSED;
1022 do_write_streams_progress(ctx->progress,
1024 wim_resource_size(cur_lte));
1026 /* Since we just finished writing a stream, write any
1027 * streams that have been added to the serial_streams
1028 * list for direct writing by the main thread (e.g.
1029 * resources that don't need to be compressed because
1030 * the desired compression type is the same as the
1031 * previous compression type). */
1032 if (!list_empty(&ctx->serial_streams)) {
1033 ret = do_write_stream_list_serial(&ctx->serial_streams,
1037 ctx->write_resource_flags,
1044 /* Advance to the next stream to write. */
1045 if (list_empty(&ctx->outstanding_streams)) {
1048 cur_lte = container_of(ctx->outstanding_streams.next,
1049 struct wim_lookup_table_entry,
1050 being_compressed_list);
1057 /* Called when the main thread has read a new chunk of data. */
1059 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1061 struct main_writer_thread_ctx *ctx = _ctx;
1063 struct message *next_msg;
1064 u64 next_chunk_in_msg;
1066 /* Update SHA1 message digest for the stream currently being read by the
1068 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1070 /* We send chunks of data to the compressor chunks in batches which we
1071 * refer to as "messages". @next_msg is the message that is currently
1072 * being prepared to send off. If it is NULL, that indicates that we
1073 * need to start a new message. */
1074 next_msg = ctx->next_msg;
1076 /* We need to start a new message. First check to see if there
1077 * is a message available in the list of available messages. If
1078 * so, we can just take one. If not, all the messages (there is
1079 * a fixed number of them, proportional to the number of
1080 * threads) have been sent off to the compressor threads, so we
1081 * receive messages from the compressor threads containing
1082 * compressed chunks of data.
1084 * We may need to receive multiple messages before one is
1085 * actually available to use because messages received that are
1086 * *not* for the very next set of chunks to compress must be
1087 * buffered until it's time to write those chunks. */
1088 while (list_empty(&ctx->available_msgs)) {
1089 ret = receive_compressed_chunks(ctx);
1094 next_msg = container_of(ctx->available_msgs.next,
1095 struct message, list);
1096 list_del(&next_msg->list);
1097 next_msg->complete = false;
1098 next_msg->begin_chunk = ctx->next_chunk;
1099 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1100 ctx->next_num_chunks - ctx->next_chunk);
1101 ctx->next_msg = next_msg;
1104 /* Fill in the next chunk to compress */
1105 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1107 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1108 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1111 if (++next_chunk_in_msg == next_msg->num_chunks) {
1112 /* Send off an array of chunks to compress */
1113 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1114 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1115 ++ctx->num_outstanding_messages;
1116 ctx->next_msg = NULL;
1122 main_writer_thread_finish(void *_ctx)
1124 struct main_writer_thread_ctx *ctx = _ctx;
1126 while (ctx->num_outstanding_messages != 0) {
1127 ret = receive_compressed_chunks(ctx);
1131 wimlib_assert(list_empty(&ctx->outstanding_streams));
1132 return do_write_stream_list_serial(&ctx->serial_streams,
1136 ctx->write_resource_flags,
1142 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1143 struct main_writer_thread_ctx *ctx)
1147 /* Read the entire stream @lte, feeding its data chunks to the
1148 * compressor threads. Also SHA1-sum the stream; this is required in
1149 * the case that @lte is unhashed, and a nice additional verification
1150 * when @lte is already hashed. */
1151 sha1_init(&ctx->next_sha_ctx);
1152 ctx->next_chunk = 0;
1153 ctx->next_num_chunks = wim_resource_chunks(lte);
1154 ctx->next_lte = lte;
1155 INIT_LIST_HEAD(<e->msg_list);
1156 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1157 ret = read_resource_prefix(lte, wim_resource_size(lte),
1158 main_writer_thread_cb, ctx, 0);
1160 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1161 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1167 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1169 struct main_writer_thread_ctx *ctx = _ctx;
1172 if (wim_resource_size(lte) < 1000 ||
1173 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1174 (lte->resource_location == RESOURCE_IN_WIM &&
1175 !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1176 wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
1178 /* Stream is too small or isn't being compressed. Process it by
1179 * the main thread when we have a chance. We can't necessarily
1180 * process it right here, as the main thread could be in the
1181 * middle of writing a different stream. */
1182 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1186 ret = submit_stream_for_compression(lte, ctx);
1192 get_default_num_threads()
1195 return win32_get_number_of_processors();
1197 return sysconf(_SC_NPROCESSORS_ONLN);
1201 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1202 * parameter and will perform compression using that many threads. Falls
1203 * back to write_stream_list_serial() on certain errors, such as a failure to
1204 * create the number of threads requested.
1206 * High level description of the algorithm for writing compressed streams in
1207 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1208 * rather than on full files. The currently executing thread becomes the main
1209 * thread and is entirely in charge of reading the data to compress (which may
1210 * be in any location understood by the resource code--- such as in an external
1211 * file being captured, or in another WIM file from which an image is being
1212 * exported) and actually writing the compressed data to the output file.
1213 * Additional threads are "compressor threads" and all execute the
1214 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1215 * the main thread, compress them, and hand them back to the main thread.
1217 * Certain streams, such as streams that do not need to be compressed (e.g.
1218 * input compression type same as output compression type) or streams of very
1219 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1220 * handled entirely by the main thread at an appropriate time.
1222 * At any given point in time, multiple streams may be having chunks compressed
1223 * concurrently. The stream that the main thread is currently *reading* may be
1224 * later in the list that the stream that the main thread is currently
1228 write_stream_list_parallel(struct list_head *stream_list,
1229 struct wim_lookup_table *lookup_table,
1232 int write_resource_flags,
1233 wimlib_progress_func_t progress_func,
1234 union wimlib_progress_info *progress,
1235 unsigned num_threads)
1238 struct shared_queue res_to_compress_queue;
1239 struct shared_queue compressed_res_queue;
1240 pthread_t *compressor_threads = NULL;
1242 if (num_threads == 0) {
1243 long nthreads = get_default_num_threads();
1244 if (nthreads < 1 || nthreads > UINT_MAX) {
1245 WARNING("Could not determine number of processors! Assuming 1");
1247 } else if (nthreads == 1) {
1248 goto out_serial_quiet;
1250 num_threads = nthreads;
1254 DEBUG("Writing stream list (parallel version, num_threads=%u)",
1257 progress->write_streams.num_threads = num_threads;
1259 static const size_t MESSAGES_PER_THREAD = 2;
1260 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1262 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1264 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1268 ret = shared_queue_init(&compressed_res_queue, queue_size);
1270 goto out_destroy_res_to_compress_queue;
1272 struct compressor_thread_params params;
1273 params.res_to_compress_queue = &res_to_compress_queue;
1274 params.compressed_res_queue = &compressed_res_queue;
1275 params.compress = get_compress_func(out_ctype);
1277 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1278 if (!compressor_threads) {
1279 ret = WIMLIB_ERR_NOMEM;
1280 goto out_destroy_compressed_res_queue;
1283 for (unsigned i = 0; i < num_threads; i++) {
1284 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1285 ret = pthread_create(&compressor_threads[i], NULL,
1286 compressor_thread_proc, ¶ms);
1289 ERROR_WITH_ERRNO("Failed to create compressor "
1291 i + 1, num_threads);
1298 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1300 struct main_writer_thread_ctx ctx;
1301 ctx.stream_list = stream_list;
1302 ctx.lookup_table = lookup_table;
1303 ctx.out_fp = out_fp;
1304 ctx.out_ctype = out_ctype;
1305 ctx.res_to_compress_queue = &res_to_compress_queue;
1306 ctx.compressed_res_queue = &compressed_res_queue;
1307 ctx.num_messages = queue_size;
1308 ctx.write_resource_flags = write_resource_flags | WIMLIB_RESOURCE_FLAG_THREADSAFE_READ;
1309 ctx.progress_func = progress_func;
1310 ctx.progress = progress;
1311 ret = main_writer_thread_init_ctx(&ctx);
1314 ret = do_write_stream_list(stream_list, lookup_table,
1315 main_thread_process_next_stream,
1318 goto out_destroy_ctx;
1320 /* The main thread has finished reading all streams that are going to be
1321 * compressed in parallel, and it now needs to wait for all remaining
1322 * chunks to be compressed so that the remaining streams can actually be
1323 * written to the output file. Furthermore, any remaining streams that
1324 * had processing deferred to the main thread need to be handled. These
1325 * tasks are done by the main_writer_thread_finish() function. */
1326 ret = main_writer_thread_finish(&ctx);
1328 main_writer_thread_destroy_ctx(&ctx);
1330 for (unsigned i = 0; i < num_threads; i++)
1331 shared_queue_put(&res_to_compress_queue, NULL);
1333 for (unsigned i = 0; i < num_threads; i++) {
1334 if (pthread_join(compressor_threads[i], NULL)) {
1335 WARNING_WITH_ERRNO("Failed to join compressor "
1337 i + 1, num_threads);
1340 FREE(compressor_threads);
1341 out_destroy_compressed_res_queue:
1342 shared_queue_destroy(&compressed_res_queue);
1343 out_destroy_res_to_compress_queue:
1344 shared_queue_destroy(&res_to_compress_queue);
1345 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1348 WARNING("Falling back to single-threaded compression");
1350 return write_stream_list_serial(stream_list,
1354 write_resource_flags,
1362 * Write a list of streams to a WIM (@out_fp) using the compression type
1363 * @out_ctype and up to @num_threads compressor threads.
1366 write_stream_list(struct list_head *stream_list,
1367 struct wim_lookup_table *lookup_table,
1368 FILE *out_fp, int out_ctype, int write_flags,
1369 unsigned num_threads, wimlib_progress_func_t progress_func)
1371 struct wim_lookup_table_entry *lte;
1372 size_t num_streams = 0;
1373 u64 total_bytes = 0;
1374 u64 total_compression_bytes = 0;
1375 union wimlib_progress_info progress;
1377 int write_resource_flags;
1379 if (list_empty(stream_list))
1382 write_resource_flags = write_flags_to_resource_flags(write_flags);
1384 /* Calculate the total size of the streams to be written. Note: this
1385 * will be the uncompressed size, as we may not know the compressed size
1386 * yet, and also this will assume that every unhashed stream will be
1387 * written (which will not necessarily be the case). */
1388 list_for_each_entry(lte, stream_list, write_streams_list) {
1390 total_bytes += wim_resource_size(lte);
1391 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1392 && (wim_resource_compression_type(lte) != out_ctype ||
1393 (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1395 total_compression_bytes += wim_resource_size(lte);
1398 progress.write_streams.total_bytes = total_bytes;
1399 progress.write_streams.total_streams = num_streams;
1400 progress.write_streams.completed_bytes = 0;
1401 progress.write_streams.completed_streams = 0;
1402 progress.write_streams.num_threads = num_threads;
1403 progress.write_streams.compression_type = out_ctype;
1404 progress.write_streams._private = 0;
1406 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1407 if (total_compression_bytes >= 1000000 && num_threads != 1)
1408 ret = write_stream_list_parallel(stream_list,
1412 write_resource_flags,
1418 ret = write_stream_list_serial(stream_list,
1422 write_resource_flags,
1428 struct stream_size_table {
1429 struct hlist_head *array;
1435 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1437 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1439 return WIMLIB_ERR_NOMEM;
1440 tab->num_entries = 0;
1441 tab->capacity = capacity;
1446 destroy_stream_size_table(struct stream_size_table *tab)
1452 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1454 struct stream_size_table *tab = _tab;
1456 struct wim_lookup_table_entry *same_size_lte;
1457 struct hlist_node *tmp;
1459 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1460 lte->unique_size = 1;
1461 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1462 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1463 lte->unique_size = 0;
1464 same_size_lte->unique_size = 0;
1469 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1475 struct lte_overwrite_prepare_args {
1478 struct list_head stream_list;
1479 struct stream_size_table stream_size_tab;
1482 /* First phase of preparing streams for an in-place overwrite. This is called
1483 * on all streams, both hashed and unhashed, except the metadata resources. */
1485 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1487 struct lte_overwrite_prepare_args *args = _args;
1489 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1490 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1491 list_add_tail(<e->write_streams_list, &args->stream_list);
1492 lte->out_refcnt = lte->refcnt;
1493 stream_size_table_insert(lte, &args->stream_size_tab);
1497 /* Second phase of preparing streams for an in-place overwrite. This is called
1498 * on existing metadata resources and hashed streams, but not unhashed streams.
1500 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1501 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1502 * the latter uses lte->hash_list_2, while the former expects to set
1503 * lte->output_resource_entry. */
1505 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1507 struct lte_overwrite_prepare_args *args = _args;
1509 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1510 /* We can't do an in place overwrite on the WIM if there are
1511 * streams after the XML data. */
1512 if (lte->resource_entry.offset +
1513 lte->resource_entry.size > args->end_offset)
1515 #ifdef ENABLE_ERROR_MESSAGES
1516 ERROR("The following resource is after the XML data:");
1517 print_lookup_table_entry(lte, stderr);
1519 return WIMLIB_ERR_RESOURCE_ORDER;
1521 copy_resource_entry(<e->output_resource_entry,
1522 <e->resource_entry);
1527 /* Given a WIM that we are going to overwrite in place with zero or more
1528 * additional streams added, construct a list the list of new unique streams
1529 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1530 * streams that need to be added but may be identical to other hashed or
1531 * unhashed streams. These unhashed streams are checksummed while the streams
1532 * are being written. To aid this process, the member @unique_size is set to 1
1533 * on streams that have a unique size and therefore must be written.
1535 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1536 * indicate the number of times the stream is referenced in only the streams
1537 * that are being written; this may still be adjusted later when unhashed
1538 * streams are being resolved.
1541 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1542 struct list_head *stream_list)
1545 struct lte_overwrite_prepare_args args;
1549 args.end_offset = end_offset;
1550 ret = init_stream_size_table(&args.stream_size_tab,
1551 wim->lookup_table->capacity);
1555 INIT_LIST_HEAD(&args.stream_list);
1556 for (i = 0; i < wim->hdr.image_count; i++) {
1557 struct wim_image_metadata *imd;
1558 struct wim_lookup_table_entry *lte;
1560 imd = wim->image_metadata[i];
1561 image_for_each_unhashed_stream(lte, imd)
1562 lte_overwrite_prepare(lte, &args);
1564 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1565 list_transfer(&args.stream_list, stream_list);
1567 for (i = 0; i < wim->hdr.image_count; i++) {
1568 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1571 goto out_destroy_stream_size_table;
1573 ret = for_lookup_table_entry(wim->lookup_table,
1574 lte_overwrite_prepare_2, &args);
1575 out_destroy_stream_size_table:
1576 destroy_stream_size_table(&args.stream_size_tab);
1581 struct find_streams_ctx {
1582 struct list_head stream_list;
1583 struct stream_size_table stream_size_tab;
1587 inode_find_streams_to_write(struct wim_inode *inode,
1588 struct wim_lookup_table *table,
1589 struct list_head *stream_list,
1590 struct stream_size_table *tab)
1592 struct wim_lookup_table_entry *lte;
1593 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1594 lte = inode_stream_lte(inode, i, table);
1596 if (lte->out_refcnt == 0) {
1598 stream_size_table_insert(lte, tab);
1599 list_add_tail(<e->write_streams_list, stream_list);
1601 lte->out_refcnt += inode->i_nlink;
1607 image_find_streams_to_write(WIMStruct *w)
1609 struct find_streams_ctx *ctx;
1610 struct wim_image_metadata *imd;
1611 struct wim_inode *inode;
1612 struct wim_lookup_table_entry *lte;
1615 imd = wim_get_current_image_metadata(w);
1617 image_for_each_unhashed_stream(lte, imd)
1618 lte->out_refcnt = 0;
1620 /* Go through this image's inodes to find any streams that have not been
1622 image_for_each_inode(inode, imd) {
1623 inode_find_streams_to_write(inode, w->lookup_table,
1625 &ctx->stream_size_tab);
1630 /* Given a WIM that from which one or all of the images is being written, build
1631 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1632 * written, plus any unhashed streams that need to be written but may be
1633 * identical to other hashed or unhashed streams being written. These unhashed
1634 * streams are checksummed while the streams are being written. To aid this
1635 * process, the member @unique_size is set to 1 on streams that have a unique
1636 * size and therefore must be written.
1638 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1639 * indicate the number of times the stream is referenced in only the streams
1640 * that are being written; this may still be adjusted later when unhashed
1641 * streams are being resolved.
1644 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1647 struct find_streams_ctx ctx;
1649 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1650 ret = init_stream_size_table(&ctx.stream_size_tab,
1651 wim->lookup_table->capacity);
1654 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1655 &ctx.stream_size_tab);
1656 INIT_LIST_HEAD(&ctx.stream_list);
1657 wim->private = &ctx;
1658 ret = for_image(wim, image, image_find_streams_to_write);
1659 destroy_stream_size_table(&ctx.stream_size_tab);
1661 list_transfer(&ctx.stream_list, stream_list);
1665 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1668 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1669 unsigned num_threads,
1670 wimlib_progress_func_t progress_func)
1673 struct list_head stream_list;
1675 ret = prepare_stream_list(wim, image, &stream_list);
1678 return write_stream_list(&stream_list,
1681 wimlib_get_compression_type(wim),
1688 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1689 * table (optional), then overwrite the WIM header.
1691 * write_flags is a bitwise OR of the following:
1693 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1694 * Include an integrity table.
1696 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1697 * Show progress information when (if) writing the integrity table.
1699 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1700 * Don't write the lookup table.
1702 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1703 * When (if) writing the integrity table, re-use entries from the
1704 * existing integrity table, if possible.
1706 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1707 * After writing the XML data but before writing the integrity
1708 * table, write a temporary WIM header and flush the stream so that
1709 * the WIM is less likely to become corrupted upon abrupt program
1712 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1713 * fsync() the output file before closing it.
1717 finish_write(WIMStruct *w, int image, int write_flags,
1718 wimlib_progress_func_t progress_func)
1721 struct wim_header hdr;
1722 FILE *out = w->out_fp;
1724 /* @hdr will be the header for the new WIM. First copy all the data
1725 * from the header in the WIMStruct; then set all the fields that may
1726 * have changed, including the resource entries, boot index, and image
1728 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1730 /* Set image count and boot index correctly for single image writes */
1731 if (image != WIMLIB_ALL_IMAGES) {
1732 hdr.image_count = 1;
1733 if (hdr.boot_idx == image)
1739 /* In the WIM header, there is room for the resource entry for a
1740 * metadata resource labeled as the "boot metadata". This entry should
1741 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1742 * it should be a copy of the resource entry for the image that is
1743 * marked as bootable. This is not well documented... */
1744 if (hdr.boot_idx == 0) {
1745 zero_resource_entry(&hdr.boot_metadata_res_entry);
1747 copy_resource_entry(&hdr.boot_metadata_res_entry,
1748 &w->image_metadata[ hdr.boot_idx- 1
1749 ]->metadata_lte->output_resource_entry);
1752 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1753 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1758 ret = write_xml_data(w->wim_info, image, out,
1759 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1760 wim_info_get_total_bytes(w->wim_info) : 0,
1761 &hdr.xml_res_entry);
1765 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1766 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1767 struct wim_header checkpoint_hdr;
1768 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1769 zero_resource_entry(&checkpoint_hdr.integrity);
1770 if (fseeko(out, 0, SEEK_SET)) {
1771 ERROR_WITH_ERRNO("Failed to seek to beginning "
1772 "of WIM being written");
1773 ret = WIMLIB_ERR_WRITE;
1776 ret = write_header(&checkpoint_hdr, out);
1780 if (fflush(out) != 0) {
1781 ERROR_WITH_ERRNO("Can't write data to WIM");
1782 ret = WIMLIB_ERR_WRITE;
1786 if (fseeko(out, 0, SEEK_END) != 0) {
1787 ERROR_WITH_ERRNO("Failed to seek to end "
1788 "of WIM being written");
1789 ret = WIMLIB_ERR_WRITE;
1794 off_t old_lookup_table_end;
1795 off_t new_lookup_table_end;
1796 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1797 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1798 w->hdr.lookup_table_res_entry.size;
1800 old_lookup_table_end = 0;
1802 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1803 hdr.lookup_table_res_entry.size;
1805 ret = write_integrity_table(out,
1807 new_lookup_table_end,
1808 old_lookup_table_end,
1813 zero_resource_entry(&hdr.integrity);
1816 if (fseeko(out, 0, SEEK_SET) != 0) {
1817 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1819 ret = WIMLIB_ERR_WRITE;
1823 ret = write_header(&hdr, out);
1827 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1828 if (fflush(out) != 0
1829 || fsync(fileno(out)) != 0)
1831 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1832 ret = WIMLIB_ERR_WRITE;
1836 if (fclose(out) != 0) {
1837 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1839 ret = WIMLIB_ERR_WRITE;
1845 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1847 lock_wim(WIMStruct *w, FILE *fp)
1850 if (fp && !w->wim_locked) {
1851 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1853 if (errno == EWOULDBLOCK) {
1854 ERROR("`%"TS"' is already being modified or has been "
1855 "mounted read-write\n"
1856 " by another process!", w->filename);
1857 ret = WIMLIB_ERR_ALREADY_LOCKED;
1859 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1872 open_wim_writable(WIMStruct *w, const tchar *path,
1873 bool trunc, bool also_readable)
1884 wimlib_assert(w->out_fp == NULL);
1885 w->out_fp = tfopen(path, mode);
1889 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1890 return WIMLIB_ERR_OPEN;
1896 close_wim_writable(WIMStruct *w)
1899 if (fclose(w->out_fp) != 0) {
1900 WARNING_WITH_ERRNO("Failed to close output WIM");
1906 /* Open file stream and write dummy header for WIM. */
1908 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1911 ret = open_wim_writable(w, path, true,
1912 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1915 /* Write dummy header. It will be overwritten later. */
1916 return write_header(&w->hdr, w->out_fp);
1919 /* Writes a stand-alone WIM to a file. */
1921 wimlib_write(WIMStruct *w, const tchar *path,
1922 int image, int write_flags, unsigned num_threads,
1923 wimlib_progress_func_t progress_func)
1928 return WIMLIB_ERR_INVALID_PARAM;
1930 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1932 if (image != WIMLIB_ALL_IMAGES &&
1933 (image < 1 || image > w->hdr.image_count))
1934 return WIMLIB_ERR_INVALID_IMAGE;
1936 if (w->hdr.total_parts != 1) {
1937 ERROR("Cannot call wimlib_write() on part of a split WIM");
1938 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1941 ret = begin_write(w, path, write_flags);
1945 ret = write_wim_streams(w, image, write_flags, num_threads,
1951 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1953 ret = for_image(w, image, write_metadata_resource);
1958 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1960 ret = finish_write(w, image, write_flags, progress_func);
1961 /* finish_write() closed the WIM for us */
1964 close_wim_writable(w);
1966 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1971 any_images_modified(WIMStruct *w)
1973 for (int i = 0; i < w->hdr.image_count; i++)
1974 if (w->image_metadata[i]->modified)
1980 * Overwrite a WIM, possibly appending streams to it.
1982 * A WIM looks like (or is supposed to look like) the following:
1984 * Header (212 bytes)
1985 * Streams and metadata resources (variable size)
1986 * Lookup table (variable size)
1987 * XML data (variable size)
1988 * Integrity table (optional) (variable size)
1990 * If we are not adding any streams or metadata resources, the lookup table is
1991 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1992 * header. This operation is potentially unsafe if the program is abruptly
1993 * terminated while the XML data or integrity table are being overwritten, but
1994 * before the new header has been written. To partially alleviate this problem,
1995 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1996 * finish_write() to cause a temporary WIM header to be written after the XML
1997 * data has been written. This may prevent the WIM from becoming corrupted if
1998 * the program is terminated while the integrity table is being calculated (but
1999 * no guarantees, due to write re-ordering...).
2001 * If we are adding new streams or images (metadata resources), the lookup table
2002 * needs to be changed, and those streams need to be written. In this case, we
2003 * try to perform a safe update of the WIM file by writing the streams *after*
2004 * the end of the previous WIM, then writing the new lookup table, XML data, and
2005 * (optionally) integrity table following the new streams. This will produce a
2006 * layout like the following:
2008 * Header (212 bytes)
2009 * (OLD) Streams and metadata resources (variable size)
2010 * (OLD) Lookup table (variable size)
2011 * (OLD) XML data (variable size)
2012 * (OLD) Integrity table (optional) (variable size)
2013 * (NEW) Streams and metadata resources (variable size)
2014 * (NEW) Lookup table (variable size)
2015 * (NEW) XML data (variable size)
2016 * (NEW) Integrity table (optional) (variable size)
2018 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2019 * the header is overwritten to point to the new lookup table, XML data, and
2020 * integrity table, to produce the following layout:
2022 * Header (212 bytes)
2023 * Streams and metadata resources (variable size)
2024 * Nothing (variable size)
2025 * More Streams and metadata resources (variable size)
2026 * Lookup table (variable size)
2027 * XML data (variable size)
2028 * Integrity table (optional) (variable size)
2030 * This method allows an image to be appended to a large WIM very quickly, and
2031 * is is crash-safe except in the case of write re-ordering, but the
2032 * disadvantage is that a small hole is left in the WIM where the old lookup
2033 * table, xml data, and integrity table were. (These usually only take up a
2034 * small amount of space compared to the streams, however.)
2037 overwrite_wim_inplace(WIMStruct *w, int write_flags,
2038 unsigned num_threads,
2039 wimlib_progress_func_t progress_func)
2042 struct list_head stream_list;
2044 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2046 DEBUG("Overwriting `%"TS"' in-place", w->filename);
2048 /* Make sure that the integrity table (if present) is after the XML
2049 * data, and that there are no stream resources, metadata resources, or
2050 * lookup tables after the XML data. Otherwise, these data would be
2052 old_xml_begin = w->hdr.xml_res_entry.offset;
2053 old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
2054 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
2055 w->hdr.lookup_table_res_entry.size;
2056 if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
2057 ERROR("Didn't expect the integrity table to be before the XML data");
2058 return WIMLIB_ERR_RESOURCE_ORDER;
2061 if (old_lookup_table_end > old_xml_begin) {
2062 ERROR("Didn't expect the lookup table to be after the XML data");
2063 return WIMLIB_ERR_RESOURCE_ORDER;
2066 /* Set @old_wim_end, which indicates the point beyond which we don't
2067 * allow any file and metadata resources to appear without returning
2068 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2069 * overwrite these resources). */
2070 if (!w->deletion_occurred && !any_images_modified(w)) {
2071 /* If no images have been modified and no images have been
2072 * deleted, a new lookup table does not need to be written. We
2073 * shall write the new XML data and optional integrity table
2074 * immediately after the lookup table. Note that this may
2075 * overwrite an existing integrity table. */
2076 DEBUG("Skipping writing lookup table "
2077 "(no images modified or deleted)");
2078 old_wim_end = old_lookup_table_end;
2079 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2080 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2081 } else if (w->hdr.integrity.offset) {
2082 /* Old WIM has an integrity table; begin writing new streams
2084 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2086 /* No existing integrity table; begin writing new streams after
2087 * the old XML data. */
2088 old_wim_end = old_xml_end;
2091 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2095 ret = open_wim_writable(w, w->filename, false,
2096 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
2100 ret = lock_wim(w, w->out_fp);
2102 close_wim_writable(w);
2106 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
2107 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2108 close_wim_writable(w);
2110 return WIMLIB_ERR_WRITE;
2113 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2115 ret = write_stream_list(&stream_list,
2118 wimlib_get_compression_type(w),
2125 for (int i = 0; i < w->hdr.image_count; i++) {
2126 if (w->image_metadata[i]->modified) {
2127 select_wim_image(w, i + 1);
2128 ret = write_metadata_resource(w);
2133 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2134 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2137 close_wim_writable(w);
2138 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2139 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2140 w->filename, old_wim_end);
2141 /* Return value of truncate() is ignored because this is already
2143 (void)ttruncate(w->filename, old_wim_end);
2150 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2151 unsigned num_threads,
2152 wimlib_progress_func_t progress_func)
2154 size_t wim_name_len;
2157 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2159 /* Write the WIM to a temporary file in the same directory as the
2161 wim_name_len = tstrlen(w->filename);
2162 tchar tmpfile[wim_name_len + 10];
2163 tmemcpy(tmpfile, w->filename, wim_name_len);
2164 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2165 tmpfile[wim_name_len + 9] = T('\0');
2167 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2168 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2169 num_threads, progress_func);
2171 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2175 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2178 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2179 * specified to CreateFile(). The WIM was opened with fopen(), which
2180 * didn't provided this flag to CreateFile, so the handle must be closed
2181 * before executing the rename(). */
2182 if (w->fp != NULL) {
2188 /* Rename the new file to the old file .*/
2189 if (trename(tmpfile, w->filename) != 0) {
2190 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2191 tmpfile, w->filename);
2192 ret = WIMLIB_ERR_RENAME;
2196 if (progress_func) {
2197 union wimlib_progress_info progress;
2198 progress.rename.from = tmpfile;
2199 progress.rename.to = w->filename;
2200 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2203 /* Close the original WIM file that was opened for reading. */
2204 if (w->fp != NULL) {
2209 /* Re-open the WIM read-only. */
2210 w->fp = tfopen(w->filename, T("rb"));
2211 if (w->fp == NULL) {
2212 ret = WIMLIB_ERR_REOPEN;
2213 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2220 /* Remove temporary file. */
2221 if (tunlink(tmpfile) != 0)
2222 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2228 * Writes a WIM file to the original file that it was read from, overwriting it.
2231 wimlib_overwrite(WIMStruct *w, int write_flags,
2232 unsigned num_threads,
2233 wimlib_progress_func_t progress_func)
2235 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2238 return WIMLIB_ERR_NO_FILENAME;
2240 if (w->hdr.total_parts != 1) {
2241 ERROR("Cannot modify a split WIM");
2242 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2245 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2246 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2249 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2251 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2252 WARNING("Falling back to re-building entire WIM");
2256 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,