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/.
28 #include "wimlib_internal.h"
31 #include "lookup_table.h"
37 #ifdef ENABLE_MULTITHREADED_COMPRESSION
38 #include <semaphore.h>
46 #include <ntfs-3g/attrib.h>
47 #include <ntfs-3g/inode.h>
48 #include <ntfs-3g/dir.h>
58 static int do_fflush(FILE *fp)
62 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
63 return WIMLIB_ERR_WRITE;
68 static int fflush_and_ftruncate(FILE *fp, off_t size)
75 ret = ftruncate(fileno(fp), size);
77 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
78 "%"PRIu64" bytes", size);
79 return WIMLIB_ERR_WRITE;
84 /* Chunk table that's located at the beginning of each compressed resource in
85 * the WIM. (This is not the on-disk format; the on-disk format just has an
86 * array of offsets.) */
90 u64 original_resource_size;
91 u64 bytes_per_chunk_entry;
99 * Allocates and initializes a chunk table, and reserves space for it in the
103 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
106 struct chunk_table **chunk_tab_ret)
108 u64 size = wim_resource_size(lte);
109 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
110 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
111 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
115 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
117 ret = WIMLIB_ERR_NOMEM;
120 chunk_tab->file_offset = file_offset;
121 chunk_tab->num_chunks = num_chunks;
122 chunk_tab->original_resource_size = size;
123 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
124 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
126 chunk_tab->cur_offset = 0;
127 chunk_tab->cur_offset_p = chunk_tab->offsets;
129 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
130 chunk_tab->table_disk_size) {
131 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
133 ret = WIMLIB_ERR_WRITE;
139 *chunk_tab_ret = chunk_tab;
144 * Pointer to function to compresses a chunk of a WIM resource.
146 * @chunk: Uncompressed data of the chunk.
147 * @chunk_size: Size of the uncompressed chunk in bytes.
148 * @compressed_chunk: Pointer to output buffer of size at least
149 * (@chunk_size - 1) bytes.
150 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
151 * of the compressed chunk will be
154 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
155 * compressed to any smaller than @chunk_size. This function cannot fail for
158 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
160 compress_func_t get_compress_func(int out_ctype)
162 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
165 return xpress_compress;
169 * Writes a chunk of a WIM resource to an output file.
171 * @chunk: Uncompressed data of the chunk.
172 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
173 * @out_fp: FILE * to write tho chunk to.
174 * @out_ctype: Compression type to use when writing the chunk (ignored if no
175 * chunk table provided)
176 * @chunk_tab: Pointer to chunk table being created. It is updated with the
177 * offset of the chunk we write.
179 * Returns 0 on success; nonzero on failure.
181 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
182 FILE *out_fp, compress_func_t compress,
183 struct chunk_table *chunk_tab)
186 unsigned out_chunk_size;
188 u8 *compressed_chunk = alloca(chunk_size);
191 ret = compress(chunk, chunk_size, compressed_chunk,
194 out_chunk = compressed_chunk;
197 out_chunk_size = chunk_size;
199 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
200 chunk_tab->cur_offset += out_chunk_size;
203 out_chunk_size = chunk_size;
205 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
206 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
207 return WIMLIB_ERR_WRITE;
213 * Finishes a WIM chunk tale and writes it to the output file at the correct
216 * The final size of the full compressed resource is returned in the
217 * @compressed_size_p.
220 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
221 FILE *out_fp, u64 *compressed_size_p)
223 size_t bytes_written;
224 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
225 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
226 "WIM file", chunk_tab->file_offset);
227 return WIMLIB_ERR_WRITE;
230 if (chunk_tab->bytes_per_chunk_entry == 8) {
231 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
233 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
234 ((u32*)chunk_tab->offsets)[i] =
235 cpu_to_le32(chunk_tab->offsets[i]);
237 bytes_written = fwrite((u8*)chunk_tab->offsets +
238 chunk_tab->bytes_per_chunk_entry,
239 1, chunk_tab->table_disk_size, out_fp);
240 if (bytes_written != chunk_tab->table_disk_size) {
241 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
243 return WIMLIB_ERR_WRITE;
245 if (fseeko(out_fp, 0, SEEK_END) != 0) {
246 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
247 return WIMLIB_ERR_WRITE;
249 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
253 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
254 * attribute pointer in the lookup table entry. */
255 static int prepare_resource_for_read(struct lookup_table_entry *lte
258 , ntfs_inode **ni_ret
262 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
263 && !lte->file_on_disk_fp)
265 wimlib_assert(lte->file_on_disk);
266 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
267 if (!lte->file_on_disk_fp) {
268 ERROR_WITH_ERRNO("Failed to open the file `%s' for "
269 "reading", lte->file_on_disk);
270 return WIMLIB_ERR_OPEN;
274 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
277 struct ntfs_location *loc = lte->ntfs_loc;
280 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
282 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
283 "volume", loc->path_utf8);
284 return WIMLIB_ERR_NTFS_3G;
286 lte->attr = ntfs_attr_open(ni,
287 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
288 (ntfschar*)loc->stream_name_utf16,
289 loc->stream_name_utf16_num_chars);
291 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
292 "NTFS volume", loc->path_utf8);
293 ntfs_inode_close(ni);
294 return WIMLIB_ERR_NTFS_3G;
302 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
304 static void end_wim_resource_read(struct lookup_table_entry *lte
310 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
311 && lte->file_on_disk_fp) {
312 fclose(lte->file_on_disk_fp);
313 lte->file_on_disk_fp = NULL;
316 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
318 ntfs_attr_close(lte->attr);
322 ntfs_inode_close(ni);
328 * Writes a WIM resource to a FILE * opened for writing. The resource may be
329 * written uncompressed or compressed depending on the @out_ctype parameter.
331 * If by chance the resource compresses to more than the original size (this may
332 * happen with random data or files than are pre-compressed), the resource is
333 * instead written uncompressed (and this is reflected in the @out_res_entry by
334 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
336 * @lte: The lookup table entry for the WIM resource.
337 * @out_fp: The FILE * to write the resource to.
338 * @out_ctype: The compression type of the resource to write. Note: if this is
339 * the same as the compression type of the WIM resource we
340 * need to read, we simply copy the data (i.e. we do not
341 * uncompress it, then compress it again).
342 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
343 * offset, original size, compressed size, and compression flag
344 * of the output resource.
346 * Returns 0 on success; nonzero on failure.
348 int write_wim_resource(struct lookup_table_entry *lte,
349 FILE *out_fp, int out_ctype,
350 struct resource_entry *out_res_entry,
355 u64 old_compressed_size;
356 u64 new_compressed_size;
359 struct chunk_table *chunk_tab = NULL;
362 compress_func_t compress = NULL;
364 ntfs_inode *ni = NULL;
369 /* Original size of the resource */
370 original_size = wim_resource_size(lte);
372 /* Compressed size of the resource (as it exists now) */
373 old_compressed_size = wim_resource_compressed_size(lte);
375 /* Current offset in output file */
376 file_offset = ftello(out_fp);
377 if (file_offset == -1) {
378 ERROR_WITH_ERRNO("Failed to get offset in output "
380 return WIMLIB_ERR_WRITE;
383 /* Are the compression types the same? If so, do a raw copy (copy
384 * without decompressing and recompressing the data). */
385 raw = (wim_resource_compression_type(lte) == out_ctype
386 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
387 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
390 flags |= WIMLIB_RESOURCE_FLAG_RAW;
391 bytes_remaining = old_compressed_size;
393 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
394 bytes_remaining = original_size;
397 /* Empty resource; nothing needs to be done, so just return success. */
398 if (bytes_remaining == 0)
401 /* Buffer for reading chunks for the resource */
402 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
404 /* If we are writing a compressed resource and not doing a raw copy, we
405 * need to initialize the chunk table */
406 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
407 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
413 /* If the WIM resource is in an external file, open a FILE * to it so we
414 * don't have to open a temporary one in read_wim_resource() for each
417 ret = prepare_resource_for_read(lte, &ni);
419 ret = prepare_resource_for_read(lte);
424 /* If we aren't doing a raw copy, we will compute the SHA1 message
425 * digest of the resource as we read it, and verify it's the same as the
426 * hash given in the lookup table entry once we've finished reading the
431 compress = get_compress_func(out_ctype);
435 /* While there are still bytes remaining in the WIM resource, read a
436 * chunk of the resource, update SHA1, then write that chunk using the
437 * desired compression type. */
439 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
440 ret = read_wim_resource(lte, buf, to_read, offset, flags);
444 sha1_update(&ctx, buf, to_read);
445 ret = write_wim_resource_chunk(buf, to_read, out_fp,
446 compress, chunk_tab);
449 bytes_remaining -= to_read;
451 } while (bytes_remaining);
453 /* Raw copy: The new compressed size is the same as the old compressed
456 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
459 * Using a different compression type: Call
460 * finish_wim_resource_chunk_tab() and it will provide the new
464 new_compressed_size = old_compressed_size;
466 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
467 new_compressed_size = original_size;
469 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
470 &new_compressed_size);
476 /* Verify SHA1 message digest of the resource, unless we are doing a raw
477 * write (in which case we never even saw the uncompressed data). Or,
478 * if the hash we had before is all 0's, just re-set it to be the new
481 u8 md[SHA1_HASH_SIZE];
482 sha1_final(md, &ctx);
483 if (is_zero_hash(lte->hash)) {
484 copy_hash(lte->hash, md);
485 } else if (!hashes_equal(md, lte->hash)) {
486 ERROR("WIM resource has incorrect hash!");
487 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
488 ERROR("We were reading it from `%s'; maybe it changed "
489 "while we were reading it.",
492 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
497 if (!raw && new_compressed_size >= original_size &&
498 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
500 /* Oops! We compressed the resource to larger than the original
501 * size. Write the resource uncompressed instead. */
502 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
503 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
504 "of output WIM file", file_offset);
505 ret = WIMLIB_ERR_WRITE;
508 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
509 out_res_entry, flags);
513 ret = fflush_and_ftruncate(out_fp, file_offset + out_res_entry->size);
518 out_res_entry->size = new_compressed_size;
519 out_res_entry->original_size = original_size;
520 out_res_entry->offset = file_offset;
521 out_res_entry->flags = lte->resource_entry.flags
522 & ~WIM_RESHDR_FLAG_COMPRESSED;
523 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
524 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
530 end_wim_resource_read(lte, ni);
532 end_wim_resource_read(lte);
539 #ifdef ENABLE_MULTITHREADED_COMPRESSION
540 struct shared_queue {
543 pthread_mutex_t lock;
550 static int shared_queue_init(struct shared_queue *q, unsigned size)
552 q->array = CALLOC(sizeof(q->array[0]), size);
554 return WIMLIB_ERR_NOMEM;
556 sem_init(&q->filled_slots, 0, 0);
557 sem_init(&q->empty_slots, 0, size);
558 pthread_mutex_init(&q->lock, NULL);
565 static void shared_queue_destroy(struct shared_queue *q)
567 sem_destroy(&q->filled_slots);
568 sem_destroy(&q->empty_slots);
569 pthread_mutex_destroy(&q->lock);
573 static void shared_queue_put(struct shared_queue *q, void *obj)
575 sem_wait(&q->empty_slots);
576 pthread_mutex_lock(&q->lock);
578 q->back = (q->back + 1) % q->size;
579 q->array[q->back] = obj;
581 sem_post(&q->filled_slots);
582 pthread_mutex_unlock(&q->lock);
585 static void *shared_queue_get(struct shared_queue *q)
587 sem_wait(&q->filled_slots);
588 pthread_mutex_lock(&q->lock);
590 void *obj = q->array[q->front];
591 q->array[q->front] = NULL;
592 q->front = (q->front + 1) % q->size;
594 sem_post(&q->empty_slots);
595 pthread_mutex_unlock(&q->lock);
599 struct compressor_thread_params {
600 struct shared_queue *res_to_compress_queue;
601 struct shared_queue *compressed_res_queue;
602 compress_func_t compress;
605 #define MAX_CHUNKS_PER_MSG 2
608 struct lookup_table_entry *lte;
609 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
610 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
611 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
612 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
613 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
615 struct list_head list;
620 static void compress_chunks(struct message *msg, compress_func_t compress)
622 for (unsigned i = 0; i < msg->num_chunks; i++) {
623 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
624 int ret = compress(msg->uncompressed_chunks[i],
625 msg->uncompressed_chunk_sizes[i],
626 msg->compressed_chunks[i],
627 &msg->compressed_chunk_sizes[i]);
629 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
631 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
632 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
637 static void *compressor_thread_proc(void *arg)
639 struct compressor_thread_params *params = arg;
640 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
641 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
642 compress_func_t compress = params->compress;
645 DEBUG("Compressor thread ready");
646 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
647 compress_chunks(msg, compress);
648 shared_queue_put(compressed_res_queue, msg);
650 DEBUG("Compressor thread terminating");
655 static int do_write_stream_list(struct list_head *my_resources,
658 wimlib_progress_func_t progress_func,
659 union wimlib_progress_info *progress,
660 int write_resource_flags)
663 struct lookup_table_entry *lte, *tmp;
665 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
666 ret = write_wim_resource(lte,
669 <e->output_resource_entry,
670 write_resource_flags);
673 list_del(<e->staging_list);
674 progress->write_streams.completed_bytes +=
675 wim_resource_size(lte);
676 progress->write_streams.completed_streams++;
678 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
685 static int write_stream_list_serial(struct list_head *stream_list,
689 wimlib_progress_func_t progress_func,
690 union wimlib_progress_info *progress)
692 int write_resource_flags;
694 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
695 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
697 write_resource_flags = 0;
698 progress->write_streams.num_threads = 1;
700 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
701 return do_write_stream_list(stream_list, out_fp,
702 out_ctype, progress_func,
703 progress, write_resource_flags);
706 #ifdef ENABLE_MULTITHREADED_COMPRESSION
707 static int write_wim_chunks(struct message *msg, FILE *out_fp,
708 struct chunk_table *chunk_tab)
710 for (unsigned i = 0; i < msg->num_chunks; i++) {
711 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
713 DEBUG2("Write wim chunk %u of %u (csize = %u)",
714 i, msg->num_chunks, chunk_csize);
716 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
719 ERROR_WITH_ERRNO("Failed to write WIM chunk");
720 return WIMLIB_ERR_WRITE;
723 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
724 chunk_tab->cur_offset += chunk_csize;
730 * This function is executed by the main thread when the resources are being
731 * compressed in parallel. The main thread is in change of all reading of the
732 * uncompressed data and writing of the compressed data. The compressor threads
733 * *only* do compression from/to in-memory buffers.
735 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
736 * chunks of compressed data to compress, represented in a `struct message'.
737 * Each message is passed from the main thread to a worker thread through the
738 * res_to_compress_queue, and it is passed back through the
739 * compressed_res_queue.
741 static int main_writer_thread_proc(struct list_head *stream_list,
744 struct shared_queue *res_to_compress_queue,
745 struct shared_queue *compressed_res_queue,
748 wimlib_progress_func_t progress_func,
749 union wimlib_progress_info *progress)
753 struct message msgs[queue_size];
756 // Initially, all the messages are available to use.
757 LIST_HEAD(available_msgs);
758 for (size_t i = 0; i < ARRAY_LEN(msgs); i++)
759 list_add(&msgs[i].list, &available_msgs);
761 // outstanding_resources is the list of resources that currently have
762 // had chunks sent off for compression.
764 // The first stream in outstanding_resources is the stream that is
765 // currently being written (cur_lte).
767 // The last stream in outstanding_resources is the stream that is
768 // currently being read and chunks fed to the compressor threads
771 // Depending on the number of threads and the sizes of the resource,
772 // the outstanding streams list may contain streams between cur_lte and
773 // next_lte that have all their chunks compressed or being compressed,
774 // but haven't been written yet.
776 LIST_HEAD(outstanding_resources);
777 struct list_head *next_resource = stream_list->next;
778 struct lookup_table_entry *next_lte = container_of(next_resource,
779 struct lookup_table_entry,
781 next_resource = next_resource->next;
783 u64 next_num_chunks = wim_resource_chunks(next_lte);
784 INIT_LIST_HEAD(&next_lte->msg_list);
785 list_add_tail(&next_lte->staging_list, &outstanding_resources);
787 // As in write_wim_resource(), each resource we read is checksummed.
788 SHA_CTX next_sha_ctx;
789 sha1_init(&next_sha_ctx);
790 u8 next_hash[SHA1_HASH_SIZE];
792 // Resources that don't need any chunks compressed are added to this
793 // list and written directly by the main thread.
794 LIST_HEAD(my_resources);
796 struct lookup_table_entry *cur_lte = next_lte;
797 struct chunk_table *cur_chunk_tab = NULL;
801 ntfs_inode *ni = NULL;
805 ret = prepare_resource_for_read(next_lte, &ni);
807 ret = prepare_resource_for_read(next_lte);
812 DEBUG("Initializing buffers for uncompressed "
813 "and compressed data (%zu bytes needed)",
814 queue_size * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
816 // Pre-allocate all the buffers that will be needed to do the chunk
818 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
819 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
820 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
821 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
822 if (msgs[i].compressed_chunks[j] == NULL ||
823 msgs[i].uncompressed_chunks[j] == NULL)
825 ERROR("Could not allocate enough memory for "
826 "multi-threaded compression");
827 ret = WIMLIB_ERR_NOMEM;
833 // This loop is executed until all resources have been written, except
834 // possibly a few that have been added to the @my_resources list for
837 // Send chunks to the compressor threads until either (a) there
838 // are no more messages available since they were all sent off,
839 // or (b) there are no more resources that need to be
841 while (!list_empty(&available_msgs) && next_lte != NULL) {
843 // Get a message from the available messages
845 msg = container_of(available_msgs.next,
849 // ... and delete it from the available messages
851 list_del(&msg->list);
853 // Initialize the message with the chunks to
855 msg->num_chunks = min(next_num_chunks - next_chunk,
858 msg->complete = false;
859 msg->begin_chunk = next_chunk;
861 unsigned size = WIM_CHUNK_SIZE;
862 for (unsigned i = 0; i < msg->num_chunks; i++) {
864 // Read chunk @next_chunk of the stream into the
865 // message so that a compressor thread can
868 if (next_chunk == next_num_chunks - 1 &&
869 wim_resource_size(next_lte) % WIM_CHUNK_SIZE != 0)
871 size = wim_resource_size(next_lte) % WIM_CHUNK_SIZE;
875 DEBUG2("Read resource (size=%u, offset=%zu)",
876 size, next_chunk * WIM_CHUNK_SIZE);
878 msg->uncompressed_chunk_sizes[i] = size;
880 ret = read_wim_resource(next_lte,
881 msg->uncompressed_chunks[i],
883 next_chunk * WIM_CHUNK_SIZE,
887 sha1_update(&next_sha_ctx,
888 msg->uncompressed_chunks[i], size);
892 // Send the compression request
893 list_add_tail(&msg->list, &next_lte->msg_list);
894 shared_queue_put(res_to_compress_queue, msg);
895 DEBUG2("Compression request sent");
897 if (next_chunk != next_num_chunks)
898 // More chunks to send for this resource
901 // Done sending compression requests for a resource!
902 // Check the SHA1 message digest.
903 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)", next_num_chunks);
904 sha1_final(next_hash, &next_sha_ctx);
905 if (!hashes_equal(next_lte->hash, next_hash)) {
906 ERROR("WIM resource has incorrect hash!");
907 if (next_lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
908 ERROR("We were reading it from `%s'; maybe it changed "
909 "while we were reading it.",
910 next_lte->file_on_disk);
912 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
916 // Advance to the next resource.
918 // If the next resource needs no compression, just write
919 // it with this thread (not now though--- we could be in
920 // the middle of writing another resource.) Keep doing
921 // this until we either get to the end of the resources
922 // list, or we get to a resource that needs compression.
925 if (next_resource == stream_list) {
930 end_wim_resource_read(next_lte, ni);
933 end_wim_resource_read(next_lte);
936 next_lte = container_of(next_resource,
937 struct lookup_table_entry,
939 next_resource = next_resource->next;
940 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
941 && next_lte->resource_location == RESOURCE_IN_WIM
942 && wimlib_get_compression_type(next_lte->wim) == out_ctype)
943 || wim_resource_size(next_lte) == 0)
945 list_add_tail(&next_lte->staging_list,
948 list_add_tail(&next_lte->staging_list,
949 &outstanding_resources);
951 next_num_chunks = wim_resource_chunks(next_lte);
952 sha1_init(&next_sha_ctx);
953 INIT_LIST_HEAD(&next_lte->msg_list);
955 ret = prepare_resource_for_read(next_lte, &ni);
957 ret = prepare_resource_for_read(next_lte);
961 DEBUG2("Updated next_lte");
967 // If there are no outstanding resources, there are no more
968 // resources that need to be written.
969 if (list_empty(&outstanding_resources)) {
970 DEBUG("No outstanding resources! Done");
975 // Get the next message from the queue and process it.
976 // The message will contain 1 or more data chunks that have been
978 DEBUG2("Waiting for message");
979 msg = shared_queue_get(compressed_res_queue);
980 msg->complete = true;
982 DEBUG2("Received msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
984 list_for_each_entry(msg, &cur_lte->msg_list, list) {
985 DEBUG2("complete=%d", msg->complete);
988 // Is this the next chunk in the current resource? If it's not
989 // (i.e., an earlier chunk in a same or different resource
990 // hasn't been compressed yet), do nothing, and keep this
991 // message around until all earlier chunks are received.
993 // Otherwise, write all the chunks we can.
994 while (!list_empty(&cur_lte->msg_list)
995 && (msg = container_of(cur_lte->msg_list.next,
999 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1000 if (msg->begin_chunk == 0) {
1001 DEBUG2("Begin chunk tab");
1003 // This is the first set of chunks. Leave space
1004 // for the chunk table in the output file.
1005 off_t cur_offset = ftello(out_fp);
1006 if (cur_offset == -1) {
1007 ret = WIMLIB_ERR_WRITE;
1010 ret = begin_wim_resource_chunk_tab(cur_lte,
1018 // Write the compressed chunks from the message.
1019 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1023 list_del(&msg->list);
1025 // This message is available to use for different chunks
1027 list_add(&msg->list, &available_msgs);
1029 // Was this the last chunk of the stream? If so,
1031 if (list_empty(&cur_lte->msg_list) &&
1032 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1034 DEBUG2("Finish wim chunk tab");
1036 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1042 progress->write_streams.completed_bytes +=
1043 wim_resource_size(cur_lte);
1044 progress->write_streams.completed_streams++;
1046 if (progress_func) {
1047 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1051 cur_lte->output_resource_entry.size =
1054 cur_lte->output_resource_entry.original_size =
1055 cur_lte->resource_entry.original_size;
1057 cur_lte->output_resource_entry.offset =
1058 cur_chunk_tab->file_offset;
1060 cur_lte->output_resource_entry.flags =
1061 cur_lte->resource_entry.flags |
1062 WIM_RESHDR_FLAG_COMPRESSED;
1064 FREE(cur_chunk_tab);
1065 cur_chunk_tab = NULL;
1067 struct list_head *next = cur_lte->staging_list.next;
1068 list_del(&cur_lte->staging_list);
1070 if (next == &outstanding_resources) {
1071 DEBUG("No more outstanding resources");
1075 cur_lte = container_of(cur_lte->staging_list.next,
1076 struct lookup_table_entry,
1080 // Since we just finished writing a stream,
1081 // write any streams that have been added to the
1082 // my_resources list for direct writing by the
1083 // main thread (e.g. resources that don't need
1084 // to be compressed because the desired
1085 // compression type is the same as the previous
1086 // compression type).
1087 ret = do_write_stream_list(&my_resources,
1101 end_wim_resource_read(cur_lte, ni);
1103 end_wim_resource_read(cur_lte);
1106 ret = do_write_stream_list(&my_resources, out_fp,
1107 out_ctype, progress_func,
1110 size_t num_available_msgs = 0;
1111 struct list_head *cur;
1113 list_for_each(cur, &available_msgs) {
1114 num_available_msgs++;
1117 while (num_available_msgs < ARRAY_LEN(msgs)) {
1118 shared_queue_get(compressed_res_queue);
1119 num_available_msgs++;
1123 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
1124 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1125 FREE(msgs[i].compressed_chunks[j]);
1126 FREE(msgs[i].uncompressed_chunks[j]);
1130 if (cur_chunk_tab != NULL)
1131 FREE(cur_chunk_tab);
1136 static int write_stream_list_parallel(struct list_head *stream_list,
1140 unsigned num_threads,
1141 wimlib_progress_func_t progress_func,
1142 union wimlib_progress_info *progress)
1145 struct shared_queue res_to_compress_queue;
1146 struct shared_queue compressed_res_queue;
1147 pthread_t *compressor_threads = NULL;
1149 if (num_threads == 0) {
1150 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1152 WARNING("Could not determine number of processors! Assuming 1");
1155 num_threads = nthreads;
1159 progress->write_streams.num_threads = num_threads;
1160 wimlib_assert(stream_list->next != stream_list);
1162 static const double MESSAGES_PER_THREAD = 2.0;
1163 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1165 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1167 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1171 ret = shared_queue_init(&compressed_res_queue, queue_size);
1173 goto out_destroy_res_to_compress_queue;
1175 struct compressor_thread_params params;
1176 params.res_to_compress_queue = &res_to_compress_queue;
1177 params.compressed_res_queue = &compressed_res_queue;
1178 params.compress = get_compress_func(out_ctype);
1180 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1182 for (unsigned i = 0; i < num_threads; i++) {
1183 DEBUG("pthread_create thread %u", i);
1184 ret = pthread_create(&compressor_threads[i], NULL,
1185 compressor_thread_proc, ¶ms);
1188 ERROR_WITH_ERRNO("Failed to create compressor "
1196 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1198 ret = main_writer_thread_proc(stream_list,
1201 &res_to_compress_queue,
1202 &compressed_res_queue,
1208 for (unsigned i = 0; i < num_threads; i++)
1209 shared_queue_put(&res_to_compress_queue, NULL);
1211 for (unsigned i = 0; i < num_threads; i++) {
1212 if (pthread_join(compressor_threads[i], NULL)) {
1213 WARNING("Failed to join compressor thread %u: %s",
1214 i, strerror(errno));
1217 FREE(compressor_threads);
1218 shared_queue_destroy(&compressed_res_queue);
1219 out_destroy_res_to_compress_queue:
1220 shared_queue_destroy(&res_to_compress_queue);
1221 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1224 WARNING("Falling back to single-threaded compression");
1225 return write_stream_list_serial(stream_list,
1236 * Write a list of streams to a WIM (@out_fp) using the compression type
1237 * @out_ctype and up to @num_threads compressor threads.
1239 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1240 int out_ctype, int write_flags,
1241 unsigned num_threads,
1242 wimlib_progress_func_t progress_func)
1244 struct lookup_table_entry *lte;
1245 size_t num_streams = 0;
1246 u64 total_bytes = 0;
1247 bool compression_needed = false;
1248 union wimlib_progress_info progress;
1251 list_for_each_entry(lte, stream_list, staging_list) {
1253 total_bytes += wim_resource_size(lte);
1254 if (!compression_needed
1256 (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1257 && (lte->resource_location != RESOURCE_IN_WIM
1258 || wimlib_get_compression_type(lte->wim) != out_ctype
1259 || (write_flags & WIMLIB_WRITE_FLAG_REBUILD)))
1260 && wim_resource_size(lte) != 0)
1261 compression_needed = true;
1263 progress.write_streams.total_bytes = total_bytes;
1264 progress.write_streams.total_streams = num_streams;
1265 progress.write_streams.completed_bytes = 0;
1266 progress.write_streams.completed_streams = 0;
1267 progress.write_streams.num_threads = num_threads;
1268 progress.write_streams.compression_type = out_ctype;
1270 if (num_streams == 0) {
1275 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1276 if (compression_needed && total_bytes >= 1000000 && num_threads != 1) {
1277 ret = write_stream_list_parallel(stream_list,
1288 ret = write_stream_list_serial(stream_list,
1300 static int dentry_find_streams_to_write(struct dentry *dentry,
1304 struct list_head *stream_list = w->private;
1305 struct lookup_table_entry *lte;
1306 for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1307 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1308 if (lte && ++lte->out_refcnt == 1)
1309 list_add_tail(<e->staging_list, stream_list);
1314 static int find_streams_to_write(WIMStruct *w)
1316 return for_dentry_in_tree(wim_root_dentry(w),
1317 dentry_find_streams_to_write, w);
1320 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1321 unsigned num_threads,
1322 wimlib_progress_func_t progress_func)
1325 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1326 LIST_HEAD(stream_list);
1327 w->private = &stream_list;
1328 for_image(w, image, find_streams_to_write);
1329 return write_stream_list(&stream_list, w->out_fp,
1330 wimlib_get_compression_type(w), write_flags,
1331 num_threads, progress_func);
1335 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1336 * table (optional), then overwrite the WIM header.
1338 * write_flags is a bitwise OR of the following:
1340 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1341 * Include an integrity table.
1343 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1344 * Show progress information when (if) writing the integrity table.
1346 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1347 * Don't write the lookup table.
1349 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1350 * When (if) writing the integrity table, re-use entries from the
1351 * existing integrity table, if possible.
1353 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1354 * After writing the XML data but before writing the integrity
1355 * table, write a temporary WIM header and flush the stream so that
1356 * the WIM is less likely to become corrupted upon abrupt program
1359 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1360 * fsync() the output file before closing it.
1363 int finish_write(WIMStruct *w, int image, int write_flags,
1364 wimlib_progress_func_t progress_func)
1367 struct wim_header hdr;
1368 FILE *out = w->out_fp;
1370 /* @hdr will be the header for the new WIM. First copy all the data
1371 * from the header in the WIMStruct; then set all the fields that may
1372 * have changed, including the resource entries, boot index, and image
1374 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1376 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1377 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1382 ret = write_xml_data(w->wim_info, image, out,
1383 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1384 wim_info_get_total_bytes(w->wim_info) : 0,
1385 &hdr.xml_res_entry);
1389 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1390 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1391 struct wim_header checkpoint_hdr;
1392 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1393 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1394 if (fseeko(out, 0, SEEK_SET) != 0) {
1395 ret = WIMLIB_ERR_WRITE;
1398 ret = write_header(&checkpoint_hdr, out);
1402 if (fflush(out) != 0) {
1403 ERROR_WITH_ERRNO("Can't write data to WIM");
1404 ret = WIMLIB_ERR_WRITE;
1408 if (fseeko(out, 0, SEEK_END) != 0) {
1409 ret = WIMLIB_ERR_WRITE;
1414 off_t old_lookup_table_end;
1415 off_t new_lookup_table_end;
1416 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1417 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1418 w->hdr.lookup_table_res_entry.size;
1420 old_lookup_table_end = 0;
1422 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1423 hdr.lookup_table_res_entry.size;
1425 ret = write_integrity_table(out,
1427 new_lookup_table_end,
1428 old_lookup_table_end,
1433 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1437 * In the WIM header, there is room for the resource entry for a
1438 * metadata resource labeled as the "boot metadata". This entry should
1439 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1440 * it should be a copy of the resource entry for the image that is
1441 * marked as bootable. This is not well documented...
1443 if (hdr.boot_idx == 0 || !w->image_metadata
1444 || (image != WIMLIB_ALL_IMAGES && image != hdr.boot_idx)) {
1445 memset(&hdr.boot_metadata_res_entry, 0,
1446 sizeof(struct resource_entry));
1448 memcpy(&hdr.boot_metadata_res_entry,
1450 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1451 sizeof(struct resource_entry));
1454 /* Set image count and boot index correctly for single image writes */
1455 if (image != WIMLIB_ALL_IMAGES) {
1456 hdr.image_count = 1;
1457 if (hdr.boot_idx == image)
1463 if (fseeko(out, 0, SEEK_SET) != 0) {
1464 ret = WIMLIB_ERR_WRITE;
1468 ret = write_header(&hdr, out);
1472 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1473 if (fflush(out) != 0
1474 || fsync(fileno(out)) != 0)
1476 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1477 ret = WIMLIB_ERR_WRITE;
1481 if (fclose(out) != 0) {
1482 ERROR_WITH_ERRNO("Failed to close the WIM file");
1484 ret = WIMLIB_ERR_WRITE;
1490 static void close_wim_writable(WIMStruct *w)
1493 if (fclose(w->out_fp) != 0) {
1494 WARNING("Failed to close output WIM: %s",
1501 /* Open file stream and write dummy header for WIM. */
1502 int begin_write(WIMStruct *w, const char *path, int write_flags)
1505 bool need_readable = false;
1507 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1508 need_readable = true;
1510 ret = open_wim_writable(w, path, trunc, need_readable);
1513 /* Write dummy header. It will be overwritten later. */
1514 return write_header(&w->hdr, w->out_fp);
1517 /* Writes a stand-alone WIM to a file. */
1518 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1519 int image, int write_flags, unsigned num_threads,
1520 wimlib_progress_func_t progress_func)
1525 return WIMLIB_ERR_INVALID_PARAM;
1527 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1529 if (image != WIMLIB_ALL_IMAGES &&
1530 (image < 1 || image > w->hdr.image_count))
1531 return WIMLIB_ERR_INVALID_IMAGE;
1533 if (w->hdr.total_parts != 1) {
1534 ERROR("Cannot call wimlib_write() on part of a split WIM");
1535 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1538 ret = begin_write(w, path, write_flags);
1542 ret = write_wim_streams(w, image, write_flags, num_threads,
1548 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1550 ret = for_image(w, image, write_metadata_resource);
1555 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1557 ret = finish_write(w, image, write_flags, progress_func);
1559 close_wim_writable(w);
1563 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1566 memcpy(<e->output_resource_entry, <e->resource_entry,
1567 sizeof(struct resource_entry));
1568 lte->out_refcnt = 0;
1572 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1574 off_t end_offset = *(u64*)arg;
1576 wimlib_assert(lte->out_refcnt <= lte->refcnt);
1577 if (lte->out_refcnt < lte->refcnt) {
1578 if (lte->resource_entry.offset + lte->resource_entry.size > end_offset) {
1579 ERROR("The following resource is after the XML data:");
1580 print_lookup_table_entry(lte);
1581 return WIMLIB_ERR_RESOURCE_ORDER;
1587 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1589 if (lte->out_refcnt == lte->refcnt)
1590 list_add(<e->staging_list, (struct list_head*)arg);
1592 lte->out_refcnt = lte->refcnt;
1597 * Overwrite a WIM, possibly appending streams to it.
1599 * A WIM looks like (or is supposed to look like) the following:
1601 * Header (212 bytes)
1602 * Streams and metadata resources (variable size)
1603 * Lookup table (variable size)
1604 * XML data (variable size)
1605 * Integrity table (optional) (variable size)
1607 * If we are not adding any streams or metadata resources, the lookup table is
1608 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1609 * header. This operation is potentially unsafe if the program is abruptly
1610 * terminated while the XML data or integrity table are being overwritten, but
1611 * before the new header has been written. To partially alleviate this problem,
1612 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1613 * finish_write() to cause a temporary WIM header to be written after the XML
1614 * data has been written. This may prevent the WIM from becoming corrupted if
1615 * the program is terminated while the integrity table is being calculated (but
1616 * no guarantees, due to write re-ordering...).
1618 * If we are adding new streams or images (metadata resources), the lookup table
1619 * needs to be changed, and those streams need to be written. In this case, we
1620 * try to perform a safe update of the WIM file by writing the streams *after*
1621 * the end of the previous WIM, then writing the new lookup table, XML data, and
1622 * (optionally) integrity table following the new streams. This will produce a
1623 * layout like the following:
1625 * Header (212 bytes)
1626 * (OLD) Streams and metadata resources (variable size)
1627 * (OLD) Lookup table (variable size)
1628 * (OLD) XML data (variable size)
1629 * (OLD) Integrity table (optional) (variable size)
1630 * (NEW) Streams and metadata resources (variable size)
1631 * (NEW) Lookup table (variable size)
1632 * (NEW) XML data (variable size)
1633 * (NEW) Integrity table (optional) (variable size)
1635 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1636 * the header is overwritten to point to the new lookup table, XML data, and
1637 * integrity table, to produce the following layout:
1639 * Header (212 bytes)
1640 * Streams and metadata resources (variable size)
1641 * Nothing (variable size)
1642 * More Streams and metadata resources (variable size)
1643 * Lookup table (variable size)
1644 * XML data (variable size)
1645 * Integrity table (optional) (variable size)
1647 * This method allows an image to be appended to a large WIM very quickly, and
1648 * is is crash-safe except in the case of write re-ordering, but the
1649 * disadvantage is that a small hole is left in the WIM where the old lookup
1650 * table, xml data, and integrity table were. (These usually only take up a
1651 * small amount of space compared to the streams, however.
1653 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1654 unsigned num_threads,
1655 wimlib_progress_func_t progress_func,
1656 int modified_image_idx)
1659 struct list_head stream_list;
1662 DEBUG("Overwriting `%s' in-place", w->filename);
1664 /* Make sure that the integrity table (if present) is after the XML
1665 * data, and that there are no stream resources, metadata resources, or
1666 * lookup tables after the XML data. Otherwise, these data would be
1668 if (w->hdr.integrity.offset != 0 &&
1669 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1670 ERROR("Didn't expect the integrity table to be before the XML data");
1671 return WIMLIB_ERR_RESOURCE_ORDER;
1674 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1675 ERROR("Didn't expect the lookup table to be after the XML data");
1676 return WIMLIB_ERR_RESOURCE_ORDER;
1679 DEBUG("Identifying newly added streams");
1680 for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1681 INIT_LIST_HEAD(&stream_list);
1682 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1683 DEBUG("Identifiying streams in image %d", i + 1);
1684 wimlib_assert(w->image_metadata[i].modified);
1685 wimlib_assert(!w->image_metadata[i].has_been_mounted_rw);
1686 wimlib_assert(w->image_metadata[i].root_dentry != NULL);
1687 wimlib_assert(w->image_metadata[i].metadata_lte != NULL);
1688 w->private = &stream_list;
1689 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1690 dentry_find_streams_to_write, w);
1693 if (w->hdr.integrity.offset)
1694 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1696 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1698 ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1703 if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1704 /* If no images have been modified and no images have been
1705 * deleted, a new lookup table does not need to be written. */
1706 wimlib_assert(list_empty(&stream_list));
1707 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1708 w->hdr.lookup_table_res_entry.size;
1709 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1710 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1713 INIT_LIST_HEAD(&stream_list);
1714 for_lookup_table_entry(w->lookup_table, find_new_streams,
1717 ret = open_wim_writable(w, w->filename, false,
1718 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1722 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1723 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1724 return WIMLIB_ERR_WRITE;
1727 if (!list_empty(&stream_list)) {
1728 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1730 ret = write_stream_list(&stream_list, w->out_fp,
1731 wimlib_get_compression_type(w),
1732 write_flags, num_threads,
1737 DEBUG("No new streams were added");
1740 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1741 select_wim_image(w, i + 1);
1742 ret = write_metadata_resource(w);
1746 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1747 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1750 close_wim_writable(w);
1752 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1753 w->filename, old_wim_end);
1754 truncate(w->filename, old_wim_end);
1759 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1760 unsigned num_threads,
1761 wimlib_progress_func_t progress_func)
1763 size_t wim_name_len;
1766 DEBUG("Overwriting `%s' via a temporary file", w->filename);
1768 /* Write the WIM to a temporary file in the same directory as the
1770 wim_name_len = strlen(w->filename);
1771 char tmpfile[wim_name_len + 10];
1772 memcpy(tmpfile, w->filename, wim_name_len);
1773 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1774 tmpfile[wim_name_len + 9] = '\0';
1776 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1777 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1778 num_threads, progress_func);
1780 ERROR("Failed to write the WIM file `%s'", tmpfile);
1784 /* Close the original WIM file that was opened for reading. */
1785 if (w->fp != NULL) {
1790 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1792 /* Rename the new file to the old file .*/
1793 if (rename(tmpfile, w->filename) != 0) {
1794 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1795 tmpfile, w->filename);
1796 ret = WIMLIB_ERR_RENAME;
1800 if (progress_func) {
1801 union wimlib_progress_info progress;
1802 progress.rename.from = tmpfile;
1803 progress.rename.to = w->filename;
1804 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1807 /* Re-open the WIM read-only. */
1808 w->fp = fopen(w->filename, "rb");
1809 if (w->fp == NULL) {
1810 ret = WIMLIB_ERR_REOPEN;
1811 WARNING("Failed to re-open `%s' read-only: %s",
1812 w->filename, strerror(errno));
1816 /* Remove temporary file. */
1817 if (unlink(tmpfile) != 0)
1818 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1823 * Writes a WIM file to the original file that it was read from, overwriting it.
1825 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1826 unsigned num_threads,
1827 wimlib_progress_func_t progress_func)
1830 return WIMLIB_ERR_INVALID_PARAM;
1832 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1835 return WIMLIB_ERR_NO_FILENAME;
1837 if (w->hdr.total_parts != 1) {
1838 ERROR("Cannot modify a split WIM");
1839 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1842 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1843 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1845 int i, modified_image_idx;
1846 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1848 modified_image_idx = i;
1849 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1850 !w->image_metadata[i].has_been_mounted_rw; i++)
1852 if (i == w->hdr.image_count) {
1853 return overwrite_wim_inplace(w, write_flags, num_threads,
1855 modified_image_idx);
1858 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,