4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "list.h" so that "list.h" can
31 * overwrite the LIST_HEAD macro. */
36 #include "wimlib_internal.h"
37 #include "buffer_io.h"
39 #include "lookup_table.h"
44 #ifdef ENABLE_MULTITHREADED_COMPRESSION
53 #include <ntfs-3g/attrib.h>
54 #include <ntfs-3g/inode.h>
55 #include <ntfs-3g/dir.h>
64 static int fflush_and_ftruncate(FILE *fp, off_t size)
70 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
71 return WIMLIB_ERR_WRITE;
73 ret = ftruncate(fileno(fp), size);
75 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
76 "%"PRIu64" bytes", size);
77 return WIMLIB_ERR_WRITE;
82 /* Chunk table that's located at the beginning of each compressed resource in
83 * the WIM. (This is not the on-disk format; the on-disk format just has an
84 * array of offsets.) */
88 u64 original_resource_size;
89 u64 bytes_per_chunk_entry;
97 * Allocates and initializes a chunk table, and reserves space for it in the
101 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
104 struct chunk_table **chunk_tab_ret)
106 u64 size = wim_resource_size(lte);
107 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
108 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
109 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
113 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
115 ret = WIMLIB_ERR_NOMEM;
118 chunk_tab->file_offset = file_offset;
119 chunk_tab->num_chunks = num_chunks;
120 chunk_tab->original_resource_size = size;
121 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
122 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
124 chunk_tab->cur_offset = 0;
125 chunk_tab->cur_offset_p = chunk_tab->offsets;
127 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
128 chunk_tab->table_disk_size) {
129 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
131 ret = WIMLIB_ERR_WRITE;
137 *chunk_tab_ret = chunk_tab;
142 * Pointer to function to compresses a chunk of a WIM resource.
144 * @chunk: Uncompressed data of the chunk.
145 * @chunk_size: Size of the uncompressed chunk in bytes.
146 * @compressed_chunk: Pointer to output buffer of size at least
147 * (@chunk_size - 1) bytes.
148 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
149 * of the compressed chunk will be
152 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
153 * compressed to any smaller than @chunk_size. This function cannot fail for
156 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
158 compress_func_t get_compress_func(int out_ctype)
160 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
163 return xpress_compress;
167 * Writes a chunk of a WIM resource to an output file.
169 * @chunk: Uncompressed data of the chunk.
170 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
171 * @out_fp: FILE * to write tho chunk to.
172 * @out_ctype: Compression type to use when writing the chunk (ignored if no
173 * chunk table provided)
174 * @chunk_tab: Pointer to chunk table being created. It is updated with the
175 * offset of the chunk we write.
177 * Returns 0 on success; nonzero on failure.
179 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
180 FILE *out_fp, compress_func_t compress,
181 struct chunk_table *chunk_tab)
184 unsigned out_chunk_size;
186 u8 *compressed_chunk = alloca(chunk_size);
189 ret = compress(chunk, chunk_size, compressed_chunk,
192 out_chunk = compressed_chunk;
195 out_chunk_size = chunk_size;
197 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
198 chunk_tab->cur_offset += out_chunk_size;
201 out_chunk_size = chunk_size;
203 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
204 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
205 return WIMLIB_ERR_WRITE;
211 * Finishes a WIM chunk table and writes it to the output file at the correct
214 * The final size of the full compressed resource is returned in the
215 * @compressed_size_p.
218 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
219 FILE *out_fp, u64 *compressed_size_p)
221 size_t bytes_written;
222 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
223 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
224 "WIM file", chunk_tab->file_offset);
225 return WIMLIB_ERR_WRITE;
228 if (chunk_tab->bytes_per_chunk_entry == 8) {
229 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
231 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
232 ((u32*)chunk_tab->offsets)[i] =
233 cpu_to_le32(chunk_tab->offsets[i]);
235 bytes_written = fwrite((u8*)chunk_tab->offsets +
236 chunk_tab->bytes_per_chunk_entry,
237 1, chunk_tab->table_disk_size, out_fp);
238 if (bytes_written != chunk_tab->table_disk_size) {
239 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
241 return WIMLIB_ERR_WRITE;
243 if (fseeko(out_fp, 0, SEEK_END) != 0) {
244 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
245 return WIMLIB_ERR_WRITE;
247 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
251 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
252 * attribute pointer in the lookup table entry. */
253 static int prepare_resource_for_read(struct lookup_table_entry *lte
256 , ntfs_inode **ni_ret
260 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
261 && !lte->file_on_disk_fp)
263 wimlib_assert(lte->file_on_disk);
264 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
265 if (!lte->file_on_disk_fp) {
266 ERROR_WITH_ERRNO("Failed to open the file `%s' for "
267 "reading", lte->file_on_disk);
268 return WIMLIB_ERR_OPEN;
272 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
275 struct ntfs_location *loc = lte->ntfs_loc;
278 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
280 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
281 "volume", loc->path_utf8);
282 return WIMLIB_ERR_NTFS_3G;
284 lte->attr = ntfs_attr_open(ni,
285 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
286 (ntfschar*)loc->stream_name_utf16,
287 loc->stream_name_utf16_num_chars);
289 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
290 "NTFS volume", loc->path_utf8);
291 ntfs_inode_close(ni);
292 return WIMLIB_ERR_NTFS_3G;
300 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
302 static void end_wim_resource_read(struct lookup_table_entry *lte
308 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
309 && lte->file_on_disk_fp) {
310 fclose(lte->file_on_disk_fp);
311 lte->file_on_disk_fp = NULL;
314 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
316 ntfs_attr_close(lte->attr);
320 ntfs_inode_close(ni);
326 write_uncompressed_resource_and_truncate(struct lookup_table_entry *lte,
329 struct resource_entry *out_res_entry)
332 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
333 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
334 "output WIM file", file_offset);
335 return WIMLIB_ERR_WRITE;
337 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
342 return fflush_and_ftruncate(out_fp,
343 file_offset + wim_resource_size(lte));
347 * Writes a WIM resource to a FILE * opened for writing. The resource may be
348 * written uncompressed or compressed depending on the @out_ctype parameter.
350 * If by chance the resource compresses to more than the original size (this may
351 * happen with random data or files than are pre-compressed), the resource is
352 * instead written uncompressed (and this is reflected in the @out_res_entry by
353 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
355 * @lte: The lookup table entry for the WIM resource.
356 * @out_fp: The FILE * to write the resource to.
357 * @out_ctype: The compression type of the resource to write. Note: if this is
358 * the same as the compression type of the WIM resource we
359 * need to read, we simply copy the data (i.e. we do not
360 * uncompress it, then compress it again).
361 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
362 * offset, original size, compressed size, and compression flag
363 * of the output resource.
365 * Returns 0 on success; nonzero on failure.
367 int write_wim_resource(struct lookup_table_entry *lte,
368 FILE *out_fp, int out_ctype,
369 struct resource_entry *out_res_entry,
374 u64 old_compressed_size;
375 u64 new_compressed_size;
378 struct chunk_table *chunk_tab = NULL;
381 compress_func_t compress = NULL;
383 ntfs_inode *ni = NULL;
388 /* Original size of the resource */
389 original_size = wim_resource_size(lte);
391 /* Compressed size of the resource (as it exists now) */
392 old_compressed_size = wim_resource_compressed_size(lte);
394 /* Current offset in output file */
395 file_offset = ftello(out_fp);
396 if (file_offset == -1) {
397 ERROR_WITH_ERRNO("Failed to get offset in output "
399 return WIMLIB_ERR_WRITE;
402 /* Are the compression types the same? If so, do a raw copy (copy
403 * without decompressing and recompressing the data). */
404 raw = (wim_resource_compression_type(lte) == out_ctype
405 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
406 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
409 flags |= WIMLIB_RESOURCE_FLAG_RAW;
410 bytes_remaining = old_compressed_size;
412 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
413 bytes_remaining = original_size;
416 /* Empty resource; nothing needs to be done, so just return success. */
417 if (bytes_remaining == 0)
420 /* Buffer for reading chunks for the resource */
421 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
423 /* If we are writing a compressed resource and not doing a raw copy, we
424 * need to initialize the chunk table */
425 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
426 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
432 /* If the WIM resource is in an external file, open a FILE * to it so we
433 * don't have to open a temporary one in read_wim_resource() for each
436 ret = prepare_resource_for_read(lte, &ni);
438 ret = prepare_resource_for_read(lte);
443 /* If we aren't doing a raw copy, we will compute the SHA1 message
444 * digest of the resource as we read it, and verify it's the same as the
445 * hash given in the lookup table entry once we've finished reading the
450 compress = get_compress_func(out_ctype);
454 /* While there are still bytes remaining in the WIM resource, read a
455 * chunk of the resource, update SHA1, then write that chunk using the
456 * desired compression type. */
458 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
459 ret = read_wim_resource(lte, buf, to_read, offset, flags);
463 sha1_update(&ctx, buf, to_read);
464 ret = write_wim_resource_chunk(buf, to_read, out_fp,
465 compress, chunk_tab);
468 bytes_remaining -= to_read;
470 } while (bytes_remaining);
472 /* Raw copy: The new compressed size is the same as the old compressed
475 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
478 * Using a different compression type: Call
479 * finish_wim_resource_chunk_tab() and it will provide the new
483 new_compressed_size = old_compressed_size;
485 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
486 new_compressed_size = original_size;
488 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
489 &new_compressed_size);
495 /* Verify SHA1 message digest of the resource, unless we are doing a raw
496 * write (in which case we never even saw the uncompressed data). Or,
497 * if the hash we had before is all 0's, just re-set it to be the new
500 u8 md[SHA1_HASH_SIZE];
501 sha1_final(md, &ctx);
502 if (is_zero_hash(lte->hash)) {
503 copy_hash(lte->hash, md);
504 } else if (!hashes_equal(md, lte->hash)) {
505 ERROR("WIM resource has incorrect hash!");
506 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
507 ERROR("We were reading it from `%s'; maybe it changed "
508 "while we were reading it.",
511 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
516 if (!raw && new_compressed_size >= original_size &&
517 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
519 /* Oops! We compressed the resource to larger than the original
520 * size. Write the resource uncompressed instead. */
521 ret = write_uncompressed_resource_and_truncate(lte,
529 out_res_entry->size = new_compressed_size;
530 out_res_entry->original_size = original_size;
531 out_res_entry->offset = file_offset;
532 out_res_entry->flags = lte->resource_entry.flags
533 & ~WIM_RESHDR_FLAG_COMPRESSED;
534 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
535 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
541 end_wim_resource_read(lte, ni);
543 end_wim_resource_read(lte);
550 #ifdef ENABLE_MULTITHREADED_COMPRESSION
552 /* Blocking shared queue (solves the producer-consumer problem) */
553 struct shared_queue {
557 unsigned filled_slots;
559 pthread_mutex_t lock;
560 pthread_cond_t msg_avail_cond;
561 pthread_cond_t space_avail_cond;
564 static int shared_queue_init(struct shared_queue *q, unsigned size)
566 wimlib_assert(size != 0);
567 q->array = CALLOC(sizeof(q->array[0]), size);
569 return WIMLIB_ERR_NOMEM;
574 pthread_mutex_init(&q->lock, NULL);
575 pthread_cond_init(&q->msg_avail_cond, NULL);
576 pthread_cond_init(&q->space_avail_cond, NULL);
580 static void shared_queue_destroy(struct shared_queue *q)
583 pthread_mutex_destroy(&q->lock);
584 pthread_cond_destroy(&q->msg_avail_cond);
585 pthread_cond_destroy(&q->space_avail_cond);
588 static void shared_queue_put(struct shared_queue *q, void *obj)
590 pthread_mutex_lock(&q->lock);
591 while (q->filled_slots == q->size)
592 pthread_cond_wait(&q->space_avail_cond, &q->lock);
594 q->back = (q->back + 1) % q->size;
595 q->array[q->back] = obj;
598 pthread_cond_broadcast(&q->msg_avail_cond);
599 pthread_mutex_unlock(&q->lock);
602 static void *shared_queue_get(struct shared_queue *q)
606 pthread_mutex_lock(&q->lock);
607 while (q->filled_slots == 0)
608 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
610 obj = q->array[q->front];
611 q->array[q->front] = NULL;
612 q->front = (q->front + 1) % q->size;
615 pthread_cond_broadcast(&q->space_avail_cond);
616 pthread_mutex_unlock(&q->lock);
620 struct compressor_thread_params {
621 struct shared_queue *res_to_compress_queue;
622 struct shared_queue *compressed_res_queue;
623 compress_func_t compress;
626 #define MAX_CHUNKS_PER_MSG 2
629 struct lookup_table_entry *lte;
630 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
631 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
632 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
633 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
634 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
636 struct list_head list;
641 static void compress_chunks(struct message *msg, compress_func_t compress)
643 for (unsigned i = 0; i < msg->num_chunks; i++) {
644 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
645 int ret = compress(msg->uncompressed_chunks[i],
646 msg->uncompressed_chunk_sizes[i],
647 msg->compressed_chunks[i],
648 &msg->compressed_chunk_sizes[i]);
650 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
652 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
653 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
658 /* Compressor thread routine. This is a lot simpler than the main thread
659 * routine: just repeatedly get a group of chunks from the
660 * res_to_compress_queue, compress them, and put them in the
661 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
663 static void *compressor_thread_proc(void *arg)
665 struct compressor_thread_params *params = arg;
666 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
667 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
668 compress_func_t compress = params->compress;
671 DEBUG("Compressor thread ready");
672 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
673 compress_chunks(msg, compress);
674 shared_queue_put(compressed_res_queue, msg);
676 DEBUG("Compressor thread terminating");
681 static int do_write_stream_list(struct list_head *my_resources,
684 wimlib_progress_func_t progress_func,
685 union wimlib_progress_info *progress,
686 int write_resource_flags)
689 struct lookup_table_entry *lte, *tmp;
691 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
692 ret = write_wim_resource(lte,
695 <e->output_resource_entry,
696 write_resource_flags);
699 list_del(<e->staging_list);
700 progress->write_streams.completed_bytes +=
701 wim_resource_size(lte);
702 progress->write_streams.completed_streams++;
704 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
711 static int write_stream_list_serial(struct list_head *stream_list,
715 wimlib_progress_func_t progress_func,
716 union wimlib_progress_info *progress)
718 int write_resource_flags;
720 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
721 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
723 write_resource_flags = 0;
724 progress->write_streams.num_threads = 1;
726 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
727 return do_write_stream_list(stream_list, out_fp,
728 out_ctype, progress_func,
729 progress, write_resource_flags);
732 #ifdef ENABLE_MULTITHREADED_COMPRESSION
733 static int write_wim_chunks(struct message *msg, FILE *out_fp,
734 struct chunk_table *chunk_tab)
736 for (unsigned i = 0; i < msg->num_chunks; i++) {
737 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
739 DEBUG2("Write wim chunk %u of %u (csize = %u)",
740 i, msg->num_chunks, chunk_csize);
742 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
745 ERROR_WITH_ERRNO("Failed to write WIM chunk");
746 return WIMLIB_ERR_WRITE;
749 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
750 chunk_tab->cur_offset += chunk_csize;
756 * This function is executed by the main thread when the resources are being
757 * compressed in parallel. The main thread is in change of all reading of the
758 * uncompressed data and writing of the compressed data. The compressor threads
759 * *only* do compression from/to in-memory buffers.
761 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
762 * chunks of compressed data to compress, represented in a `struct message'.
763 * Each message is passed from the main thread to a worker thread through the
764 * res_to_compress_queue, and it is passed back through the
765 * compressed_res_queue.
767 static int main_writer_thread_proc(struct list_head *stream_list,
770 struct shared_queue *res_to_compress_queue,
771 struct shared_queue *compressed_res_queue,
774 wimlib_progress_func_t progress_func,
775 union wimlib_progress_info *progress)
778 struct chunk_table *cur_chunk_tab = NULL;
779 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
780 struct lookup_table_entry *next_lte = NULL;
782 // Initially, all the messages are available to use.
783 LIST_HEAD(available_msgs);
786 ret = WIMLIB_ERR_NOMEM;
790 for (size_t i = 0; i < num_messages; i++)
791 list_add(&msgs[i].list, &available_msgs);
793 // outstanding_resources is the list of resources that currently have
794 // had chunks sent off for compression.
796 // The first stream in outstanding_resources is the stream that is
797 // currently being written (cur_lte).
799 // The last stream in outstanding_resources is the stream that is
800 // currently being read and chunks fed to the compressor threads
803 // Depending on the number of threads and the sizes of the resource,
804 // the outstanding streams list may contain streams between cur_lte and
805 // next_lte that have all their chunks compressed or being compressed,
806 // but haven't been written yet.
808 LIST_HEAD(outstanding_resources);
809 struct list_head *next_resource = stream_list->next;
811 u64 next_num_chunks = 0;
813 // As in write_wim_resource(), each resource we read is checksummed.
814 SHA_CTX next_sha_ctx;
815 u8 next_hash[SHA1_HASH_SIZE];
817 // Resources that don't need any chunks compressed are added to this
818 // list and written directly by the main thread.
819 LIST_HEAD(my_resources);
821 struct lookup_table_entry *cur_lte = NULL;
825 ntfs_inode *ni = NULL;
828 DEBUG("Initializing buffers for uncompressed "
829 "and compressed data (%zu bytes needed)",
830 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
832 // Pre-allocate all the buffers that will be needed to do the chunk
834 for (size_t i = 0; i < num_messages; i++) {
835 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
836 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
838 // The extra 8 bytes is because longest_match() in lz.c
839 // may read a little bit off the end of the uncompressed
840 // data. It doesn't need to be initialized--- we really
841 // just need to avoid accessing an unmapped page.
842 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
843 if (msgs[i].compressed_chunks[j] == NULL ||
844 msgs[i].uncompressed_chunks[j] == NULL)
846 ret = WIMLIB_ERR_NOMEM;
852 // This loop is executed until all resources have been written, except
853 // possibly a few that have been added to the @my_resources list for
856 // Send chunks to the compressor threads until either (a) there
857 // are no more messages available since they were all sent off,
858 // or (b) there are no more resources that need to be
860 while (!list_empty(&available_msgs)) {
861 if (next_chunk == next_num_chunks) {
862 // If next_chunk == next_num_chunks, there are
863 // no more chunks to write in the current
864 // stream. So, check the SHA1 message digest of
865 // the stream that was just finished (unless
866 // next_lte == NULL, which is the case the very
867 // first time this loop is entered, and also
868 // near the very end of the compression when
869 // there are no more streams.) Then, advance to
870 // the next stream (if there is one).
871 if (next_lte != NULL) {
873 end_wim_resource_read(next_lte, ni);
876 end_wim_resource_read(next_lte);
878 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
880 sha1_final(next_hash, &next_sha_ctx);
881 if (!hashes_equal(next_lte->hash, next_hash)) {
882 ERROR("WIM resource has incorrect hash!");
883 if (next_lte->resource_location ==
884 RESOURCE_IN_FILE_ON_DISK)
886 ERROR("We were reading it from `%s'; "
887 "maybe it changed while we were "
889 next_lte->file_on_disk);
891 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
896 // Advance to the next resource.
898 // If the next resource needs no compression, just write
899 // it with this thread (not now though--- we could be in
900 // the middle of writing another resource.) Keep doing
901 // this until we either get to the end of the resources
902 // list, or we get to a resource that needs compression.
904 if (next_resource == stream_list) {
905 // No more resources to send for
910 next_lte = container_of(next_resource,
911 struct lookup_table_entry,
913 next_resource = next_resource->next;
914 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
915 && wim_resource_compression_type(next_lte) == out_ctype)
916 || wim_resource_size(next_lte) == 0)
918 list_add_tail(&next_lte->staging_list,
921 list_add_tail(&next_lte->staging_list,
922 &outstanding_resources);
924 next_num_chunks = wim_resource_chunks(next_lte);
925 sha1_init(&next_sha_ctx);
926 INIT_LIST_HEAD(&next_lte->msg_list);
928 ret = prepare_resource_for_read(next_lte, &ni);
930 ret = prepare_resource_for_read(next_lte);
935 if (cur_lte == NULL) {
936 // Set cur_lte for the
945 if (next_lte == NULL) {
946 // No more resources to send for compression
950 // Get a message from the available messages
952 msg = container_of(available_msgs.next,
956 // ... and delete it from the available messages
958 list_del(&msg->list);
960 // Initialize the message with the chunks to
962 msg->num_chunks = min(next_num_chunks - next_chunk,
965 msg->complete = false;
966 msg->begin_chunk = next_chunk;
968 unsigned size = WIM_CHUNK_SIZE;
969 for (unsigned i = 0; i < msg->num_chunks; i++) {
971 // Read chunk @next_chunk of the stream into the
972 // message so that a compressor thread can
975 if (next_chunk == next_num_chunks - 1) {
976 size = MODULO_NONZERO(wim_resource_size(next_lte),
980 DEBUG2("Read resource (size=%u, offset=%zu)",
981 size, next_chunk * WIM_CHUNK_SIZE);
983 msg->uncompressed_chunk_sizes[i] = size;
985 ret = read_wim_resource(next_lte,
986 msg->uncompressed_chunks[i],
988 next_chunk * WIM_CHUNK_SIZE,
992 sha1_update(&next_sha_ctx,
993 msg->uncompressed_chunks[i], size);
997 // Send the compression request
998 list_add_tail(&msg->list, &next_lte->msg_list);
999 shared_queue_put(res_to_compress_queue, msg);
1000 DEBUG2("Compression request sent");
1003 // If there are no outstanding resources, there are no more
1004 // resources that need to be written.
1005 if (list_empty(&outstanding_resources)) {
1010 // Get the next message from the queue and process it.
1011 // The message will contain 1 or more data chunks that have been
1013 msg = shared_queue_get(compressed_res_queue);
1014 msg->complete = true;
1016 // Is this the next chunk in the current resource? If it's not
1017 // (i.e., an earlier chunk in a same or different resource
1018 // hasn't been compressed yet), do nothing, and keep this
1019 // message around until all earlier chunks are received.
1021 // Otherwise, write all the chunks we can.
1022 while (cur_lte != NULL &&
1023 (msg = container_of(cur_lte->msg_list.next,
1027 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1028 if (msg->begin_chunk == 0) {
1029 DEBUG2("Begin chunk tab");
1031 // This is the first set of chunks. Leave space
1032 // for the chunk table in the output file.
1033 off_t cur_offset = ftello(out_fp);
1034 if (cur_offset == -1) {
1035 ret = WIMLIB_ERR_WRITE;
1038 ret = begin_wim_resource_chunk_tab(cur_lte,
1046 // Write the compressed chunks from the message.
1047 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1051 list_del(&msg->list);
1053 // This message is available to use for different chunks
1055 list_add(&msg->list, &available_msgs);
1057 // Was this the last chunk of the stream? If so, finish
1059 if (list_empty(&cur_lte->msg_list) &&
1060 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1062 DEBUG2("Finish wim chunk tab");
1064 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1070 if (res_csize >= wim_resource_size(cur_lte)) {
1071 /* Oops! We compressed the resource to
1072 * larger than the original size. Write
1073 * the resource uncompressed instead. */
1074 ret = write_uncompressed_resource_and_truncate(
1077 cur_chunk_tab->file_offset,
1078 &cur_lte->output_resource_entry);
1082 cur_lte->output_resource_entry.size =
1085 cur_lte->output_resource_entry.original_size =
1086 cur_lte->resource_entry.original_size;
1088 cur_lte->output_resource_entry.offset =
1089 cur_chunk_tab->file_offset;
1091 cur_lte->output_resource_entry.flags =
1092 cur_lte->resource_entry.flags |
1093 WIM_RESHDR_FLAG_COMPRESSED;
1096 progress->write_streams.completed_bytes +=
1097 wim_resource_size(cur_lte);
1098 progress->write_streams.completed_streams++;
1100 if (progress_func) {
1101 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1105 FREE(cur_chunk_tab);
1106 cur_chunk_tab = NULL;
1108 struct list_head *next = cur_lte->staging_list.next;
1109 list_del(&cur_lte->staging_list);
1111 if (next == &outstanding_resources)
1114 cur_lte = container_of(cur_lte->staging_list.next,
1115 struct lookup_table_entry,
1118 // Since we just finished writing a stream,
1119 // write any streams that have been added to the
1120 // my_resources list for direct writing by the
1121 // main thread (e.g. resources that don't need
1122 // to be compressed because the desired
1123 // compression type is the same as the previous
1124 // compression type).
1125 ret = do_write_stream_list(&my_resources,
1138 if (ret == WIMLIB_ERR_NOMEM) {
1139 ERROR("Could not allocate enough memory for "
1140 "multi-threaded compression");
1145 end_wim_resource_read(next_lte, ni);
1147 end_wim_resource_read(next_lte);
1152 ret = do_write_stream_list(&my_resources, out_fp,
1153 out_ctype, progress_func,
1157 size_t num_available_msgs = 0;
1158 struct list_head *cur;
1160 list_for_each(cur, &available_msgs) {
1161 num_available_msgs++;
1164 while (num_available_msgs < num_messages) {
1165 shared_queue_get(compressed_res_queue);
1166 num_available_msgs++;
1172 for (size_t i = 0; i < num_messages; i++) {
1173 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1174 FREE(msgs[i].compressed_chunks[j]);
1175 FREE(msgs[i].uncompressed_chunks[j]);
1181 FREE(cur_chunk_tab);
1186 static int write_stream_list_parallel(struct list_head *stream_list,
1190 unsigned num_threads,
1191 wimlib_progress_func_t progress_func,
1192 union wimlib_progress_info *progress)
1195 struct shared_queue res_to_compress_queue;
1196 struct shared_queue compressed_res_queue;
1197 pthread_t *compressor_threads = NULL;
1199 if (num_threads == 0) {
1200 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1202 WARNING("Could not determine number of processors! Assuming 1");
1205 num_threads = nthreads;
1209 progress->write_streams.num_threads = num_threads;
1210 wimlib_assert(stream_list->next != stream_list);
1212 static const double MESSAGES_PER_THREAD = 2.0;
1213 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1215 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1217 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1221 ret = shared_queue_init(&compressed_res_queue, queue_size);
1223 goto out_destroy_res_to_compress_queue;
1225 struct compressor_thread_params params;
1226 params.res_to_compress_queue = &res_to_compress_queue;
1227 params.compressed_res_queue = &compressed_res_queue;
1228 params.compress = get_compress_func(out_ctype);
1230 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1231 if (!compressor_threads) {
1232 ret = WIMLIB_ERR_NOMEM;
1233 goto out_destroy_compressed_res_queue;
1236 for (unsigned i = 0; i < num_threads; i++) {
1237 DEBUG("pthread_create thread %u", i);
1238 ret = pthread_create(&compressor_threads[i], NULL,
1239 compressor_thread_proc, ¶ms);
1242 ERROR_WITH_ERRNO("Failed to create compressor "
1250 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1252 ret = main_writer_thread_proc(stream_list,
1255 &res_to_compress_queue,
1256 &compressed_res_queue,
1262 for (unsigned i = 0; i < num_threads; i++)
1263 shared_queue_put(&res_to_compress_queue, NULL);
1265 for (unsigned i = 0; i < num_threads; i++) {
1266 if (pthread_join(compressor_threads[i], NULL)) {
1267 WARNING("Failed to join compressor thread %u: %s",
1268 i, strerror(errno));
1271 FREE(compressor_threads);
1272 out_destroy_compressed_res_queue:
1273 shared_queue_destroy(&compressed_res_queue);
1274 out_destroy_res_to_compress_queue:
1275 shared_queue_destroy(&res_to_compress_queue);
1276 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1279 WARNING("Falling back to single-threaded compression");
1280 return write_stream_list_serial(stream_list,
1291 * Write a list of streams to a WIM (@out_fp) using the compression type
1292 * @out_ctype and up to @num_threads compressor threads.
1294 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1295 int out_ctype, int write_flags,
1296 unsigned num_threads,
1297 wimlib_progress_func_t progress_func)
1299 struct lookup_table_entry *lte;
1300 size_t num_streams = 0;
1301 u64 total_bytes = 0;
1302 u64 total_compression_bytes = 0;
1303 union wimlib_progress_info progress;
1305 list_for_each_entry(lte, stream_list, staging_list) {
1307 total_bytes += wim_resource_size(lte);
1308 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1309 && (wim_resource_compression_type(lte) != out_ctype ||
1310 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1312 total_compression_bytes += wim_resource_size(lte);
1315 progress.write_streams.total_bytes = total_bytes;
1316 progress.write_streams.total_streams = num_streams;
1317 progress.write_streams.completed_bytes = 0;
1318 progress.write_streams.completed_streams = 0;
1319 progress.write_streams.num_threads = num_threads;
1320 progress.write_streams.compression_type = out_ctype;
1322 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1323 if (total_compression_bytes >= 1000000 && num_threads != 1)
1324 return write_stream_list_parallel(stream_list,
1333 return write_stream_list_serial(stream_list,
1342 static int dentry_find_streams_to_write(struct dentry *dentry,
1346 struct list_head *stream_list = w->private;
1347 struct lookup_table_entry *lte;
1348 for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1349 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1350 if (lte && ++lte->out_refcnt == 1)
1351 list_add_tail(<e->staging_list, stream_list);
1356 static int find_streams_to_write(WIMStruct *w)
1358 return for_dentry_in_tree(wim_root_dentry(w),
1359 dentry_find_streams_to_write, w);
1362 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1363 unsigned num_threads,
1364 wimlib_progress_func_t progress_func)
1367 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1368 LIST_HEAD(stream_list);
1369 w->private = &stream_list;
1370 for_image(w, image, find_streams_to_write);
1371 return write_stream_list(&stream_list, w->out_fp,
1372 wimlib_get_compression_type(w), write_flags,
1373 num_threads, progress_func);
1377 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1378 * table (optional), then overwrite the WIM header.
1380 * write_flags is a bitwise OR of the following:
1382 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1383 * Include an integrity table.
1385 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1386 * Show progress information when (if) writing the integrity table.
1388 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1389 * Don't write the lookup table.
1391 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1392 * When (if) writing the integrity table, re-use entries from the
1393 * existing integrity table, if possible.
1395 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1396 * After writing the XML data but before writing the integrity
1397 * table, write a temporary WIM header and flush the stream so that
1398 * the WIM is less likely to become corrupted upon abrupt program
1401 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1402 * fsync() the output file before closing it.
1405 int finish_write(WIMStruct *w, int image, int write_flags,
1406 wimlib_progress_func_t progress_func)
1409 struct wim_header hdr;
1410 FILE *out = w->out_fp;
1412 /* @hdr will be the header for the new WIM. First copy all the data
1413 * from the header in the WIMStruct; then set all the fields that may
1414 * have changed, including the resource entries, boot index, and image
1416 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1418 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1419 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1424 ret = write_xml_data(w->wim_info, image, out,
1425 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1426 wim_info_get_total_bytes(w->wim_info) : 0,
1427 &hdr.xml_res_entry);
1431 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1432 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1433 struct wim_header checkpoint_hdr;
1434 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1435 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1436 if (fseeko(out, 0, SEEK_SET) != 0) {
1437 ERROR_WITH_ERRNO("Failed to seek to beginning "
1438 "of WIM being written");
1439 ret = WIMLIB_ERR_WRITE;
1442 ret = write_header(&checkpoint_hdr, out);
1446 if (fflush(out) != 0) {
1447 ERROR_WITH_ERRNO("Can't write data to WIM");
1448 ret = WIMLIB_ERR_WRITE;
1452 if (fseeko(out, 0, SEEK_END) != 0) {
1453 ERROR_WITH_ERRNO("Failed to seek to end "
1454 "of WIM being written");
1455 ret = WIMLIB_ERR_WRITE;
1460 off_t old_lookup_table_end;
1461 off_t new_lookup_table_end;
1462 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1463 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1464 w->hdr.lookup_table_res_entry.size;
1466 old_lookup_table_end = 0;
1468 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1469 hdr.lookup_table_res_entry.size;
1471 ret = write_integrity_table(out,
1473 new_lookup_table_end,
1474 old_lookup_table_end,
1479 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1483 * In the WIM header, there is room for the resource entry for a
1484 * metadata resource labeled as the "boot metadata". This entry should
1485 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1486 * it should be a copy of the resource entry for the image that is
1487 * marked as bootable. This is not well documented...
1490 /* Set image count and boot index correctly for single image writes */
1491 if (image != WIMLIB_ALL_IMAGES) {
1492 hdr.image_count = 1;
1493 if (hdr.boot_idx == image)
1499 if (hdr.boot_idx == 0) {
1500 memset(&hdr.boot_metadata_res_entry, 0,
1501 sizeof(struct resource_entry));
1503 memcpy(&hdr.boot_metadata_res_entry,
1505 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1506 sizeof(struct resource_entry));
1509 if (fseeko(out, 0, SEEK_SET) != 0) {
1510 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1512 ret = WIMLIB_ERR_WRITE;
1516 ret = write_header(&hdr, out);
1520 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1521 if (fflush(out) != 0
1522 || fsync(fileno(out)) != 0)
1524 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1525 ret = WIMLIB_ERR_WRITE;
1529 if (fclose(out) != 0) {
1530 ERROR_WITH_ERRNO("Failed to close the WIM file");
1532 ret = WIMLIB_ERR_WRITE;
1538 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1539 int lock_wim(FILE *fp, const char *path)
1543 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1545 if (errno == EWOULDBLOCK) {
1546 ERROR("`%s' is already being modified or has been "
1547 "mounted read-write\n"
1548 " by another process!", path);
1549 ret = WIMLIB_ERR_ALREADY_LOCKED;
1551 WARNING("Failed to lock `%s': %s",
1552 path, strerror(errno));
1561 static int open_wim_writable(WIMStruct *w, const char *path,
1562 bool trunc, bool readable)
1573 wimlib_assert(w->out_fp == NULL);
1574 w->out_fp = fopen(path, mode);
1578 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
1579 return WIMLIB_ERR_OPEN;
1584 void close_wim_writable(WIMStruct *w)
1587 if (fclose(w->out_fp) != 0) {
1588 WARNING("Failed to close output WIM: %s",
1595 /* Open file stream and write dummy header for WIM. */
1596 int begin_write(WIMStruct *w, const char *path, int write_flags)
1599 ret = open_wim_writable(w, path, true,
1600 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1603 /* Write dummy header. It will be overwritten later. */
1604 return write_header(&w->hdr, w->out_fp);
1607 /* Writes a stand-alone WIM to a file. */
1608 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1609 int image, int write_flags, unsigned num_threads,
1610 wimlib_progress_func_t progress_func)
1615 return WIMLIB_ERR_INVALID_PARAM;
1617 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1619 if (image != WIMLIB_ALL_IMAGES &&
1620 (image < 1 || image > w->hdr.image_count))
1621 return WIMLIB_ERR_INVALID_IMAGE;
1623 if (w->hdr.total_parts != 1) {
1624 ERROR("Cannot call wimlib_write() on part of a split WIM");
1625 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1628 ret = begin_write(w, path, write_flags);
1632 ret = write_wim_streams(w, image, write_flags, num_threads,
1638 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1640 ret = for_image(w, image, write_metadata_resource);
1645 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1647 ret = finish_write(w, image, write_flags, progress_func);
1649 close_wim_writable(w);
1653 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1656 memcpy(<e->output_resource_entry, <e->resource_entry,
1657 sizeof(struct resource_entry));
1658 lte->out_refcnt = 0;
1662 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1664 wimlib_assert(lte->out_refcnt <= lte->refcnt);
1665 if (lte->out_refcnt < lte->refcnt) {
1666 off_t end_offset = *(u64*)arg;
1667 if (lte->resource_entry.offset +
1668 lte->resource_entry.size > end_offset)
1670 ERROR("The following resource is after the XML data:");
1671 print_lookup_table_entry(lte);
1672 return WIMLIB_ERR_RESOURCE_ORDER;
1678 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1680 if (lte->out_refcnt == lte->refcnt) {
1681 /* Newly added stream that is only referenced in the modified
1682 * images. Append it to the list of streams to write. */
1683 list_add(<e->staging_list, (struct list_head*)arg);
1685 /* Not a newly added stream. But set out_refcnt to the full
1686 * refcnt so that it's written correctly. */
1687 lte->out_refcnt = lte->refcnt;
1693 * Overwrite a WIM, possibly appending streams to it.
1695 * A WIM looks like (or is supposed to look like) the following:
1697 * Header (212 bytes)
1698 * Streams and metadata resources (variable size)
1699 * Lookup table (variable size)
1700 * XML data (variable size)
1701 * Integrity table (optional) (variable size)
1703 * If we are not adding any streams or metadata resources, the lookup table is
1704 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1705 * header. This operation is potentially unsafe if the program is abruptly
1706 * terminated while the XML data or integrity table are being overwritten, but
1707 * before the new header has been written. To partially alleviate this problem,
1708 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1709 * finish_write() to cause a temporary WIM header to be written after the XML
1710 * data has been written. This may prevent the WIM from becoming corrupted if
1711 * the program is terminated while the integrity table is being calculated (but
1712 * no guarantees, due to write re-ordering...).
1714 * If we are adding new streams or images (metadata resources), the lookup table
1715 * needs to be changed, and those streams need to be written. In this case, we
1716 * try to perform a safe update of the WIM file by writing the streams *after*
1717 * the end of the previous WIM, then writing the new lookup table, XML data, and
1718 * (optionally) integrity table following the new streams. This will produce a
1719 * layout like the following:
1721 * Header (212 bytes)
1722 * (OLD) Streams and metadata resources (variable size)
1723 * (OLD) Lookup table (variable size)
1724 * (OLD) XML data (variable size)
1725 * (OLD) Integrity table (optional) (variable size)
1726 * (NEW) Streams and metadata resources (variable size)
1727 * (NEW) Lookup table (variable size)
1728 * (NEW) XML data (variable size)
1729 * (NEW) Integrity table (optional) (variable size)
1731 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1732 * the header is overwritten to point to the new lookup table, XML data, and
1733 * integrity table, to produce the following layout:
1735 * Header (212 bytes)
1736 * Streams and metadata resources (variable size)
1737 * Nothing (variable size)
1738 * More Streams and metadata resources (variable size)
1739 * Lookup table (variable size)
1740 * XML data (variable size)
1741 * Integrity table (optional) (variable size)
1743 * This method allows an image to be appended to a large WIM very quickly, and
1744 * is is crash-safe except in the case of write re-ordering, but the
1745 * disadvantage is that a small hole is left in the WIM where the old lookup
1746 * table, xml data, and integrity table were. (These usually only take up a
1747 * small amount of space compared to the streams, however.)
1749 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1750 unsigned num_threads,
1751 wimlib_progress_func_t progress_func,
1752 int modified_image_idx)
1755 struct list_head stream_list;
1758 DEBUG("Overwriting `%s' in-place", w->filename);
1760 /* Make sure that the integrity table (if present) is after the XML
1761 * data, and that there are no stream resources, metadata resources, or
1762 * lookup tables after the XML data. Otherwise, these data would be
1764 if (w->hdr.integrity.offset != 0 &&
1765 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1766 ERROR("Didn't expect the integrity table to be before the XML data");
1767 return WIMLIB_ERR_RESOURCE_ORDER;
1770 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1771 ERROR("Didn't expect the lookup table to be after the XML data");
1772 return WIMLIB_ERR_RESOURCE_ORDER;
1775 DEBUG("Identifying newly added streams");
1776 for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1777 INIT_LIST_HEAD(&stream_list);
1778 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1779 DEBUG("Identifiying streams in image %d", i + 1);
1780 w->private = &stream_list;
1781 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1782 dentry_find_streams_to_write, w);
1785 if (w->hdr.integrity.offset)
1786 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1788 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1790 ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1795 if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1796 /* If no images have been modified and no images have been
1797 * deleted, a new lookup table does not need to be written. */
1798 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1799 w->hdr.lookup_table_res_entry.size;
1800 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1801 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1804 INIT_LIST_HEAD(&stream_list);
1805 for_lookup_table_entry(w->lookup_table, find_new_streams,
1808 ret = open_wim_writable(w, w->filename, false,
1809 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1813 ret = lock_wim(w->out_fp, w->filename);
1820 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1821 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1824 return WIMLIB_ERR_WRITE;
1827 if (!list_empty(&stream_list)) {
1828 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1830 ret = write_stream_list(&stream_list, w->out_fp,
1831 wimlib_get_compression_type(w),
1832 write_flags, num_threads,
1837 DEBUG("No new streams were added");
1840 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1841 select_wim_image(w, i + 1);
1842 ret = write_metadata_resource(w);
1846 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1847 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1850 close_wim_writable(w);
1851 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1852 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1853 w->filename, old_wim_end);
1854 truncate(w->filename, old_wim_end);
1859 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1860 unsigned num_threads,
1861 wimlib_progress_func_t progress_func)
1863 size_t wim_name_len;
1866 DEBUG("Overwriting `%s' via a temporary file", w->filename);
1868 /* Write the WIM to a temporary file in the same directory as the
1870 wim_name_len = strlen(w->filename);
1871 char tmpfile[wim_name_len + 10];
1872 memcpy(tmpfile, w->filename, wim_name_len);
1873 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1874 tmpfile[wim_name_len + 9] = '\0';
1876 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1877 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1878 num_threads, progress_func);
1880 ERROR("Failed to write the WIM file `%s'", tmpfile);
1884 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1886 /* Rename the new file to the old file .*/
1887 if (rename(tmpfile, w->filename) != 0) {
1888 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1889 tmpfile, w->filename);
1890 ret = WIMLIB_ERR_RENAME;
1894 if (progress_func) {
1895 union wimlib_progress_info progress;
1896 progress.rename.from = tmpfile;
1897 progress.rename.to = w->filename;
1898 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1901 /* Close the original WIM file that was opened for reading. */
1902 if (w->fp != NULL) {
1907 /* Re-open the WIM read-only. */
1908 w->fp = fopen(w->filename, "rb");
1909 if (w->fp == NULL) {
1910 ret = WIMLIB_ERR_REOPEN;
1911 WARNING("Failed to re-open `%s' read-only: %s",
1912 w->filename, strerror(errno));
1918 /* Remove temporary file. */
1919 if (unlink(tmpfile) != 0)
1920 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1925 * Writes a WIM file to the original file that it was read from, overwriting it.
1927 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1928 unsigned num_threads,
1929 wimlib_progress_func_t progress_func)
1931 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1934 return WIMLIB_ERR_NO_FILENAME;
1936 if (w->hdr.total_parts != 1) {
1937 ERROR("Cannot modify a split WIM");
1938 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1941 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1942 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1945 int modified_image_idx;
1948 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1950 modified_image_idx = i;
1951 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1952 !w->image_metadata[i].has_been_mounted_rw; i++)
1954 if (i == w->hdr.image_count) {
1955 ret = overwrite_wim_inplace(w, write_flags, num_threads,
1957 modified_image_idx);
1958 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
1959 WARNING("Falling back to re-building entire WIM");
1964 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,