4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 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. */
32 # include <sys/file.h>
40 #include "wimlib_internal.h"
41 #include "buffer_io.h"
43 #include "lookup_table.h"
48 #ifdef ENABLE_MULTITHREADED_COMPRESSION
57 # include <ntfs-3g/attrib.h>
58 # include <ntfs-3g/inode.h>
59 # include <ntfs-3g/dir.h>
68 static int fflush_and_ftruncate(FILE *fp, off_t size)
74 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
75 return WIMLIB_ERR_WRITE;
77 ret = ftruncate(fileno(fp), size);
79 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
80 "%"PRIu64" bytes", size);
81 return WIMLIB_ERR_WRITE;
86 /* Chunk table that's located at the beginning of each compressed resource in
87 * the WIM. (This is not the on-disk format; the on-disk format just has an
88 * array of offsets.) */
92 u64 original_resource_size;
93 u64 bytes_per_chunk_entry;
101 * Allocates and initializes a chunk table, and reserves space for it in the
105 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
108 struct chunk_table **chunk_tab_ret)
110 u64 size = wim_resource_size(lte);
111 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
112 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
113 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
117 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
119 ret = WIMLIB_ERR_NOMEM;
122 chunk_tab->file_offset = file_offset;
123 chunk_tab->num_chunks = num_chunks;
124 chunk_tab->original_resource_size = size;
125 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
126 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
128 chunk_tab->cur_offset = 0;
129 chunk_tab->cur_offset_p = chunk_tab->offsets;
131 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
132 chunk_tab->table_disk_size) {
133 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
135 ret = WIMLIB_ERR_WRITE;
141 *chunk_tab_ret = chunk_tab;
146 * Pointer to function to compresses a chunk of a WIM resource.
148 * @chunk: Uncompressed data of the chunk.
149 * @chunk_size: Size of the uncompressed chunk in bytes.
150 * @compressed_chunk: Pointer to output buffer of size at least
151 * (@chunk_size - 1) bytes.
152 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
153 * of the compressed chunk will be
156 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
157 * compressed to any smaller than @chunk_size. This function cannot fail for
160 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
162 compress_func_t get_compress_func(int out_ctype)
164 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
167 return xpress_compress;
171 * Writes a chunk of a WIM resource to an output file.
173 * @chunk: Uncompressed data of the chunk.
174 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
175 * @out_fp: FILE * to write tho chunk to.
176 * @out_ctype: Compression type to use when writing the chunk (ignored if no
177 * chunk table provided)
178 * @chunk_tab: Pointer to chunk table being created. It is updated with the
179 * offset of the chunk we write.
181 * Returns 0 on success; nonzero on failure.
183 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
184 FILE *out_fp, compress_func_t compress,
185 struct chunk_table *chunk_tab)
188 unsigned out_chunk_size;
190 u8 *compressed_chunk = alloca(chunk_size);
193 ret = compress(chunk, chunk_size, compressed_chunk,
196 out_chunk = compressed_chunk;
199 out_chunk_size = chunk_size;
201 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
202 chunk_tab->cur_offset += out_chunk_size;
205 out_chunk_size = chunk_size;
207 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
208 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
209 return WIMLIB_ERR_WRITE;
215 * Finishes a WIM chunk table and writes it to the output file at the correct
218 * The final size of the full compressed resource is returned in the
219 * @compressed_size_p.
222 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
223 FILE *out_fp, u64 *compressed_size_p)
225 size_t bytes_written;
226 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
227 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
228 "WIM file", chunk_tab->file_offset);
229 return WIMLIB_ERR_WRITE;
232 if (chunk_tab->bytes_per_chunk_entry == 8) {
233 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
235 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
236 ((u32*)chunk_tab->offsets)[i] =
237 cpu_to_le32(chunk_tab->offsets[i]);
239 bytes_written = fwrite((u8*)chunk_tab->offsets +
240 chunk_tab->bytes_per_chunk_entry,
241 1, chunk_tab->table_disk_size, out_fp);
242 if (bytes_written != chunk_tab->table_disk_size) {
243 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
245 return WIMLIB_ERR_WRITE;
247 if (fseeko(out_fp, 0, SEEK_END) != 0) {
248 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
249 return WIMLIB_ERR_WRITE;
251 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
255 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
256 * attribute pointer in the lookup table entry. */
257 static int prepare_resource_for_read(struct wim_lookup_table_entry *lte
260 , ntfs_inode **ni_ret
264 switch (lte->resource_location) {
265 case RESOURCE_IN_FILE_ON_DISK:
266 if (!lte->file_on_disk_fp) {
267 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
268 if (!lte->file_on_disk_fp) {
269 ERROR_WITH_ERRNO("Failed to open the file "
270 "`%s'", lte->file_on_disk);
271 return WIMLIB_ERR_OPEN;
276 case RESOURCE_IN_NTFS_VOLUME:
278 struct ntfs_location *loc = lte->ntfs_loc;
281 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
283 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
284 "volume", loc->path_utf8);
285 return WIMLIB_ERR_NTFS_3G;
287 lte->attr = ntfs_attr_open(ni,
288 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
289 (ntfschar*)loc->stream_name_utf16,
290 loc->stream_name_utf16_num_chars);
292 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
293 "NTFS volume", loc->path_utf8);
294 ntfs_inode_close(ni);
295 return WIMLIB_ERR_NTFS_3G;
303 if (!lte->file_on_disk_fp) {
304 lte->file_on_disk_fp = win32_open_file_readonly(lte->file_on_disk);
305 if (!lte->file_on_disk_fp)
306 return WIMLIB_ERR_OPEN;
316 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
318 static void end_wim_resource_read(struct wim_lookup_table_entry *lte
324 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
325 && lte->file_on_disk_fp)
327 fclose(lte->file_on_disk_fp);
328 lte->file_on_disk_fp = NULL;
331 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
333 ntfs_attr_close(lte->attr);
337 ntfs_inode_close(ni);
341 else if (lte->resource_location == RESOURCE_WIN32
342 && lte->file_on_disk_fp)
344 win32_close_file(lte->file_on_disk_fp);
345 lte->file_on_disk_fp = NULL;
351 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
354 struct resource_entry *out_res_entry)
357 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
358 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
359 "output WIM file", file_offset);
360 return WIMLIB_ERR_WRITE;
362 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
367 return fflush_and_ftruncate(out_fp,
368 file_offset + wim_resource_size(lte));
372 * Writes a WIM resource to a FILE * opened for writing. The resource may be
373 * written uncompressed or compressed depending on the @out_ctype parameter.
375 * If by chance the resource compresses to more than the original size (this may
376 * happen with random data or files than are pre-compressed), the resource is
377 * instead written uncompressed (and this is reflected in the @out_res_entry by
378 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
380 * @lte: The lookup table entry for the WIM resource.
381 * @out_fp: The FILE * to write the resource to.
382 * @out_ctype: The compression type of the resource to write. Note: if this is
383 * the same as the compression type of the WIM resource we
384 * need to read, we simply copy the data (i.e. we do not
385 * uncompress it, then compress it again).
386 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
387 * offset, original size, compressed size, and compression flag
388 * of the output resource.
390 * Returns 0 on success; nonzero on failure.
392 int write_wim_resource(struct wim_lookup_table_entry *lte,
393 FILE *out_fp, int out_ctype,
394 struct resource_entry *out_res_entry,
399 u64 old_compressed_size;
400 u64 new_compressed_size;
403 struct chunk_table *chunk_tab = NULL;
406 compress_func_t compress = NULL;
408 ntfs_inode *ni = NULL;
413 /* Original size of the resource */
414 original_size = wim_resource_size(lte);
416 /* Compressed size of the resource (as it exists now) */
417 old_compressed_size = wim_resource_compressed_size(lte);
419 /* Current offset in output file */
420 file_offset = ftello(out_fp);
421 if (file_offset == -1) {
422 ERROR_WITH_ERRNO("Failed to get offset in output "
424 return WIMLIB_ERR_WRITE;
427 /* Are the compression types the same? If so, do a raw copy (copy
428 * without decompressing and recompressing the data). */
429 raw = (wim_resource_compression_type(lte) == out_ctype
430 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
431 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
434 flags |= WIMLIB_RESOURCE_FLAG_RAW;
435 bytes_remaining = old_compressed_size;
437 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
438 bytes_remaining = original_size;
441 /* Empty resource; nothing needs to be done, so just return success. */
442 if (bytes_remaining == 0)
445 /* Buffer for reading chunks for the resource */
446 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
448 /* If we are writing a compressed resource and not doing a raw copy, we
449 * need to initialize the chunk table */
450 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
451 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
457 /* If the WIM resource is in an external file, open a FILE * to it so we
458 * don't have to open a temporary one in read_wim_resource() for each
461 ret = prepare_resource_for_read(lte, &ni);
463 ret = prepare_resource_for_read(lte);
468 /* If we aren't doing a raw copy, we will compute the SHA1 message
469 * digest of the resource as we read it, and verify it's the same as the
470 * hash given in the lookup table entry once we've finished reading the
475 compress = get_compress_func(out_ctype);
479 /* While there are still bytes remaining in the WIM resource, read a
480 * chunk of the resource, update SHA1, then write that chunk using the
481 * desired compression type. */
483 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
484 ret = read_wim_resource(lte, buf, to_read, offset, flags);
488 sha1_update(&ctx, buf, to_read);
489 ret = write_wim_resource_chunk(buf, to_read, out_fp,
490 compress, chunk_tab);
493 bytes_remaining -= to_read;
495 } while (bytes_remaining);
497 /* Raw copy: The new compressed size is the same as the old compressed
500 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
503 * Using a different compression type: Call
504 * finish_wim_resource_chunk_tab() and it will provide the new
508 new_compressed_size = old_compressed_size;
510 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
511 new_compressed_size = original_size;
513 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
514 &new_compressed_size);
520 /* Verify SHA1 message digest of the resource, unless we are doing a raw
521 * write (in which case we never even saw the uncompressed data). Or,
522 * if the hash we had before is all 0's, just re-set it to be the new
525 u8 md[SHA1_HASH_SIZE];
526 sha1_final(md, &ctx);
527 if (is_zero_hash(lte->hash)) {
528 copy_hash(lte->hash, md);
529 } else if (!hashes_equal(md, lte->hash)) {
530 ERROR("WIM resource has incorrect hash!");
531 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
532 ERROR("We were reading it from `%s'; maybe it changed "
533 "while we were reading it.",
536 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
541 if (!raw && new_compressed_size >= original_size &&
542 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
544 /* Oops! We compressed the resource to larger than the original
545 * size. Write the resource uncompressed instead. */
546 ret = write_uncompressed_resource_and_truncate(lte,
554 out_res_entry->size = new_compressed_size;
555 out_res_entry->original_size = original_size;
556 out_res_entry->offset = file_offset;
557 out_res_entry->flags = lte->resource_entry.flags
558 & ~WIM_RESHDR_FLAG_COMPRESSED;
559 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
560 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
566 end_wim_resource_read(lte, ni);
568 end_wim_resource_read(lte);
575 #ifdef ENABLE_MULTITHREADED_COMPRESSION
577 /* Blocking shared queue (solves the producer-consumer problem) */
578 struct shared_queue {
582 unsigned filled_slots;
584 pthread_mutex_t lock;
585 pthread_cond_t msg_avail_cond;
586 pthread_cond_t space_avail_cond;
589 static int shared_queue_init(struct shared_queue *q, unsigned size)
591 wimlib_assert(size != 0);
592 q->array = CALLOC(sizeof(q->array[0]), size);
594 return WIMLIB_ERR_NOMEM;
599 pthread_mutex_init(&q->lock, NULL);
600 pthread_cond_init(&q->msg_avail_cond, NULL);
601 pthread_cond_init(&q->space_avail_cond, NULL);
605 static void shared_queue_destroy(struct shared_queue *q)
608 pthread_mutex_destroy(&q->lock);
609 pthread_cond_destroy(&q->msg_avail_cond);
610 pthread_cond_destroy(&q->space_avail_cond);
613 static void shared_queue_put(struct shared_queue *q, void *obj)
615 pthread_mutex_lock(&q->lock);
616 while (q->filled_slots == q->size)
617 pthread_cond_wait(&q->space_avail_cond, &q->lock);
619 q->back = (q->back + 1) % q->size;
620 q->array[q->back] = obj;
623 pthread_cond_broadcast(&q->msg_avail_cond);
624 pthread_mutex_unlock(&q->lock);
627 static void *shared_queue_get(struct shared_queue *q)
631 pthread_mutex_lock(&q->lock);
632 while (q->filled_slots == 0)
633 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
635 obj = q->array[q->front];
636 q->array[q->front] = NULL;
637 q->front = (q->front + 1) % q->size;
640 pthread_cond_broadcast(&q->space_avail_cond);
641 pthread_mutex_unlock(&q->lock);
645 struct compressor_thread_params {
646 struct shared_queue *res_to_compress_queue;
647 struct shared_queue *compressed_res_queue;
648 compress_func_t compress;
651 #define MAX_CHUNKS_PER_MSG 2
654 struct wim_lookup_table_entry *lte;
655 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
656 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
657 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
658 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
659 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
661 struct list_head list;
666 static void compress_chunks(struct message *msg, compress_func_t compress)
668 for (unsigned i = 0; i < msg->num_chunks; i++) {
669 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
670 int ret = compress(msg->uncompressed_chunks[i],
671 msg->uncompressed_chunk_sizes[i],
672 msg->compressed_chunks[i],
673 &msg->compressed_chunk_sizes[i]);
675 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
677 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
678 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
683 /* Compressor thread routine. This is a lot simpler than the main thread
684 * routine: just repeatedly get a group of chunks from the
685 * res_to_compress_queue, compress them, and put them in the
686 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
688 static void *compressor_thread_proc(void *arg)
690 struct compressor_thread_params *params = arg;
691 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
692 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
693 compress_func_t compress = params->compress;
696 DEBUG("Compressor thread ready");
697 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
698 compress_chunks(msg, compress);
699 shared_queue_put(compressed_res_queue, msg);
701 DEBUG("Compressor thread terminating");
706 static int do_write_stream_list(struct list_head *my_resources,
709 wimlib_progress_func_t progress_func,
710 union wimlib_progress_info *progress,
711 int write_resource_flags)
714 struct wim_lookup_table_entry *lte, *tmp;
716 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
717 ret = write_wim_resource(lte,
720 <e->output_resource_entry,
721 write_resource_flags);
724 list_del(<e->staging_list);
725 progress->write_streams.completed_bytes +=
726 wim_resource_size(lte);
727 progress->write_streams.completed_streams++;
729 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
736 static int write_stream_list_serial(struct list_head *stream_list,
740 wimlib_progress_func_t progress_func,
741 union wimlib_progress_info *progress)
743 int write_resource_flags;
745 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
746 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
748 write_resource_flags = 0;
749 progress->write_streams.num_threads = 1;
751 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
752 return do_write_stream_list(stream_list, out_fp,
753 out_ctype, progress_func,
754 progress, write_resource_flags);
757 #ifdef ENABLE_MULTITHREADED_COMPRESSION
758 static int write_wim_chunks(struct message *msg, FILE *out_fp,
759 struct chunk_table *chunk_tab)
761 for (unsigned i = 0; i < msg->num_chunks; i++) {
762 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
764 DEBUG2("Write wim chunk %u of %u (csize = %u)",
765 i, msg->num_chunks, chunk_csize);
767 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
770 ERROR_WITH_ERRNO("Failed to write WIM chunk");
771 return WIMLIB_ERR_WRITE;
774 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
775 chunk_tab->cur_offset += chunk_csize;
781 * This function is executed by the main thread when the resources are being
782 * compressed in parallel. The main thread is in change of all reading of the
783 * uncompressed data and writing of the compressed data. The compressor threads
784 * *only* do compression from/to in-memory buffers.
786 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
787 * chunks of compressed data to compress, represented in a `struct message'.
788 * Each message is passed from the main thread to a worker thread through the
789 * res_to_compress_queue, and it is passed back through the
790 * compressed_res_queue.
792 static int main_writer_thread_proc(struct list_head *stream_list,
795 struct shared_queue *res_to_compress_queue,
796 struct shared_queue *compressed_res_queue,
799 wimlib_progress_func_t progress_func,
800 union wimlib_progress_info *progress)
803 struct chunk_table *cur_chunk_tab = NULL;
804 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
805 struct wim_lookup_table_entry *next_lte = NULL;
807 // Initially, all the messages are available to use.
808 LIST_HEAD(available_msgs);
811 ret = WIMLIB_ERR_NOMEM;
815 for (size_t i = 0; i < num_messages; i++)
816 list_add(&msgs[i].list, &available_msgs);
818 // outstanding_resources is the list of resources that currently have
819 // had chunks sent off for compression.
821 // The first stream in outstanding_resources is the stream that is
822 // currently being written (cur_lte).
824 // The last stream in outstanding_resources is the stream that is
825 // currently being read and chunks fed to the compressor threads
828 // Depending on the number of threads and the sizes of the resource,
829 // the outstanding streams list may contain streams between cur_lte and
830 // next_lte that have all their chunks compressed or being compressed,
831 // but haven't been written yet.
833 LIST_HEAD(outstanding_resources);
834 struct list_head *next_resource = stream_list->next;
836 u64 next_num_chunks = 0;
838 // As in write_wim_resource(), each resource we read is checksummed.
839 SHA_CTX next_sha_ctx;
840 u8 next_hash[SHA1_HASH_SIZE];
842 // Resources that don't need any chunks compressed are added to this
843 // list and written directly by the main thread.
844 LIST_HEAD(my_resources);
846 struct wim_lookup_table_entry *cur_lte = NULL;
850 ntfs_inode *ni = NULL;
853 DEBUG("Initializing buffers for uncompressed "
854 "and compressed data (%zu bytes needed)",
855 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
857 // Pre-allocate all the buffers that will be needed to do the chunk
859 for (size_t i = 0; i < num_messages; i++) {
860 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
861 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
863 // The extra 8 bytes is because longest_match() in
864 // lz77.c may read a little bit off the end of the
865 // uncompressed data. It doesn't need to be
866 // initialized--- we really just need to avoid accessing
868 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
869 if (msgs[i].compressed_chunks[j] == NULL ||
870 msgs[i].uncompressed_chunks[j] == NULL)
872 ret = WIMLIB_ERR_NOMEM;
878 // This loop is executed until all resources have been written, except
879 // possibly a few that have been added to the @my_resources list for
882 // Send chunks to the compressor threads until either (a) there
883 // are no more messages available since they were all sent off,
884 // or (b) there are no more resources that need to be
886 while (!list_empty(&available_msgs)) {
887 if (next_chunk == next_num_chunks) {
888 // If next_chunk == next_num_chunks, there are
889 // no more chunks to write in the current
890 // stream. So, check the SHA1 message digest of
891 // the stream that was just finished (unless
892 // next_lte == NULL, which is the case the very
893 // first time this loop is entered, and also
894 // near the very end of the compression when
895 // there are no more streams.) Then, advance to
896 // the next stream (if there is one).
897 if (next_lte != NULL) {
899 end_wim_resource_read(next_lte, ni);
902 end_wim_resource_read(next_lte);
904 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
906 sha1_final(next_hash, &next_sha_ctx);
907 if (!hashes_equal(next_lte->hash, next_hash)) {
908 ERROR("WIM resource has incorrect hash!");
909 if (next_lte->resource_location ==
910 RESOURCE_IN_FILE_ON_DISK)
912 ERROR("We were reading it from `%s'; "
913 "maybe it changed while we were "
915 next_lte->file_on_disk);
917 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
922 // Advance to the next resource.
924 // If the next resource needs no compression, just write
925 // it with this thread (not now though--- we could be in
926 // the middle of writing another resource.) Keep doing
927 // this until we either get to the end of the resources
928 // list, or we get to a resource that needs compression.
930 if (next_resource == stream_list) {
931 // No more resources to send for
936 next_lte = container_of(next_resource,
937 struct wim_lookup_table_entry,
939 next_resource = next_resource->next;
940 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
941 && wim_resource_compression_type(next_lte) == out_ctype)
942 || wim_resource_size(next_lte) == 0)
944 list_add_tail(&next_lte->staging_list,
947 list_add_tail(&next_lte->staging_list,
948 &outstanding_resources);
950 next_num_chunks = wim_resource_chunks(next_lte);
951 sha1_init(&next_sha_ctx);
952 INIT_LIST_HEAD(&next_lte->msg_list);
954 ret = prepare_resource_for_read(next_lte, &ni);
956 ret = prepare_resource_for_read(next_lte);
961 if (cur_lte == NULL) {
962 // Set cur_lte for the
971 if (next_lte == NULL) {
972 // No more resources to send for compression
976 // Get a message from the available messages
978 msg = container_of(available_msgs.next,
982 // ... and delete it from the available messages
984 list_del(&msg->list);
986 // Initialize the message with the chunks to
988 msg->num_chunks = min(next_num_chunks - next_chunk,
991 msg->complete = false;
992 msg->begin_chunk = next_chunk;
994 unsigned size = WIM_CHUNK_SIZE;
995 for (unsigned i = 0; i < msg->num_chunks; i++) {
997 // Read chunk @next_chunk of the stream into the
998 // message so that a compressor thread can
1001 if (next_chunk == next_num_chunks - 1) {
1002 size = MODULO_NONZERO(wim_resource_size(next_lte),
1006 DEBUG2("Read resource (size=%u, offset=%zu)",
1007 size, next_chunk * WIM_CHUNK_SIZE);
1009 msg->uncompressed_chunk_sizes[i] = size;
1011 ret = read_wim_resource(next_lte,
1012 msg->uncompressed_chunks[i],
1014 next_chunk * WIM_CHUNK_SIZE,
1018 sha1_update(&next_sha_ctx,
1019 msg->uncompressed_chunks[i], size);
1023 // Send the compression request
1024 list_add_tail(&msg->list, &next_lte->msg_list);
1025 shared_queue_put(res_to_compress_queue, msg);
1026 DEBUG2("Compression request sent");
1029 // If there are no outstanding resources, there are no more
1030 // resources that need to be written.
1031 if (list_empty(&outstanding_resources)) {
1036 // Get the next message from the queue and process it.
1037 // The message will contain 1 or more data chunks that have been
1039 msg = shared_queue_get(compressed_res_queue);
1040 msg->complete = true;
1042 // Is this the next chunk in the current resource? If it's not
1043 // (i.e., an earlier chunk in a same or different resource
1044 // hasn't been compressed yet), do nothing, and keep this
1045 // message around until all earlier chunks are received.
1047 // Otherwise, write all the chunks we can.
1048 while (cur_lte != NULL &&
1049 !list_empty(&cur_lte->msg_list) &&
1050 (msg = container_of(cur_lte->msg_list.next,
1054 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1055 if (msg->begin_chunk == 0) {
1056 DEBUG2("Begin chunk tab");
1058 // This is the first set of chunks. Leave space
1059 // for the chunk table in the output file.
1060 off_t cur_offset = ftello(out_fp);
1061 if (cur_offset == -1) {
1062 ret = WIMLIB_ERR_WRITE;
1065 ret = begin_wim_resource_chunk_tab(cur_lte,
1073 // Write the compressed chunks from the message.
1074 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1078 list_del(&msg->list);
1080 // This message is available to use for different chunks
1082 list_add(&msg->list, &available_msgs);
1084 // Was this the last chunk of the stream? If so, finish
1086 if (list_empty(&cur_lte->msg_list) &&
1087 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1089 DEBUG2("Finish wim chunk tab");
1091 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1097 if (res_csize >= wim_resource_size(cur_lte)) {
1098 /* Oops! We compressed the resource to
1099 * larger than the original size. Write
1100 * the resource uncompressed instead. */
1101 ret = write_uncompressed_resource_and_truncate(
1104 cur_chunk_tab->file_offset,
1105 &cur_lte->output_resource_entry);
1109 cur_lte->output_resource_entry.size =
1112 cur_lte->output_resource_entry.original_size =
1113 cur_lte->resource_entry.original_size;
1115 cur_lte->output_resource_entry.offset =
1116 cur_chunk_tab->file_offset;
1118 cur_lte->output_resource_entry.flags =
1119 cur_lte->resource_entry.flags |
1120 WIM_RESHDR_FLAG_COMPRESSED;
1123 progress->write_streams.completed_bytes +=
1124 wim_resource_size(cur_lte);
1125 progress->write_streams.completed_streams++;
1127 if (progress_func) {
1128 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1132 FREE(cur_chunk_tab);
1133 cur_chunk_tab = NULL;
1135 struct list_head *next = cur_lte->staging_list.next;
1136 list_del(&cur_lte->staging_list);
1138 if (next == &outstanding_resources)
1141 cur_lte = container_of(cur_lte->staging_list.next,
1142 struct wim_lookup_table_entry,
1145 // Since we just finished writing a stream,
1146 // write any streams that have been added to the
1147 // my_resources list for direct writing by the
1148 // main thread (e.g. resources that don't need
1149 // to be compressed because the desired
1150 // compression type is the same as the previous
1151 // compression type).
1152 ret = do_write_stream_list(&my_resources,
1165 if (ret == WIMLIB_ERR_NOMEM) {
1166 ERROR("Could not allocate enough memory for "
1167 "multi-threaded compression");
1172 end_wim_resource_read(next_lte, ni);
1174 end_wim_resource_read(next_lte);
1179 ret = do_write_stream_list(&my_resources, out_fp,
1180 out_ctype, progress_func,
1184 size_t num_available_msgs = 0;
1185 struct list_head *cur;
1187 list_for_each(cur, &available_msgs) {
1188 num_available_msgs++;
1191 while (num_available_msgs < num_messages) {
1192 shared_queue_get(compressed_res_queue);
1193 num_available_msgs++;
1199 for (size_t i = 0; i < num_messages; i++) {
1200 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1201 FREE(msgs[i].compressed_chunks[j]);
1202 FREE(msgs[i].uncompressed_chunks[j]);
1208 FREE(cur_chunk_tab);
1212 static long get_default_num_threads()
1215 return win32_get_number_of_processors();
1217 return sysconf(_SC_NPROCESSORS_ONLN);
1221 static int write_stream_list_parallel(struct list_head *stream_list,
1225 unsigned num_threads,
1226 wimlib_progress_func_t progress_func,
1227 union wimlib_progress_info *progress)
1230 struct shared_queue res_to_compress_queue;
1231 struct shared_queue compressed_res_queue;
1232 pthread_t *compressor_threads = NULL;
1234 if (num_threads == 0) {
1235 long nthreads = get_default_num_threads();
1236 if (nthreads < 1 || nthreads > UINT_MAX) {
1237 WARNING("Could not determine number of processors! Assuming 1");
1240 num_threads = nthreads;
1244 progress->write_streams.num_threads = num_threads;
1245 wimlib_assert(stream_list->next != stream_list);
1247 static const double MESSAGES_PER_THREAD = 2.0;
1248 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1250 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1252 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1256 ret = shared_queue_init(&compressed_res_queue, queue_size);
1258 goto out_destroy_res_to_compress_queue;
1260 struct compressor_thread_params params;
1261 params.res_to_compress_queue = &res_to_compress_queue;
1262 params.compressed_res_queue = &compressed_res_queue;
1263 params.compress = get_compress_func(out_ctype);
1265 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1266 if (!compressor_threads) {
1267 ret = WIMLIB_ERR_NOMEM;
1268 goto out_destroy_compressed_res_queue;
1271 for (unsigned i = 0; i < num_threads; i++) {
1272 DEBUG("pthread_create thread %u", i);
1273 ret = pthread_create(&compressor_threads[i], NULL,
1274 compressor_thread_proc, ¶ms);
1277 ERROR_WITH_ERRNO("Failed to create compressor "
1285 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1287 ret = main_writer_thread_proc(stream_list,
1290 &res_to_compress_queue,
1291 &compressed_res_queue,
1297 for (unsigned i = 0; i < num_threads; i++)
1298 shared_queue_put(&res_to_compress_queue, NULL);
1300 for (unsigned i = 0; i < num_threads; i++) {
1301 if (pthread_join(compressor_threads[i], NULL)) {
1302 WARNING_WITH_ERRNO("Failed to join compressor "
1306 FREE(compressor_threads);
1307 out_destroy_compressed_res_queue:
1308 shared_queue_destroy(&compressed_res_queue);
1309 out_destroy_res_to_compress_queue:
1310 shared_queue_destroy(&res_to_compress_queue);
1311 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1314 WARNING("Falling back to single-threaded compression");
1315 return write_stream_list_serial(stream_list,
1326 * Write a list of streams to a WIM (@out_fp) using the compression type
1327 * @out_ctype and up to @num_threads compressor threads.
1329 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1330 int out_ctype, int write_flags,
1331 unsigned num_threads,
1332 wimlib_progress_func_t progress_func)
1334 struct wim_lookup_table_entry *lte;
1335 size_t num_streams = 0;
1336 u64 total_bytes = 0;
1337 u64 total_compression_bytes = 0;
1338 union wimlib_progress_info progress;
1340 list_for_each_entry(lte, stream_list, staging_list) {
1342 total_bytes += wim_resource_size(lte);
1343 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1344 && (wim_resource_compression_type(lte) != out_ctype ||
1345 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1347 total_compression_bytes += wim_resource_size(lte);
1350 progress.write_streams.total_bytes = total_bytes;
1351 progress.write_streams.total_streams = num_streams;
1352 progress.write_streams.completed_bytes = 0;
1353 progress.write_streams.completed_streams = 0;
1354 progress.write_streams.num_threads = num_threads;
1355 progress.write_streams.compression_type = out_ctype;
1357 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1358 if (total_compression_bytes >= 1000000 && num_threads != 1)
1359 return write_stream_list_parallel(stream_list,
1368 return write_stream_list_serial(stream_list,
1376 struct lte_overwrite_prepare_args {
1379 struct list_head *stream_list;
1382 static int lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1384 struct lte_overwrite_prepare_args *args = arg;
1386 if (lte->resource_location == RESOURCE_IN_WIM &&
1387 lte->wim == args->wim &&
1388 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1390 #ifdef ENABLE_ERROR_MESSAGES
1391 ERROR("The following resource is after the XML data:");
1392 print_lookup_table_entry(lte, stderr);
1394 return WIMLIB_ERR_RESOURCE_ORDER;
1397 lte->out_refcnt = lte->refcnt;
1398 memcpy(<e->output_resource_entry, <e->resource_entry,
1399 sizeof(struct resource_entry));
1400 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA)) {
1401 wimlib_assert(lte->resource_location != RESOURCE_NONEXISTENT);
1402 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1403 list_add(<e->staging_list, args->stream_list);
1408 static int wim_find_new_streams(WIMStruct *wim, off_t end_offset,
1409 struct list_head *stream_list)
1411 struct lte_overwrite_prepare_args args = {
1413 .end_offset = end_offset,
1414 .stream_list = stream_list,
1417 return for_lookup_table_entry(wim->lookup_table,
1418 lte_overwrite_prepare, &args);
1421 static int inode_find_streams_to_write(struct wim_inode *inode,
1422 struct wim_lookup_table *table,
1423 struct list_head *stream_list)
1425 struct wim_lookup_table_entry *lte;
1426 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1427 lte = inode_stream_lte(inode, i, table);
1429 if (lte->out_refcnt == 0)
1430 list_add_tail(<e->staging_list, stream_list);
1431 lte->out_refcnt += inode->i_nlink;
1437 static int image_find_streams_to_write(WIMStruct *w)
1439 struct wim_inode *inode;
1440 struct hlist_node *cur;
1441 struct hlist_head *inode_list;
1443 inode_list = &wim_get_current_image_metadata(w)->inode_list;
1444 hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1445 inode_find_streams_to_write(inode, w->lookup_table,
1446 (struct list_head*)w->private);
1451 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1452 unsigned num_threads,
1453 wimlib_progress_func_t progress_func)
1456 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1457 LIST_HEAD(stream_list);
1458 w->private = &stream_list;
1459 for_image(w, image, image_find_streams_to_write);
1460 return write_stream_list(&stream_list, w->out_fp,
1461 wimlib_get_compression_type(w), write_flags,
1462 num_threads, progress_func);
1466 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1467 * table (optional), then overwrite the WIM header.
1469 * write_flags is a bitwise OR of the following:
1471 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1472 * Include an integrity table.
1474 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1475 * Show progress information when (if) writing the integrity table.
1477 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1478 * Don't write the lookup table.
1480 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1481 * When (if) writing the integrity table, re-use entries from the
1482 * existing integrity table, if possible.
1484 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1485 * After writing the XML data but before writing the integrity
1486 * table, write a temporary WIM header and flush the stream so that
1487 * the WIM is less likely to become corrupted upon abrupt program
1490 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1491 * fsync() the output file before closing it.
1494 int finish_write(WIMStruct *w, int image, int write_flags,
1495 wimlib_progress_func_t progress_func)
1498 struct wim_header hdr;
1499 FILE *out = w->out_fp;
1501 /* @hdr will be the header for the new WIM. First copy all the data
1502 * from the header in the WIMStruct; then set all the fields that may
1503 * have changed, including the resource entries, boot index, and image
1505 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1507 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1508 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1513 ret = write_xml_data(w->wim_info, image, out,
1514 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1515 wim_info_get_total_bytes(w->wim_info) : 0,
1516 &hdr.xml_res_entry);
1520 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1521 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1522 struct wim_header checkpoint_hdr;
1523 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1524 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1525 if (fseeko(out, 0, SEEK_SET) != 0) {
1526 ERROR_WITH_ERRNO("Failed to seek to beginning "
1527 "of WIM being written");
1528 ret = WIMLIB_ERR_WRITE;
1531 ret = write_header(&checkpoint_hdr, out);
1535 if (fflush(out) != 0) {
1536 ERROR_WITH_ERRNO("Can't write data to WIM");
1537 ret = WIMLIB_ERR_WRITE;
1541 if (fseeko(out, 0, SEEK_END) != 0) {
1542 ERROR_WITH_ERRNO("Failed to seek to end "
1543 "of WIM being written");
1544 ret = WIMLIB_ERR_WRITE;
1549 off_t old_lookup_table_end;
1550 off_t new_lookup_table_end;
1551 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1552 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1553 w->hdr.lookup_table_res_entry.size;
1555 old_lookup_table_end = 0;
1557 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1558 hdr.lookup_table_res_entry.size;
1560 ret = write_integrity_table(out,
1562 new_lookup_table_end,
1563 old_lookup_table_end,
1568 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1572 * In the WIM header, there is room for the resource entry for a
1573 * metadata resource labeled as the "boot metadata". This entry should
1574 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1575 * it should be a copy of the resource entry for the image that is
1576 * marked as bootable. This is not well documented...
1579 /* Set image count and boot index correctly for single image writes */
1580 if (image != WIMLIB_ALL_IMAGES) {
1581 hdr.image_count = 1;
1582 if (hdr.boot_idx == image)
1588 if (hdr.boot_idx == 0) {
1589 memset(&hdr.boot_metadata_res_entry, 0,
1590 sizeof(struct resource_entry));
1592 memcpy(&hdr.boot_metadata_res_entry,
1594 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1595 sizeof(struct resource_entry));
1598 if (fseeko(out, 0, SEEK_SET) != 0) {
1599 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1601 ret = WIMLIB_ERR_WRITE;
1605 ret = write_header(&hdr, out);
1609 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1610 if (fflush(out) != 0
1611 || fsync(fileno(out)) != 0)
1613 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1614 ret = WIMLIB_ERR_WRITE;
1618 if (fclose(out) != 0) {
1619 ERROR_WITH_ERRNO("Failed to close the WIM file");
1621 ret = WIMLIB_ERR_WRITE;
1627 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1628 int lock_wim(WIMStruct *w, FILE *fp)
1631 if (fp && !w->wim_locked) {
1632 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1634 if (errno == EWOULDBLOCK) {
1635 ERROR("`%s' is already being modified or has been "
1636 "mounted read-write\n"
1637 " by another process!", w->filename);
1638 ret = WIMLIB_ERR_ALREADY_LOCKED;
1640 WARNING_WITH_ERRNO("Failed to lock `%s'",
1652 static int open_wim_writable(WIMStruct *w, const char *path,
1653 bool trunc, bool readable)
1664 wimlib_assert(w->out_fp == NULL);
1665 w->out_fp = fopen(path, mode);
1669 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
1670 return WIMLIB_ERR_OPEN;
1675 void close_wim_writable(WIMStruct *w)
1678 if (fclose(w->out_fp) != 0) {
1679 WARNING_WITH_ERRNO("Failed to close output WIM");
1685 /* Open file stream and write dummy header for WIM. */
1686 int begin_write(WIMStruct *w, const char *path, int write_flags)
1689 ret = open_wim_writable(w, path, true,
1690 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1693 /* Write dummy header. It will be overwritten later. */
1694 return write_header(&w->hdr, w->out_fp);
1697 /* Writes a stand-alone WIM to a file. */
1698 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1699 int image, int write_flags, unsigned num_threads,
1700 wimlib_progress_func_t progress_func)
1705 return WIMLIB_ERR_INVALID_PARAM;
1707 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1709 if (image != WIMLIB_ALL_IMAGES &&
1710 (image < 1 || image > w->hdr.image_count))
1711 return WIMLIB_ERR_INVALID_IMAGE;
1713 if (w->hdr.total_parts != 1) {
1714 ERROR("Cannot call wimlib_write() on part of a split WIM");
1715 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1718 ret = begin_write(w, path, write_flags);
1722 ret = write_wim_streams(w, image, write_flags, num_threads,
1728 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1730 ret = for_image(w, image, write_metadata_resource);
1735 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1737 ret = finish_write(w, image, write_flags, progress_func);
1739 close_wim_writable(w);
1740 DEBUG("wimlib_write(path=%s) = %d", path, ret);
1744 static bool any_images_modified(WIMStruct *w)
1746 for (int i = 0; i < w->hdr.image_count; i++)
1747 if (w->image_metadata[i].modified)
1753 * Overwrite a WIM, possibly appending streams to it.
1755 * A WIM looks like (or is supposed to look like) the following:
1757 * Header (212 bytes)
1758 * Streams and metadata resources (variable size)
1759 * Lookup table (variable size)
1760 * XML data (variable size)
1761 * Integrity table (optional) (variable size)
1763 * If we are not adding any streams or metadata resources, the lookup table is
1764 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1765 * header. This operation is potentially unsafe if the program is abruptly
1766 * terminated while the XML data or integrity table are being overwritten, but
1767 * before the new header has been written. To partially alleviate this problem,
1768 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1769 * finish_write() to cause a temporary WIM header to be written after the XML
1770 * data has been written. This may prevent the WIM from becoming corrupted if
1771 * the program is terminated while the integrity table is being calculated (but
1772 * no guarantees, due to write re-ordering...).
1774 * If we are adding new streams or images (metadata resources), the lookup table
1775 * needs to be changed, and those streams need to be written. In this case, we
1776 * try to perform a safe update of the WIM file by writing the streams *after*
1777 * the end of the previous WIM, then writing the new lookup table, XML data, and
1778 * (optionally) integrity table following the new streams. This will produce a
1779 * layout like the following:
1781 * Header (212 bytes)
1782 * (OLD) Streams and metadata resources (variable size)
1783 * (OLD) Lookup table (variable size)
1784 * (OLD) XML data (variable size)
1785 * (OLD) Integrity table (optional) (variable size)
1786 * (NEW) Streams and metadata resources (variable size)
1787 * (NEW) Lookup table (variable size)
1788 * (NEW) XML data (variable size)
1789 * (NEW) Integrity table (optional) (variable size)
1791 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1792 * the header is overwritten to point to the new lookup table, XML data, and
1793 * integrity table, to produce the following layout:
1795 * Header (212 bytes)
1796 * Streams and metadata resources (variable size)
1797 * Nothing (variable size)
1798 * More Streams and metadata resources (variable size)
1799 * Lookup table (variable size)
1800 * XML data (variable size)
1801 * Integrity table (optional) (variable size)
1803 * This method allows an image to be appended to a large WIM very quickly, and
1804 * is is crash-safe except in the case of write re-ordering, but the
1805 * disadvantage is that a small hole is left in the WIM where the old lookup
1806 * table, xml data, and integrity table were. (These usually only take up a
1807 * small amount of space compared to the streams, however.)
1809 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1810 unsigned num_threads,
1811 wimlib_progress_func_t progress_func)
1814 struct list_head stream_list;
1816 bool found_modified_image;
1818 DEBUG("Overwriting `%s' in-place", w->filename);
1820 /* Make sure that the integrity table (if present) is after the XML
1821 * data, and that there are no stream resources, metadata resources, or
1822 * lookup tables after the XML data. Otherwise, these data would be
1824 if (w->hdr.integrity.offset != 0 &&
1825 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1826 ERROR("Didn't expect the integrity table to be before the XML data");
1827 return WIMLIB_ERR_RESOURCE_ORDER;
1830 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1831 ERROR("Didn't expect the lookup table to be after the XML data");
1832 return WIMLIB_ERR_RESOURCE_ORDER;
1836 if (w->hdr.integrity.offset)
1837 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1839 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1841 if (!w->deletion_occurred && !any_images_modified(w)) {
1842 /* If no images have been modified and no images have been
1843 * deleted, a new lookup table does not need to be written. */
1844 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1845 w->hdr.lookup_table_res_entry.size;
1846 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1847 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1849 INIT_LIST_HEAD(&stream_list);
1850 ret = wim_find_new_streams(w, old_wim_end, &stream_list);
1854 ret = open_wim_writable(w, w->filename, false,
1855 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1859 ret = lock_wim(w, w->out_fp);
1866 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1867 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1871 return WIMLIB_ERR_WRITE;
1874 if (!list_empty(&stream_list)) {
1875 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1877 ret = write_stream_list(&stream_list, w->out_fp,
1878 wimlib_get_compression_type(w),
1879 write_flags, num_threads,
1884 DEBUG("No new streams were added");
1887 found_modified_image = false;
1888 for (int i = 0; i < w->hdr.image_count; i++) {
1889 if (!found_modified_image)
1890 found_modified_image = w->image_metadata[i].modified;
1891 if (found_modified_image) {
1892 select_wim_image(w, i + 1);
1893 ret = write_metadata_resource(w);
1898 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1899 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1902 close_wim_writable(w);
1903 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1904 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1905 w->filename, old_wim_end);
1906 /* Return value of truncate() is ignored because this is already
1908 (void)truncate(w->filename, old_wim_end);
1914 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1915 unsigned num_threads,
1916 wimlib_progress_func_t progress_func)
1918 size_t wim_name_len;
1921 DEBUG("Overwriting `%s' via a temporary file", w->filename);
1923 /* Write the WIM to a temporary file in the same directory as the
1925 wim_name_len = strlen(w->filename);
1926 char tmpfile[wim_name_len + 10];
1927 memcpy(tmpfile, w->filename, wim_name_len);
1928 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1929 tmpfile[wim_name_len + 9] = '\0';
1931 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1932 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1933 num_threads, progress_func);
1935 ERROR("Failed to write the WIM file `%s'", tmpfile);
1939 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1941 /* Rename the new file to the old file .*/
1942 if (rename(tmpfile, w->filename) != 0) {
1943 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1944 tmpfile, w->filename);
1945 ret = WIMLIB_ERR_RENAME;
1949 if (progress_func) {
1950 union wimlib_progress_info progress;
1951 progress.rename.from = tmpfile;
1952 progress.rename.to = w->filename;
1953 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1956 /* Close the original WIM file that was opened for reading. */
1957 if (w->fp != NULL) {
1962 /* Re-open the WIM read-only. */
1963 w->fp = fopen(w->filename, "rb");
1964 if (w->fp == NULL) {
1965 ret = WIMLIB_ERR_REOPEN;
1966 WARNING_WITH_ERRNO("Failed to re-open `%s' read-only",
1973 /* Remove temporary file. */
1974 if (unlink(tmpfile) != 0)
1975 WARNING_WITH_ERRNO("Failed to remove `%s'", tmpfile);
1980 * Writes a WIM file to the original file that it was read from, overwriting it.
1982 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1983 unsigned num_threads,
1984 wimlib_progress_func_t progress_func)
1986 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1989 return WIMLIB_ERR_NO_FILENAME;
1991 if (w->hdr.total_parts != 1) {
1992 ERROR("Cannot modify a split WIM");
1993 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1996 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1997 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2000 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2002 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2003 WARNING("Falling back to re-building entire WIM");
2007 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,