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);
103 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
105 ret = WIMLIB_ERR_NOMEM;
108 chunk_tab->file_offset = file_offset;
109 chunk_tab->num_chunks = num_chunks;
110 chunk_tab->original_resource_size = size;
111 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
112 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
114 chunk_tab->cur_offset = 0;
115 chunk_tab->cur_offset_p = chunk_tab->offsets;
117 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
118 chunk_tab->table_disk_size) {
119 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
122 ret = WIMLIB_ERR_WRITE;
127 *chunk_tab_ret = chunk_tab;
133 * compress_func_t- Pointer to a function to compresses a chunk
134 * of a WIM resource. This may be either
135 * wimlib_xpress_compress() (xpress-compress.c) or
136 * wimlib_lzx_compress() (lzx-compress.c).
138 * @chunk: Uncompressed data of the chunk.
139 * @chunk_size: Size of the uncompressed chunk, in bytes.
140 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
142 * Returns the size of the compressed data written to @out in bytes, or 0 if the
143 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
145 * As a special requirement, the compression code is optimized for the WIM
146 * format and therefore requires (@chunk_size <= 32768).
148 * As another special requirement, the compression code will read up to 8 bytes
149 * off the end of the @chunk array for performance reasons. The values of these
150 * bytes will not affect the output of the compression, but the calling code
151 * must make sure that the buffer holding the uncompressed chunk is actually at
152 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
153 * mapped memory that will not cause a memory access violation if accessed.
155 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
159 get_compress_func(int out_ctype)
161 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
162 return wimlib_lzx_compress;
164 return wimlib_xpress_compress;
168 * Writes a chunk of a WIM resource to an output file.
170 * @chunk: Uncompressed data of the chunk.
171 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
172 * @out_fp: FILE * to write the chunk to.
173 * @compress: Compression function to use (NULL if writing uncompressed
175 * @chunk_tab: Pointer to chunk table being created. It is updated with the
176 * offset of the chunk we write.
178 * Returns 0 on success; nonzero on failure.
181 write_wim_resource_chunk(const void *chunk, unsigned chunk_size,
182 FILE *out_fp, compress_func_t compress,
183 struct chunk_table *chunk_tab)
186 unsigned out_chunk_size;
188 u8 *compressed_chunk = alloca(chunk_size);
190 out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
191 if (out_chunk_size) {
192 /* Write compressed */
193 out_chunk = compressed_chunk;
195 /* Write uncompressed */
197 out_chunk_size = chunk_size;
199 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
200 chunk_tab->cur_offset += out_chunk_size;
202 /* Write uncompressed */
204 out_chunk_size = chunk_size;
206 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
207 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
208 return WIMLIB_ERR_WRITE;
214 * Finishes a WIM chunk table and writes it to the output file at the correct
217 * The final size of the full compressed resource is returned in the
218 * @compressed_size_p.
221 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
222 FILE *out_fp, u64 *compressed_size_p)
224 size_t bytes_written;
225 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
226 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
227 "WIM file", chunk_tab->file_offset);
228 return WIMLIB_ERR_WRITE;
231 if (chunk_tab->bytes_per_chunk_entry == 8) {
232 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
234 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
235 ((u32*)chunk_tab->offsets)[i] =
236 cpu_to_le32(chunk_tab->offsets[i]);
238 bytes_written = fwrite((u8*)chunk_tab->offsets +
239 chunk_tab->bytes_per_chunk_entry,
240 1, chunk_tab->table_disk_size, out_fp);
241 if (bytes_written != chunk_tab->table_disk_size) {
242 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
244 return WIMLIB_ERR_WRITE;
246 if (fseeko(out_fp, 0, SEEK_END) != 0) {
247 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
248 return WIMLIB_ERR_WRITE;
250 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
254 struct write_resource_ctx {
255 compress_func_t compress;
256 struct chunk_table *chunk_tab;
263 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
265 struct write_resource_ctx *ctx = _ctx;
268 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
271 return write_wim_resource_chunk(chunk, chunk_size,
272 ctx->out_fp, ctx->compress,
275 if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
276 ERROR_WITH_ERRNO("Error writing to output WIM");
277 return WIMLIB_ERR_WRITE;
285 * Write a resource to an output WIM.
287 * @lte: Lookup table entry for the resource, which could be in another WIM,
288 * in an external file, or in another location.
290 * @out_fp: FILE * opened to the output WIM.
292 * @out_ctype: One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
293 * which compression algorithm to use.
295 * @out_res_entry: On success, this is filled in with the offset, flags,
296 * compressed size, and uncompressed size of the resource
299 * @flags: WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
300 * even if it could otherwise be copied directly from the input.
302 * Additional notes: The SHA1 message digest of the uncompressed data is
303 * calculated (except when doing a raw copy --- see below). If the @unhashed
304 * flag is set on the lookup table entry, this message digest is simply copied
305 * to it; otherwise, the message digest is compared with the existing one, and
306 * the function will fail if they do not match.
309 write_wim_resource(struct wim_lookup_table_entry *lte,
310 FILE *out_fp, int out_ctype,
311 struct resource_entry *out_res_entry,
314 struct write_resource_ctx write_ctx;
320 flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
322 if (wim_resource_size(lte) == 0) {
323 /* Empty resource; nothing needs to be done, so just return
328 /* Get current position in output WIM */
329 offset = ftello(out_fp);
331 ERROR_WITH_ERRNO("Can't get position in output WIM");
332 return WIMLIB_ERR_WRITE;
335 /* If we are not forcing the data to be recompressed, and the input
336 * resource is located in a WIM with the same compression type as that
337 * desired other than no compression, we can simply copy the compressed
338 * data without recompressing it. This also means we must skip
339 * calculating the SHA1, as we never will see the uncompressed data. */
340 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
341 lte->resource_location == RESOURCE_IN_WIM &&
342 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
343 wimlib_get_compression_type(lte->wim) == out_ctype)
345 flags |= WIMLIB_RESOURCE_FLAG_RAW;
346 write_ctx.doing_sha = false;
347 read_size = lte->resource_entry.size;
349 write_ctx.doing_sha = true;
350 sha1_init(&write_ctx.sha_ctx);
351 read_size = lte->resource_entry.original_size;
354 /* Initialize the chunk table and set the compression function if
355 * compressing the resource. */
356 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
357 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
358 write_ctx.compress = NULL;
359 write_ctx.chunk_tab = NULL;
361 write_ctx.compress = get_compress_func(out_ctype);
362 ret = begin_wim_resource_chunk_tab(lte, out_fp,
364 &write_ctx.chunk_tab);
369 /* Write the entire resource by reading the entire resource and feeding
370 * the data through the write_resource_cb function. */
371 write_ctx.out_fp = out_fp;
373 ret = read_resource_prefix(lte, read_size,
374 write_resource_cb, &write_ctx, flags);
376 goto out_free_chunk_tab;
378 /* Verify SHA1 message digest of the resource, or set the hash for the
380 if (write_ctx.doing_sha) {
381 u8 md[SHA1_HASH_SIZE];
382 sha1_final(md, &write_ctx.sha_ctx);
384 copy_hash(lte->hash, md);
385 } else if (!hashes_equal(md, lte->hash)) {
386 ERROR("WIM resource has incorrect hash!");
387 if (lte_filename_valid(lte)) {
388 ERROR("We were reading it from \"%"TS"\"; maybe "
389 "it changed while we were reading it.",
392 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
393 goto out_free_chunk_tab;
397 out_res_entry->flags = lte->resource_entry.flags;
398 out_res_entry->original_size = wim_resource_size(lte);
399 out_res_entry->offset = offset;
400 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
401 /* Doing a raw write: The new compressed size is the same as
402 * the compressed size in the other WIM. */
403 new_size = lte->resource_entry.size;
404 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
405 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
406 * is the original size. */
407 new_size = lte->resource_entry.original_size;
408 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
410 /* Using a different compression type: Call
411 * finish_wim_resource_chunk_tab() and it will provide the new
412 * compressed size. */
413 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
416 goto out_free_chunk_tab;
417 if (new_size >= wim_resource_size(lte)) {
418 /* Oops! We compressed the resource to larger than the original
419 * size. Write the resource uncompressed instead. */
420 if (fseeko(out_fp, offset, SEEK_SET) ||
422 ftruncate(fileno(out_fp),
423 offset + wim_resource_size(lte)))
425 ERROR_WITH_ERRNO("Failed to flush and/or truncate "
427 ret = WIMLIB_ERR_WRITE;
428 goto out_free_chunk_tab;
430 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
431 "writing uncompressed instead",
432 wim_resource_size(lte), new_size);
433 write_ctx.compress = NULL;
434 write_ctx.doing_sha = false;
435 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
436 goto try_write_again;
438 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
440 out_res_entry->size = new_size;
443 FREE(write_ctx.chunk_tab);
447 #ifdef ENABLE_MULTITHREADED_COMPRESSION
449 /* Blocking shared queue (solves the producer-consumer problem) */
450 struct shared_queue {
454 unsigned filled_slots;
456 pthread_mutex_t lock;
457 pthread_cond_t msg_avail_cond;
458 pthread_cond_t space_avail_cond;
462 shared_queue_init(struct shared_queue *q, unsigned size)
464 wimlib_assert(size != 0);
465 q->array = CALLOC(sizeof(q->array[0]), size);
467 return WIMLIB_ERR_NOMEM;
472 pthread_mutex_init(&q->lock, NULL);
473 pthread_cond_init(&q->msg_avail_cond, NULL);
474 pthread_cond_init(&q->space_avail_cond, NULL);
479 shared_queue_destroy(struct shared_queue *q)
482 pthread_mutex_destroy(&q->lock);
483 pthread_cond_destroy(&q->msg_avail_cond);
484 pthread_cond_destroy(&q->space_avail_cond);
488 shared_queue_put(struct shared_queue *q, void *obj)
490 pthread_mutex_lock(&q->lock);
491 while (q->filled_slots == q->size)
492 pthread_cond_wait(&q->space_avail_cond, &q->lock);
494 q->back = (q->back + 1) % q->size;
495 q->array[q->back] = obj;
498 pthread_cond_broadcast(&q->msg_avail_cond);
499 pthread_mutex_unlock(&q->lock);
503 shared_queue_get(struct shared_queue *q)
507 pthread_mutex_lock(&q->lock);
508 while (q->filled_slots == 0)
509 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
511 obj = q->array[q->front];
512 q->array[q->front] = NULL;
513 q->front = (q->front + 1) % q->size;
516 pthread_cond_broadcast(&q->space_avail_cond);
517 pthread_mutex_unlock(&q->lock);
521 struct compressor_thread_params {
522 struct shared_queue *res_to_compress_queue;
523 struct shared_queue *compressed_res_queue;
524 compress_func_t compress;
527 #define MAX_CHUNKS_PER_MSG 2
530 struct wim_lookup_table_entry *lte;
531 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
532 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
533 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
534 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
535 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
537 struct list_head list;
543 compress_chunks(struct message *msg, compress_func_t compress)
545 for (unsigned i = 0; i < msg->num_chunks; i++) {
546 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
547 unsigned len = compress(msg->uncompressed_chunks[i],
548 msg->uncompressed_chunk_sizes[i],
549 msg->compressed_chunks[i]);
551 /* To be written compressed */
552 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
553 msg->compressed_chunk_sizes[i] = len;
555 /* To be written uncompressed */
556 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
557 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
563 /* Compressor thread routine. This is a lot simpler than the main thread
564 * routine: just repeatedly get a group of chunks from the
565 * res_to_compress_queue, compress them, and put them in the
566 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
569 compressor_thread_proc(void *arg)
571 struct compressor_thread_params *params = arg;
572 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
573 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
574 compress_func_t compress = params->compress;
577 DEBUG("Compressor thread ready");
578 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
579 compress_chunks(msg, compress);
580 shared_queue_put(compressed_res_queue, msg);
582 DEBUG("Compressor thread terminating");
585 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
588 do_write_streams_progress(union wimlib_progress_info *progress,
589 wimlib_progress_func_t progress_func,
592 progress->write_streams.completed_bytes += size_added;
593 progress->write_streams.completed_streams++;
595 progress->write_streams.completed_bytes >= progress->write_streams._private)
597 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
599 if (progress->write_streams._private == progress->write_streams.total_bytes) {
600 progress->write_streams._private = ~0;
602 progress->write_streams._private =
603 min(progress->write_streams.total_bytes,
604 progress->write_streams.completed_bytes +
605 progress->write_streams.total_bytes / 100);
612 STREAMS_NOT_MERGED = 1,
616 do_write_stream_list(struct list_head *stream_list,
617 struct wim_lookup_table *lookup_table,
620 wimlib_progress_func_t progress_func,
621 union wimlib_progress_info *progress,
622 int write_resource_flags)
625 struct wim_lookup_table_entry *lte;
627 /* For each stream in @stream_list ... */
628 while (!list_empty(stream_list)) {
629 lte = container_of(stream_list->next,
630 struct wim_lookup_table_entry,
632 list_del(<e->write_streams_list);
633 if (lte->unhashed && !lte->unique_size) {
634 /* Unhashed stream that shares a size with some other
635 * stream in the WIM we are writing. The stream must be
636 * checksummed to know if we need to write it or not. */
637 struct wim_lookup_table_entry *tmp;
638 u32 orig_refcnt = lte->out_refcnt;
640 ret = hash_unhashed_stream(lte,
647 /* We found a duplicate stream. */
648 if (orig_refcnt != tmp->out_refcnt) {
649 /* We have already written, or are going
650 * to write, the duplicate stream. So
651 * just skip to the next stream. */
652 DEBUG("Discarding duplicate stream of length %"PRIu64,
653 wim_resource_size(lte));
654 goto skip_to_progress;
659 /* Here, @lte is either a hashed stream or an unhashed stream
660 * with a unique size. In either case we know that the stream
661 * has to be written. In either case the SHA1 message digest
662 * will be calculated over the stream while writing it; however,
663 * in the former case this is done merely to check the data,
664 * while in the latter case this is done because we do not have
665 * the SHA1 message digest yet. */
666 wimlib_assert(lte->out_refcnt != 0);
667 ret = write_wim_resource(lte,
670 <e->output_resource_entry,
671 write_resource_flags);
675 list_del(<e->unhashed_list);
676 lookup_table_insert(lookup_table, lte);
680 do_write_streams_progress(progress,
682 wim_resource_size(lte));
688 write_stream_list_serial(struct list_head *stream_list,
689 struct wim_lookup_table *lookup_table,
693 wimlib_progress_func_t progress_func,
694 union wimlib_progress_info *progress)
696 int write_resource_flags = 0;
697 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
698 write_resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
700 progress->write_streams.num_threads = 1;
702 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
703 return do_write_stream_list(stream_list,
706 out_ctype, progress_func,
707 progress, write_resource_flags);
710 #ifdef ENABLE_MULTITHREADED_COMPRESSION
712 write_wim_chunks(struct message *msg, FILE *out_fp,
713 struct chunk_table *chunk_tab)
715 for (unsigned i = 0; i < msg->num_chunks; i++) {
716 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
718 DEBUG2("Write wim chunk %u of %u (csize = %u)",
719 i, msg->num_chunks, chunk_csize);
721 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
724 ERROR_WITH_ERRNO("Failed to write WIM chunk");
725 return WIMLIB_ERR_WRITE;
728 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
729 chunk_tab->cur_offset += chunk_csize;
735 * This function is executed by the main thread when the resources are being
736 * compressed in parallel. The main thread is in change of all reading of the
737 * uncompressed data and writing of the compressed data. The compressor threads
738 * *only* do compression from/to in-memory buffers.
740 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
741 * chunks of compressed data to compress, represented in a `struct message'.
742 * Each message is passed from the main thread to a worker thread through the
743 * res_to_compress_queue, and it is passed back through the
744 * compressed_res_queue.
747 main_writer_thread_proc(struct list_head *stream_list,
750 struct shared_queue *res_to_compress_queue,
751 struct shared_queue *compressed_res_queue,
754 wimlib_progress_func_t progress_func,
755 union wimlib_progress_info *progress)
758 struct chunk_table *cur_chunk_tab = NULL;
759 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
760 struct wim_lookup_table_entry *next_lte = NULL;
762 // Initially, all the messages are available to use.
763 LIST_HEAD(available_msgs);
766 ret = WIMLIB_ERR_NOMEM;
770 for (size_t i = 0; i < num_messages; i++)
771 list_add(&msgs[i].list, &available_msgs);
773 // outstanding_resources is the list of resources that currently have
774 // had chunks sent off for compression.
776 // The first stream in outstanding_resources is the stream that is
777 // currently being written (cur_lte).
779 // The last stream in outstanding_resources is the stream that is
780 // currently being read and chunks fed to the compressor threads
783 // Depending on the number of threads and the sizes of the resource,
784 // the outstanding streams list may contain streams between cur_lte and
785 // next_lte that have all their chunks compressed or being compressed,
786 // but haven't been written yet.
788 LIST_HEAD(outstanding_resources);
789 struct list_head *next_resource = stream_list->next;
791 u64 next_num_chunks = 0;
793 // As in write_wim_resource(), each resource we read is checksummed.
794 SHA_CTX next_sha_ctx;
795 u8 next_hash[SHA1_HASH_SIZE];
797 // Resources that don't need any chunks compressed are added to this
798 // list and written directly by the main thread.
799 LIST_HEAD(my_resources);
801 struct wim_lookup_table_entry *cur_lte = NULL;
805 ntfs_inode *ni = NULL;
808 DEBUG("Initializing buffers for uncompressed "
809 "and compressed data (%zu bytes needed)",
810 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
812 // Pre-allocate all the buffers that will be needed to do the chunk
814 for (size_t i = 0; i < num_messages; i++) {
815 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
816 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
818 // The extra 8 bytes is because longest_match() in
819 // lz77.c may read a little bit off the end of the
820 // uncompressed data. It doesn't need to be
821 // initialized--- we really just need to avoid accessing
823 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
824 if (msgs[i].compressed_chunks[j] == NULL ||
825 msgs[i].uncompressed_chunks[j] == NULL)
827 ret = WIMLIB_ERR_NOMEM;
833 // This loop is executed until all resources have been written, except
834 // possibly a few that have been added to the @my_resources list for
837 // Send chunks to the compressor threads until either (a) there
838 // are no more messages available since they were all sent off,
839 // or (b) there are no more resources that need to be
841 while (!list_empty(&available_msgs)) {
842 if (next_chunk == next_num_chunks) {
843 // If next_chunk == next_num_chunks, there are
844 // no more chunks to write in the current
845 // stream. So, check the SHA1 message digest of
846 // the stream that was just finished (unless
847 // next_lte == NULL, which is the case the very
848 // first time this loop is entered, and also
849 // near the very end of the compression when
850 // there are no more streams.) Then, advance to
851 // the next stream (if there is one).
852 if (next_lte != NULL) {
854 end_wim_resource_read(next_lte, ni);
857 end_wim_resource_read(next_lte);
859 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
861 sha1_final(next_hash, &next_sha_ctx);
862 if (!hashes_equal(next_lte->hash, next_hash)) {
863 ERROR("WIM resource has incorrect hash!");
864 if (next_lte->resource_location ==
865 RESOURCE_IN_FILE_ON_DISK)
867 ERROR("We were reading it from `%"TS"'; "
868 "maybe it changed while we were "
870 next_lte->file_on_disk);
872 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
877 // Advance to the next resource.
879 // If the next resource needs no compression, just write
880 // it with this thread (not now though--- we could be in
881 // the middle of writing another resource.) Keep doing
882 // this until we either get to the end of the resources
883 // list, or we get to a resource that needs compression.
885 if (next_resource == stream_list) {
886 // No more resources to send for
891 next_lte = container_of(next_resource,
892 struct wim_lookup_table_entry,
894 next_resource = next_resource->next;
895 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
896 && wim_resource_compression_type(next_lte) == out_ctype)
897 || wim_resource_size(next_lte) == 0)
899 list_add_tail(&next_lte->write_streams_list,
902 list_add_tail(&next_lte->write_streams_list,
903 &outstanding_resources);
905 next_num_chunks = wim_resource_chunks(next_lte);
906 sha1_init(&next_sha_ctx);
907 INIT_LIST_HEAD(&next_lte->msg_list);
909 ret = prepare_resource_for_read(next_lte, &ni);
911 ret = prepare_resource_for_read(next_lte);
916 if (cur_lte == NULL) {
917 // Set cur_lte for the
926 if (next_lte == NULL) {
927 // No more resources to send for compression
931 // Get a message from the available messages
933 msg = container_of(available_msgs.next,
937 // ... and delete it from the available messages
939 list_del(&msg->list);
941 // Initialize the message with the chunks to
943 msg->num_chunks = min(next_num_chunks - next_chunk,
946 msg->complete = false;
947 msg->begin_chunk = next_chunk;
949 unsigned size = WIM_CHUNK_SIZE;
950 for (unsigned i = 0; i < msg->num_chunks; i++) {
952 // Read chunk @next_chunk of the stream into the
953 // message so that a compressor thread can
956 if (next_chunk == next_num_chunks - 1) {
957 size = MODULO_NONZERO(wim_resource_size(next_lte),
961 DEBUG2("Read resource (size=%u, offset=%zu)",
962 size, next_chunk * WIM_CHUNK_SIZE);
964 msg->uncompressed_chunk_sizes[i] = size;
966 ret = read_wim_resource(next_lte,
967 msg->uncompressed_chunks[i],
969 next_chunk * WIM_CHUNK_SIZE,
973 sha1_update(&next_sha_ctx,
974 msg->uncompressed_chunks[i], size);
978 // Send the compression request
979 list_add_tail(&msg->list, &next_lte->msg_list);
980 shared_queue_put(res_to_compress_queue, msg);
981 DEBUG2("Compression request sent");
984 // If there are no outstanding resources, there are no more
985 // resources that need to be written.
986 if (list_empty(&outstanding_resources)) {
991 // Get the next message from the queue and process it.
992 // The message will contain 1 or more data chunks that have been
994 msg = shared_queue_get(compressed_res_queue);
995 msg->complete = true;
997 // Is this the next chunk in the current resource? If it's not
998 // (i.e., an earlier chunk in a same or different resource
999 // hasn't been compressed yet), do nothing, and keep this
1000 // message around until all earlier chunks are received.
1002 // Otherwise, write all the chunks we can.
1003 while (cur_lte != NULL &&
1004 !list_empty(&cur_lte->msg_list) &&
1005 (msg = container_of(cur_lte->msg_list.next,
1009 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1010 if (msg->begin_chunk == 0) {
1011 DEBUG2("Begin chunk tab");
1013 // This is the first set of chunks. Leave space
1014 // for the chunk table in the output file.
1015 off_t cur_offset = ftello(out_fp);
1016 if (cur_offset == -1) {
1017 ret = WIMLIB_ERR_WRITE;
1020 ret = begin_wim_resource_chunk_tab(cur_lte,
1028 // Write the compressed chunks from the message.
1029 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1033 list_del(&msg->list);
1035 // This message is available to use for different chunks
1037 list_add(&msg->list, &available_msgs);
1039 // Was this the last chunk of the stream? If so, finish
1041 if (list_empty(&cur_lte->msg_list) &&
1042 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1044 DEBUG2("Finish wim chunk tab");
1046 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1052 if (res_csize >= wim_resource_size(cur_lte)) {
1053 /* Oops! We compressed the resource to
1054 * larger than the original size. Write
1055 * the resource uncompressed instead. */
1056 ret = write_uncompressed_resource_and_truncate(
1059 cur_chunk_tab->file_offset,
1060 &cur_lte->output_resource_entry);
1064 cur_lte->output_resource_entry.size =
1067 cur_lte->output_resource_entry.original_size =
1068 cur_lte->resource_entry.original_size;
1070 cur_lte->output_resource_entry.offset =
1071 cur_chunk_tab->file_offset;
1073 cur_lte->output_resource_entry.flags =
1074 cur_lte->resource_entry.flags |
1075 WIM_RESHDR_FLAG_COMPRESSED;
1078 do_write_streams_progress(progress, progress_func,
1079 wim_resource_size(cur_lte));
1081 FREE(cur_chunk_tab);
1082 cur_chunk_tab = NULL;
1084 struct list_head *next = cur_lte->write_streams_list.next;
1085 list_del(&cur_lte->write_streams_list);
1087 if (next == &outstanding_resources)
1090 cur_lte = container_of(cur_lte->write_streams_list.next,
1091 struct wim_lookup_table_entry,
1092 write_streams_list);
1094 // Since we just finished writing a stream,
1095 // write any streams that have been added to the
1096 // my_resources list for direct writing by the
1097 // main thread (e.g. resources that don't need
1098 // to be compressed because the desired
1099 // compression type is the same as the previous
1100 // compression type).
1101 ret = do_write_stream_list(&my_resources,
1114 if (ret == WIMLIB_ERR_NOMEM) {
1115 ERROR("Could not allocate enough memory for "
1116 "multi-threaded compression");
1121 end_wim_resource_read(next_lte, ni);
1123 end_wim_resource_read(next_lte);
1128 ret = do_write_stream_list(&my_resources, out_fp,
1129 out_ctype, progress_func,
1133 size_t num_available_msgs = 0;
1134 struct list_head *cur;
1136 list_for_each(cur, &available_msgs) {
1137 num_available_msgs++;
1140 while (num_available_msgs < num_messages) {
1141 shared_queue_get(compressed_res_queue);
1142 num_available_msgs++;
1148 for (size_t i = 0; i < num_messages; i++) {
1149 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1150 FREE(msgs[i].compressed_chunks[j]);
1151 FREE(msgs[i].uncompressed_chunks[j]);
1157 FREE(cur_chunk_tab);
1162 get_default_num_threads()
1165 return win32_get_number_of_processors();
1167 return sysconf(_SC_NPROCESSORS_ONLN);
1172 write_stream_list_parallel(struct list_head *stream_list,
1173 struct wim_lookup_table *lookup_table,
1177 unsigned num_threads,
1178 wimlib_progress_func_t progress_func,
1179 union wimlib_progress_info *progress)
1182 struct shared_queue res_to_compress_queue;
1183 struct shared_queue compressed_res_queue;
1184 pthread_t *compressor_threads = NULL;
1186 if (num_threads == 0) {
1187 long nthreads = get_default_num_threads();
1188 if (nthreads < 1 || nthreads > UINT_MAX) {
1189 WARNING("Could not determine number of processors! Assuming 1");
1192 num_threads = nthreads;
1196 progress->write_streams.num_threads = num_threads;
1197 wimlib_assert(stream_list->next != stream_list);
1199 static const double MESSAGES_PER_THREAD = 2.0;
1200 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1202 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1204 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1208 ret = shared_queue_init(&compressed_res_queue, queue_size);
1210 goto out_destroy_res_to_compress_queue;
1212 struct compressor_thread_params params;
1213 params.res_to_compress_queue = &res_to_compress_queue;
1214 params.compressed_res_queue = &compressed_res_queue;
1215 params.compress = get_compress_func(out_ctype);
1217 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1218 if (!compressor_threads) {
1219 ret = WIMLIB_ERR_NOMEM;
1220 goto out_destroy_compressed_res_queue;
1223 for (unsigned i = 0; i < num_threads; i++) {
1224 DEBUG("pthread_create thread %u", i);
1225 ret = pthread_create(&compressor_threads[i], NULL,
1226 compressor_thread_proc, ¶ms);
1229 ERROR_WITH_ERRNO("Failed to create compressor "
1237 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1239 ret = main_writer_thread_proc(stream_list,
1242 &res_to_compress_queue,
1243 &compressed_res_queue,
1249 for (unsigned i = 0; i < num_threads; i++)
1250 shared_queue_put(&res_to_compress_queue, NULL);
1252 for (unsigned i = 0; i < num_threads; i++) {
1253 if (pthread_join(compressor_threads[i], NULL)) {
1254 WARNING_WITH_ERRNO("Failed to join compressor "
1258 FREE(compressor_threads);
1259 out_destroy_compressed_res_queue:
1260 shared_queue_destroy(&compressed_res_queue);
1261 out_destroy_res_to_compress_queue:
1262 shared_queue_destroy(&res_to_compress_queue);
1263 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1266 WARNING("Falling back to single-threaded compression");
1267 return write_stream_list_serial(stream_list,
1279 * Write a list of streams to a WIM (@out_fp) using the compression type
1280 * @out_ctype and up to @num_threads compressor threads.
1283 write_stream_list(struct list_head *stream_list,
1284 struct wim_lookup_table *lookup_table,
1285 FILE *out_fp, int out_ctype, int write_flags,
1286 unsigned num_threads, wimlib_progress_func_t progress_func)
1288 struct wim_lookup_table_entry *lte;
1289 size_t num_streams = 0;
1290 u64 total_bytes = 0;
1291 u64 total_compression_bytes = 0;
1292 union wimlib_progress_info progress;
1295 if (list_empty(stream_list))
1298 list_for_each_entry(lte, stream_list, write_streams_list) {
1300 total_bytes += wim_resource_size(lte);
1301 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1302 && (wim_resource_compression_type(lte) != out_ctype ||
1303 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1305 total_compression_bytes += wim_resource_size(lte);
1308 progress.write_streams.total_bytes = total_bytes;
1309 progress.write_streams.total_streams = num_streams;
1310 progress.write_streams.completed_bytes = 0;
1311 progress.write_streams.completed_streams = 0;
1312 progress.write_streams.num_threads = num_threads;
1313 progress.write_streams.compression_type = out_ctype;
1314 progress.write_streams._private = 0;
1316 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1317 if (total_compression_bytes >= 1000000 && num_threads != 1)
1318 ret = write_stream_list_parallel(stream_list,
1328 ret = write_stream_list_serial(stream_list,
1338 struct stream_size_table {
1339 struct hlist_head *array;
1345 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1347 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1349 return WIMLIB_ERR_NOMEM;
1350 tab->num_entries = 0;
1351 tab->capacity = capacity;
1356 destroy_stream_size_table(struct stream_size_table *tab)
1362 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1364 struct stream_size_table *tab = _tab;
1366 struct wim_lookup_table_entry *hashed_lte;
1367 struct hlist_node *tmp;
1369 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1370 lte->unique_size = 1;
1371 hlist_for_each_entry(hashed_lte, tmp, &tab->array[pos], hash_list_2) {
1372 if (wim_resource_size(hashed_lte) == wim_resource_size(lte)) {
1373 lte->unique_size = 0;
1374 hashed_lte->unique_size = 0;
1379 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1385 struct lte_overwrite_prepare_args {
1388 struct list_head stream_list;
1389 struct stream_size_table stream_size_tab;
1393 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1395 struct lte_overwrite_prepare_args *args = arg;
1397 if (lte->resource_location == RESOURCE_IN_WIM &&
1398 lte->wim == args->wim)
1400 /* We can't do an in place overwrite on the WIM if there are
1401 * streams after the XML data. */
1402 if (lte->resource_entry.offset +
1403 lte->resource_entry.size > args->end_offset)
1405 #ifdef ENABLE_ERROR_MESSAGES
1406 ERROR("The following resource is after the XML data:");
1407 print_lookup_table_entry(lte, stderr);
1409 return WIMLIB_ERR_RESOURCE_ORDER;
1412 wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
1413 list_add_tail(<e->write_streams_list, &args->stream_list);
1415 lte->out_refcnt = lte->refcnt;
1416 stream_size_table_insert(lte, &args->stream_size_tab);
1421 lte_set_output_res_entry(struct wim_lookup_table_entry *lte, void *_wim)
1423 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == _wim) {
1424 copy_resource_entry(<e->output_resource_entry,
1425 <e->resource_entry);
1430 /* Given a WIM that we are going to overwrite in place with zero or more
1431 * additional streams added, construct a list the list of new unique streams
1432 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1433 * streams that need to be added but may be identical to other hashed or
1434 * unhashed streams. These unhashed streams are checksummed while the streams
1435 * are being written. To aid this process, the member @unique_size is set to 1
1436 * on streams that have a unique size and therefore must be written.
1438 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1439 * indicate the number of times the stream is referenced in only the streams
1440 * that are being written; this may still be adjusted later when unhashed
1441 * streams are being resolved.
1444 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1445 struct list_head *stream_list)
1448 struct lte_overwrite_prepare_args args;
1451 args.end_offset = end_offset;
1452 ret = init_stream_size_table(&args.stream_size_tab,
1453 wim->lookup_table->capacity);
1457 INIT_LIST_HEAD(&args.stream_list);
1458 for (int i = 0; i < wim->hdr.image_count; i++) {
1459 struct wim_image_metadata *imd;
1460 struct wim_lookup_table_entry *lte;
1462 imd = wim->image_metadata[i];
1463 image_for_each_unhashed_stream(lte, imd) {
1464 ret = lte_overwrite_prepare(lte, &args);
1466 goto out_destroy_stream_size_table;
1469 ret = for_lookup_table_entry(wim->lookup_table,
1470 lte_overwrite_prepare, &args);
1472 goto out_destroy_stream_size_table;
1474 for (int i = 0; i < wim->hdr.image_count; i++)
1475 lte_set_output_res_entry(wim->image_metadata[i]->metadata_lte,
1477 for_lookup_table_entry(wim->lookup_table, lte_set_output_res_entry, wim);
1478 INIT_LIST_HEAD(stream_list);
1479 list_splice(&args.stream_list, stream_list);
1480 out_destroy_stream_size_table:
1481 destroy_stream_size_table(&args.stream_size_tab);
1486 struct find_streams_ctx {
1487 struct list_head stream_list;
1488 struct stream_size_table stream_size_tab;
1492 inode_find_streams_to_write(struct wim_inode *inode,
1493 struct wim_lookup_table *table,
1494 struct list_head *stream_list,
1495 struct stream_size_table *tab)
1497 struct wim_lookup_table_entry *lte;
1498 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1499 lte = inode_stream_lte(inode, i, table);
1501 if (lte->out_refcnt == 0) {
1503 stream_size_table_insert(lte, tab);
1504 list_add_tail(<e->write_streams_list, stream_list);
1506 lte->out_refcnt += inode->i_nlink;
1512 image_find_streams_to_write(WIMStruct *w)
1514 struct wim_image_metadata *imd;
1515 struct find_streams_ctx *ctx;
1516 struct wim_inode *inode;
1517 struct wim_lookup_table_entry *lte;
1520 imd = wim_get_current_image_metadata(w);
1522 image_for_each_unhashed_stream(lte, imd)
1523 lte->out_refcnt = 0;
1525 /* Go through this image's inodes to find any streams that have not been
1527 image_for_each_inode(inode, imd) {
1528 inode_find_streams_to_write(inode, w->lookup_table,
1530 &ctx->stream_size_tab);
1535 /* Given a WIM that from which one or all of the images is being written, build
1536 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1537 * written, plus any unhashed streams that need to be written but may be
1538 * identical to other hashed or unhashed streams being written. These unhashed
1539 * streams are checksummed while the streams are being written. To aid this
1540 * process, the member @unique_size is set to 1 on streams that have a unique
1541 * size and therefore must be written.
1543 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1544 * indicate the number of times the stream is referenced in only the streams
1545 * that are being written; this may still be adjusted later when unhashed
1546 * streams are being resolved.
1549 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1552 struct find_streams_ctx ctx;
1554 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1555 ret = init_stream_size_table(&ctx.stream_size_tab,
1556 wim->lookup_table->capacity);
1559 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1560 &ctx.stream_size_tab);
1561 INIT_LIST_HEAD(&ctx.stream_list);
1562 wim->private = &ctx;
1563 ret = for_image(wim, image, image_find_streams_to_write);
1564 destroy_stream_size_table(&ctx.stream_size_tab);
1566 INIT_LIST_HEAD(stream_list);
1567 list_splice(&ctx.stream_list, stream_list);
1572 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1575 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1576 unsigned num_threads,
1577 wimlib_progress_func_t progress_func)
1580 struct list_head stream_list;
1582 ret = prepare_stream_list(wim, image, &stream_list);
1585 return write_stream_list(&stream_list,
1588 wimlib_get_compression_type(wim),
1595 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1596 * table (optional), then overwrite the WIM header.
1598 * write_flags is a bitwise OR of the following:
1600 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1601 * Include an integrity table.
1603 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1604 * Show progress information when (if) writing the integrity table.
1606 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1607 * Don't write the lookup table.
1609 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1610 * When (if) writing the integrity table, re-use entries from the
1611 * existing integrity table, if possible.
1613 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1614 * After writing the XML data but before writing the integrity
1615 * table, write a temporary WIM header and flush the stream so that
1616 * the WIM is less likely to become corrupted upon abrupt program
1619 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1620 * fsync() the output file before closing it.
1624 finish_write(WIMStruct *w, int image, int write_flags,
1625 wimlib_progress_func_t progress_func)
1628 struct wim_header hdr;
1629 FILE *out = w->out_fp;
1631 /* @hdr will be the header for the new WIM. First copy all the data
1632 * from the header in the WIMStruct; then set all the fields that may
1633 * have changed, including the resource entries, boot index, and image
1635 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1637 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1638 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1643 ret = write_xml_data(w->wim_info, image, out,
1644 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1645 wim_info_get_total_bytes(w->wim_info) : 0,
1646 &hdr.xml_res_entry);
1650 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1651 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1652 struct wim_header checkpoint_hdr;
1653 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1654 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1655 if (fseeko(out, 0, SEEK_SET)) {
1656 ERROR_WITH_ERRNO("Failed to seek to beginning "
1657 "of WIM being written");
1658 ret = WIMLIB_ERR_WRITE;
1661 ret = write_header(&checkpoint_hdr, out);
1665 if (fflush(out) != 0) {
1666 ERROR_WITH_ERRNO("Can't write data to WIM");
1667 ret = WIMLIB_ERR_WRITE;
1671 if (fseeko(out, 0, SEEK_END) != 0) {
1672 ERROR_WITH_ERRNO("Failed to seek to end "
1673 "of WIM being written");
1674 ret = WIMLIB_ERR_WRITE;
1679 off_t old_lookup_table_end;
1680 off_t new_lookup_table_end;
1681 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1682 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1683 w->hdr.lookup_table_res_entry.size;
1685 old_lookup_table_end = 0;
1687 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1688 hdr.lookup_table_res_entry.size;
1690 ret = write_integrity_table(out,
1692 new_lookup_table_end,
1693 old_lookup_table_end,
1698 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1702 * In the WIM header, there is room for the resource entry for a
1703 * metadata resource labeled as the "boot metadata". This entry should
1704 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1705 * it should be a copy of the resource entry for the image that is
1706 * marked as bootable. This is not well documented...
1709 /* Set image count and boot index correctly for single image writes */
1710 if (image != WIMLIB_ALL_IMAGES) {
1711 hdr.image_count = 1;
1712 if (hdr.boot_idx == image)
1718 if (hdr.boot_idx == 0) {
1719 memset(&hdr.boot_metadata_res_entry, 0,
1720 sizeof(struct resource_entry));
1722 memcpy(&hdr.boot_metadata_res_entry,
1724 hdr.boot_idx - 1]->metadata_lte->output_resource_entry,
1725 sizeof(struct resource_entry));
1728 if (fseeko(out, 0, SEEK_SET) != 0) {
1729 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1731 ret = WIMLIB_ERR_WRITE;
1735 ret = write_header(&hdr, out);
1739 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1740 if (fflush(out) != 0
1741 || fsync(fileno(out)) != 0)
1743 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1744 ret = WIMLIB_ERR_WRITE;
1748 if (fclose(out) != 0) {
1749 ERROR_WITH_ERRNO("Failed to close the WIM file");
1751 ret = WIMLIB_ERR_WRITE;
1757 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1759 lock_wim(WIMStruct *w, FILE *fp)
1762 if (fp && !w->wim_locked) {
1763 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1765 if (errno == EWOULDBLOCK) {
1766 ERROR("`%"TS"' is already being modified or has been "
1767 "mounted read-write\n"
1768 " by another process!", w->filename);
1769 ret = WIMLIB_ERR_ALREADY_LOCKED;
1771 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1784 open_wim_writable(WIMStruct *w, const tchar *path,
1785 bool trunc, bool also_readable)
1796 wimlib_assert(w->out_fp == NULL);
1797 w->out_fp = tfopen(path, mode);
1801 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1802 return WIMLIB_ERR_OPEN;
1808 close_wim_writable(WIMStruct *w)
1811 if (fclose(w->out_fp) != 0) {
1812 WARNING_WITH_ERRNO("Failed to close output WIM");
1818 /* Open file stream and write dummy header for WIM. */
1820 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1823 ret = open_wim_writable(w, path, true,
1824 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1827 /* Write dummy header. It will be overwritten later. */
1828 return write_header(&w->hdr, w->out_fp);
1831 /* Writes a stand-alone WIM to a file. */
1833 wimlib_write(WIMStruct *w, const tchar *path,
1834 int image, int write_flags, unsigned num_threads,
1835 wimlib_progress_func_t progress_func)
1840 return WIMLIB_ERR_INVALID_PARAM;
1842 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1844 if (image != WIMLIB_ALL_IMAGES &&
1845 (image < 1 || image > w->hdr.image_count))
1846 return WIMLIB_ERR_INVALID_IMAGE;
1848 if (w->hdr.total_parts != 1) {
1849 ERROR("Cannot call wimlib_write() on part of a split WIM");
1850 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1853 ret = begin_write(w, path, write_flags);
1857 ret = write_wim_streams(w, image, write_flags, num_threads,
1863 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1865 ret = for_image(w, image, write_metadata_resource);
1870 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1872 ret = finish_write(w, image, write_flags, progress_func);
1874 close_wim_writable(w);
1875 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1880 any_images_modified(WIMStruct *w)
1882 for (int i = 0; i < w->hdr.image_count; i++)
1883 if (w->image_metadata[i]->modified)
1889 * Overwrite a WIM, possibly appending streams to it.
1891 * A WIM looks like (or is supposed to look like) the following:
1893 * Header (212 bytes)
1894 * Streams and metadata resources (variable size)
1895 * Lookup table (variable size)
1896 * XML data (variable size)
1897 * Integrity table (optional) (variable size)
1899 * If we are not adding any streams or metadata resources, the lookup table is
1900 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1901 * header. This operation is potentially unsafe if the program is abruptly
1902 * terminated while the XML data or integrity table are being overwritten, but
1903 * before the new header has been written. To partially alleviate this problem,
1904 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1905 * finish_write() to cause a temporary WIM header to be written after the XML
1906 * data has been written. This may prevent the WIM from becoming corrupted if
1907 * the program is terminated while the integrity table is being calculated (but
1908 * no guarantees, due to write re-ordering...).
1910 * If we are adding new streams or images (metadata resources), the lookup table
1911 * needs to be changed, and those streams need to be written. In this case, we
1912 * try to perform a safe update of the WIM file by writing the streams *after*
1913 * the end of the previous WIM, then writing the new lookup table, XML data, and
1914 * (optionally) integrity table following the new streams. This will produce a
1915 * layout like the following:
1917 * Header (212 bytes)
1918 * (OLD) Streams and metadata resources (variable size)
1919 * (OLD) Lookup table (variable size)
1920 * (OLD) XML data (variable size)
1921 * (OLD) Integrity table (optional) (variable size)
1922 * (NEW) Streams and metadata resources (variable size)
1923 * (NEW) Lookup table (variable size)
1924 * (NEW) XML data (variable size)
1925 * (NEW) Integrity table (optional) (variable size)
1927 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1928 * the header is overwritten to point to the new lookup table, XML data, and
1929 * integrity table, to produce the following layout:
1931 * Header (212 bytes)
1932 * Streams and metadata resources (variable size)
1933 * Nothing (variable size)
1934 * More Streams and metadata resources (variable size)
1935 * Lookup table (variable size)
1936 * XML data (variable size)
1937 * Integrity table (optional) (variable size)
1939 * This method allows an image to be appended to a large WIM very quickly, and
1940 * is is crash-safe except in the case of write re-ordering, but the
1941 * disadvantage is that a small hole is left in the WIM where the old lookup
1942 * table, xml data, and integrity table were. (These usually only take up a
1943 * small amount of space compared to the streams, however.)
1946 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1947 unsigned num_threads,
1948 wimlib_progress_func_t progress_func)
1951 struct list_head stream_list;
1954 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1956 /* Make sure that the integrity table (if present) is after the XML
1957 * data, and that there are no stream resources, metadata resources, or
1958 * lookup tables after the XML data. Otherwise, these data would be
1960 if (w->hdr.integrity.offset != 0 &&
1961 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1962 ERROR("Didn't expect the integrity table to be before the XML data");
1963 return WIMLIB_ERR_RESOURCE_ORDER;
1966 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1967 ERROR("Didn't expect the lookup table to be after the XML data");
1968 return WIMLIB_ERR_RESOURCE_ORDER;
1972 if (w->hdr.integrity.offset)
1973 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1975 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1977 if (!w->deletion_occurred && !any_images_modified(w)) {
1978 /* If no images have been modified and no images have been
1979 * deleted, a new lookup table does not need to be written. */
1980 DEBUG("Skipping writing lookup table "
1981 "(no images modified or deleted)");
1982 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1983 w->hdr.lookup_table_res_entry.size;
1984 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1985 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1987 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
1991 ret = open_wim_writable(w, w->filename, false,
1992 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1996 ret = lock_wim(w, w->out_fp);
2003 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
2004 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2008 return WIMLIB_ERR_WRITE;
2011 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2013 ret = write_stream_list(&stream_list,
2016 wimlib_get_compression_type(w),
2023 for (int i = 0; i < w->hdr.image_count; i++) {
2024 if (w->image_metadata[i]->modified) {
2025 select_wim_image(w, i + 1);
2026 ret = write_metadata_resource(w);
2031 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2032 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2035 close_wim_writable(w);
2036 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2037 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2038 w->filename, old_wim_end);
2039 /* Return value of truncate() is ignored because this is already
2041 (void)ttruncate(w->filename, old_wim_end);
2048 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2049 unsigned num_threads,
2050 wimlib_progress_func_t progress_func)
2052 size_t wim_name_len;
2055 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2057 /* Write the WIM to a temporary file in the same directory as the
2059 wim_name_len = tstrlen(w->filename);
2060 tchar tmpfile[wim_name_len + 10];
2061 tmemcpy(tmpfile, w->filename, wim_name_len);
2062 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2063 tmpfile[wim_name_len + 9] = T('\0');
2065 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2066 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2067 num_threads, progress_func);
2069 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2073 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2076 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2077 * specified to CreateFile(). The WIM was opened with fopen(), which
2078 * didn't provided this flag to CreateFile, so the handle must be closed
2079 * before executing the rename(). */
2080 if (w->fp != NULL) {
2086 /* Rename the new file to the old file .*/
2087 if (trename(tmpfile, w->filename) != 0) {
2088 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2089 tmpfile, w->filename);
2090 ret = WIMLIB_ERR_RENAME;
2094 if (progress_func) {
2095 union wimlib_progress_info progress;
2096 progress.rename.from = tmpfile;
2097 progress.rename.to = w->filename;
2098 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2101 /* Close the original WIM file that was opened for reading. */
2102 if (w->fp != NULL) {
2107 /* Re-open the WIM read-only. */
2108 w->fp = tfopen(w->filename, T("rb"));
2109 if (w->fp == NULL) {
2110 ret = WIMLIB_ERR_REOPEN;
2111 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2118 /* Remove temporary file. */
2119 if (tunlink(tmpfile) != 0)
2120 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2125 * Writes a WIM file to the original file that it was read from, overwriting it.
2128 wimlib_overwrite(WIMStruct *w, int write_flags,
2129 unsigned num_threads,
2130 wimlib_progress_func_t progress_func)
2132 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2135 return WIMLIB_ERR_NO_FILENAME;
2137 if (w->hdr.total_parts != 1) {
2138 ERROR("Cannot modify a split WIM");
2139 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2142 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2143 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2146 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2148 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2149 WARNING("Falling back to re-building entire WIM");
2153 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,