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"
49 #ifdef ENABLE_MULTITHREADED_COMPRESSION
58 # include <ntfs-3g/attrib.h>
59 # include <ntfs-3g/inode.h>
60 # include <ntfs-3g/dir.h>
71 #if defined(__WIN32__) && !defined(INVALID_HANDLE_VALUE)
72 # define INVALID_HANDLE_VALUE ((HANDLE)(-1))
76 fflush_and_ftruncate(FILE *fp, off_t size)
82 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
83 return WIMLIB_ERR_WRITE;
85 ret = ftruncate(fileno(fp), size);
87 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
88 "%"PRIu64" bytes", size);
89 return WIMLIB_ERR_WRITE;
94 /* Chunk table that's located at the beginning of each compressed resource in
95 * the WIM. (This is not the on-disk format; the on-disk format just has an
96 * array of offsets.) */
100 u64 original_resource_size;
101 u64 bytes_per_chunk_entry;
109 * Allocates and initializes a chunk table, and reserves space for it in the
113 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
116 struct chunk_table **chunk_tab_ret)
118 u64 size = wim_resource_size(lte);
119 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
120 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
121 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
125 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
127 ret = WIMLIB_ERR_NOMEM;
130 chunk_tab->file_offset = file_offset;
131 chunk_tab->num_chunks = num_chunks;
132 chunk_tab->original_resource_size = size;
133 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
134 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
136 chunk_tab->cur_offset = 0;
137 chunk_tab->cur_offset_p = chunk_tab->offsets;
139 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
140 chunk_tab->table_disk_size) {
141 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
143 ret = WIMLIB_ERR_WRITE;
149 *chunk_tab_ret = chunk_tab;
154 * compress_func_t- Pointer to a function to compresses a chunk
155 * of a WIM resource. This may be either xpress_compress()
156 * (xpress-compress.c) or lzx_compress() (lzx-compress.c).
158 * @chunk: Uncompressed data of the chunk.
159 * @chunk_size: Size of the uncompressed chunk, in bytes.
160 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
162 * Returns the size of the compressed data written to @out in bytes, or 0 if the
163 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
165 * As a special requirement, the compression code is optimized for the WIM
166 * format and therefore requires (@chunk_size <= 32768).
168 * As another special requirement, the compression code will read up to 8 bytes
169 * off the end of the @chunk array for performance reasons. The values of these
170 * bytes will not affect the output of the compression, but the calling code
171 * must make sure that the buffer holding the uncompressed chunk is actually at
172 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
173 * mapped memory that will not cause a memory access violation if accessed.
175 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
179 get_compress_func(int out_ctype)
181 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
184 return xpress_compress;
188 * Writes a chunk of a WIM resource to an output file.
190 * @chunk: Uncompressed data of the chunk.
191 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
192 * @out_fp: FILE * to write tho chunk to.
193 * @out_ctype: Compression type to use when writing the chunk (ignored if no
194 * chunk table provided)
195 * @chunk_tab: Pointer to chunk table being created. It is updated with the
196 * offset of the chunk we write.
198 * Returns 0 on success; nonzero on failure.
201 write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
202 FILE *out_fp, compress_func_t compress,
203 struct chunk_table *chunk_tab)
206 unsigned out_chunk_size;
208 u8 *compressed_chunk = alloca(chunk_size);
210 out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
211 if (out_chunk_size) {
212 /* Write compressed */
213 out_chunk = compressed_chunk;
215 /* Write uncompressed */
217 out_chunk_size = chunk_size;
219 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
220 chunk_tab->cur_offset += out_chunk_size;
222 /* Write uncompressed */
224 out_chunk_size = chunk_size;
226 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
227 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
228 return WIMLIB_ERR_WRITE;
234 * Finishes a WIM chunk table and writes it to the output file at the correct
237 * The final size of the full compressed resource is returned in the
238 * @compressed_size_p.
241 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
242 FILE *out_fp, u64 *compressed_size_p)
244 size_t bytes_written;
245 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
246 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
247 "WIM file", chunk_tab->file_offset);
248 return WIMLIB_ERR_WRITE;
251 if (chunk_tab->bytes_per_chunk_entry == 8) {
252 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
254 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
255 ((u32*)chunk_tab->offsets)[i] =
256 cpu_to_le32(chunk_tab->offsets[i]);
258 bytes_written = fwrite((u8*)chunk_tab->offsets +
259 chunk_tab->bytes_per_chunk_entry,
260 1, chunk_tab->table_disk_size, out_fp);
261 if (bytes_written != chunk_tab->table_disk_size) {
262 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
264 return WIMLIB_ERR_WRITE;
266 if (fseeko(out_fp, 0, SEEK_END) != 0) {
267 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
268 return WIMLIB_ERR_WRITE;
270 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
274 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
275 * attribute pointer in the lookup table entry. */
277 prepare_resource_for_read(struct wim_lookup_table_entry *lte
280 , ntfs_inode **ni_ret
284 switch (lte->resource_location) {
285 case RESOURCE_IN_FILE_ON_DISK:
286 if (!lte->file_on_disk_fp) {
287 lte->file_on_disk_fp = tfopen(lte->file_on_disk, T("rb"));
288 if (!lte->file_on_disk_fp) {
289 ERROR_WITH_ERRNO("Failed to open the file "
290 "`%"TS"'", lte->file_on_disk);
291 return WIMLIB_ERR_OPEN;
296 case RESOURCE_IN_NTFS_VOLUME:
298 struct ntfs_location *loc = lte->ntfs_loc;
301 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path);
303 ERROR_WITH_ERRNO("Failed to open inode `%"TS"' in NTFS "
304 "volume", loc->path);
305 return WIMLIB_ERR_NTFS_3G;
307 lte->attr = ntfs_attr_open(ni,
308 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
310 loc->stream_name_nchars);
312 ERROR_WITH_ERRNO("Failed to open attribute of `%"TS"' in "
313 "NTFS volume", loc->path);
314 ntfs_inode_close(ni);
315 return WIMLIB_ERR_NTFS_3G;
323 if (lte->win32_file_on_disk_fp == INVALID_HANDLE_VALUE) {
324 lte->win32_file_on_disk_fp =
325 win32_open_file_data_only(lte->file_on_disk);
326 if (lte->win32_file_on_disk_fp == INVALID_HANDLE_VALUE) {
327 ERROR("Win32 API: Can't open %"TS, lte->file_on_disk);
329 return WIMLIB_ERR_OPEN;
340 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
343 end_wim_resource_read(struct wim_lookup_table_entry *lte
349 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
350 && lte->file_on_disk_fp)
352 fclose(lte->file_on_disk_fp);
353 lte->file_on_disk_fp = NULL;
356 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
358 ntfs_attr_close(lte->attr);
362 ntfs_inode_close(ni);
366 else if (lte->resource_location == RESOURCE_WIN32
367 && lte->win32_file_on_disk_fp != INVALID_HANDLE_VALUE)
369 win32_close_file(lte->win32_file_on_disk_fp);
370 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
376 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
379 struct resource_entry *out_res_entry)
382 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
383 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
384 "output WIM file", file_offset);
385 return WIMLIB_ERR_WRITE;
387 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
392 return fflush_and_ftruncate(out_fp,
393 file_offset + wim_resource_size(lte));
397 * Writes a WIM resource to a FILE * opened for writing. The resource may be
398 * written uncompressed or compressed depending on the @out_ctype parameter.
400 * If by chance the resource compresses to more than the original size (this may
401 * happen with random data or files than are pre-compressed), the resource is
402 * instead written uncompressed (and this is reflected in the @out_res_entry by
403 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
405 * @lte: The lookup table entry for the WIM resource.
406 * @out_fp: The FILE * to write the resource to.
407 * @out_ctype: The compression type of the resource to write. Note: if this is
408 * the same as the compression type of the WIM resource we
409 * need to read, we simply copy the data (i.e. we do not
410 * uncompress it, then compress it again).
411 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
412 * offset, original size, compressed size, and compression flag
413 * of the output resource.
415 * Returns 0 on success; nonzero on failure.
418 write_wim_resource(struct wim_lookup_table_entry *lte,
419 FILE *out_fp, int out_ctype,
420 struct resource_entry *out_res_entry,
425 u64 old_compressed_size;
426 u64 new_compressed_size;
429 struct chunk_table *chunk_tab = NULL;
432 compress_func_t compress = NULL;
434 ntfs_inode *ni = NULL;
439 /* Original size of the resource */
440 original_size = wim_resource_size(lte);
442 /* Compressed size of the resource (as it exists now) */
443 old_compressed_size = wim_resource_compressed_size(lte);
445 /* Current offset in output file */
446 file_offset = ftello(out_fp);
447 if (file_offset == -1) {
448 ERROR_WITH_ERRNO("Failed to get offset in output "
450 return WIMLIB_ERR_WRITE;
453 /* Are the compression types the same? If so, do a raw copy (copy
454 * without decompressing and recompressing the data). */
455 raw = (wim_resource_compression_type(lte) == out_ctype
456 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
457 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
460 flags |= WIMLIB_RESOURCE_FLAG_RAW;
461 bytes_remaining = old_compressed_size;
463 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
464 bytes_remaining = original_size;
467 /* Empty resource; nothing needs to be done, so just return success. */
468 if (bytes_remaining == 0)
471 /* Buffer for reading chunks for the resource */
472 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
474 /* If we are writing a compressed resource and not doing a raw copy, we
475 * need to initialize the chunk table */
476 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
477 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
483 /* If the WIM resource is in an external file, open a FILE * to it so we
484 * don't have to open a temporary one in read_wim_resource() for each
487 ret = prepare_resource_for_read(lte, &ni);
489 ret = prepare_resource_for_read(lte);
494 /* If we aren't doing a raw copy, we will compute the SHA1 message
495 * digest of the resource as we read it, and verify it's the same as the
496 * hash given in the lookup table entry once we've finished reading the
501 compress = get_compress_func(out_ctype);
505 /* While there are still bytes remaining in the WIM resource, read a
506 * chunk of the resource, update SHA1, then write that chunk using the
507 * desired compression type. */
509 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
510 ret = read_wim_resource(lte, buf, to_read, offset, flags);
514 sha1_update(&ctx, buf, to_read);
515 ret = write_wim_resource_chunk(buf, to_read, out_fp,
516 compress, chunk_tab);
519 bytes_remaining -= to_read;
521 } while (bytes_remaining);
523 /* Raw copy: The new compressed size is the same as the old compressed
526 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
529 * Using a different compression type: Call
530 * finish_wim_resource_chunk_tab() and it will provide the new
534 new_compressed_size = old_compressed_size;
536 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
537 new_compressed_size = original_size;
539 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
540 &new_compressed_size);
546 /* Verify SHA1 message digest of the resource, unless we are doing a raw
547 * write (in which case we never even saw the uncompressed data). Or,
548 * if the hash we had before is all 0's, just re-set it to be the new
551 u8 md[SHA1_HASH_SIZE];
552 sha1_final(md, &ctx);
553 if (is_zero_hash(lte->hash)) {
554 copy_hash(lte->hash, md);
555 } else if (!hashes_equal(md, lte->hash)) {
556 ERROR("WIM resource has incorrect hash!");
557 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
558 ERROR("We were reading it from `%"TS"'; maybe "
559 "it changed while we were reading it.",
562 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
567 if (!raw && new_compressed_size >= original_size &&
568 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
570 /* Oops! We compressed the resource to larger than the original
571 * size. Write the resource uncompressed instead. */
572 ret = write_uncompressed_resource_and_truncate(lte,
580 out_res_entry->size = new_compressed_size;
581 out_res_entry->original_size = original_size;
582 out_res_entry->offset = file_offset;
583 out_res_entry->flags = lte->resource_entry.flags
584 & ~WIM_RESHDR_FLAG_COMPRESSED;
585 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
586 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
592 end_wim_resource_read(lte, ni);
594 end_wim_resource_read(lte);
601 #ifdef ENABLE_MULTITHREADED_COMPRESSION
603 /* Blocking shared queue (solves the producer-consumer problem) */
604 struct shared_queue {
608 unsigned filled_slots;
610 pthread_mutex_t lock;
611 pthread_cond_t msg_avail_cond;
612 pthread_cond_t space_avail_cond;
616 shared_queue_init(struct shared_queue *q, unsigned size)
618 wimlib_assert(size != 0);
619 q->array = CALLOC(sizeof(q->array[0]), size);
621 return WIMLIB_ERR_NOMEM;
626 pthread_mutex_init(&q->lock, NULL);
627 pthread_cond_init(&q->msg_avail_cond, NULL);
628 pthread_cond_init(&q->space_avail_cond, NULL);
633 shared_queue_destroy(struct shared_queue *q)
636 pthread_mutex_destroy(&q->lock);
637 pthread_cond_destroy(&q->msg_avail_cond);
638 pthread_cond_destroy(&q->space_avail_cond);
642 shared_queue_put(struct shared_queue *q, void *obj)
644 pthread_mutex_lock(&q->lock);
645 while (q->filled_slots == q->size)
646 pthread_cond_wait(&q->space_avail_cond, &q->lock);
648 q->back = (q->back + 1) % q->size;
649 q->array[q->back] = obj;
652 pthread_cond_broadcast(&q->msg_avail_cond);
653 pthread_mutex_unlock(&q->lock);
657 shared_queue_get(struct shared_queue *q)
661 pthread_mutex_lock(&q->lock);
662 while (q->filled_slots == 0)
663 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
665 obj = q->array[q->front];
666 q->array[q->front] = NULL;
667 q->front = (q->front + 1) % q->size;
670 pthread_cond_broadcast(&q->space_avail_cond);
671 pthread_mutex_unlock(&q->lock);
675 struct compressor_thread_params {
676 struct shared_queue *res_to_compress_queue;
677 struct shared_queue *compressed_res_queue;
678 compress_func_t compress;
681 #define MAX_CHUNKS_PER_MSG 2
684 struct wim_lookup_table_entry *lte;
685 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
686 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
687 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
688 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
689 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
691 struct list_head list;
697 compress_chunks(struct message *msg, compress_func_t compress)
699 for (unsigned i = 0; i < msg->num_chunks; i++) {
700 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
701 unsigned len = compress(msg->uncompressed_chunks[i],
702 msg->uncompressed_chunk_sizes[i],
703 msg->compressed_chunks[i]);
705 /* To be written compressed */
706 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
707 msg->compressed_chunk_sizes[i] = len;
709 /* To be written uncompressed */
710 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
711 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
717 /* Compressor thread routine. This is a lot simpler than the main thread
718 * routine: just repeatedly get a group of chunks from the
719 * res_to_compress_queue, compress them, and put them in the
720 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
723 compressor_thread_proc(void *arg)
725 struct compressor_thread_params *params = arg;
726 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
727 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
728 compress_func_t compress = params->compress;
731 DEBUG("Compressor thread ready");
732 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
733 compress_chunks(msg, compress);
734 shared_queue_put(compressed_res_queue, msg);
736 DEBUG("Compressor thread terminating");
739 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
742 do_write_stream_list(struct list_head *my_resources,
745 wimlib_progress_func_t progress_func,
746 union wimlib_progress_info *progress,
747 int write_resource_flags)
750 struct wim_lookup_table_entry *lte, *tmp;
752 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
753 ret = write_wim_resource(lte,
756 <e->output_resource_entry,
757 write_resource_flags);
760 list_del(<e->staging_list);
761 progress->write_streams.completed_bytes +=
762 wim_resource_size(lte);
763 progress->write_streams.completed_streams++;
765 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
773 write_stream_list_serial(struct list_head *stream_list,
777 wimlib_progress_func_t progress_func,
778 union wimlib_progress_info *progress)
780 int write_resource_flags;
782 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
783 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
785 write_resource_flags = 0;
786 progress->write_streams.num_threads = 1;
788 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
789 return do_write_stream_list(stream_list, out_fp,
790 out_ctype, progress_func,
791 progress, write_resource_flags);
794 #ifdef ENABLE_MULTITHREADED_COMPRESSION
796 write_wim_chunks(struct message *msg, FILE *out_fp,
797 struct chunk_table *chunk_tab)
799 for (unsigned i = 0; i < msg->num_chunks; i++) {
800 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
802 DEBUG2("Write wim chunk %u of %u (csize = %u)",
803 i, msg->num_chunks, chunk_csize);
805 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
808 ERROR_WITH_ERRNO("Failed to write WIM chunk");
809 return WIMLIB_ERR_WRITE;
812 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
813 chunk_tab->cur_offset += chunk_csize;
819 * This function is executed by the main thread when the resources are being
820 * compressed in parallel. The main thread is in change of all reading of the
821 * uncompressed data and writing of the compressed data. The compressor threads
822 * *only* do compression from/to in-memory buffers.
824 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
825 * chunks of compressed data to compress, represented in a `struct message'.
826 * Each message is passed from the main thread to a worker thread through the
827 * res_to_compress_queue, and it is passed back through the
828 * compressed_res_queue.
831 main_writer_thread_proc(struct list_head *stream_list,
834 struct shared_queue *res_to_compress_queue,
835 struct shared_queue *compressed_res_queue,
838 wimlib_progress_func_t progress_func,
839 union wimlib_progress_info *progress)
842 struct chunk_table *cur_chunk_tab = NULL;
843 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
844 struct wim_lookup_table_entry *next_lte = NULL;
846 // Initially, all the messages are available to use.
847 LIST_HEAD(available_msgs);
850 ret = WIMLIB_ERR_NOMEM;
854 for (size_t i = 0; i < num_messages; i++)
855 list_add(&msgs[i].list, &available_msgs);
857 // outstanding_resources is the list of resources that currently have
858 // had chunks sent off for compression.
860 // The first stream in outstanding_resources is the stream that is
861 // currently being written (cur_lte).
863 // The last stream in outstanding_resources is the stream that is
864 // currently being read and chunks fed to the compressor threads
867 // Depending on the number of threads and the sizes of the resource,
868 // the outstanding streams list may contain streams between cur_lte and
869 // next_lte that have all their chunks compressed or being compressed,
870 // but haven't been written yet.
872 LIST_HEAD(outstanding_resources);
873 struct list_head *next_resource = stream_list->next;
875 u64 next_num_chunks = 0;
877 // As in write_wim_resource(), each resource we read is checksummed.
878 SHA_CTX next_sha_ctx;
879 u8 next_hash[SHA1_HASH_SIZE];
881 // Resources that don't need any chunks compressed are added to this
882 // list and written directly by the main thread.
883 LIST_HEAD(my_resources);
885 struct wim_lookup_table_entry *cur_lte = NULL;
889 ntfs_inode *ni = NULL;
892 DEBUG("Initializing buffers for uncompressed "
893 "and compressed data (%zu bytes needed)",
894 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
896 // Pre-allocate all the buffers that will be needed to do the chunk
898 for (size_t i = 0; i < num_messages; i++) {
899 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
900 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
902 // The extra 8 bytes is because longest_match() in
903 // lz77.c may read a little bit off the end of the
904 // uncompressed data. It doesn't need to be
905 // initialized--- we really just need to avoid accessing
907 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
908 if (msgs[i].compressed_chunks[j] == NULL ||
909 msgs[i].uncompressed_chunks[j] == NULL)
911 ret = WIMLIB_ERR_NOMEM;
917 // This loop is executed until all resources have been written, except
918 // possibly a few that have been added to the @my_resources list for
921 // Send chunks to the compressor threads until either (a) there
922 // are no more messages available since they were all sent off,
923 // or (b) there are no more resources that need to be
925 while (!list_empty(&available_msgs)) {
926 if (next_chunk == next_num_chunks) {
927 // If next_chunk == next_num_chunks, there are
928 // no more chunks to write in the current
929 // stream. So, check the SHA1 message digest of
930 // the stream that was just finished (unless
931 // next_lte == NULL, which is the case the very
932 // first time this loop is entered, and also
933 // near the very end of the compression when
934 // there are no more streams.) Then, advance to
935 // the next stream (if there is one).
936 if (next_lte != NULL) {
938 end_wim_resource_read(next_lte, ni);
941 end_wim_resource_read(next_lte);
943 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
945 sha1_final(next_hash, &next_sha_ctx);
946 if (!hashes_equal(next_lte->hash, next_hash)) {
947 ERROR("WIM resource has incorrect hash!");
948 if (next_lte->resource_location ==
949 RESOURCE_IN_FILE_ON_DISK)
951 ERROR("We were reading it from `%"TS"'; "
952 "maybe it changed while we were "
954 next_lte->file_on_disk);
956 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
961 // Advance to the next resource.
963 // If the next resource needs no compression, just write
964 // it with this thread (not now though--- we could be in
965 // the middle of writing another resource.) Keep doing
966 // this until we either get to the end of the resources
967 // list, or we get to a resource that needs compression.
969 if (next_resource == stream_list) {
970 // No more resources to send for
975 next_lte = container_of(next_resource,
976 struct wim_lookup_table_entry,
978 next_resource = next_resource->next;
979 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
980 && wim_resource_compression_type(next_lte) == out_ctype)
981 || wim_resource_size(next_lte) == 0)
983 list_add_tail(&next_lte->staging_list,
986 list_add_tail(&next_lte->staging_list,
987 &outstanding_resources);
989 next_num_chunks = wim_resource_chunks(next_lte);
990 sha1_init(&next_sha_ctx);
991 INIT_LIST_HEAD(&next_lte->msg_list);
993 ret = prepare_resource_for_read(next_lte, &ni);
995 ret = prepare_resource_for_read(next_lte);
1000 if (cur_lte == NULL) {
1001 // Set cur_lte for the
1010 if (next_lte == NULL) {
1011 // No more resources to send for compression
1015 // Get a message from the available messages
1017 msg = container_of(available_msgs.next,
1021 // ... and delete it from the available messages
1023 list_del(&msg->list);
1025 // Initialize the message with the chunks to
1027 msg->num_chunks = min(next_num_chunks - next_chunk,
1028 MAX_CHUNKS_PER_MSG);
1029 msg->lte = next_lte;
1030 msg->complete = false;
1031 msg->begin_chunk = next_chunk;
1033 unsigned size = WIM_CHUNK_SIZE;
1034 for (unsigned i = 0; i < msg->num_chunks; i++) {
1036 // Read chunk @next_chunk of the stream into the
1037 // message so that a compressor thread can
1040 if (next_chunk == next_num_chunks - 1) {
1041 size = MODULO_NONZERO(wim_resource_size(next_lte),
1045 DEBUG2("Read resource (size=%u, offset=%zu)",
1046 size, next_chunk * WIM_CHUNK_SIZE);
1048 msg->uncompressed_chunk_sizes[i] = size;
1050 ret = read_wim_resource(next_lte,
1051 msg->uncompressed_chunks[i],
1053 next_chunk * WIM_CHUNK_SIZE,
1057 sha1_update(&next_sha_ctx,
1058 msg->uncompressed_chunks[i], size);
1062 // Send the compression request
1063 list_add_tail(&msg->list, &next_lte->msg_list);
1064 shared_queue_put(res_to_compress_queue, msg);
1065 DEBUG2("Compression request sent");
1068 // If there are no outstanding resources, there are no more
1069 // resources that need to be written.
1070 if (list_empty(&outstanding_resources)) {
1075 // Get the next message from the queue and process it.
1076 // The message will contain 1 or more data chunks that have been
1078 msg = shared_queue_get(compressed_res_queue);
1079 msg->complete = true;
1081 // Is this the next chunk in the current resource? If it's not
1082 // (i.e., an earlier chunk in a same or different resource
1083 // hasn't been compressed yet), do nothing, and keep this
1084 // message around until all earlier chunks are received.
1086 // Otherwise, write all the chunks we can.
1087 while (cur_lte != NULL &&
1088 !list_empty(&cur_lte->msg_list) &&
1089 (msg = container_of(cur_lte->msg_list.next,
1093 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1094 if (msg->begin_chunk == 0) {
1095 DEBUG2("Begin chunk tab");
1097 // This is the first set of chunks. Leave space
1098 // for the chunk table in the output file.
1099 off_t cur_offset = ftello(out_fp);
1100 if (cur_offset == -1) {
1101 ret = WIMLIB_ERR_WRITE;
1104 ret = begin_wim_resource_chunk_tab(cur_lte,
1112 // Write the compressed chunks from the message.
1113 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1117 list_del(&msg->list);
1119 // This message is available to use for different chunks
1121 list_add(&msg->list, &available_msgs);
1123 // Was this the last chunk of the stream? If so, finish
1125 if (list_empty(&cur_lte->msg_list) &&
1126 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1128 DEBUG2("Finish wim chunk tab");
1130 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1136 if (res_csize >= wim_resource_size(cur_lte)) {
1137 /* Oops! We compressed the resource to
1138 * larger than the original size. Write
1139 * the resource uncompressed instead. */
1140 ret = write_uncompressed_resource_and_truncate(
1143 cur_chunk_tab->file_offset,
1144 &cur_lte->output_resource_entry);
1148 cur_lte->output_resource_entry.size =
1151 cur_lte->output_resource_entry.original_size =
1152 cur_lte->resource_entry.original_size;
1154 cur_lte->output_resource_entry.offset =
1155 cur_chunk_tab->file_offset;
1157 cur_lte->output_resource_entry.flags =
1158 cur_lte->resource_entry.flags |
1159 WIM_RESHDR_FLAG_COMPRESSED;
1162 progress->write_streams.completed_bytes +=
1163 wim_resource_size(cur_lte);
1164 progress->write_streams.completed_streams++;
1166 if (progress_func) {
1167 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1171 FREE(cur_chunk_tab);
1172 cur_chunk_tab = NULL;
1174 struct list_head *next = cur_lte->staging_list.next;
1175 list_del(&cur_lte->staging_list);
1177 if (next == &outstanding_resources)
1180 cur_lte = container_of(cur_lte->staging_list.next,
1181 struct wim_lookup_table_entry,
1184 // Since we just finished writing a stream,
1185 // write any streams that have been added to the
1186 // my_resources list for direct writing by the
1187 // main thread (e.g. resources that don't need
1188 // to be compressed because the desired
1189 // compression type is the same as the previous
1190 // compression type).
1191 ret = do_write_stream_list(&my_resources,
1204 if (ret == WIMLIB_ERR_NOMEM) {
1205 ERROR("Could not allocate enough memory for "
1206 "multi-threaded compression");
1211 end_wim_resource_read(next_lte, ni);
1213 end_wim_resource_read(next_lte);
1218 ret = do_write_stream_list(&my_resources, out_fp,
1219 out_ctype, progress_func,
1223 size_t num_available_msgs = 0;
1224 struct list_head *cur;
1226 list_for_each(cur, &available_msgs) {
1227 num_available_msgs++;
1230 while (num_available_msgs < num_messages) {
1231 shared_queue_get(compressed_res_queue);
1232 num_available_msgs++;
1238 for (size_t i = 0; i < num_messages; i++) {
1239 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1240 FREE(msgs[i].compressed_chunks[j]);
1241 FREE(msgs[i].uncompressed_chunks[j]);
1247 FREE(cur_chunk_tab);
1252 get_default_num_threads()
1255 return win32_get_number_of_processors();
1257 return sysconf(_SC_NPROCESSORS_ONLN);
1262 write_stream_list_parallel(struct list_head *stream_list,
1266 unsigned num_threads,
1267 wimlib_progress_func_t progress_func,
1268 union wimlib_progress_info *progress)
1271 struct shared_queue res_to_compress_queue;
1272 struct shared_queue compressed_res_queue;
1273 pthread_t *compressor_threads = NULL;
1275 if (num_threads == 0) {
1276 long nthreads = get_default_num_threads();
1277 if (nthreads < 1 || nthreads > UINT_MAX) {
1278 WARNING("Could not determine number of processors! Assuming 1");
1281 num_threads = nthreads;
1285 progress->write_streams.num_threads = num_threads;
1286 wimlib_assert(stream_list->next != stream_list);
1288 static const double MESSAGES_PER_THREAD = 2.0;
1289 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1291 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1293 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1297 ret = shared_queue_init(&compressed_res_queue, queue_size);
1299 goto out_destroy_res_to_compress_queue;
1301 struct compressor_thread_params params;
1302 params.res_to_compress_queue = &res_to_compress_queue;
1303 params.compressed_res_queue = &compressed_res_queue;
1304 params.compress = get_compress_func(out_ctype);
1306 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1307 if (!compressor_threads) {
1308 ret = WIMLIB_ERR_NOMEM;
1309 goto out_destroy_compressed_res_queue;
1312 for (unsigned i = 0; i < num_threads; i++) {
1313 DEBUG("pthread_create thread %u", i);
1314 ret = pthread_create(&compressor_threads[i], NULL,
1315 compressor_thread_proc, ¶ms);
1318 ERROR_WITH_ERRNO("Failed to create compressor "
1326 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1328 ret = main_writer_thread_proc(stream_list,
1331 &res_to_compress_queue,
1332 &compressed_res_queue,
1338 for (unsigned i = 0; i < num_threads; i++)
1339 shared_queue_put(&res_to_compress_queue, NULL);
1341 for (unsigned i = 0; i < num_threads; i++) {
1342 if (pthread_join(compressor_threads[i], NULL)) {
1343 WARNING_WITH_ERRNO("Failed to join compressor "
1347 FREE(compressor_threads);
1348 out_destroy_compressed_res_queue:
1349 shared_queue_destroy(&compressed_res_queue);
1350 out_destroy_res_to_compress_queue:
1351 shared_queue_destroy(&res_to_compress_queue);
1352 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1355 WARNING("Falling back to single-threaded compression");
1356 return write_stream_list_serial(stream_list,
1367 * Write a list of streams to a WIM (@out_fp) using the compression type
1368 * @out_ctype and up to @num_threads compressor threads.
1371 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1372 int out_ctype, int write_flags,
1373 unsigned num_threads,
1374 wimlib_progress_func_t progress_func)
1376 struct wim_lookup_table_entry *lte;
1377 size_t num_streams = 0;
1378 u64 total_bytes = 0;
1379 u64 total_compression_bytes = 0;
1380 union wimlib_progress_info progress;
1382 list_for_each_entry(lte, stream_list, staging_list) {
1384 total_bytes += wim_resource_size(lte);
1385 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1386 && (wim_resource_compression_type(lte) != out_ctype ||
1387 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1389 total_compression_bytes += wim_resource_size(lte);
1392 progress.write_streams.total_bytes = total_bytes;
1393 progress.write_streams.total_streams = num_streams;
1394 progress.write_streams.completed_bytes = 0;
1395 progress.write_streams.completed_streams = 0;
1396 progress.write_streams.num_threads = num_threads;
1397 progress.write_streams.compression_type = out_ctype;
1399 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1400 if (total_compression_bytes >= 1000000 && num_threads != 1)
1401 return write_stream_list_parallel(stream_list,
1410 return write_stream_list_serial(stream_list,
1418 struct lte_overwrite_prepare_args {
1421 struct list_head *stream_list;
1425 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1427 struct lte_overwrite_prepare_args *args = arg;
1429 if (lte->resource_location == RESOURCE_IN_WIM &&
1430 lte->wim == args->wim &&
1431 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1433 #ifdef ENABLE_ERROR_MESSAGES
1434 ERROR("The following resource is after the XML data:");
1435 print_lookup_table_entry(lte, stderr);
1437 return WIMLIB_ERR_RESOURCE_ORDER;
1440 lte->out_refcnt = lte->refcnt;
1441 memcpy(<e->output_resource_entry, <e->resource_entry,
1442 sizeof(struct resource_entry));
1443 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1444 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1445 list_add(<e->staging_list, args->stream_list);
1450 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1451 struct list_head *stream_list)
1453 struct lte_overwrite_prepare_args args = {
1455 .end_offset = end_offset,
1456 .stream_list = stream_list,
1460 for (int i = 0; i < wim->hdr.image_count; i++) {
1461 ret = lte_overwrite_prepare(wim->image_metadata[i].metadata_lte,
1466 return for_lookup_table_entry(wim->lookup_table,
1467 lte_overwrite_prepare, &args);
1471 inode_find_streams_to_write(struct wim_inode *inode,
1472 struct wim_lookup_table *table,
1473 struct list_head *stream_list)
1475 struct wim_lookup_table_entry *lte;
1476 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1477 lte = inode_stream_lte(inode, i, table);
1479 if (lte->out_refcnt == 0)
1480 list_add_tail(<e->staging_list, stream_list);
1481 lte->out_refcnt += inode->i_nlink;
1488 image_find_streams_to_write(WIMStruct *w)
1490 struct wim_inode *inode;
1491 struct hlist_node *cur;
1492 struct hlist_head *inode_list;
1494 inode_list = &wim_get_current_image_metadata(w)->inode_list;
1495 hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1496 inode_find_streams_to_write(inode, w->lookup_table,
1497 (struct list_head*)w->private);
1503 write_wim_streams(WIMStruct *w, int image, int write_flags,
1504 unsigned num_threads,
1505 wimlib_progress_func_t progress_func)
1508 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1509 LIST_HEAD(stream_list);
1510 w->private = &stream_list;
1511 for_image(w, image, image_find_streams_to_write);
1512 return write_stream_list(&stream_list, w->out_fp,
1513 wimlib_get_compression_type(w), write_flags,
1514 num_threads, progress_func);
1518 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1519 * table (optional), then overwrite the WIM header.
1521 * write_flags is a bitwise OR of the following:
1523 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1524 * Include an integrity table.
1526 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1527 * Show progress information when (if) writing the integrity table.
1529 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1530 * Don't write the lookup table.
1532 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1533 * When (if) writing the integrity table, re-use entries from the
1534 * existing integrity table, if possible.
1536 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1537 * After writing the XML data but before writing the integrity
1538 * table, write a temporary WIM header and flush the stream so that
1539 * the WIM is less likely to become corrupted upon abrupt program
1542 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1543 * fsync() the output file before closing it.
1547 finish_write(WIMStruct *w, int image, int write_flags,
1548 wimlib_progress_func_t progress_func)
1551 struct wim_header hdr;
1552 FILE *out = w->out_fp;
1554 /* @hdr will be the header for the new WIM. First copy all the data
1555 * from the header in the WIMStruct; then set all the fields that may
1556 * have changed, including the resource entries, boot index, and image
1558 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1560 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1561 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1566 ret = write_xml_data(w->wim_info, image, out,
1567 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1568 wim_info_get_total_bytes(w->wim_info) : 0,
1569 &hdr.xml_res_entry);
1573 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1574 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1575 struct wim_header checkpoint_hdr;
1576 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1577 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1578 if (fseeko(out, 0, SEEK_SET) != 0) {
1579 ERROR_WITH_ERRNO("Failed to seek to beginning "
1580 "of WIM being written");
1581 ret = WIMLIB_ERR_WRITE;
1584 ret = write_header(&checkpoint_hdr, out);
1588 if (fflush(out) != 0) {
1589 ERROR_WITH_ERRNO("Can't write data to WIM");
1590 ret = WIMLIB_ERR_WRITE;
1594 if (fseeko(out, 0, SEEK_END) != 0) {
1595 ERROR_WITH_ERRNO("Failed to seek to end "
1596 "of WIM being written");
1597 ret = WIMLIB_ERR_WRITE;
1602 off_t old_lookup_table_end;
1603 off_t new_lookup_table_end;
1604 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1605 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1606 w->hdr.lookup_table_res_entry.size;
1608 old_lookup_table_end = 0;
1610 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1611 hdr.lookup_table_res_entry.size;
1613 ret = write_integrity_table(out,
1615 new_lookup_table_end,
1616 old_lookup_table_end,
1621 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1625 * In the WIM header, there is room for the resource entry for a
1626 * metadata resource labeled as the "boot metadata". This entry should
1627 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1628 * it should be a copy of the resource entry for the image that is
1629 * marked as bootable. This is not well documented...
1632 /* Set image count and boot index correctly for single image writes */
1633 if (image != WIMLIB_ALL_IMAGES) {
1634 hdr.image_count = 1;
1635 if (hdr.boot_idx == image)
1641 if (hdr.boot_idx == 0) {
1642 memset(&hdr.boot_metadata_res_entry, 0,
1643 sizeof(struct resource_entry));
1645 memcpy(&hdr.boot_metadata_res_entry,
1647 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1648 sizeof(struct resource_entry));
1651 if (fseeko(out, 0, SEEK_SET) != 0) {
1652 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1654 ret = WIMLIB_ERR_WRITE;
1658 ret = write_header(&hdr, out);
1662 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1663 if (fflush(out) != 0
1664 || fsync(fileno(out)) != 0)
1666 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1667 ret = WIMLIB_ERR_WRITE;
1671 if (fclose(out) != 0) {
1672 ERROR_WITH_ERRNO("Failed to close the WIM file");
1674 ret = WIMLIB_ERR_WRITE;
1680 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1682 lock_wim(WIMStruct *w, FILE *fp)
1685 if (fp && !w->wim_locked) {
1686 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1688 if (errno == EWOULDBLOCK) {
1689 ERROR("`%"TS"' is already being modified or has been "
1690 "mounted read-write\n"
1691 " by another process!", w->filename);
1692 ret = WIMLIB_ERR_ALREADY_LOCKED;
1694 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1707 open_wim_writable(WIMStruct *w, const tchar *path,
1708 bool trunc, bool also_readable)
1719 wimlib_assert(w->out_fp == NULL);
1720 w->out_fp = tfopen(path, mode);
1724 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1725 return WIMLIB_ERR_OPEN;
1731 close_wim_writable(WIMStruct *w)
1734 if (fclose(w->out_fp) != 0) {
1735 WARNING_WITH_ERRNO("Failed to close output WIM");
1741 /* Open file stream and write dummy header for WIM. */
1743 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1746 ret = open_wim_writable(w, path, true,
1747 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1750 /* Write dummy header. It will be overwritten later. */
1751 return write_header(&w->hdr, w->out_fp);
1754 /* Writes a stand-alone WIM to a file. */
1756 wimlib_write(WIMStruct *w, const tchar *path,
1757 int image, int write_flags, unsigned num_threads,
1758 wimlib_progress_func_t progress_func)
1763 return WIMLIB_ERR_INVALID_PARAM;
1765 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1767 if (image != WIMLIB_ALL_IMAGES &&
1768 (image < 1 || image > w->hdr.image_count))
1769 return WIMLIB_ERR_INVALID_IMAGE;
1771 if (w->hdr.total_parts != 1) {
1772 ERROR("Cannot call wimlib_write() on part of a split WIM");
1773 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1776 ret = begin_write(w, path, write_flags);
1780 ret = write_wim_streams(w, image, write_flags, num_threads,
1786 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1788 ret = for_image(w, image, write_metadata_resource);
1793 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1795 ret = finish_write(w, image, write_flags, progress_func);
1797 close_wim_writable(w);
1798 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1803 any_images_modified(WIMStruct *w)
1805 for (int i = 0; i < w->hdr.image_count; i++)
1806 if (w->image_metadata[i].modified)
1812 * Overwrite a WIM, possibly appending streams to it.
1814 * A WIM looks like (or is supposed to look like) the following:
1816 * Header (212 bytes)
1817 * Streams and metadata resources (variable size)
1818 * Lookup table (variable size)
1819 * XML data (variable size)
1820 * Integrity table (optional) (variable size)
1822 * If we are not adding any streams or metadata resources, the lookup table is
1823 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1824 * header. This operation is potentially unsafe if the program is abruptly
1825 * terminated while the XML data or integrity table are being overwritten, but
1826 * before the new header has been written. To partially alleviate this problem,
1827 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1828 * finish_write() to cause a temporary WIM header to be written after the XML
1829 * data has been written. This may prevent the WIM from becoming corrupted if
1830 * the program is terminated while the integrity table is being calculated (but
1831 * no guarantees, due to write re-ordering...).
1833 * If we are adding new streams or images (metadata resources), the lookup table
1834 * needs to be changed, and those streams need to be written. In this case, we
1835 * try to perform a safe update of the WIM file by writing the streams *after*
1836 * the end of the previous WIM, then writing the new lookup table, XML data, and
1837 * (optionally) integrity table following the new streams. This will produce a
1838 * layout like the following:
1840 * Header (212 bytes)
1841 * (OLD) Streams and metadata resources (variable size)
1842 * (OLD) Lookup table (variable size)
1843 * (OLD) XML data (variable size)
1844 * (OLD) Integrity table (optional) (variable size)
1845 * (NEW) Streams and metadata resources (variable size)
1846 * (NEW) Lookup table (variable size)
1847 * (NEW) XML data (variable size)
1848 * (NEW) Integrity table (optional) (variable size)
1850 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1851 * the header is overwritten to point to the new lookup table, XML data, and
1852 * integrity table, to produce the following layout:
1854 * Header (212 bytes)
1855 * Streams and metadata resources (variable size)
1856 * Nothing (variable size)
1857 * More Streams and metadata resources (variable size)
1858 * Lookup table (variable size)
1859 * XML data (variable size)
1860 * Integrity table (optional) (variable size)
1862 * This method allows an image to be appended to a large WIM very quickly, and
1863 * is is crash-safe except in the case of write re-ordering, but the
1864 * disadvantage is that a small hole is left in the WIM where the old lookup
1865 * table, xml data, and integrity table were. (These usually only take up a
1866 * small amount of space compared to the streams, however.)
1869 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1870 unsigned num_threads,
1871 wimlib_progress_func_t progress_func)
1874 struct list_head stream_list;
1876 bool found_modified_image;
1878 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1880 /* Make sure that the integrity table (if present) is after the XML
1881 * data, and that there are no stream resources, metadata resources, or
1882 * lookup tables after the XML data. Otherwise, these data would be
1884 if (w->hdr.integrity.offset != 0 &&
1885 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1886 ERROR("Didn't expect the integrity table to be before the XML data");
1887 return WIMLIB_ERR_RESOURCE_ORDER;
1890 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1891 ERROR("Didn't expect the lookup table to be after the XML data");
1892 return WIMLIB_ERR_RESOURCE_ORDER;
1896 if (w->hdr.integrity.offset)
1897 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1899 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1901 if (!w->deletion_occurred && !any_images_modified(w)) {
1902 /* If no images have been modified and no images have been
1903 * deleted, a new lookup table does not need to be written. */
1904 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1905 w->hdr.lookup_table_res_entry.size;
1906 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1907 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1909 INIT_LIST_HEAD(&stream_list);
1910 ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1914 ret = open_wim_writable(w, w->filename, false,
1915 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1919 ret = lock_wim(w, w->out_fp);
1926 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1927 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1931 return WIMLIB_ERR_WRITE;
1934 if (!list_empty(&stream_list)) {
1935 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1937 ret = write_stream_list(&stream_list, w->out_fp,
1938 wimlib_get_compression_type(w),
1939 write_flags, num_threads,
1944 DEBUG("No new streams were added");
1947 found_modified_image = false;
1948 for (int i = 0; i < w->hdr.image_count; i++) {
1949 if (!found_modified_image)
1950 found_modified_image = w->image_metadata[i].modified;
1951 if (found_modified_image) {
1952 select_wim_image(w, i + 1);
1953 ret = write_metadata_resource(w);
1958 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1959 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1962 close_wim_writable(w);
1963 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1964 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1965 w->filename, old_wim_end);
1966 /* Return value of truncate() is ignored because this is already
1968 (void)ttruncate(w->filename, old_wim_end);
1975 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1976 unsigned num_threads,
1977 wimlib_progress_func_t progress_func)
1979 size_t wim_name_len;
1982 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1984 /* Write the WIM to a temporary file in the same directory as the
1986 wim_name_len = tstrlen(w->filename);
1987 tchar tmpfile[wim_name_len + 10];
1988 tmemcpy(tmpfile, w->filename, wim_name_len);
1989 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1990 tmpfile[wim_name_len + 9] = T('\0');
1992 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1993 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1994 num_threads, progress_func);
1996 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2000 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2003 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2004 * specified to CreateFile(). The WIM was opened with fopen(), which
2005 * didn't provided this flag to CreateFile, so the handle must be closed
2006 * before executing the rename(). */
2007 if (w->fp != NULL) {
2013 /* Rename the new file to the old file .*/
2014 if (trename(tmpfile, w->filename) != 0) {
2015 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2016 tmpfile, w->filename);
2017 ret = WIMLIB_ERR_RENAME;
2021 if (progress_func) {
2022 union wimlib_progress_info progress;
2023 progress.rename.from = tmpfile;
2024 progress.rename.to = w->filename;
2025 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2028 /* Close the original WIM file that was opened for reading. */
2029 if (w->fp != NULL) {
2034 /* Re-open the WIM read-only. */
2035 w->fp = tfopen(w->filename, T("rb"));
2036 if (w->fp == NULL) {
2037 ret = WIMLIB_ERR_REOPEN;
2038 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2045 /* Remove temporary file. */
2046 if (tunlink(tmpfile) != 0)
2047 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2052 * Writes a WIM file to the original file that it was read from, overwriting it.
2055 wimlib_overwrite(WIMStruct *w, int write_flags,
2056 unsigned num_threads,
2057 wimlib_progress_func_t progress_func)
2059 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2062 return WIMLIB_ERR_NO_FILENAME;
2064 if (w->hdr.total_parts != 1) {
2065 ERROR("Cannot modify a split WIM");
2066 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2069 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2070 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2073 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2075 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2076 WARNING("Falling back to re-building entire WIM");
2080 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,