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
54 #include <ntfs-3g/attrib.h>
55 #include <ntfs-3g/inode.h>
56 #include <ntfs-3g/dir.h>
65 static int fflush_and_ftruncate(FILE *fp, off_t size)
71 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
72 return WIMLIB_ERR_WRITE;
74 ret = ftruncate(fileno(fp), size);
76 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
77 "%"PRIu64" bytes", size);
78 return WIMLIB_ERR_WRITE;
83 /* Chunk table that's located at the beginning of each compressed resource in
84 * the WIM. (This is not the on-disk format; the on-disk format just has an
85 * array of offsets.) */
89 u64 original_resource_size;
90 u64 bytes_per_chunk_entry;
98 * Allocates and initializes a chunk table, and reserves space for it in the
102 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
105 struct chunk_table **chunk_tab_ret)
107 u64 size = wim_resource_size(lte);
108 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
109 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
110 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
114 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
116 ret = WIMLIB_ERR_NOMEM;
119 chunk_tab->file_offset = file_offset;
120 chunk_tab->num_chunks = num_chunks;
121 chunk_tab->original_resource_size = size;
122 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
123 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
125 chunk_tab->cur_offset = 0;
126 chunk_tab->cur_offset_p = chunk_tab->offsets;
128 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
129 chunk_tab->table_disk_size) {
130 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
132 ret = WIMLIB_ERR_WRITE;
138 *chunk_tab_ret = chunk_tab;
143 * Pointer to function to compresses a chunk of a WIM resource.
145 * @chunk: Uncompressed data of the chunk.
146 * @chunk_size: Size of the uncompressed chunk in bytes.
147 * @compressed_chunk: Pointer to output buffer of size at least
148 * (@chunk_size - 1) bytes.
149 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
150 * of the compressed chunk will be
153 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
154 * compressed to any smaller than @chunk_size. This function cannot fail for
157 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
159 compress_func_t get_compress_func(int out_ctype)
161 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
164 return xpress_compress;
168 * Writes a chunk of a WIM resource to an output file.
170 * @chunk: Uncompressed data of the chunk.
171 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
172 * @out_fp: FILE * to write tho chunk to.
173 * @out_ctype: Compression type to use when writing the chunk (ignored if no
174 * chunk table provided)
175 * @chunk_tab: Pointer to chunk table being created. It is updated with the
176 * offset of the chunk we write.
178 * Returns 0 on success; nonzero on failure.
180 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
181 FILE *out_fp, compress_func_t compress,
182 struct chunk_table *chunk_tab)
185 unsigned out_chunk_size;
187 u8 *compressed_chunk = alloca(chunk_size);
190 ret = compress(chunk, chunk_size, compressed_chunk,
193 out_chunk = compressed_chunk;
196 out_chunk_size = chunk_size;
198 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
199 chunk_tab->cur_offset += out_chunk_size;
202 out_chunk_size = chunk_size;
204 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
205 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
206 return WIMLIB_ERR_WRITE;
212 * Finishes a WIM chunk table and writes it to the output file at the correct
215 * The final size of the full compressed resource is returned in the
216 * @compressed_size_p.
219 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
220 FILE *out_fp, u64 *compressed_size_p)
222 size_t bytes_written;
223 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
224 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
225 "WIM file", chunk_tab->file_offset);
226 return WIMLIB_ERR_WRITE;
229 if (chunk_tab->bytes_per_chunk_entry == 8) {
230 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
232 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
233 ((u32*)chunk_tab->offsets)[i] =
234 cpu_to_le32(chunk_tab->offsets[i]);
236 bytes_written = fwrite((u8*)chunk_tab->offsets +
237 chunk_tab->bytes_per_chunk_entry,
238 1, chunk_tab->table_disk_size, out_fp);
239 if (bytes_written != chunk_tab->table_disk_size) {
240 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
242 return WIMLIB_ERR_WRITE;
244 if (fseeko(out_fp, 0, SEEK_END) != 0) {
245 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
246 return WIMLIB_ERR_WRITE;
248 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
252 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
253 * attribute pointer in the lookup table entry. */
254 static int prepare_resource_for_read(struct lookup_table_entry *lte
257 , ntfs_inode **ni_ret
261 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
262 && !lte->file_on_disk_fp)
264 wimlib_assert(lte->file_on_disk);
265 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
266 if (!lte->file_on_disk_fp) {
267 ERROR_WITH_ERRNO("Failed to open the file `%s' for "
268 "reading", lte->file_on_disk);
269 return WIMLIB_ERR_OPEN;
273 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
276 struct ntfs_location *loc = lte->ntfs_loc;
279 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
281 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
282 "volume", loc->path_utf8);
283 return WIMLIB_ERR_NTFS_3G;
285 lte->attr = ntfs_attr_open(ni,
286 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
287 (ntfschar*)loc->stream_name_utf16,
288 loc->stream_name_utf16_num_chars);
290 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
291 "NTFS volume", loc->path_utf8);
292 ntfs_inode_close(ni);
293 return WIMLIB_ERR_NTFS_3G;
301 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
303 static void end_wim_resource_read(struct lookup_table_entry *lte
309 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
310 && lte->file_on_disk_fp) {
311 fclose(lte->file_on_disk_fp);
312 lte->file_on_disk_fp = NULL;
315 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
317 ntfs_attr_close(lte->attr);
321 ntfs_inode_close(ni);
327 write_uncompressed_resource_and_truncate(struct lookup_table_entry *lte,
330 struct resource_entry *out_res_entry)
333 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
334 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
335 "output WIM file", file_offset);
336 return WIMLIB_ERR_WRITE;
338 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
343 return fflush_and_ftruncate(out_fp,
344 file_offset + wim_resource_size(lte));
348 * Writes a WIM resource to a FILE * opened for writing. The resource may be
349 * written uncompressed or compressed depending on the @out_ctype parameter.
351 * If by chance the resource compresses to more than the original size (this may
352 * happen with random data or files than are pre-compressed), the resource is
353 * instead written uncompressed (and this is reflected in the @out_res_entry by
354 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
356 * @lte: The lookup table entry for the WIM resource.
357 * @out_fp: The FILE * to write the resource to.
358 * @out_ctype: The compression type of the resource to write. Note: if this is
359 * the same as the compression type of the WIM resource we
360 * need to read, we simply copy the data (i.e. we do not
361 * uncompress it, then compress it again).
362 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
363 * offset, original size, compressed size, and compression flag
364 * of the output resource.
366 * Returns 0 on success; nonzero on failure.
368 int write_wim_resource(struct lookup_table_entry *lte,
369 FILE *out_fp, int out_ctype,
370 struct resource_entry *out_res_entry,
375 u64 old_compressed_size;
376 u64 new_compressed_size;
379 struct chunk_table *chunk_tab = NULL;
382 compress_func_t compress = NULL;
384 ntfs_inode *ni = NULL;
389 /* Original size of the resource */
390 original_size = wim_resource_size(lte);
392 /* Compressed size of the resource (as it exists now) */
393 old_compressed_size = wim_resource_compressed_size(lte);
395 /* Current offset in output file */
396 file_offset = ftello(out_fp);
397 if (file_offset == -1) {
398 ERROR_WITH_ERRNO("Failed to get offset in output "
400 return WIMLIB_ERR_WRITE;
403 /* Are the compression types the same? If so, do a raw copy (copy
404 * without decompressing and recompressing the data). */
405 raw = (wim_resource_compression_type(lte) == out_ctype
406 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
407 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
410 flags |= WIMLIB_RESOURCE_FLAG_RAW;
411 bytes_remaining = old_compressed_size;
413 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
414 bytes_remaining = original_size;
417 /* Empty resource; nothing needs to be done, so just return success. */
418 if (bytes_remaining == 0)
421 /* Buffer for reading chunks for the resource */
422 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
424 /* If we are writing a compressed resource and not doing a raw copy, we
425 * need to initialize the chunk table */
426 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
427 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
433 /* If the WIM resource is in an external file, open a FILE * to it so we
434 * don't have to open a temporary one in read_wim_resource() for each
437 ret = prepare_resource_for_read(lte, &ni);
439 ret = prepare_resource_for_read(lte);
444 /* If we aren't doing a raw copy, we will compute the SHA1 message
445 * digest of the resource as we read it, and verify it's the same as the
446 * hash given in the lookup table entry once we've finished reading the
451 compress = get_compress_func(out_ctype);
455 /* While there are still bytes remaining in the WIM resource, read a
456 * chunk of the resource, update SHA1, then write that chunk using the
457 * desired compression type. */
459 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
460 ret = read_wim_resource(lte, buf, to_read, offset, flags);
464 sha1_update(&ctx, buf, to_read);
465 ret = write_wim_resource_chunk(buf, to_read, out_fp,
466 compress, chunk_tab);
469 bytes_remaining -= to_read;
471 } while (bytes_remaining);
473 /* Raw copy: The new compressed size is the same as the old compressed
476 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
479 * Using a different compression type: Call
480 * finish_wim_resource_chunk_tab() and it will provide the new
484 new_compressed_size = old_compressed_size;
486 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
487 new_compressed_size = original_size;
489 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
490 &new_compressed_size);
496 /* Verify SHA1 message digest of the resource, unless we are doing a raw
497 * write (in which case we never even saw the uncompressed data). Or,
498 * if the hash we had before is all 0's, just re-set it to be the new
501 u8 md[SHA1_HASH_SIZE];
502 sha1_final(md, &ctx);
503 if (is_zero_hash(lte->hash)) {
504 copy_hash(lte->hash, md);
505 } else if (!hashes_equal(md, lte->hash)) {
506 ERROR("WIM resource has incorrect hash!");
507 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
508 ERROR("We were reading it from `%s'; maybe it changed "
509 "while we were reading it.",
512 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
517 if (!raw && new_compressed_size >= original_size &&
518 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
520 /* Oops! We compressed the resource to larger than the original
521 * size. Write the resource uncompressed instead. */
522 ret = write_uncompressed_resource_and_truncate(lte,
530 out_res_entry->size = new_compressed_size;
531 out_res_entry->original_size = original_size;
532 out_res_entry->offset = file_offset;
533 out_res_entry->flags = lte->resource_entry.flags
534 & ~WIM_RESHDR_FLAG_COMPRESSED;
535 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
536 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
542 end_wim_resource_read(lte, ni);
544 end_wim_resource_read(lte);
551 #ifdef ENABLE_MULTITHREADED_COMPRESSION
552 struct shared_queue {
556 unsigned filled_slots;
558 pthread_mutex_t lock;
559 pthread_cond_t msg_avail_cond;
560 pthread_cond_t space_avail_cond;
563 static int shared_queue_init(struct shared_queue *q, unsigned size)
565 q->array = CALLOC(sizeof(q->array[0]), size);
567 return WIMLIB_ERR_NOMEM;
572 pthread_mutex_init(&q->lock, NULL);
573 pthread_cond_init(&q->msg_avail_cond, NULL);
574 pthread_cond_init(&q->space_avail_cond, NULL);
578 static void shared_queue_destroy(struct shared_queue *q)
581 pthread_mutex_destroy(&q->lock);
582 pthread_cond_destroy(&q->msg_avail_cond);
583 pthread_cond_destroy(&q->space_avail_cond);
586 static void shared_queue_put(struct shared_queue *q, void *obj)
588 pthread_mutex_lock(&q->lock);
589 while (q->filled_slots == q->size)
590 pthread_cond_wait(&q->space_avail_cond, &q->lock);
592 q->back = (q->back + 1) % q->size;
593 q->array[q->back] = obj;
596 pthread_cond_broadcast(&q->msg_avail_cond);
597 pthread_mutex_unlock(&q->lock);
600 static void *shared_queue_get(struct shared_queue *q)
604 pthread_mutex_lock(&q->lock);
605 while (q->filled_slots == 0)
606 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
608 obj = q->array[q->front];
609 q->array[q->front] = NULL;
610 q->front = (q->front + 1) % q->size;
613 pthread_cond_broadcast(&q->space_avail_cond);
614 pthread_mutex_unlock(&q->lock);
618 struct compressor_thread_params {
619 struct shared_queue *res_to_compress_queue;
620 struct shared_queue *compressed_res_queue;
621 compress_func_t compress;
624 #define MAX_CHUNKS_PER_MSG 2
627 struct lookup_table_entry *lte;
628 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
629 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
630 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
631 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
632 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
634 struct list_head list;
639 static void compress_chunks(struct message *msg, compress_func_t compress)
641 for (unsigned i = 0; i < msg->num_chunks; i++) {
642 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
643 int ret = compress(msg->uncompressed_chunks[i],
644 msg->uncompressed_chunk_sizes[i],
645 msg->compressed_chunks[i],
646 &msg->compressed_chunk_sizes[i]);
648 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
650 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
651 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
656 static void *compressor_thread_proc(void *arg)
658 struct compressor_thread_params *params = arg;
659 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
660 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
661 compress_func_t compress = params->compress;
664 DEBUG("Compressor thread ready");
665 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
666 compress_chunks(msg, compress);
667 shared_queue_put(compressed_res_queue, msg);
669 DEBUG("Compressor thread terminating");
674 static int do_write_stream_list(struct list_head *my_resources,
677 wimlib_progress_func_t progress_func,
678 union wimlib_progress_info *progress,
679 int write_resource_flags)
682 struct lookup_table_entry *lte, *tmp;
684 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
685 ret = write_wim_resource(lte,
688 <e->output_resource_entry,
689 write_resource_flags);
692 list_del(<e->staging_list);
693 progress->write_streams.completed_bytes +=
694 wim_resource_size(lte);
695 progress->write_streams.completed_streams++;
697 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
704 static int write_stream_list_serial(struct list_head *stream_list,
708 wimlib_progress_func_t progress_func,
709 union wimlib_progress_info *progress)
711 int write_resource_flags;
713 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
714 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
716 write_resource_flags = 0;
717 progress->write_streams.num_threads = 1;
719 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
720 return do_write_stream_list(stream_list, out_fp,
721 out_ctype, progress_func,
722 progress, write_resource_flags);
725 #ifdef ENABLE_MULTITHREADED_COMPRESSION
726 static int write_wim_chunks(struct message *msg, FILE *out_fp,
727 struct chunk_table *chunk_tab)
729 for (unsigned i = 0; i < msg->num_chunks; i++) {
730 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
732 DEBUG2("Write wim chunk %u of %u (csize = %u)",
733 i, msg->num_chunks, chunk_csize);
735 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
738 ERROR_WITH_ERRNO("Failed to write WIM chunk");
739 return WIMLIB_ERR_WRITE;
742 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
743 chunk_tab->cur_offset += chunk_csize;
749 * This function is executed by the main thread when the resources are being
750 * compressed in parallel. The main thread is in change of all reading of the
751 * uncompressed data and writing of the compressed data. The compressor threads
752 * *only* do compression from/to in-memory buffers.
754 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
755 * chunks of compressed data to compress, represented in a `struct message'.
756 * Each message is passed from the main thread to a worker thread through the
757 * res_to_compress_queue, and it is passed back through the
758 * compressed_res_queue.
760 static int main_writer_thread_proc(struct list_head *stream_list,
763 struct shared_queue *res_to_compress_queue,
764 struct shared_queue *compressed_res_queue,
767 wimlib_progress_func_t progress_func,
768 union wimlib_progress_info *progress)
772 struct message msgs[queue_size];
775 // Initially, all the messages are available to use.
776 LIST_HEAD(available_msgs);
777 for (size_t i = 0; i < ARRAY_LEN(msgs); i++)
778 list_add(&msgs[i].list, &available_msgs);
780 // outstanding_resources is the list of resources that currently have
781 // had chunks sent off for compression.
783 // The first stream in outstanding_resources is the stream that is
784 // currently being written (cur_lte).
786 // The last stream in outstanding_resources is the stream that is
787 // currently being read and chunks fed to the compressor threads
790 // Depending on the number of threads and the sizes of the resource,
791 // the outstanding streams list may contain streams between cur_lte and
792 // next_lte that have all their chunks compressed or being compressed,
793 // but haven't been written yet.
795 LIST_HEAD(outstanding_resources);
796 struct list_head *next_resource = stream_list->next;
797 struct lookup_table_entry *next_lte = NULL;
799 u64 next_num_chunks = 0;
801 // As in write_wim_resource(), each resource we read is checksummed.
802 SHA_CTX next_sha_ctx;
803 u8 next_hash[SHA1_HASH_SIZE];
805 // Resources that don't need any chunks compressed are added to this
806 // list and written directly by the main thread.
807 LIST_HEAD(my_resources);
809 struct lookup_table_entry *cur_lte = NULL;
810 struct chunk_table *cur_chunk_tab = NULL;
814 ntfs_inode *ni = NULL;
817 DEBUG("Initializing buffers for uncompressed "
818 "and compressed data (%zu bytes needed)",
819 queue_size * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
821 // Pre-allocate all the buffers that will be needed to do the chunk
823 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
824 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
825 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
827 // The extra 8 bytes is because longest_match() in lz.c
828 // may read a little bit off the end of the uncompressed
829 // data. It doesn't need to be initialized--- we really
830 // just need to avoid accessing an unmapped page.
831 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
832 if (msgs[i].compressed_chunks[j] == NULL ||
833 msgs[i].uncompressed_chunks[j] == NULL)
835 ERROR("Could not allocate enough memory for "
836 "multi-threaded compression");
837 ret = WIMLIB_ERR_NOMEM;
843 // This loop is executed until all resources have been written, except
844 // possibly a few that have been added to the @my_resources list for
847 // Send chunks to the compressor threads until either (a) there
848 // are no more messages available since they were all sent off,
849 // or (b) there are no more resources that need to be
851 while (!list_empty(&available_msgs)) {
852 if (next_chunk == next_num_chunks) {
853 // If next_chunk == next_num_chunks, there are
854 // no more chunks to write in the current
855 // stream. So, check the SHA1 message digest of
856 // the stream that was just finished (unless
857 // next_lte == NULL, which is the case the very
858 // first time this loop is entered, and also
859 // near the very end of the compression when
860 // there are no more streams.) Then, advance to
861 // the next stream (if there is one).
862 if (next_lte != NULL) {
864 end_wim_resource_read(next_lte, ni);
867 end_wim_resource_read(next_lte);
869 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
871 sha1_final(next_hash, &next_sha_ctx);
872 if (!hashes_equal(next_lte->hash, next_hash)) {
873 ERROR("WIM resource has incorrect hash!");
874 if (next_lte->resource_location ==
875 RESOURCE_IN_FILE_ON_DISK)
877 ERROR("We were reading it from `%s'; "
878 "maybe it changed while we were "
880 next_lte->file_on_disk);
882 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
887 // Advance to the next resource.
889 // If the next resource needs no compression, just write
890 // it with this thread (not now though--- we could be in
891 // the middle of writing another resource.) Keep doing
892 // this until we either get to the end of the resources
893 // list, or we get to a resource that needs compression.
895 if (next_resource == stream_list) {
899 next_lte = container_of(next_resource,
900 struct lookup_table_entry,
902 next_resource = next_resource->next;
903 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
904 && wim_resource_compression_type(next_lte) == out_ctype)
905 || wim_resource_size(next_lte) == 0)
907 list_add_tail(&next_lte->staging_list,
910 list_add_tail(&next_lte->staging_list,
911 &outstanding_resources);
913 next_num_chunks = wim_resource_chunks(next_lte);
914 sha1_init(&next_sha_ctx);
915 INIT_LIST_HEAD(&next_lte->msg_list);
917 ret = prepare_resource_for_read(next_lte, &ni);
919 ret = prepare_resource_for_read(next_lte);
931 if (next_lte == NULL)
934 // Get a message from the available messages
936 msg = container_of(available_msgs.next,
940 // ... and delete it from the available messages
942 list_del(&msg->list);
944 // Initialize the message with the chunks to
946 msg->num_chunks = min(next_num_chunks - next_chunk,
949 msg->complete = false;
950 msg->begin_chunk = next_chunk;
952 unsigned size = WIM_CHUNK_SIZE;
953 for (unsigned i = 0; i < msg->num_chunks; i++) {
955 // Read chunk @next_chunk of the stream into the
956 // message so that a compressor thread can
959 if (next_chunk == next_num_chunks - 1 &&
960 wim_resource_size(next_lte) % WIM_CHUNK_SIZE != 0)
962 size = wim_resource_size(next_lte) % WIM_CHUNK_SIZE;
966 DEBUG2("Read resource (size=%u, offset=%zu)",
967 size, next_chunk * WIM_CHUNK_SIZE);
969 msg->uncompressed_chunk_sizes[i] = size;
971 ret = read_wim_resource(next_lte,
972 msg->uncompressed_chunks[i],
974 next_chunk * WIM_CHUNK_SIZE,
978 sha1_update(&next_sha_ctx,
979 msg->uncompressed_chunks[i], size);
983 // Send the compression request
984 list_add_tail(&msg->list, &next_lte->msg_list);
985 shared_queue_put(res_to_compress_queue, msg);
986 DEBUG2("Compression request sent");
989 // If there are no outstanding resources, there are no more
990 // resources that need to be written.
991 if (list_empty(&outstanding_resources)) {
996 // Get the next message from the queue and process it.
997 // The message will contain 1 or more data chunks that have been
999 msg = shared_queue_get(compressed_res_queue);
1000 msg->complete = true;
1002 // Is this the next chunk in the current resource? If it's not
1003 // (i.e., an earlier chunk in a same or different resource
1004 // hasn't been compressed yet), do nothing, and keep this
1005 // message around until all earlier chunks are received.
1007 // Otherwise, write all the chunks we can.
1008 while (cur_lte != NULL && !list_empty(&cur_lte->msg_list)
1009 && (msg = container_of(cur_lte->msg_list.next,
1013 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1014 if (msg->begin_chunk == 0) {
1015 DEBUG2("Begin chunk tab");
1017 // This is the first set of chunks. Leave space
1018 // for the chunk table in the output file.
1019 off_t cur_offset = ftello(out_fp);
1020 if (cur_offset == -1) {
1021 ret = WIMLIB_ERR_WRITE;
1024 ret = begin_wim_resource_chunk_tab(cur_lte,
1032 // Write the compressed chunks from the message.
1033 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1037 list_del(&msg->list);
1039 // This message is available to use for different chunks
1041 list_add(&msg->list, &available_msgs);
1043 // Was this the last chunk of the stream? If so,
1045 if (list_empty(&cur_lte->msg_list) &&
1046 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1048 DEBUG2("Finish wim chunk tab");
1050 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1056 if (res_csize >= wim_resource_size(cur_lte)) {
1057 /* Oops! We compressed the resource to
1058 * larger than the original size. Write
1059 * the resource uncompressed instead. */
1060 ret = write_uncompressed_resource_and_truncate(
1063 cur_chunk_tab->file_offset,
1064 &cur_lte->output_resource_entry);
1068 cur_lte->output_resource_entry.size =
1071 cur_lte->output_resource_entry.original_size =
1072 cur_lte->resource_entry.original_size;
1074 cur_lte->output_resource_entry.offset =
1075 cur_chunk_tab->file_offset;
1077 cur_lte->output_resource_entry.flags =
1078 cur_lte->resource_entry.flags |
1079 WIM_RESHDR_FLAG_COMPRESSED;
1082 progress->write_streams.completed_bytes +=
1083 wim_resource_size(cur_lte);
1084 progress->write_streams.completed_streams++;
1086 if (progress_func) {
1087 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1091 FREE(cur_chunk_tab);
1092 cur_chunk_tab = NULL;
1094 struct list_head *next = cur_lte->staging_list.next;
1095 list_del(&cur_lte->staging_list);
1097 if (next == &outstanding_resources) {
1098 if (next_lte == NULL) {
1099 DEBUG("No more outstanding resources");
1103 DEBUG("No more outstanding resources---"
1104 "but still more to compress!");
1108 cur_lte = container_of(cur_lte->staging_list.next,
1109 struct lookup_table_entry,
1113 // Since we just finished writing a stream,
1114 // write any streams that have been added to the
1115 // my_resources list for direct writing by the
1116 // main thread (e.g. resources that don't need
1117 // to be compressed because the desired
1118 // compression type is the same as the previous
1119 // compression type).
1120 ret = do_write_stream_list(&my_resources,
1135 end_wim_resource_read(next_lte, ni);
1137 end_wim_resource_read(next_lte);
1142 ret = do_write_stream_list(&my_resources, out_fp,
1143 out_ctype, progress_func,
1146 size_t num_available_msgs = 0;
1147 struct list_head *cur;
1149 list_for_each(cur, &available_msgs) {
1150 num_available_msgs++;
1153 while (num_available_msgs < ARRAY_LEN(msgs)) {
1154 shared_queue_get(compressed_res_queue);
1155 num_available_msgs++;
1159 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
1160 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1161 FREE(msgs[i].compressed_chunks[j]);
1162 FREE(msgs[i].uncompressed_chunks[j]);
1166 if (cur_chunk_tab != NULL)
1167 FREE(cur_chunk_tab);
1172 static int write_stream_list_parallel(struct list_head *stream_list,
1176 unsigned num_threads,
1177 wimlib_progress_func_t progress_func,
1178 union wimlib_progress_info *progress)
1181 struct shared_queue res_to_compress_queue;
1182 struct shared_queue compressed_res_queue;
1183 pthread_t *compressor_threads = NULL;
1185 if (num_threads == 0) {
1186 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1188 WARNING("Could not determine number of processors! Assuming 1");
1191 num_threads = nthreads;
1195 progress->write_streams.num_threads = num_threads;
1196 wimlib_assert(stream_list->next != stream_list);
1198 static const double MESSAGES_PER_THREAD = 2.0;
1199 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1201 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1203 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1207 ret = shared_queue_init(&compressed_res_queue, queue_size);
1209 goto out_destroy_res_to_compress_queue;
1211 struct compressor_thread_params params;
1212 params.res_to_compress_queue = &res_to_compress_queue;
1213 params.compressed_res_queue = &compressed_res_queue;
1214 params.compress = get_compress_func(out_ctype);
1216 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1218 for (unsigned i = 0; i < num_threads; i++) {
1219 DEBUG("pthread_create thread %u", i);
1220 ret = pthread_create(&compressor_threads[i], NULL,
1221 compressor_thread_proc, ¶ms);
1224 ERROR_WITH_ERRNO("Failed to create compressor "
1232 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1234 ret = main_writer_thread_proc(stream_list,
1237 &res_to_compress_queue,
1238 &compressed_res_queue,
1244 for (unsigned i = 0; i < num_threads; i++)
1245 shared_queue_put(&res_to_compress_queue, NULL);
1247 for (unsigned i = 0; i < num_threads; i++) {
1248 if (pthread_join(compressor_threads[i], NULL)) {
1249 WARNING("Failed to join compressor thread %u: %s",
1250 i, strerror(errno));
1253 FREE(compressor_threads);
1254 shared_queue_destroy(&compressed_res_queue);
1255 out_destroy_res_to_compress_queue:
1256 shared_queue_destroy(&res_to_compress_queue);
1257 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1260 WARNING("Falling back to single-threaded compression");
1261 return write_stream_list_serial(stream_list,
1272 * Write a list of streams to a WIM (@out_fp) using the compression type
1273 * @out_ctype and up to @num_threads compressor threads.
1275 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1276 int out_ctype, int write_flags,
1277 unsigned num_threads,
1278 wimlib_progress_func_t progress_func)
1280 struct lookup_table_entry *lte;
1281 size_t num_streams = 0;
1282 u64 total_bytes = 0;
1283 u64 total_compression_bytes = 0;
1284 union wimlib_progress_info progress;
1287 list_for_each_entry(lte, stream_list, staging_list) {
1289 total_bytes += wim_resource_size(lte);
1290 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1291 && (wim_resource_compression_type(lte) != out_ctype ||
1292 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1294 total_compression_bytes += wim_resource_size(lte);
1297 progress.write_streams.total_bytes = total_bytes;
1298 progress.write_streams.total_streams = num_streams;
1299 progress.write_streams.completed_bytes = 0;
1300 progress.write_streams.completed_streams = 0;
1301 progress.write_streams.num_threads = num_threads;
1302 progress.write_streams.compression_type = out_ctype;
1304 if (num_streams == 0) {
1309 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1310 if (total_compression_bytes >= 1000000 && num_threads != 1) {
1311 ret = write_stream_list_parallel(stream_list,
1322 ret = write_stream_list_serial(stream_list,
1334 static int dentry_find_streams_to_write(struct dentry *dentry,
1338 struct list_head *stream_list = w->private;
1339 struct lookup_table_entry *lte;
1340 for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1341 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1342 if (lte && ++lte->out_refcnt == 1)
1343 list_add_tail(<e->staging_list, stream_list);
1348 static int find_streams_to_write(WIMStruct *w)
1350 return for_dentry_in_tree(wim_root_dentry(w),
1351 dentry_find_streams_to_write, w);
1354 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1355 unsigned num_threads,
1356 wimlib_progress_func_t progress_func)
1359 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1360 LIST_HEAD(stream_list);
1361 w->private = &stream_list;
1362 for_image(w, image, find_streams_to_write);
1363 return write_stream_list(&stream_list, w->out_fp,
1364 wimlib_get_compression_type(w), write_flags,
1365 num_threads, progress_func);
1369 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1370 * table (optional), then overwrite the WIM header.
1372 * write_flags is a bitwise OR of the following:
1374 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1375 * Include an integrity table.
1377 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1378 * Show progress information when (if) writing the integrity table.
1380 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1381 * Don't write the lookup table.
1383 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1384 * When (if) writing the integrity table, re-use entries from the
1385 * existing integrity table, if possible.
1387 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1388 * After writing the XML data but before writing the integrity
1389 * table, write a temporary WIM header and flush the stream so that
1390 * the WIM is less likely to become corrupted upon abrupt program
1393 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1394 * fsync() the output file before closing it.
1397 int finish_write(WIMStruct *w, int image, int write_flags,
1398 wimlib_progress_func_t progress_func)
1401 struct wim_header hdr;
1402 FILE *out = w->out_fp;
1404 /* @hdr will be the header for the new WIM. First copy all the data
1405 * from the header in the WIMStruct; then set all the fields that may
1406 * have changed, including the resource entries, boot index, and image
1408 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1410 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1411 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1416 ret = write_xml_data(w->wim_info, image, out,
1417 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1418 wim_info_get_total_bytes(w->wim_info) : 0,
1419 &hdr.xml_res_entry);
1423 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1424 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1425 struct wim_header checkpoint_hdr;
1426 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1427 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1428 if (fseeko(out, 0, SEEK_SET) != 0) {
1429 ret = WIMLIB_ERR_WRITE;
1432 ret = write_header(&checkpoint_hdr, out);
1436 if (fflush(out) != 0) {
1437 ERROR_WITH_ERRNO("Can't write data to WIM");
1438 ret = WIMLIB_ERR_WRITE;
1442 if (fseeko(out, 0, SEEK_END) != 0) {
1443 ret = WIMLIB_ERR_WRITE;
1448 off_t old_lookup_table_end;
1449 off_t new_lookup_table_end;
1450 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1451 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1452 w->hdr.lookup_table_res_entry.size;
1454 old_lookup_table_end = 0;
1456 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1457 hdr.lookup_table_res_entry.size;
1459 ret = write_integrity_table(out,
1461 new_lookup_table_end,
1462 old_lookup_table_end,
1467 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1471 * In the WIM header, there is room for the resource entry for a
1472 * metadata resource labeled as the "boot metadata". This entry should
1473 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1474 * it should be a copy of the resource entry for the image that is
1475 * marked as bootable. This is not well documented...
1477 if (hdr.boot_idx == 0 || !w->image_metadata
1478 || (image != WIMLIB_ALL_IMAGES && image != hdr.boot_idx)) {
1479 memset(&hdr.boot_metadata_res_entry, 0,
1480 sizeof(struct resource_entry));
1482 memcpy(&hdr.boot_metadata_res_entry,
1484 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1485 sizeof(struct resource_entry));
1488 /* Set image count and boot index correctly for single image writes */
1489 if (image != WIMLIB_ALL_IMAGES) {
1490 hdr.image_count = 1;
1491 if (hdr.boot_idx == image)
1497 if (fseeko(out, 0, SEEK_SET) != 0) {
1498 ret = WIMLIB_ERR_WRITE;
1502 ret = write_header(&hdr, out);
1506 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1507 if (fflush(out) != 0
1508 || fsync(fileno(out)) != 0)
1510 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1511 ret = WIMLIB_ERR_WRITE;
1515 if (fclose(out) != 0) {
1516 ERROR_WITH_ERRNO("Failed to close the WIM file");
1518 ret = WIMLIB_ERR_WRITE;
1524 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1525 int lock_wim(FILE *fp, const char *path)
1529 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1531 if (errno == EWOULDBLOCK) {
1532 ERROR("`%s' is already being modified or has been "
1533 "mounted read-write\n"
1534 " by another process!", path);
1535 ret = WIMLIB_ERR_ALREADY_LOCKED;
1537 WARNING("Failed to lock `%s': %s",
1538 path, strerror(errno));
1547 static int open_wim_writable(WIMStruct *w, const char *path,
1548 bool trunc, bool readable)
1559 wimlib_assert(w->out_fp == NULL);
1560 w->out_fp = fopen(path, mode);
1564 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
1565 return WIMLIB_ERR_OPEN;
1570 void close_wim_writable(WIMStruct *w)
1573 if (fclose(w->out_fp) != 0) {
1574 WARNING("Failed to close output WIM: %s",
1581 /* Open file stream and write dummy header for WIM. */
1582 int begin_write(WIMStruct *w, const char *path, int write_flags)
1585 ret = open_wim_writable(w, path, true,
1586 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1589 /* Write dummy header. It will be overwritten later. */
1590 return write_header(&w->hdr, w->out_fp);
1593 /* Writes a stand-alone WIM to a file. */
1594 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1595 int image, int write_flags, unsigned num_threads,
1596 wimlib_progress_func_t progress_func)
1601 return WIMLIB_ERR_INVALID_PARAM;
1603 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1605 if (image != WIMLIB_ALL_IMAGES &&
1606 (image < 1 || image > w->hdr.image_count))
1607 return WIMLIB_ERR_INVALID_IMAGE;
1609 if (w->hdr.total_parts != 1) {
1610 ERROR("Cannot call wimlib_write() on part of a split WIM");
1611 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1614 ret = begin_write(w, path, write_flags);
1618 ret = write_wim_streams(w, image, write_flags, num_threads,
1624 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1626 ret = for_image(w, image, write_metadata_resource);
1631 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1633 ret = finish_write(w, image, write_flags, progress_func);
1635 close_wim_writable(w);
1639 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1642 memcpy(<e->output_resource_entry, <e->resource_entry,
1643 sizeof(struct resource_entry));
1644 lte->out_refcnt = 0;
1648 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1650 off_t end_offset = *(u64*)arg;
1652 wimlib_assert(lte->out_refcnt <= lte->refcnt);
1653 if (lte->out_refcnt < lte->refcnt) {
1654 if (lte->resource_entry.offset + lte->resource_entry.size > end_offset) {
1655 ERROR("The following resource is after the XML data:");
1656 print_lookup_table_entry(lte);
1657 return WIMLIB_ERR_RESOURCE_ORDER;
1663 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1665 if (lte->out_refcnt == lte->refcnt)
1666 list_add(<e->staging_list, (struct list_head*)arg);
1668 lte->out_refcnt = lte->refcnt;
1673 * Overwrite a WIM, possibly appending streams to it.
1675 * A WIM looks like (or is supposed to look like) the following:
1677 * Header (212 bytes)
1678 * Streams and metadata resources (variable size)
1679 * Lookup table (variable size)
1680 * XML data (variable size)
1681 * Integrity table (optional) (variable size)
1683 * If we are not adding any streams or metadata resources, the lookup table is
1684 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1685 * header. This operation is potentially unsafe if the program is abruptly
1686 * terminated while the XML data or integrity table are being overwritten, but
1687 * before the new header has been written. To partially alleviate this problem,
1688 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1689 * finish_write() to cause a temporary WIM header to be written after the XML
1690 * data has been written. This may prevent the WIM from becoming corrupted if
1691 * the program is terminated while the integrity table is being calculated (but
1692 * no guarantees, due to write re-ordering...).
1694 * If we are adding new streams or images (metadata resources), the lookup table
1695 * needs to be changed, and those streams need to be written. In this case, we
1696 * try to perform a safe update of the WIM file by writing the streams *after*
1697 * the end of the previous WIM, then writing the new lookup table, XML data, and
1698 * (optionally) integrity table following the new streams. This will produce a
1699 * layout like the following:
1701 * Header (212 bytes)
1702 * (OLD) Streams and metadata resources (variable size)
1703 * (OLD) Lookup table (variable size)
1704 * (OLD) XML data (variable size)
1705 * (OLD) Integrity table (optional) (variable size)
1706 * (NEW) Streams and metadata resources (variable size)
1707 * (NEW) Lookup table (variable size)
1708 * (NEW) XML data (variable size)
1709 * (NEW) Integrity table (optional) (variable size)
1711 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1712 * the header is overwritten to point to the new lookup table, XML data, and
1713 * integrity table, to produce the following layout:
1715 * Header (212 bytes)
1716 * Streams and metadata resources (variable size)
1717 * Nothing (variable size)
1718 * More Streams and metadata resources (variable size)
1719 * Lookup table (variable size)
1720 * XML data (variable size)
1721 * Integrity table (optional) (variable size)
1723 * This method allows an image to be appended to a large WIM very quickly, and
1724 * is is crash-safe except in the case of write re-ordering, but the
1725 * disadvantage is that a small hole is left in the WIM where the old lookup
1726 * table, xml data, and integrity table were. (These usually only take up a
1727 * small amount of space compared to the streams, however.
1729 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1730 unsigned num_threads,
1731 wimlib_progress_func_t progress_func,
1732 int modified_image_idx)
1735 struct list_head stream_list;
1738 DEBUG("Overwriting `%s' in-place", w->filename);
1740 /* Make sure that the integrity table (if present) is after the XML
1741 * data, and that there are no stream resources, metadata resources, or
1742 * lookup tables after the XML data. Otherwise, these data would be
1744 if (w->hdr.integrity.offset != 0 &&
1745 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1746 ERROR("Didn't expect the integrity table to be before the XML data");
1747 return WIMLIB_ERR_RESOURCE_ORDER;
1750 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1751 ERROR("Didn't expect the lookup table to be after the XML data");
1752 return WIMLIB_ERR_RESOURCE_ORDER;
1755 DEBUG("Identifying newly added streams");
1756 for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1757 INIT_LIST_HEAD(&stream_list);
1758 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1759 DEBUG("Identifiying streams in image %d", i + 1);
1760 w->private = &stream_list;
1761 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1762 dentry_find_streams_to_write, w);
1765 if (w->hdr.integrity.offset)
1766 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1768 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1770 ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1775 if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1776 /* If no images have been modified and no images have been
1777 * deleted, a new lookup table does not need to be written. */
1778 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1779 w->hdr.lookup_table_res_entry.size;
1780 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1781 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1784 INIT_LIST_HEAD(&stream_list);
1785 for_lookup_table_entry(w->lookup_table, find_new_streams,
1788 ret = open_wim_writable(w, w->filename, false,
1789 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1793 ret = lock_wim(w->out_fp, w->filename);
1800 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1801 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1802 ret = WIMLIB_ERR_WRITE;
1806 if (!list_empty(&stream_list)) {
1807 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1809 ret = write_stream_list(&stream_list, w->out_fp,
1810 wimlib_get_compression_type(w),
1811 write_flags, num_threads,
1816 DEBUG("No new streams were added");
1819 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1820 select_wim_image(w, i + 1);
1821 ret = write_metadata_resource(w);
1825 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1826 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1829 close_wim_writable(w);
1831 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1832 w->filename, old_wim_end);
1833 truncate(w->filename, old_wim_end);
1838 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1839 unsigned num_threads,
1840 wimlib_progress_func_t progress_func)
1842 size_t wim_name_len;
1845 DEBUG("Overwriting `%s' via a temporary file", w->filename);
1847 /* Write the WIM to a temporary file in the same directory as the
1849 wim_name_len = strlen(w->filename);
1850 char tmpfile[wim_name_len + 10];
1851 memcpy(tmpfile, w->filename, wim_name_len);
1852 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1853 tmpfile[wim_name_len + 9] = '\0';
1855 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1856 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1857 num_threads, progress_func);
1859 ERROR("Failed to write the WIM file `%s'", tmpfile);
1863 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1865 /* Rename the new file to the old file .*/
1866 if (rename(tmpfile, w->filename) != 0) {
1867 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1868 tmpfile, w->filename);
1869 ret = WIMLIB_ERR_RENAME;
1873 if (progress_func) {
1874 union wimlib_progress_info progress;
1875 progress.rename.from = tmpfile;
1876 progress.rename.to = w->filename;
1877 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1880 /* Close the original WIM file that was opened for reading. */
1881 if (w->fp != NULL) {
1886 /* Re-open the WIM read-only. */
1887 w->fp = fopen(w->filename, "rb");
1888 if (w->fp == NULL) {
1889 ret = WIMLIB_ERR_REOPEN;
1890 WARNING("Failed to re-open `%s' read-only: %s",
1891 w->filename, strerror(errno));
1897 /* Remove temporary file. */
1898 if (unlink(tmpfile) != 0)
1899 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1904 * Writes a WIM file to the original file that it was read from, overwriting it.
1906 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1907 unsigned num_threads,
1908 wimlib_progress_func_t progress_func)
1911 return WIMLIB_ERR_INVALID_PARAM;
1913 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1916 return WIMLIB_ERR_NO_FILENAME;
1918 if (w->hdr.total_parts != 1) {
1919 ERROR("Cannot modify a split WIM");
1920 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1923 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1924 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1926 int i, modified_image_idx;
1927 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1929 modified_image_idx = i;
1930 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1931 !w->image_metadata[i].has_been_mounted_rw; i++)
1933 if (i == w->hdr.image_count) {
1934 return overwrite_wim_inplace(w, write_flags, num_threads,
1936 modified_image_idx);
1939 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,