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))
73 fflush_and_ftruncate(FILE *fp, off_t size)
79 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
80 return WIMLIB_ERR_WRITE;
82 ret = ftruncate(fileno(fp), size);
84 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
85 "%"PRIu64" bytes", size);
86 return WIMLIB_ERR_WRITE;
91 /* Chunk table that's located at the beginning of each compressed resource in
92 * the WIM. (This is not the on-disk format; the on-disk format just has an
93 * array of offsets.) */
97 u64 original_resource_size;
98 u64 bytes_per_chunk_entry;
106 * Allocates and initializes a chunk table, and reserves space for it in the
110 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
113 struct chunk_table **chunk_tab_ret)
115 u64 size = wim_resource_size(lte);
116 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
117 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
118 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
122 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
124 ret = WIMLIB_ERR_NOMEM;
127 chunk_tab->file_offset = file_offset;
128 chunk_tab->num_chunks = num_chunks;
129 chunk_tab->original_resource_size = size;
130 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
131 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
133 chunk_tab->cur_offset = 0;
134 chunk_tab->cur_offset_p = chunk_tab->offsets;
136 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
137 chunk_tab->table_disk_size) {
138 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
140 ret = WIMLIB_ERR_WRITE;
146 *chunk_tab_ret = chunk_tab;
151 * compress_func_t- Pointer to a function to compresses a chunk
152 * of a WIM resource. This may be either
153 * wimlib_xpress_compress() (xpress-compress.c) or
154 * wimlib_lzx_compress() (lzx-compress.c).
156 * @chunk: Uncompressed data of the chunk.
157 * @chunk_size: Size of the uncompressed chunk, in bytes.
158 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
160 * Returns the size of the compressed data written to @out in bytes, or 0 if the
161 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
163 * As a special requirement, the compression code is optimized for the WIM
164 * format and therefore requires (@chunk_size <= 32768).
166 * As another special requirement, the compression code will read up to 8 bytes
167 * off the end of the @chunk array for performance reasons. The values of these
168 * bytes will not affect the output of the compression, but the calling code
169 * must make sure that the buffer holding the uncompressed chunk is actually at
170 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
171 * mapped memory that will not cause a memory access violation if accessed.
173 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
177 get_compress_func(int out_ctype)
179 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
180 return wimlib_lzx_compress;
182 return wimlib_xpress_compress;
186 * Writes a chunk of a WIM resource to an output file.
188 * @chunk: Uncompressed data of the chunk.
189 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
190 * @out_fp: FILE * to write tho chunk to.
191 * @out_ctype: Compression type to use when writing the chunk (ignored if no
192 * chunk table provided)
193 * @chunk_tab: Pointer to chunk table being created. It is updated with the
194 * offset of the chunk we write.
196 * Returns 0 on success; nonzero on failure.
199 write_wim_resource_chunk(const void *chunk, unsigned chunk_size,
200 FILE *out_fp, compress_func_t compress,
201 struct chunk_table *chunk_tab)
204 unsigned out_chunk_size;
206 u8 *compressed_chunk = alloca(chunk_size);
208 out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
209 if (out_chunk_size) {
210 /* Write compressed */
211 out_chunk = compressed_chunk;
213 /* Write uncompressed */
215 out_chunk_size = chunk_size;
217 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
218 chunk_tab->cur_offset += out_chunk_size;
220 /* Write uncompressed */
222 out_chunk_size = chunk_size;
224 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
225 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
226 return WIMLIB_ERR_WRITE;
232 * Finishes a WIM chunk table and writes it to the output file at the correct
235 * The final size of the full compressed resource is returned in the
236 * @compressed_size_p.
239 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
240 FILE *out_fp, u64 *compressed_size_p)
242 size_t bytes_written;
243 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
244 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
245 "WIM file", chunk_tab->file_offset);
246 return WIMLIB_ERR_WRITE;
249 if (chunk_tab->bytes_per_chunk_entry == 8) {
250 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
252 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
253 ((u32*)chunk_tab->offsets)[i] =
254 cpu_to_le32(chunk_tab->offsets[i]);
256 bytes_written = fwrite((u8*)chunk_tab->offsets +
257 chunk_tab->bytes_per_chunk_entry,
258 1, chunk_tab->table_disk_size, out_fp);
259 if (bytes_written != chunk_tab->table_disk_size) {
260 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
262 return WIMLIB_ERR_WRITE;
264 if (fseeko(out_fp, 0, SEEK_END) != 0) {
265 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
266 return WIMLIB_ERR_WRITE;
268 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
273 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
276 struct resource_entry *out_res_entry)
279 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
280 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
281 "output WIM file", file_offset);
282 return WIMLIB_ERR_WRITE;
284 ret = write_wim_resource(lte, out_fp,
285 WIMLIB_COMPRESSION_TYPE_NONE,
291 return fflush_and_ftruncate(out_fp,
292 file_offset + wim_resource_size(lte));
295 struct write_resource_ctx {
296 compress_func_t compress;
297 struct chunk_table *chunk_tab;
304 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
306 struct write_resource_ctx *ctx = _ctx;
309 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
312 return write_wim_resource_chunk(chunk, chunk_size,
313 ctx->out_fp, ctx->compress,
316 if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
317 ERROR_WITH_ERRNO("Error writing to output WIM");
318 return WIMLIB_ERR_WRITE;
326 write_wim_resource(struct wim_lookup_table_entry *lte,
327 FILE *out_fp, int out_ctype,
328 struct resource_entry *out_res_entry,
331 struct write_resource_ctx write_ctx;
336 if (wim_resource_size(lte) == 0) {
337 /* Empty resource; nothing needs to be done, so just return
342 offset = ftello(out_fp);
344 ERROR_WITH_ERRNO("Can't get position in output WIM");
345 return WIMLIB_ERR_WRITE;
348 /* Can we simply copy the compressed data without recompressing it? */
350 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
351 lte->resource_location == RESOURCE_IN_WIM &&
352 wimlib_get_compression_type(lte->wim) == out_ctype)
354 flags |= WIMLIB_RESOURCE_FLAG_RAW;
355 write_ctx.doing_sha = false;
357 write_ctx.doing_sha = true;
358 sha1_init(&write_ctx.sha_ctx);
361 /* Initialize the chunk table and set the compression function if
362 * compressing the resource. */
363 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
364 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
365 write_ctx.compress = NULL;
366 write_ctx.chunk_tab = NULL;
368 write_ctx.compress = get_compress_func(out_ctype);
369 ret = begin_wim_resource_chunk_tab(lte, out_fp,
371 &write_ctx.chunk_tab);
377 write_ctx.out_fp = out_fp;
378 ret = read_resource_prefix(lte, wim_resource_size(lte),
379 write_resource_cb, &write_ctx, 0);
381 /* Verify SHA1 message digest of the resource, or set the hash for the
383 if (write_ctx.doing_sha) {
384 u8 md[SHA1_HASH_SIZE];
385 sha1_final(md, &write_ctx.sha_ctx);
387 copy_hash(lte->hash, md);
388 } else if (!hashes_equal(md, lte->hash)) {
389 ERROR("WIM resource has incorrect hash!");
390 if (lte_filename_valid(lte)) {
391 ERROR("We were reading it from \"%"TS"\"; maybe "
392 "it changed while we were reading it.",
395 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
396 goto out_free_chunk_tab;
400 out_res_entry->flags = lte->resource_entry.flags;
401 out_res_entry->original_size = wim_resource_size(lte);
402 out_res_entry->offset = offset;
403 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
404 /* Doing a raw write: The new compressed size is the same as
405 * the compressed size in the other WIM. */
406 new_size = lte->resource_entry.size;
407 out_res_entry->flags = lte->resource_entry.flags;
408 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
409 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
410 * is the original size. */
411 new_size = lte->resource_entry.original_size;
412 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
414 /* Using a different compression type: Call
415 * finish_wim_resource_chunk_tab() and it will provide the new
416 * compressed size. */
417 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
420 goto out_free_chunk_tab;
421 if (new_size >= wim_resource_size(lte)) {
422 /* Oops! We compressed the resource to larger than the original
423 * size. Write the resource uncompressed instead. */
424 ret = write_uncompressed_resource_and_truncate(lte,
428 goto out_free_chunk_tab;
430 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
432 out_res_entry->size = new_size;
435 FREE(write_ctx.chunk_tab);
439 #ifdef ENABLE_MULTITHREADED_COMPRESSION
441 /* Blocking shared queue (solves the producer-consumer problem) */
442 struct shared_queue {
446 unsigned filled_slots;
448 pthread_mutex_t lock;
449 pthread_cond_t msg_avail_cond;
450 pthread_cond_t space_avail_cond;
454 shared_queue_init(struct shared_queue *q, unsigned size)
456 wimlib_assert(size != 0);
457 q->array = CALLOC(sizeof(q->array[0]), size);
459 return WIMLIB_ERR_NOMEM;
464 pthread_mutex_init(&q->lock, NULL);
465 pthread_cond_init(&q->msg_avail_cond, NULL);
466 pthread_cond_init(&q->space_avail_cond, NULL);
471 shared_queue_destroy(struct shared_queue *q)
474 pthread_mutex_destroy(&q->lock);
475 pthread_cond_destroy(&q->msg_avail_cond);
476 pthread_cond_destroy(&q->space_avail_cond);
480 shared_queue_put(struct shared_queue *q, void *obj)
482 pthread_mutex_lock(&q->lock);
483 while (q->filled_slots == q->size)
484 pthread_cond_wait(&q->space_avail_cond, &q->lock);
486 q->back = (q->back + 1) % q->size;
487 q->array[q->back] = obj;
490 pthread_cond_broadcast(&q->msg_avail_cond);
491 pthread_mutex_unlock(&q->lock);
495 shared_queue_get(struct shared_queue *q)
499 pthread_mutex_lock(&q->lock);
500 while (q->filled_slots == 0)
501 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
503 obj = q->array[q->front];
504 q->array[q->front] = NULL;
505 q->front = (q->front + 1) % q->size;
508 pthread_cond_broadcast(&q->space_avail_cond);
509 pthread_mutex_unlock(&q->lock);
513 struct compressor_thread_params {
514 struct shared_queue *res_to_compress_queue;
515 struct shared_queue *compressed_res_queue;
516 compress_func_t compress;
519 #define MAX_CHUNKS_PER_MSG 2
522 struct wim_lookup_table_entry *lte;
523 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
524 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
525 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
526 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
527 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
529 struct list_head list;
535 compress_chunks(struct message *msg, compress_func_t compress)
537 for (unsigned i = 0; i < msg->num_chunks; i++) {
538 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
539 unsigned len = compress(msg->uncompressed_chunks[i],
540 msg->uncompressed_chunk_sizes[i],
541 msg->compressed_chunks[i]);
543 /* To be written compressed */
544 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
545 msg->compressed_chunk_sizes[i] = len;
547 /* To be written uncompressed */
548 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
549 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
555 /* Compressor thread routine. This is a lot simpler than the main thread
556 * routine: just repeatedly get a group of chunks from the
557 * res_to_compress_queue, compress them, and put them in the
558 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
561 compressor_thread_proc(void *arg)
563 struct compressor_thread_params *params = arg;
564 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
565 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
566 compress_func_t compress = params->compress;
569 DEBUG("Compressor thread ready");
570 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
571 compress_chunks(msg, compress);
572 shared_queue_put(compressed_res_queue, msg);
574 DEBUG("Compressor thread terminating");
577 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
580 do_write_streams_progress(union wimlib_progress_info *progress,
581 wimlib_progress_func_t progress_func,
584 progress->write_streams.completed_bytes += size_added;
585 progress->write_streams.completed_streams++;
587 progress->write_streams.completed_bytes >= progress->write_streams._private)
589 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
591 if (progress->write_streams._private == progress->write_streams.total_bytes) {
592 progress->write_streams._private = ~0;
594 progress->write_streams._private =
595 min(progress->write_streams.total_bytes,
596 progress->write_streams.completed_bytes +
597 progress->write_streams.total_bytes / 100);
603 sha1_chunk(const void *buf, size_t len, void *ctx)
605 sha1_update(ctx, buf, len);
610 sha1_resource(struct wim_lookup_table_entry *lte)
616 ret = read_resource_prefix(lte, wim_resource_size(lte),
617 sha1_chunk, &sha_ctx, 0);
619 sha1_final(lte->hash, &sha_ctx);
625 STREAMS_NOT_MERGED = 1,
629 do_write_stream_list(struct list_head *my_resources,
630 struct wim_lookup_table *lookup_table,
633 wimlib_progress_func_t progress_func,
634 union wimlib_progress_info *progress,
635 int write_resource_flags)
638 struct wim_lookup_table_entry *lte;
640 while (!list_empty(my_resources)) {
641 lte = container_of(my_resources->next,
642 struct wim_lookup_table_entry,
644 list_del(<e->write_streams_list);
645 if (lte->unhashed && !lte->unique_size) {
646 struct wim_lookup_table_entry *duplicate_lte;
648 ret = sha1_resource(lte);
651 list_del(<e->staging_list);
653 duplicate_lte = __lookup_resource(lookup_table, lte->hash);
655 bool new_stream = (duplicate_lte->out_refcnt == 0);
656 duplicate_lte->refcnt += lte->refcnt;
657 duplicate_lte->out_refcnt += lte->refcnt;
658 free_lookup_table_entry(lte);
665 lookup_table_insert(lookup_table, lte);
666 lte->out_refcnt = lte->refcnt;
671 wimlib_assert(lte->out_refcnt != 0);
673 ret = write_wim_resource(lte,
676 <e->output_resource_entry,
677 write_resource_flags);
681 wimlib_assert(__lookup_resource(lookup_table, lte->hash) == NULL);
682 lookup_table_insert(lookup_table, lte);
685 do_write_streams_progress(progress,
687 wim_resource_size(lte));
693 write_stream_list_serial(struct list_head *stream_list,
694 struct wim_lookup_table *lookup_table,
698 wimlib_progress_func_t progress_func,
699 union wimlib_progress_info *progress)
701 int write_resource_flags;
703 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
704 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
706 write_resource_flags = 0;
707 progress->write_streams.num_threads = 1;
709 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
710 return do_write_stream_list(stream_list,
713 out_ctype, progress_func,
714 progress, write_resource_flags);
717 #ifdef ENABLE_MULTITHREADED_COMPRESSION
719 write_wim_chunks(struct message *msg, FILE *out_fp,
720 struct chunk_table *chunk_tab)
722 for (unsigned i = 0; i < msg->num_chunks; i++) {
723 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
725 DEBUG2("Write wim chunk %u of %u (csize = %u)",
726 i, msg->num_chunks, chunk_csize);
728 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
731 ERROR_WITH_ERRNO("Failed to write WIM chunk");
732 return WIMLIB_ERR_WRITE;
735 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
736 chunk_tab->cur_offset += chunk_csize;
742 * This function is executed by the main thread when the resources are being
743 * compressed in parallel. The main thread is in change of all reading of the
744 * uncompressed data and writing of the compressed data. The compressor threads
745 * *only* do compression from/to in-memory buffers.
747 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
748 * chunks of compressed data to compress, represented in a `struct message'.
749 * Each message is passed from the main thread to a worker thread through the
750 * res_to_compress_queue, and it is passed back through the
751 * compressed_res_queue.
754 main_writer_thread_proc(struct list_head *stream_list,
757 struct shared_queue *res_to_compress_queue,
758 struct shared_queue *compressed_res_queue,
761 wimlib_progress_func_t progress_func,
762 union wimlib_progress_info *progress)
765 struct chunk_table *cur_chunk_tab = NULL;
766 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
767 struct wim_lookup_table_entry *next_lte = NULL;
769 // Initially, all the messages are available to use.
770 LIST_HEAD(available_msgs);
773 ret = WIMLIB_ERR_NOMEM;
777 for (size_t i = 0; i < num_messages; i++)
778 list_add(&msgs[i].list, &available_msgs);
780 // outstanding_resources is the list of resources that currently have
781 // had chunks sent off for compression.
783 // The first stream in outstanding_resources is the stream that is
784 // currently being written (cur_lte).
786 // The last stream in outstanding_resources is the stream that is
787 // currently being read and chunks fed to the compressor threads
790 // Depending on the number of threads and the sizes of the resource,
791 // the outstanding streams list may contain streams between cur_lte and
792 // next_lte that have all their chunks compressed or being compressed,
793 // but haven't been written yet.
795 LIST_HEAD(outstanding_resources);
796 struct list_head *next_resource = stream_list->next;
798 u64 next_num_chunks = 0;
800 // As in write_wim_resource(), each resource we read is checksummed.
801 SHA_CTX next_sha_ctx;
802 u8 next_hash[SHA1_HASH_SIZE];
804 // Resources that don't need any chunks compressed are added to this
805 // list and written directly by the main thread.
806 LIST_HEAD(my_resources);
808 struct wim_lookup_table_entry *cur_lte = NULL;
812 ntfs_inode *ni = NULL;
815 DEBUG("Initializing buffers for uncompressed "
816 "and compressed data (%zu bytes needed)",
817 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
819 // Pre-allocate all the buffers that will be needed to do the chunk
821 for (size_t i = 0; i < num_messages; i++) {
822 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
823 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
825 // The extra 8 bytes is because longest_match() in
826 // lz77.c may read a little bit off the end of the
827 // uncompressed data. It doesn't need to be
828 // initialized--- we really just need to avoid accessing
830 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
831 if (msgs[i].compressed_chunks[j] == NULL ||
832 msgs[i].uncompressed_chunks[j] == NULL)
834 ret = WIMLIB_ERR_NOMEM;
840 // This loop is executed until all resources have been written, except
841 // possibly a few that have been added to the @my_resources list for
844 // Send chunks to the compressor threads until either (a) there
845 // are no more messages available since they were all sent off,
846 // or (b) there are no more resources that need to be
848 while (!list_empty(&available_msgs)) {
849 if (next_chunk == next_num_chunks) {
850 // If next_chunk == next_num_chunks, there are
851 // no more chunks to write in the current
852 // stream. So, check the SHA1 message digest of
853 // the stream that was just finished (unless
854 // next_lte == NULL, which is the case the very
855 // first time this loop is entered, and also
856 // near the very end of the compression when
857 // there are no more streams.) Then, advance to
858 // the next stream (if there is one).
859 if (next_lte != NULL) {
861 end_wim_resource_read(next_lte, ni);
864 end_wim_resource_read(next_lte);
866 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
868 sha1_final(next_hash, &next_sha_ctx);
869 if (!hashes_equal(next_lte->hash, next_hash)) {
870 ERROR("WIM resource has incorrect hash!");
871 if (next_lte->resource_location ==
872 RESOURCE_IN_FILE_ON_DISK)
874 ERROR("We were reading it from `%"TS"'; "
875 "maybe it changed while we were "
877 next_lte->file_on_disk);
879 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
884 // Advance to the next resource.
886 // If the next resource needs no compression, just write
887 // it with this thread (not now though--- we could be in
888 // the middle of writing another resource.) Keep doing
889 // this until we either get to the end of the resources
890 // list, or we get to a resource that needs compression.
892 if (next_resource == stream_list) {
893 // No more resources to send for
898 next_lte = container_of(next_resource,
899 struct wim_lookup_table_entry,
901 next_resource = next_resource->next;
902 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
903 && wim_resource_compression_type(next_lte) == out_ctype)
904 || wim_resource_size(next_lte) == 0)
906 list_add_tail(&next_lte->staging_list,
909 list_add_tail(&next_lte->staging_list,
910 &outstanding_resources);
912 next_num_chunks = wim_resource_chunks(next_lte);
913 sha1_init(&next_sha_ctx);
914 INIT_LIST_HEAD(&next_lte->msg_list);
916 ret = prepare_resource_for_read(next_lte, &ni);
918 ret = prepare_resource_for_read(next_lte);
923 if (cur_lte == NULL) {
924 // Set cur_lte for the
933 if (next_lte == NULL) {
934 // No more resources to send for compression
938 // Get a message from the available messages
940 msg = container_of(available_msgs.next,
944 // ... and delete it from the available messages
946 list_del(&msg->list);
948 // Initialize the message with the chunks to
950 msg->num_chunks = min(next_num_chunks - next_chunk,
953 msg->complete = false;
954 msg->begin_chunk = next_chunk;
956 unsigned size = WIM_CHUNK_SIZE;
957 for (unsigned i = 0; i < msg->num_chunks; i++) {
959 // Read chunk @next_chunk of the stream into the
960 // message so that a compressor thread can
963 if (next_chunk == next_num_chunks - 1) {
964 size = MODULO_NONZERO(wim_resource_size(next_lte),
968 DEBUG2("Read resource (size=%u, offset=%zu)",
969 size, next_chunk * WIM_CHUNK_SIZE);
971 msg->uncompressed_chunk_sizes[i] = size;
973 ret = read_wim_resource(next_lte,
974 msg->uncompressed_chunks[i],
976 next_chunk * WIM_CHUNK_SIZE,
980 sha1_update(&next_sha_ctx,
981 msg->uncompressed_chunks[i], size);
985 // Send the compression request
986 list_add_tail(&msg->list, &next_lte->msg_list);
987 shared_queue_put(res_to_compress_queue, msg);
988 DEBUG2("Compression request sent");
991 // If there are no outstanding resources, there are no more
992 // resources that need to be written.
993 if (list_empty(&outstanding_resources)) {
998 // Get the next message from the queue and process it.
999 // The message will contain 1 or more data chunks that have been
1001 msg = shared_queue_get(compressed_res_queue);
1002 msg->complete = true;
1004 // Is this the next chunk in the current resource? If it's not
1005 // (i.e., an earlier chunk in a same or different resource
1006 // hasn't been compressed yet), do nothing, and keep this
1007 // message around until all earlier chunks are received.
1009 // Otherwise, write all the chunks we can.
1010 while (cur_lte != NULL &&
1011 !list_empty(&cur_lte->msg_list) &&
1012 (msg = container_of(cur_lte->msg_list.next,
1016 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1017 if (msg->begin_chunk == 0) {
1018 DEBUG2("Begin chunk tab");
1020 // This is the first set of chunks. Leave space
1021 // for the chunk table in the output file.
1022 off_t cur_offset = ftello(out_fp);
1023 if (cur_offset == -1) {
1024 ret = WIMLIB_ERR_WRITE;
1027 ret = begin_wim_resource_chunk_tab(cur_lte,
1035 // Write the compressed chunks from the message.
1036 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1040 list_del(&msg->list);
1042 // This message is available to use for different chunks
1044 list_add(&msg->list, &available_msgs);
1046 // Was this the last chunk of the stream? If so, finish
1048 if (list_empty(&cur_lte->msg_list) &&
1049 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1051 DEBUG2("Finish wim chunk tab");
1053 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1059 if (res_csize >= wim_resource_size(cur_lte)) {
1060 /* Oops! We compressed the resource to
1061 * larger than the original size. Write
1062 * the resource uncompressed instead. */
1063 ret = write_uncompressed_resource_and_truncate(
1066 cur_chunk_tab->file_offset,
1067 &cur_lte->output_resource_entry);
1071 cur_lte->output_resource_entry.size =
1074 cur_lte->output_resource_entry.original_size =
1075 cur_lte->resource_entry.original_size;
1077 cur_lte->output_resource_entry.offset =
1078 cur_chunk_tab->file_offset;
1080 cur_lte->output_resource_entry.flags =
1081 cur_lte->resource_entry.flags |
1082 WIM_RESHDR_FLAG_COMPRESSED;
1085 do_write_streams_progress(progress, progress_func,
1086 wim_resource_size(cur_lte));
1088 FREE(cur_chunk_tab);
1089 cur_chunk_tab = NULL;
1091 struct list_head *next = cur_lte->staging_list.next;
1092 list_del(&cur_lte->staging_list);
1094 if (next == &outstanding_resources)
1097 cur_lte = container_of(cur_lte->staging_list.next,
1098 struct wim_lookup_table_entry,
1101 // Since we just finished writing a stream,
1102 // write any streams that have been added to the
1103 // my_resources list for direct writing by the
1104 // main thread (e.g. resources that don't need
1105 // to be compressed because the desired
1106 // compression type is the same as the previous
1107 // compression type).
1108 ret = do_write_stream_list(&my_resources,
1121 if (ret == WIMLIB_ERR_NOMEM) {
1122 ERROR("Could not allocate enough memory for "
1123 "multi-threaded compression");
1128 end_wim_resource_read(next_lte, ni);
1130 end_wim_resource_read(next_lte);
1135 ret = do_write_stream_list(&my_resources, out_fp,
1136 out_ctype, progress_func,
1140 size_t num_available_msgs = 0;
1141 struct list_head *cur;
1143 list_for_each(cur, &available_msgs) {
1144 num_available_msgs++;
1147 while (num_available_msgs < num_messages) {
1148 shared_queue_get(compressed_res_queue);
1149 num_available_msgs++;
1155 for (size_t i = 0; i < num_messages; i++) {
1156 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1157 FREE(msgs[i].compressed_chunks[j]);
1158 FREE(msgs[i].uncompressed_chunks[j]);
1164 FREE(cur_chunk_tab);
1169 get_default_num_threads()
1172 return win32_get_number_of_processors();
1174 return sysconf(_SC_NPROCESSORS_ONLN);
1179 write_stream_list_parallel(struct list_head *stream_list,
1180 struct wim_lookup_table *lookup_table,
1184 unsigned num_threads,
1185 wimlib_progress_func_t progress_func,
1186 union wimlib_progress_info *progress)
1189 struct shared_queue res_to_compress_queue;
1190 struct shared_queue compressed_res_queue;
1191 pthread_t *compressor_threads = NULL;
1193 if (num_threads == 0) {
1194 long nthreads = get_default_num_threads();
1195 if (nthreads < 1 || nthreads > UINT_MAX) {
1196 WARNING("Could not determine number of processors! Assuming 1");
1199 num_threads = nthreads;
1203 progress->write_streams.num_threads = num_threads;
1204 wimlib_assert(stream_list->next != stream_list);
1206 static const double MESSAGES_PER_THREAD = 2.0;
1207 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1209 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1211 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1215 ret = shared_queue_init(&compressed_res_queue, queue_size);
1217 goto out_destroy_res_to_compress_queue;
1219 struct compressor_thread_params params;
1220 params.res_to_compress_queue = &res_to_compress_queue;
1221 params.compressed_res_queue = &compressed_res_queue;
1222 params.compress = get_compress_func(out_ctype);
1224 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1225 if (!compressor_threads) {
1226 ret = WIMLIB_ERR_NOMEM;
1227 goto out_destroy_compressed_res_queue;
1230 for (unsigned i = 0; i < num_threads; i++) {
1231 DEBUG("pthread_create thread %u", i);
1232 ret = pthread_create(&compressor_threads[i], NULL,
1233 compressor_thread_proc, ¶ms);
1236 ERROR_WITH_ERRNO("Failed to create compressor "
1244 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1246 ret = main_writer_thread_proc(stream_list,
1249 &res_to_compress_queue,
1250 &compressed_res_queue,
1256 for (unsigned i = 0; i < num_threads; i++)
1257 shared_queue_put(&res_to_compress_queue, NULL);
1259 for (unsigned i = 0; i < num_threads; i++) {
1260 if (pthread_join(compressor_threads[i], NULL)) {
1261 WARNING_WITH_ERRNO("Failed to join compressor "
1265 FREE(compressor_threads);
1266 out_destroy_compressed_res_queue:
1267 shared_queue_destroy(&compressed_res_queue);
1268 out_destroy_res_to_compress_queue:
1269 shared_queue_destroy(&res_to_compress_queue);
1270 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1273 WARNING("Falling back to single-threaded compression");
1274 return write_stream_list_serial(stream_list,
1286 * Write a list of streams to a WIM (@out_fp) using the compression type
1287 * @out_ctype and up to @num_threads compressor threads.
1290 write_stream_list(struct list_head *stream_list,
1291 struct wim_lookup_table *lookup_table,
1292 FILE *out_fp, int out_ctype, int write_flags,
1293 unsigned num_threads, wimlib_progress_func_t progress_func)
1295 struct wim_lookup_table_entry *lte;
1296 size_t num_streams = 0;
1297 u64 total_bytes = 0;
1298 u64 total_compression_bytes = 0;
1299 union wimlib_progress_info progress;
1302 list_for_each_entry(lte, stream_list, write_streams_list) {
1304 total_bytes += wim_resource_size(lte);
1305 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1306 && (wim_resource_compression_type(lte) != out_ctype ||
1307 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1309 total_compression_bytes += wim_resource_size(lte);
1312 progress.write_streams.total_bytes = total_bytes;
1313 progress.write_streams.total_streams = num_streams;
1314 progress.write_streams.completed_bytes = 0;
1315 progress.write_streams.completed_streams = 0;
1316 progress.write_streams.num_threads = num_threads;
1317 progress.write_streams.compression_type = out_ctype;
1318 progress.write_streams._private = 0;
1320 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1321 if (total_compression_bytes >= 1000000 && num_threads != 1)
1322 ret = write_stream_list_parallel(stream_list,
1332 ret = write_stream_list_serial(stream_list,
1342 struct lte_overwrite_prepare_args {
1345 struct list_head *stream_list;
1349 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1351 struct lte_overwrite_prepare_args *args = arg;
1353 if (lte->resource_location == RESOURCE_IN_WIM &&
1354 lte->wim == args->wim &&
1355 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1357 #ifdef ENABLE_ERROR_MESSAGES
1358 ERROR("The following resource is after the XML data:");
1359 print_lookup_table_entry(lte, stderr);
1361 return WIMLIB_ERR_RESOURCE_ORDER;
1364 lte->out_refcnt = lte->refcnt;
1365 memcpy(<e->output_resource_entry, <e->resource_entry,
1366 sizeof(struct resource_entry));
1367 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1368 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1369 list_add(<e->staging_list, args->stream_list);
1374 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1375 struct list_head *stream_list)
1377 struct lte_overwrite_prepare_args args = {
1379 .end_offset = end_offset,
1380 .stream_list = stream_list,
1384 for (int i = 0; i < wim->hdr.image_count; i++) {
1385 ret = lte_overwrite_prepare(wim->image_metadata[i]->metadata_lte,
1390 return for_lookup_table_entry(wim->lookup_table,
1391 lte_overwrite_prepare, &args);
1394 struct stream_size_table {
1395 struct hlist_head *array;
1401 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1403 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1405 return WIMLIB_ERR_NOMEM;
1406 tab->num_entries = 0;
1407 tab->capacity = capacity;
1412 destroy_stream_size_table(struct stream_size_table *tab)
1418 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1420 struct stream_size_table *tab = _tab;
1421 size_t pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1422 struct wim_lookup_table_entry *hashed_lte;
1423 struct hlist_node *tmp;
1425 lte->unique_size = 1;
1426 hlist_for_each_entry(hashed_lte, tmp, &tab->array[pos], hash_list_2) {
1427 if (wim_resource_size(hashed_lte) == wim_resource_size(lte)) {
1428 lte->unique_size = 0;
1429 hashed_lte->unique_size = 0;
1434 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1440 struct find_streams_ctx {
1441 struct list_head stream_list;
1442 struct stream_size_table stream_size_tab;
1446 inode_find_streams_to_write(struct wim_inode *inode,
1447 struct wim_lookup_table *table,
1448 struct list_head *stream_list,
1449 struct stream_size_table *tab)
1451 struct wim_lookup_table_entry *lte;
1452 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1453 lte = inode_stream_lte(inode, i, table);
1455 if (lte->out_refcnt == 0)
1456 list_add_tail(<e->write_streams_list, stream_list);
1457 lte->out_refcnt += inode->i_nlink;
1459 stream_size_table_insert(lte, tab);
1466 image_find_streams_to_write(WIMStruct *w)
1468 struct wim_image_metadata *imd;
1469 struct find_streams_ctx *ctx;
1470 struct wim_inode *inode;
1471 struct hlist_node *cur;
1474 imd = wim_get_current_image_metadata(w);
1475 hlist_for_each_entry(inode, cur, &imd->inode_list, i_hlist) {
1476 inode_find_streams_to_write(inode, w->lookup_table,
1478 &ctx->stream_size_tab);
1484 write_wim_streams(WIMStruct *w, int image, int write_flags,
1485 unsigned num_threads,
1486 wimlib_progress_func_t progress_func)
1488 struct find_streams_ctx ctx;
1491 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1492 ret = init_stream_size_table(&ctx.stream_size_tab, 9001);
1495 for_lookup_table_entry(w->lookup_table, stream_size_table_insert,
1496 &ctx.stream_size_tab);
1498 INIT_LIST_HEAD(&ctx.stream_list);
1500 for_image(w, image, image_find_streams_to_write);
1501 destroy_stream_size_table(&ctx.stream_size_tab);
1502 ret = write_stream_list(&ctx.stream_list,
1505 wimlib_get_compression_type(w), write_flags,
1506 num_threads, progress_func);
1511 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1512 * table (optional), then overwrite the WIM header.
1514 * write_flags is a bitwise OR of the following:
1516 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1517 * Include an integrity table.
1519 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1520 * Show progress information when (if) writing the integrity table.
1522 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1523 * Don't write the lookup table.
1525 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1526 * When (if) writing the integrity table, re-use entries from the
1527 * existing integrity table, if possible.
1529 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1530 * After writing the XML data but before writing the integrity
1531 * table, write a temporary WIM header and flush the stream so that
1532 * the WIM is less likely to become corrupted upon abrupt program
1535 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1536 * fsync() the output file before closing it.
1540 finish_write(WIMStruct *w, int image, int write_flags,
1541 wimlib_progress_func_t progress_func)
1544 struct wim_header hdr;
1545 FILE *out = w->out_fp;
1547 /* @hdr will be the header for the new WIM. First copy all the data
1548 * from the header in the WIMStruct; then set all the fields that may
1549 * have changed, including the resource entries, boot index, and image
1551 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1553 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1554 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1559 ret = write_xml_data(w->wim_info, image, out,
1560 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1561 wim_info_get_total_bytes(w->wim_info) : 0,
1562 &hdr.xml_res_entry);
1566 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1567 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1568 struct wim_header checkpoint_hdr;
1569 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1570 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1571 if (fseeko(out, 0, SEEK_SET) != 0) {
1572 ERROR_WITH_ERRNO("Failed to seek to beginning "
1573 "of WIM being written");
1574 ret = WIMLIB_ERR_WRITE;
1577 ret = write_header(&checkpoint_hdr, out);
1581 if (fflush(out) != 0) {
1582 ERROR_WITH_ERRNO("Can't write data to WIM");
1583 ret = WIMLIB_ERR_WRITE;
1587 if (fseeko(out, 0, SEEK_END) != 0) {
1588 ERROR_WITH_ERRNO("Failed to seek to end "
1589 "of WIM being written");
1590 ret = WIMLIB_ERR_WRITE;
1595 off_t old_lookup_table_end;
1596 off_t new_lookup_table_end;
1597 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1598 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1599 w->hdr.lookup_table_res_entry.size;
1601 old_lookup_table_end = 0;
1603 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1604 hdr.lookup_table_res_entry.size;
1606 ret = write_integrity_table(out,
1608 new_lookup_table_end,
1609 old_lookup_table_end,
1614 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1618 * In the WIM header, there is room for the resource entry for a
1619 * metadata resource labeled as the "boot metadata". This entry should
1620 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1621 * it should be a copy of the resource entry for the image that is
1622 * marked as bootable. This is not well documented...
1625 /* Set image count and boot index correctly for single image writes */
1626 if (image != WIMLIB_ALL_IMAGES) {
1627 hdr.image_count = 1;
1628 if (hdr.boot_idx == image)
1634 if (hdr.boot_idx == 0) {
1635 memset(&hdr.boot_metadata_res_entry, 0,
1636 sizeof(struct resource_entry));
1638 memcpy(&hdr.boot_metadata_res_entry,
1640 hdr.boot_idx - 1]->metadata_lte->output_resource_entry,
1641 sizeof(struct resource_entry));
1644 if (fseeko(out, 0, SEEK_SET) != 0) {
1645 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1647 ret = WIMLIB_ERR_WRITE;
1651 ret = write_header(&hdr, out);
1655 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1656 if (fflush(out) != 0
1657 || fsync(fileno(out)) != 0)
1659 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1660 ret = WIMLIB_ERR_WRITE;
1664 if (fclose(out) != 0) {
1665 ERROR_WITH_ERRNO("Failed to close the WIM file");
1667 ret = WIMLIB_ERR_WRITE;
1673 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1675 lock_wim(WIMStruct *w, FILE *fp)
1678 if (fp && !w->wim_locked) {
1679 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1681 if (errno == EWOULDBLOCK) {
1682 ERROR("`%"TS"' is already being modified or has been "
1683 "mounted read-write\n"
1684 " by another process!", w->filename);
1685 ret = WIMLIB_ERR_ALREADY_LOCKED;
1687 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1700 open_wim_writable(WIMStruct *w, const tchar *path,
1701 bool trunc, bool also_readable)
1712 wimlib_assert(w->out_fp == NULL);
1713 w->out_fp = tfopen(path, mode);
1717 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1718 return WIMLIB_ERR_OPEN;
1724 close_wim_writable(WIMStruct *w)
1727 if (fclose(w->out_fp) != 0) {
1728 WARNING_WITH_ERRNO("Failed to close output WIM");
1734 /* Open file stream and write dummy header for WIM. */
1736 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1739 ret = open_wim_writable(w, path, true,
1740 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1743 /* Write dummy header. It will be overwritten later. */
1744 return write_header(&w->hdr, w->out_fp);
1747 /* Writes a stand-alone WIM to a file. */
1749 wimlib_write(WIMStruct *w, const tchar *path,
1750 int image, int write_flags, unsigned num_threads,
1751 wimlib_progress_func_t progress_func)
1756 return WIMLIB_ERR_INVALID_PARAM;
1758 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1760 if (image != WIMLIB_ALL_IMAGES &&
1761 (image < 1 || image > w->hdr.image_count))
1762 return WIMLIB_ERR_INVALID_IMAGE;
1764 if (w->hdr.total_parts != 1) {
1765 ERROR("Cannot call wimlib_write() on part of a split WIM");
1766 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1769 ret = begin_write(w, path, write_flags);
1773 ret = write_wim_streams(w, image, write_flags, num_threads,
1779 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1781 ret = for_image(w, image, write_metadata_resource);
1786 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1788 ret = finish_write(w, image, write_flags, progress_func);
1790 close_wim_writable(w);
1791 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1796 any_images_modified(WIMStruct *w)
1798 for (int i = 0; i < w->hdr.image_count; i++)
1799 if (w->image_metadata[i]->modified)
1805 * Overwrite a WIM, possibly appending streams to it.
1807 * A WIM looks like (or is supposed to look like) the following:
1809 * Header (212 bytes)
1810 * Streams and metadata resources (variable size)
1811 * Lookup table (variable size)
1812 * XML data (variable size)
1813 * Integrity table (optional) (variable size)
1815 * If we are not adding any streams or metadata resources, the lookup table is
1816 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1817 * header. This operation is potentially unsafe if the program is abruptly
1818 * terminated while the XML data or integrity table are being overwritten, but
1819 * before the new header has been written. To partially alleviate this problem,
1820 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1821 * finish_write() to cause a temporary WIM header to be written after the XML
1822 * data has been written. This may prevent the WIM from becoming corrupted if
1823 * the program is terminated while the integrity table is being calculated (but
1824 * no guarantees, due to write re-ordering...).
1826 * If we are adding new streams or images (metadata resources), the lookup table
1827 * needs to be changed, and those streams need to be written. In this case, we
1828 * try to perform a safe update of the WIM file by writing the streams *after*
1829 * the end of the previous WIM, then writing the new lookup table, XML data, and
1830 * (optionally) integrity table following the new streams. This will produce a
1831 * layout like the following:
1833 * Header (212 bytes)
1834 * (OLD) Streams and metadata resources (variable size)
1835 * (OLD) Lookup table (variable size)
1836 * (OLD) XML data (variable size)
1837 * (OLD) Integrity table (optional) (variable size)
1838 * (NEW) Streams and metadata resources (variable size)
1839 * (NEW) Lookup table (variable size)
1840 * (NEW) XML data (variable size)
1841 * (NEW) Integrity table (optional) (variable size)
1843 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1844 * the header is overwritten to point to the new lookup table, XML data, and
1845 * integrity table, to produce the following layout:
1847 * Header (212 bytes)
1848 * Streams and metadata resources (variable size)
1849 * Nothing (variable size)
1850 * More Streams and metadata resources (variable size)
1851 * Lookup table (variable size)
1852 * XML data (variable size)
1853 * Integrity table (optional) (variable size)
1855 * This method allows an image to be appended to a large WIM very quickly, and
1856 * is is crash-safe except in the case of write re-ordering, but the
1857 * disadvantage is that a small hole is left in the WIM where the old lookup
1858 * table, xml data, and integrity table were. (These usually only take up a
1859 * small amount of space compared to the streams, however.)
1862 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1863 unsigned num_threads,
1864 wimlib_progress_func_t progress_func)
1867 struct list_head stream_list;
1870 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1872 /* Make sure that the integrity table (if present) is after the XML
1873 * data, and that there are no stream resources, metadata resources, or
1874 * lookup tables after the XML data. Otherwise, these data would be
1876 if (w->hdr.integrity.offset != 0 &&
1877 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1878 ERROR("Didn't expect the integrity table to be before the XML data");
1879 return WIMLIB_ERR_RESOURCE_ORDER;
1882 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1883 ERROR("Didn't expect the lookup table to be after the XML data");
1884 return WIMLIB_ERR_RESOURCE_ORDER;
1888 if (w->hdr.integrity.offset)
1889 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1891 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1893 if (!w->deletion_occurred && !any_images_modified(w)) {
1894 /* If no images have been modified and no images have been
1895 * deleted, a new lookup table does not need to be written. */
1896 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1897 w->hdr.lookup_table_res_entry.size;
1898 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1899 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1901 INIT_LIST_HEAD(&stream_list);
1902 ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1906 ret = open_wim_writable(w, w->filename, false,
1907 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1911 ret = lock_wim(w, w->out_fp);
1918 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1919 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1923 return WIMLIB_ERR_WRITE;
1926 if (!list_empty(&stream_list)) {
1927 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1929 ret = write_stream_list(&stream_list,
1932 wimlib_get_compression_type(w),
1933 write_flags, num_threads,
1938 DEBUG("No new streams were added");
1941 for (int i = 0; i < w->hdr.image_count; i++) {
1942 if (w->image_metadata[i]->modified) {
1943 select_wim_image(w, i + 1);
1944 ret = write_metadata_resource(w);
1949 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1950 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1953 close_wim_writable(w);
1954 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1955 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1956 w->filename, old_wim_end);
1957 /* Return value of truncate() is ignored because this is already
1959 (void)ttruncate(w->filename, old_wim_end);
1966 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1967 unsigned num_threads,
1968 wimlib_progress_func_t progress_func)
1970 size_t wim_name_len;
1973 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1975 /* Write the WIM to a temporary file in the same directory as the
1977 wim_name_len = tstrlen(w->filename);
1978 tchar tmpfile[wim_name_len + 10];
1979 tmemcpy(tmpfile, w->filename, wim_name_len);
1980 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1981 tmpfile[wim_name_len + 9] = T('\0');
1983 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1984 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1985 num_threads, progress_func);
1987 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
1991 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
1994 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
1995 * specified to CreateFile(). The WIM was opened with fopen(), which
1996 * didn't provided this flag to CreateFile, so the handle must be closed
1997 * before executing the rename(). */
1998 if (w->fp != NULL) {
2004 /* Rename the new file to the old file .*/
2005 if (trename(tmpfile, w->filename) != 0) {
2006 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2007 tmpfile, w->filename);
2008 ret = WIMLIB_ERR_RENAME;
2012 if (progress_func) {
2013 union wimlib_progress_info progress;
2014 progress.rename.from = tmpfile;
2015 progress.rename.to = w->filename;
2016 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2019 /* Close the original WIM file that was opened for reading. */
2020 if (w->fp != NULL) {
2025 /* Re-open the WIM read-only. */
2026 w->fp = tfopen(w->filename, T("rb"));
2027 if (w->fp == NULL) {
2028 ret = WIMLIB_ERR_REOPEN;
2029 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2036 /* Remove temporary file. */
2037 if (tunlink(tmpfile) != 0)
2038 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2043 * Writes a WIM file to the original file that it was read from, overwriting it.
2046 wimlib_overwrite(WIMStruct *w, int write_flags,
2047 unsigned num_threads,
2048 wimlib_progress_func_t progress_func)
2050 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2053 return WIMLIB_ERR_NO_FILENAME;
2055 if (w->hdr.total_parts != 1) {
2056 ERROR("Cannot modify a split WIM");
2057 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2060 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2061 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2064 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2066 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2067 WARNING("Falling back to re-building entire WIM");
2071 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,