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 /* Chunk table that's located at the beginning of each compressed resource in
69 * the WIM. (This is not the on-disk format; the on-disk format just has an
70 * array of offsets.) */
74 u64 original_resource_size;
75 u64 bytes_per_chunk_entry;
83 * Allocates and initializes a chunk table, and reserves space for it in the
87 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
90 struct chunk_table **chunk_tab_ret)
92 u64 size = wim_resource_size(lte);
93 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
94 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
95 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
98 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
100 return WIMLIB_ERR_NOMEM;
102 chunk_tab->file_offset = file_offset;
103 chunk_tab->num_chunks = num_chunks;
104 chunk_tab->original_resource_size = size;
105 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
106 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
108 chunk_tab->cur_offset = 0;
109 chunk_tab->cur_offset_p = chunk_tab->offsets;
111 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
112 chunk_tab->table_disk_size) {
113 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
116 return WIMLIB_ERR_WRITE;
118 *chunk_tab_ret = chunk_tab;
123 * compress_func_t- Pointer to a function to compresses a chunk
124 * of a WIM resource. This may be either
125 * wimlib_xpress_compress() (xpress-compress.c) or
126 * wimlib_lzx_compress() (lzx-compress.c).
128 * @chunk: Uncompressed data of the chunk.
129 * @chunk_size: Size of the uncompressed chunk, in bytes.
130 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
132 * Returns the size of the compressed data written to @out in bytes, or 0 if the
133 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
135 * As a special requirement, the compression code is optimized for the WIM
136 * format and therefore requires (@chunk_size <= 32768).
138 * As another special requirement, the compression code will read up to 8 bytes
139 * off the end of the @chunk array for performance reasons. The values of these
140 * bytes will not affect the output of the compression, but the calling code
141 * must make sure that the buffer holding the uncompressed chunk is actually at
142 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
143 * mapped memory that will not cause a memory access violation if accessed.
145 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
148 static compress_func_t
149 get_compress_func(int out_ctype)
151 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
152 return wimlib_lzx_compress;
154 return wimlib_xpress_compress;
158 * Writes a chunk of a WIM resource to an output file.
160 * @chunk: Uncompressed data of the chunk.
161 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
162 * @out_fp: FILE * to write the chunk to.
163 * @compress: Compression function to use (NULL if writing uncompressed
165 * @chunk_tab: Pointer to chunk table being created. It is updated with the
166 * offset of the chunk we write.
168 * Returns 0 on success; nonzero on failure.
171 write_wim_resource_chunk(const void * restrict chunk,
173 FILE * restrict out_fp,
174 compress_func_t compress,
175 struct chunk_table * restrict chunk_tab)
177 const void *out_chunk;
178 unsigned out_chunk_size;
180 void *compressed_chunk = alloca(chunk_size);
182 out_chunk_size = (*compress)(chunk, chunk_size, compressed_chunk);
183 if (out_chunk_size) {
184 /* Write compressed */
185 out_chunk = compressed_chunk;
187 /* Write uncompressed */
189 out_chunk_size = chunk_size;
191 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
192 chunk_tab->cur_offset += out_chunk_size;
194 /* Write uncompressed */
196 out_chunk_size = chunk_size;
198 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
199 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
200 return WIMLIB_ERR_WRITE;
206 * Finishes a WIM chunk table and writes it to the output file at the correct
209 * The final size of the full compressed resource is returned in the
210 * @compressed_size_p.
213 finish_wim_resource_chunk_tab(struct chunk_table * restrict chunk_tab,
214 FILE * restrict out_fp,
215 u64 * restrict compressed_size_p)
217 size_t bytes_written;
218 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
219 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
220 "WIM file", chunk_tab->file_offset);
221 return WIMLIB_ERR_WRITE;
224 if (chunk_tab->bytes_per_chunk_entry == 8) {
225 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
227 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
228 ((u32*)chunk_tab->offsets)[i] =
229 cpu_to_le32(chunk_tab->offsets[i]);
231 bytes_written = fwrite((u8*)chunk_tab->offsets +
232 chunk_tab->bytes_per_chunk_entry,
233 1, chunk_tab->table_disk_size, out_fp);
234 if (bytes_written != chunk_tab->table_disk_size) {
235 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
237 return WIMLIB_ERR_WRITE;
239 if (fseeko(out_fp, 0, SEEK_END) != 0) {
240 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
241 return WIMLIB_ERR_WRITE;
243 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
248 fflush_and_ftruncate(FILE *out_fp, off_t offset)
250 if (fseeko(out_fp, offset, SEEK_SET) ||
252 ftruncate(fileno(out_fp), offset))
254 ERROR_WITH_ERRNO("Failed to flush and/or truncate "
256 return WIMLIB_ERR_WRITE;
263 finalize_and_check_sha1(SHA_CTX * restrict sha_ctx,
264 struct wim_lookup_table_entry * restrict 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 *restrict chunk, size_t chunk_size,
295 struct write_resource_ctx *ctx = _ctx;
298 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
299 return write_wim_resource_chunk(chunk, chunk_size,
300 ctx->out_fp, ctx->compress,
305 * Write a resource to an output WIM.
307 * @lte: Lookup table entry for the resource, which could be in another WIM,
308 * in an external file, or in another location.
310 * @out_fp: FILE * opened to the output WIM.
312 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
313 * which compression algorithm to use.
315 * @out_res_entry: On success, this is filled in with the offset, flags,
316 * compressed size, and uncompressed size of the resource
319 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
320 * even if it could otherwise be copied directly from the input.
322 * Additional notes: The SHA1 message digest of the uncompressed data is
323 * calculated (except when doing a raw copy --- see below). If the @unhashed
324 * flag is set on the lookup table entry, this message digest is simply copied
325 * to it; otherwise, the message digest is compared with the existing one, and
326 * the function will fail if they do not match.
329 write_wim_resource(struct wim_lookup_table_entry *lte,
330 FILE *out_fp, int out_ctype,
331 struct resource_entry *out_res_entry,
334 struct write_resource_ctx write_ctx;
340 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
342 /* Get current position in output WIM */
343 offset = ftello(out_fp);
345 ERROR_WITH_ERRNO("Can't get position in output WIM");
346 return WIMLIB_ERR_WRITE;
349 /* If we are not forcing the data to be recompressed, and the input
350 * resource is located in a WIM with the same compression type as that
351 * desired other than no compression, we can simply copy the compressed
352 * data without recompressing it. This also means we must skip
353 * calculating the SHA1, as we never will see the uncompressed data. */
354 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
355 lte->resource_location == RESOURCE_IN_WIM &&
356 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
357 wimlib_get_compression_type(lte->wim) == out_ctype)
359 flags |= WIMLIB_RESOURCE_FLAG_RAW;
360 write_ctx.doing_sha = false;
361 read_size = lte->resource_entry.size;
363 write_ctx.doing_sha = true;
364 sha1_init(&write_ctx.sha_ctx);
365 read_size = lte->resource_entry.original_size;
368 /* Initialize the chunk table and set the compression function if
369 * compressing the resource. */
370 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
371 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
372 write_ctx.compress = NULL;
373 write_ctx.chunk_tab = NULL;
375 write_ctx.compress = get_compress_func(out_ctype);
376 ret = begin_wim_resource_chunk_tab(lte, out_fp,
378 &write_ctx.chunk_tab);
383 /* Write the entire resource by reading the entire resource and feeding
384 * the data through the write_resource_cb function. */
385 write_ctx.out_fp = out_fp;
387 ret = read_resource_prefix(lte, read_size,
388 write_resource_cb, &write_ctx, flags);
390 goto out_free_chunk_tab;
392 /* Verify SHA1 message digest of the resource, or set the hash for the
394 if (write_ctx.doing_sha) {
395 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
397 goto out_free_chunk_tab;
400 out_res_entry->flags = lte->resource_entry.flags;
401 out_res_entry->original_size = wim_resource_size(lte);
402 out_res_entry->offset = offset;
403 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
404 /* Doing a raw write: The new compressed size is the same as
405 * the compressed size in the other WIM. */
406 new_size = lte->resource_entry.size;
407 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
408 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
409 * is the original size. */
410 new_size = lte->resource_entry.original_size;
411 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
413 /* Using a different compression type: Call
414 * finish_wim_resource_chunk_tab() and it will provide the new
415 * compressed size. */
416 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
419 goto out_free_chunk_tab;
420 if (new_size >= wim_resource_size(lte)) {
421 /* Oops! We compressed the resource to larger than the original
422 * size. Write the resource uncompressed instead. */
423 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
424 "writing uncompressed instead",
425 wim_resource_size(lte), new_size);
426 ret = fflush_and_ftruncate(out_fp, offset);
428 goto out_free_chunk_tab;
429 write_ctx.compress = NULL;
430 write_ctx.doing_sha = false;
431 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
432 goto try_write_again;
434 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
436 out_res_entry->size = new_size;
439 FREE(write_ctx.chunk_tab);
443 #ifdef ENABLE_MULTITHREADED_COMPRESSION
445 /* Blocking shared queue (solves the producer-consumer problem) */
446 struct shared_queue {
450 unsigned filled_slots;
452 pthread_mutex_t lock;
453 pthread_cond_t msg_avail_cond;
454 pthread_cond_t space_avail_cond;
458 shared_queue_init(struct shared_queue *q, unsigned size)
460 wimlib_assert(size != 0);
461 q->array = CALLOC(sizeof(q->array[0]), size);
468 if (pthread_mutex_init(&q->lock, NULL)) {
469 ERROR_WITH_ERRNO("Failed to initialize mutex");
472 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
473 ERROR_WITH_ERRNO("Failed to initialize condition variable");
474 goto err_destroy_lock;
476 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
477 ERROR_WITH_ERRNO("Failed to initialize condition variable");
478 goto err_destroy_msg_avail_cond;
481 err_destroy_msg_avail_cond:
482 pthread_cond_destroy(&q->msg_avail_cond);
484 pthread_mutex_destroy(&q->lock);
486 return WIMLIB_ERR_NOMEM;
490 shared_queue_destroy(struct shared_queue *q)
493 pthread_mutex_destroy(&q->lock);
494 pthread_cond_destroy(&q->msg_avail_cond);
495 pthread_cond_destroy(&q->space_avail_cond);
499 shared_queue_put(struct shared_queue *q, void *obj)
501 pthread_mutex_lock(&q->lock);
502 while (q->filled_slots == q->size)
503 pthread_cond_wait(&q->space_avail_cond, &q->lock);
505 q->back = (q->back + 1) % q->size;
506 q->array[q->back] = obj;
509 pthread_cond_broadcast(&q->msg_avail_cond);
510 pthread_mutex_unlock(&q->lock);
514 shared_queue_get(struct shared_queue *q)
518 pthread_mutex_lock(&q->lock);
519 while (q->filled_slots == 0)
520 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
522 obj = q->array[q->front];
523 q->array[q->front] = NULL;
524 q->front = (q->front + 1) % q->size;
527 pthread_cond_broadcast(&q->space_avail_cond);
528 pthread_mutex_unlock(&q->lock);
532 struct compressor_thread_params {
533 struct shared_queue *res_to_compress_queue;
534 struct shared_queue *compressed_res_queue;
535 compress_func_t compress;
538 #define MAX_CHUNKS_PER_MSG 2
541 struct wim_lookup_table_entry *lte;
542 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
543 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
544 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
545 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
546 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
548 struct list_head list;
554 compress_chunks(struct message *msg, compress_func_t compress)
556 for (unsigned i = 0; i < msg->num_chunks; i++) {
557 unsigned len = compress(msg->uncompressed_chunks[i],
558 msg->uncompressed_chunk_sizes[i],
559 msg->compressed_chunks[i]);
561 /* To be written compressed */
562 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
563 msg->compressed_chunk_sizes[i] = len;
565 /* To be written uncompressed */
566 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
567 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
573 /* Compressor thread routine. This is a lot simpler than the main thread
574 * routine: just repeatedly get a group of chunks from the
575 * res_to_compress_queue, compress them, and put them in the
576 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
579 compressor_thread_proc(void *arg)
581 struct compressor_thread_params *params = arg;
582 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
583 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
584 compress_func_t compress = params->compress;
587 DEBUG("Compressor thread ready");
588 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
589 compress_chunks(msg, compress);
590 shared_queue_put(compressed_res_queue, msg);
592 DEBUG("Compressor thread terminating");
595 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
598 do_write_streams_progress(union wimlib_progress_info *progress,
599 wimlib_progress_func_t progress_func,
602 progress->write_streams.completed_bytes += size_added;
603 progress->write_streams.completed_streams++;
605 progress->write_streams.completed_bytes >= progress->write_streams._private)
607 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
609 if (progress->write_streams._private == progress->write_streams.total_bytes) {
610 progress->write_streams._private = ~0;
612 progress->write_streams._private =
613 min(progress->write_streams.total_bytes,
614 progress->write_streams.completed_bytes +
615 progress->write_streams.total_bytes / 100);
620 struct serial_write_stream_ctx {
623 int write_resource_flags;
627 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
629 struct serial_write_stream_ctx *ctx = _ctx;
630 return write_wim_resource(lte, ctx->out_fp,
631 ctx->out_ctype, <e->output_resource_entry,
632 ctx->write_resource_flags);
635 /* Write a list of streams, taking into account that some streams may be
636 * duplicates that are checksummed and discarded on the fly, and also delegating
637 * the actual writing of a stream to a function @write_stream_cb, which is
638 * passed the context @write_stream_ctx. */
640 do_write_stream_list(struct list_head *stream_list,
641 struct wim_lookup_table *lookup_table,
642 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
643 void *write_stream_ctx,
644 wimlib_progress_func_t progress_func,
645 union wimlib_progress_info *progress)
648 struct wim_lookup_table_entry *lte;
650 /* For each stream in @stream_list ... */
651 while (!list_empty(stream_list)) {
652 lte = container_of(stream_list->next,
653 struct wim_lookup_table_entry,
655 list_del(<e->write_streams_list);
656 if (lte->unhashed && !lte->unique_size) {
657 /* Unhashed stream that shares a size with some other
658 * stream in the WIM we are writing. The stream must be
659 * checksummed to know if we need to write it or not. */
660 struct wim_lookup_table_entry *tmp;
661 u32 orig_refcnt = lte->out_refcnt;
663 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
668 /* We found a duplicate stream. */
669 if (orig_refcnt != tmp->out_refcnt) {
670 /* We have already written, or are going
671 * to write, the duplicate stream. So
672 * just skip to the next stream. */
673 DEBUG("Discarding duplicate stream of length %"PRIu64,
674 wim_resource_size(lte));
675 lte->no_progress = 0;
676 goto skip_to_progress;
681 /* Here, @lte is either a hashed stream or an unhashed stream
682 * with a unique size. In either case we know that the stream
683 * has to be written. In either case the SHA1 message digest
684 * will be calculated over the stream while writing it; however,
685 * in the former case this is done merely to check the data,
686 * while in the latter case this is done because we do not have
687 * the SHA1 message digest yet. */
688 wimlib_assert(lte->out_refcnt != 0);
690 lte->no_progress = 0;
691 ret = (*write_stream_cb)(lte, write_stream_ctx);
694 /* In parallel mode, some streams are deferred for later,
695 * serialized processing; ignore them here. */
699 list_del(<e->unhashed_list);
700 lookup_table_insert(lookup_table, lte);
704 if (!lte->no_progress) {
705 do_write_streams_progress(progress,
707 wim_resource_size(lte));
714 do_write_stream_list_serial(struct list_head *stream_list,
715 struct wim_lookup_table *lookup_table,
718 int write_resource_flags,
719 wimlib_progress_func_t progress_func,
720 union wimlib_progress_info *progress)
722 struct serial_write_stream_ctx ctx = {
724 .out_ctype = out_ctype,
725 .write_resource_flags = write_resource_flags,
727 return do_write_stream_list(stream_list,
736 write_flags_to_resource_flags(int write_flags)
738 int resource_flags = 0;
740 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
741 resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
742 return resource_flags;
746 write_stream_list_serial(struct list_head *stream_list,
747 struct wim_lookup_table *lookup_table,
750 int write_resource_flags,
751 wimlib_progress_func_t progress_func,
752 union wimlib_progress_info *progress)
754 DEBUG("Writing stream list (serial version)");
755 progress->write_streams.num_threads = 1;
757 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
758 return do_write_stream_list_serial(stream_list,
762 write_resource_flags,
767 #ifdef ENABLE_MULTITHREADED_COMPRESSION
769 write_wim_chunks(struct message *msg, FILE *out_fp,
770 struct chunk_table *chunk_tab)
772 for (unsigned i = 0; i < msg->num_chunks; i++) {
773 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
775 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
778 ERROR_WITH_ERRNO("Failed to write WIM chunk");
779 return WIMLIB_ERR_WRITE;
782 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
783 chunk_tab->cur_offset += chunk_csize;
788 struct main_writer_thread_ctx {
789 struct list_head *stream_list;
790 struct wim_lookup_table *lookup_table;
793 int write_resource_flags;
794 struct shared_queue *res_to_compress_queue;
795 struct shared_queue *compressed_res_queue;
797 wimlib_progress_func_t progress_func;
798 union wimlib_progress_info *progress;
800 struct list_head available_msgs;
801 struct list_head outstanding_streams;
802 struct list_head serial_streams;
803 size_t num_outstanding_messages;
805 SHA_CTX next_sha_ctx;
808 struct wim_lookup_table_entry *next_lte;
810 struct message *msgs;
811 struct message *next_msg;
812 struct chunk_table *cur_chunk_tab;
816 init_message(struct message *msg)
818 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
819 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
820 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
821 if (msg->compressed_chunks[i] == NULL ||
822 msg->uncompressed_chunks[i] == NULL)
823 return WIMLIB_ERR_NOMEM;
829 destroy_message(struct message *msg)
831 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
832 FREE(msg->compressed_chunks[i]);
833 FREE(msg->uncompressed_chunks[i]);
838 free_messages(struct message *msgs, size_t num_messages)
841 for (size_t i = 0; i < num_messages; i++)
842 destroy_message(&msgs[i]);
847 static struct message *
848 allocate_messages(size_t num_messages)
850 struct message *msgs;
852 msgs = CALLOC(num_messages, sizeof(struct message));
855 for (size_t i = 0; i < num_messages; i++) {
856 if (init_message(&msgs[i])) {
857 free_messages(msgs, num_messages);
865 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
867 while (ctx->num_outstanding_messages--)
868 shared_queue_get(ctx->compressed_res_queue);
869 free_messages(ctx->msgs, ctx->num_messages);
870 FREE(ctx->cur_chunk_tab);
874 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
876 /* Pre-allocate all the buffers that will be needed to do the chunk
878 ctx->msgs = allocate_messages(ctx->num_messages);
880 return WIMLIB_ERR_NOMEM;
882 /* Initially, all the messages are available to use. */
883 INIT_LIST_HEAD(&ctx->available_msgs);
884 for (size_t i = 0; i < ctx->num_messages; i++)
885 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
887 /* outstanding_streams is the list of streams that currently have had
888 * chunks sent off for compression.
890 * The first stream in outstanding_streams is the stream that is
891 * currently being written.
893 * The last stream in outstanding_streams is the stream that is
894 * currently being read and having chunks fed to the compressor threads.
896 INIT_LIST_HEAD(&ctx->outstanding_streams);
897 ctx->num_outstanding_messages = 0;
899 ctx->next_msg = NULL;
901 /* Resources that don't need any chunks compressed are added to this
902 * list and written directly by the main thread. */
903 INIT_LIST_HEAD(&ctx->serial_streams);
905 ctx->cur_chunk_tab = NULL;
911 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
914 struct wim_lookup_table_entry *cur_lte;
917 wimlib_assert(!list_empty(&ctx->outstanding_streams));
918 wimlib_assert(ctx->num_outstanding_messages != 0);
920 cur_lte = container_of(ctx->outstanding_streams.next,
921 struct wim_lookup_table_entry,
922 being_compressed_list);
924 /* Get the next message from the queue and process it.
925 * The message will contain 1 or more data chunks that have been
927 msg = shared_queue_get(ctx->compressed_res_queue);
928 msg->complete = true;
929 --ctx->num_outstanding_messages;
931 /* Is this the next chunk in the current resource? If it's not
932 * (i.e., an earlier chunk in a same or different resource
933 * hasn't been compressed yet), do nothing, and keep this
934 * message around until all earlier chunks are received.
936 * Otherwise, write all the chunks we can. */
937 while (cur_lte != NULL &&
938 !list_empty(&cur_lte->msg_list)
939 && (msg = container_of(cur_lte->msg_list.next,
943 list_move(&msg->list, &ctx->available_msgs);
944 if (msg->begin_chunk == 0) {
945 /* This is the first set of chunks. Leave space
946 * for the chunk table in the output file. */
947 off_t cur_offset = ftello(ctx->out_fp);
948 if (cur_offset == -1)
949 return WIMLIB_ERR_WRITE;
950 ret = begin_wim_resource_chunk_tab(cur_lte,
953 &ctx->cur_chunk_tab);
958 /* Write the compressed chunks from the message. */
959 ret = write_wim_chunks(msg, ctx->out_fp, ctx->cur_chunk_tab);
963 /* Was this the last chunk of the stream? If so, finish
965 if (list_empty(&cur_lte->msg_list) &&
966 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
971 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
977 list_del(&cur_lte->being_compressed_list);
979 /* Grab the offset of this stream in the output file
980 * from the chunk table before we free it. */
981 offset = ctx->cur_chunk_tab->file_offset;
983 FREE(ctx->cur_chunk_tab);
984 ctx->cur_chunk_tab = NULL;
986 if (res_csize >= wim_resource_size(cur_lte)) {
987 /* Oops! We compressed the resource to
988 * larger than the original size. Write
989 * the resource uncompressed instead. */
990 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
991 "writing uncompressed instead",
992 wim_resource_size(cur_lte), res_csize);
993 ret = fflush_and_ftruncate(ctx->out_fp, offset);
996 ret = write_wim_resource(cur_lte,
998 WIMLIB_COMPRESSION_TYPE_NONE,
999 &cur_lte->output_resource_entry,
1000 ctx->write_resource_flags);
1004 cur_lte->output_resource_entry.size =
1007 cur_lte->output_resource_entry.original_size =
1008 cur_lte->resource_entry.original_size;
1010 cur_lte->output_resource_entry.offset =
1013 cur_lte->output_resource_entry.flags =
1014 cur_lte->resource_entry.flags |
1015 WIM_RESHDR_FLAG_COMPRESSED;
1018 do_write_streams_progress(ctx->progress,
1020 wim_resource_size(cur_lte));
1022 /* Since we just finished writing a stream, write any
1023 * streams that have been added to the serial_streams
1024 * list for direct writing by the main thread (e.g.
1025 * resources that don't need to be compressed because
1026 * the desired compression type is the same as the
1027 * previous compression type). */
1028 if (!list_empty(&ctx->serial_streams)) {
1029 ret = do_write_stream_list_serial(&ctx->serial_streams,
1033 ctx->write_resource_flags,
1040 /* Advance to the next stream to write. */
1041 if (list_empty(&ctx->outstanding_streams)) {
1044 cur_lte = container_of(ctx->outstanding_streams.next,
1045 struct wim_lookup_table_entry,
1046 being_compressed_list);
1053 /* Called when the main thread has read a new chunk of data. */
1055 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1057 struct main_writer_thread_ctx *ctx = _ctx;
1059 struct message *next_msg;
1060 u64 next_chunk_in_msg;
1062 /* Update SHA1 message digest for the stream currently being read by the
1064 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1066 /* We send chunks of data to the compressor chunks in batches which we
1067 * refer to as "messages". @next_msg is the message that is currently
1068 * being prepared to send off. If it is NULL, that indicates that we
1069 * need to start a new message. */
1070 next_msg = ctx->next_msg;
1072 /* We need to start a new message. First check to see if there
1073 * is a message available in the list of available messages. If
1074 * so, we can just take one. If not, all the messages (there is
1075 * a fixed number of them, proportional to the number of
1076 * threads) have been sent off to the compressor threads, so we
1077 * receive messages from the compressor threads containing
1078 * compressed chunks of data.
1080 * We may need to receive multiple messages before one is
1081 * actually available to use because messages received that are
1082 * *not* for the very next set of chunks to compress must be
1083 * buffered until it's time to write those chunks. */
1084 while (list_empty(&ctx->available_msgs)) {
1085 ret = receive_compressed_chunks(ctx);
1090 next_msg = container_of(ctx->available_msgs.next,
1091 struct message, list);
1092 list_del(&next_msg->list);
1093 next_msg->complete = false;
1094 next_msg->begin_chunk = ctx->next_chunk;
1095 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1096 ctx->next_num_chunks - ctx->next_chunk);
1097 ctx->next_msg = next_msg;
1100 /* Fill in the next chunk to compress */
1101 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1103 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1104 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1107 if (++next_chunk_in_msg == next_msg->num_chunks) {
1108 /* Send off an array of chunks to compress */
1109 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1110 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1111 ++ctx->num_outstanding_messages;
1112 ctx->next_msg = NULL;
1118 main_writer_thread_finish(void *_ctx)
1120 struct main_writer_thread_ctx *ctx = _ctx;
1122 while (ctx->num_outstanding_messages != 0) {
1123 ret = receive_compressed_chunks(ctx);
1127 wimlib_assert(list_empty(&ctx->outstanding_streams));
1128 return do_write_stream_list_serial(&ctx->serial_streams,
1132 ctx->write_resource_flags,
1138 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1139 struct main_writer_thread_ctx *ctx)
1143 /* Read the entire stream @lte, feeding its data chunks to the
1144 * compressor threads. Also SHA1-sum the stream; this is required in
1145 * the case that @lte is unhashed, and a nice additional verification
1146 * when @lte is already hashed. */
1147 sha1_init(&ctx->next_sha_ctx);
1148 ctx->next_chunk = 0;
1149 ctx->next_num_chunks = wim_resource_chunks(lte);
1150 ctx->next_lte = lte;
1151 INIT_LIST_HEAD(<e->msg_list);
1152 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1153 ret = read_resource_prefix(lte, wim_resource_size(lte),
1154 main_writer_thread_cb, ctx, 0);
1156 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1157 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1163 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1165 struct main_writer_thread_ctx *ctx = _ctx;
1168 if (wim_resource_size(lte) < 1000 ||
1169 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1170 (lte->resource_location == RESOURCE_IN_WIM &&
1171 !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1172 wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
1174 /* Stream is too small or isn't being compressed. Process it by
1175 * the main thread when we have a chance. We can't necessarily
1176 * process it right here, as the main thread could be in the
1177 * middle of writing a different stream. */
1178 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1182 ret = submit_stream_for_compression(lte, ctx);
1184 lte->no_progress = 1;
1189 get_default_num_threads()
1192 return win32_get_number_of_processors();
1194 return sysconf(_SC_NPROCESSORS_ONLN);
1198 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1199 * parameter and will perform compression using that many threads. Falls
1200 * back to write_stream_list_serial() on certain errors, such as a failure to
1201 * create the number of threads requested.
1203 * High level description of the algorithm for writing compressed streams in
1204 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1205 * rather than on full files. The currently executing thread becomes the main
1206 * thread and is entirely in charge of reading the data to compress (which may
1207 * be in any location understood by the resource code--- such as in an external
1208 * file being captured, or in another WIM file from which an image is being
1209 * exported) and actually writing the compressed data to the output file.
1210 * Additional threads are "compressor threads" and all execute the
1211 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1212 * the main thread, compress them, and hand them back to the main thread.
1214 * Certain streams, such as streams that do not need to be compressed (e.g.
1215 * input compression type same as output compression type) or streams of very
1216 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1217 * handled entirely by the main thread at an appropriate time.
1219 * At any given point in time, multiple streams may be having chunks compressed
1220 * concurrently. The stream that the main thread is currently *reading* may be
1221 * later in the list that the stream that the main thread is currently
1225 write_stream_list_parallel(struct list_head *stream_list,
1226 struct wim_lookup_table *lookup_table,
1229 int write_resource_flags,
1230 wimlib_progress_func_t progress_func,
1231 union wimlib_progress_info *progress,
1232 unsigned num_threads)
1235 struct shared_queue res_to_compress_queue;
1236 struct shared_queue compressed_res_queue;
1237 pthread_t *compressor_threads = NULL;
1239 if (num_threads == 0) {
1240 long nthreads = get_default_num_threads();
1241 if (nthreads < 1 || nthreads > UINT_MAX) {
1242 WARNING("Could not determine number of processors! Assuming 1");
1244 } else if (nthreads == 1) {
1245 goto out_serial_quiet;
1247 num_threads = nthreads;
1251 DEBUG("Writing stream list (parallel version, num_threads=%u)",
1254 progress->write_streams.num_threads = num_threads;
1256 static const size_t MESSAGES_PER_THREAD = 2;
1257 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1259 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1261 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1265 ret = shared_queue_init(&compressed_res_queue, queue_size);
1267 goto out_destroy_res_to_compress_queue;
1269 struct compressor_thread_params params;
1270 params.res_to_compress_queue = &res_to_compress_queue;
1271 params.compressed_res_queue = &compressed_res_queue;
1272 params.compress = get_compress_func(out_ctype);
1274 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1275 if (!compressor_threads) {
1276 ret = WIMLIB_ERR_NOMEM;
1277 goto out_destroy_compressed_res_queue;
1280 for (unsigned i = 0; i < num_threads; i++) {
1281 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1282 ret = pthread_create(&compressor_threads[i], NULL,
1283 compressor_thread_proc, ¶ms);
1286 ERROR_WITH_ERRNO("Failed to create compressor "
1288 i + 1, num_threads);
1295 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1297 struct main_writer_thread_ctx ctx;
1298 ctx.stream_list = stream_list;
1299 ctx.lookup_table = lookup_table;
1300 ctx.out_fp = out_fp;
1301 ctx.out_ctype = out_ctype;
1302 ctx.res_to_compress_queue = &res_to_compress_queue;
1303 ctx.compressed_res_queue = &compressed_res_queue;
1304 ctx.num_messages = queue_size;
1305 ctx.write_resource_flags = write_resource_flags | WIMLIB_RESOURCE_FLAG_THREADSAFE_READ;
1306 ctx.progress_func = progress_func;
1307 ctx.progress = progress;
1308 ret = main_writer_thread_init_ctx(&ctx);
1311 ret = do_write_stream_list(stream_list, lookup_table,
1312 main_thread_process_next_stream,
1313 &ctx, progress_func, progress);
1315 goto out_destroy_ctx;
1317 /* The main thread has finished reading all streams that are going to be
1318 * compressed in parallel, and it now needs to wait for all remaining
1319 * chunks to be compressed so that the remaining streams can actually be
1320 * written to the output file. Furthermore, any remaining streams that
1321 * had processing deferred to the main thread need to be handled. These
1322 * tasks are done by the main_writer_thread_finish() function. */
1323 ret = main_writer_thread_finish(&ctx);
1325 main_writer_thread_destroy_ctx(&ctx);
1327 for (unsigned i = 0; i < num_threads; i++)
1328 shared_queue_put(&res_to_compress_queue, NULL);
1330 for (unsigned i = 0; i < num_threads; i++) {
1331 if (pthread_join(compressor_threads[i], NULL)) {
1332 WARNING_WITH_ERRNO("Failed to join compressor "
1334 i + 1, num_threads);
1337 FREE(compressor_threads);
1338 out_destroy_compressed_res_queue:
1339 shared_queue_destroy(&compressed_res_queue);
1340 out_destroy_res_to_compress_queue:
1341 shared_queue_destroy(&res_to_compress_queue);
1342 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1345 WARNING("Falling back to single-threaded compression");
1347 return write_stream_list_serial(stream_list,
1351 write_resource_flags,
1359 * Write a list of streams to a WIM (@out_fp) using the compression type
1360 * @out_ctype and up to @num_threads compressor threads.
1363 write_stream_list(struct list_head *stream_list,
1364 struct wim_lookup_table *lookup_table,
1365 FILE *out_fp, int out_ctype, int write_flags,
1366 unsigned num_threads, wimlib_progress_func_t progress_func)
1368 struct wim_lookup_table_entry *lte;
1369 size_t num_streams = 0;
1370 u64 total_bytes = 0;
1371 u64 total_compression_bytes = 0;
1372 union wimlib_progress_info progress;
1374 int write_resource_flags;
1376 if (list_empty(stream_list))
1379 write_resource_flags = write_flags_to_resource_flags(write_flags);
1381 /* Calculate the total size of the streams to be written. Note: this
1382 * will be the uncompressed size, as we may not know the compressed size
1383 * yet, and also this will assume that every unhashed stream will be
1384 * written (which will not necessarily be the case). */
1385 list_for_each_entry(lte, stream_list, write_streams_list) {
1387 total_bytes += wim_resource_size(lte);
1388 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1389 && (wim_resource_compression_type(lte) != out_ctype ||
1390 (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1392 total_compression_bytes += wim_resource_size(lte);
1395 progress.write_streams.total_bytes = total_bytes;
1396 progress.write_streams.total_streams = num_streams;
1397 progress.write_streams.completed_bytes = 0;
1398 progress.write_streams.completed_streams = 0;
1399 progress.write_streams.num_threads = num_threads;
1400 progress.write_streams.compression_type = out_ctype;
1401 progress.write_streams._private = 0;
1403 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1404 if (total_compression_bytes >= 1000000 && num_threads != 1)
1405 ret = write_stream_list_parallel(stream_list,
1409 write_resource_flags,
1415 ret = write_stream_list_serial(stream_list,
1419 write_resource_flags,
1425 struct stream_size_table {
1426 struct hlist_head *array;
1432 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1434 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1436 return WIMLIB_ERR_NOMEM;
1437 tab->num_entries = 0;
1438 tab->capacity = capacity;
1443 destroy_stream_size_table(struct stream_size_table *tab)
1449 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1451 struct stream_size_table *tab = _tab;
1453 struct wim_lookup_table_entry *same_size_lte;
1454 struct hlist_node *tmp;
1456 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1457 lte->unique_size = 1;
1458 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1459 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1460 lte->unique_size = 0;
1461 same_size_lte->unique_size = 0;
1466 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1472 struct lte_overwrite_prepare_args {
1475 struct list_head stream_list;
1476 struct stream_size_table stream_size_tab;
1479 /* First phase of preparing streams for an in-place overwrite. This is called
1480 * on all streams, both hashed and unhashed, except the metadata resources. */
1482 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1484 struct lte_overwrite_prepare_args *args = _args;
1486 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1487 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1488 list_add_tail(<e->write_streams_list, &args->stream_list);
1489 lte->out_refcnt = lte->refcnt;
1490 stream_size_table_insert(lte, &args->stream_size_tab);
1494 /* Second phase of preparing streams for an in-place overwrite. This is called
1495 * on existing metadata resources and hashed streams, but not unhashed streams.
1497 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1498 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1499 * the latter uses lte->hash_list_2, while the former expects to set
1500 * lte->output_resource_entry. */
1502 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1504 struct lte_overwrite_prepare_args *args = _args;
1506 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1507 /* We can't do an in place overwrite on the WIM if there are
1508 * streams after the XML data. */
1509 if (lte->resource_entry.offset +
1510 lte->resource_entry.size > args->end_offset)
1512 #ifdef ENABLE_ERROR_MESSAGES
1513 ERROR("The following resource is after the XML data:");
1514 print_lookup_table_entry(lte, stderr);
1516 return WIMLIB_ERR_RESOURCE_ORDER;
1518 copy_resource_entry(<e->output_resource_entry,
1519 <e->resource_entry);
1524 /* Given a WIM that we are going to overwrite in place with zero or more
1525 * additional streams added, construct a list the list of new unique streams
1526 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1527 * streams that need to be added but may be identical to other hashed or
1528 * unhashed streams. These unhashed streams are checksummed while the streams
1529 * are being written. To aid this process, the member @unique_size is set to 1
1530 * on streams that have a unique size and therefore must be written.
1532 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1533 * indicate the number of times the stream is referenced in only the streams
1534 * that are being written; this may still be adjusted later when unhashed
1535 * streams are being resolved.
1538 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1539 struct list_head *stream_list)
1542 struct lte_overwrite_prepare_args args;
1546 args.end_offset = end_offset;
1547 ret = init_stream_size_table(&args.stream_size_tab,
1548 wim->lookup_table->capacity);
1552 INIT_LIST_HEAD(&args.stream_list);
1553 for (i = 0; i < wim->hdr.image_count; i++) {
1554 struct wim_image_metadata *imd;
1555 struct wim_lookup_table_entry *lte;
1557 imd = wim->image_metadata[i];
1558 image_for_each_unhashed_stream(lte, imd)
1559 lte_overwrite_prepare(lte, &args);
1561 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1562 list_transfer(&args.stream_list, stream_list);
1564 for (i = 0; i < wim->hdr.image_count; i++) {
1565 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1568 goto out_destroy_stream_size_table;
1570 ret = for_lookup_table_entry(wim->lookup_table,
1571 lte_overwrite_prepare_2, &args);
1572 out_destroy_stream_size_table:
1573 destroy_stream_size_table(&args.stream_size_tab);
1578 struct find_streams_ctx {
1579 struct list_head stream_list;
1580 struct stream_size_table stream_size_tab;
1584 inode_find_streams_to_write(struct wim_inode *inode,
1585 struct wim_lookup_table *table,
1586 struct list_head *stream_list,
1587 struct stream_size_table *tab)
1589 struct wim_lookup_table_entry *lte;
1590 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1591 lte = inode_stream_lte(inode, i, table);
1593 if (lte->out_refcnt == 0) {
1595 stream_size_table_insert(lte, tab);
1596 list_add_tail(<e->write_streams_list, stream_list);
1598 lte->out_refcnt += inode->i_nlink;
1604 image_find_streams_to_write(WIMStruct *w)
1606 struct find_streams_ctx *ctx;
1607 struct wim_image_metadata *imd;
1608 struct wim_inode *inode;
1609 struct wim_lookup_table_entry *lte;
1612 imd = wim_get_current_image_metadata(w);
1614 image_for_each_unhashed_stream(lte, imd)
1615 lte->out_refcnt = 0;
1617 /* Go through this image's inodes to find any streams that have not been
1619 image_for_each_inode(inode, imd) {
1620 inode_find_streams_to_write(inode, w->lookup_table,
1622 &ctx->stream_size_tab);
1627 /* Given a WIM that from which one or all of the images is being written, build
1628 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1629 * written, plus any unhashed streams that need to be written but may be
1630 * identical to other hashed or unhashed streams being written. These unhashed
1631 * streams are checksummed while the streams are being written. To aid this
1632 * process, the member @unique_size is set to 1 on streams that have a unique
1633 * size and therefore must be written.
1635 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1636 * indicate the number of times the stream is referenced in only the streams
1637 * that are being written; this may still be adjusted later when unhashed
1638 * streams are being resolved.
1641 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1644 struct find_streams_ctx ctx;
1646 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1647 ret = init_stream_size_table(&ctx.stream_size_tab,
1648 wim->lookup_table->capacity);
1651 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1652 &ctx.stream_size_tab);
1653 INIT_LIST_HEAD(&ctx.stream_list);
1654 wim->private = &ctx;
1655 ret = for_image(wim, image, image_find_streams_to_write);
1656 destroy_stream_size_table(&ctx.stream_size_tab);
1658 list_transfer(&ctx.stream_list, stream_list);
1662 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1665 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1666 unsigned num_threads,
1667 wimlib_progress_func_t progress_func)
1670 struct list_head stream_list;
1672 ret = prepare_stream_list(wim, image, &stream_list);
1675 return write_stream_list(&stream_list,
1678 wimlib_get_compression_type(wim),
1685 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1686 * table (optional), then overwrite the WIM header.
1688 * write_flags is a bitwise OR of the following:
1690 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1691 * Include an integrity table.
1693 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1694 * Show progress information when (if) writing the integrity table.
1696 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1697 * Don't write the lookup table.
1699 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1700 * When (if) writing the integrity table, re-use entries from the
1701 * existing integrity table, if possible.
1703 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1704 * After writing the XML data but before writing the integrity
1705 * table, write a temporary WIM header and flush the stream so that
1706 * the WIM is less likely to become corrupted upon abrupt program
1709 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1710 * fsync() the output file before closing it.
1714 finish_write(WIMStruct *w, int image, int write_flags,
1715 wimlib_progress_func_t progress_func)
1718 struct wim_header hdr;
1719 FILE *out = w->out_fp;
1721 /* @hdr will be the header for the new WIM. First copy all the data
1722 * from the header in the WIMStruct; then set all the fields that may
1723 * have changed, including the resource entries, boot index, and image
1725 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1727 /* Set image count and boot index correctly for single image writes */
1728 if (image != WIMLIB_ALL_IMAGES) {
1729 hdr.image_count = 1;
1730 if (hdr.boot_idx == image)
1736 /* In the WIM header, there is room for the resource entry for a
1737 * metadata resource labeled as the "boot metadata". This entry should
1738 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1739 * it should be a copy of the resource entry for the image that is
1740 * marked as bootable. This is not well documented... */
1741 if (hdr.boot_idx == 0) {
1742 zero_resource_entry(&hdr.boot_metadata_res_entry);
1744 copy_resource_entry(&hdr.boot_metadata_res_entry,
1745 &w->image_metadata[ hdr.boot_idx- 1
1746 ]->metadata_lte->output_resource_entry);
1749 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1750 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1755 ret = write_xml_data(w->wim_info, image, out,
1756 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1757 wim_info_get_total_bytes(w->wim_info) : 0,
1758 &hdr.xml_res_entry);
1762 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1763 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1764 struct wim_header checkpoint_hdr;
1765 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1766 zero_resource_entry(&checkpoint_hdr.integrity);
1767 if (fseeko(out, 0, SEEK_SET)) {
1768 ERROR_WITH_ERRNO("Failed to seek to beginning "
1769 "of WIM being written");
1770 ret = WIMLIB_ERR_WRITE;
1773 ret = write_header(&checkpoint_hdr, out);
1777 if (fflush(out) != 0) {
1778 ERROR_WITH_ERRNO("Can't write data to WIM");
1779 ret = WIMLIB_ERR_WRITE;
1783 if (fseeko(out, 0, SEEK_END) != 0) {
1784 ERROR_WITH_ERRNO("Failed to seek to end "
1785 "of WIM being written");
1786 ret = WIMLIB_ERR_WRITE;
1791 off_t old_lookup_table_end;
1792 off_t new_lookup_table_end;
1793 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1794 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1795 w->hdr.lookup_table_res_entry.size;
1797 old_lookup_table_end = 0;
1799 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1800 hdr.lookup_table_res_entry.size;
1802 ret = write_integrity_table(out,
1804 new_lookup_table_end,
1805 old_lookup_table_end,
1810 zero_resource_entry(&hdr.integrity);
1813 if (fseeko(out, 0, SEEK_SET) != 0) {
1814 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1816 ret = WIMLIB_ERR_WRITE;
1820 ret = write_header(&hdr, out);
1824 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1825 if (fflush(out) != 0
1826 || fsync(fileno(out)) != 0)
1828 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1829 ret = WIMLIB_ERR_WRITE;
1833 if (fclose(out) != 0) {
1834 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1836 ret = WIMLIB_ERR_WRITE;
1842 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1844 lock_wim(WIMStruct *w, FILE *fp)
1847 if (fp && !w->wim_locked) {
1848 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1850 if (errno == EWOULDBLOCK) {
1851 ERROR("`%"TS"' is already being modified or has been "
1852 "mounted read-write\n"
1853 " by another process!", w->filename);
1854 ret = WIMLIB_ERR_ALREADY_LOCKED;
1856 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1869 open_wim_writable(WIMStruct *w, const tchar *path,
1870 bool trunc, bool also_readable)
1881 wimlib_assert(w->out_fp == NULL);
1882 w->out_fp = tfopen(path, mode);
1886 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1887 return WIMLIB_ERR_OPEN;
1893 close_wim_writable(WIMStruct *w)
1896 if (fclose(w->out_fp) != 0) {
1897 WARNING_WITH_ERRNO("Failed to close output WIM");
1903 /* Open file stream and write dummy header for WIM. */
1905 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1908 ret = open_wim_writable(w, path, true,
1909 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1912 /* Write dummy header. It will be overwritten later. */
1913 return write_header(&w->hdr, w->out_fp);
1916 /* Writes a stand-alone WIM to a file. */
1918 wimlib_write(WIMStruct *w, const tchar *path,
1919 int image, int write_flags, unsigned num_threads,
1920 wimlib_progress_func_t progress_func)
1925 return WIMLIB_ERR_INVALID_PARAM;
1927 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1929 if (image != WIMLIB_ALL_IMAGES &&
1930 (image < 1 || image > w->hdr.image_count))
1931 return WIMLIB_ERR_INVALID_IMAGE;
1933 if (w->hdr.total_parts != 1) {
1934 ERROR("Cannot call wimlib_write() on part of a split WIM");
1935 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1938 ret = begin_write(w, path, write_flags);
1942 ret = write_wim_streams(w, image, write_flags, num_threads,
1948 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1950 ret = for_image(w, image, write_metadata_resource);
1955 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1957 ret = finish_write(w, image, write_flags, progress_func);
1958 /* finish_write() closed the WIM for us */
1961 close_wim_writable(w);
1963 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1968 any_images_modified(WIMStruct *w)
1970 for (int i = 0; i < w->hdr.image_count; i++)
1971 if (w->image_metadata[i]->modified)
1977 * Overwrite a WIM, possibly appending streams to it.
1979 * A WIM looks like (or is supposed to look like) the following:
1981 * Header (212 bytes)
1982 * Streams and metadata resources (variable size)
1983 * Lookup table (variable size)
1984 * XML data (variable size)
1985 * Integrity table (optional) (variable size)
1987 * If we are not adding any streams or metadata resources, the lookup table is
1988 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1989 * header. This operation is potentially unsafe if the program is abruptly
1990 * terminated while the XML data or integrity table are being overwritten, but
1991 * before the new header has been written. To partially alleviate this problem,
1992 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1993 * finish_write() to cause a temporary WIM header to be written after the XML
1994 * data has been written. This may prevent the WIM from becoming corrupted if
1995 * the program is terminated while the integrity table is being calculated (but
1996 * no guarantees, due to write re-ordering...).
1998 * If we are adding new streams or images (metadata resources), the lookup table
1999 * needs to be changed, and those streams need to be written. In this case, we
2000 * try to perform a safe update of the WIM file by writing the streams *after*
2001 * the end of the previous WIM, then writing the new lookup table, XML data, and
2002 * (optionally) integrity table following the new streams. This will produce a
2003 * layout like the following:
2005 * Header (212 bytes)
2006 * (OLD) Streams and metadata resources (variable size)
2007 * (OLD) Lookup table (variable size)
2008 * (OLD) XML data (variable size)
2009 * (OLD) Integrity table (optional) (variable size)
2010 * (NEW) Streams and metadata resources (variable size)
2011 * (NEW) Lookup table (variable size)
2012 * (NEW) XML data (variable size)
2013 * (NEW) Integrity table (optional) (variable size)
2015 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2016 * the header is overwritten to point to the new lookup table, XML data, and
2017 * integrity table, to produce the following layout:
2019 * Header (212 bytes)
2020 * Streams and metadata resources (variable size)
2021 * Nothing (variable size)
2022 * More Streams and metadata resources (variable size)
2023 * Lookup table (variable size)
2024 * XML data (variable size)
2025 * Integrity table (optional) (variable size)
2027 * This method allows an image to be appended to a large WIM very quickly, and
2028 * is is crash-safe except in the case of write re-ordering, but the
2029 * disadvantage is that a small hole is left in the WIM where the old lookup
2030 * table, xml data, and integrity table were. (These usually only take up a
2031 * small amount of space compared to the streams, however.)
2034 overwrite_wim_inplace(WIMStruct *w, int write_flags,
2035 unsigned num_threads,
2036 wimlib_progress_func_t progress_func)
2039 struct list_head stream_list;
2041 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2043 DEBUG("Overwriting `%"TS"' in-place", w->filename);
2045 /* Make sure that the integrity table (if present) is after the XML
2046 * data, and that there are no stream resources, metadata resources, or
2047 * lookup tables after the XML data. Otherwise, these data would be
2049 old_xml_begin = w->hdr.xml_res_entry.offset;
2050 old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
2051 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
2052 w->hdr.lookup_table_res_entry.size;
2053 if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
2054 ERROR("Didn't expect the integrity table to be before the XML data");
2055 return WIMLIB_ERR_RESOURCE_ORDER;
2058 if (old_lookup_table_end > old_xml_begin) {
2059 ERROR("Didn't expect the lookup table to be after the XML data");
2060 return WIMLIB_ERR_RESOURCE_ORDER;
2063 /* Set @old_wim_end, which indicates the point beyond which we don't
2064 * allow any file and metadata resources to appear without returning
2065 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2066 * overwrite these resources). */
2067 if (!w->deletion_occurred && !any_images_modified(w)) {
2068 /* If no images have been modified and no images have been
2069 * deleted, a new lookup table does not need to be written. We
2070 * shall write the new XML data and optional integrity table
2071 * immediately after the lookup table. Note that this may
2072 * overwrite an existing integrity table. */
2073 DEBUG("Skipping writing lookup table "
2074 "(no images modified or deleted)");
2075 old_wim_end = old_lookup_table_end;
2076 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2077 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2078 } else if (w->hdr.integrity.offset) {
2079 /* Old WIM has an integrity table; begin writing new streams
2081 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2083 /* No existing integrity table; begin writing new streams after
2084 * the old XML data. */
2085 old_wim_end = old_xml_end;
2088 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2092 ret = open_wim_writable(w, w->filename, false,
2093 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
2097 ret = lock_wim(w, w->out_fp);
2099 close_wim_writable(w);
2103 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
2104 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2105 close_wim_writable(w);
2107 return WIMLIB_ERR_WRITE;
2110 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2112 ret = write_stream_list(&stream_list,
2115 wimlib_get_compression_type(w),
2122 for (int i = 0; i < w->hdr.image_count; i++) {
2123 if (w->image_metadata[i]->modified) {
2124 select_wim_image(w, i + 1);
2125 ret = write_metadata_resource(w);
2130 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2131 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2134 close_wim_writable(w);
2135 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2136 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2137 w->filename, old_wim_end);
2138 /* Return value of truncate() is ignored because this is already
2140 (void)ttruncate(w->filename, old_wim_end);
2147 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2148 unsigned num_threads,
2149 wimlib_progress_func_t progress_func)
2151 size_t wim_name_len;
2154 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2156 /* Write the WIM to a temporary file in the same directory as the
2158 wim_name_len = tstrlen(w->filename);
2159 tchar tmpfile[wim_name_len + 10];
2160 tmemcpy(tmpfile, w->filename, wim_name_len);
2161 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2162 tmpfile[wim_name_len + 9] = T('\0');
2164 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2165 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2166 num_threads, progress_func);
2168 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2172 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2175 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2176 * specified to CreateFile(). The WIM was opened with fopen(), which
2177 * didn't provided this flag to CreateFile, so the handle must be closed
2178 * before executing the rename(). */
2179 if (w->fp != NULL) {
2185 /* Rename the new file to the old file .*/
2186 if (trename(tmpfile, w->filename) != 0) {
2187 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2188 tmpfile, w->filename);
2189 ret = WIMLIB_ERR_RENAME;
2193 if (progress_func) {
2194 union wimlib_progress_info progress;
2195 progress.rename.from = tmpfile;
2196 progress.rename.to = w->filename;
2197 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2200 /* Close the original WIM file that was opened for reading. */
2201 if (w->fp != NULL) {
2206 /* Re-open the WIM read-only. */
2207 w->fp = tfopen(w->filename, T("rb"));
2208 if (w->fp == NULL) {
2209 ret = WIMLIB_ERR_REOPEN;
2210 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2217 /* Remove temporary file. */
2218 if (tunlink(tmpfile) != 0)
2219 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2225 * Writes a WIM file to the original file that it was read from, overwriting it.
2228 wimlib_overwrite(WIMStruct *w, int write_flags,
2229 unsigned num_threads,
2230 wimlib_progress_func_t progress_func)
2232 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2235 return WIMLIB_ERR_NO_FILENAME;
2237 if (w->hdr.total_parts != 1) {
2238 ERROR("Cannot modify a split WIM");
2239 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2242 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2243 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2246 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2248 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2249 WARNING("Falling back to re-building entire WIM");
2253 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,