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"
46 #ifdef ENABLE_MULTITHREADED_COMPRESSION
55 # include <ntfs-3g/attrib.h>
56 # include <ntfs-3g/inode.h>
57 # include <ntfs-3g/dir.h>
68 #if defined(__WIN32__) && !defined(INVALID_HANDLE_VALUE)
69 # define INVALID_HANDLE_VALUE ((HANDLE)(-1))
73 fflush_and_ftruncate(FILE *fp, off_t size)
79 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
80 return WIMLIB_ERR_WRITE;
82 ret = ftruncate(fileno(fp), size);
84 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
85 "%"PRIu64" bytes", size);
86 return WIMLIB_ERR_WRITE;
91 /* Chunk table that's located at the beginning of each compressed resource in
92 * the WIM. (This is not the on-disk format; the on-disk format just has an
93 * array of offsets.) */
97 u64 original_resource_size;
98 u64 bytes_per_chunk_entry;
106 * Allocates and initializes a chunk table, and reserves space for it in the
110 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
113 struct chunk_table **chunk_tab_ret)
115 u64 size = wim_resource_size(lte);
116 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
117 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
118 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
122 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
124 ret = WIMLIB_ERR_NOMEM;
127 chunk_tab->file_offset = file_offset;
128 chunk_tab->num_chunks = num_chunks;
129 chunk_tab->original_resource_size = size;
130 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
131 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
133 chunk_tab->cur_offset = 0;
134 chunk_tab->cur_offset_p = chunk_tab->offsets;
136 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
137 chunk_tab->table_disk_size) {
138 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
140 ret = WIMLIB_ERR_WRITE;
146 *chunk_tab_ret = chunk_tab;
151 * compress_func_t- Pointer to a function to compresses a chunk
152 * of a WIM resource. This may be either
153 * wimlib_xpress_compress() (xpress-compress.c) or
154 * wimlib_lzx_compress() (lzx-compress.c).
156 * @chunk: Uncompressed data of the chunk.
157 * @chunk_size: Size of the uncompressed chunk, in bytes.
158 * @out: Pointer to output buffer of size at least (@chunk_size - 1) bytes.
160 * Returns the size of the compressed data written to @out in bytes, or 0 if the
161 * data could not be compressed to (@chunk_size - 1) bytes or fewer.
163 * As a special requirement, the compression code is optimized for the WIM
164 * format and therefore requires (@chunk_size <= 32768).
166 * As another special requirement, the compression code will read up to 8 bytes
167 * off the end of the @chunk array for performance reasons. The values of these
168 * bytes will not affect the output of the compression, but the calling code
169 * must make sure that the buffer holding the uncompressed chunk is actually at
170 * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
171 * mapped memory that will not cause a memory access violation if accessed.
173 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
177 get_compress_func(int out_ctype)
179 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
180 return wimlib_lzx_compress;
182 return wimlib_xpress_compress;
186 * Writes a chunk of a WIM resource to an output file.
188 * @chunk: Uncompressed data of the chunk.
189 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
190 * @out_fp: FILE * to write tho chunk to.
191 * @out_ctype: Compression type to use when writing the chunk (ignored if no
192 * chunk table provided)
193 * @chunk_tab: Pointer to chunk table being created. It is updated with the
194 * offset of the chunk we write.
196 * Returns 0 on success; nonzero on failure.
199 write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
200 FILE *out_fp, compress_func_t compress,
201 struct chunk_table *chunk_tab)
204 unsigned out_chunk_size;
206 u8 *compressed_chunk = alloca(chunk_size);
208 out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
209 if (out_chunk_size) {
210 /* Write compressed */
211 out_chunk = compressed_chunk;
213 /* Write uncompressed */
215 out_chunk_size = chunk_size;
217 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
218 chunk_tab->cur_offset += out_chunk_size;
220 /* Write uncompressed */
222 out_chunk_size = chunk_size;
224 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
225 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
226 return WIMLIB_ERR_WRITE;
232 * Finishes a WIM chunk table and writes it to the output file at the correct
235 * The final size of the full compressed resource is returned in the
236 * @compressed_size_p.
239 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
240 FILE *out_fp, u64 *compressed_size_p)
242 size_t bytes_written;
243 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
244 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
245 "WIM file", chunk_tab->file_offset);
246 return WIMLIB_ERR_WRITE;
249 if (chunk_tab->bytes_per_chunk_entry == 8) {
250 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
252 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
253 ((u32*)chunk_tab->offsets)[i] =
254 cpu_to_le32(chunk_tab->offsets[i]);
256 bytes_written = fwrite((u8*)chunk_tab->offsets +
257 chunk_tab->bytes_per_chunk_entry,
258 1, chunk_tab->table_disk_size, out_fp);
259 if (bytes_written != chunk_tab->table_disk_size) {
260 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
262 return WIMLIB_ERR_WRITE;
264 if (fseeko(out_fp, 0, SEEK_END) != 0) {
265 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
266 return WIMLIB_ERR_WRITE;
268 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
272 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
273 * attribute pointer in the lookup table entry. */
275 prepare_resource_for_read(struct wim_lookup_table_entry *lte
278 , ntfs_inode **ni_ret
282 switch (lte->resource_location) {
283 case RESOURCE_IN_FILE_ON_DISK:
284 if (!lte->file_on_disk_fp) {
285 lte->file_on_disk_fp = tfopen(lte->file_on_disk, T("rb"));
286 if (!lte->file_on_disk_fp) {
287 ERROR_WITH_ERRNO("Failed to open the file "
288 "`%"TS"'", lte->file_on_disk);
289 return WIMLIB_ERR_OPEN;
294 case RESOURCE_IN_NTFS_VOLUME:
296 struct ntfs_location *loc = lte->ntfs_loc;
299 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path);
301 ERROR_WITH_ERRNO("Failed to open inode `%"TS"' in NTFS "
302 "volume", loc->path);
303 return WIMLIB_ERR_NTFS_3G;
305 lte->attr = ntfs_attr_open(ni,
306 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
308 loc->stream_name_nchars);
310 ERROR_WITH_ERRNO("Failed to open attribute of `%"TS"' in "
311 "NTFS volume", loc->path);
312 ntfs_inode_close(ni);
313 return WIMLIB_ERR_NTFS_3G;
321 if (lte->win32_file_on_disk_fp == INVALID_HANDLE_VALUE) {
322 lte->win32_file_on_disk_fp =
323 win32_open_file_data_only(lte->file_on_disk);
324 if (lte->win32_file_on_disk_fp == INVALID_HANDLE_VALUE) {
325 ERROR("Win32 API: Can't open %"TS, lte->file_on_disk);
327 return WIMLIB_ERR_OPEN;
338 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
341 end_wim_resource_read(struct wim_lookup_table_entry *lte
347 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
348 && lte->file_on_disk_fp)
350 fclose(lte->file_on_disk_fp);
351 lte->file_on_disk_fp = NULL;
354 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
356 ntfs_attr_close(lte->attr);
360 ntfs_inode_close(ni);
364 else if (lte->resource_location == RESOURCE_WIN32
365 && lte->win32_file_on_disk_fp != INVALID_HANDLE_VALUE)
367 win32_close_file(lte->win32_file_on_disk_fp);
368 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
374 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
377 struct resource_entry *out_res_entry)
380 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
381 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
382 "output WIM file", file_offset);
383 return WIMLIB_ERR_WRITE;
385 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
390 return fflush_and_ftruncate(out_fp,
391 file_offset + wim_resource_size(lte));
395 * Writes a WIM resource to a FILE * opened for writing. The resource may be
396 * written uncompressed or compressed depending on the @out_ctype parameter.
398 * If by chance the resource compresses to more than the original size (this may
399 * happen with random data or files than are pre-compressed), the resource is
400 * instead written uncompressed (and this is reflected in the @out_res_entry by
401 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
403 * @lte: The lookup table entry for the WIM resource.
404 * @out_fp: The FILE * to write the resource to.
405 * @out_ctype: The compression type of the resource to write. Note: if this is
406 * the same as the compression type of the WIM resource we
407 * need to read, we simply copy the data (i.e. we do not
408 * uncompress it, then compress it again).
409 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
410 * offset, original size, compressed size, and compression flag
411 * of the output resource.
413 * Returns 0 on success; nonzero on failure.
416 write_wim_resource(struct wim_lookup_table_entry *lte,
417 FILE *out_fp, int out_ctype,
418 struct resource_entry *out_res_entry,
423 u64 old_compressed_size;
424 u64 new_compressed_size;
427 struct chunk_table *chunk_tab = NULL;
430 compress_func_t compress = NULL;
432 ntfs_inode *ni = NULL;
437 /* Original size of the resource */
438 original_size = wim_resource_size(lte);
440 /* Compressed size of the resource (as it exists now) */
441 old_compressed_size = wim_resource_compressed_size(lte);
443 /* Current offset in output file */
444 file_offset = ftello(out_fp);
445 if (file_offset == -1) {
446 ERROR_WITH_ERRNO("Failed to get offset in output "
448 return WIMLIB_ERR_WRITE;
451 /* Are the compression types the same? If so, do a raw copy (copy
452 * without decompressing and recompressing the data). */
453 raw = (wim_resource_compression_type(lte) == out_ctype
454 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
455 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
458 flags |= WIMLIB_RESOURCE_FLAG_RAW;
459 bytes_remaining = old_compressed_size;
461 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
462 bytes_remaining = original_size;
465 /* Empty resource; nothing needs to be done, so just return success. */
466 if (bytes_remaining == 0)
469 /* Buffer for reading chunks for the resource */
470 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
472 /* If we are writing a compressed resource and not doing a raw copy, we
473 * need to initialize the chunk table */
474 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
475 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
481 /* If the WIM resource is in an external file, open a FILE * to it so we
482 * don't have to open a temporary one in read_wim_resource() for each
485 ret = prepare_resource_for_read(lte, &ni);
487 ret = prepare_resource_for_read(lte);
492 /* If we aren't doing a raw copy, we will compute the SHA1 message
493 * digest of the resource as we read it, and verify it's the same as the
494 * hash given in the lookup table entry once we've finished reading the
499 compress = get_compress_func(out_ctype);
503 /* While there are still bytes remaining in the WIM resource, read a
504 * chunk of the resource, update SHA1, then write that chunk using the
505 * desired compression type. */
507 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
508 ret = read_wim_resource(lte, buf, to_read, offset, flags);
512 sha1_update(&ctx, buf, to_read);
513 ret = write_wim_resource_chunk(buf, to_read, out_fp,
514 compress, chunk_tab);
517 bytes_remaining -= to_read;
519 } while (bytes_remaining);
521 /* Raw copy: The new compressed size is the same as the old compressed
524 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
527 * Using a different compression type: Call
528 * finish_wim_resource_chunk_tab() and it will provide the new
532 new_compressed_size = old_compressed_size;
534 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
535 new_compressed_size = original_size;
537 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
538 &new_compressed_size);
544 /* Verify SHA1 message digest of the resource, unless we are doing a raw
545 * write (in which case we never even saw the uncompressed data). Or,
546 * if the hash we had before is all 0's, just re-set it to be the new
549 u8 md[SHA1_HASH_SIZE];
550 sha1_final(md, &ctx);
551 if (is_zero_hash(lte->hash)) {
552 copy_hash(lte->hash, md);
553 } else if (!hashes_equal(md, lte->hash)) {
554 ERROR("WIM resource has incorrect hash!");
555 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
556 ERROR("We were reading it from `%"TS"'; maybe "
557 "it changed while we were reading it.",
560 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
565 if (!raw && new_compressed_size >= original_size &&
566 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
568 /* Oops! We compressed the resource to larger than the original
569 * size. Write the resource uncompressed instead. */
570 ret = write_uncompressed_resource_and_truncate(lte,
578 out_res_entry->size = new_compressed_size;
579 out_res_entry->original_size = original_size;
580 out_res_entry->offset = file_offset;
581 out_res_entry->flags = lte->resource_entry.flags
582 & ~WIM_RESHDR_FLAG_COMPRESSED;
583 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
584 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
590 end_wim_resource_read(lte, ni);
592 end_wim_resource_read(lte);
599 #ifdef ENABLE_MULTITHREADED_COMPRESSION
601 /* Blocking shared queue (solves the producer-consumer problem) */
602 struct shared_queue {
606 unsigned filled_slots;
608 pthread_mutex_t lock;
609 pthread_cond_t msg_avail_cond;
610 pthread_cond_t space_avail_cond;
614 shared_queue_init(struct shared_queue *q, unsigned size)
616 wimlib_assert(size != 0);
617 q->array = CALLOC(sizeof(q->array[0]), size);
619 return WIMLIB_ERR_NOMEM;
624 pthread_mutex_init(&q->lock, NULL);
625 pthread_cond_init(&q->msg_avail_cond, NULL);
626 pthread_cond_init(&q->space_avail_cond, NULL);
631 shared_queue_destroy(struct shared_queue *q)
634 pthread_mutex_destroy(&q->lock);
635 pthread_cond_destroy(&q->msg_avail_cond);
636 pthread_cond_destroy(&q->space_avail_cond);
640 shared_queue_put(struct shared_queue *q, void *obj)
642 pthread_mutex_lock(&q->lock);
643 while (q->filled_slots == q->size)
644 pthread_cond_wait(&q->space_avail_cond, &q->lock);
646 q->back = (q->back + 1) % q->size;
647 q->array[q->back] = obj;
650 pthread_cond_broadcast(&q->msg_avail_cond);
651 pthread_mutex_unlock(&q->lock);
655 shared_queue_get(struct shared_queue *q)
659 pthread_mutex_lock(&q->lock);
660 while (q->filled_slots == 0)
661 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
663 obj = q->array[q->front];
664 q->array[q->front] = NULL;
665 q->front = (q->front + 1) % q->size;
668 pthread_cond_broadcast(&q->space_avail_cond);
669 pthread_mutex_unlock(&q->lock);
673 struct compressor_thread_params {
674 struct shared_queue *res_to_compress_queue;
675 struct shared_queue *compressed_res_queue;
676 compress_func_t compress;
679 #define MAX_CHUNKS_PER_MSG 2
682 struct wim_lookup_table_entry *lte;
683 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
684 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
685 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
686 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
687 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
689 struct list_head list;
695 compress_chunks(struct message *msg, compress_func_t compress)
697 for (unsigned i = 0; i < msg->num_chunks; i++) {
698 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
699 unsigned len = compress(msg->uncompressed_chunks[i],
700 msg->uncompressed_chunk_sizes[i],
701 msg->compressed_chunks[i]);
703 /* To be written compressed */
704 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
705 msg->compressed_chunk_sizes[i] = len;
707 /* To be written uncompressed */
708 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
709 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
715 /* Compressor thread routine. This is a lot simpler than the main thread
716 * routine: just repeatedly get a group of chunks from the
717 * res_to_compress_queue, compress them, and put them in the
718 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
721 compressor_thread_proc(void *arg)
723 struct compressor_thread_params *params = arg;
724 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
725 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
726 compress_func_t compress = params->compress;
729 DEBUG("Compressor thread ready");
730 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
731 compress_chunks(msg, compress);
732 shared_queue_put(compressed_res_queue, msg);
734 DEBUG("Compressor thread terminating");
737 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
740 do_write_streams_progress(union wimlib_progress_info *progress,
741 wimlib_progress_func_t progress_func,
744 progress->write_streams.completed_bytes += size_added;
745 progress->write_streams.completed_streams++;
747 progress->write_streams.completed_bytes >= progress->write_streams._private)
749 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
751 if (progress->write_streams._private == progress->write_streams.total_bytes) {
752 progress->write_streams._private = ~0;
754 progress->write_streams._private =
755 min(progress->write_streams.total_bytes,
756 progress->write_streams.completed_bytes +
757 progress->write_streams.total_bytes / 100);
763 do_write_stream_list(struct list_head *my_resources,
766 wimlib_progress_func_t progress_func,
767 union wimlib_progress_info *progress,
768 int write_resource_flags)
771 struct wim_lookup_table_entry *lte, *tmp;
773 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
774 ret = write_wim_resource(lte,
777 <e->output_resource_entry,
778 write_resource_flags);
781 list_del(<e->staging_list);
783 do_write_streams_progress(progress,
785 wim_resource_size(lte));
791 write_stream_list_serial(struct list_head *stream_list,
795 wimlib_progress_func_t progress_func,
796 union wimlib_progress_info *progress)
798 int write_resource_flags;
800 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
801 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
803 write_resource_flags = 0;
804 progress->write_streams.num_threads = 1;
806 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
807 return do_write_stream_list(stream_list, out_fp,
808 out_ctype, progress_func,
809 progress, write_resource_flags);
812 #ifdef ENABLE_MULTITHREADED_COMPRESSION
814 write_wim_chunks(struct message *msg, FILE *out_fp,
815 struct chunk_table *chunk_tab)
817 for (unsigned i = 0; i < msg->num_chunks; i++) {
818 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
820 DEBUG2("Write wim chunk %u of %u (csize = %u)",
821 i, msg->num_chunks, chunk_csize);
823 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
826 ERROR_WITH_ERRNO("Failed to write WIM chunk");
827 return WIMLIB_ERR_WRITE;
830 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
831 chunk_tab->cur_offset += chunk_csize;
837 * This function is executed by the main thread when the resources are being
838 * compressed in parallel. The main thread is in change of all reading of the
839 * uncompressed data and writing of the compressed data. The compressor threads
840 * *only* do compression from/to in-memory buffers.
842 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
843 * chunks of compressed data to compress, represented in a `struct message'.
844 * Each message is passed from the main thread to a worker thread through the
845 * res_to_compress_queue, and it is passed back through the
846 * compressed_res_queue.
849 main_writer_thread_proc(struct list_head *stream_list,
852 struct shared_queue *res_to_compress_queue,
853 struct shared_queue *compressed_res_queue,
856 wimlib_progress_func_t progress_func,
857 union wimlib_progress_info *progress)
860 struct chunk_table *cur_chunk_tab = NULL;
861 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
862 struct wim_lookup_table_entry *next_lte = NULL;
864 // Initially, all the messages are available to use.
865 LIST_HEAD(available_msgs);
868 ret = WIMLIB_ERR_NOMEM;
872 for (size_t i = 0; i < num_messages; i++)
873 list_add(&msgs[i].list, &available_msgs);
875 // outstanding_resources is the list of resources that currently have
876 // had chunks sent off for compression.
878 // The first stream in outstanding_resources is the stream that is
879 // currently being written (cur_lte).
881 // The last stream in outstanding_resources is the stream that is
882 // currently being read and chunks fed to the compressor threads
885 // Depending on the number of threads and the sizes of the resource,
886 // the outstanding streams list may contain streams between cur_lte and
887 // next_lte that have all their chunks compressed or being compressed,
888 // but haven't been written yet.
890 LIST_HEAD(outstanding_resources);
891 struct list_head *next_resource = stream_list->next;
893 u64 next_num_chunks = 0;
895 // As in write_wim_resource(), each resource we read is checksummed.
896 SHA_CTX next_sha_ctx;
897 u8 next_hash[SHA1_HASH_SIZE];
899 // Resources that don't need any chunks compressed are added to this
900 // list and written directly by the main thread.
901 LIST_HEAD(my_resources);
903 struct wim_lookup_table_entry *cur_lte = NULL;
907 ntfs_inode *ni = NULL;
910 DEBUG("Initializing buffers for uncompressed "
911 "and compressed data (%zu bytes needed)",
912 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
914 // Pre-allocate all the buffers that will be needed to do the chunk
916 for (size_t i = 0; i < num_messages; i++) {
917 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
918 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
920 // The extra 8 bytes is because longest_match() in
921 // lz77.c may read a little bit off the end of the
922 // uncompressed data. It doesn't need to be
923 // initialized--- we really just need to avoid accessing
925 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
926 if (msgs[i].compressed_chunks[j] == NULL ||
927 msgs[i].uncompressed_chunks[j] == NULL)
929 ret = WIMLIB_ERR_NOMEM;
935 // This loop is executed until all resources have been written, except
936 // possibly a few that have been added to the @my_resources list for
939 // Send chunks to the compressor threads until either (a) there
940 // are no more messages available since they were all sent off,
941 // or (b) there are no more resources that need to be
943 while (!list_empty(&available_msgs)) {
944 if (next_chunk == next_num_chunks) {
945 // If next_chunk == next_num_chunks, there are
946 // no more chunks to write in the current
947 // stream. So, check the SHA1 message digest of
948 // the stream that was just finished (unless
949 // next_lte == NULL, which is the case the very
950 // first time this loop is entered, and also
951 // near the very end of the compression when
952 // there are no more streams.) Then, advance to
953 // the next stream (if there is one).
954 if (next_lte != NULL) {
956 end_wim_resource_read(next_lte, ni);
959 end_wim_resource_read(next_lte);
961 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
963 sha1_final(next_hash, &next_sha_ctx);
964 if (!hashes_equal(next_lte->hash, next_hash)) {
965 ERROR("WIM resource has incorrect hash!");
966 if (next_lte->resource_location ==
967 RESOURCE_IN_FILE_ON_DISK)
969 ERROR("We were reading it from `%"TS"'; "
970 "maybe it changed while we were "
972 next_lte->file_on_disk);
974 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
979 // Advance to the next resource.
981 // If the next resource needs no compression, just write
982 // it with this thread (not now though--- we could be in
983 // the middle of writing another resource.) Keep doing
984 // this until we either get to the end of the resources
985 // list, or we get to a resource that needs compression.
987 if (next_resource == stream_list) {
988 // No more resources to send for
993 next_lte = container_of(next_resource,
994 struct wim_lookup_table_entry,
996 next_resource = next_resource->next;
997 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
998 && wim_resource_compression_type(next_lte) == out_ctype)
999 || wim_resource_size(next_lte) == 0)
1001 list_add_tail(&next_lte->staging_list,
1004 list_add_tail(&next_lte->staging_list,
1005 &outstanding_resources);
1007 next_num_chunks = wim_resource_chunks(next_lte);
1008 sha1_init(&next_sha_ctx);
1009 INIT_LIST_HEAD(&next_lte->msg_list);
1011 ret = prepare_resource_for_read(next_lte, &ni);
1013 ret = prepare_resource_for_read(next_lte);
1018 if (cur_lte == NULL) {
1019 // Set cur_lte for the
1028 if (next_lte == NULL) {
1029 // No more resources to send for compression
1033 // Get a message from the available messages
1035 msg = container_of(available_msgs.next,
1039 // ... and delete it from the available messages
1041 list_del(&msg->list);
1043 // Initialize the message with the chunks to
1045 msg->num_chunks = min(next_num_chunks - next_chunk,
1046 MAX_CHUNKS_PER_MSG);
1047 msg->lte = next_lte;
1048 msg->complete = false;
1049 msg->begin_chunk = next_chunk;
1051 unsigned size = WIM_CHUNK_SIZE;
1052 for (unsigned i = 0; i < msg->num_chunks; i++) {
1054 // Read chunk @next_chunk of the stream into the
1055 // message so that a compressor thread can
1058 if (next_chunk == next_num_chunks - 1) {
1059 size = MODULO_NONZERO(wim_resource_size(next_lte),
1063 DEBUG2("Read resource (size=%u, offset=%zu)",
1064 size, next_chunk * WIM_CHUNK_SIZE);
1066 msg->uncompressed_chunk_sizes[i] = size;
1068 ret = read_wim_resource(next_lte,
1069 msg->uncompressed_chunks[i],
1071 next_chunk * WIM_CHUNK_SIZE,
1075 sha1_update(&next_sha_ctx,
1076 msg->uncompressed_chunks[i], size);
1080 // Send the compression request
1081 list_add_tail(&msg->list, &next_lte->msg_list);
1082 shared_queue_put(res_to_compress_queue, msg);
1083 DEBUG2("Compression request sent");
1086 // If there are no outstanding resources, there are no more
1087 // resources that need to be written.
1088 if (list_empty(&outstanding_resources)) {
1093 // Get the next message from the queue and process it.
1094 // The message will contain 1 or more data chunks that have been
1096 msg = shared_queue_get(compressed_res_queue);
1097 msg->complete = true;
1099 // Is this the next chunk in the current resource? If it's not
1100 // (i.e., an earlier chunk in a same or different resource
1101 // hasn't been compressed yet), do nothing, and keep this
1102 // message around until all earlier chunks are received.
1104 // Otherwise, write all the chunks we can.
1105 while (cur_lte != NULL &&
1106 !list_empty(&cur_lte->msg_list) &&
1107 (msg = container_of(cur_lte->msg_list.next,
1111 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1112 if (msg->begin_chunk == 0) {
1113 DEBUG2("Begin chunk tab");
1115 // This is the first set of chunks. Leave space
1116 // for the chunk table in the output file.
1117 off_t cur_offset = ftello(out_fp);
1118 if (cur_offset == -1) {
1119 ret = WIMLIB_ERR_WRITE;
1122 ret = begin_wim_resource_chunk_tab(cur_lte,
1130 // Write the compressed chunks from the message.
1131 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1135 list_del(&msg->list);
1137 // This message is available to use for different chunks
1139 list_add(&msg->list, &available_msgs);
1141 // Was this the last chunk of the stream? If so, finish
1143 if (list_empty(&cur_lte->msg_list) &&
1144 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1146 DEBUG2("Finish wim chunk tab");
1148 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1154 if (res_csize >= wim_resource_size(cur_lte)) {
1155 /* Oops! We compressed the resource to
1156 * larger than the original size. Write
1157 * the resource uncompressed instead. */
1158 ret = write_uncompressed_resource_and_truncate(
1161 cur_chunk_tab->file_offset,
1162 &cur_lte->output_resource_entry);
1166 cur_lte->output_resource_entry.size =
1169 cur_lte->output_resource_entry.original_size =
1170 cur_lte->resource_entry.original_size;
1172 cur_lte->output_resource_entry.offset =
1173 cur_chunk_tab->file_offset;
1175 cur_lte->output_resource_entry.flags =
1176 cur_lte->resource_entry.flags |
1177 WIM_RESHDR_FLAG_COMPRESSED;
1180 do_write_streams_progress(progress, progress_func,
1181 wim_resource_size(cur_lte));
1183 FREE(cur_chunk_tab);
1184 cur_chunk_tab = NULL;
1186 struct list_head *next = cur_lte->staging_list.next;
1187 list_del(&cur_lte->staging_list);
1189 if (next == &outstanding_resources)
1192 cur_lte = container_of(cur_lte->staging_list.next,
1193 struct wim_lookup_table_entry,
1196 // Since we just finished writing a stream,
1197 // write any streams that have been added to the
1198 // my_resources list for direct writing by the
1199 // main thread (e.g. resources that don't need
1200 // to be compressed because the desired
1201 // compression type is the same as the previous
1202 // compression type).
1203 ret = do_write_stream_list(&my_resources,
1216 if (ret == WIMLIB_ERR_NOMEM) {
1217 ERROR("Could not allocate enough memory for "
1218 "multi-threaded compression");
1223 end_wim_resource_read(next_lte, ni);
1225 end_wim_resource_read(next_lte);
1230 ret = do_write_stream_list(&my_resources, out_fp,
1231 out_ctype, progress_func,
1235 size_t num_available_msgs = 0;
1236 struct list_head *cur;
1238 list_for_each(cur, &available_msgs) {
1239 num_available_msgs++;
1242 while (num_available_msgs < num_messages) {
1243 shared_queue_get(compressed_res_queue);
1244 num_available_msgs++;
1250 for (size_t i = 0; i < num_messages; i++) {
1251 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1252 FREE(msgs[i].compressed_chunks[j]);
1253 FREE(msgs[i].uncompressed_chunks[j]);
1259 FREE(cur_chunk_tab);
1264 get_default_num_threads()
1267 return win32_get_number_of_processors();
1269 return sysconf(_SC_NPROCESSORS_ONLN);
1274 write_stream_list_parallel(struct list_head *stream_list,
1278 unsigned num_threads,
1279 wimlib_progress_func_t progress_func,
1280 union wimlib_progress_info *progress)
1283 struct shared_queue res_to_compress_queue;
1284 struct shared_queue compressed_res_queue;
1285 pthread_t *compressor_threads = NULL;
1287 if (num_threads == 0) {
1288 long nthreads = get_default_num_threads();
1289 if (nthreads < 1 || nthreads > UINT_MAX) {
1290 WARNING("Could not determine number of processors! Assuming 1");
1293 num_threads = nthreads;
1297 progress->write_streams.num_threads = num_threads;
1298 wimlib_assert(stream_list->next != stream_list);
1300 static const double MESSAGES_PER_THREAD = 2.0;
1301 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1303 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1305 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1309 ret = shared_queue_init(&compressed_res_queue, queue_size);
1311 goto out_destroy_res_to_compress_queue;
1313 struct compressor_thread_params params;
1314 params.res_to_compress_queue = &res_to_compress_queue;
1315 params.compressed_res_queue = &compressed_res_queue;
1316 params.compress = get_compress_func(out_ctype);
1318 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1319 if (!compressor_threads) {
1320 ret = WIMLIB_ERR_NOMEM;
1321 goto out_destroy_compressed_res_queue;
1324 for (unsigned i = 0; i < num_threads; i++) {
1325 DEBUG("pthread_create thread %u", i);
1326 ret = pthread_create(&compressor_threads[i], NULL,
1327 compressor_thread_proc, ¶ms);
1330 ERROR_WITH_ERRNO("Failed to create compressor "
1338 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1340 ret = main_writer_thread_proc(stream_list,
1343 &res_to_compress_queue,
1344 &compressed_res_queue,
1350 for (unsigned i = 0; i < num_threads; i++)
1351 shared_queue_put(&res_to_compress_queue, NULL);
1353 for (unsigned i = 0; i < num_threads; i++) {
1354 if (pthread_join(compressor_threads[i], NULL)) {
1355 WARNING_WITH_ERRNO("Failed to join compressor "
1359 FREE(compressor_threads);
1360 out_destroy_compressed_res_queue:
1361 shared_queue_destroy(&compressed_res_queue);
1362 out_destroy_res_to_compress_queue:
1363 shared_queue_destroy(&res_to_compress_queue);
1364 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1367 WARNING("Falling back to single-threaded compression");
1368 return write_stream_list_serial(stream_list,
1379 * Write a list of streams to a WIM (@out_fp) using the compression type
1380 * @out_ctype and up to @num_threads compressor threads.
1383 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1384 int out_ctype, int write_flags,
1385 unsigned num_threads,
1386 wimlib_progress_func_t progress_func)
1388 struct wim_lookup_table_entry *lte;
1389 size_t num_streams = 0;
1390 u64 total_bytes = 0;
1391 u64 total_compression_bytes = 0;
1392 union wimlib_progress_info progress;
1394 list_for_each_entry(lte, stream_list, staging_list) {
1396 total_bytes += wim_resource_size(lte);
1397 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1398 && (wim_resource_compression_type(lte) != out_ctype ||
1399 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1401 total_compression_bytes += wim_resource_size(lte);
1404 progress.write_streams.total_bytes = total_bytes;
1405 progress.write_streams.total_streams = num_streams;
1406 progress.write_streams.completed_bytes = 0;
1407 progress.write_streams.completed_streams = 0;
1408 progress.write_streams.num_threads = num_threads;
1409 progress.write_streams.compression_type = out_ctype;
1410 progress.write_streams._private = 0;
1412 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1413 if (total_compression_bytes >= 1000000 && num_threads != 1)
1414 return write_stream_list_parallel(stream_list,
1423 return write_stream_list_serial(stream_list,
1431 struct lte_overwrite_prepare_args {
1434 struct list_head *stream_list;
1438 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1440 struct lte_overwrite_prepare_args *args = arg;
1442 if (lte->resource_location == RESOURCE_IN_WIM &&
1443 lte->wim == args->wim &&
1444 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1446 #ifdef ENABLE_ERROR_MESSAGES
1447 ERROR("The following resource is after the XML data:");
1448 print_lookup_table_entry(lte, stderr);
1450 return WIMLIB_ERR_RESOURCE_ORDER;
1453 lte->out_refcnt = lte->refcnt;
1454 memcpy(<e->output_resource_entry, <e->resource_entry,
1455 sizeof(struct resource_entry));
1456 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1457 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1458 list_add(<e->staging_list, args->stream_list);
1463 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1464 struct list_head *stream_list)
1466 struct lte_overwrite_prepare_args args = {
1468 .end_offset = end_offset,
1469 .stream_list = stream_list,
1473 for (int i = 0; i < wim->hdr.image_count; i++) {
1474 ret = lte_overwrite_prepare(wim->image_metadata[i].metadata_lte,
1479 return for_lookup_table_entry(wim->lookup_table,
1480 lte_overwrite_prepare, &args);
1484 inode_find_streams_to_write(struct wim_inode *inode,
1485 struct wim_lookup_table *table,
1486 struct list_head *stream_list)
1488 struct wim_lookup_table_entry *lte;
1489 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1490 lte = inode_stream_lte(inode, i, table);
1492 if (lte->out_refcnt == 0)
1493 list_add_tail(<e->staging_list, stream_list);
1494 lte->out_refcnt += inode->i_nlink;
1501 image_find_streams_to_write(WIMStruct *w)
1503 struct wim_inode *inode;
1504 struct hlist_node *cur;
1505 struct hlist_head *inode_list;
1507 inode_list = &wim_get_current_image_metadata(w)->inode_list;
1508 hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1509 inode_find_streams_to_write(inode, w->lookup_table,
1510 (struct list_head*)w->private);
1516 write_wim_streams(WIMStruct *w, int image, int write_flags,
1517 unsigned num_threads,
1518 wimlib_progress_func_t progress_func)
1521 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1522 LIST_HEAD(stream_list);
1523 w->private = &stream_list;
1524 for_image(w, image, image_find_streams_to_write);
1525 return write_stream_list(&stream_list, w->out_fp,
1526 wimlib_get_compression_type(w), write_flags,
1527 num_threads, progress_func);
1531 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1532 * table (optional), then overwrite the WIM header.
1534 * write_flags is a bitwise OR of the following:
1536 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1537 * Include an integrity table.
1539 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1540 * Show progress information when (if) writing the integrity table.
1542 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1543 * Don't write the lookup table.
1545 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1546 * When (if) writing the integrity table, re-use entries from the
1547 * existing integrity table, if possible.
1549 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1550 * After writing the XML data but before writing the integrity
1551 * table, write a temporary WIM header and flush the stream so that
1552 * the WIM is less likely to become corrupted upon abrupt program
1555 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1556 * fsync() the output file before closing it.
1560 finish_write(WIMStruct *w, int image, int write_flags,
1561 wimlib_progress_func_t progress_func)
1564 struct wim_header hdr;
1565 FILE *out = w->out_fp;
1567 /* @hdr will be the header for the new WIM. First copy all the data
1568 * from the header in the WIMStruct; then set all the fields that may
1569 * have changed, including the resource entries, boot index, and image
1571 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1573 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1574 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1579 ret = write_xml_data(w->wim_info, image, out,
1580 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1581 wim_info_get_total_bytes(w->wim_info) : 0,
1582 &hdr.xml_res_entry);
1586 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1587 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1588 struct wim_header checkpoint_hdr;
1589 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1590 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1591 if (fseeko(out, 0, SEEK_SET) != 0) {
1592 ERROR_WITH_ERRNO("Failed to seek to beginning "
1593 "of WIM being written");
1594 ret = WIMLIB_ERR_WRITE;
1597 ret = write_header(&checkpoint_hdr, out);
1601 if (fflush(out) != 0) {
1602 ERROR_WITH_ERRNO("Can't write data to WIM");
1603 ret = WIMLIB_ERR_WRITE;
1607 if (fseeko(out, 0, SEEK_END) != 0) {
1608 ERROR_WITH_ERRNO("Failed to seek to end "
1609 "of WIM being written");
1610 ret = WIMLIB_ERR_WRITE;
1615 off_t old_lookup_table_end;
1616 off_t new_lookup_table_end;
1617 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1618 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1619 w->hdr.lookup_table_res_entry.size;
1621 old_lookup_table_end = 0;
1623 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1624 hdr.lookup_table_res_entry.size;
1626 ret = write_integrity_table(out,
1628 new_lookup_table_end,
1629 old_lookup_table_end,
1634 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1638 * In the WIM header, there is room for the resource entry for a
1639 * metadata resource labeled as the "boot metadata". This entry should
1640 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1641 * it should be a copy of the resource entry for the image that is
1642 * marked as bootable. This is not well documented...
1645 /* Set image count and boot index correctly for single image writes */
1646 if (image != WIMLIB_ALL_IMAGES) {
1647 hdr.image_count = 1;
1648 if (hdr.boot_idx == image)
1654 if (hdr.boot_idx == 0) {
1655 memset(&hdr.boot_metadata_res_entry, 0,
1656 sizeof(struct resource_entry));
1658 memcpy(&hdr.boot_metadata_res_entry,
1660 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1661 sizeof(struct resource_entry));
1664 if (fseeko(out, 0, SEEK_SET) != 0) {
1665 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1667 ret = WIMLIB_ERR_WRITE;
1671 ret = write_header(&hdr, out);
1675 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1676 if (fflush(out) != 0
1677 || fsync(fileno(out)) != 0)
1679 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1680 ret = WIMLIB_ERR_WRITE;
1684 if (fclose(out) != 0) {
1685 ERROR_WITH_ERRNO("Failed to close the WIM file");
1687 ret = WIMLIB_ERR_WRITE;
1693 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1695 lock_wim(WIMStruct *w, FILE *fp)
1698 if (fp && !w->wim_locked) {
1699 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1701 if (errno == EWOULDBLOCK) {
1702 ERROR("`%"TS"' is already being modified or has been "
1703 "mounted read-write\n"
1704 " by another process!", w->filename);
1705 ret = WIMLIB_ERR_ALREADY_LOCKED;
1707 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1720 open_wim_writable(WIMStruct *w, const tchar *path,
1721 bool trunc, bool also_readable)
1732 wimlib_assert(w->out_fp == NULL);
1733 w->out_fp = tfopen(path, mode);
1737 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1738 return WIMLIB_ERR_OPEN;
1744 close_wim_writable(WIMStruct *w)
1747 if (fclose(w->out_fp) != 0) {
1748 WARNING_WITH_ERRNO("Failed to close output WIM");
1754 /* Open file stream and write dummy header for WIM. */
1756 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1759 ret = open_wim_writable(w, path, true,
1760 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1763 /* Write dummy header. It will be overwritten later. */
1764 return write_header(&w->hdr, w->out_fp);
1767 /* Writes a stand-alone WIM to a file. */
1769 wimlib_write(WIMStruct *w, const tchar *path,
1770 int image, int write_flags, unsigned num_threads,
1771 wimlib_progress_func_t progress_func)
1776 return WIMLIB_ERR_INVALID_PARAM;
1778 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1780 if (image != WIMLIB_ALL_IMAGES &&
1781 (image < 1 || image > w->hdr.image_count))
1782 return WIMLIB_ERR_INVALID_IMAGE;
1784 if (w->hdr.total_parts != 1) {
1785 ERROR("Cannot call wimlib_write() on part of a split WIM");
1786 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1789 ret = begin_write(w, path, write_flags);
1793 ret = write_wim_streams(w, image, write_flags, num_threads,
1799 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1801 ret = for_image(w, image, write_metadata_resource);
1806 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1808 ret = finish_write(w, image, write_flags, progress_func);
1810 close_wim_writable(w);
1811 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1816 any_images_modified(WIMStruct *w)
1818 for (int i = 0; i < w->hdr.image_count; i++)
1819 if (w->image_metadata[i].modified)
1825 * Overwrite a WIM, possibly appending streams to it.
1827 * A WIM looks like (or is supposed to look like) the following:
1829 * Header (212 bytes)
1830 * Streams and metadata resources (variable size)
1831 * Lookup table (variable size)
1832 * XML data (variable size)
1833 * Integrity table (optional) (variable size)
1835 * If we are not adding any streams or metadata resources, the lookup table is
1836 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1837 * header. This operation is potentially unsafe if the program is abruptly
1838 * terminated while the XML data or integrity table are being overwritten, but
1839 * before the new header has been written. To partially alleviate this problem,
1840 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1841 * finish_write() to cause a temporary WIM header to be written after the XML
1842 * data has been written. This may prevent the WIM from becoming corrupted if
1843 * the program is terminated while the integrity table is being calculated (but
1844 * no guarantees, due to write re-ordering...).
1846 * If we are adding new streams or images (metadata resources), the lookup table
1847 * needs to be changed, and those streams need to be written. In this case, we
1848 * try to perform a safe update of the WIM file by writing the streams *after*
1849 * the end of the previous WIM, then writing the new lookup table, XML data, and
1850 * (optionally) integrity table following the new streams. This will produce a
1851 * layout like the following:
1853 * Header (212 bytes)
1854 * (OLD) Streams and metadata resources (variable size)
1855 * (OLD) Lookup table (variable size)
1856 * (OLD) XML data (variable size)
1857 * (OLD) Integrity table (optional) (variable size)
1858 * (NEW) Streams and metadata resources (variable size)
1859 * (NEW) Lookup table (variable size)
1860 * (NEW) XML data (variable size)
1861 * (NEW) Integrity table (optional) (variable size)
1863 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1864 * the header is overwritten to point to the new lookup table, XML data, and
1865 * integrity table, to produce the following layout:
1867 * Header (212 bytes)
1868 * Streams and metadata resources (variable size)
1869 * Nothing (variable size)
1870 * More Streams and metadata resources (variable size)
1871 * Lookup table (variable size)
1872 * XML data (variable size)
1873 * Integrity table (optional) (variable size)
1875 * This method allows an image to be appended to a large WIM very quickly, and
1876 * is is crash-safe except in the case of write re-ordering, but the
1877 * disadvantage is that a small hole is left in the WIM where the old lookup
1878 * table, xml data, and integrity table were. (These usually only take up a
1879 * small amount of space compared to the streams, however.)
1882 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1883 unsigned num_threads,
1884 wimlib_progress_func_t progress_func)
1887 struct list_head stream_list;
1889 bool found_modified_image;
1891 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1893 /* Make sure that the integrity table (if present) is after the XML
1894 * data, and that there are no stream resources, metadata resources, or
1895 * lookup tables after the XML data. Otherwise, these data would be
1897 if (w->hdr.integrity.offset != 0 &&
1898 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1899 ERROR("Didn't expect the integrity table to be before the XML data");
1900 return WIMLIB_ERR_RESOURCE_ORDER;
1903 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1904 ERROR("Didn't expect the lookup table to be after the XML data");
1905 return WIMLIB_ERR_RESOURCE_ORDER;
1909 if (w->hdr.integrity.offset)
1910 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1912 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1914 if (!w->deletion_occurred && !any_images_modified(w)) {
1915 /* If no images have been modified and no images have been
1916 * deleted, a new lookup table does not need to be written. */
1917 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1918 w->hdr.lookup_table_res_entry.size;
1919 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1920 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1922 INIT_LIST_HEAD(&stream_list);
1923 ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1927 ret = open_wim_writable(w, w->filename, false,
1928 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1932 ret = lock_wim(w, w->out_fp);
1939 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1940 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1944 return WIMLIB_ERR_WRITE;
1947 if (!list_empty(&stream_list)) {
1948 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1950 ret = write_stream_list(&stream_list, w->out_fp,
1951 wimlib_get_compression_type(w),
1952 write_flags, num_threads,
1957 DEBUG("No new streams were added");
1960 found_modified_image = false;
1961 for (int i = 0; i < w->hdr.image_count; i++) {
1962 if (w->image_metadata[i].modified) {
1963 select_wim_image(w, i + 1);
1964 ret = write_metadata_resource(w);
1969 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1970 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1973 close_wim_writable(w);
1974 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1975 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1976 w->filename, old_wim_end);
1977 /* Return value of truncate() is ignored because this is already
1979 (void)ttruncate(w->filename, old_wim_end);
1986 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1987 unsigned num_threads,
1988 wimlib_progress_func_t progress_func)
1990 size_t wim_name_len;
1993 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1995 /* Write the WIM to a temporary file in the same directory as the
1997 wim_name_len = tstrlen(w->filename);
1998 tchar tmpfile[wim_name_len + 10];
1999 tmemcpy(tmpfile, w->filename, wim_name_len);
2000 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2001 tmpfile[wim_name_len + 9] = T('\0');
2003 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2004 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2005 num_threads, progress_func);
2007 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2011 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2014 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2015 * specified to CreateFile(). The WIM was opened with fopen(), which
2016 * didn't provided this flag to CreateFile, so the handle must be closed
2017 * before executing the rename(). */
2018 if (w->fp != NULL) {
2024 /* Rename the new file to the old file .*/
2025 if (trename(tmpfile, w->filename) != 0) {
2026 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2027 tmpfile, w->filename);
2028 ret = WIMLIB_ERR_RENAME;
2032 if (progress_func) {
2033 union wimlib_progress_info progress;
2034 progress.rename.from = tmpfile;
2035 progress.rename.to = w->filename;
2036 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2039 /* Close the original WIM file that was opened for reading. */
2040 if (w->fp != NULL) {
2045 /* Re-open the WIM read-only. */
2046 w->fp = tfopen(w->filename, T("rb"));
2047 if (w->fp == NULL) {
2048 ret = WIMLIB_ERR_REOPEN;
2049 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2056 /* Remove temporary file. */
2057 if (tunlink(tmpfile) != 0)
2058 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2063 * Writes a WIM file to the original file that it was read from, overwriting it.
2066 wimlib_overwrite(WIMStruct *w, int write_flags,
2067 unsigned num_threads,
2068 wimlib_progress_func_t progress_func)
2070 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2073 return WIMLIB_ERR_NO_FILENAME;
2075 if (w->hdr.total_parts != 1) {
2076 ERROR("Cannot modify a split WIM");
2077 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2080 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2081 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2084 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2086 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2087 WARNING("Falling back to re-building entire WIM");
2091 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,