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, if the hash we had
382 * before is all 0's, just re-set it to be the new hash. */
383 if (write_ctx.doing_sha) {
384 u8 md[SHA1_HASH_SIZE];
385 sha1_final(md, &write_ctx.sha_ctx);
386 if (is_zero_hash(lte->hash)) {
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 do_write_stream_list(struct list_head *my_resources,
606 wimlib_progress_func_t progress_func,
607 union wimlib_progress_info *progress,
608 int write_resource_flags)
611 struct wim_lookup_table_entry *lte, *tmp;
613 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
614 ret = write_wim_resource(lte,
617 <e->output_resource_entry,
618 write_resource_flags);
621 list_del(<e->staging_list);
623 do_write_streams_progress(progress,
625 wim_resource_size(lte));
631 write_stream_list_serial(struct list_head *stream_list,
635 wimlib_progress_func_t progress_func,
636 union wimlib_progress_info *progress)
638 int write_resource_flags;
640 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
641 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
643 write_resource_flags = 0;
644 progress->write_streams.num_threads = 1;
646 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
647 return do_write_stream_list(stream_list, out_fp,
648 out_ctype, progress_func,
649 progress, write_resource_flags);
652 #ifdef ENABLE_MULTITHREADED_COMPRESSION
654 write_wim_chunks(struct message *msg, FILE *out_fp,
655 struct chunk_table *chunk_tab)
657 for (unsigned i = 0; i < msg->num_chunks; i++) {
658 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
660 DEBUG2("Write wim chunk %u of %u (csize = %u)",
661 i, msg->num_chunks, chunk_csize);
663 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
666 ERROR_WITH_ERRNO("Failed to write WIM chunk");
667 return WIMLIB_ERR_WRITE;
670 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
671 chunk_tab->cur_offset += chunk_csize;
677 * This function is executed by the main thread when the resources are being
678 * compressed in parallel. The main thread is in change of all reading of the
679 * uncompressed data and writing of the compressed data. The compressor threads
680 * *only* do compression from/to in-memory buffers.
682 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
683 * chunks of compressed data to compress, represented in a `struct message'.
684 * Each message is passed from the main thread to a worker thread through the
685 * res_to_compress_queue, and it is passed back through the
686 * compressed_res_queue.
689 main_writer_thread_proc(struct list_head *stream_list,
692 struct shared_queue *res_to_compress_queue,
693 struct shared_queue *compressed_res_queue,
696 wimlib_progress_func_t progress_func,
697 union wimlib_progress_info *progress)
700 struct chunk_table *cur_chunk_tab = NULL;
701 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
702 struct wim_lookup_table_entry *next_lte = NULL;
704 // Initially, all the messages are available to use.
705 LIST_HEAD(available_msgs);
708 ret = WIMLIB_ERR_NOMEM;
712 for (size_t i = 0; i < num_messages; i++)
713 list_add(&msgs[i].list, &available_msgs);
715 // outstanding_resources is the list of resources that currently have
716 // had chunks sent off for compression.
718 // The first stream in outstanding_resources is the stream that is
719 // currently being written (cur_lte).
721 // The last stream in outstanding_resources is the stream that is
722 // currently being read and chunks fed to the compressor threads
725 // Depending on the number of threads and the sizes of the resource,
726 // the outstanding streams list may contain streams between cur_lte and
727 // next_lte that have all their chunks compressed or being compressed,
728 // but haven't been written yet.
730 LIST_HEAD(outstanding_resources);
731 struct list_head *next_resource = stream_list->next;
733 u64 next_num_chunks = 0;
735 // As in write_wim_resource(), each resource we read is checksummed.
736 SHA_CTX next_sha_ctx;
737 u8 next_hash[SHA1_HASH_SIZE];
739 // Resources that don't need any chunks compressed are added to this
740 // list and written directly by the main thread.
741 LIST_HEAD(my_resources);
743 struct wim_lookup_table_entry *cur_lte = NULL;
747 ntfs_inode *ni = NULL;
750 DEBUG("Initializing buffers for uncompressed "
751 "and compressed data (%zu bytes needed)",
752 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
754 // Pre-allocate all the buffers that will be needed to do the chunk
756 for (size_t i = 0; i < num_messages; i++) {
757 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
758 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
760 // The extra 8 bytes is because longest_match() in
761 // lz77.c may read a little bit off the end of the
762 // uncompressed data. It doesn't need to be
763 // initialized--- we really just need to avoid accessing
765 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
766 if (msgs[i].compressed_chunks[j] == NULL ||
767 msgs[i].uncompressed_chunks[j] == NULL)
769 ret = WIMLIB_ERR_NOMEM;
775 // This loop is executed until all resources have been written, except
776 // possibly a few that have been added to the @my_resources list for
779 // Send chunks to the compressor threads until either (a) there
780 // are no more messages available since they were all sent off,
781 // or (b) there are no more resources that need to be
783 while (!list_empty(&available_msgs)) {
784 if (next_chunk == next_num_chunks) {
785 // If next_chunk == next_num_chunks, there are
786 // no more chunks to write in the current
787 // stream. So, check the SHA1 message digest of
788 // the stream that was just finished (unless
789 // next_lte == NULL, which is the case the very
790 // first time this loop is entered, and also
791 // near the very end of the compression when
792 // there are no more streams.) Then, advance to
793 // the next stream (if there is one).
794 if (next_lte != NULL) {
796 end_wim_resource_read(next_lte, ni);
799 end_wim_resource_read(next_lte);
801 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
803 sha1_final(next_hash, &next_sha_ctx);
804 if (!hashes_equal(next_lte->hash, next_hash)) {
805 ERROR("WIM resource has incorrect hash!");
806 if (next_lte->resource_location ==
807 RESOURCE_IN_FILE_ON_DISK)
809 ERROR("We were reading it from `%"TS"'; "
810 "maybe it changed while we were "
812 next_lte->file_on_disk);
814 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
819 // Advance to the next resource.
821 // If the next resource needs no compression, just write
822 // it with this thread (not now though--- we could be in
823 // the middle of writing another resource.) Keep doing
824 // this until we either get to the end of the resources
825 // list, or we get to a resource that needs compression.
827 if (next_resource == stream_list) {
828 // No more resources to send for
833 next_lte = container_of(next_resource,
834 struct wim_lookup_table_entry,
836 next_resource = next_resource->next;
837 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
838 && wim_resource_compression_type(next_lte) == out_ctype)
839 || wim_resource_size(next_lte) == 0)
841 list_add_tail(&next_lte->staging_list,
844 list_add_tail(&next_lte->staging_list,
845 &outstanding_resources);
847 next_num_chunks = wim_resource_chunks(next_lte);
848 sha1_init(&next_sha_ctx);
849 INIT_LIST_HEAD(&next_lte->msg_list);
851 ret = prepare_resource_for_read(next_lte, &ni);
853 ret = prepare_resource_for_read(next_lte);
858 if (cur_lte == NULL) {
859 // Set cur_lte for the
868 if (next_lte == NULL) {
869 // No more resources to send for compression
873 // Get a message from the available messages
875 msg = container_of(available_msgs.next,
879 // ... and delete it from the available messages
881 list_del(&msg->list);
883 // Initialize the message with the chunks to
885 msg->num_chunks = min(next_num_chunks - next_chunk,
888 msg->complete = false;
889 msg->begin_chunk = next_chunk;
891 unsigned size = WIM_CHUNK_SIZE;
892 for (unsigned i = 0; i < msg->num_chunks; i++) {
894 // Read chunk @next_chunk of the stream into the
895 // message so that a compressor thread can
898 if (next_chunk == next_num_chunks - 1) {
899 size = MODULO_NONZERO(wim_resource_size(next_lte),
903 DEBUG2("Read resource (size=%u, offset=%zu)",
904 size, next_chunk * WIM_CHUNK_SIZE);
906 msg->uncompressed_chunk_sizes[i] = size;
908 ret = read_wim_resource(next_lte,
909 msg->uncompressed_chunks[i],
911 next_chunk * WIM_CHUNK_SIZE,
915 sha1_update(&next_sha_ctx,
916 msg->uncompressed_chunks[i], size);
920 // Send the compression request
921 list_add_tail(&msg->list, &next_lte->msg_list);
922 shared_queue_put(res_to_compress_queue, msg);
923 DEBUG2("Compression request sent");
926 // If there are no outstanding resources, there are no more
927 // resources that need to be written.
928 if (list_empty(&outstanding_resources)) {
933 // Get the next message from the queue and process it.
934 // The message will contain 1 or more data chunks that have been
936 msg = shared_queue_get(compressed_res_queue);
937 msg->complete = true;
939 // Is this the next chunk in the current resource? If it's not
940 // (i.e., an earlier chunk in a same or different resource
941 // hasn't been compressed yet), do nothing, and keep this
942 // message around until all earlier chunks are received.
944 // Otherwise, write all the chunks we can.
945 while (cur_lte != NULL &&
946 !list_empty(&cur_lte->msg_list) &&
947 (msg = container_of(cur_lte->msg_list.next,
951 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
952 if (msg->begin_chunk == 0) {
953 DEBUG2("Begin chunk tab");
955 // This is the first set of chunks. Leave space
956 // for the chunk table in the output file.
957 off_t cur_offset = ftello(out_fp);
958 if (cur_offset == -1) {
959 ret = WIMLIB_ERR_WRITE;
962 ret = begin_wim_resource_chunk_tab(cur_lte,
970 // Write the compressed chunks from the message.
971 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
975 list_del(&msg->list);
977 // This message is available to use for different chunks
979 list_add(&msg->list, &available_msgs);
981 // Was this the last chunk of the stream? If so, finish
983 if (list_empty(&cur_lte->msg_list) &&
984 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
986 DEBUG2("Finish wim chunk tab");
988 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
994 if (res_csize >= wim_resource_size(cur_lte)) {
995 /* Oops! We compressed the resource to
996 * larger than the original size. Write
997 * the resource uncompressed instead. */
998 ret = write_uncompressed_resource_and_truncate(
1001 cur_chunk_tab->file_offset,
1002 &cur_lte->output_resource_entry);
1006 cur_lte->output_resource_entry.size =
1009 cur_lte->output_resource_entry.original_size =
1010 cur_lte->resource_entry.original_size;
1012 cur_lte->output_resource_entry.offset =
1013 cur_chunk_tab->file_offset;
1015 cur_lte->output_resource_entry.flags =
1016 cur_lte->resource_entry.flags |
1017 WIM_RESHDR_FLAG_COMPRESSED;
1020 do_write_streams_progress(progress, progress_func,
1021 wim_resource_size(cur_lte));
1023 FREE(cur_chunk_tab);
1024 cur_chunk_tab = NULL;
1026 struct list_head *next = cur_lte->staging_list.next;
1027 list_del(&cur_lte->staging_list);
1029 if (next == &outstanding_resources)
1032 cur_lte = container_of(cur_lte->staging_list.next,
1033 struct wim_lookup_table_entry,
1036 // Since we just finished writing a stream,
1037 // write any streams that have been added to the
1038 // my_resources list for direct writing by the
1039 // main thread (e.g. resources that don't need
1040 // to be compressed because the desired
1041 // compression type is the same as the previous
1042 // compression type).
1043 ret = do_write_stream_list(&my_resources,
1056 if (ret == WIMLIB_ERR_NOMEM) {
1057 ERROR("Could not allocate enough memory for "
1058 "multi-threaded compression");
1063 end_wim_resource_read(next_lte, ni);
1065 end_wim_resource_read(next_lte);
1070 ret = do_write_stream_list(&my_resources, out_fp,
1071 out_ctype, progress_func,
1075 size_t num_available_msgs = 0;
1076 struct list_head *cur;
1078 list_for_each(cur, &available_msgs) {
1079 num_available_msgs++;
1082 while (num_available_msgs < num_messages) {
1083 shared_queue_get(compressed_res_queue);
1084 num_available_msgs++;
1090 for (size_t i = 0; i < num_messages; i++) {
1091 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1092 FREE(msgs[i].compressed_chunks[j]);
1093 FREE(msgs[i].uncompressed_chunks[j]);
1099 FREE(cur_chunk_tab);
1104 get_default_num_threads()
1107 return win32_get_number_of_processors();
1109 return sysconf(_SC_NPROCESSORS_ONLN);
1114 write_stream_list_parallel(struct list_head *stream_list,
1118 unsigned num_threads,
1119 wimlib_progress_func_t progress_func,
1120 union wimlib_progress_info *progress)
1123 struct shared_queue res_to_compress_queue;
1124 struct shared_queue compressed_res_queue;
1125 pthread_t *compressor_threads = NULL;
1127 if (num_threads == 0) {
1128 long nthreads = get_default_num_threads();
1129 if (nthreads < 1 || nthreads > UINT_MAX) {
1130 WARNING("Could not determine number of processors! Assuming 1");
1133 num_threads = nthreads;
1137 progress->write_streams.num_threads = num_threads;
1138 wimlib_assert(stream_list->next != stream_list);
1140 static const double MESSAGES_PER_THREAD = 2.0;
1141 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1143 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1145 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1149 ret = shared_queue_init(&compressed_res_queue, queue_size);
1151 goto out_destroy_res_to_compress_queue;
1153 struct compressor_thread_params params;
1154 params.res_to_compress_queue = &res_to_compress_queue;
1155 params.compressed_res_queue = &compressed_res_queue;
1156 params.compress = get_compress_func(out_ctype);
1158 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1159 if (!compressor_threads) {
1160 ret = WIMLIB_ERR_NOMEM;
1161 goto out_destroy_compressed_res_queue;
1164 for (unsigned i = 0; i < num_threads; i++) {
1165 DEBUG("pthread_create thread %u", i);
1166 ret = pthread_create(&compressor_threads[i], NULL,
1167 compressor_thread_proc, ¶ms);
1170 ERROR_WITH_ERRNO("Failed to create compressor "
1178 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1180 ret = main_writer_thread_proc(stream_list,
1183 &res_to_compress_queue,
1184 &compressed_res_queue,
1190 for (unsigned i = 0; i < num_threads; i++)
1191 shared_queue_put(&res_to_compress_queue, NULL);
1193 for (unsigned i = 0; i < num_threads; i++) {
1194 if (pthread_join(compressor_threads[i], NULL)) {
1195 WARNING_WITH_ERRNO("Failed to join compressor "
1199 FREE(compressor_threads);
1200 out_destroy_compressed_res_queue:
1201 shared_queue_destroy(&compressed_res_queue);
1202 out_destroy_res_to_compress_queue:
1203 shared_queue_destroy(&res_to_compress_queue);
1204 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1207 WARNING("Falling back to single-threaded compression");
1208 return write_stream_list_serial(stream_list,
1219 * Write a list of streams to a WIM (@out_fp) using the compression type
1220 * @out_ctype and up to @num_threads compressor threads.
1223 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1224 int out_ctype, int write_flags,
1225 unsigned num_threads,
1226 wimlib_progress_func_t progress_func)
1228 struct wim_lookup_table_entry *lte;
1229 size_t num_streams = 0;
1230 u64 total_bytes = 0;
1231 u64 total_compression_bytes = 0;
1232 union wimlib_progress_info progress;
1234 list_for_each_entry(lte, stream_list, staging_list) {
1236 total_bytes += wim_resource_size(lte);
1237 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1238 && (wim_resource_compression_type(lte) != out_ctype ||
1239 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1241 total_compression_bytes += wim_resource_size(lte);
1244 progress.write_streams.total_bytes = total_bytes;
1245 progress.write_streams.total_streams = num_streams;
1246 progress.write_streams.completed_bytes = 0;
1247 progress.write_streams.completed_streams = 0;
1248 progress.write_streams.num_threads = num_threads;
1249 progress.write_streams.compression_type = out_ctype;
1250 progress.write_streams._private = 0;
1252 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1253 if (total_compression_bytes >= 1000000 && num_threads != 1)
1254 return write_stream_list_parallel(stream_list,
1263 return write_stream_list_serial(stream_list,
1271 struct lte_overwrite_prepare_args {
1274 struct list_head *stream_list;
1278 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1280 struct lte_overwrite_prepare_args *args = arg;
1282 if (lte->resource_location == RESOURCE_IN_WIM &&
1283 lte->wim == args->wim &&
1284 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1286 #ifdef ENABLE_ERROR_MESSAGES
1287 ERROR("The following resource is after the XML data:");
1288 print_lookup_table_entry(lte, stderr);
1290 return WIMLIB_ERR_RESOURCE_ORDER;
1293 lte->out_refcnt = lte->refcnt;
1294 memcpy(<e->output_resource_entry, <e->resource_entry,
1295 sizeof(struct resource_entry));
1296 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1297 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1298 list_add(<e->staging_list, args->stream_list);
1303 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1304 struct list_head *stream_list)
1306 struct lte_overwrite_prepare_args args = {
1308 .end_offset = end_offset,
1309 .stream_list = stream_list,
1313 for (int i = 0; i < wim->hdr.image_count; i++) {
1314 ret = lte_overwrite_prepare(wim->image_metadata[i].metadata_lte,
1319 return for_lookup_table_entry(wim->lookup_table,
1320 lte_overwrite_prepare, &args);
1324 inode_find_streams_to_write(struct wim_inode *inode,
1325 struct wim_lookup_table *table,
1326 struct list_head *stream_list)
1328 struct wim_lookup_table_entry *lte;
1329 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1330 lte = inode_stream_lte(inode, i, table);
1332 if (lte->out_refcnt == 0)
1333 list_add_tail(<e->staging_list, stream_list);
1334 lte->out_refcnt += inode->i_nlink;
1341 image_find_streams_to_write(WIMStruct *w)
1343 struct wim_inode *inode;
1344 struct hlist_node *cur;
1345 struct hlist_head *inode_list;
1347 inode_list = &wim_get_current_image_metadata(w)->inode_list;
1348 hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1349 inode_find_streams_to_write(inode, w->lookup_table,
1350 (struct list_head*)w->private);
1356 write_wim_streams(WIMStruct *w, int image, int write_flags,
1357 unsigned num_threads,
1358 wimlib_progress_func_t progress_func)
1361 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1362 LIST_HEAD(stream_list);
1363 w->private = &stream_list;
1364 for_image(w, image, image_find_streams_to_write);
1365 return write_stream_list(&stream_list, w->out_fp,
1366 wimlib_get_compression_type(w), write_flags,
1367 num_threads, progress_func);
1371 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1372 * table (optional), then overwrite the WIM header.
1374 * write_flags is a bitwise OR of the following:
1376 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1377 * Include an integrity table.
1379 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1380 * Show progress information when (if) writing the integrity table.
1382 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1383 * Don't write the lookup table.
1385 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1386 * When (if) writing the integrity table, re-use entries from the
1387 * existing integrity table, if possible.
1389 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1390 * After writing the XML data but before writing the integrity
1391 * table, write a temporary WIM header and flush the stream so that
1392 * the WIM is less likely to become corrupted upon abrupt program
1395 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1396 * fsync() the output file before closing it.
1400 finish_write(WIMStruct *w, int image, int write_flags,
1401 wimlib_progress_func_t progress_func)
1404 struct wim_header hdr;
1405 FILE *out = w->out_fp;
1407 /* @hdr will be the header for the new WIM. First copy all the data
1408 * from the header in the WIMStruct; then set all the fields that may
1409 * have changed, including the resource entries, boot index, and image
1411 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1413 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1414 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1419 ret = write_xml_data(w->wim_info, image, out,
1420 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1421 wim_info_get_total_bytes(w->wim_info) : 0,
1422 &hdr.xml_res_entry);
1426 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1427 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1428 struct wim_header checkpoint_hdr;
1429 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1430 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1431 if (fseeko(out, 0, SEEK_SET) != 0) {
1432 ERROR_WITH_ERRNO("Failed to seek to beginning "
1433 "of WIM being written");
1434 ret = WIMLIB_ERR_WRITE;
1437 ret = write_header(&checkpoint_hdr, out);
1441 if (fflush(out) != 0) {
1442 ERROR_WITH_ERRNO("Can't write data to WIM");
1443 ret = WIMLIB_ERR_WRITE;
1447 if (fseeko(out, 0, SEEK_END) != 0) {
1448 ERROR_WITH_ERRNO("Failed to seek to end "
1449 "of WIM being written");
1450 ret = WIMLIB_ERR_WRITE;
1455 off_t old_lookup_table_end;
1456 off_t new_lookup_table_end;
1457 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1458 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1459 w->hdr.lookup_table_res_entry.size;
1461 old_lookup_table_end = 0;
1463 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1464 hdr.lookup_table_res_entry.size;
1466 ret = write_integrity_table(out,
1468 new_lookup_table_end,
1469 old_lookup_table_end,
1474 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1478 * In the WIM header, there is room for the resource entry for a
1479 * metadata resource labeled as the "boot metadata". This entry should
1480 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1481 * it should be a copy of the resource entry for the image that is
1482 * marked as bootable. This is not well documented...
1485 /* Set image count and boot index correctly for single image writes */
1486 if (image != WIMLIB_ALL_IMAGES) {
1487 hdr.image_count = 1;
1488 if (hdr.boot_idx == image)
1494 if (hdr.boot_idx == 0) {
1495 memset(&hdr.boot_metadata_res_entry, 0,
1496 sizeof(struct resource_entry));
1498 memcpy(&hdr.boot_metadata_res_entry,
1500 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1501 sizeof(struct resource_entry));
1504 if (fseeko(out, 0, SEEK_SET) != 0) {
1505 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1507 ret = WIMLIB_ERR_WRITE;
1511 ret = write_header(&hdr, out);
1515 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1516 if (fflush(out) != 0
1517 || fsync(fileno(out)) != 0)
1519 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1520 ret = WIMLIB_ERR_WRITE;
1524 if (fclose(out) != 0) {
1525 ERROR_WITH_ERRNO("Failed to close the WIM file");
1527 ret = WIMLIB_ERR_WRITE;
1533 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1535 lock_wim(WIMStruct *w, FILE *fp)
1538 if (fp && !w->wim_locked) {
1539 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1541 if (errno == EWOULDBLOCK) {
1542 ERROR("`%"TS"' is already being modified or has been "
1543 "mounted read-write\n"
1544 " by another process!", w->filename);
1545 ret = WIMLIB_ERR_ALREADY_LOCKED;
1547 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1560 open_wim_writable(WIMStruct *w, const tchar *path,
1561 bool trunc, bool also_readable)
1572 wimlib_assert(w->out_fp == NULL);
1573 w->out_fp = tfopen(path, mode);
1577 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1578 return WIMLIB_ERR_OPEN;
1584 close_wim_writable(WIMStruct *w)
1587 if (fclose(w->out_fp) != 0) {
1588 WARNING_WITH_ERRNO("Failed to close output WIM");
1594 /* Open file stream and write dummy header for WIM. */
1596 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1599 ret = open_wim_writable(w, path, true,
1600 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1603 /* Write dummy header. It will be overwritten later. */
1604 return write_header(&w->hdr, w->out_fp);
1607 /* Writes a stand-alone WIM to a file. */
1609 wimlib_write(WIMStruct *w, const tchar *path,
1610 int image, int write_flags, unsigned num_threads,
1611 wimlib_progress_func_t progress_func)
1616 return WIMLIB_ERR_INVALID_PARAM;
1618 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1620 if (image != WIMLIB_ALL_IMAGES &&
1621 (image < 1 || image > w->hdr.image_count))
1622 return WIMLIB_ERR_INVALID_IMAGE;
1624 if (w->hdr.total_parts != 1) {
1625 ERROR("Cannot call wimlib_write() on part of a split WIM");
1626 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1629 ret = begin_write(w, path, write_flags);
1633 ret = write_wim_streams(w, image, write_flags, num_threads,
1639 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1641 ret = for_image(w, image, write_metadata_resource);
1646 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1648 ret = finish_write(w, image, write_flags, progress_func);
1650 close_wim_writable(w);
1651 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1656 any_images_modified(WIMStruct *w)
1658 for (int i = 0; i < w->hdr.image_count; i++)
1659 if (w->image_metadata[i].modified)
1665 * Overwrite a WIM, possibly appending streams to it.
1667 * A WIM looks like (or is supposed to look like) the following:
1669 * Header (212 bytes)
1670 * Streams and metadata resources (variable size)
1671 * Lookup table (variable size)
1672 * XML data (variable size)
1673 * Integrity table (optional) (variable size)
1675 * If we are not adding any streams or metadata resources, the lookup table is
1676 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1677 * header. This operation is potentially unsafe if the program is abruptly
1678 * terminated while the XML data or integrity table are being overwritten, but
1679 * before the new header has been written. To partially alleviate this problem,
1680 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1681 * finish_write() to cause a temporary WIM header to be written after the XML
1682 * data has been written. This may prevent the WIM from becoming corrupted if
1683 * the program is terminated while the integrity table is being calculated (but
1684 * no guarantees, due to write re-ordering...).
1686 * If we are adding new streams or images (metadata resources), the lookup table
1687 * needs to be changed, and those streams need to be written. In this case, we
1688 * try to perform a safe update of the WIM file by writing the streams *after*
1689 * the end of the previous WIM, then writing the new lookup table, XML data, and
1690 * (optionally) integrity table following the new streams. This will produce a
1691 * layout like the following:
1693 * Header (212 bytes)
1694 * (OLD) Streams and metadata resources (variable size)
1695 * (OLD) Lookup table (variable size)
1696 * (OLD) XML data (variable size)
1697 * (OLD) Integrity table (optional) (variable size)
1698 * (NEW) Streams and metadata resources (variable size)
1699 * (NEW) Lookup table (variable size)
1700 * (NEW) XML data (variable size)
1701 * (NEW) Integrity table (optional) (variable size)
1703 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1704 * the header is overwritten to point to the new lookup table, XML data, and
1705 * integrity table, to produce the following layout:
1707 * Header (212 bytes)
1708 * Streams and metadata resources (variable size)
1709 * Nothing (variable size)
1710 * More Streams and metadata resources (variable size)
1711 * Lookup table (variable size)
1712 * XML data (variable size)
1713 * Integrity table (optional) (variable size)
1715 * This method allows an image to be appended to a large WIM very quickly, and
1716 * is is crash-safe except in the case of write re-ordering, but the
1717 * disadvantage is that a small hole is left in the WIM where the old lookup
1718 * table, xml data, and integrity table were. (These usually only take up a
1719 * small amount of space compared to the streams, however.)
1722 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1723 unsigned num_threads,
1724 wimlib_progress_func_t progress_func)
1727 struct list_head stream_list;
1730 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1732 /* Make sure that the integrity table (if present) is after the XML
1733 * data, and that there are no stream resources, metadata resources, or
1734 * lookup tables after the XML data. Otherwise, these data would be
1736 if (w->hdr.integrity.offset != 0 &&
1737 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1738 ERROR("Didn't expect the integrity table to be before the XML data");
1739 return WIMLIB_ERR_RESOURCE_ORDER;
1742 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1743 ERROR("Didn't expect the lookup table to be after the XML data");
1744 return WIMLIB_ERR_RESOURCE_ORDER;
1748 if (w->hdr.integrity.offset)
1749 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1751 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1753 if (!w->deletion_occurred && !any_images_modified(w)) {
1754 /* If no images have been modified and no images have been
1755 * deleted, a new lookup table does not need to be written. */
1756 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1757 w->hdr.lookup_table_res_entry.size;
1758 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1759 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1761 INIT_LIST_HEAD(&stream_list);
1762 ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1766 ret = open_wim_writable(w, w->filename, false,
1767 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1771 ret = lock_wim(w, w->out_fp);
1778 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1779 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1783 return WIMLIB_ERR_WRITE;
1786 if (!list_empty(&stream_list)) {
1787 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1789 ret = write_stream_list(&stream_list, w->out_fp,
1790 wimlib_get_compression_type(w),
1791 write_flags, num_threads,
1796 DEBUG("No new streams were added");
1799 for (int i = 0; i < w->hdr.image_count; i++) {
1800 if (w->image_metadata[i].modified) {
1801 select_wim_image(w, i + 1);
1802 ret = write_metadata_resource(w);
1807 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1808 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1811 close_wim_writable(w);
1812 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1813 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1814 w->filename, old_wim_end);
1815 /* Return value of truncate() is ignored because this is already
1817 (void)ttruncate(w->filename, old_wim_end);
1824 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1825 unsigned num_threads,
1826 wimlib_progress_func_t progress_func)
1828 size_t wim_name_len;
1831 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1833 /* Write the WIM to a temporary file in the same directory as the
1835 wim_name_len = tstrlen(w->filename);
1836 tchar tmpfile[wim_name_len + 10];
1837 tmemcpy(tmpfile, w->filename, wim_name_len);
1838 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1839 tmpfile[wim_name_len + 9] = T('\0');
1841 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1842 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1843 num_threads, progress_func);
1845 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
1849 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
1852 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
1853 * specified to CreateFile(). The WIM was opened with fopen(), which
1854 * didn't provided this flag to CreateFile, so the handle must be closed
1855 * before executing the rename(). */
1856 if (w->fp != NULL) {
1862 /* Rename the new file to the old file .*/
1863 if (trename(tmpfile, w->filename) != 0) {
1864 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
1865 tmpfile, w->filename);
1866 ret = WIMLIB_ERR_RENAME;
1870 if (progress_func) {
1871 union wimlib_progress_info progress;
1872 progress.rename.from = tmpfile;
1873 progress.rename.to = w->filename;
1874 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1877 /* Close the original WIM file that was opened for reading. */
1878 if (w->fp != NULL) {
1883 /* Re-open the WIM read-only. */
1884 w->fp = tfopen(w->filename, T("rb"));
1885 if (w->fp == NULL) {
1886 ret = WIMLIB_ERR_REOPEN;
1887 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
1894 /* Remove temporary file. */
1895 if (tunlink(tmpfile) != 0)
1896 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
1901 * Writes a WIM file to the original file that it was read from, overwriting it.
1904 wimlib_overwrite(WIMStruct *w, int write_flags,
1905 unsigned num_threads,
1906 wimlib_progress_func_t progress_func)
1908 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1911 return WIMLIB_ERR_NO_FILENAME;
1913 if (w->hdr.total_parts != 1) {
1914 ERROR("Cannot modify a split WIM");
1915 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1918 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1919 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1922 ret = overwrite_wim_inplace(w, write_flags, num_threads,
1924 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
1925 WARNING("Falling back to re-building entire WIM");
1929 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,