4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2010 Carl Thijssen
10 * Copyright (C) 2012 Eric Biggers
12 * This file is part of wimlib, a library for working with WIM files.
14 * wimlib is free software; you can redistribute it and/or modify it under the
15 * terms of the GNU General Public License as published by the Free
16 * Software Foundation; either version 3 of the License, or (at your option)
19 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21 * A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with wimlib; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib_internal.h"
31 #include "lookup_table.h"
37 #ifdef ENABLE_MULTITHREADED_COMPRESSION
38 #include <semaphore.h>
45 #include <ntfs-3g/attrib.h>
46 #include <ntfs-3g/inode.h>
47 #include <ntfs-3g/dir.h>
57 static int do_fflush(FILE *fp)
61 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
62 return WIMLIB_ERR_WRITE;
67 static int fflush_and_ftruncate(FILE *fp, off_t size)
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 == WIM_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 tale 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 * Writes a WIM resource to a FILE * opened for writing. The resource may be
328 * written uncompressed or compressed depending on the @out_ctype parameter.
330 * If by chance the resource compresses to more than the original size (this may
331 * happen with random data or files than are pre-compressed), the resource is
332 * instead written uncompressed (and this is reflected in the @out_res_entry by
333 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
335 * @lte: The lookup table entry for the WIM resource.
336 * @out_fp: The FILE * to write the resource to.
337 * @out_ctype: The compression type of the resource to write. Note: if this is
338 * the same as the compression type of the WIM resource we
339 * need to read, we simply copy the data (i.e. we do not
340 * uncompress it, then compress it again).
341 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
342 * offset, original size, compressed size, and compression flag
343 * of the output resource.
345 * Returns 0 on success; nonzero on failure.
347 int write_wim_resource(struct lookup_table_entry *lte,
348 FILE *out_fp, int out_ctype,
349 struct resource_entry *out_res_entry,
354 u64 old_compressed_size;
355 u64 new_compressed_size;
358 struct chunk_table *chunk_tab = NULL;
361 compress_func_t compress;
363 ntfs_inode *ni = NULL;
368 /* Original size of the resource */
369 original_size = wim_resource_size(lte);
371 /* Compressed size of the resource (as it exists now) */
372 old_compressed_size = wim_resource_compressed_size(lte);
374 /* Current offset in output file */
375 file_offset = ftello(out_fp);
376 if (file_offset == -1) {
377 ERROR_WITH_ERRNO("Failed to get offset in output "
379 return WIMLIB_ERR_WRITE;
382 /* Are the compression types the same? If so, do a raw copy (copy
383 * without decompressing and recompressing the data). */
384 raw = (wim_resource_compression_type(lte) == out_ctype
385 && out_ctype != WIM_COMPRESSION_TYPE_NONE
386 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
389 flags |= WIMLIB_RESOURCE_FLAG_RAW;
390 bytes_remaining = old_compressed_size;
392 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
393 bytes_remaining = original_size;
396 /* Empty resource; nothing needs to be done, so just return success. */
397 if (bytes_remaining == 0)
400 /* Buffer for reading chunks for the resource */
401 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
403 /* If we are writing a compressed resource and not doing a raw copy, we
404 * need to initialize the chunk table */
405 if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
406 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
412 /* If the WIM resource is in an external file, open a FILE * to it so we
413 * don't have to open a temporary one in read_wim_resource() for each
416 ret = prepare_resource_for_read(lte, &ni);
418 ret = prepare_resource_for_read(lte);
423 /* If we aren't doing a raw copy, we will compute the SHA1 message
424 * digest of the resource as we read it, and verify it's the same as the
425 * hash given in the lookup table entry once we've finished reading the
430 compress = get_compress_func(out_ctype);
434 /* While there are still bytes remaining in the WIM resource, read a
435 * chunk of the resource, update SHA1, then write that chunk using the
436 * desired compression type. */
438 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
439 ret = read_wim_resource(lte, buf, to_read, offset, flags);
443 sha1_update(&ctx, buf, to_read);
444 ret = write_wim_resource_chunk(buf, to_read, out_fp,
445 compress, chunk_tab);
448 bytes_remaining -= to_read;
450 } while (bytes_remaining);
452 /* Raw copy: The new compressed size is the same as the old compressed
455 * Using WIM_COMPRESSION_TYPE_NONE: The new compressed size is the
458 * Using a different compression type: Call
459 * finish_wim_resource_chunk_tab() and it will provide the new
463 new_compressed_size = old_compressed_size;
465 if (out_ctype == WIM_COMPRESSION_TYPE_NONE)
466 new_compressed_size = original_size;
468 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
469 &new_compressed_size);
475 /* Verify SHA1 message digest of the resource, unless we are doing a raw
476 * write (in which case we never even saw the uncompressed data). Or,
477 * if the hash we had before is all 0's, just re-set it to be the new
480 u8 md[SHA1_HASH_SIZE];
481 sha1_final(md, &ctx);
482 if (is_zero_hash(lte->hash)) {
483 copy_hash(lte->hash, md);
484 } else if (!hashes_equal(md, lte->hash)) {
485 ERROR("WIM resource has incorrect hash!");
486 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
487 ERROR("We were reading it from `%s'; maybe it changed "
488 "while we were reading it.",
491 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
496 if (!raw && new_compressed_size >= original_size &&
497 out_ctype != WIM_COMPRESSION_TYPE_NONE)
499 /* Oops! We compressed the resource to larger than the original
500 * size. Write the resource uncompressed instead. */
501 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
502 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
503 "of output WIM file", file_offset);
504 ret = WIMLIB_ERR_WRITE;
507 ret = write_wim_resource(lte, out_fp, WIM_COMPRESSION_TYPE_NONE,
508 out_res_entry, flags);
512 ret = fflush_and_ftruncate(out_fp, file_offset + out_res_entry->size);
517 out_res_entry->size = new_compressed_size;
518 out_res_entry->original_size = original_size;
519 out_res_entry->offset = file_offset;
520 out_res_entry->flags = lte->resource_entry.flags
521 & ~WIM_RESHDR_FLAG_COMPRESSED;
522 if (out_ctype != WIM_COMPRESSION_TYPE_NONE)
523 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
529 end_wim_resource_read(lte, ni);
531 end_wim_resource_read(lte);
538 #ifdef ENABLE_MULTITHREADED_COMPRESSION
539 struct shared_queue {
542 pthread_mutex_t lock;
549 static int shared_queue_init(struct shared_queue *q, unsigned size)
551 q->array = CALLOC(sizeof(q->array[0]), size);
553 return WIMLIB_ERR_NOMEM;
555 sem_init(&q->filled_slots, 0, 0);
556 sem_init(&q->empty_slots, 0, size);
557 pthread_mutex_init(&q->lock, NULL);
564 static void shared_queue_destroy(struct shared_queue *q)
566 sem_destroy(&q->filled_slots);
567 sem_destroy(&q->empty_slots);
568 pthread_mutex_destroy(&q->lock);
572 static void shared_queue_put(struct shared_queue *q, void *obj)
574 sem_wait(&q->empty_slots);
575 pthread_mutex_lock(&q->lock);
577 q->back = (q->back + 1) % q->size;
578 q->array[q->back] = obj;
580 sem_post(&q->filled_slots);
581 pthread_mutex_unlock(&q->lock);
584 static void *shared_queue_get(struct shared_queue *q)
586 sem_wait(&q->filled_slots);
587 pthread_mutex_lock(&q->lock);
589 void *obj = q->array[q->front];
590 q->array[q->front] = NULL;
591 q->front = (q->front + 1) % q->size;
593 sem_post(&q->empty_slots);
594 pthread_mutex_unlock(&q->lock);
598 struct compressor_thread_params {
599 struct shared_queue *res_to_compress_queue;
600 struct shared_queue *compressed_res_queue;
601 compress_func_t compress;
604 #define MAX_CHUNKS_PER_MSG 2
607 struct lookup_table_entry *lte;
608 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
609 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
610 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
611 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
612 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
614 struct list_head list;
619 static void compress_chunks(struct message *msg, compress_func_t compress)
621 for (unsigned i = 0; i < msg->num_chunks; i++) {
622 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
623 int ret = compress(msg->uncompressed_chunks[i],
624 msg->uncompressed_chunk_sizes[i],
625 msg->compressed_chunks[i],
626 &msg->compressed_chunk_sizes[i]);
628 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
630 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
631 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
636 static void *compressor_thread_proc(void *arg)
638 struct compressor_thread_params *params = arg;
639 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
640 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
641 compress_func_t compress = params->compress;
644 DEBUG("Compressor thread ready");
645 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
646 compress_chunks(msg, compress);
647 shared_queue_put(compressed_res_queue, msg);
649 DEBUG("Compressor thread terminating");
653 void show_stream_op_progress(u64 *cur_size, u64 *next_size,
654 u64 total_size, u64 one_percent,
655 unsigned *cur_percent,
656 const struct lookup_table_entry *cur_lte,
659 if (*cur_size >= *next_size) {
660 printf("\r%"PRIu64" MiB of %"PRIu64" MiB "
661 "(uncompressed) %s (%u%% done)",
663 total_size >> 20, op, *cur_percent);
665 *next_size += one_percent;
668 *cur_size += wim_resource_size(cur_lte);
671 void finish_stream_op_progress(u64 total_size, const char *op)
673 printf("\r%"PRIu64" MiB of %"PRIu64" MiB "
674 "(uncompressed) %s (100%% done)\n",
675 total_size >> 20, total_size >> 20, op);
679 static int write_stream_list_serial(struct list_head *stream_list,
680 FILE *out_fp, int out_ctype,
681 int write_flags, u64 total_size)
683 struct lookup_table_entry *lte;
686 u64 one_percent = total_size / 100;
689 unsigned cur_percent = 0;
690 int write_resource_flags = 0;
692 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
693 write_resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
695 list_for_each_entry(lte, stream_list, staging_list) {
696 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
697 show_stream_op_progress(&cur_size, &next_size,
698 total_size, one_percent,
699 &cur_percent, lte, "written");
701 ret = write_wim_resource(lte, out_fp, out_ctype,
702 <e->output_resource_entry,
703 write_resource_flags);
707 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
708 finish_stream_op_progress(total_size, "written");
712 #ifdef ENABLE_MULTITHREADED_COMPRESSION
713 static int write_wim_chunks(struct message *msg, FILE *out_fp,
714 struct chunk_table *chunk_tab)
716 for (unsigned i = 0; i < msg->num_chunks; i++) {
717 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
719 DEBUG2("Write wim chunk %u of %u (csize = %u)",
720 i, msg->num_chunks, chunk_csize);
722 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
725 ERROR_WITH_ERRNO("Failed to write WIM chunk");
726 return WIMLIB_ERR_WRITE;
729 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
730 chunk_tab->cur_offset += chunk_csize;
736 * This function is executed by the main thread when the resources are being
737 * compressed in parallel. The main thread is in change of all reading of the
738 * uncompressed data and writing of the compressed data. The compressor threads
739 * *only* do compression from/to in-memory buffers.
741 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
742 * chunks of compressed data to compress, represented in a `struct message'.
743 * Each message is passed from the main thread to a worker thread through the
744 * res_to_compress_queue, and it is passed back through the
745 * compressed_res_queue.
747 static int main_writer_thread_proc(struct list_head *stream_list,
750 struct shared_queue *res_to_compress_queue,
751 struct shared_queue *compressed_res_queue,
758 struct message msgs[queue_size];
761 // Initially, all the messages are available to use.
762 LIST_HEAD(available_msgs);
763 for (size_t i = 0; i < ARRAY_LEN(msgs); i++)
764 list_add(&msgs[i].list, &available_msgs);
766 // outstanding_resources is the list of resources that currently have
767 // had chunks sent off for compression.
769 // The first stream in outstanding_resources is the stream that is
770 // currently being written (cur_lte).
772 // The last stream in outstanding_resources is the stream that is
773 // currently being read and chunks fed to the compressor threads
776 // Depending on the number of threads and the sizes of the resource,
777 // the outstanding streams list may contain streams between cur_lte and
778 // next_lte that have all their chunks compressed or being compressed,
779 // but haven't been written yet.
781 LIST_HEAD(outstanding_resources);
782 struct list_head *next_resource = stream_list->next;
783 struct lookup_table_entry *next_lte = container_of(next_resource,
784 struct lookup_table_entry,
786 next_resource = next_resource->next;
788 u64 next_num_chunks = wim_resource_chunks(next_lte);
789 INIT_LIST_HEAD(&next_lte->msg_list);
790 list_add_tail(&next_lte->staging_list, &outstanding_resources);
792 // As in write_wim_resource(), each resource we read is checksummed.
793 SHA_CTX next_sha_ctx;
794 sha1_init(&next_sha_ctx);
795 u8 next_hash[SHA1_HASH_SIZE];
797 // Resources that don't need any chunks compressed are added to this
798 // list and written directly by the main thread.
799 LIST_HEAD(my_resources);
801 struct lookup_table_entry *cur_lte = next_lte;
802 struct chunk_table *cur_chunk_tab = NULL;
803 struct lookup_table_entry *lte;
806 u64 one_percent = total_size / 100;
809 unsigned cur_percent = 0;
812 ntfs_inode *ni = NULL;
816 ret = prepare_resource_for_read(next_lte, &ni);
818 ret = prepare_resource_for_read(next_lte);
823 DEBUG("Initializing buffers for uncompressed "
824 "and compressed data (%zu bytes needed)",
825 queue_size * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
827 // Pre-allocate all the buffers that will be needed to do the chunk
829 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
830 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
831 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
832 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
833 if (msgs[i].compressed_chunks[j] == NULL ||
834 msgs[i].uncompressed_chunks[j] == NULL)
836 ERROR("Could not allocate enough memory for "
837 "multi-threaded compression");
838 ret = WIMLIB_ERR_NOMEM;
844 // This loop is executed until all resources have been written, except
845 // possibly a few that have been added to the @my_resources list for
848 // Send chunks to the compressor threads until either (a) there
849 // are no more messages available since they were all sent off,
850 // or (b) there are no more resources that need to be
852 while (!list_empty(&available_msgs) && next_lte != NULL) {
854 // Get a message from the available messages
856 msg = container_of(available_msgs.next,
860 // ... and delete it from the available messages
862 list_del(&msg->list);
864 // Initialize the message with the chunks to
866 msg->num_chunks = min(next_num_chunks - next_chunk,
869 msg->complete = false;
870 msg->begin_chunk = next_chunk;
872 unsigned size = WIM_CHUNK_SIZE;
873 for (unsigned i = 0; i < msg->num_chunks; i++) {
875 // Read chunk @next_chunk of the stream into the
876 // message so that a compressor thread can
879 if (next_chunk == next_num_chunks - 1 &&
880 wim_resource_size(next_lte) % WIM_CHUNK_SIZE != 0)
882 size = wim_resource_size(next_lte) % WIM_CHUNK_SIZE;
886 DEBUG2("Read resource (size=%u, offset=%zu)",
887 size, next_chunk * WIM_CHUNK_SIZE);
889 msg->uncompressed_chunk_sizes[i] = size;
891 ret = read_wim_resource(next_lte,
892 msg->uncompressed_chunks[i],
894 next_chunk * WIM_CHUNK_SIZE,
898 sha1_update(&next_sha_ctx,
899 msg->uncompressed_chunks[i], size);
903 // Send the compression request
904 list_add_tail(&msg->list, &next_lte->msg_list);
905 shared_queue_put(res_to_compress_queue, msg);
906 DEBUG2("Compression request sent");
908 if (next_chunk != next_num_chunks)
909 // More chunks to send for this resource
912 // Done sending compression requests for a resource!
913 // Check the SHA1 message digest.
914 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)", next_num_chunks);
915 sha1_final(next_hash, &next_sha_ctx);
916 if (!hashes_equal(next_lte->hash, next_hash)) {
917 ERROR("WIM resource has incorrect hash!");
918 if (next_lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
919 ERROR("We were reading it from `%s'; maybe it changed "
920 "while we were reading it.",
921 next_lte->file_on_disk);
923 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
927 // Advance to the next resource.
929 // If the next resource needs no compression, just write
930 // it with this thread (not now though--- we could be in
931 // the middle of writing another resource.) Keep doing
932 // this until we either get to the end of the resources
933 // list, or we get to a resource that needs compression.
936 if (next_resource == stream_list) {
941 end_wim_resource_read(next_lte, ni);
944 end_wim_resource_read(next_lte);
947 next_lte = container_of(next_resource,
948 struct lookup_table_entry,
950 next_resource = next_resource->next;
951 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
952 && next_lte->resource_location == RESOURCE_IN_WIM
953 && wimlib_get_compression_type(next_lte->wim) == out_ctype)
954 || wim_resource_size(next_lte) == 0)
956 list_add_tail(&next_lte->staging_list,
959 list_add_tail(&next_lte->staging_list,
960 &outstanding_resources);
962 next_num_chunks = wim_resource_chunks(next_lte);
963 sha1_init(&next_sha_ctx);
964 INIT_LIST_HEAD(&next_lte->msg_list);
966 ret = prepare_resource_for_read(next_lte, &ni);
968 ret = prepare_resource_for_read(next_lte);
972 DEBUG2("Updated next_lte");
978 // If there are no outstanding resources, there are no more
979 // resources that need to be written.
980 if (list_empty(&outstanding_resources)) {
981 DEBUG("No outstanding resources! Done");
986 // Get the next message from the queue and process it.
987 // The message will contain 1 or more data chunks that have been
989 DEBUG2("Waiting for message");
990 msg = shared_queue_get(compressed_res_queue);
991 msg->complete = true;
993 DEBUG2("Received msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
995 list_for_each_entry(msg, &cur_lte->msg_list, list) {
996 DEBUG2("complete=%d", msg->complete);
999 // Is this the next chunk in the current resource? If it's not
1000 // (i.e., an earlier chunk in a same or different resource
1001 // hasn't been compressed yet), do nothing, and keep this
1002 // message around until all earlier chunks are received.
1004 // Otherwise, write all the chunks we can.
1005 while (!list_empty(&cur_lte->msg_list)
1006 && (msg = container_of(cur_lte->msg_list.next,
1010 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1011 if (msg->begin_chunk == 0) {
1012 DEBUG2("Begin chunk tab");
1013 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1014 show_stream_op_progress(&cur_size,
1023 // This is the first set of chunks. Leave space
1024 // for the chunk table in the output file.
1025 off_t cur_offset = ftello(out_fp);
1026 if (cur_offset == -1) {
1027 ret = WIMLIB_ERR_WRITE;
1030 ret = begin_wim_resource_chunk_tab(cur_lte,
1038 // Write the compressed chunks from the message.
1039 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1043 list_del(&msg->list);
1045 // This message is available to use for different chunks
1047 list_add(&msg->list, &available_msgs);
1049 // Was this the last chunk of the stream? If so,
1051 if (list_empty(&cur_lte->msg_list) &&
1052 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1054 DEBUG2("Finish wim chunk tab");
1056 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1063 cur_lte->output_resource_entry.size =
1066 cur_lte->output_resource_entry.original_size =
1067 cur_lte->resource_entry.original_size;
1069 cur_lte->output_resource_entry.offset =
1070 cur_chunk_tab->file_offset;
1072 cur_lte->output_resource_entry.flags =
1073 cur_lte->resource_entry.flags |
1074 WIM_RESHDR_FLAG_COMPRESSED;
1076 FREE(cur_chunk_tab);
1077 cur_chunk_tab = NULL;
1079 struct list_head *next = cur_lte->staging_list.next;
1080 list_del(&cur_lte->staging_list);
1082 if (next == &outstanding_resources) {
1083 DEBUG("No more outstanding resources");
1087 cur_lte = container_of(cur_lte->staging_list.next,
1088 struct lookup_table_entry,
1092 // Since we just finished writing a stream,
1093 // write any streams that have been added to the
1094 // my_resources list for direct writing by the
1095 // main thread (e.g. resources that don't need
1096 // to be compressed because the desired
1097 // compression type is the same as the previous
1098 // compression type).
1099 struct lookup_table_entry *tmp;
1100 list_for_each_entry_safe(lte,
1105 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1106 show_stream_op_progress(&cur_size,
1115 ret = write_wim_resource(lte,
1118 <e->output_resource_entry,
1120 list_del(<e->staging_list);
1130 end_wim_resource_read(cur_lte, ni);
1132 end_wim_resource_read(cur_lte);
1135 list_for_each_entry(lte, &my_resources, staging_list) {
1136 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1137 show_stream_op_progress(&cur_size,
1145 ret = write_wim_resource(lte, out_fp,
1147 <e->output_resource_entry,
1152 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
1153 finish_stream_op_progress(total_size, "written");
1155 size_t num_available_msgs = 0;
1156 struct list_head *cur;
1158 list_for_each(cur, &available_msgs) {
1159 num_available_msgs++;
1162 while (num_available_msgs < ARRAY_LEN(msgs)) {
1163 shared_queue_get(compressed_res_queue);
1164 num_available_msgs++;
1168 DEBUG("Freeing messages");
1170 for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
1171 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1172 FREE(msgs[i].compressed_chunks[j]);
1173 FREE(msgs[i].uncompressed_chunks[j]);
1177 if (cur_chunk_tab != NULL)
1178 FREE(cur_chunk_tab);
1183 static const char *get_data_type(int ctype)
1186 case WIM_COMPRESSION_TYPE_NONE:
1187 return "uncompressed";
1188 case WIM_COMPRESSION_TYPE_LZX:
1189 return "LZX-compressed";
1190 case WIM_COMPRESSION_TYPE_XPRESS:
1191 return "XPRESS-compressed";
1195 static int write_stream_list_parallel(struct list_head *stream_list,
1196 FILE *out_fp, int out_ctype,
1197 int write_flags, u64 total_size,
1198 unsigned num_threads)
1201 struct shared_queue res_to_compress_queue;
1202 struct shared_queue compressed_res_queue;
1203 pthread_t *compressor_threads = NULL;
1205 if (num_threads == 0) {
1206 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1208 WARNING("Could not determine number of processors! Assuming 1");
1211 num_threads = nthreads;
1215 wimlib_assert(stream_list->next != stream_list);
1217 static const double MESSAGES_PER_THREAD = 2.0;
1218 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1220 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1222 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1226 ret = shared_queue_init(&compressed_res_queue, queue_size);
1228 goto out_destroy_res_to_compress_queue;
1230 struct compressor_thread_params params;
1231 params.res_to_compress_queue = &res_to_compress_queue;
1232 params.compressed_res_queue = &compressed_res_queue;
1233 params.compress = get_compress_func(out_ctype);
1235 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1237 for (unsigned i = 0; i < num_threads; i++) {
1238 DEBUG("pthread_create thread %u", i);
1239 ret = pthread_create(&compressor_threads[i], NULL,
1240 compressor_thread_proc, ¶ms);
1243 ERROR_WITH_ERRNO("Failed to create compressor "
1250 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1251 printf("Writing %s data using %u threads...\n",
1252 get_data_type(out_ctype), num_threads);
1255 ret = main_writer_thread_proc(stream_list,
1258 &res_to_compress_queue,
1259 &compressed_res_queue,
1265 for (unsigned i = 0; i < num_threads; i++)
1266 shared_queue_put(&res_to_compress_queue, NULL);
1268 for (unsigned i = 0; i < num_threads; i++) {
1269 if (pthread_join(compressor_threads[i], NULL)) {
1270 WARNING("Failed to join compressor thread %u: %s",
1271 i, strerror(errno));
1274 FREE(compressor_threads);
1275 shared_queue_destroy(&compressed_res_queue);
1276 out_destroy_res_to_compress_queue:
1277 shared_queue_destroy(&res_to_compress_queue);
1278 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1281 WARNING("Falling back to single-threaded compression");
1282 return write_stream_list_serial(stream_list, out_fp,
1283 out_ctype, write_flags, total_size);
1288 * Write a list of streams to a WIM (@out_fp) using the compression type
1289 * @out_ctype and up to @num_threads compressor threads.
1291 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1292 int out_ctype, int write_flags,
1293 unsigned num_threads)
1295 struct lookup_table_entry *lte;
1296 size_t num_streams = 0;
1298 bool compression_needed = false;
1300 list_for_each_entry(lte, stream_list, staging_list) {
1302 total_size += wim_resource_size(lte);
1303 if (!compression_needed
1305 (out_ctype != WIM_COMPRESSION_TYPE_NONE
1306 && (lte->resource_location != RESOURCE_IN_WIM
1307 || wimlib_get_compression_type(lte->wim) != out_ctype
1308 || (write_flags & WIMLIB_WRITE_FLAG_REBUILD)))
1309 && wim_resource_size(lte) != 0)
1310 compression_needed = true;
1313 if (num_streams == 0) {
1314 if (write_flags & WIMLIB_WRITE_FLAG_VERBOSE)
1315 printf("No streams to write\n");
1319 if (write_flags & WIMLIB_WRITE_FLAG_VERBOSE) {
1320 printf("Preparing to write %zu streams "
1321 "(%"PRIu64" total bytes uncompressed)\n",
1322 num_streams, total_size);
1323 printf("Using compression type %s\n",
1324 wimlib_get_compression_type_string(out_ctype));
1327 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1328 if (compression_needed && total_size >= 1000000 && num_threads != 1) {
1329 return write_stream_list_parallel(stream_list, out_fp,
1330 out_ctype, write_flags,
1331 total_size, num_threads);
1336 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1337 const char *reason = "";
1338 if (!compression_needed)
1339 reason = " (no compression needed)";
1340 printf("Writing %s data using 1 thread%s\n",
1341 get_data_type(out_ctype), reason);
1344 return write_stream_list_serial(stream_list, out_fp,
1345 out_ctype, write_flags,
1351 static int dentry_find_streams_to_write(struct dentry *dentry,
1355 struct list_head *stream_list = w->private;
1356 struct lookup_table_entry *lte;
1357 for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1358 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1359 if (lte && ++lte->out_refcnt == 1)
1360 list_add_tail(<e->staging_list, stream_list);
1365 static int find_streams_to_write(WIMStruct *w)
1367 return for_dentry_in_tree(wim_root_dentry(w),
1368 dentry_find_streams_to_write, w);
1371 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1372 unsigned num_threads)
1375 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1376 LIST_HEAD(stream_list);
1377 w->private = &stream_list;
1378 for_image(w, image, find_streams_to_write);
1379 return write_stream_list(&stream_list, w->out_fp,
1380 wimlib_get_compression_type(w), write_flags,
1385 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1386 * table (optional), then overwrite the WIM header.
1388 * write_flags is a bitwise OR of the following:
1390 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1391 * Include an integrity table.
1393 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1394 * Show progress information when (if) writing the integrity table.
1396 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1397 * Don't write the lookup table.
1399 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1400 * When (if) writing the integrity table, re-use entries from the
1401 * existing integrity table, if possible.
1403 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1404 * After writing the XML data but before writing the integrity
1405 * table, write a temporary WIM header and flush the stream so that
1406 * the WIM is less likely to become corrupted upon abrupt program
1409 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1410 * fsync() the output file before closing it.
1413 int finish_write(WIMStruct *w, int image, int write_flags)
1416 struct wim_header hdr;
1417 FILE *out = w->out_fp;
1419 /* @hdr will be the header for the new WIM. First copy all the data
1420 * from the header in the WIMStruct; then set all the fields that may
1421 * have changed, including the resource entries, boot index, and image
1423 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1425 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1426 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1431 ret = write_xml_data(w->wim_info, image, out,
1432 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1433 wim_info_get_total_bytes(w->wim_info) : 0,
1434 &hdr.xml_res_entry);
1438 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1439 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1440 struct wim_header checkpoint_hdr;
1441 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1442 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1443 if (fseeko(out, 0, SEEK_SET) != 0) {
1444 ret = WIMLIB_ERR_WRITE;
1447 ret = write_header(&checkpoint_hdr, out);
1451 if (fflush(out) != 0) {
1452 ERROR_WITH_ERRNO("Can't write data to WIM");
1453 ret = WIMLIB_ERR_WRITE;
1457 if (fseeko(out, 0, SEEK_END) != 0) {
1458 ret = WIMLIB_ERR_WRITE;
1463 off_t old_lookup_table_end;
1464 off_t new_lookup_table_end;
1466 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1467 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1468 w->hdr.lookup_table_res_entry.size;
1470 old_lookup_table_end = 0;
1472 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1473 hdr.lookup_table_res_entry.size;
1474 show_progress = ((write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) != 0);
1476 ret = write_integrity_table(out,
1478 new_lookup_table_end,
1479 old_lookup_table_end,
1484 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1488 * In the WIM header, there is room for the resource entry for a
1489 * metadata resource labeled as the "boot metadata". This entry should
1490 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1491 * it should be a copy of the resource entry for the image that is
1492 * marked as bootable. This is not well documented...
1494 if (hdr.boot_idx == 0 || !w->image_metadata
1495 || (image != WIM_ALL_IMAGES && image != hdr.boot_idx)) {
1496 memset(&hdr.boot_metadata_res_entry, 0,
1497 sizeof(struct resource_entry));
1499 memcpy(&hdr.boot_metadata_res_entry,
1501 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1502 sizeof(struct resource_entry));
1505 /* Set image count and boot index correctly for single image writes */
1506 if (image != WIM_ALL_IMAGES) {
1507 hdr.image_count = 1;
1508 if (hdr.boot_idx == image)
1514 if (fseeko(out, 0, SEEK_SET) != 0) {
1515 ret = WIMLIB_ERR_WRITE;
1519 ret = write_header(&hdr, out);
1523 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1524 if (fflush(out) != 0
1525 || fsync(fileno(out)) != 0)
1527 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1528 ret = WIMLIB_ERR_WRITE;
1532 if (fclose(out) != 0) {
1533 ERROR_WITH_ERRNO("Failed to close the WIM file");
1535 ret = WIMLIB_ERR_WRITE;
1541 static void close_wim_writable(WIMStruct *w)
1544 if (fclose(w->out_fp) != 0) {
1545 WARNING("Failed to close output WIM: %s",
1552 /* Open file stream and write dummy header for WIM. */
1553 int begin_write(WIMStruct *w, const char *path, int write_flags)
1556 bool need_readable = false;
1558 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1559 need_readable = true;
1561 ret = open_wim_writable(w, path, trunc, need_readable);
1564 /* Write dummy header. It will be overwritten later. */
1565 return write_header(&w->hdr, w->out_fp);
1568 /* Writes a stand-alone WIM to a file. */
1569 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1570 int image, int write_flags, unsigned num_threads)
1575 return WIMLIB_ERR_INVALID_PARAM;
1577 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1579 if (image != WIM_ALL_IMAGES &&
1580 (image < 1 || image > w->hdr.image_count))
1581 return WIMLIB_ERR_INVALID_IMAGE;
1583 if (w->hdr.total_parts != 1) {
1584 ERROR("Cannot call wimlib_write() on part of a split WIM");
1585 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1588 if (image == WIM_ALL_IMAGES)
1589 DEBUG("Writing all images to `%s'.", path);
1591 DEBUG("Writing image %d to `%s'.", image, path);
1593 ret = begin_write(w, path, write_flags);
1597 ret = write_wim_streams(w, image, write_flags, num_threads);
1601 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
1602 printf("Writing image metadata...\n");
1604 ret = for_image(w, image, write_metadata_resource);
1608 ret = finish_write(w, image, write_flags);
1609 if (ret == 0 && (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS))
1610 printf("Successfully wrote `%s'\n", path);
1612 close_wim_writable(w);
1616 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1619 memcpy(<e->output_resource_entry, <e->resource_entry,
1620 sizeof(struct resource_entry));
1621 lte->out_refcnt = 0;
1625 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1627 off_t end_offset = *(u64*)arg;
1629 wimlib_assert(lte->out_refcnt <= lte->refcnt);
1630 if (lte->out_refcnt < lte->refcnt) {
1631 if (lte->resource_entry.offset + lte->resource_entry.size > end_offset) {
1632 ERROR("The following resource is after the XML data:");
1633 print_lookup_table_entry(lte);
1634 return WIMLIB_ERR_RESOURCE_ORDER;
1640 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1642 if (lte->out_refcnt == lte->refcnt)
1643 list_add(<e->staging_list, (struct list_head*)arg);
1645 lte->out_refcnt = lte->refcnt;
1650 * Overwrite a WIM, possibly appending streams to it.
1652 * A WIM looks like (or is supposed to look like) the following:
1654 * Header (212 bytes)
1655 * Streams and metadata resources (variable size)
1656 * Lookup table (variable size)
1657 * XML data (variable size)
1658 * Integrity table (optional) (variable size)
1660 * If we are not adding any streams or metadata resources, the lookup table is
1661 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1662 * header. This operation is potentially unsafe if the program is abruptly
1663 * terminated while the XML data or integrity table are being overwritten, but
1664 * before the new header has been written. To partially alleviate this problem,
1665 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1666 * finish_write() to cause a temporary WIM header to be written after the XML
1667 * data has been written. This may prevent the WIM from becoming corrupted if
1668 * the program is terminated while the integrity table is being calculated (but
1669 * no guarantees, due to write re-ordering...).
1671 * If we are adding new streams or images (metadata resources), the lookup table
1672 * needs to be changed, and those streams need to be written. In this case, we
1673 * try to perform a safe update of the WIM file by writing the streams *after*
1674 * the end of the previous WIM, then writing the new lookup table, XML data, and
1675 * (optionally) integrity table following the new streams. This will produce a
1676 * layout like the following:
1678 * Header (212 bytes)
1679 * (OLD) Streams and metadata resources (variable size)
1680 * (OLD) Lookup table (variable size)
1681 * (OLD) XML data (variable size)
1682 * (OLD) Integrity table (optional) (variable size)
1683 * (NEW) Streams and metadata resources (variable size)
1684 * (NEW) Lookup table (variable size)
1685 * (NEW) XML data (variable size)
1686 * (NEW) Integrity table (optional) (variable size)
1688 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1689 * the header is overwritten to point to the new lookup table, XML data, and
1690 * integrity table, to produce the following layout:
1692 * Header (212 bytes)
1693 * Streams and metadata resources (variable size)
1694 * Nothing (variable size)
1695 * More Streams and metadata resources (variable size)
1696 * Lookup table (variable size)
1697 * XML data (variable size)
1698 * Integrity table (optional) (variable size)
1700 * This method allows an image to be appended to a large WIM very quickly, and
1701 * is is crash-safe except in the case of write re-ordering, but the
1702 * disadvantage is that a small hole is left in the WIM where the old lookup
1703 * table, xml data, and integrity table were. (These usually only take up a
1704 * small amount of space compared to the streams, however.
1706 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1707 unsigned num_threads,
1708 int modified_image_idx)
1711 struct list_head stream_list;
1714 DEBUG("Overwriting `%s' in-place", w->filename);
1716 /* Make sure that the integrity table (if present) is after the XML
1717 * data, and that there are no stream resources, metadata resources, or
1718 * lookup tables after the XML data. Otherwise, these data would be
1720 if (w->hdr.integrity.offset != 0 &&
1721 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1722 ERROR("Didn't expect the integrity table to be before the XML data");
1723 return WIMLIB_ERR_RESOURCE_ORDER;
1726 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1727 ERROR("Didn't expect the lookup table to be after the XML data");
1728 return WIMLIB_ERR_RESOURCE_ORDER;
1731 DEBUG("Identifying newly added streams");
1732 for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1733 INIT_LIST_HEAD(&stream_list);
1734 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1735 DEBUG("Identifiying streams in image %d", i + 1);
1736 wimlib_assert(w->image_metadata[i].modified);
1737 wimlib_assert(!w->image_metadata[i].has_been_mounted_rw);
1738 wimlib_assert(w->image_metadata[i].root_dentry != NULL);
1739 wimlib_assert(w->image_metadata[i].metadata_lte != NULL);
1740 w->private = &stream_list;
1741 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1742 dentry_find_streams_to_write, w);
1745 if (w->hdr.integrity.offset)
1746 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1748 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1750 ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1755 if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1756 /* If no images have been modified and no images have been
1757 * deleted, a new lookup table does not need to be written. */
1758 wimlib_assert(list_empty(&stream_list));
1759 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1760 w->hdr.lookup_table_res_entry.size;
1761 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1762 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1765 INIT_LIST_HEAD(&stream_list);
1766 for_lookup_table_entry(w->lookup_table, find_new_streams,
1769 ret = open_wim_writable(w, w->filename, false,
1770 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1774 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1775 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1776 return WIMLIB_ERR_WRITE;
1779 if (!list_empty(&stream_list)) {
1780 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1782 ret = write_stream_list(&stream_list, w->out_fp,
1783 wimlib_get_compression_type(w),
1784 write_flags, num_threads);
1788 DEBUG("No new streams were added");
1791 for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1792 select_wim_image(w, i + 1);
1793 ret = write_metadata_resource(w);
1797 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1798 ret = finish_write(w, WIM_ALL_IMAGES, write_flags);
1800 close_wim_writable(w);
1802 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1803 w->filename, old_wim_end);
1804 truncate(w->filename, old_wim_end);
1809 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1810 unsigned num_threads)
1812 size_t wim_name_len;
1815 DEBUG("Overwrining `%s' via a temporary file", w->filename);
1817 /* Write the WIM to a temporary file in the same directory as the
1819 wim_name_len = strlen(w->filename);
1820 char tmpfile[wim_name_len + 10];
1821 memcpy(tmpfile, w->filename, wim_name_len);
1822 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1823 tmpfile[wim_name_len + 9] = '\0';
1825 ret = wimlib_write(w, tmpfile, WIM_ALL_IMAGES,
1826 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1829 ERROR("Failed to write the WIM file `%s'", tmpfile);
1833 /* Close the original WIM file that was opened for reading. */
1834 if (w->fp != NULL) {
1839 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1841 /* Rename the new file to the old file .*/
1842 if (rename(tmpfile, w->filename) != 0) {
1843 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1844 tmpfile, w->filename);
1845 ret = WIMLIB_ERR_RENAME;
1849 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
1850 printf("Successfully renamed `%s' to `%s'\n", tmpfile, w->filename);
1852 /* Re-open the WIM read-only. */
1853 w->fp = fopen(w->filename, "rb");
1854 if (w->fp == NULL) {
1855 ret = WIMLIB_ERR_REOPEN;
1856 WARNING("Failed to re-open `%s' read-only: %s",
1857 w->filename, strerror(errno));
1861 /* Remove temporary file. */
1862 if (unlink(tmpfile) != 0)
1863 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1868 * Writes a WIM file to the original file that it was read from, overwriting it.
1870 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1871 unsigned num_threads)
1874 return WIMLIB_ERR_INVALID_PARAM;
1876 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1879 return WIMLIB_ERR_NO_FILENAME;
1881 if (w->hdr.total_parts != 1) {
1882 ERROR("Cannot modify a split WIM");
1883 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1886 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1887 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1889 int i, modified_image_idx;
1890 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1892 modified_image_idx = i;
1893 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1894 !w->image_metadata[i].has_been_mounted_rw; i++)
1896 if (i == w->hdr.image_count) {
1897 return overwrite_wim_inplace(w, write_flags, num_threads,
1898 modified_image_idx);
1901 return overwrite_wim_via_tmpfile(w, write_flags, num_threads);
1905 WIMLIBAPI int wimlib_overwrite_xml_and_header(WIMStruct *wim, int write_flags)
1907 return wimlib_overwrite(wim, write_flags, 1);