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_streams_progress(union wimlib_progress_info *progress,
743 wimlib_progress_func_t progress_func,
746 progress->write_streams.completed_bytes += size_added;
747 progress->write_streams.completed_streams++;
749 progress->write_streams.completed_bytes >= progress->write_streams._private)
751 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
753 if (progress->write_streams._private == progress->write_streams.total_bytes) {
754 progress->write_streams._private = ~0;
756 progress->write_streams._private =
757 min(progress->write_streams.total_bytes,
758 progress->write_streams.completed_bytes +
759 progress->write_streams.total_bytes / 100);
765 do_write_stream_list(struct list_head *my_resources,
768 wimlib_progress_func_t progress_func,
769 union wimlib_progress_info *progress,
770 int write_resource_flags)
773 struct wim_lookup_table_entry *lte, *tmp;
775 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
776 ret = write_wim_resource(lte,
779 <e->output_resource_entry,
780 write_resource_flags);
783 list_del(<e->staging_list);
785 do_write_streams_progress(progress,
787 wim_resource_size(lte));
793 write_stream_list_serial(struct list_head *stream_list,
797 wimlib_progress_func_t progress_func,
798 union wimlib_progress_info *progress)
800 int write_resource_flags;
802 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
803 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
805 write_resource_flags = 0;
806 progress->write_streams.num_threads = 1;
808 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
809 return do_write_stream_list(stream_list, out_fp,
810 out_ctype, progress_func,
811 progress, write_resource_flags);
814 #ifdef ENABLE_MULTITHREADED_COMPRESSION
816 write_wim_chunks(struct message *msg, FILE *out_fp,
817 struct chunk_table *chunk_tab)
819 for (unsigned i = 0; i < msg->num_chunks; i++) {
820 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
822 DEBUG2("Write wim chunk %u of %u (csize = %u)",
823 i, msg->num_chunks, chunk_csize);
825 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
828 ERROR_WITH_ERRNO("Failed to write WIM chunk");
829 return WIMLIB_ERR_WRITE;
832 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
833 chunk_tab->cur_offset += chunk_csize;
839 * This function is executed by the main thread when the resources are being
840 * compressed in parallel. The main thread is in change of all reading of the
841 * uncompressed data and writing of the compressed data. The compressor threads
842 * *only* do compression from/to in-memory buffers.
844 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
845 * chunks of compressed data to compress, represented in a `struct message'.
846 * Each message is passed from the main thread to a worker thread through the
847 * res_to_compress_queue, and it is passed back through the
848 * compressed_res_queue.
851 main_writer_thread_proc(struct list_head *stream_list,
854 struct shared_queue *res_to_compress_queue,
855 struct shared_queue *compressed_res_queue,
858 wimlib_progress_func_t progress_func,
859 union wimlib_progress_info *progress)
862 struct chunk_table *cur_chunk_tab = NULL;
863 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
864 struct wim_lookup_table_entry *next_lte = NULL;
866 // Initially, all the messages are available to use.
867 LIST_HEAD(available_msgs);
870 ret = WIMLIB_ERR_NOMEM;
874 for (size_t i = 0; i < num_messages; i++)
875 list_add(&msgs[i].list, &available_msgs);
877 // outstanding_resources is the list of resources that currently have
878 // had chunks sent off for compression.
880 // The first stream in outstanding_resources is the stream that is
881 // currently being written (cur_lte).
883 // The last stream in outstanding_resources is the stream that is
884 // currently being read and chunks fed to the compressor threads
887 // Depending on the number of threads and the sizes of the resource,
888 // the outstanding streams list may contain streams between cur_lte and
889 // next_lte that have all their chunks compressed or being compressed,
890 // but haven't been written yet.
892 LIST_HEAD(outstanding_resources);
893 struct list_head *next_resource = stream_list->next;
895 u64 next_num_chunks = 0;
897 // As in write_wim_resource(), each resource we read is checksummed.
898 SHA_CTX next_sha_ctx;
899 u8 next_hash[SHA1_HASH_SIZE];
901 // Resources that don't need any chunks compressed are added to this
902 // list and written directly by the main thread.
903 LIST_HEAD(my_resources);
905 struct wim_lookup_table_entry *cur_lte = NULL;
909 ntfs_inode *ni = NULL;
912 DEBUG("Initializing buffers for uncompressed "
913 "and compressed data (%zu bytes needed)",
914 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
916 // Pre-allocate all the buffers that will be needed to do the chunk
918 for (size_t i = 0; i < num_messages; i++) {
919 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
920 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
922 // The extra 8 bytes is because longest_match() in
923 // lz77.c may read a little bit off the end of the
924 // uncompressed data. It doesn't need to be
925 // initialized--- we really just need to avoid accessing
927 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
928 if (msgs[i].compressed_chunks[j] == NULL ||
929 msgs[i].uncompressed_chunks[j] == NULL)
931 ret = WIMLIB_ERR_NOMEM;
937 // This loop is executed until all resources have been written, except
938 // possibly a few that have been added to the @my_resources list for
941 // Send chunks to the compressor threads until either (a) there
942 // are no more messages available since they were all sent off,
943 // or (b) there are no more resources that need to be
945 while (!list_empty(&available_msgs)) {
946 if (next_chunk == next_num_chunks) {
947 // If next_chunk == next_num_chunks, there are
948 // no more chunks to write in the current
949 // stream. So, check the SHA1 message digest of
950 // the stream that was just finished (unless
951 // next_lte == NULL, which is the case the very
952 // first time this loop is entered, and also
953 // near the very end of the compression when
954 // there are no more streams.) Then, advance to
955 // the next stream (if there is one).
956 if (next_lte != NULL) {
958 end_wim_resource_read(next_lte, ni);
961 end_wim_resource_read(next_lte);
963 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
965 sha1_final(next_hash, &next_sha_ctx);
966 if (!hashes_equal(next_lte->hash, next_hash)) {
967 ERROR("WIM resource has incorrect hash!");
968 if (next_lte->resource_location ==
969 RESOURCE_IN_FILE_ON_DISK)
971 ERROR("We were reading it from `%"TS"'; "
972 "maybe it changed while we were "
974 next_lte->file_on_disk);
976 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
981 // Advance to the next resource.
983 // If the next resource needs no compression, just write
984 // it with this thread (not now though--- we could be in
985 // the middle of writing another resource.) Keep doing
986 // this until we either get to the end of the resources
987 // list, or we get to a resource that needs compression.
989 if (next_resource == stream_list) {
990 // No more resources to send for
995 next_lte = container_of(next_resource,
996 struct wim_lookup_table_entry,
998 next_resource = next_resource->next;
999 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
1000 && wim_resource_compression_type(next_lte) == out_ctype)
1001 || wim_resource_size(next_lte) == 0)
1003 list_add_tail(&next_lte->staging_list,
1006 list_add_tail(&next_lte->staging_list,
1007 &outstanding_resources);
1009 next_num_chunks = wim_resource_chunks(next_lte);
1010 sha1_init(&next_sha_ctx);
1011 INIT_LIST_HEAD(&next_lte->msg_list);
1013 ret = prepare_resource_for_read(next_lte, &ni);
1015 ret = prepare_resource_for_read(next_lte);
1020 if (cur_lte == NULL) {
1021 // Set cur_lte for the
1030 if (next_lte == NULL) {
1031 // No more resources to send for compression
1035 // Get a message from the available messages
1037 msg = container_of(available_msgs.next,
1041 // ... and delete it from the available messages
1043 list_del(&msg->list);
1045 // Initialize the message with the chunks to
1047 msg->num_chunks = min(next_num_chunks - next_chunk,
1048 MAX_CHUNKS_PER_MSG);
1049 msg->lte = next_lte;
1050 msg->complete = false;
1051 msg->begin_chunk = next_chunk;
1053 unsigned size = WIM_CHUNK_SIZE;
1054 for (unsigned i = 0; i < msg->num_chunks; i++) {
1056 // Read chunk @next_chunk of the stream into the
1057 // message so that a compressor thread can
1060 if (next_chunk == next_num_chunks - 1) {
1061 size = MODULO_NONZERO(wim_resource_size(next_lte),
1065 DEBUG2("Read resource (size=%u, offset=%zu)",
1066 size, next_chunk * WIM_CHUNK_SIZE);
1068 msg->uncompressed_chunk_sizes[i] = size;
1070 ret = read_wim_resource(next_lte,
1071 msg->uncompressed_chunks[i],
1073 next_chunk * WIM_CHUNK_SIZE,
1077 sha1_update(&next_sha_ctx,
1078 msg->uncompressed_chunks[i], size);
1082 // Send the compression request
1083 list_add_tail(&msg->list, &next_lte->msg_list);
1084 shared_queue_put(res_to_compress_queue, msg);
1085 DEBUG2("Compression request sent");
1088 // If there are no outstanding resources, there are no more
1089 // resources that need to be written.
1090 if (list_empty(&outstanding_resources)) {
1095 // Get the next message from the queue and process it.
1096 // The message will contain 1 or more data chunks that have been
1098 msg = shared_queue_get(compressed_res_queue);
1099 msg->complete = true;
1101 // Is this the next chunk in the current resource? If it's not
1102 // (i.e., an earlier chunk in a same or different resource
1103 // hasn't been compressed yet), do nothing, and keep this
1104 // message around until all earlier chunks are received.
1106 // Otherwise, write all the chunks we can.
1107 while (cur_lte != NULL &&
1108 !list_empty(&cur_lte->msg_list) &&
1109 (msg = container_of(cur_lte->msg_list.next,
1113 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1114 if (msg->begin_chunk == 0) {
1115 DEBUG2("Begin chunk tab");
1117 // This is the first set of chunks. Leave space
1118 // for the chunk table in the output file.
1119 off_t cur_offset = ftello(out_fp);
1120 if (cur_offset == -1) {
1121 ret = WIMLIB_ERR_WRITE;
1124 ret = begin_wim_resource_chunk_tab(cur_lte,
1132 // Write the compressed chunks from the message.
1133 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1137 list_del(&msg->list);
1139 // This message is available to use for different chunks
1141 list_add(&msg->list, &available_msgs);
1143 // Was this the last chunk of the stream? If so, finish
1145 if (list_empty(&cur_lte->msg_list) &&
1146 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1148 DEBUG2("Finish wim chunk tab");
1150 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1156 if (res_csize >= wim_resource_size(cur_lte)) {
1157 /* Oops! We compressed the resource to
1158 * larger than the original size. Write
1159 * the resource uncompressed instead. */
1160 ret = write_uncompressed_resource_and_truncate(
1163 cur_chunk_tab->file_offset,
1164 &cur_lte->output_resource_entry);
1168 cur_lte->output_resource_entry.size =
1171 cur_lte->output_resource_entry.original_size =
1172 cur_lte->resource_entry.original_size;
1174 cur_lte->output_resource_entry.offset =
1175 cur_chunk_tab->file_offset;
1177 cur_lte->output_resource_entry.flags =
1178 cur_lte->resource_entry.flags |
1179 WIM_RESHDR_FLAG_COMPRESSED;
1182 do_write_streams_progress(progress, progress_func,
1183 wim_resource_size(cur_lte));
1185 FREE(cur_chunk_tab);
1186 cur_chunk_tab = NULL;
1188 struct list_head *next = cur_lte->staging_list.next;
1189 list_del(&cur_lte->staging_list);
1191 if (next == &outstanding_resources)
1194 cur_lte = container_of(cur_lte->staging_list.next,
1195 struct wim_lookup_table_entry,
1198 // Since we just finished writing a stream,
1199 // write any streams that have been added to the
1200 // my_resources list for direct writing by the
1201 // main thread (e.g. resources that don't need
1202 // to be compressed because the desired
1203 // compression type is the same as the previous
1204 // compression type).
1205 ret = do_write_stream_list(&my_resources,
1218 if (ret == WIMLIB_ERR_NOMEM) {
1219 ERROR("Could not allocate enough memory for "
1220 "multi-threaded compression");
1225 end_wim_resource_read(next_lte, ni);
1227 end_wim_resource_read(next_lte);
1232 ret = do_write_stream_list(&my_resources, out_fp,
1233 out_ctype, progress_func,
1237 size_t num_available_msgs = 0;
1238 struct list_head *cur;
1240 list_for_each(cur, &available_msgs) {
1241 num_available_msgs++;
1244 while (num_available_msgs < num_messages) {
1245 shared_queue_get(compressed_res_queue);
1246 num_available_msgs++;
1252 for (size_t i = 0; i < num_messages; i++) {
1253 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1254 FREE(msgs[i].compressed_chunks[j]);
1255 FREE(msgs[i].uncompressed_chunks[j]);
1261 FREE(cur_chunk_tab);
1266 get_default_num_threads()
1269 return win32_get_number_of_processors();
1271 return sysconf(_SC_NPROCESSORS_ONLN);
1276 write_stream_list_parallel(struct list_head *stream_list,
1280 unsigned num_threads,
1281 wimlib_progress_func_t progress_func,
1282 union wimlib_progress_info *progress)
1285 struct shared_queue res_to_compress_queue;
1286 struct shared_queue compressed_res_queue;
1287 pthread_t *compressor_threads = NULL;
1289 if (num_threads == 0) {
1290 long nthreads = get_default_num_threads();
1291 if (nthreads < 1 || nthreads > UINT_MAX) {
1292 WARNING("Could not determine number of processors! Assuming 1");
1295 num_threads = nthreads;
1299 progress->write_streams.num_threads = num_threads;
1300 wimlib_assert(stream_list->next != stream_list);
1302 static const double MESSAGES_PER_THREAD = 2.0;
1303 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1305 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1307 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1311 ret = shared_queue_init(&compressed_res_queue, queue_size);
1313 goto out_destroy_res_to_compress_queue;
1315 struct compressor_thread_params params;
1316 params.res_to_compress_queue = &res_to_compress_queue;
1317 params.compressed_res_queue = &compressed_res_queue;
1318 params.compress = get_compress_func(out_ctype);
1320 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1321 if (!compressor_threads) {
1322 ret = WIMLIB_ERR_NOMEM;
1323 goto out_destroy_compressed_res_queue;
1326 for (unsigned i = 0; i < num_threads; i++) {
1327 DEBUG("pthread_create thread %u", i);
1328 ret = pthread_create(&compressor_threads[i], NULL,
1329 compressor_thread_proc, ¶ms);
1332 ERROR_WITH_ERRNO("Failed to create compressor "
1340 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1342 ret = main_writer_thread_proc(stream_list,
1345 &res_to_compress_queue,
1346 &compressed_res_queue,
1352 for (unsigned i = 0; i < num_threads; i++)
1353 shared_queue_put(&res_to_compress_queue, NULL);
1355 for (unsigned i = 0; i < num_threads; i++) {
1356 if (pthread_join(compressor_threads[i], NULL)) {
1357 WARNING_WITH_ERRNO("Failed to join compressor "
1361 FREE(compressor_threads);
1362 out_destroy_compressed_res_queue:
1363 shared_queue_destroy(&compressed_res_queue);
1364 out_destroy_res_to_compress_queue:
1365 shared_queue_destroy(&res_to_compress_queue);
1366 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1369 WARNING("Falling back to single-threaded compression");
1370 return write_stream_list_serial(stream_list,
1381 * Write a list of streams to a WIM (@out_fp) using the compression type
1382 * @out_ctype and up to @num_threads compressor threads.
1385 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1386 int out_ctype, int write_flags,
1387 unsigned num_threads,
1388 wimlib_progress_func_t progress_func)
1390 struct wim_lookup_table_entry *lte;
1391 size_t num_streams = 0;
1392 u64 total_bytes = 0;
1393 u64 total_compression_bytes = 0;
1394 union wimlib_progress_info progress;
1396 list_for_each_entry(lte, stream_list, staging_list) {
1398 total_bytes += wim_resource_size(lte);
1399 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1400 && (wim_resource_compression_type(lte) != out_ctype ||
1401 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1403 total_compression_bytes += wim_resource_size(lte);
1406 progress.write_streams.total_bytes = total_bytes;
1407 progress.write_streams.total_streams = num_streams;
1408 progress.write_streams.completed_bytes = 0;
1409 progress.write_streams.completed_streams = 0;
1410 progress.write_streams.num_threads = num_threads;
1411 progress.write_streams.compression_type = out_ctype;
1412 progress.write_streams._private = 0;
1414 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1415 if (total_compression_bytes >= 1000000 && num_threads != 1)
1416 return write_stream_list_parallel(stream_list,
1425 return write_stream_list_serial(stream_list,
1433 struct lte_overwrite_prepare_args {
1436 struct list_head *stream_list;
1440 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1442 struct lte_overwrite_prepare_args *args = arg;
1444 if (lte->resource_location == RESOURCE_IN_WIM &&
1445 lte->wim == args->wim &&
1446 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1448 #ifdef ENABLE_ERROR_MESSAGES
1449 ERROR("The following resource is after the XML data:");
1450 print_lookup_table_entry(lte, stderr);
1452 return WIMLIB_ERR_RESOURCE_ORDER;
1455 lte->out_refcnt = lte->refcnt;
1456 memcpy(<e->output_resource_entry, <e->resource_entry,
1457 sizeof(struct resource_entry));
1458 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1459 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1460 list_add(<e->staging_list, args->stream_list);
1465 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1466 struct list_head *stream_list)
1468 struct lte_overwrite_prepare_args args = {
1470 .end_offset = end_offset,
1471 .stream_list = stream_list,
1475 for (int i = 0; i < wim->hdr.image_count; i++) {
1476 ret = lte_overwrite_prepare(wim->image_metadata[i].metadata_lte,
1481 return for_lookup_table_entry(wim->lookup_table,
1482 lte_overwrite_prepare, &args);
1486 inode_find_streams_to_write(struct wim_inode *inode,
1487 struct wim_lookup_table *table,
1488 struct list_head *stream_list)
1490 struct wim_lookup_table_entry *lte;
1491 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1492 lte = inode_stream_lte(inode, i, table);
1494 if (lte->out_refcnt == 0)
1495 list_add_tail(<e->staging_list, stream_list);
1496 lte->out_refcnt += inode->i_nlink;
1503 image_find_streams_to_write(WIMStruct *w)
1505 struct wim_inode *inode;
1506 struct hlist_node *cur;
1507 struct hlist_head *inode_list;
1509 inode_list = &wim_get_current_image_metadata(w)->inode_list;
1510 hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1511 inode_find_streams_to_write(inode, w->lookup_table,
1512 (struct list_head*)w->private);
1518 write_wim_streams(WIMStruct *w, int image, int write_flags,
1519 unsigned num_threads,
1520 wimlib_progress_func_t progress_func)
1523 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1524 LIST_HEAD(stream_list);
1525 w->private = &stream_list;
1526 for_image(w, image, image_find_streams_to_write);
1527 return write_stream_list(&stream_list, w->out_fp,
1528 wimlib_get_compression_type(w), write_flags,
1529 num_threads, progress_func);
1533 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1534 * table (optional), then overwrite the WIM header.
1536 * write_flags is a bitwise OR of the following:
1538 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1539 * Include an integrity table.
1541 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1542 * Show progress information when (if) writing the integrity table.
1544 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1545 * Don't write the lookup table.
1547 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1548 * When (if) writing the integrity table, re-use entries from the
1549 * existing integrity table, if possible.
1551 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1552 * After writing the XML data but before writing the integrity
1553 * table, write a temporary WIM header and flush the stream so that
1554 * the WIM is less likely to become corrupted upon abrupt program
1557 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1558 * fsync() the output file before closing it.
1562 finish_write(WIMStruct *w, int image, int write_flags,
1563 wimlib_progress_func_t progress_func)
1566 struct wim_header hdr;
1567 FILE *out = w->out_fp;
1569 /* @hdr will be the header for the new WIM. First copy all the data
1570 * from the header in the WIMStruct; then set all the fields that may
1571 * have changed, including the resource entries, boot index, and image
1573 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1575 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1576 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1581 ret = write_xml_data(w->wim_info, image, out,
1582 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1583 wim_info_get_total_bytes(w->wim_info) : 0,
1584 &hdr.xml_res_entry);
1588 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1589 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1590 struct wim_header checkpoint_hdr;
1591 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1592 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1593 if (fseeko(out, 0, SEEK_SET) != 0) {
1594 ERROR_WITH_ERRNO("Failed to seek to beginning "
1595 "of WIM being written");
1596 ret = WIMLIB_ERR_WRITE;
1599 ret = write_header(&checkpoint_hdr, out);
1603 if (fflush(out) != 0) {
1604 ERROR_WITH_ERRNO("Can't write data to WIM");
1605 ret = WIMLIB_ERR_WRITE;
1609 if (fseeko(out, 0, SEEK_END) != 0) {
1610 ERROR_WITH_ERRNO("Failed to seek to end "
1611 "of WIM being written");
1612 ret = WIMLIB_ERR_WRITE;
1617 off_t old_lookup_table_end;
1618 off_t new_lookup_table_end;
1619 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1620 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1621 w->hdr.lookup_table_res_entry.size;
1623 old_lookup_table_end = 0;
1625 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1626 hdr.lookup_table_res_entry.size;
1628 ret = write_integrity_table(out,
1630 new_lookup_table_end,
1631 old_lookup_table_end,
1636 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1640 * In the WIM header, there is room for the resource entry for a
1641 * metadata resource labeled as the "boot metadata". This entry should
1642 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1643 * it should be a copy of the resource entry for the image that is
1644 * marked as bootable. This is not well documented...
1647 /* Set image count and boot index correctly for single image writes */
1648 if (image != WIMLIB_ALL_IMAGES) {
1649 hdr.image_count = 1;
1650 if (hdr.boot_idx == image)
1656 if (hdr.boot_idx == 0) {
1657 memset(&hdr.boot_metadata_res_entry, 0,
1658 sizeof(struct resource_entry));
1660 memcpy(&hdr.boot_metadata_res_entry,
1662 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1663 sizeof(struct resource_entry));
1666 if (fseeko(out, 0, SEEK_SET) != 0) {
1667 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1669 ret = WIMLIB_ERR_WRITE;
1673 ret = write_header(&hdr, out);
1677 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1678 if (fflush(out) != 0
1679 || fsync(fileno(out)) != 0)
1681 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1682 ret = WIMLIB_ERR_WRITE;
1686 if (fclose(out) != 0) {
1687 ERROR_WITH_ERRNO("Failed to close the WIM file");
1689 ret = WIMLIB_ERR_WRITE;
1695 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1697 lock_wim(WIMStruct *w, FILE *fp)
1700 if (fp && !w->wim_locked) {
1701 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1703 if (errno == EWOULDBLOCK) {
1704 ERROR("`%"TS"' is already being modified or has been "
1705 "mounted read-write\n"
1706 " by another process!", w->filename);
1707 ret = WIMLIB_ERR_ALREADY_LOCKED;
1709 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1722 open_wim_writable(WIMStruct *w, const tchar *path,
1723 bool trunc, bool also_readable)
1734 wimlib_assert(w->out_fp == NULL);
1735 w->out_fp = tfopen(path, mode);
1739 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1740 return WIMLIB_ERR_OPEN;
1746 close_wim_writable(WIMStruct *w)
1749 if (fclose(w->out_fp) != 0) {
1750 WARNING_WITH_ERRNO("Failed to close output WIM");
1756 /* Open file stream and write dummy header for WIM. */
1758 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1761 ret = open_wim_writable(w, path, true,
1762 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1765 /* Write dummy header. It will be overwritten later. */
1766 return write_header(&w->hdr, w->out_fp);
1769 /* Writes a stand-alone WIM to a file. */
1771 wimlib_write(WIMStruct *w, const tchar *path,
1772 int image, int write_flags, unsigned num_threads,
1773 wimlib_progress_func_t progress_func)
1778 return WIMLIB_ERR_INVALID_PARAM;
1780 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1782 if (image != WIMLIB_ALL_IMAGES &&
1783 (image < 1 || image > w->hdr.image_count))
1784 return WIMLIB_ERR_INVALID_IMAGE;
1786 if (w->hdr.total_parts != 1) {
1787 ERROR("Cannot call wimlib_write() on part of a split WIM");
1788 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1791 ret = begin_write(w, path, write_flags);
1795 ret = write_wim_streams(w, image, write_flags, num_threads,
1801 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1803 ret = for_image(w, image, write_metadata_resource);
1808 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1810 ret = finish_write(w, image, write_flags, progress_func);
1812 close_wim_writable(w);
1813 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1818 any_images_modified(WIMStruct *w)
1820 for (int i = 0; i < w->hdr.image_count; i++)
1821 if (w->image_metadata[i].modified)
1827 * Overwrite a WIM, possibly appending streams to it.
1829 * A WIM looks like (or is supposed to look like) the following:
1831 * Header (212 bytes)
1832 * Streams and metadata resources (variable size)
1833 * Lookup table (variable size)
1834 * XML data (variable size)
1835 * Integrity table (optional) (variable size)
1837 * If we are not adding any streams or metadata resources, the lookup table is
1838 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1839 * header. This operation is potentially unsafe if the program is abruptly
1840 * terminated while the XML data or integrity table are being overwritten, but
1841 * before the new header has been written. To partially alleviate this problem,
1842 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1843 * finish_write() to cause a temporary WIM header to be written after the XML
1844 * data has been written. This may prevent the WIM from becoming corrupted if
1845 * the program is terminated while the integrity table is being calculated (but
1846 * no guarantees, due to write re-ordering...).
1848 * If we are adding new streams or images (metadata resources), the lookup table
1849 * needs to be changed, and those streams need to be written. In this case, we
1850 * try to perform a safe update of the WIM file by writing the streams *after*
1851 * the end of the previous WIM, then writing the new lookup table, XML data, and
1852 * (optionally) integrity table following the new streams. This will produce a
1853 * layout like the following:
1855 * Header (212 bytes)
1856 * (OLD) Streams and metadata resources (variable size)
1857 * (OLD) Lookup table (variable size)
1858 * (OLD) XML data (variable size)
1859 * (OLD) Integrity table (optional) (variable size)
1860 * (NEW) Streams and metadata resources (variable size)
1861 * (NEW) Lookup table (variable size)
1862 * (NEW) XML data (variable size)
1863 * (NEW) Integrity table (optional) (variable size)
1865 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1866 * the header is overwritten to point to the new lookup table, XML data, and
1867 * integrity table, to produce the following layout:
1869 * Header (212 bytes)
1870 * Streams and metadata resources (variable size)
1871 * Nothing (variable size)
1872 * More Streams and metadata resources (variable size)
1873 * Lookup table (variable size)
1874 * XML data (variable size)
1875 * Integrity table (optional) (variable size)
1877 * This method allows an image to be appended to a large WIM very quickly, and
1878 * is is crash-safe except in the case of write re-ordering, but the
1879 * disadvantage is that a small hole is left in the WIM where the old lookup
1880 * table, xml data, and integrity table were. (These usually only take up a
1881 * small amount of space compared to the streams, however.)
1884 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1885 unsigned num_threads,
1886 wimlib_progress_func_t progress_func)
1889 struct list_head stream_list;
1891 bool found_modified_image;
1893 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1895 /* Make sure that the integrity table (if present) is after the XML
1896 * data, and that there are no stream resources, metadata resources, or
1897 * lookup tables after the XML data. Otherwise, these data would be
1899 if (w->hdr.integrity.offset != 0 &&
1900 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1901 ERROR("Didn't expect the integrity table to be before the XML data");
1902 return WIMLIB_ERR_RESOURCE_ORDER;
1905 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1906 ERROR("Didn't expect the lookup table to be after the XML data");
1907 return WIMLIB_ERR_RESOURCE_ORDER;
1911 if (w->hdr.integrity.offset)
1912 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1914 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1916 if (!w->deletion_occurred && !any_images_modified(w)) {
1917 /* If no images have been modified and no images have been
1918 * deleted, a new lookup table does not need to be written. */
1919 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1920 w->hdr.lookup_table_res_entry.size;
1921 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1922 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1924 INIT_LIST_HEAD(&stream_list);
1925 ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1929 ret = open_wim_writable(w, w->filename, false,
1930 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1934 ret = lock_wim(w, w->out_fp);
1941 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1942 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1946 return WIMLIB_ERR_WRITE;
1949 if (!list_empty(&stream_list)) {
1950 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1952 ret = write_stream_list(&stream_list, w->out_fp,
1953 wimlib_get_compression_type(w),
1954 write_flags, num_threads,
1959 DEBUG("No new streams were added");
1962 found_modified_image = false;
1963 for (int i = 0; i < w->hdr.image_count; i++) {
1964 if (w->image_metadata[i].modified) {
1965 select_wim_image(w, i + 1);
1966 ret = write_metadata_resource(w);
1971 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1972 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1975 close_wim_writable(w);
1976 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1977 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1978 w->filename, old_wim_end);
1979 /* Return value of truncate() is ignored because this is already
1981 (void)ttruncate(w->filename, old_wim_end);
1988 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1989 unsigned num_threads,
1990 wimlib_progress_func_t progress_func)
1992 size_t wim_name_len;
1995 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1997 /* Write the WIM to a temporary file in the same directory as the
1999 wim_name_len = tstrlen(w->filename);
2000 tchar tmpfile[wim_name_len + 10];
2001 tmemcpy(tmpfile, w->filename, wim_name_len);
2002 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2003 tmpfile[wim_name_len + 9] = T('\0');
2005 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2006 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2007 num_threads, progress_func);
2009 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2013 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2016 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2017 * specified to CreateFile(). The WIM was opened with fopen(), which
2018 * didn't provided this flag to CreateFile, so the handle must be closed
2019 * before executing the rename(). */
2020 if (w->fp != NULL) {
2026 /* Rename the new file to the old file .*/
2027 if (trename(tmpfile, w->filename) != 0) {
2028 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2029 tmpfile, w->filename);
2030 ret = WIMLIB_ERR_RENAME;
2034 if (progress_func) {
2035 union wimlib_progress_info progress;
2036 progress.rename.from = tmpfile;
2037 progress.rename.to = w->filename;
2038 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2041 /* Close the original WIM file that was opened for reading. */
2042 if (w->fp != NULL) {
2047 /* Re-open the WIM read-only. */
2048 w->fp = tfopen(w->filename, T("rb"));
2049 if (w->fp == NULL) {
2050 ret = WIMLIB_ERR_REOPEN;
2051 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2058 /* Remove temporary file. */
2059 if (tunlink(tmpfile) != 0)
2060 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2065 * Writes a WIM file to the original file that it was read from, overwriting it.
2068 wimlib_overwrite(WIMStruct *w, int write_flags,
2069 unsigned num_threads,
2070 wimlib_progress_func_t progress_func)
2072 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2075 return WIMLIB_ERR_NO_FILENAME;
2077 if (w->hdr.total_parts != 1) {
2078 ERROR("Cannot modify a split WIM");
2079 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2082 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2083 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2086 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2088 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2089 WARNING("Falling back to re-building entire WIM");
2093 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,