4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2010 Carl Thijssen
10 * Copyright (C) 2012 Eric Biggers
12 * This file is part of wimlib, a library for working with WIM files.
14 * wimlib is free software; you can redistribute it and/or modify it under the
15 * terms of the GNU General Public License as published by the Free
16 * Software Foundation; either version 3 of the License, or (at your option)
19 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21 * A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with wimlib; if not, see http://www.gnu.org/licenses/.
30 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
31 /* On BSD, this should be included before "list.h" so that "list.h" can
32 * overwrite the LIST_HEAD macro. */
37 #include "wimlib_internal.h"
40 #include "lookup_table.h"
45 #ifdef ENABLE_MULTITHREADED_COMPRESSION
46 #include <semaphore.h>
55 #include <ntfs-3g/attrib.h>
56 #include <ntfs-3g/inode.h>
57 #include <ntfs-3g/dir.h>
67 static int do_fflush(FILE *fp)
71 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
72 return WIMLIB_ERR_WRITE;
77 static int fflush_and_ftruncate(FILE *fp, off_t size)
84 ret = ftruncate(fileno(fp), size);
86 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
87 "%"PRIu64" bytes", size);
88 return WIMLIB_ERR_WRITE;
93 /* Chunk table that's located at the beginning of each compressed resource in
94 * the WIM. (This is not the on-disk format; the on-disk format just has an
95 * array of offsets.) */
99 u64 original_resource_size;
100 u64 bytes_per_chunk_entry;
108 * Allocates and initializes a chunk table, and reserves space for it in the
112 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
115 struct chunk_table **chunk_tab_ret)
117 u64 size = wim_resource_size(lte);
118 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
119 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
120 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
124 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
126 ret = WIMLIB_ERR_NOMEM;
129 chunk_tab->file_offset = file_offset;
130 chunk_tab->num_chunks = num_chunks;
131 chunk_tab->original_resource_size = size;
132 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
133 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
135 chunk_tab->cur_offset = 0;
136 chunk_tab->cur_offset_p = chunk_tab->offsets;
138 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
139 chunk_tab->table_disk_size) {
140 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
142 ret = WIMLIB_ERR_WRITE;
148 *chunk_tab_ret = chunk_tab;
153 * Pointer to function to compresses a chunk of a WIM resource.
155 * @chunk: Uncompressed data of the chunk.
156 * @chunk_size: Size of the uncompressed chunk in bytes.
157 * @compressed_chunk: Pointer to output buffer of size at least
158 * (@chunk_size - 1) bytes.
159 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
160 * of the compressed chunk will be
163 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
164 * compressed to any smaller than @chunk_size. This function cannot fail for
167 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
169 compress_func_t get_compress_func(int out_ctype)
171 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
174 return xpress_compress;
178 * Writes a chunk of a WIM resource to an output file.
180 * @chunk: Uncompressed data of the chunk.
181 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
182 * @out_fp: FILE * to write tho chunk to.
183 * @out_ctype: Compression type to use when writing the chunk (ignored if no
184 * chunk table provided)
185 * @chunk_tab: Pointer to chunk table being created. It is updated with the
186 * offset of the chunk we write.
188 * Returns 0 on success; nonzero on failure.
190 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
191 FILE *out_fp, compress_func_t compress,
192 struct chunk_table *chunk_tab)
195 unsigned out_chunk_size;
197 u8 *compressed_chunk = alloca(chunk_size);
200 ret = compress(chunk, chunk_size, compressed_chunk,
203 out_chunk = compressed_chunk;
206 out_chunk_size = chunk_size;
208 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
209 chunk_tab->cur_offset += out_chunk_size;
212 out_chunk_size = chunk_size;
214 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
215 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
216 return WIMLIB_ERR_WRITE;
222 * Finishes a WIM chunk tale and writes it to the output file at the correct
225 * The final size of the full compressed resource is returned in the
226 * @compressed_size_p.
229 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
230 FILE *out_fp, u64 *compressed_size_p)
232 size_t bytes_written;
233 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
234 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
235 "WIM file", chunk_tab->file_offset);
236 return WIMLIB_ERR_WRITE;
239 if (chunk_tab->bytes_per_chunk_entry == 8) {
240 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
242 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
243 ((u32*)chunk_tab->offsets)[i] =
244 cpu_to_le32(chunk_tab->offsets[i]);
246 bytes_written = fwrite((u8*)chunk_tab->offsets +
247 chunk_tab->bytes_per_chunk_entry,
248 1, chunk_tab->table_disk_size, out_fp);
249 if (bytes_written != chunk_tab->table_disk_size) {
250 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
252 return WIMLIB_ERR_WRITE;
254 if (fseeko(out_fp, 0, SEEK_END) != 0) {
255 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
256 return WIMLIB_ERR_WRITE;
258 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
262 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
263 * attribute pointer in the lookup table entry. */
264 static int prepare_resource_for_read(struct lookup_table_entry *lte
267 , ntfs_inode **ni_ret
271 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
272 && !lte->file_on_disk_fp)
274 wimlib_assert(lte->file_on_disk);
275 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
276 if (!lte->file_on_disk_fp) {
277 ERROR_WITH_ERRNO("Failed to open the file `%s' for "
278 "reading", lte->file_on_disk);
279 return WIMLIB_ERR_OPEN;
283 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
286 struct ntfs_location *loc = lte->ntfs_loc;
289 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
291 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
292 "volume", loc->path_utf8);
293 return WIMLIB_ERR_NTFS_3G;
295 lte->attr = ntfs_attr_open(ni,
296 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
297 (ntfschar*)loc->stream_name_utf16,
298 loc->stream_name_utf16_num_chars);
300 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
301 "NTFS volume", loc->path_utf8);
302 ntfs_inode_close(ni);
303 return WIMLIB_ERR_NTFS_3G;
311 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
313 static void end_wim_resource_read(struct lookup_table_entry *lte
319 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
320 && lte->file_on_disk_fp) {
321 fclose(lte->file_on_disk_fp);
322 lte->file_on_disk_fp = NULL;
325 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
327 ntfs_attr_close(lte->attr);
331 ntfs_inode_close(ni);
337 * Writes a WIM resource to a FILE * opened for writing. The resource may be
338 * written uncompressed or compressed depending on the @out_ctype parameter.
340 * If by chance the resource compresses to more than the original size (this may
341 * happen with random data or files than are pre-compressed), the resource is
342 * instead written uncompressed (and this is reflected in the @out_res_entry by
343 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
345 * @lte: The lookup table entry for the WIM resource.
346 * @out_fp: The FILE * to write the resource to.
347 * @out_ctype: The compression type of the resource to write. Note: if this is
348 * the same as the compression type of the WIM resource we
349 * need to read, we simply copy the data (i.e. we do not
350 * uncompress it, then compress it again).
351 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
352 * offset, original size, compressed size, and compression flag
353 * of the output resource.
355 * Returns 0 on success; nonzero on failure.
357 int write_wim_resource(struct lookup_table_entry *lte,
358 FILE *out_fp, int out_ctype,
359 struct resource_entry *out_res_entry,
364 u64 old_compressed_size;
365 u64 new_compressed_size;
368 struct chunk_table *chunk_tab = NULL;
371 compress_func_t compress = NULL;
373 ntfs_inode *ni = NULL;
378 /* Original size of the resource */
379 original_size = wim_resource_size(lte);
381 /* Compressed size of the resource (as it exists now) */
382 old_compressed_size = wim_resource_compressed_size(lte);
384 /* Current offset in output file */
385 file_offset = ftello(out_fp);
386 if (file_offset == -1) {
387 ERROR_WITH_ERRNO("Failed to get offset in output "
389 return WIMLIB_ERR_WRITE;
392 /* Are the compression types the same? If so, do a raw copy (copy
393 * without decompressing and recompressing the data). */
394 raw = (wim_resource_compression_type(lte) == out_ctype
395 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
396 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
399 flags |= WIMLIB_RESOURCE_FLAG_RAW;
400 bytes_remaining = old_compressed_size;
402 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
403 bytes_remaining = original_size;
406 /* Empty resource; nothing needs to be done, so just return success. */
407 if (bytes_remaining == 0)
410 /* Buffer for reading chunks for the resource */
411 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
413 /* If we are writing a compressed resource and not doing a raw copy, we
414 * need to initialize the chunk table */
415 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
416 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
422 /* If the WIM resource is in an external file, open a FILE * to it so we
423 * don't have to open a temporary one in read_wim_resource() for each
426 ret = prepare_resource_for_read(lte, &ni);
428 ret = prepare_resource_for_read(lte);
433 /* If we aren't doing a raw copy, we will compute the SHA1 message
434 * digest of the resource as we read it, and verify it's the same as the
435 * hash given in the lookup table entry once we've finished reading the
440 compress = get_compress_func(out_ctype);
444 /* While there are still bytes remaining in the WIM resource, read a
445 * chunk of the resource, update SHA1, then write that chunk using the
446 * desired compression type. */
448 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
449 ret = read_wim_resource(lte, buf, to_read, offset, flags);
453 sha1_update(&ctx, buf, to_read);
454 ret = write_wim_resource_chunk(buf, to_read, out_fp,
455 compress, chunk_tab);
458 bytes_remaining -= to_read;
460 } while (bytes_remaining);
462 /* Raw copy: The new compressed size is the same as the old compressed
465 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
468 * Using a different compression type: Call
469 * finish_wim_resource_chunk_tab() and it will provide the new
473 new_compressed_size = old_compressed_size;
475 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
476 new_compressed_size = original_size;
478 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
479 &new_compressed_size);
485 /* Verify SHA1 message digest of the resource, unless we are doing a raw
486 * write (in which case we never even saw the uncompressed data). Or,
487 * if the hash we had before is all 0's, just re-set it to be the new
490 u8 md[SHA1_HASH_SIZE];
491 sha1_final(md, &ctx);
492 if (is_zero_hash(lte->hash)) {
493 copy_hash(lte->hash, md);
494 } else if (!hashes_equal(md, lte->hash)) {
495 ERROR("WIM resource has incorrect hash!");
496 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
497 ERROR("We were reading it from `%s'; maybe it changed "
498 "while we were reading it.",
501 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
506 if (!raw && new_compressed_size >= original_size &&
507 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
509 /* Oops! We compressed the resource to larger than the original
510 * size. Write the resource uncompressed instead. */
511 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
512 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
513 "of output WIM file", file_offset);
514 ret = WIMLIB_ERR_WRITE;
517 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
518 out_res_entry, flags);
522 ret = fflush_and_ftruncate(out_fp, file_offset + out_res_entry->size);
527 out_res_entry->size = new_compressed_size;
528 out_res_entry->original_size = original_size;
529 out_res_entry->offset = file_offset;
530 out_res_entry->flags = lte->resource_entry.flags
531 & ~WIM_RESHDR_FLAG_COMPRESSED;
532 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
533 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
539 end_wim_resource_read(lte, ni);
541 end_wim_resource_read(lte);
548 #ifdef ENABLE_MULTITHREADED_COMPRESSION
549 struct shared_queue {
552 pthread_mutex_t lock;
559 static int shared_queue_init(struct shared_queue *q, unsigned size)
561 q->array = CALLOC(sizeof(q->array[0]), size);
563 return WIMLIB_ERR_NOMEM;
565 sem_init(&q->filled_slots, 0, 0);
566 sem_init(&q->empty_slots, 0, size);
567 pthread_mutex_init(&q->lock, NULL);
574 static void shared_queue_destroy(struct shared_queue *q)
576 sem_destroy(&q->filled_slots);
577 sem_destroy(&q->empty_slots);
578 pthread_mutex_destroy(&q->lock);
582 static void shared_queue_put(struct shared_queue *q, void *obj)
584 sem_wait(&q->empty_slots);
585 pthread_mutex_lock(&q->lock);
587 q->back = (q->back + 1) % q->size;
588 q->array[q->back] = obj;
590 sem_post(&q->filled_slots);
591 pthread_mutex_unlock(&q->lock);
594 static void *shared_queue_get(struct shared_queue *q)
596 sem_wait(&q->filled_slots);
597 pthread_mutex_lock(&q->lock);
599 void *obj = q->array[q->front];
600 q->array[q->front] = NULL;
601 q->front = (q->front + 1) % q->size;
603 sem_post(&q->empty_slots);
604 pthread_mutex_unlock(&q->lock);
608 struct compressor_thread_params {
609 struct shared_queue *res_to_compress_queue;
610 struct shared_queue *compressed_res_queue;
611 compress_func_t compress;
614 #define MAX_CHUNKS_PER_MSG 2
617 struct lookup_table_entry *lte;
618 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
619 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
620 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
621 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
622 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
624 struct list_head list;
629 static void compress_chunks(struct message *msg, compress_func_t compress)
631 for (unsigned i = 0; i < msg->num_chunks; i++) {
632 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
633 int ret = compress(msg->uncompressed_chunks[i],
634 msg->uncompressed_chunk_sizes[i],
635 msg->compressed_chunks[i],
636 &msg->compressed_chunk_sizes[i]);
638 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
640 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
641 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
646 static void *compressor_thread_proc(void *arg)
648 struct compressor_thread_params *params = arg;
649 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
650 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
651 compress_func_t compress = params->compress;
654 DEBUG("Compressor thread ready");
655 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
656 compress_chunks(msg, compress);
657 shared_queue_put(compressed_res_queue, msg);
659 DEBUG("Compressor thread terminating");
664 static int do_write_stream_list(struct list_head *my_resources,
667 wimlib_progress_func_t progress_func,
668 union wimlib_progress_info *progress,
669 int write_resource_flags)
672 struct lookup_table_entry *lte, *tmp;
674 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
675 ret = write_wim_resource(lte,
678 <e->output_resource_entry,
679 write_resource_flags);
682 list_del(<e->staging_list);
683 progress->write_streams.completed_bytes +=
684 wim_resource_size(lte);
685 progress->write_streams.completed_streams++;
687 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
694 static int write_stream_list_serial(struct list_head *stream_list,
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, out_fp,
711 out_ctype, progress_func,
712 progress, write_resource_flags);
715 #ifdef ENABLE_MULTITHREADED_COMPRESSION
716 static int write_wim_chunks(struct message *msg, FILE *out_fp,
717 struct chunk_table *chunk_tab)
719 for (unsigned i = 0; i < msg->num_chunks; i++) {
720 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
722 DEBUG2("Write wim chunk %u of %u (csize = %u)",
723 i, msg->num_chunks, chunk_csize);
725 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
728 ERROR_WITH_ERRNO("Failed to write WIM chunk");
729 return WIMLIB_ERR_WRITE;
732 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
733 chunk_tab->cur_offset += chunk_csize;
739 * This function is executed by the main thread when the resources are being
740 * compressed in parallel. The main thread is in change of all reading of the
741 * uncompressed data and writing of the compressed data. The compressor threads
742 * *only* do compression from/to in-memory buffers.
744 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
745 * chunks of compressed data to compress, represented in a `struct message'.
746 * Each message is passed from the main thread to a worker thread through the
747 * res_to_compress_queue, and it is passed back through the
748 * compressed_res_queue.
750 static int main_writer_thread_proc(struct list_head *stream_list,
753 struct shared_queue *res_to_compress_queue,
754 struct shared_queue *compressed_res_queue,
757 wimlib_progress_func_t progress_func,
758 union wimlib_progress_info *progress)
762 struct message msgs[queue_size];
765 // Initially, all the messages are available to use.
766 LIST_HEAD(available_msgs);
767 for (size_t i = 0; i < ARRAY_LEN(msgs); i++)
768 list_add(&msgs[i].list, &available_msgs);
770 // outstanding_resources is the list of resources that currently have
771 // had chunks sent off for compression.
773 // The first stream in outstanding_resources is the stream that is
774 // currently being written (cur_lte).
776 // The last stream in outstanding_resources is the stream that is
777 // currently being read and chunks fed to the compressor threads
780 // Depending on the number of threads and the sizes of the resource,
781 // the outstanding streams list may contain streams between cur_lte and
782 // next_lte that have all their chunks compressed or being compressed,
783 // but haven't been written yet.
785 LIST_HEAD(outstanding_resources);
786 struct list_head *next_resource = stream_list->next;
787 struct lookup_table_entry *next_lte = container_of(next_resource,
788 struct lookup_table_entry,
790 next_resource = next_resource->next;
792 u64 next_num_chunks = wim_resource_chunks(next_lte);
793 INIT_LIST_HEAD(&next_lte->msg_list);
794 list_add_tail(&next_lte->staging_list, &outstanding_resources);
796 // As in write_wim_resource(), each resource we read is checksummed.
797 SHA_CTX next_sha_ctx;
798 sha1_init(&next_sha_ctx);
799 u8 next_hash[SHA1_HASH_SIZE];
801 // Resources that don't need any chunks compressed are added to this
802 // list and written directly by the main thread.
803 LIST_HEAD(my_resources);
805 struct lookup_table_entry *cur_lte = next_lte;
806 struct chunk_table *cur_chunk_tab = NULL;
810 ntfs_inode *ni = NULL;
814 ret = prepare_resource_for_read(next_lte, &ni);
816 ret = prepare_resource_for_read(next_lte);
821 DEBUG("Initializing buffers for uncompressed "
822 "and compressed data (%zu bytes needed)",
823 queue_size * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
825 // Pre-allocate all the buffers that will be needed to do the chunk
827 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
828 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
829 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
830 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
831 if (msgs[i].compressed_chunks[j] == NULL ||
832 msgs[i].uncompressed_chunks[j] == NULL)
834 ERROR("Could not allocate enough memory for "
835 "multi-threaded compression");
836 ret = WIMLIB_ERR_NOMEM;
842 // This loop is executed until all resources have been written, except
843 // possibly a few that have been added to the @my_resources list for
846 // Send chunks to the compressor threads until either (a) there
847 // are no more messages available since they were all sent off,
848 // or (b) there are no more resources that need to be
850 while (!list_empty(&available_msgs) && next_lte != NULL) {
852 // Get a message from the available messages
854 msg = container_of(available_msgs.next,
858 // ... and delete it from the available messages
860 list_del(&msg->list);
862 // Initialize the message with the chunks to
864 msg->num_chunks = min(next_num_chunks - next_chunk,
867 msg->complete = false;
868 msg->begin_chunk = next_chunk;
870 unsigned size = WIM_CHUNK_SIZE;
871 for (unsigned i = 0; i < msg->num_chunks; i++) {
873 // Read chunk @next_chunk of the stream into the
874 // message so that a compressor thread can
877 if (next_chunk == next_num_chunks - 1 &&
878 wim_resource_size(next_lte) % WIM_CHUNK_SIZE != 0)
880 size = wim_resource_size(next_lte) % WIM_CHUNK_SIZE;
884 DEBUG2("Read resource (size=%u, offset=%zu)",
885 size, next_chunk * WIM_CHUNK_SIZE);
887 msg->uncompressed_chunk_sizes[i] = size;
889 ret = read_wim_resource(next_lte,
890 msg->uncompressed_chunks[i],
892 next_chunk * WIM_CHUNK_SIZE,
896 sha1_update(&next_sha_ctx,
897 msg->uncompressed_chunks[i], size);
901 // Send the compression request
902 list_add_tail(&msg->list, &next_lte->msg_list);
903 shared_queue_put(res_to_compress_queue, msg);
904 DEBUG2("Compression request sent");
906 if (next_chunk != next_num_chunks)
907 // More chunks to send for this resource
910 // Done sending compression requests for a resource!
911 // Check the SHA1 message digest.
912 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)", next_num_chunks);
913 sha1_final(next_hash, &next_sha_ctx);
914 if (!hashes_equal(next_lte->hash, next_hash)) {
915 ERROR("WIM resource has incorrect hash!");
916 if (next_lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
917 ERROR("We were reading it from `%s'; maybe it changed "
918 "while we were reading it.",
919 next_lte->file_on_disk);
921 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
925 // Advance to the next resource.
927 // If the next resource needs no compression, just write
928 // it with this thread (not now though--- we could be in
929 // the middle of writing another resource.) Keep doing
930 // this until we either get to the end of the resources
931 // list, or we get to a resource that needs compression.
934 if (next_resource == stream_list) {
939 end_wim_resource_read(next_lte, ni);
942 end_wim_resource_read(next_lte);
945 next_lte = container_of(next_resource,
946 struct lookup_table_entry,
948 next_resource = next_resource->next;
949 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
950 && next_lte->resource_location == RESOURCE_IN_WIM
951 && wimlib_get_compression_type(next_lte->wim) == out_ctype)
952 || wim_resource_size(next_lte) == 0)
954 list_add_tail(&next_lte->staging_list,
957 list_add_tail(&next_lte->staging_list,
958 &outstanding_resources);
960 next_num_chunks = wim_resource_chunks(next_lte);
961 sha1_init(&next_sha_ctx);
962 INIT_LIST_HEAD(&next_lte->msg_list);
964 ret = prepare_resource_for_read(next_lte, &ni);
966 ret = prepare_resource_for_read(next_lte);
970 DEBUG2("Updated next_lte");
976 // If there are no outstanding resources, there are no more
977 // resources that need to be written.
978 if (list_empty(&outstanding_resources)) {
979 DEBUG("No outstanding resources! Done");
984 // Get the next message from the queue and process it.
985 // The message will contain 1 or more data chunks that have been
987 DEBUG2("Waiting for message");
988 msg = shared_queue_get(compressed_res_queue);
989 msg->complete = true;
991 DEBUG2("Received msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
993 list_for_each_entry(msg, &cur_lte->msg_list, list) {
994 DEBUG2("complete=%d", msg->complete);
997 // Is this the next chunk in the current resource? If it's not
998 // (i.e., an earlier chunk in a same or different resource
999 // hasn't been compressed yet), do nothing, and keep this
1000 // message around until all earlier chunks are received.
1002 // Otherwise, write all the chunks we can.
1003 while (!list_empty(&cur_lte->msg_list)
1004 && (msg = container_of(cur_lte->msg_list.next,
1008 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1009 if (msg->begin_chunk == 0) {
1010 DEBUG2("Begin chunk tab");
1012 // This is the first set of chunks. Leave space
1013 // for the chunk table in the output file.
1014 off_t cur_offset = ftello(out_fp);
1015 if (cur_offset == -1) {
1016 ret = WIMLIB_ERR_WRITE;
1019 ret = begin_wim_resource_chunk_tab(cur_lte,
1027 // Write the compressed chunks from the message.
1028 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1032 list_del(&msg->list);
1034 // This message is available to use for different chunks
1036 list_add(&msg->list, &available_msgs);
1038 // Was this the last chunk of the stream? If so,
1040 if (list_empty(&cur_lte->msg_list) &&
1041 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1043 DEBUG2("Finish wim chunk tab");
1045 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1051 progress->write_streams.completed_bytes +=
1052 wim_resource_size(cur_lte);
1053 progress->write_streams.completed_streams++;
1055 if (progress_func) {
1056 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1060 cur_lte->output_resource_entry.size =
1063 cur_lte->output_resource_entry.original_size =
1064 cur_lte->resource_entry.original_size;
1066 cur_lte->output_resource_entry.offset =
1067 cur_chunk_tab->file_offset;
1069 cur_lte->output_resource_entry.flags =
1070 cur_lte->resource_entry.flags |
1071 WIM_RESHDR_FLAG_COMPRESSED;
1073 FREE(cur_chunk_tab);
1074 cur_chunk_tab = NULL;
1076 struct list_head *next = cur_lte->staging_list.next;
1077 list_del(&cur_lte->staging_list);
1079 if (next == &outstanding_resources) {
1080 DEBUG("No more outstanding resources");
1084 cur_lte = container_of(cur_lte->staging_list.next,
1085 struct lookup_table_entry,
1089 // Since we just finished writing a stream,
1090 // write any streams that have been added to the
1091 // my_resources list for direct writing by the
1092 // main thread (e.g. resources that don't need
1093 // to be compressed because the desired
1094 // compression type is the same as the previous
1095 // compression type).
1096 ret = do_write_stream_list(&my_resources,
1110 end_wim_resource_read(cur_lte, ni);
1112 end_wim_resource_read(cur_lte);
1115 ret = do_write_stream_list(&my_resources, out_fp,
1116 out_ctype, progress_func,
1119 size_t num_available_msgs = 0;
1120 struct list_head *cur;
1122 list_for_each(cur, &available_msgs) {
1123 num_available_msgs++;
1126 while (num_available_msgs < ARRAY_LEN(msgs)) {
1127 shared_queue_get(compressed_res_queue);
1128 num_available_msgs++;
1132 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
1133 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1134 FREE(msgs[i].compressed_chunks[j]);
1135 FREE(msgs[i].uncompressed_chunks[j]);
1139 if (cur_chunk_tab != NULL)
1140 FREE(cur_chunk_tab);
1145 static int write_stream_list_parallel(struct list_head *stream_list,
1149 unsigned num_threads,
1150 wimlib_progress_func_t progress_func,
1151 union wimlib_progress_info *progress)
1154 struct shared_queue res_to_compress_queue;
1155 struct shared_queue compressed_res_queue;
1156 pthread_t *compressor_threads = NULL;
1158 if (num_threads == 0) {
1159 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1161 WARNING("Could not determine number of processors! Assuming 1");
1164 num_threads = nthreads;
1168 progress->write_streams.num_threads = num_threads;
1169 wimlib_assert(stream_list->next != stream_list);
1171 static const double MESSAGES_PER_THREAD = 2.0;
1172 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1174 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1176 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1180 ret = shared_queue_init(&compressed_res_queue, queue_size);
1182 goto out_destroy_res_to_compress_queue;
1184 struct compressor_thread_params params;
1185 params.res_to_compress_queue = &res_to_compress_queue;
1186 params.compressed_res_queue = &compressed_res_queue;
1187 params.compress = get_compress_func(out_ctype);
1189 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1191 for (unsigned i = 0; i < num_threads; i++) {
1192 DEBUG("pthread_create thread %u", i);
1193 ret = pthread_create(&compressor_threads[i], NULL,
1194 compressor_thread_proc, ¶ms);
1197 ERROR_WITH_ERRNO("Failed to create compressor "
1205 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1207 ret = main_writer_thread_proc(stream_list,
1210 &res_to_compress_queue,
1211 &compressed_res_queue,
1217 for (unsigned i = 0; i < num_threads; i++)
1218 shared_queue_put(&res_to_compress_queue, NULL);
1220 for (unsigned i = 0; i < num_threads; i++) {
1221 if (pthread_join(compressor_threads[i], NULL)) {
1222 WARNING("Failed to join compressor thread %u: %s",
1223 i, strerror(errno));
1226 FREE(compressor_threads);
1227 shared_queue_destroy(&compressed_res_queue);
1228 out_destroy_res_to_compress_queue:
1229 shared_queue_destroy(&res_to_compress_queue);
1230 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1233 WARNING("Falling back to single-threaded compression");
1234 return write_stream_list_serial(stream_list,
1245 * Write a list of streams to a WIM (@out_fp) using the compression type
1246 * @out_ctype and up to @num_threads compressor threads.
1248 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1249 int out_ctype, int write_flags,
1250 unsigned num_threads,
1251 wimlib_progress_func_t progress_func)
1253 struct lookup_table_entry *lte;
1254 size_t num_streams = 0;
1255 u64 total_bytes = 0;
1256 bool compression_needed = false;
1257 union wimlib_progress_info progress;
1260 list_for_each_entry(lte, stream_list, staging_list) {
1262 total_bytes += wim_resource_size(lte);
1263 if (!compression_needed
1265 (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1266 && (lte->resource_location != RESOURCE_IN_WIM
1267 || wimlib_get_compression_type(lte->wim) != out_ctype
1268 || (write_flags & WIMLIB_WRITE_FLAG_REBUILD)))
1269 && wim_resource_size(lte) != 0)
1270 compression_needed = true;
1272 progress.write_streams.total_bytes = total_bytes;
1273 progress.write_streams.total_streams = num_streams;
1274 progress.write_streams.completed_bytes = 0;
1275 progress.write_streams.completed_streams = 0;
1276 progress.write_streams.num_threads = num_threads;
1277 progress.write_streams.compression_type = out_ctype;
1279 if (num_streams == 0) {
1284 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1285 if (compression_needed && total_bytes >= 1000000 && num_threads != 1) {
1286 ret = write_stream_list_parallel(stream_list,
1297 ret = write_stream_list_serial(stream_list,
1309 static int dentry_find_streams_to_write(struct dentry *dentry,
1313 struct list_head *stream_list = w->private;
1314 struct lookup_table_entry *lte;
1315 for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1316 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1317 if (lte && ++lte->out_refcnt == 1)
1318 list_add_tail(<e->staging_list, stream_list);
1323 static int find_streams_to_write(WIMStruct *w)
1325 return for_dentry_in_tree(wim_root_dentry(w),
1326 dentry_find_streams_to_write, w);
1329 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1330 unsigned num_threads,
1331 wimlib_progress_func_t progress_func)
1334 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1335 LIST_HEAD(stream_list);
1336 w->private = &stream_list;
1337 for_image(w, image, find_streams_to_write);
1338 return write_stream_list(&stream_list, w->out_fp,
1339 wimlib_get_compression_type(w), write_flags,
1340 num_threads, progress_func);
1344 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1345 * table (optional), then overwrite the WIM header.
1347 * write_flags is a bitwise OR of the following:
1349 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1350 * Include an integrity table.
1352 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1353 * Show progress information when (if) writing the integrity table.
1355 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1356 * Don't write the lookup table.
1358 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1359 * When (if) writing the integrity table, re-use entries from the
1360 * existing integrity table, if possible.
1362 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1363 * After writing the XML data but before writing the integrity
1364 * table, write a temporary WIM header and flush the stream so that
1365 * the WIM is less likely to become corrupted upon abrupt program
1368 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1369 * fsync() the output file before closing it.
1372 int finish_write(WIMStruct *w, int image, int write_flags,
1373 wimlib_progress_func_t progress_func)
1376 struct wim_header hdr;
1377 FILE *out = w->out_fp;
1379 /* @hdr will be the header for the new WIM. First copy all the data
1380 * from the header in the WIMStruct; then set all the fields that may
1381 * have changed, including the resource entries, boot index, and image
1383 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1385 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1386 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1391 ret = write_xml_data(w->wim_info, image, out,
1392 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1393 wim_info_get_total_bytes(w->wim_info) : 0,
1394 &hdr.xml_res_entry);
1398 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1399 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1400 struct wim_header checkpoint_hdr;
1401 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1402 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1403 if (fseeko(out, 0, SEEK_SET) != 0) {
1404 ret = WIMLIB_ERR_WRITE;
1407 ret = write_header(&checkpoint_hdr, out);
1411 if (fflush(out) != 0) {
1412 ERROR_WITH_ERRNO("Can't write data to WIM");
1413 ret = WIMLIB_ERR_WRITE;
1417 if (fseeko(out, 0, SEEK_END) != 0) {
1418 ret = WIMLIB_ERR_WRITE;
1423 off_t old_lookup_table_end;
1424 off_t new_lookup_table_end;
1425 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1426 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1427 w->hdr.lookup_table_res_entry.size;
1429 old_lookup_table_end = 0;
1431 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1432 hdr.lookup_table_res_entry.size;
1434 ret = write_integrity_table(out,
1436 new_lookup_table_end,
1437 old_lookup_table_end,
1442 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1446 * In the WIM header, there is room for the resource entry for a
1447 * metadata resource labeled as the "boot metadata". This entry should
1448 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1449 * it should be a copy of the resource entry for the image that is
1450 * marked as bootable. This is not well documented...
1452 if (hdr.boot_idx == 0 || !w->image_metadata
1453 || (image != WIMLIB_ALL_IMAGES && image != hdr.boot_idx)) {
1454 memset(&hdr.boot_metadata_res_entry, 0,
1455 sizeof(struct resource_entry));
1457 memcpy(&hdr.boot_metadata_res_entry,
1459 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1460 sizeof(struct resource_entry));
1463 /* Set image count and boot index correctly for single image writes */
1464 if (image != WIMLIB_ALL_IMAGES) {
1465 hdr.image_count = 1;
1466 if (hdr.boot_idx == image)
1472 if (fseeko(out, 0, SEEK_SET) != 0) {
1473 ret = WIMLIB_ERR_WRITE;
1477 ret = write_header(&hdr, out);
1481 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1482 if (fflush(out) != 0
1483 || fsync(fileno(out)) != 0)
1485 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1486 ret = WIMLIB_ERR_WRITE;
1490 if (fclose(out) != 0) {
1491 ERROR_WITH_ERRNO("Failed to close the WIM file");
1493 ret = WIMLIB_ERR_WRITE;
1499 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1500 int lock_wim(FILE *fp, const char *path)
1504 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1506 if (errno == EWOULDBLOCK) {
1507 ERROR("`%s' is already being modified or has been "
1508 "mounted read-write\n"
1509 " by another process!", path);
1510 ret = WIMLIB_ERR_ALREADY_LOCKED;
1512 WARNING("Failed to lock `%s': %s",
1513 path, strerror(errno));
1522 static int open_wim_writable(WIMStruct *w, const char *path,
1523 bool trunc, bool readable)
1535 DEBUG("Opening `%s' read-write", path);
1536 wimlib_assert(w->out_fp == NULL);
1537 wimlib_assert(path != NULL);
1538 w->out_fp = fopen(path, mode);
1540 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
1541 return WIMLIB_ERR_OPEN;
1544 ret = lock_wim(w->out_fp, path);
1554 static void close_wim_writable(WIMStruct *w)
1557 if (fclose(w->out_fp) != 0) {
1558 WARNING("Failed to close output WIM: %s",
1565 /* Open file stream and write dummy header for WIM. */
1566 int begin_write(WIMStruct *w, const char *path, int write_flags)
1569 bool need_readable = false;
1571 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1572 need_readable = true;
1574 ret = open_wim_writable(w, path, trunc, need_readable);
1577 /* Write dummy header. It will be overwritten later. */
1578 return write_header(&w->hdr, w->out_fp);
1581 /* Writes a stand-alone WIM to a file. */
1582 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1583 int image, int write_flags, unsigned num_threads,
1584 wimlib_progress_func_t progress_func)
1589 return WIMLIB_ERR_INVALID_PARAM;
1591 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1593 if (image != WIMLIB_ALL_IMAGES &&
1594 (image < 1 || image > w->hdr.image_count))
1595 return WIMLIB_ERR_INVALID_IMAGE;
1597 if (w->hdr.total_parts != 1) {
1598 ERROR("Cannot call wimlib_write() on part of a split WIM");
1599 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1602 ret = begin_write(w, path, write_flags);
1606 ret = write_wim_streams(w, image, write_flags, num_threads,
1612 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1614 ret = for_image(w, image, write_metadata_resource);
1619 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1621 ret = finish_write(w, image, write_flags, progress_func);
1623 close_wim_writable(w);
1627 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1630 memcpy(<e->output_resource_entry, <e->resource_entry,
1631 sizeof(struct resource_entry));
1632 lte->out_refcnt = 0;
1636 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1638 off_t end_offset = *(u64*)arg;
1640 wimlib_assert(lte->out_refcnt <= lte->refcnt);
1641 if (lte->out_refcnt < lte->refcnt) {
1642 if (lte->resource_entry.offset + lte->resource_entry.size > end_offset) {
1643 ERROR("The following resource is after the XML data:");
1644 print_lookup_table_entry(lte);
1645 return WIMLIB_ERR_RESOURCE_ORDER;
1651 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1653 if (lte->out_refcnt == lte->refcnt)
1654 list_add(<e->staging_list, (struct list_head*)arg);
1656 lte->out_refcnt = lte->refcnt;
1661 * Overwrite a WIM, possibly appending streams to it.
1663 * A WIM looks like (or is supposed to look like) the following:
1665 * Header (212 bytes)
1666 * Streams and metadata resources (variable size)
1667 * Lookup table (variable size)
1668 * XML data (variable size)
1669 * Integrity table (optional) (variable size)
1671 * If we are not adding any streams or metadata resources, the lookup table is
1672 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1673 * header. This operation is potentially unsafe if the program is abruptly
1674 * terminated while the XML data or integrity table are being overwritten, but
1675 * before the new header has been written. To partially alleviate this problem,
1676 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1677 * finish_write() to cause a temporary WIM header to be written after the XML
1678 * data has been written. This may prevent the WIM from becoming corrupted if
1679 * the program is terminated while the integrity table is being calculated (but
1680 * no guarantees, due to write re-ordering...).
1682 * If we are adding new streams or images (metadata resources), the lookup table
1683 * needs to be changed, and those streams need to be written. In this case, we
1684 * try to perform a safe update of the WIM file by writing the streams *after*
1685 * the end of the previous WIM, then writing the new lookup table, XML data, and
1686 * (optionally) integrity table following the new streams. This will produce a
1687 * layout like the following:
1689 * Header (212 bytes)
1690 * (OLD) Streams and metadata resources (variable size)
1691 * (OLD) Lookup table (variable size)
1692 * (OLD) XML data (variable size)
1693 * (OLD) Integrity table (optional) (variable size)
1694 * (NEW) Streams and metadata resources (variable size)
1695 * (NEW) Lookup table (variable size)
1696 * (NEW) XML data (variable size)
1697 * (NEW) Integrity table (optional) (variable size)
1699 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1700 * the header is overwritten to point to the new lookup table, XML data, and
1701 * integrity table, to produce the following layout:
1703 * Header (212 bytes)
1704 * Streams and metadata resources (variable size)
1705 * Nothing (variable size)
1706 * More Streams and metadata resources (variable size)
1707 * Lookup table (variable size)
1708 * XML data (variable size)
1709 * Integrity table (optional) (variable size)
1711 * This method allows an image to be appended to a large WIM very quickly, and
1712 * is is crash-safe except in the case of write re-ordering, but the
1713 * disadvantage is that a small hole is left in the WIM where the old lookup
1714 * table, xml data, and integrity table were. (These usually only take up a
1715 * small amount of space compared to the streams, however.
1717 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1718 unsigned num_threads,
1719 wimlib_progress_func_t progress_func,
1720 int modified_image_idx)
1723 struct list_head stream_list;
1726 DEBUG("Overwriting `%s' in-place", w->filename);
1728 /* Make sure that the integrity table (if present) is after the XML
1729 * data, and that there are no stream resources, metadata resources, or
1730 * lookup tables after the XML data. Otherwise, these data would be
1732 if (w->hdr.integrity.offset != 0 &&
1733 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1734 ERROR("Didn't expect the integrity table to be before the XML data");
1735 return WIMLIB_ERR_RESOURCE_ORDER;
1738 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1739 ERROR("Didn't expect the lookup table to be after the XML data");
1740 return WIMLIB_ERR_RESOURCE_ORDER;
1743 DEBUG("Identifying newly added streams");
1744 for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1745 INIT_LIST_HEAD(&stream_list);
1746 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1747 DEBUG("Identifiying streams in image %d", i + 1);
1748 wimlib_assert(w->image_metadata[i].modified);
1749 wimlib_assert(!w->image_metadata[i].has_been_mounted_rw);
1750 wimlib_assert(w->image_metadata[i].root_dentry != NULL);
1751 wimlib_assert(w->image_metadata[i].metadata_lte != NULL);
1752 w->private = &stream_list;
1753 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1754 dentry_find_streams_to_write, w);
1757 if (w->hdr.integrity.offset)
1758 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1760 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1762 ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1767 if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1768 /* If no images have been modified and no images have been
1769 * deleted, a new lookup table does not need to be written. */
1770 wimlib_assert(list_empty(&stream_list));
1771 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1772 w->hdr.lookup_table_res_entry.size;
1773 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1774 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1777 INIT_LIST_HEAD(&stream_list);
1778 for_lookup_table_entry(w->lookup_table, find_new_streams,
1781 ret = open_wim_writable(w, w->filename, false,
1782 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1786 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1787 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1788 return WIMLIB_ERR_WRITE;
1791 if (!list_empty(&stream_list)) {
1792 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1794 ret = write_stream_list(&stream_list, w->out_fp,
1795 wimlib_get_compression_type(w),
1796 write_flags, num_threads,
1801 DEBUG("No new streams were added");
1804 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1805 select_wim_image(w, i + 1);
1806 ret = write_metadata_resource(w);
1810 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1811 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1814 close_wim_writable(w);
1816 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1817 w->filename, old_wim_end);
1818 truncate(w->filename, old_wim_end);
1823 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1824 unsigned num_threads,
1825 wimlib_progress_func_t progress_func)
1827 size_t wim_name_len;
1830 DEBUG("Overwriting `%s' via a temporary file", w->filename);
1832 /* Write the WIM to a temporary file in the same directory as the
1834 wim_name_len = strlen(w->filename);
1835 char tmpfile[wim_name_len + 10];
1836 memcpy(tmpfile, w->filename, wim_name_len);
1837 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1838 tmpfile[wim_name_len + 9] = '\0';
1840 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1841 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1842 num_threads, progress_func);
1844 ERROR("Failed to write the WIM file `%s'", tmpfile);
1848 /* Close the original WIM file that was opened for reading. */
1849 if (w->fp != NULL) {
1854 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1856 /* Rename the new file to the old file .*/
1857 if (rename(tmpfile, w->filename) != 0) {
1858 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1859 tmpfile, w->filename);
1860 ret = WIMLIB_ERR_RENAME;
1864 if (progress_func) {
1865 union wimlib_progress_info progress;
1866 progress.rename.from = tmpfile;
1867 progress.rename.to = w->filename;
1868 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1871 /* Re-open the WIM read-only. */
1872 w->fp = fopen(w->filename, "rb");
1873 if (w->fp == NULL) {
1874 ret = WIMLIB_ERR_REOPEN;
1875 WARNING("Failed to re-open `%s' read-only: %s",
1876 w->filename, strerror(errno));
1880 /* Remove temporary file. */
1881 if (unlink(tmpfile) != 0)
1882 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1887 * Writes a WIM file to the original file that it was read from, overwriting it.
1889 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1890 unsigned num_threads,
1891 wimlib_progress_func_t progress_func)
1894 return WIMLIB_ERR_INVALID_PARAM;
1896 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1899 return WIMLIB_ERR_NO_FILENAME;
1901 if (w->hdr.total_parts != 1) {
1902 ERROR("Cannot modify a split WIM");
1903 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1906 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1907 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1909 int i, modified_image_idx;
1910 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1912 modified_image_idx = i;
1913 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1914 !w->image_metadata[i].has_been_mounted_rw; i++)
1916 if (i == w->hdr.image_count) {
1917 return overwrite_wim_inplace(w, write_flags, num_threads,
1919 modified_image_idx);
1922 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,