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 the chunk to.
191 * @compress: Compression function to use (NULL if writing uncompressed
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 void *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;
273 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
276 struct resource_entry *out_res_entry)
279 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
280 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
281 "output WIM file", file_offset);
282 return WIMLIB_ERR_WRITE;
284 ret = write_wim_resource(lte, out_fp,
285 WIMLIB_COMPRESSION_TYPE_NONE,
291 return fflush_and_ftruncate(out_fp,
292 file_offset + wim_resource_size(lte));
295 struct write_resource_ctx {
296 compress_func_t compress;
297 struct chunk_table *chunk_tab;
304 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
306 struct write_resource_ctx *ctx = _ctx;
309 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
312 return write_wim_resource_chunk(chunk, chunk_size,
313 ctx->out_fp, ctx->compress,
316 if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
317 ERROR_WITH_ERRNO("Error writing to output WIM");
318 return WIMLIB_ERR_WRITE;
326 write_wim_resource(struct wim_lookup_table_entry *lte,
327 FILE *out_fp, int out_ctype,
328 struct resource_entry *out_res_entry,
331 struct write_resource_ctx write_ctx;
336 if (wim_resource_size(lte) == 0) {
337 /* Empty resource; nothing needs to be done, so just return
342 offset = ftello(out_fp);
344 ERROR_WITH_ERRNO("Can't get position in output WIM");
345 return WIMLIB_ERR_WRITE;
348 /* Can we simply copy the compressed data without recompressing it? */
350 if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
351 lte->resource_location == RESOURCE_IN_WIM &&
352 wimlib_get_compression_type(lte->wim) == out_ctype)
354 flags |= WIMLIB_RESOURCE_FLAG_RAW;
355 write_ctx.doing_sha = false;
357 write_ctx.doing_sha = true;
358 sha1_init(&write_ctx.sha_ctx);
361 /* Initialize the chunk table and set the compression function if
362 * compressing the resource. */
363 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
364 (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
365 write_ctx.compress = NULL;
366 write_ctx.chunk_tab = NULL;
368 write_ctx.compress = get_compress_func(out_ctype);
369 ret = begin_wim_resource_chunk_tab(lte, out_fp,
371 &write_ctx.chunk_tab);
377 write_ctx.out_fp = out_fp;
378 ret = read_resource_prefix(lte, wim_resource_size(lte),
379 write_resource_cb, &write_ctx, 0);
381 /* Verify SHA1 message digest of the resource, or set the hash for the
383 if (write_ctx.doing_sha) {
384 u8 md[SHA1_HASH_SIZE];
385 sha1_final(md, &write_ctx.sha_ctx);
387 copy_hash(lte->hash, md);
388 } else if (!hashes_equal(md, lte->hash)) {
389 ERROR("WIM resource has incorrect hash!");
390 if (lte_filename_valid(lte)) {
391 ERROR("We were reading it from \"%"TS"\"; maybe "
392 "it changed while we were reading it.",
395 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
396 goto out_free_chunk_tab;
400 out_res_entry->flags = lte->resource_entry.flags;
401 out_res_entry->original_size = wim_resource_size(lte);
402 out_res_entry->offset = offset;
403 if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
404 /* Doing a raw write: The new compressed size is the same as
405 * the compressed size in the other WIM. */
406 new_size = lte->resource_entry.size;
407 } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
408 /* Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size
409 * is the original size. */
410 new_size = lte->resource_entry.original_size;
411 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
413 /* Using a different compression type: Call
414 * finish_wim_resource_chunk_tab() and it will provide the new
415 * compressed size. */
416 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
419 goto out_free_chunk_tab;
420 if (new_size >= wim_resource_size(lte)) {
421 /* Oops! We compressed the resource to larger than the original
422 * size. Write the resource uncompressed instead. */
423 ret = write_uncompressed_resource_and_truncate(lte,
427 goto out_free_chunk_tab;
429 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
431 out_res_entry->size = new_size;
434 FREE(write_ctx.chunk_tab);
438 #ifdef ENABLE_MULTITHREADED_COMPRESSION
440 /* Blocking shared queue (solves the producer-consumer problem) */
441 struct shared_queue {
445 unsigned filled_slots;
447 pthread_mutex_t lock;
448 pthread_cond_t msg_avail_cond;
449 pthread_cond_t space_avail_cond;
453 shared_queue_init(struct shared_queue *q, unsigned size)
455 wimlib_assert(size != 0);
456 q->array = CALLOC(sizeof(q->array[0]), size);
458 return WIMLIB_ERR_NOMEM;
463 pthread_mutex_init(&q->lock, NULL);
464 pthread_cond_init(&q->msg_avail_cond, NULL);
465 pthread_cond_init(&q->space_avail_cond, NULL);
470 shared_queue_destroy(struct shared_queue *q)
473 pthread_mutex_destroy(&q->lock);
474 pthread_cond_destroy(&q->msg_avail_cond);
475 pthread_cond_destroy(&q->space_avail_cond);
479 shared_queue_put(struct shared_queue *q, void *obj)
481 pthread_mutex_lock(&q->lock);
482 while (q->filled_slots == q->size)
483 pthread_cond_wait(&q->space_avail_cond, &q->lock);
485 q->back = (q->back + 1) % q->size;
486 q->array[q->back] = obj;
489 pthread_cond_broadcast(&q->msg_avail_cond);
490 pthread_mutex_unlock(&q->lock);
494 shared_queue_get(struct shared_queue *q)
498 pthread_mutex_lock(&q->lock);
499 while (q->filled_slots == 0)
500 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
502 obj = q->array[q->front];
503 q->array[q->front] = NULL;
504 q->front = (q->front + 1) % q->size;
507 pthread_cond_broadcast(&q->space_avail_cond);
508 pthread_mutex_unlock(&q->lock);
512 struct compressor_thread_params {
513 struct shared_queue *res_to_compress_queue;
514 struct shared_queue *compressed_res_queue;
515 compress_func_t compress;
518 #define MAX_CHUNKS_PER_MSG 2
521 struct wim_lookup_table_entry *lte;
522 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
523 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
524 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
525 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
526 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
528 struct list_head list;
534 compress_chunks(struct message *msg, compress_func_t compress)
536 for (unsigned i = 0; i < msg->num_chunks; i++) {
537 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
538 unsigned len = compress(msg->uncompressed_chunks[i],
539 msg->uncompressed_chunk_sizes[i],
540 msg->compressed_chunks[i]);
542 /* To be written compressed */
543 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
544 msg->compressed_chunk_sizes[i] = len;
546 /* To be written uncompressed */
547 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
548 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
554 /* Compressor thread routine. This is a lot simpler than the main thread
555 * routine: just repeatedly get a group of chunks from the
556 * res_to_compress_queue, compress them, and put them in the
557 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
560 compressor_thread_proc(void *arg)
562 struct compressor_thread_params *params = arg;
563 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
564 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
565 compress_func_t compress = params->compress;
568 DEBUG("Compressor thread ready");
569 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
570 compress_chunks(msg, compress);
571 shared_queue_put(compressed_res_queue, msg);
573 DEBUG("Compressor thread terminating");
576 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
579 do_write_streams_progress(union wimlib_progress_info *progress,
580 wimlib_progress_func_t progress_func,
583 progress->write_streams.completed_bytes += size_added;
584 progress->write_streams.completed_streams++;
586 progress->write_streams.completed_bytes >= progress->write_streams._private)
588 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
590 if (progress->write_streams._private == progress->write_streams.total_bytes) {
591 progress->write_streams._private = ~0;
593 progress->write_streams._private =
594 min(progress->write_streams.total_bytes,
595 progress->write_streams.completed_bytes +
596 progress->write_streams.total_bytes / 100);
602 sha1_chunk(const void *buf, size_t len, void *ctx)
604 sha1_update(ctx, buf, len);
609 sha1_resource(struct wim_lookup_table_entry *lte)
615 ret = read_resource_prefix(lte, wim_resource_size(lte),
616 sha1_chunk, &sha_ctx, 0);
618 sha1_final(lte->hash, &sha_ctx);
624 STREAMS_NOT_MERGED = 1,
628 do_write_stream_list(struct list_head *my_resources,
629 struct wim_lookup_table *lookup_table,
632 wimlib_progress_func_t progress_func,
633 union wimlib_progress_info *progress,
634 int write_resource_flags)
637 struct wim_lookup_table_entry *lte;
639 while (!list_empty(my_resources)) {
640 lte = container_of(my_resources->next,
641 struct wim_lookup_table_entry,
643 list_del(<e->write_streams_list);
644 if (lte->unhashed && !lte->unique_size) {
645 struct wim_lookup_table_entry *duplicate_lte;
646 struct wim_lookup_table_entry **my_ptr;
648 my_ptr = lte->my_ptr;
649 ret = sha1_resource(lte);
652 duplicate_lte = __lookup_resource(lookup_table, lte->hash);
654 bool new_stream = (duplicate_lte->out_refcnt == 0);
655 duplicate_lte->refcnt += lte->refcnt;
656 duplicate_lte->out_refcnt += lte->refcnt;
657 *my_ptr = duplicate_lte;
658 free_lookup_table_entry(lte);
662 DEBUG("Stream of length %"PRIu64" is duplicate "
663 "with one already in WIM",
664 wim_resource_size(duplicate_lte));
666 DEBUG("Discarding duplicate stream of length %"PRIu64,
667 wim_resource_size(duplicate_lte));
668 goto skip_to_progress;
672 lookup_table_insert(lookup_table, lte);
673 lte->out_refcnt = lte->refcnt;
678 wimlib_assert(lte->out_refcnt != 0);
680 ret = write_wim_resource(lte,
683 <e->output_resource_entry,
684 write_resource_flags);
688 lookup_table_insert(lookup_table, lte);
692 do_write_streams_progress(progress,
694 wim_resource_size(lte));
700 write_stream_list_serial(struct list_head *stream_list,
701 struct wim_lookup_table *lookup_table,
705 wimlib_progress_func_t progress_func,
706 union wimlib_progress_info *progress)
708 int write_resource_flags;
710 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
711 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
713 write_resource_flags = 0;
714 progress->write_streams.num_threads = 1;
716 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
717 return do_write_stream_list(stream_list,
720 out_ctype, progress_func,
721 progress, write_resource_flags);
724 #ifdef ENABLE_MULTITHREADED_COMPRESSION
726 write_wim_chunks(struct message *msg, FILE *out_fp,
727 struct chunk_table *chunk_tab)
729 for (unsigned i = 0; i < msg->num_chunks; i++) {
730 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
732 DEBUG2("Write wim chunk %u of %u (csize = %u)",
733 i, msg->num_chunks, chunk_csize);
735 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
738 ERROR_WITH_ERRNO("Failed to write WIM chunk");
739 return WIMLIB_ERR_WRITE;
742 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
743 chunk_tab->cur_offset += chunk_csize;
749 * This function is executed by the main thread when the resources are being
750 * compressed in parallel. The main thread is in change of all reading of the
751 * uncompressed data and writing of the compressed data. The compressor threads
752 * *only* do compression from/to in-memory buffers.
754 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
755 * chunks of compressed data to compress, represented in a `struct message'.
756 * Each message is passed from the main thread to a worker thread through the
757 * res_to_compress_queue, and it is passed back through the
758 * compressed_res_queue.
761 main_writer_thread_proc(struct list_head *stream_list,
764 struct shared_queue *res_to_compress_queue,
765 struct shared_queue *compressed_res_queue,
768 wimlib_progress_func_t progress_func,
769 union wimlib_progress_info *progress)
772 struct chunk_table *cur_chunk_tab = NULL;
773 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
774 struct wim_lookup_table_entry *next_lte = NULL;
776 // Initially, all the messages are available to use.
777 LIST_HEAD(available_msgs);
780 ret = WIMLIB_ERR_NOMEM;
784 for (size_t i = 0; i < num_messages; i++)
785 list_add(&msgs[i].list, &available_msgs);
787 // outstanding_resources is the list of resources that currently have
788 // had chunks sent off for compression.
790 // The first stream in outstanding_resources is the stream that is
791 // currently being written (cur_lte).
793 // The last stream in outstanding_resources is the stream that is
794 // currently being read and chunks fed to the compressor threads
797 // Depending on the number of threads and the sizes of the resource,
798 // the outstanding streams list may contain streams between cur_lte and
799 // next_lte that have all their chunks compressed or being compressed,
800 // but haven't been written yet.
802 LIST_HEAD(outstanding_resources);
803 struct list_head *next_resource = stream_list->next;
805 u64 next_num_chunks = 0;
807 // As in write_wim_resource(), each resource we read is checksummed.
808 SHA_CTX next_sha_ctx;
809 u8 next_hash[SHA1_HASH_SIZE];
811 // Resources that don't need any chunks compressed are added to this
812 // list and written directly by the main thread.
813 LIST_HEAD(my_resources);
815 struct wim_lookup_table_entry *cur_lte = NULL;
819 ntfs_inode *ni = NULL;
822 DEBUG("Initializing buffers for uncompressed "
823 "and compressed data (%zu bytes needed)",
824 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
826 // Pre-allocate all the buffers that will be needed to do the chunk
828 for (size_t i = 0; i < num_messages; i++) {
829 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
830 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
832 // The extra 8 bytes is because longest_match() in
833 // lz77.c may read a little bit off the end of the
834 // uncompressed data. It doesn't need to be
835 // initialized--- we really just need to avoid accessing
837 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
838 if (msgs[i].compressed_chunks[j] == NULL ||
839 msgs[i].uncompressed_chunks[j] == NULL)
841 ret = WIMLIB_ERR_NOMEM;
847 // This loop is executed until all resources have been written, except
848 // possibly a few that have been added to the @my_resources list for
851 // Send chunks to the compressor threads until either (a) there
852 // are no more messages available since they were all sent off,
853 // or (b) there are no more resources that need to be
855 while (!list_empty(&available_msgs)) {
856 if (next_chunk == next_num_chunks) {
857 // If next_chunk == next_num_chunks, there are
858 // no more chunks to write in the current
859 // stream. So, check the SHA1 message digest of
860 // the stream that was just finished (unless
861 // next_lte == NULL, which is the case the very
862 // first time this loop is entered, and also
863 // near the very end of the compression when
864 // there are no more streams.) Then, advance to
865 // the next stream (if there is one).
866 if (next_lte != NULL) {
868 end_wim_resource_read(next_lte, ni);
871 end_wim_resource_read(next_lte);
873 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
875 sha1_final(next_hash, &next_sha_ctx);
876 if (!hashes_equal(next_lte->hash, next_hash)) {
877 ERROR("WIM resource has incorrect hash!");
878 if (next_lte->resource_location ==
879 RESOURCE_IN_FILE_ON_DISK)
881 ERROR("We were reading it from `%"TS"'; "
882 "maybe it changed while we were "
884 next_lte->file_on_disk);
886 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
891 // Advance to the next resource.
893 // If the next resource needs no compression, just write
894 // it with this thread (not now though--- we could be in
895 // the middle of writing another resource.) Keep doing
896 // this until we either get to the end of the resources
897 // list, or we get to a resource that needs compression.
899 if (next_resource == stream_list) {
900 // No more resources to send for
905 next_lte = container_of(next_resource,
906 struct wim_lookup_table_entry,
908 next_resource = next_resource->next;
909 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
910 && wim_resource_compression_type(next_lte) == out_ctype)
911 || wim_resource_size(next_lte) == 0)
913 list_add_tail(&next_lte->staging_list,
916 list_add_tail(&next_lte->staging_list,
917 &outstanding_resources);
919 next_num_chunks = wim_resource_chunks(next_lte);
920 sha1_init(&next_sha_ctx);
921 INIT_LIST_HEAD(&next_lte->msg_list);
923 ret = prepare_resource_for_read(next_lte, &ni);
925 ret = prepare_resource_for_read(next_lte);
930 if (cur_lte == NULL) {
931 // Set cur_lte for the
940 if (next_lte == NULL) {
941 // No more resources to send for compression
945 // Get a message from the available messages
947 msg = container_of(available_msgs.next,
951 // ... and delete it from the available messages
953 list_del(&msg->list);
955 // Initialize the message with the chunks to
957 msg->num_chunks = min(next_num_chunks - next_chunk,
960 msg->complete = false;
961 msg->begin_chunk = next_chunk;
963 unsigned size = WIM_CHUNK_SIZE;
964 for (unsigned i = 0; i < msg->num_chunks; i++) {
966 // Read chunk @next_chunk of the stream into the
967 // message so that a compressor thread can
970 if (next_chunk == next_num_chunks - 1) {
971 size = MODULO_NONZERO(wim_resource_size(next_lte),
975 DEBUG2("Read resource (size=%u, offset=%zu)",
976 size, next_chunk * WIM_CHUNK_SIZE);
978 msg->uncompressed_chunk_sizes[i] = size;
980 ret = read_wim_resource(next_lte,
981 msg->uncompressed_chunks[i],
983 next_chunk * WIM_CHUNK_SIZE,
987 sha1_update(&next_sha_ctx,
988 msg->uncompressed_chunks[i], size);
992 // Send the compression request
993 list_add_tail(&msg->list, &next_lte->msg_list);
994 shared_queue_put(res_to_compress_queue, msg);
995 DEBUG2("Compression request sent");
998 // If there are no outstanding resources, there are no more
999 // resources that need to be written.
1000 if (list_empty(&outstanding_resources)) {
1005 // Get the next message from the queue and process it.
1006 // The message will contain 1 or more data chunks that have been
1008 msg = shared_queue_get(compressed_res_queue);
1009 msg->complete = true;
1011 // Is this the next chunk in the current resource? If it's not
1012 // (i.e., an earlier chunk in a same or different resource
1013 // hasn't been compressed yet), do nothing, and keep this
1014 // message around until all earlier chunks are received.
1016 // Otherwise, write all the chunks we can.
1017 while (cur_lte != NULL &&
1018 !list_empty(&cur_lte->msg_list) &&
1019 (msg = container_of(cur_lte->msg_list.next,
1023 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1024 if (msg->begin_chunk == 0) {
1025 DEBUG2("Begin chunk tab");
1027 // This is the first set of chunks. Leave space
1028 // for the chunk table in the output file.
1029 off_t cur_offset = ftello(out_fp);
1030 if (cur_offset == -1) {
1031 ret = WIMLIB_ERR_WRITE;
1034 ret = begin_wim_resource_chunk_tab(cur_lte,
1042 // Write the compressed chunks from the message.
1043 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1047 list_del(&msg->list);
1049 // This message is available to use for different chunks
1051 list_add(&msg->list, &available_msgs);
1053 // Was this the last chunk of the stream? If so, finish
1055 if (list_empty(&cur_lte->msg_list) &&
1056 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1058 DEBUG2("Finish wim chunk tab");
1060 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1066 if (res_csize >= wim_resource_size(cur_lte)) {
1067 /* Oops! We compressed the resource to
1068 * larger than the original size. Write
1069 * the resource uncompressed instead. */
1070 ret = write_uncompressed_resource_and_truncate(
1073 cur_chunk_tab->file_offset,
1074 &cur_lte->output_resource_entry);
1078 cur_lte->output_resource_entry.size =
1081 cur_lte->output_resource_entry.original_size =
1082 cur_lte->resource_entry.original_size;
1084 cur_lte->output_resource_entry.offset =
1085 cur_chunk_tab->file_offset;
1087 cur_lte->output_resource_entry.flags =
1088 cur_lte->resource_entry.flags |
1089 WIM_RESHDR_FLAG_COMPRESSED;
1092 do_write_streams_progress(progress, progress_func,
1093 wim_resource_size(cur_lte));
1095 FREE(cur_chunk_tab);
1096 cur_chunk_tab = NULL;
1098 struct list_head *next = cur_lte->staging_list.next;
1099 list_del(&cur_lte->staging_list);
1101 if (next == &outstanding_resources)
1104 cur_lte = container_of(cur_lte->staging_list.next,
1105 struct wim_lookup_table_entry,
1108 // Since we just finished writing a stream,
1109 // write any streams that have been added to the
1110 // my_resources list for direct writing by the
1111 // main thread (e.g. resources that don't need
1112 // to be compressed because the desired
1113 // compression type is the same as the previous
1114 // compression type).
1115 ret = do_write_stream_list(&my_resources,
1128 if (ret == WIMLIB_ERR_NOMEM) {
1129 ERROR("Could not allocate enough memory for "
1130 "multi-threaded compression");
1135 end_wim_resource_read(next_lte, ni);
1137 end_wim_resource_read(next_lte);
1142 ret = do_write_stream_list(&my_resources, out_fp,
1143 out_ctype, progress_func,
1147 size_t num_available_msgs = 0;
1148 struct list_head *cur;
1150 list_for_each(cur, &available_msgs) {
1151 num_available_msgs++;
1154 while (num_available_msgs < num_messages) {
1155 shared_queue_get(compressed_res_queue);
1156 num_available_msgs++;
1162 for (size_t i = 0; i < num_messages; i++) {
1163 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1164 FREE(msgs[i].compressed_chunks[j]);
1165 FREE(msgs[i].uncompressed_chunks[j]);
1171 FREE(cur_chunk_tab);
1176 get_default_num_threads()
1179 return win32_get_number_of_processors();
1181 return sysconf(_SC_NPROCESSORS_ONLN);
1186 write_stream_list_parallel(struct list_head *stream_list,
1187 struct wim_lookup_table *lookup_table,
1191 unsigned num_threads,
1192 wimlib_progress_func_t progress_func,
1193 union wimlib_progress_info *progress)
1196 struct shared_queue res_to_compress_queue;
1197 struct shared_queue compressed_res_queue;
1198 pthread_t *compressor_threads = NULL;
1200 if (num_threads == 0) {
1201 long nthreads = get_default_num_threads();
1202 if (nthreads < 1 || nthreads > UINT_MAX) {
1203 WARNING("Could not determine number of processors! Assuming 1");
1206 num_threads = nthreads;
1210 progress->write_streams.num_threads = num_threads;
1211 wimlib_assert(stream_list->next != stream_list);
1213 static const double MESSAGES_PER_THREAD = 2.0;
1214 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1216 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1218 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1222 ret = shared_queue_init(&compressed_res_queue, queue_size);
1224 goto out_destroy_res_to_compress_queue;
1226 struct compressor_thread_params params;
1227 params.res_to_compress_queue = &res_to_compress_queue;
1228 params.compressed_res_queue = &compressed_res_queue;
1229 params.compress = get_compress_func(out_ctype);
1231 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1232 if (!compressor_threads) {
1233 ret = WIMLIB_ERR_NOMEM;
1234 goto out_destroy_compressed_res_queue;
1237 for (unsigned i = 0; i < num_threads; i++) {
1238 DEBUG("pthread_create thread %u", i);
1239 ret = pthread_create(&compressor_threads[i], NULL,
1240 compressor_thread_proc, ¶ms);
1243 ERROR_WITH_ERRNO("Failed to create compressor "
1251 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1253 ret = main_writer_thread_proc(stream_list,
1256 &res_to_compress_queue,
1257 &compressed_res_queue,
1263 for (unsigned i = 0; i < num_threads; i++)
1264 shared_queue_put(&res_to_compress_queue, NULL);
1266 for (unsigned i = 0; i < num_threads; i++) {
1267 if (pthread_join(compressor_threads[i], NULL)) {
1268 WARNING_WITH_ERRNO("Failed to join compressor "
1272 FREE(compressor_threads);
1273 out_destroy_compressed_res_queue:
1274 shared_queue_destroy(&compressed_res_queue);
1275 out_destroy_res_to_compress_queue:
1276 shared_queue_destroy(&res_to_compress_queue);
1277 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1280 WARNING("Falling back to single-threaded compression");
1281 return write_stream_list_serial(stream_list,
1293 * Write a list of streams to a WIM (@out_fp) using the compression type
1294 * @out_ctype and up to @num_threads compressor threads.
1297 write_stream_list(struct list_head *stream_list,
1298 struct wim_lookup_table *lookup_table,
1299 FILE *out_fp, int out_ctype, int write_flags,
1300 unsigned num_threads, wimlib_progress_func_t progress_func)
1302 struct wim_lookup_table_entry *lte;
1303 size_t num_streams = 0;
1304 u64 total_bytes = 0;
1305 u64 total_compression_bytes = 0;
1306 union wimlib_progress_info progress;
1309 list_for_each_entry(lte, stream_list, write_streams_list) {
1311 total_bytes += wim_resource_size(lte);
1312 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1313 && (wim_resource_compression_type(lte) != out_ctype ||
1314 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1316 total_compression_bytes += wim_resource_size(lte);
1319 progress.write_streams.total_bytes = total_bytes;
1320 progress.write_streams.total_streams = num_streams;
1321 progress.write_streams.completed_bytes = 0;
1322 progress.write_streams.completed_streams = 0;
1323 progress.write_streams.num_threads = num_threads;
1324 progress.write_streams.compression_type = out_ctype;
1325 progress.write_streams._private = 0;
1327 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1328 if (total_compression_bytes >= 1000000 && num_threads != 1)
1329 ret = write_stream_list_parallel(stream_list,
1339 ret = write_stream_list_serial(stream_list,
1349 struct lte_overwrite_prepare_args {
1352 struct list_head *stream_list;
1356 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1358 struct lte_overwrite_prepare_args *args = arg;
1360 if (lte->resource_location == RESOURCE_IN_WIM &&
1361 lte->wim == args->wim &&
1362 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1364 #ifdef ENABLE_ERROR_MESSAGES
1365 ERROR("The following resource is after the XML data:");
1366 print_lookup_table_entry(lte, stderr);
1368 return WIMLIB_ERR_RESOURCE_ORDER;
1371 lte->out_refcnt = lte->refcnt;
1372 memcpy(<e->output_resource_entry, <e->resource_entry,
1373 sizeof(struct resource_entry));
1374 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1375 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1376 list_add(<e->staging_list, args->stream_list);
1381 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1382 struct list_head *stream_list)
1384 struct lte_overwrite_prepare_args args = {
1386 .end_offset = end_offset,
1387 .stream_list = stream_list,
1391 for (int i = 0; i < wim->hdr.image_count; i++) {
1392 ret = lte_overwrite_prepare(wim->image_metadata[i]->metadata_lte,
1397 return for_lookup_table_entry(wim->lookup_table,
1398 lte_overwrite_prepare, &args);
1401 struct stream_size_table {
1402 struct hlist_head *array;
1408 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1410 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1412 return WIMLIB_ERR_NOMEM;
1413 tab->num_entries = 0;
1414 tab->capacity = capacity;
1419 destroy_stream_size_table(struct stream_size_table *tab)
1425 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1427 struct stream_size_table *tab = _tab;
1429 struct wim_lookup_table_entry *hashed_lte;
1430 struct hlist_node *tmp;
1432 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1433 lte->unique_size = 1;
1434 hlist_for_each_entry(hashed_lte, tmp, &tab->array[pos], hash_list_2) {
1435 if (wim_resource_size(hashed_lte) == wim_resource_size(lte)) {
1436 lte->unique_size = 0;
1437 hashed_lte->unique_size = 0;
1442 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1448 struct find_streams_ctx {
1449 struct list_head stream_list;
1450 struct stream_size_table stream_size_tab;
1454 inode_find_streams_to_write(struct wim_inode *inode,
1455 struct wim_lookup_table *table,
1456 struct list_head *stream_list,
1457 struct stream_size_table *tab)
1459 struct wim_lookup_table_entry *lte;
1460 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1461 lte = inode_stream_lte(inode, i, table);
1463 if (lte->out_refcnt == 0) {
1465 stream_size_table_insert(lte, tab);
1466 list_add_tail(<e->write_streams_list, stream_list);
1468 lte->out_refcnt += inode->i_nlink;
1475 image_find_streams_to_write(WIMStruct *w)
1477 struct wim_image_metadata *imd;
1478 struct find_streams_ctx *ctx;
1479 struct wim_inode *inode;
1480 struct wim_lookup_table_entry *lte;
1483 imd = wim_get_current_image_metadata(w);
1485 image_for_each_unhashed_stream(lte, imd) {
1486 lte->out_refcnt = 0;
1487 wimlib_assert(lte->unhashed);
1488 wimlib_assert(lte->my_ptr != NULL);
1491 /* Go through this image's inodes to find any streams that have not been
1493 image_for_each_inode(inode, imd) {
1494 inode_find_streams_to_write(inode, w->lookup_table,
1496 &ctx->stream_size_tab);
1501 /* Given a WIM that from which one or all of the images is being written, build
1502 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1503 * written, plus any unhashed streams that need to be written but may be
1504 * identical to other hashed or unhashed streams being written. These unhashed
1505 * streams are checksummed while the streams are being written. To aid this
1506 * process, the member @unique_size is set to 1 on streams that have a unique
1507 * size and therefore must be written.
1509 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1510 * indicate the number of times the stream is referenced in only the streams
1511 * that are being written; this may still be adjusted later when unhashed
1512 * streams are being resolved.
1515 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1518 struct find_streams_ctx ctx;
1520 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1521 ret = init_stream_size_table(&ctx.stream_size_tab, 9001);
1524 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1525 &ctx.stream_size_tab);
1526 INIT_LIST_HEAD(&ctx.stream_list);
1527 wim->private = &ctx;
1528 for_image(wim, image, image_find_streams_to_write);
1529 destroy_stream_size_table(&ctx.stream_size_tab);
1531 INIT_LIST_HEAD(stream_list);
1532 list_splice(&ctx.stream_list, stream_list);
1536 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1539 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1540 unsigned num_threads,
1541 wimlib_progress_func_t progress_func)
1544 struct list_head stream_list;
1546 ret = prepare_stream_list(wim, image, &stream_list);
1549 return write_stream_list(&stream_list,
1552 wimlib_get_compression_type(wim),
1559 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1560 * table (optional), then overwrite the WIM header.
1562 * write_flags is a bitwise OR of the following:
1564 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1565 * Include an integrity table.
1567 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1568 * Show progress information when (if) writing the integrity table.
1570 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1571 * Don't write the lookup table.
1573 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1574 * When (if) writing the integrity table, re-use entries from the
1575 * existing integrity table, if possible.
1577 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1578 * After writing the XML data but before writing the integrity
1579 * table, write a temporary WIM header and flush the stream so that
1580 * the WIM is less likely to become corrupted upon abrupt program
1583 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1584 * fsync() the output file before closing it.
1588 finish_write(WIMStruct *w, int image, int write_flags,
1589 wimlib_progress_func_t progress_func)
1592 struct wim_header hdr;
1593 FILE *out = w->out_fp;
1595 /* @hdr will be the header for the new WIM. First copy all the data
1596 * from the header in the WIMStruct; then set all the fields that may
1597 * have changed, including the resource entries, boot index, and image
1599 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1601 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1602 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1607 ret = write_xml_data(w->wim_info, image, out,
1608 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1609 wim_info_get_total_bytes(w->wim_info) : 0,
1610 &hdr.xml_res_entry);
1614 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1615 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1616 struct wim_header checkpoint_hdr;
1617 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1618 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1619 if (fseeko(out, 0, SEEK_SET) != 0) {
1620 ERROR_WITH_ERRNO("Failed to seek to beginning "
1621 "of WIM being written");
1622 ret = WIMLIB_ERR_WRITE;
1625 ret = write_header(&checkpoint_hdr, out);
1629 if (fflush(out) != 0) {
1630 ERROR_WITH_ERRNO("Can't write data to WIM");
1631 ret = WIMLIB_ERR_WRITE;
1635 if (fseeko(out, 0, SEEK_END) != 0) {
1636 ERROR_WITH_ERRNO("Failed to seek to end "
1637 "of WIM being written");
1638 ret = WIMLIB_ERR_WRITE;
1643 off_t old_lookup_table_end;
1644 off_t new_lookup_table_end;
1645 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1646 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1647 w->hdr.lookup_table_res_entry.size;
1649 old_lookup_table_end = 0;
1651 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1652 hdr.lookup_table_res_entry.size;
1654 ret = write_integrity_table(out,
1656 new_lookup_table_end,
1657 old_lookup_table_end,
1662 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1666 * In the WIM header, there is room for the resource entry for a
1667 * metadata resource labeled as the "boot metadata". This entry should
1668 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1669 * it should be a copy of the resource entry for the image that is
1670 * marked as bootable. This is not well documented...
1673 /* Set image count and boot index correctly for single image writes */
1674 if (image != WIMLIB_ALL_IMAGES) {
1675 hdr.image_count = 1;
1676 if (hdr.boot_idx == image)
1682 if (hdr.boot_idx == 0) {
1683 memset(&hdr.boot_metadata_res_entry, 0,
1684 sizeof(struct resource_entry));
1686 memcpy(&hdr.boot_metadata_res_entry,
1688 hdr.boot_idx - 1]->metadata_lte->output_resource_entry,
1689 sizeof(struct resource_entry));
1692 if (fseeko(out, 0, SEEK_SET) != 0) {
1693 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1695 ret = WIMLIB_ERR_WRITE;
1699 ret = write_header(&hdr, out);
1703 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1704 if (fflush(out) != 0
1705 || fsync(fileno(out)) != 0)
1707 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1708 ret = WIMLIB_ERR_WRITE;
1712 if (fclose(out) != 0) {
1713 ERROR_WITH_ERRNO("Failed to close the WIM file");
1715 ret = WIMLIB_ERR_WRITE;
1721 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1723 lock_wim(WIMStruct *w, FILE *fp)
1726 if (fp && !w->wim_locked) {
1727 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1729 if (errno == EWOULDBLOCK) {
1730 ERROR("`%"TS"' is already being modified or has been "
1731 "mounted read-write\n"
1732 " by another process!", w->filename);
1733 ret = WIMLIB_ERR_ALREADY_LOCKED;
1735 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1748 open_wim_writable(WIMStruct *w, const tchar *path,
1749 bool trunc, bool also_readable)
1760 wimlib_assert(w->out_fp == NULL);
1761 w->out_fp = tfopen(path, mode);
1765 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1766 return WIMLIB_ERR_OPEN;
1772 close_wim_writable(WIMStruct *w)
1775 if (fclose(w->out_fp) != 0) {
1776 WARNING_WITH_ERRNO("Failed to close output WIM");
1782 /* Open file stream and write dummy header for WIM. */
1784 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1787 ret = open_wim_writable(w, path, true,
1788 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1791 /* Write dummy header. It will be overwritten later. */
1792 return write_header(&w->hdr, w->out_fp);
1795 /* Writes a stand-alone WIM to a file. */
1797 wimlib_write(WIMStruct *w, const tchar *path,
1798 int image, int write_flags, unsigned num_threads,
1799 wimlib_progress_func_t progress_func)
1804 return WIMLIB_ERR_INVALID_PARAM;
1806 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1808 if (image != WIMLIB_ALL_IMAGES &&
1809 (image < 1 || image > w->hdr.image_count))
1810 return WIMLIB_ERR_INVALID_IMAGE;
1812 if (w->hdr.total_parts != 1) {
1813 ERROR("Cannot call wimlib_write() on part of a split WIM");
1814 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1817 ret = begin_write(w, path, write_flags);
1821 ret = write_wim_streams(w, image, write_flags, num_threads,
1827 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1829 ret = for_image(w, image, write_metadata_resource);
1834 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1836 ret = finish_write(w, image, write_flags, progress_func);
1838 close_wim_writable(w);
1839 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1844 any_images_modified(WIMStruct *w)
1846 for (int i = 0; i < w->hdr.image_count; i++)
1847 if (w->image_metadata[i]->modified)
1853 * Overwrite a WIM, possibly appending streams to it.
1855 * A WIM looks like (or is supposed to look like) the following:
1857 * Header (212 bytes)
1858 * Streams and metadata resources (variable size)
1859 * Lookup table (variable size)
1860 * XML data (variable size)
1861 * Integrity table (optional) (variable size)
1863 * If we are not adding any streams or metadata resources, the lookup table is
1864 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1865 * header. This operation is potentially unsafe if the program is abruptly
1866 * terminated while the XML data or integrity table are being overwritten, but
1867 * before the new header has been written. To partially alleviate this problem,
1868 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1869 * finish_write() to cause a temporary WIM header to be written after the XML
1870 * data has been written. This may prevent the WIM from becoming corrupted if
1871 * the program is terminated while the integrity table is being calculated (but
1872 * no guarantees, due to write re-ordering...).
1874 * If we are adding new streams or images (metadata resources), the lookup table
1875 * needs to be changed, and those streams need to be written. In this case, we
1876 * try to perform a safe update of the WIM file by writing the streams *after*
1877 * the end of the previous WIM, then writing the new lookup table, XML data, and
1878 * (optionally) integrity table following the new streams. This will produce a
1879 * layout like the following:
1881 * Header (212 bytes)
1882 * (OLD) Streams and metadata resources (variable size)
1883 * (OLD) Lookup table (variable size)
1884 * (OLD) XML data (variable size)
1885 * (OLD) Integrity table (optional) (variable size)
1886 * (NEW) Streams and metadata resources (variable size)
1887 * (NEW) Lookup table (variable size)
1888 * (NEW) XML data (variable size)
1889 * (NEW) Integrity table (optional) (variable size)
1891 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1892 * the header is overwritten to point to the new lookup table, XML data, and
1893 * integrity table, to produce the following layout:
1895 * Header (212 bytes)
1896 * Streams and metadata resources (variable size)
1897 * Nothing (variable size)
1898 * More Streams and metadata resources (variable size)
1899 * Lookup table (variable size)
1900 * XML data (variable size)
1901 * Integrity table (optional) (variable size)
1903 * This method allows an image to be appended to a large WIM very quickly, and
1904 * is is crash-safe except in the case of write re-ordering, but the
1905 * disadvantage is that a small hole is left in the WIM where the old lookup
1906 * table, xml data, and integrity table were. (These usually only take up a
1907 * small amount of space compared to the streams, however.)
1910 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1911 unsigned num_threads,
1912 wimlib_progress_func_t progress_func)
1915 struct list_head stream_list;
1918 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1920 /* Make sure that the integrity table (if present) is after the XML
1921 * data, and that there are no stream resources, metadata resources, or
1922 * lookup tables after the XML data. Otherwise, these data would be
1924 if (w->hdr.integrity.offset != 0 &&
1925 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1926 ERROR("Didn't expect the integrity table to be before the XML data");
1927 return WIMLIB_ERR_RESOURCE_ORDER;
1930 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1931 ERROR("Didn't expect the lookup table to be after the XML data");
1932 return WIMLIB_ERR_RESOURCE_ORDER;
1936 if (w->hdr.integrity.offset)
1937 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1939 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1941 if (!w->deletion_occurred && !any_images_modified(w)) {
1942 /* If no images have been modified and no images have been
1943 * deleted, a new lookup table does not need to be written. */
1944 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1945 w->hdr.lookup_table_res_entry.size;
1946 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1947 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1949 INIT_LIST_HEAD(&stream_list);
1950 ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1954 ret = open_wim_writable(w, w->filename, false,
1955 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1959 ret = lock_wim(w, w->out_fp);
1966 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1967 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1971 return WIMLIB_ERR_WRITE;
1974 if (!list_empty(&stream_list)) {
1975 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1977 ret = write_stream_list(&stream_list,
1980 wimlib_get_compression_type(w),
1981 write_flags, num_threads,
1986 DEBUG("No new streams were added");
1989 for (int i = 0; i < w->hdr.image_count; i++) {
1990 if (w->image_metadata[i]->modified) {
1991 select_wim_image(w, i + 1);
1992 ret = write_metadata_resource(w);
1997 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1998 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2001 close_wim_writable(w);
2002 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2003 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2004 w->filename, old_wim_end);
2005 /* Return value of truncate() is ignored because this is already
2007 (void)ttruncate(w->filename, old_wim_end);
2014 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2015 unsigned num_threads,
2016 wimlib_progress_func_t progress_func)
2018 size_t wim_name_len;
2021 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2023 /* Write the WIM to a temporary file in the same directory as the
2025 wim_name_len = tstrlen(w->filename);
2026 tchar tmpfile[wim_name_len + 10];
2027 tmemcpy(tmpfile, w->filename, wim_name_len);
2028 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2029 tmpfile[wim_name_len + 9] = T('\0');
2031 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2032 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2033 num_threads, progress_func);
2035 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2039 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2042 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2043 * specified to CreateFile(). The WIM was opened with fopen(), which
2044 * didn't provided this flag to CreateFile, so the handle must be closed
2045 * before executing the rename(). */
2046 if (w->fp != NULL) {
2052 /* Rename the new file to the old file .*/
2053 if (trename(tmpfile, w->filename) != 0) {
2054 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2055 tmpfile, w->filename);
2056 ret = WIMLIB_ERR_RENAME;
2060 if (progress_func) {
2061 union wimlib_progress_info progress;
2062 progress.rename.from = tmpfile;
2063 progress.rename.to = w->filename;
2064 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2067 /* Close the original WIM file that was opened for reading. */
2068 if (w->fp != NULL) {
2073 /* Re-open the WIM read-only. */
2074 w->fp = tfopen(w->filename, T("rb"));
2075 if (w->fp == NULL) {
2076 ret = WIMLIB_ERR_REOPEN;
2077 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2084 /* Remove temporary file. */
2085 if (tunlink(tmpfile) != 0)
2086 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2091 * Writes a WIM file to the original file that it was read from, overwriting it.
2094 wimlib_overwrite(WIMStruct *w, int write_flags,
2095 unsigned num_threads,
2096 wimlib_progress_func_t progress_func)
2098 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2101 return WIMLIB_ERR_NO_FILENAME;
2103 if (w->hdr.total_parts != 1) {
2104 ERROR("Cannot modify a split WIM");
2105 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2108 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2109 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2112 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2114 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2115 WARNING("Falling back to re-building entire WIM");
2119 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,