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);
661 DEBUG("Stream of length %"PRIu64" is duplicate "
662 "with one already in WIM",
663 wim_resource_size(lte));
665 DEBUG("Discarding duplicate stream of length %"PRIu64,
666 wim_resource_size(lte));
667 goto skip_to_progress;
671 lookup_table_insert(lookup_table, lte);
672 lte->out_refcnt = lte->refcnt;
677 wimlib_assert(lte->out_refcnt != 0);
679 ret = write_wim_resource(lte,
682 <e->output_resource_entry,
683 write_resource_flags);
687 lookup_table_insert(lookup_table, lte);
691 do_write_streams_progress(progress,
693 wim_resource_size(lte));
699 write_stream_list_serial(struct list_head *stream_list,
700 struct wim_lookup_table *lookup_table,
704 wimlib_progress_func_t progress_func,
705 union wimlib_progress_info *progress)
707 int write_resource_flags;
709 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
710 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
712 write_resource_flags = 0;
713 progress->write_streams.num_threads = 1;
715 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
716 return do_write_stream_list(stream_list,
719 out_ctype, progress_func,
720 progress, write_resource_flags);
723 #ifdef ENABLE_MULTITHREADED_COMPRESSION
725 write_wim_chunks(struct message *msg, FILE *out_fp,
726 struct chunk_table *chunk_tab)
728 for (unsigned i = 0; i < msg->num_chunks; i++) {
729 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
731 DEBUG2("Write wim chunk %u of %u (csize = %u)",
732 i, msg->num_chunks, chunk_csize);
734 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
737 ERROR_WITH_ERRNO("Failed to write WIM chunk");
738 return WIMLIB_ERR_WRITE;
741 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
742 chunk_tab->cur_offset += chunk_csize;
748 * This function is executed by the main thread when the resources are being
749 * compressed in parallel. The main thread is in change of all reading of the
750 * uncompressed data and writing of the compressed data. The compressor threads
751 * *only* do compression from/to in-memory buffers.
753 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
754 * chunks of compressed data to compress, represented in a `struct message'.
755 * Each message is passed from the main thread to a worker thread through the
756 * res_to_compress_queue, and it is passed back through the
757 * compressed_res_queue.
760 main_writer_thread_proc(struct list_head *stream_list,
763 struct shared_queue *res_to_compress_queue,
764 struct shared_queue *compressed_res_queue,
767 wimlib_progress_func_t progress_func,
768 union wimlib_progress_info *progress)
771 struct chunk_table *cur_chunk_tab = NULL;
772 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
773 struct wim_lookup_table_entry *next_lte = NULL;
775 // Initially, all the messages are available to use.
776 LIST_HEAD(available_msgs);
779 ret = WIMLIB_ERR_NOMEM;
783 for (size_t i = 0; i < num_messages; i++)
784 list_add(&msgs[i].list, &available_msgs);
786 // outstanding_resources is the list of resources that currently have
787 // had chunks sent off for compression.
789 // The first stream in outstanding_resources is the stream that is
790 // currently being written (cur_lte).
792 // The last stream in outstanding_resources is the stream that is
793 // currently being read and chunks fed to the compressor threads
796 // Depending on the number of threads and the sizes of the resource,
797 // the outstanding streams list may contain streams between cur_lte and
798 // next_lte that have all their chunks compressed or being compressed,
799 // but haven't been written yet.
801 LIST_HEAD(outstanding_resources);
802 struct list_head *next_resource = stream_list->next;
804 u64 next_num_chunks = 0;
806 // As in write_wim_resource(), each resource we read is checksummed.
807 SHA_CTX next_sha_ctx;
808 u8 next_hash[SHA1_HASH_SIZE];
810 // Resources that don't need any chunks compressed are added to this
811 // list and written directly by the main thread.
812 LIST_HEAD(my_resources);
814 struct wim_lookup_table_entry *cur_lte = NULL;
818 ntfs_inode *ni = NULL;
821 DEBUG("Initializing buffers for uncompressed "
822 "and compressed data (%zu bytes needed)",
823 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
825 // Pre-allocate all the buffers that will be needed to do the chunk
827 for (size_t i = 0; i < num_messages; i++) {
828 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
829 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
831 // The extra 8 bytes is because longest_match() in
832 // lz77.c may read a little bit off the end of the
833 // uncompressed data. It doesn't need to be
834 // initialized--- we really just need to avoid accessing
836 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
837 if (msgs[i].compressed_chunks[j] == NULL ||
838 msgs[i].uncompressed_chunks[j] == NULL)
840 ret = WIMLIB_ERR_NOMEM;
846 // This loop is executed until all resources have been written, except
847 // possibly a few that have been added to the @my_resources list for
850 // Send chunks to the compressor threads until either (a) there
851 // are no more messages available since they were all sent off,
852 // or (b) there are no more resources that need to be
854 while (!list_empty(&available_msgs)) {
855 if (next_chunk == next_num_chunks) {
856 // If next_chunk == next_num_chunks, there are
857 // no more chunks to write in the current
858 // stream. So, check the SHA1 message digest of
859 // the stream that was just finished (unless
860 // next_lte == NULL, which is the case the very
861 // first time this loop is entered, and also
862 // near the very end of the compression when
863 // there are no more streams.) Then, advance to
864 // the next stream (if there is one).
865 if (next_lte != NULL) {
867 end_wim_resource_read(next_lte, ni);
870 end_wim_resource_read(next_lte);
872 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
874 sha1_final(next_hash, &next_sha_ctx);
875 if (!hashes_equal(next_lte->hash, next_hash)) {
876 ERROR("WIM resource has incorrect hash!");
877 if (next_lte->resource_location ==
878 RESOURCE_IN_FILE_ON_DISK)
880 ERROR("We were reading it from `%"TS"'; "
881 "maybe it changed while we were "
883 next_lte->file_on_disk);
885 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
890 // Advance to the next resource.
892 // If the next resource needs no compression, just write
893 // it with this thread (not now though--- we could be in
894 // the middle of writing another resource.) Keep doing
895 // this until we either get to the end of the resources
896 // list, or we get to a resource that needs compression.
898 if (next_resource == stream_list) {
899 // No more resources to send for
904 next_lte = container_of(next_resource,
905 struct wim_lookup_table_entry,
907 next_resource = next_resource->next;
908 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
909 && wim_resource_compression_type(next_lte) == out_ctype)
910 || wim_resource_size(next_lte) == 0)
912 list_add_tail(&next_lte->staging_list,
915 list_add_tail(&next_lte->staging_list,
916 &outstanding_resources);
918 next_num_chunks = wim_resource_chunks(next_lte);
919 sha1_init(&next_sha_ctx);
920 INIT_LIST_HEAD(&next_lte->msg_list);
922 ret = prepare_resource_for_read(next_lte, &ni);
924 ret = prepare_resource_for_read(next_lte);
929 if (cur_lte == NULL) {
930 // Set cur_lte for the
939 if (next_lte == NULL) {
940 // No more resources to send for compression
944 // Get a message from the available messages
946 msg = container_of(available_msgs.next,
950 // ... and delete it from the available messages
952 list_del(&msg->list);
954 // Initialize the message with the chunks to
956 msg->num_chunks = min(next_num_chunks - next_chunk,
959 msg->complete = false;
960 msg->begin_chunk = next_chunk;
962 unsigned size = WIM_CHUNK_SIZE;
963 for (unsigned i = 0; i < msg->num_chunks; i++) {
965 // Read chunk @next_chunk of the stream into the
966 // message so that a compressor thread can
969 if (next_chunk == next_num_chunks - 1) {
970 size = MODULO_NONZERO(wim_resource_size(next_lte),
974 DEBUG2("Read resource (size=%u, offset=%zu)",
975 size, next_chunk * WIM_CHUNK_SIZE);
977 msg->uncompressed_chunk_sizes[i] = size;
979 ret = read_wim_resource(next_lte,
980 msg->uncompressed_chunks[i],
982 next_chunk * WIM_CHUNK_SIZE,
986 sha1_update(&next_sha_ctx,
987 msg->uncompressed_chunks[i], size);
991 // Send the compression request
992 list_add_tail(&msg->list, &next_lte->msg_list);
993 shared_queue_put(res_to_compress_queue, msg);
994 DEBUG2("Compression request sent");
997 // If there are no outstanding resources, there are no more
998 // resources that need to be written.
999 if (list_empty(&outstanding_resources)) {
1004 // Get the next message from the queue and process it.
1005 // The message will contain 1 or more data chunks that have been
1007 msg = shared_queue_get(compressed_res_queue);
1008 msg->complete = true;
1010 // Is this the next chunk in the current resource? If it's not
1011 // (i.e., an earlier chunk in a same or different resource
1012 // hasn't been compressed yet), do nothing, and keep this
1013 // message around until all earlier chunks are received.
1015 // Otherwise, write all the chunks we can.
1016 while (cur_lte != NULL &&
1017 !list_empty(&cur_lte->msg_list) &&
1018 (msg = container_of(cur_lte->msg_list.next,
1022 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1023 if (msg->begin_chunk == 0) {
1024 DEBUG2("Begin chunk tab");
1026 // This is the first set of chunks. Leave space
1027 // for the chunk table in the output file.
1028 off_t cur_offset = ftello(out_fp);
1029 if (cur_offset == -1) {
1030 ret = WIMLIB_ERR_WRITE;
1033 ret = begin_wim_resource_chunk_tab(cur_lte,
1041 // Write the compressed chunks from the message.
1042 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1046 list_del(&msg->list);
1048 // This message is available to use for different chunks
1050 list_add(&msg->list, &available_msgs);
1052 // Was this the last chunk of the stream? If so, finish
1054 if (list_empty(&cur_lte->msg_list) &&
1055 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1057 DEBUG2("Finish wim chunk tab");
1059 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1065 if (res_csize >= wim_resource_size(cur_lte)) {
1066 /* Oops! We compressed the resource to
1067 * larger than the original size. Write
1068 * the resource uncompressed instead. */
1069 ret = write_uncompressed_resource_and_truncate(
1072 cur_chunk_tab->file_offset,
1073 &cur_lte->output_resource_entry);
1077 cur_lte->output_resource_entry.size =
1080 cur_lte->output_resource_entry.original_size =
1081 cur_lte->resource_entry.original_size;
1083 cur_lte->output_resource_entry.offset =
1084 cur_chunk_tab->file_offset;
1086 cur_lte->output_resource_entry.flags =
1087 cur_lte->resource_entry.flags |
1088 WIM_RESHDR_FLAG_COMPRESSED;
1091 do_write_streams_progress(progress, progress_func,
1092 wim_resource_size(cur_lte));
1094 FREE(cur_chunk_tab);
1095 cur_chunk_tab = NULL;
1097 struct list_head *next = cur_lte->staging_list.next;
1098 list_del(&cur_lte->staging_list);
1100 if (next == &outstanding_resources)
1103 cur_lte = container_of(cur_lte->staging_list.next,
1104 struct wim_lookup_table_entry,
1107 // Since we just finished writing a stream,
1108 // write any streams that have been added to the
1109 // my_resources list for direct writing by the
1110 // main thread (e.g. resources that don't need
1111 // to be compressed because the desired
1112 // compression type is the same as the previous
1113 // compression type).
1114 ret = do_write_stream_list(&my_resources,
1127 if (ret == WIMLIB_ERR_NOMEM) {
1128 ERROR("Could not allocate enough memory for "
1129 "multi-threaded compression");
1134 end_wim_resource_read(next_lte, ni);
1136 end_wim_resource_read(next_lte);
1141 ret = do_write_stream_list(&my_resources, out_fp,
1142 out_ctype, progress_func,
1146 size_t num_available_msgs = 0;
1147 struct list_head *cur;
1149 list_for_each(cur, &available_msgs) {
1150 num_available_msgs++;
1153 while (num_available_msgs < num_messages) {
1154 shared_queue_get(compressed_res_queue);
1155 num_available_msgs++;
1161 for (size_t i = 0; i < num_messages; i++) {
1162 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1163 FREE(msgs[i].compressed_chunks[j]);
1164 FREE(msgs[i].uncompressed_chunks[j]);
1170 FREE(cur_chunk_tab);
1175 get_default_num_threads()
1178 return win32_get_number_of_processors();
1180 return sysconf(_SC_NPROCESSORS_ONLN);
1185 write_stream_list_parallel(struct list_head *stream_list,
1186 struct wim_lookup_table *lookup_table,
1190 unsigned num_threads,
1191 wimlib_progress_func_t progress_func,
1192 union wimlib_progress_info *progress)
1195 struct shared_queue res_to_compress_queue;
1196 struct shared_queue compressed_res_queue;
1197 pthread_t *compressor_threads = NULL;
1199 if (num_threads == 0) {
1200 long nthreads = get_default_num_threads();
1201 if (nthreads < 1 || nthreads > UINT_MAX) {
1202 WARNING("Could not determine number of processors! Assuming 1");
1205 num_threads = nthreads;
1209 progress->write_streams.num_threads = num_threads;
1210 wimlib_assert(stream_list->next != stream_list);
1212 static const double MESSAGES_PER_THREAD = 2.0;
1213 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1215 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1217 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1221 ret = shared_queue_init(&compressed_res_queue, queue_size);
1223 goto out_destroy_res_to_compress_queue;
1225 struct compressor_thread_params params;
1226 params.res_to_compress_queue = &res_to_compress_queue;
1227 params.compressed_res_queue = &compressed_res_queue;
1228 params.compress = get_compress_func(out_ctype);
1230 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1231 if (!compressor_threads) {
1232 ret = WIMLIB_ERR_NOMEM;
1233 goto out_destroy_compressed_res_queue;
1236 for (unsigned i = 0; i < num_threads; i++) {
1237 DEBUG("pthread_create thread %u", i);
1238 ret = pthread_create(&compressor_threads[i], NULL,
1239 compressor_thread_proc, ¶ms);
1242 ERROR_WITH_ERRNO("Failed to create compressor "
1250 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1252 ret = main_writer_thread_proc(stream_list,
1255 &res_to_compress_queue,
1256 &compressed_res_queue,
1262 for (unsigned i = 0; i < num_threads; i++)
1263 shared_queue_put(&res_to_compress_queue, NULL);
1265 for (unsigned i = 0; i < num_threads; i++) {
1266 if (pthread_join(compressor_threads[i], NULL)) {
1267 WARNING_WITH_ERRNO("Failed to join compressor "
1271 FREE(compressor_threads);
1272 out_destroy_compressed_res_queue:
1273 shared_queue_destroy(&compressed_res_queue);
1274 out_destroy_res_to_compress_queue:
1275 shared_queue_destroy(&res_to_compress_queue);
1276 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1279 WARNING("Falling back to single-threaded compression");
1280 return write_stream_list_serial(stream_list,
1292 * Write a list of streams to a WIM (@out_fp) using the compression type
1293 * @out_ctype and up to @num_threads compressor threads.
1296 write_stream_list(struct list_head *stream_list,
1297 struct wim_lookup_table *lookup_table,
1298 FILE *out_fp, int out_ctype, int write_flags,
1299 unsigned num_threads, wimlib_progress_func_t progress_func)
1301 struct wim_lookup_table_entry *lte;
1302 size_t num_streams = 0;
1303 u64 total_bytes = 0;
1304 u64 total_compression_bytes = 0;
1305 union wimlib_progress_info progress;
1308 if (list_empty(stream_list))
1311 list_for_each_entry(lte, stream_list, write_streams_list) {
1313 total_bytes += wim_resource_size(lte);
1314 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1315 && (wim_resource_compression_type(lte) != out_ctype ||
1316 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1318 total_compression_bytes += wim_resource_size(lte);
1321 progress.write_streams.total_bytes = total_bytes;
1322 progress.write_streams.total_streams = num_streams;
1323 progress.write_streams.completed_bytes = 0;
1324 progress.write_streams.completed_streams = 0;
1325 progress.write_streams.num_threads = num_threads;
1326 progress.write_streams.compression_type = out_ctype;
1327 progress.write_streams._private = 0;
1329 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1330 if (total_compression_bytes >= 1000000 && num_threads != 1)
1331 ret = write_stream_list_parallel(stream_list,
1341 ret = write_stream_list_serial(stream_list,
1351 struct stream_size_table {
1352 struct hlist_head *array;
1358 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1360 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1362 return WIMLIB_ERR_NOMEM;
1363 tab->num_entries = 0;
1364 tab->capacity = capacity;
1369 destroy_stream_size_table(struct stream_size_table *tab)
1375 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1377 struct stream_size_table *tab = _tab;
1379 struct wim_lookup_table_entry *hashed_lte;
1380 struct hlist_node *tmp;
1382 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1383 lte->unique_size = 1;
1384 hlist_for_each_entry(hashed_lte, tmp, &tab->array[pos], hash_list_2) {
1385 if (wim_resource_size(hashed_lte) == wim_resource_size(lte)) {
1386 lte->unique_size = 0;
1387 hashed_lte->unique_size = 0;
1392 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1398 struct lte_overwrite_prepare_args {
1401 struct list_head *stream_list;
1402 struct stream_size_table *stream_size_tab;
1406 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1408 struct lte_overwrite_prepare_args *args = arg;
1410 if (lte->resource_location == RESOURCE_IN_WIM &&
1411 lte->wim == args->wim)
1413 /* We can't do an in place overwrite on the WIM if there are
1414 * streams after the XML data. */
1415 if (lte->resource_entry.offset +
1416 lte->resource_entry.size > args->end_offset)
1418 #ifdef ENABLE_ERROR_MESSAGES
1419 ERROR("The following resource is after the XML data:");
1420 print_lookup_table_entry(lte, stderr);
1422 return WIMLIB_ERR_RESOURCE_ORDER;
1425 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1426 list_add_tail(<e->write_streams_list, args->stream_list);
1428 lte->out_refcnt = lte->refcnt;
1429 stream_size_table_insert(lte, args->stream_size_tab);
1434 lte_set_output_res_entry(struct wim_lookup_table_entry *lte, void *_wim)
1436 if (lte->resource_location == RESOURCE_IN_WIM &&
1439 memcpy(<e->output_resource_entry, <e->resource_entry,
1440 sizeof(struct resource_entry));
1445 /* Given a WIM that we are going to overwrite in place with zero or more
1446 * additional streams added, construct a list the list of new unique streams
1447 * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
1448 * streams that need to be added but may be identical to other hashed or
1449 * unhashed streams. These unhashed streams are checksummed while the streams
1450 * are being written. To aid this process, the member @unique_size is set to 1
1451 * on streams that have a unique size and therefore must be written.
1453 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1454 * indicate the number of times the stream is referenced in only the streams
1455 * that are being written; this may still be adjusted later when unhashed
1456 * streams are being resolved.
1459 prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
1460 struct list_head *stream_list)
1463 struct stream_size_table stream_size_tab;
1464 struct lte_overwrite_prepare_args args = {
1466 .end_offset = end_offset,
1467 .stream_list = stream_list,
1468 .stream_size_tab = &stream_size_tab,
1471 ret = init_stream_size_table(&stream_size_tab, 9001);
1475 INIT_LIST_HEAD(stream_list);
1476 for (int i = 0; i < wim->hdr.image_count; i++) {
1477 struct wim_image_metadata *imd;
1478 struct wim_lookup_table_entry *lte;
1480 imd = wim->image_metadata[i];
1481 image_for_each_unhashed_stream(lte, imd) {
1482 ret = lte_overwrite_prepare(lte, &args);
1484 goto out_destroy_stream_size_table;
1487 ret = for_lookup_table_entry(wim->lookup_table,
1488 lte_overwrite_prepare, &args);
1490 goto out_destroy_stream_size_table;
1492 for (int i = 0; i < wim->hdr.image_count; i++)
1493 lte_set_output_res_entry(wim->image_metadata[i]->metadata_lte,
1495 ret = for_lookup_table_entry(wim->lookup_table,
1496 lte_set_output_res_entry, wim);
1497 out_destroy_stream_size_table:
1498 destroy_stream_size_table(&stream_size_tab);
1503 struct find_streams_ctx {
1504 struct list_head stream_list;
1505 struct stream_size_table stream_size_tab;
1509 inode_find_streams_to_write(struct wim_inode *inode,
1510 struct wim_lookup_table *table,
1511 struct list_head *stream_list,
1512 struct stream_size_table *tab)
1514 struct wim_lookup_table_entry *lte;
1515 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1516 lte = inode_stream_lte(inode, i, table);
1518 if (lte->out_refcnt == 0) {
1520 stream_size_table_insert(lte, tab);
1521 list_add_tail(<e->write_streams_list, stream_list);
1523 lte->out_refcnt += inode->i_nlink;
1530 image_find_streams_to_write(WIMStruct *w)
1532 struct wim_image_metadata *imd;
1533 struct find_streams_ctx *ctx;
1534 struct wim_inode *inode;
1535 struct wim_lookup_table_entry *lte;
1538 imd = wim_get_current_image_metadata(w);
1540 image_for_each_unhashed_stream(lte, imd) {
1541 lte->out_refcnt = 0;
1542 wimlib_assert(lte->unhashed);
1543 wimlib_assert(lte->my_ptr != NULL);
1546 /* Go through this image's inodes to find any streams that have not been
1548 image_for_each_inode(inode, imd) {
1549 inode_find_streams_to_write(inode, w->lookup_table,
1551 &ctx->stream_size_tab);
1556 /* Given a WIM that from which one or all of the images is being written, build
1557 * the list of unique streams ('struct wim_lookup_table_entry's) that must be
1558 * written, plus any unhashed streams that need to be written but may be
1559 * identical to other hashed or unhashed streams being written. These unhashed
1560 * streams are checksummed while the streams are being written. To aid this
1561 * process, the member @unique_size is set to 1 on streams that have a unique
1562 * size and therefore must be written.
1564 * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
1565 * indicate the number of times the stream is referenced in only the streams
1566 * that are being written; this may still be adjusted later when unhashed
1567 * streams are being resolved.
1570 prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
1573 struct find_streams_ctx ctx;
1575 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1576 ret = init_stream_size_table(&ctx.stream_size_tab, 9001);
1579 for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
1580 &ctx.stream_size_tab);
1581 INIT_LIST_HEAD(&ctx.stream_list);
1582 wim->private = &ctx;
1583 for_image(wim, image, image_find_streams_to_write);
1584 destroy_stream_size_table(&ctx.stream_size_tab);
1586 INIT_LIST_HEAD(stream_list);
1587 list_splice(&ctx.stream_list, stream_list);
1591 /* Writes the streams for the specified @image in @wim to @wim->out_fp.
1594 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1595 unsigned num_threads,
1596 wimlib_progress_func_t progress_func)
1599 struct list_head stream_list;
1601 ret = prepare_stream_list(wim, image, &stream_list);
1604 return write_stream_list(&stream_list,
1607 wimlib_get_compression_type(wim),
1614 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1615 * table (optional), then overwrite the WIM header.
1617 * write_flags is a bitwise OR of the following:
1619 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1620 * Include an integrity table.
1622 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1623 * Show progress information when (if) writing the integrity table.
1625 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1626 * Don't write the lookup table.
1628 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1629 * When (if) writing the integrity table, re-use entries from the
1630 * existing integrity table, if possible.
1632 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1633 * After writing the XML data but before writing the integrity
1634 * table, write a temporary WIM header and flush the stream so that
1635 * the WIM is less likely to become corrupted upon abrupt program
1638 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1639 * fsync() the output file before closing it.
1643 finish_write(WIMStruct *w, int image, int write_flags,
1644 wimlib_progress_func_t progress_func)
1647 struct wim_header hdr;
1648 FILE *out = w->out_fp;
1650 /* @hdr will be the header for the new WIM. First copy all the data
1651 * from the header in the WIMStruct; then set all the fields that may
1652 * have changed, including the resource entries, boot index, and image
1654 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1656 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1657 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1662 ret = write_xml_data(w->wim_info, image, out,
1663 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1664 wim_info_get_total_bytes(w->wim_info) : 0,
1665 &hdr.xml_res_entry);
1669 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1670 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1671 struct wim_header checkpoint_hdr;
1672 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1673 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1674 if (fseeko(out, 0, SEEK_SET) != 0) {
1675 ERROR_WITH_ERRNO("Failed to seek to beginning "
1676 "of WIM being written");
1677 ret = WIMLIB_ERR_WRITE;
1680 ret = write_header(&checkpoint_hdr, out);
1684 if (fflush(out) != 0) {
1685 ERROR_WITH_ERRNO("Can't write data to WIM");
1686 ret = WIMLIB_ERR_WRITE;
1690 if (fseeko(out, 0, SEEK_END) != 0) {
1691 ERROR_WITH_ERRNO("Failed to seek to end "
1692 "of WIM being written");
1693 ret = WIMLIB_ERR_WRITE;
1698 off_t old_lookup_table_end;
1699 off_t new_lookup_table_end;
1700 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1701 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1702 w->hdr.lookup_table_res_entry.size;
1704 old_lookup_table_end = 0;
1706 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1707 hdr.lookup_table_res_entry.size;
1709 ret = write_integrity_table(out,
1711 new_lookup_table_end,
1712 old_lookup_table_end,
1717 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1721 * In the WIM header, there is room for the resource entry for a
1722 * metadata resource labeled as the "boot metadata". This entry should
1723 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1724 * it should be a copy of the resource entry for the image that is
1725 * marked as bootable. This is not well documented...
1728 /* Set image count and boot index correctly for single image writes */
1729 if (image != WIMLIB_ALL_IMAGES) {
1730 hdr.image_count = 1;
1731 if (hdr.boot_idx == image)
1737 if (hdr.boot_idx == 0) {
1738 memset(&hdr.boot_metadata_res_entry, 0,
1739 sizeof(struct resource_entry));
1741 memcpy(&hdr.boot_metadata_res_entry,
1743 hdr.boot_idx - 1]->metadata_lte->output_resource_entry,
1744 sizeof(struct resource_entry));
1747 if (fseeko(out, 0, SEEK_SET) != 0) {
1748 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1750 ret = WIMLIB_ERR_WRITE;
1754 ret = write_header(&hdr, out);
1758 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1759 if (fflush(out) != 0
1760 || fsync(fileno(out)) != 0)
1762 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1763 ret = WIMLIB_ERR_WRITE;
1767 if (fclose(out) != 0) {
1768 ERROR_WITH_ERRNO("Failed to close the WIM file");
1770 ret = WIMLIB_ERR_WRITE;
1776 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1778 lock_wim(WIMStruct *w, FILE *fp)
1781 if (fp && !w->wim_locked) {
1782 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1784 if (errno == EWOULDBLOCK) {
1785 ERROR("`%"TS"' is already being modified or has been "
1786 "mounted read-write\n"
1787 " by another process!", w->filename);
1788 ret = WIMLIB_ERR_ALREADY_LOCKED;
1790 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1803 open_wim_writable(WIMStruct *w, const tchar *path,
1804 bool trunc, bool also_readable)
1815 wimlib_assert(w->out_fp == NULL);
1816 w->out_fp = tfopen(path, mode);
1820 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1821 return WIMLIB_ERR_OPEN;
1827 close_wim_writable(WIMStruct *w)
1830 if (fclose(w->out_fp) != 0) {
1831 WARNING_WITH_ERRNO("Failed to close output WIM");
1837 /* Open file stream and write dummy header for WIM. */
1839 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1842 ret = open_wim_writable(w, path, true,
1843 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1846 /* Write dummy header. It will be overwritten later. */
1847 return write_header(&w->hdr, w->out_fp);
1850 /* Writes a stand-alone WIM to a file. */
1852 wimlib_write(WIMStruct *w, const tchar *path,
1853 int image, int write_flags, unsigned num_threads,
1854 wimlib_progress_func_t progress_func)
1859 return WIMLIB_ERR_INVALID_PARAM;
1861 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1863 if (image != WIMLIB_ALL_IMAGES &&
1864 (image < 1 || image > w->hdr.image_count))
1865 return WIMLIB_ERR_INVALID_IMAGE;
1867 if (w->hdr.total_parts != 1) {
1868 ERROR("Cannot call wimlib_write() on part of a split WIM");
1869 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1872 ret = begin_write(w, path, write_flags);
1876 ret = write_wim_streams(w, image, write_flags, num_threads,
1882 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1884 ret = for_image(w, image, write_metadata_resource);
1889 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1891 ret = finish_write(w, image, write_flags, progress_func);
1893 close_wim_writable(w);
1894 DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1899 any_images_modified(WIMStruct *w)
1901 for (int i = 0; i < w->hdr.image_count; i++)
1902 if (w->image_metadata[i]->modified)
1908 * Overwrite a WIM, possibly appending streams to it.
1910 * A WIM looks like (or is supposed to look like) the following:
1912 * Header (212 bytes)
1913 * Streams and metadata resources (variable size)
1914 * Lookup table (variable size)
1915 * XML data (variable size)
1916 * Integrity table (optional) (variable size)
1918 * If we are not adding any streams or metadata resources, the lookup table is
1919 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1920 * header. This operation is potentially unsafe if the program is abruptly
1921 * terminated while the XML data or integrity table are being overwritten, but
1922 * before the new header has been written. To partially alleviate this problem,
1923 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1924 * finish_write() to cause a temporary WIM header to be written after the XML
1925 * data has been written. This may prevent the WIM from becoming corrupted if
1926 * the program is terminated while the integrity table is being calculated (but
1927 * no guarantees, due to write re-ordering...).
1929 * If we are adding new streams or images (metadata resources), the lookup table
1930 * needs to be changed, and those streams need to be written. In this case, we
1931 * try to perform a safe update of the WIM file by writing the streams *after*
1932 * the end of the previous WIM, then writing the new lookup table, XML data, and
1933 * (optionally) integrity table following the new streams. This will produce a
1934 * layout like the following:
1936 * Header (212 bytes)
1937 * (OLD) Streams and metadata resources (variable size)
1938 * (OLD) Lookup table (variable size)
1939 * (OLD) XML data (variable size)
1940 * (OLD) Integrity table (optional) (variable size)
1941 * (NEW) Streams and metadata resources (variable size)
1942 * (NEW) Lookup table (variable size)
1943 * (NEW) XML data (variable size)
1944 * (NEW) Integrity table (optional) (variable size)
1946 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1947 * the header is overwritten to point to the new lookup table, XML data, and
1948 * integrity table, to produce the following layout:
1950 * Header (212 bytes)
1951 * Streams and metadata resources (variable size)
1952 * Nothing (variable size)
1953 * More Streams and metadata resources (variable size)
1954 * Lookup table (variable size)
1955 * XML data (variable size)
1956 * Integrity table (optional) (variable size)
1958 * This method allows an image to be appended to a large WIM very quickly, and
1959 * is is crash-safe except in the case of write re-ordering, but the
1960 * disadvantage is that a small hole is left in the WIM where the old lookup
1961 * table, xml data, and integrity table were. (These usually only take up a
1962 * small amount of space compared to the streams, however.)
1965 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1966 unsigned num_threads,
1967 wimlib_progress_func_t progress_func)
1970 struct list_head stream_list;
1973 DEBUG("Overwriting `%"TS"' in-place", w->filename);
1975 /* Make sure that the integrity table (if present) is after the XML
1976 * data, and that there are no stream resources, metadata resources, or
1977 * lookup tables after the XML data. Otherwise, these data would be
1979 if (w->hdr.integrity.offset != 0 &&
1980 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1981 ERROR("Didn't expect the integrity table to be before the XML data");
1982 return WIMLIB_ERR_RESOURCE_ORDER;
1985 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1986 ERROR("Didn't expect the lookup table to be after the XML data");
1987 return WIMLIB_ERR_RESOURCE_ORDER;
1991 if (w->hdr.integrity.offset)
1992 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1994 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1996 if (!w->deletion_occurred && !any_images_modified(w)) {
1997 /* If no images have been modified and no images have been
1998 * deleted, a new lookup table does not need to be written. */
1999 old_wim_end = w->hdr.lookup_table_res_entry.offset +
2000 w->hdr.lookup_table_res_entry.size;
2001 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2002 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2004 ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
2008 ret = open_wim_writable(w, w->filename, false,
2009 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
2013 ret = lock_wim(w, w->out_fp);
2020 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
2021 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2025 return WIMLIB_ERR_WRITE;
2028 DEBUG("Writing newly added streams (offset = %"PRIu64")",
2030 ret = write_stream_list(&stream_list,
2033 wimlib_get_compression_type(w),
2034 write_flags, num_threads,
2039 for (int i = 0; i < w->hdr.image_count; i++) {
2040 if (w->image_metadata[i]->modified) {
2041 select_wim_image(w, i + 1);
2042 ret = write_metadata_resource(w);
2047 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2048 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
2051 close_wim_writable(w);
2052 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2053 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2054 w->filename, old_wim_end);
2055 /* Return value of truncate() is ignored because this is already
2057 (void)ttruncate(w->filename, old_wim_end);
2064 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
2065 unsigned num_threads,
2066 wimlib_progress_func_t progress_func)
2068 size_t wim_name_len;
2071 DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
2073 /* Write the WIM to a temporary file in the same directory as the
2075 wim_name_len = tstrlen(w->filename);
2076 tchar tmpfile[wim_name_len + 10];
2077 tmemcpy(tmpfile, w->filename, wim_name_len);
2078 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2079 tmpfile[wim_name_len + 9] = T('\0');
2081 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
2082 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2083 num_threads, progress_func);
2085 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
2089 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2092 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2093 * specified to CreateFile(). The WIM was opened with fopen(), which
2094 * didn't provided this flag to CreateFile, so the handle must be closed
2095 * before executing the rename(). */
2096 if (w->fp != NULL) {
2102 /* Rename the new file to the old file .*/
2103 if (trename(tmpfile, w->filename) != 0) {
2104 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2105 tmpfile, w->filename);
2106 ret = WIMLIB_ERR_RENAME;
2110 if (progress_func) {
2111 union wimlib_progress_info progress;
2112 progress.rename.from = tmpfile;
2113 progress.rename.to = w->filename;
2114 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2117 /* Close the original WIM file that was opened for reading. */
2118 if (w->fp != NULL) {
2123 /* Re-open the WIM read-only. */
2124 w->fp = tfopen(w->filename, T("rb"));
2125 if (w->fp == NULL) {
2126 ret = WIMLIB_ERR_REOPEN;
2127 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2134 /* Remove temporary file. */
2135 if (tunlink(tmpfile) != 0)
2136 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2141 * Writes a WIM file to the original file that it was read from, overwriting it.
2144 wimlib_overwrite(WIMStruct *w, int write_flags,
2145 unsigned num_threads,
2146 wimlib_progress_func_t progress_func)
2148 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2151 return WIMLIB_ERR_NO_FILENAME;
2153 if (w->hdr.total_parts != 1) {
2154 ERROR("Cannot modify a split WIM");
2155 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2158 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2159 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2162 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2164 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2165 WARNING("Falling back to re-building entire WIM");
2169 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,