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 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
251 u8 md[SHA1_HASH_SIZE];
252 sha1_final(md, sha_ctx);
254 copy_hash(lte->hash, md);
255 } else if (!hashes_equal(md, lte->hash)) {
256 ERROR("WIM resource has incorrect hash!");
257 if (lte_filename_valid(lte)) {
258 ERROR("We were reading it from \"%"TS"\"; maybe "
259 "it changed while we were reading it.",
262 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
268 struct write_resource_ctx {
269 compress_func_t compress;
270 struct chunk_table *chunk_tab;
277 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
279 struct write_resource_ctx *ctx = _ctx;
282 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
285 return write_wim_resource_chunk(chunk, chunk_size,
286 ctx->out_fp, ctx->compress,
289 if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
290 ERROR_WITH_ERRNO("Error writing to output WIM");
291 return WIMLIB_ERR_WRITE;
299 * Write a resource to an output WIM.
301 * @lte: Lookup table entry for the resource, which could be in another WIM,
302 * in an external file, or in another location.
304 * @out_fp: FILE * opened to the output WIM.
306 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
307 * which compression algorithm to use.
309 * @out_res_entry: On success, this is filled in with the offset, flags,
310 * compressed size, and uncompressed size of the resource
313 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
314 * even if it could otherwise be copied directly from the input.
316 * Additional notes: The SHA1 message digest of the uncompressed data is
317 * calculated (except when doing a raw copy --- see below). If the @unhashed
318 * flag is set on the lookup table entry, this message digest is simply copied
319 * to it; otherwise, the message digest is compared with the existing one, and
320 * the function will fail if they do not match.
323 write_wim_resource(struct wim_lookup_table_entry *lte,
324 FILE *out_fp, int out_ctype,
325 struct resource_entry *out_res_entry,
328 struct write_resource_ctx write_ctx;
334 DEBUG2("wim_resource_size(lte)=%"PRIu64, wim_resource_size(lte));
336 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
338 /* Get current position in output WIM */
339 offset = ftello(out_fp);
341 ERROR_WITH_ERRNO("Can't get position in output WIM");
342 return WIMLIB_ERR_WRITE;
345 /* If we are not forcing the data to be recompressed, and the input
346 * resource is located in a WIM with the same compression type as that
347 * desired other than no compression, we can simply copy the compressed
348 * data without recompressing it. This also means we must skip
349 * calculating the SHA1, as we never will see the uncompressed data. */
350 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
351 lte->resource_location == RESOURCE_IN_WIM &&
352 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
353 wimlib_get_compression_type(lte->wim) == out_ctype)
355 flags |= WIMLIB_RESOURCE_FLAG_RAW;
356 write_ctx.doing_sha = false;
357 read_size = lte->resource_entry.size;
359 write_ctx.doing_sha = true;
360 sha1_init(&write_ctx.sha_ctx);
361 read_size = lte->resource_entry.original_size;
364 /* Initialize the chunk table and set the compression function if
365 * compressing the resource. */
366 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
367 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
368 write_ctx.compress = NULL;
369 write_ctx.chunk_tab = NULL;
371 write_ctx.compress = get_compress_func(out_ctype);
372 ret = begin_wim_resource_chunk_tab(lte, out_fp,
374 &write_ctx.chunk_tab);
379 /* Write the entire resource by reading the entire resource and feeding
380 * the data through the write_resource_cb function. */
381 write_ctx.out_fp = out_fp;
383 ret = read_resource_prefix(lte, read_size,
384 write_resource_cb, &write_ctx, flags);
386 goto out_free_chunk_tab;
388 /* Verify SHA1 message digest of the resource, or set the hash for the
390 if (write_ctx.doing_sha) {
391 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
393 goto out_free_chunk_tab;
396 out_res_entry->flags = lte->resource_entry.flags;
397 out_res_entry->original_size = wim_resource_size(lte);
398 out_res_entry->offset = offset;
399 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
400 /* Doing a raw write: The new compressed size is the same as
401 * the compressed size in the other WIM. */
402 new_size = lte->resource_entry.size;
403 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
404 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
405 * is the original size. */
406 new_size = lte->resource_entry.original_size;
407 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
409 /* Using a different compression type: Call
410 * finish_wim_resource_chunk_tab() and it will provide the new
411 * compressed size. */
412 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
415 goto out_free_chunk_tab;
416 if (new_size >= wim_resource_size(lte)) {
417 /* Oops! We compressed the resource to larger than the original
418 * size. Write the resource uncompressed instead. */
419 if (fseeko(out_fp, offset, SEEK_SET) ||
421 ftruncate(fileno(out_fp),
422 offset + wim_resource_size(lte)))
424 ERROR_WITH_ERRNO("Failed to flush and/or truncate "
426 ret = WIMLIB_ERR_WRITE;
427 goto out_free_chunk_tab;
429 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
430 "writing uncompressed instead",
431 wim_resource_size(lte), new_size);
432 write_ctx.compress = NULL;
433 write_ctx.doing_sha = false;
434 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
435 goto try_write_again;
437 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
439 out_res_entry->size = new_size;
442 FREE(write_ctx.chunk_tab);
446 #ifdef ENABLE_MULTITHREADED_COMPRESSION
448 /* Blocking shared queue (solves the producer-consumer problem) */
449 struct shared_queue {
453 unsigned filled_slots;
455 pthread_mutex_t lock;
456 pthread_cond_t msg_avail_cond;
457 pthread_cond_t space_avail_cond;
461 shared_queue_init(struct shared_queue *q, unsigned size)
463 wimlib_assert(size != 0);
464 q->array = CALLOC(sizeof(q->array[0]), size);
471 if (pthread_mutex_init(&q->lock, NULL)) {
472 ERROR_WITH_ERRNO("Failed to initialize mutex");
475 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
476 ERROR_WITH_ERRNO("Failed to initialize condition variable");
477 goto err_destroy_lock;
479 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
480 ERROR_WITH_ERRNO("Failed to initialize condition variable");
481 goto err_destroy_msg_avail_cond;
484 err_destroy_msg_avail_cond:
485 pthread_cond_destroy(&q->msg_avail_cond);
487 pthread_mutex_destroy(&q->lock);
489 return WIMLIB_ERR_NOMEM;
493 shared_queue_destroy(struct shared_queue *q)
496 pthread_mutex_destroy(&q->lock);
497 pthread_cond_destroy(&q->msg_avail_cond);
498 pthread_cond_destroy(&q->space_avail_cond);
502 shared_queue_put(struct shared_queue *q, void *obj)
504 pthread_mutex_lock(&q->lock);
505 while (q->filled_slots == q->size)
506 pthread_cond_wait(&q->space_avail_cond, &q->lock);
508 q->back = (q->back + 1) % q->size;
509 q->array[q->back] = obj;
512 pthread_cond_broadcast(&q->msg_avail_cond);
513 pthread_mutex_unlock(&q->lock);
517 shared_queue_get(struct shared_queue *q)
521 pthread_mutex_lock(&q->lock);
522 while (q->filled_slots == 0)
523 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
525 obj = q->array[q->front];
526 q->array[q->front] = NULL;
527 q->front = (q->front + 1) % q->size;
530 pthread_cond_broadcast(&q->space_avail_cond);
531 pthread_mutex_unlock(&q->lock);
535 struct compressor_thread_params {
536 struct shared_queue *res_to_compress_queue;
537 struct shared_queue *compressed_res_queue;
538 compress_func_t compress;
541 #define MAX_CHUNKS_PER_MSG 2
544 struct wim_lookup_table_entry *lte;
545 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
546 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
547 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
548 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
549 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
551 struct list_head list;
557 compress_chunks(struct message *msg, compress_func_t compress)
559 for (unsigned i = 0; i < msg->num_chunks; i++) {
560 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
561 unsigned len = compress(msg->uncompressed_chunks[i],
562 msg->uncompressed_chunk_sizes[i],
563 msg->compressed_chunks[i]);
565 /* To be written compressed */
566 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
567 msg->compressed_chunk_sizes[i] = len;
569 /* To be written uncompressed */
570 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
571 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
577 /* Compressor thread routine. This is a lot simpler than the main thread
578 * routine: just repeatedly get a group of chunks from the
579 * res_to_compress_queue, compress them, and put them in the
580 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
583 compressor_thread_proc(void *arg)
585 struct compressor_thread_params *params = arg;
586 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
587 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
588 compress_func_t compress = params->compress;
591 DEBUG("Compressor thread ready");
592 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
593 compress_chunks(msg, compress);
594 shared_queue_put(compressed_res_queue, msg);
596 DEBUG("Compressor thread terminating");
599 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
602 do_write_streams_progress(union wimlib_progress_info *progress,
603 wimlib_progress_func_t progress_func,
606 progress->write_streams.completed_bytes += size_added;
607 progress->write_streams.completed_streams++;
609 progress->write_streams.completed_bytes >= progress->write_streams._private)
611 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
613 if (progress->write_streams._private == progress->write_streams.total_bytes) {
614 progress->write_streams._private = ~0;
616 progress->write_streams._private =
617 min(progress->write_streams.total_bytes,
618 progress->write_streams.completed_bytes +
619 progress->write_streams.total_bytes / 100);
624 struct serial_write_stream_ctx {
627 int write_resource_flags;
631 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
633 struct serial_write_stream_ctx *ctx = _ctx;
634 return write_wim_resource(lte, ctx->out_fp,
635 ctx->out_ctype, <e->output_resource_entry,
636 ctx->write_resource_flags);
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 goto skip_to_progress;
680 /* Here, @lte is either a hashed stream or an unhashed stream
681 * with a unique size. In either case we know that the stream
682 * has to be written. In either case the SHA1 message digest
683 * will be calculated over the stream while writing it; however,
684 * in the former case this is done merely to check the data,
685 * while in the latter case this is done because we do not have
686 * the SHA1 message digest yet. */
687 wimlib_assert(lte->out_refcnt != 0);
689 ret = (*write_stream_cb)(lte, write_stream_ctx);
692 /* In parallel mode, some streams are deferred for later,
693 * serialized processing; ignore them here. */
697 list_del(<e->unhashed_list);
698 lookup_table_insert(lookup_table, lte);
703 do_write_streams_progress(progress,
705 wim_resource_size(lte));
712 do_write_stream_list_serial(struct list_head *stream_list,
713 struct wim_lookup_table *lookup_table,
716 int write_resource_flags,
717 wimlib_progress_func_t progress_func,
718 union wimlib_progress_info *progress)
720 struct serial_write_stream_ctx ctx = {
722 .out_ctype = out_ctype,
723 .write_resource_flags = write_resource_flags,
725 return do_write_stream_list(stream_list,
734 write_flags_to_resource_flags(int write_flags)
736 return (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS) ?
737 WIMLIB_RESOURCE_FLAG_RECOMPRESS : 0;
741 write_stream_list_serial(struct list_head *stream_list,
742 struct wim_lookup_table *lookup_table,
745 int write_resource_flags,
746 wimlib_progress_func_t progress_func,
747 union wimlib_progress_info *progress)
749 progress->write_streams.num_threads = 1;
751 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
752 return do_write_stream_list_serial(stream_list,
756 write_resource_flags,
761 #ifdef ENABLE_MULTITHREADED_COMPRESSION
763 write_wim_chunks(struct message *msg, FILE *out_fp,
764 struct chunk_table *chunk_tab)
766 for (unsigned i = 0; i < msg->num_chunks; i++) {
767 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
769 DEBUG2("Write wim chunk %u of %u (csize = %u)",
770 i, msg->num_chunks, chunk_csize);
772 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
775 ERROR_WITH_ERRNO("Failed to write WIM chunk");
776 return WIMLIB_ERR_WRITE;
779 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
780 chunk_tab->cur_offset += chunk_csize;
785 struct main_writer_thread_ctx {
786 struct list_head *stream_list;
787 struct wim_lookup_table *lookup_table;
790 int write_resource_flags;
791 struct shared_queue *res_to_compress_queue;
792 struct shared_queue *compressed_res_queue;
794 wimlib_progress_func_t progress_func;
795 union wimlib_progress_info *progress;
797 struct list_head available_msgs;
798 struct list_head outstanding_streams;
799 struct list_head serial_streams;
800 size_t num_outstanding_messages;
802 SHA_CTX next_sha_ctx;
805 struct wim_lookup_table_entry *next_lte;
807 struct message *msgs;
808 struct message *next_msg;
809 struct chunk_table *cur_chunk_tab;
813 init_message(struct message *msg)
815 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
816 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
817 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
818 if (msg->compressed_chunks[i] == NULL ||
819 msg->uncompressed_chunks[i] == NULL)
820 return WIMLIB_ERR_NOMEM;
826 destroy_message(struct message *msg)
828 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
829 FREE(msg->compressed_chunks[i]);
830 FREE(msg->uncompressed_chunks[i]);
835 free_messages(struct message *msgs, size_t num_messages)
838 for (size_t i = 0; i < num_messages; i++)
839 destroy_message(&msgs[i]);
844 static struct message *
845 allocate_messages(size_t num_messages)
847 struct message *msgs;
849 msgs = CALLOC(num_messages, sizeof(struct message));
852 for (size_t i = 0; i < num_messages; i++) {
853 if (init_message(&msgs[i])) {
854 free_messages(msgs, num_messages);
862 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
864 while (ctx->num_outstanding_messages--)
865 shared_queue_get(ctx->compressed_res_queue);
866 free_messages(ctx->msgs, ctx->num_messages);
867 FREE(ctx->cur_chunk_tab);
871 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
873 /* Pre-allocate all the buffers that will be needed to do the chunk
875 ctx->msgs = allocate_messages(ctx->num_messages);
877 return WIMLIB_ERR_NOMEM;
879 /* Initially, all the messages are available to use. */
880 INIT_LIST_HEAD(&ctx->available_msgs);
881 for (size_t i = 0; i < ctx->num_messages; i++)
882 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
884 /* outstanding_streams is the list of streams that currently have had
885 * chunks sent off for compression.
887 * The first stream in outstanding_streams is the stream that is
888 * currently being written.
890 * The last stream in outstanding_streams is the stream that is
891 * currently being read and having chunks fed to the compressor threads.
893 INIT_LIST_HEAD(&ctx->outstanding_streams);
894 ctx->num_outstanding_messages = 0;
896 ctx->next_msg = NULL;
898 /* Resources that don't need any chunks compressed are added to this
899 * list and written directly by the main thread. */
900 INIT_LIST_HEAD(&ctx->serial_streams);
902 ctx->cur_chunk_tab = NULL;
908 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
911 struct wim_lookup_table_entry *cur_lte;
914 wimlib_assert(!list_empty(&ctx->outstanding_streams));
915 wimlib_assert(ctx->num_outstanding_messages != 0);
917 DEBUG2("Receiving more compressed chunks");
918 cur_lte = container_of(ctx->outstanding_streams.next,
919 struct wim_lookup_table_entry,
920 being_compressed_list);
922 /* Get the next message from the queue and process it.
923 * The message will contain 1 or more data chunks that have been
925 msg = shared_queue_get(ctx->compressed_res_queue);
926 msg->complete = true;
927 --ctx->num_outstanding_messages;
929 DEBUG2("recved msg %p", msg);
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)
968 DEBUG2("Finish wim chunk tab");
970 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
976 list_del(&cur_lte->being_compressed_list);
978 if (res_csize >= wim_resource_size(cur_lte)) {
979 /* Oops! We compressed the resource to
980 * larger than the original size. Write
981 * the resource uncompressed instead. */
982 ret = write_uncompressed_resource_and_truncate(
985 ctx->cur_chunk_tab->file_offset,
986 &cur_lte->output_resource_entry);
992 cur_lte->output_resource_entry.size =
995 cur_lte->output_resource_entry.original_size =
996 cur_lte->resource_entry.original_size;
998 cur_lte->output_resource_entry.offset =
999 ctx->cur_chunk_tab->file_offset;
1001 cur_lte->output_resource_entry.flags =
1002 cur_lte->resource_entry.flags |
1003 WIM_RESHDR_FLAG_COMPRESSED;
1005 do_write_streams_progress(ctx->progress, ctx->progress_func,
1006 wim_resource_size(cur_lte));
1007 FREE(ctx->cur_chunk_tab);
1008 ctx->cur_chunk_tab = NULL;
1010 /* Since we just finished writing a stream, write any
1011 * streams that have been added to the serial_streams
1012 * list for direct writing by the main thread (e.g.
1013 * resources that don't need to be compressed because
1014 * the desired compression type is the same as the
1015 * previous compression type). */
1016 ret = do_write_stream_list_serial(&ctx->serial_streams,
1020 ctx->write_resource_flags,
1025 if (list_empty(&ctx->outstanding_streams)) {
1028 cur_lte = container_of(ctx->outstanding_streams.next,
1029 struct wim_lookup_table_entry,
1030 being_compressed_list);
1031 #ifdef ENABLE_MORE_DEBUG
1032 DEBUG2("Advance to stream:");
1033 print_lookup_table_entry(cur_lte, stderr);
1042 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1044 struct main_writer_thread_ctx *ctx = _ctx;
1046 struct message *next_msg;
1047 u64 next_chunk_in_msg;
1049 DEBUG2("chunk_size=%zu, wim_resource_size(next_lte)=%"PRIu64,
1050 chunk_size, wim_resource_size(ctx->next_lte));
1052 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1053 next_msg = ctx->next_msg;
1055 /* Start filling in a new message */
1057 DEBUG2("Start new msg");
1059 while (list_empty(&ctx->available_msgs)) {
1060 /* No message available; receive messages, writing
1061 * compressed data. */
1062 DEBUG2("No msgs available!");
1063 ret = receive_compressed_chunks(ctx);
1068 next_msg = container_of(ctx->available_msgs.next,
1069 struct message, list);
1070 list_del(&next_msg->list);
1071 next_msg->complete = false;
1072 next_msg->begin_chunk = ctx->next_chunk;
1073 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1074 ctx->next_num_chunks - ctx->next_chunk);
1075 DEBUG2("next_msg {begin_chunk=%"PRIu64", num_chunks=%"PRIu64"}",
1076 next_msg->begin_chunk, next_msg->num_chunks);
1077 ctx->next_msg = next_msg;
1080 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1082 /* Fill in the next chunk to compress */
1083 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1084 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1087 if (++next_chunk_in_msg == next_msg->num_chunks) {
1088 DEBUG2("Sending message %p", next_msg);
1089 /* Send off an array of chunks to compress */
1090 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1091 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1092 ++ctx->num_outstanding_messages;
1093 ctx->next_msg = NULL;
1099 main_writer_thread_finish(void *_ctx)
1101 struct main_writer_thread_ctx *ctx = _ctx;
1103 DEBUG2("finishing");
1104 while (ctx->num_outstanding_messages != 0) {
1105 ret = receive_compressed_chunks(ctx);
1109 wimlib_assert(list_empty(&ctx->outstanding_streams));
1110 return do_write_stream_list_serial(&ctx->serial_streams,
1114 ctx->write_resource_flags,
1120 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1121 struct main_writer_thread_ctx *ctx)
1125 #ifdef ENABLE_MORE_DEBUG
1126 DEBUG2("Submit for compression:");
1127 print_lookup_table_entry(lte, stderr);
1130 sha1_init(&ctx->next_sha_ctx);
1131 ctx->next_chunk = 0;
1132 ctx->next_num_chunks = wim_resource_chunks(lte);
1133 ctx->next_lte = lte;
1134 INIT_LIST_HEAD(<e->msg_list);
1135 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1136 ret = read_resource_prefix(lte, wim_resource_size(lte),
1137 main_writer_thread_cb, ctx, 0);
1139 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1140 ret = finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1146 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1148 struct main_writer_thread_ctx *ctx = _ctx;
1151 if (wim_resource_size(lte) < 1000 ||
1152 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1153 (lte->resource_location == RESOURCE_IN_WIM &&
1154 !(ctx->write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
1155 wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
1157 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1161 ret = submit_stream_for_compression(lte, ctx);
1167 get_default_num_threads()
1170 return win32_get_number_of_processors();
1172 return sysconf(_SC_NPROCESSORS_ONLN);
1177 write_stream_list_parallel(struct list_head *stream_list,
1178 struct wim_lookup_table *lookup_table,
1181 int write_resource_flags,
1182 wimlib_progress_func_t progress_func,
1183 union wimlib_progress_info *progress,
1184 unsigned num_threads)
1187 struct shared_queue res_to_compress_queue;
1188 struct shared_queue compressed_res_queue;
1189 pthread_t *compressor_threads = NULL;
1191 if (num_threads == 0) {
1192 long nthreads = get_default_num_threads();
1193 if (nthreads < 1 || nthreads > UINT_MAX) {
1194 WARNING("Could not determine number of processors! Assuming 1");
1197 num_threads = nthreads;
1201 progress->write_streams.num_threads = num_threads;
1203 static const size_t MESSAGES_PER_THREAD = 2;
1204 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1206 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1208 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1212 ret = shared_queue_init(&compressed_res_queue, queue_size);
1214 goto out_destroy_res_to_compress_queue;
1216 struct compressor_thread_params params;
1217 params.res_to_compress_queue = &res_to_compress_queue;
1218 params.compressed_res_queue = &compressed_res_queue;
1219 params.compress = get_compress_func(out_ctype);
1221 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1222 if (!compressor_threads) {
1223 ret = WIMLIB_ERR_NOMEM;
1224 goto out_destroy_compressed_res_queue;
1227 for (unsigned i = 0; i < num_threads; i++) {
1228 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1229 ret = pthread_create(&compressor_threads[i], NULL,
1230 compressor_thread_proc, ¶ms);
1233 ERROR_WITH_ERRNO("Failed to create compressor "
1235 i + 1, num_threads);
1242 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1244 struct main_writer_thread_ctx ctx;
1245 ctx.stream_list = stream_list;
1246 ctx.lookup_table = lookup_table;
1247 ctx.out_fp = out_fp;
1248 ctx.out_ctype = out_ctype;
1249 ctx.res_to_compress_queue = &res_to_compress_queue;
1250 ctx.compressed_res_queue = &compressed_res_queue;
1251 ctx.num_messages = queue_size;
1252 ctx.write_resource_flags = write_resource_flags | WIMLIB_RESOURCE_FLAG_THREADSAFE_READ;
1253 ctx.progress_func = progress_func;
1254 ctx.progress = progress;
1255 ret = main_writer_thread_init_ctx(&ctx);
1258 ret = do_write_stream_list(stream_list, lookup_table,
1259 main_thread_process_next_stream,
1262 goto out_destroy_ctx;
1263 ret = main_writer_thread_finish(&ctx);
1265 main_writer_thread_destroy_ctx(&ctx);
1267 for (unsigned i = 0; i < num_threads; i++)
1268 shared_queue_put(&res_to_compress_queue, NULL);
1270 for (unsigned i = 0; i < num_threads; i++) {
1271 if (pthread_join(compressor_threads[i], NULL)) {
1272 WARNING_WITH_ERRNO("Failed to join compressor "
1274 i + 1, num_threads);
1277 FREE(compressor_threads);
1278 out_destroy_compressed_res_queue:
1279 shared_queue_destroy(&compressed_res_queue);
1280 out_destroy_res_to_compress_queue:
1281 shared_queue_destroy(&res_to_compress_queue);
1282 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1285 WARNING("Falling back to single-threaded compression");
1286 return write_stream_list_serial(stream_list,
1290 write_resource_flags,
1298 * Write a list of streams to a WIM (@out_fp) using the compression type
1299 * @out_ctype and up to @num_threads compressor threads.
1302 write_stream_list(struct list_head *stream_list,
1303 struct wim_lookup_table *lookup_table,
1304 FILE *out_fp, int out_ctype, int write_flags,
1305 unsigned num_threads, wimlib_progress_func_t progress_func)
1307 struct wim_lookup_table_entry *lte;
1308 size_t num_streams = 0;
1309 u64 total_bytes = 0;
1310 u64 total_compression_bytes = 0;
1311 union wimlib_progress_info progress;
1313 int write_resource_flags;
1315 if (list_empty(stream_list))
1318 write_resource_flags = write_flags_to_resource_flags(write_flags);
1320 /* Calculate the total size of the streams to be written. Note: this
1321 * will be the uncompressed size, as we may not know the compressed size
1322 * yet, and also this will assume that every unhashed stream will be
1323 * written (which will not necessarily be the case). */
1324 list_for_each_entry(lte, stream_list, write_streams_list) {
1326 total_bytes += wim_resource_size(lte);
1327 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1328 && (wim_resource_compression_type(lte) != out_ctype ||
1329 (write_resource_flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS)))
1331 total_compression_bytes += wim_resource_size(lte);
1334 progress.write_streams.total_bytes = total_bytes;
1335 progress.write_streams.total_streams = num_streams;
1336 progress.write_streams.completed_bytes = 0;
1337 progress.write_streams.completed_streams = 0;
1338 progress.write_streams.num_threads = num_threads;
1339 progress.write_streams.compression_type = out_ctype;
1340 progress.write_streams._private = 0;
1342 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1343 if (total_compression_bytes >= 1000000 && num_threads != 1)
1344 ret = write_stream_list_parallel(stream_list,
1348 write_resource_flags,
1354 ret = write_stream_list_serial(stream_list,
1358 write_resource_flags,
1364 struct stream_size_table {
1365 struct hlist_head *array;
1371 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1373 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1375 return WIMLIB_ERR_NOMEM;
1376 tab->num_entries = 0;
1377 tab->capacity = capacity;
1382 destroy_stream_size_table(struct stream_size_table *tab)
1388 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1390 struct stream_size_table *tab = _tab;
1392 struct wim_lookup_table_entry *same_size_lte;
1393 struct hlist_node *tmp;
1395 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1396 lte->unique_size = 1;
1397 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1398 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1399 lte->unique_size = 0;
1400 same_size_lte->unique_size = 0;
1405 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1411 struct lte_overwrite_prepare_args {
1414 struct list_head stream_list;
1415 struct stream_size_table stream_size_tab;
1418 /* First phase of preparing streams for an in-place overwrite. This is called
1419 * on all streams, both hashed and unhashed, except the metadata resources. */
1421 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
1423 struct lte_overwrite_prepare_args *args = _args;
1425 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1426 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1427 list_add_tail(<e->write_streams_list, &args->stream_list);
1428 lte->out_refcnt = lte->refcnt;
1429 stream_size_table_insert(lte, &args->stream_size_tab);
1433 /* Second phase of preparing streams for an in-place overwrite. This is called
1434 * on existing metadata resources and hashed streams, but not unhashed streams.
1436 * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
1437 * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
1438 * the latter uses lte->hash_list_2, while the former expects to set
1439 * lte->output_resource_entry. */
1441 lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
1443 struct lte_overwrite_prepare_args *args = _args;
1445 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
1446 /* We can't do an in place overwrite on the WIM if there are
1447 * streams after the XML data. */
1448 if (lte->resource_entry.offset +
1449 lte->resource_entry.size > args->end_offset)
1451 #ifdef ENABLE_ERROR_MESSAGES
1452 ERROR("The following resource is after the XML data:");
1453 print_lookup_table_entry(lte, stderr);
1455 return WIMLIB_ERR_RESOURCE_ORDER;
1457 copy_resource_entry(<e->output_resource_entry,
1458 <e->resource_entry);
1463 /* Given a WIM that we are going to overwrite in place with zero or more
1464 * additional streams added, construct a list the list of new unique streams
1465 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1466 * streams that need to be added but may be identical to other hashed or
1467 * unhashed streams. These unhashed streams are checksummed while the streams
1468 * are being written. To aid this process, the member @unique_size is set to 1
1469 * on streams that have a unique size and therefore must be written.
1471 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1472 * indicate the number of times the stream is referenced in only the streams
1473 * that are being written; this may still be adjusted later when unhashed
1474 * streams are being resolved.
1477 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1478 struct list_head *stream_list)
1481 struct lte_overwrite_prepare_args args;
1485 args.end_offset = end_offset;
1486 ret = init_stream_size_table(&args.stream_size_tab,
1487 wim->lookup_table->capacity);
1491 INIT_LIST_HEAD(&args.stream_list);
1492 for (i = 0; i < wim->hdr.image_count; i++) {
1493 struct wim_image_metadata *imd;
1494 struct wim_lookup_table_entry *lte;
1496 imd = wim->image_metadata[i];
1497 image_for_each_unhashed_stream(lte, imd)
1498 lte_overwrite_prepare(lte, &args);
1500 for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
1501 list_transfer(&args.stream_list, stream_list);
1503 for (i = 0; i < wim->hdr.image_count; i++) {
1504 ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
1507 goto out_destroy_stream_size_table;
1509 ret = for_lookup_table_entry(wim->lookup_table,
1510 lte_overwrite_prepare_2, &args);
1511 out_destroy_stream_size_table:
1512 destroy_stream_size_table(&args.stream_size_tab);
1517 struct find_streams_ctx {
1518 struct list_head stream_list;
1519 struct stream_size_table stream_size_tab;
1523 inode_find_streams_to_write(struct wim_inode *inode,
1524 struct wim_lookup_table *table,
1525 struct list_head *stream_list,
1526 struct stream_size_table *tab)
1528 struct wim_lookup_table_entry *lte;
1529 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1530 lte = inode_stream_lte(inode, i, table);
1532 if (lte->out_refcnt == 0) {
1534 stream_size_table_insert(lte, tab);
1535 list_add_tail(<e->write_streams_list, stream_list);
1537 lte->out_refcnt += inode->i_nlink;
1543 image_find_streams_to_write(WIMStruct *w)
1545 struct find_streams_ctx *ctx;
1546 struct wim_image_metadata *imd;
1547 struct wim_inode *inode;
1548 struct wim_lookup_table_entry *lte;
1551 imd = wim_get_current_image_metadata(w);
1553 image_for_each_unhashed_stream(lte, imd)
1554 lte->out_refcnt = 0;
1556 /* Go through this image's inodes to find any streams that have not been
1558 image_for_each_inode(inode, imd) {
1559 inode_find_streams_to_write(inode, w->lookup_table,
1561 &ctx->stream_size_tab);
1566 /* Given a WIM that from which one or all of the images is being written, build
1567 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1568 * written, plus any unhashed streams that need to be written but may be
1569 * identical to other hashed or unhashed streams being written. These unhashed
1570 * streams are checksummed while the streams are being written. To aid this
1571 * process, the member @unique_size is set to 1 on streams that have a unique
1572 * size and therefore must be written.
1574 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1575 * indicate the number of times the stream is referenced in only the streams
1576 * that are being written; this may still be adjusted later when unhashed
1577 * streams are being resolved.
1580 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1583 struct find_streams_ctx ctx;
1585 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1586 ret = init_stream_size_table(&ctx.stream_size_tab,
1587 wim->lookup_table->capacity);
1590 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1591 &ctx.stream_size_tab);
1592 INIT_LIST_HEAD(&ctx.stream_list);
1593 wim->private = &ctx;
1594 ret = for_image(wim, image, image_find_streams_to_write);
1595 destroy_stream_size_table(&ctx.stream_size_tab);
1597 list_transfer(&ctx.stream_list, stream_list);
1601 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1604 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1605 unsigned num_threads,
1606 wimlib_progress_func_t progress_func)
1609 struct list_head stream_list;
1611 ret = prepare_stream_list(wim, image, &stream_list);
1614 return write_stream_list(&stream_list,
1617 wimlib_get_compression_type(wim),
1624 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1625 * table (optional), then overwrite the WIM header.
1627 * write_flags is a bitwise OR of the following:
1629 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1630 * Include an integrity table.
1632 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1633 * Show progress information when (if) writing the integrity table.
1635 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1636 * Don't write the lookup table.
1638 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1639 * When (if) writing the integrity table, re-use entries from the
1640 * existing integrity table, if possible.
1642 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1643 * After writing the XML data but before writing the integrity
1644 * table, write a temporary WIM header and flush the stream so that
1645 * the WIM is less likely to become corrupted upon abrupt program
1648 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1649 * fsync() the output file before closing it.
1653 finish_write(WIMStruct *w, int image, int write_flags,
1654 wimlib_progress_func_t progress_func)
1657 struct wim_header hdr;
1658 FILE *out = w->out_fp;
1660 /* @hdr will be the header for the new WIM. First copy all the data
1661 * from the header in the WIMStruct; then set all the fields that may
1662 * have changed, including the resource entries, boot index, and image
1664 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1666 /* Set image count and boot index correctly for single image writes */
1667 if (image != WIMLIB_ALL_IMAGES) {
1668 hdr.image_count = 1;
1669 if (hdr.boot_idx == image)
1675 /* In the WIM header, there is room for the resource entry for a
1676 * metadata resource labeled as the "boot metadata". This entry should
1677 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1678 * it should be a copy of the resource entry for the image that is
1679 * marked as bootable. This is not well documented... */
1680 if (hdr.boot_idx == 0) {
1681 zero_resource_entry(&hdr.boot_metadata_res_entry);
1683 copy_resource_entry(&hdr.boot_metadata_res_entry,
1684 &w->image_metadata[ hdr.boot_idx- 1
1685 ]->metadata_lte->output_resource_entry);
1688 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1689 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1694 ret = write_xml_data(w->wim_info, image, out,
1695 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1696 wim_info_get_total_bytes(w->wim_info) : 0,
1697 &hdr.xml_res_entry);
1701 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1702 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1703 struct wim_header checkpoint_hdr;
1704 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1705 zero_resource_entry(&checkpoint_hdr.integrity);
1706 if (fseeko(out, 0, SEEK_SET)) {
1707 ERROR_WITH_ERRNO("Failed to seek to beginning "
1708 "of WIM being written");
1709 ret = WIMLIB_ERR_WRITE;
1712 ret = write_header(&checkpoint_hdr, out);
1716 if (fflush(out) != 0) {
1717 ERROR_WITH_ERRNO("Can't write data to WIM");
1718 ret = WIMLIB_ERR_WRITE;
1722 if (fseeko(out, 0, SEEK_END) != 0) {
1723 ERROR_WITH_ERRNO("Failed to seek to end "
1724 "of WIM being written");
1725 ret = WIMLIB_ERR_WRITE;
1730 off_t old_lookup_table_end;
1731 off_t new_lookup_table_end;
1732 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1733 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1734 w->hdr.lookup_table_res_entry.size;
1736 old_lookup_table_end = 0;
1738 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1739 hdr.lookup_table_res_entry.size;
1741 ret = write_integrity_table(out,
1743 new_lookup_table_end,
1744 old_lookup_table_end,
1749 zero_resource_entry(&hdr.integrity);
1752 if (fseeko(out, 0, SEEK_SET) != 0) {
1753 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1755 ret = WIMLIB_ERR_WRITE;
1759 ret = write_header(&hdr, out);
1763 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1764 if (fflush(out) != 0
1765 || fsync(fileno(out)) != 0)
1767 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1768 ret = WIMLIB_ERR_WRITE;
1772 if (fclose(out) != 0) {
1773 ERROR_WITH_ERRNO("Failed to close the output WIM file");
1775 ret = WIMLIB_ERR_WRITE;
1781 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1783 lock_wim(WIMStruct *w, FILE *fp)
1786 if (fp && !w->wim_locked) {
1787 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1789 if (errno == EWOULDBLOCK) {
1790 ERROR("`%"TS"' is already being modified or has been "
1791 "mounted read-write\n"
1792 " by another process!", w->filename);
1793 ret = WIMLIB_ERR_ALREADY_LOCKED;
1795 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1808 open_wim_writable(WIMStruct *w, const tchar *path,
1809 bool trunc, bool also_readable)
1820 wimlib_assert(w->out_fp == NULL);
1821 w->out_fp = tfopen(path, mode);
1825 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1826 return WIMLIB_ERR_OPEN;
1832 close_wim_writable(WIMStruct *w)
1835 if (fclose(w->out_fp) != 0) {
1836 WARNING_WITH_ERRNO("Failed to close output WIM");
1842 /* Open file stream and write dummy header for WIM. */
1844 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1847 ret = open_wim_writable(w, path, true,
1848 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1851 /* Write dummy header. It will be overwritten later. */
1852 return write_header(&w->hdr, w->out_fp);
1855 /* Writes a stand-alone WIM to a file. */
1857 wimlib_write(WIMStruct *w, const tchar *path,
1858 int image, int write_flags, unsigned num_threads,
1859 wimlib_progress_func_t progress_func)
1864 return WIMLIB_ERR_INVALID_PARAM;
1866 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1868 if (image != WIMLIB_ALL_IMAGES &&
1869 (image < 1 || image > w->hdr.image_count))
1870 return WIMLIB_ERR_INVALID_IMAGE;
1872 if (w->hdr.total_parts != 1) {
1873 ERROR("Cannot call wimlib_write() on part of a split WIM");
1874 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1877 ret = begin_write(w, path, write_flags);
1881 ret = write_wim_streams(w, image, write_flags, num_threads,
1887 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1889 ret = for_image(w, image, write_metadata_resource);
1894 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1896 ret = finish_write(w, image, write_flags, progress_func);
1897 /* finish_write() closed the WIM for us */
1900 close_wim_writable(w);
1902 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1907 any_images_modified(WIMStruct *w)
1909 for (int i = 0; i < w->hdr.image_count; i++)
1910 if (w->image_metadata[i]->modified)
1916 * Overwrite a WIM, possibly appending streams to it.
1918 * A WIM looks like (or is supposed to look like) the following:
1920 * Header (212 bytes)
1921 * Streams and metadata resources (variable size)
1922 * Lookup table (variable size)
1923 * XML data (variable size)
1924 * Integrity table (optional) (variable size)
1926 * If we are not adding any streams or metadata resources, the lookup table is
1927 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1928 * header. This operation is potentially unsafe if the program is abruptly
1929 * terminated while the XML data or integrity table are being overwritten, but
1930 * before the new header has been written. To partially alleviate this problem,
1931 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1932 * finish_write() to cause a temporary WIM header to be written after the XML
1933 * data has been written. This may prevent the WIM from becoming corrupted if
1934 * the program is terminated while the integrity table is being calculated (but
1935 * no guarantees, due to write re-ordering...).
1937 * If we are adding new streams or images (metadata resources), the lookup table
1938 * needs to be changed, and those streams need to be written. In this case, we
1939 * try to perform a safe update of the WIM file by writing the streams *after*
1940 * the end of the previous WIM, then writing the new lookup table, XML data, and
1941 * (optionally) integrity table following the new streams. This will produce a
1942 * layout like the following:
1944 * Header (212 bytes)
1945 * (OLD) Streams and metadata resources (variable size)
1946 * (OLD) Lookup table (variable size)
1947 * (OLD) XML data (variable size)
1948 * (OLD) Integrity table (optional) (variable size)
1949 * (NEW) Streams and metadata resources (variable size)
1950 * (NEW) Lookup table (variable size)
1951 * (NEW) XML data (variable size)
1952 * (NEW) Integrity table (optional) (variable size)
1954 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1955 * the header is overwritten to point to the new lookup table, XML data, and
1956 * integrity table, to produce the following layout:
1958 * Header (212 bytes)
1959 * Streams and metadata resources (variable size)
1960 * Nothing (variable size)
1961 * More Streams and metadata resources (variable size)
1962 * Lookup table (variable size)
1963 * XML data (variable size)
1964 * Integrity table (optional) (variable size)
1966 * This method allows an image to be appended to a large WIM very quickly, and
1967 * is is crash-safe except in the case of write re-ordering, but the
1968 * disadvantage is that a small hole is left in the WIM where the old lookup
1969 * table, xml data, and integrity table were. (These usually only take up a
1970 * small amount of space compared to the streams, however.)
1973 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1974 unsigned num_threads,
1975 wimlib_progress_func_t progress_func)
1978 struct list_head stream_list;
1980 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
1982 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1984 /* Make sure that the integrity table (if present) is after the XML
1985 * data, and that there are no stream resources, metadata resources, or
1986 * lookup tables after the XML data. Otherwise, these data would be
1988 old_xml_begin = w->hdr.xml_res_entry.offset;
1989 old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
1990 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1991 w->hdr.lookup_table_res_entry.size;
1992 if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
1993 ERROR("Didn't expect the integrity table to be before the XML data");
1994 return WIMLIB_ERR_RESOURCE_ORDER;
1997 if (old_lookup_table_end > old_xml_begin) {
1998 ERROR("Didn't expect the lookup table to be after the XML data");
1999 return WIMLIB_ERR_RESOURCE_ORDER;
2002 /* Set @old_wim_end, which indicates the point beyond which we don't
2003 * allow any file and metadata resources to appear without returning
2004 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2005 * overwrite these resources). */
2006 if (!w->deletion_occurred && !any_images_modified(w)) {
2007 /* If no images have been modified and no images have been
2008 * deleted, a new lookup table does not need to be written. We
2009 * shall write the new XML data and optional integrity table
2010 * immediately after the lookup table. Note that this may
2011 * overwrite an existing integrity table. */
2012 DEBUG("Skipping writing lookup table "
2013 "(no images modified or deleted)");
2014 old_wim_end = old_lookup_table_end;
2015 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2016 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2017 } else if (w->hdr.integrity.offset) {
2018 /* Old WIM has an integrity table; begin writing new streams
2020 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
2022 /* No existing integrity table; begin writing new streams after
2023 * the old XML data. */
2024 old_wim_end = old_xml_end;
2027 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2031 ret = open_wim_writable(w, w->filename, false,
2032 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
2036 ret = lock_wim(w, w->out_fp);
2038 close_wim_writable(w);
2042 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
2043 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2044 close_wim_writable(w);
2046 return WIMLIB_ERR_WRITE;
2049 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2051 ret = write_stream_list(&stream_list,
2054 wimlib_get_compression_type(w),
2061 for (int i = 0; i < w->hdr.image_count; i++) {
2062 if (w->image_metadata[i]->modified) {
2063 select_wim_image(w, i + 1);
2064 ret = write_metadata_resource(w);
2069 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2070 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2073 close_wim_writable(w);
2074 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2075 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2076 w->filename, old_wim_end);
2077 /* Return value of truncate() is ignored because this is already
2079 (void)ttruncate(w->filename, old_wim_end);
2086 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2087 unsigned num_threads,
2088 wimlib_progress_func_t progress_func)
2090 size_t wim_name_len;
2093 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2095 /* Write the WIM to a temporary file in the same directory as the
2097 wim_name_len = tstrlen(w->filename);
2098 tchar tmpfile[wim_name_len + 10];
2099 tmemcpy(tmpfile, w->filename, wim_name_len);
2100 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2101 tmpfile[wim_name_len + 9] = T('\0');
2103 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2104 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2105 num_threads, progress_func);
2107 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2111 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2114 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2115 * specified to CreateFile(). The WIM was opened with fopen(), which
2116 * didn't provided this flag to CreateFile, so the handle must be closed
2117 * before executing the rename(). */
2118 if (w->fp != NULL) {
2124 /* Rename the new file to the old file .*/
2125 if (trename(tmpfile, w->filename) != 0) {
2126 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2127 tmpfile, w->filename);
2128 ret = WIMLIB_ERR_RENAME;
2132 if (progress_func) {
2133 union wimlib_progress_info progress;
2134 progress.rename.from = tmpfile;
2135 progress.rename.to = w->filename;
2136 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2139 /* Close the original WIM file that was opened for reading. */
2140 if (w->fp != NULL) {
2145 /* Re-open the WIM read-only. */
2146 w->fp = tfopen(w->filename, T("rb"));
2147 if (w->fp == NULL) {
2148 ret = WIMLIB_ERR_REOPEN;
2149 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2156 /* Remove temporary file. */
2157 if (tunlink(tmpfile) != 0)
2158 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2164 * Writes a WIM file to the original file that it was read from, overwriting it.
2167 wimlib_overwrite(WIMStruct *w, int write_flags,
2168 unsigned num_threads,
2169 wimlib_progress_func_t progress_func)
2171 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2174 return WIMLIB_ERR_NO_FILENAME;
2176 if (w->hdr.total_parts != 1) {
2177 ERROR("Cannot modify a split WIM");
2178 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2181 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2182 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2185 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2187 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2188 WARNING("Falling back to re-building entire WIM");
2192 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,