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/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/header.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/lookup_table.h"
43 #include "wimlib/metadata.h"
44 #include "wimlib/resource.h"
45 #include "wimlib/write.h"
46 #include "wimlib/xml.h"
49 # include "wimlib/win32.h" /* win32_get_number_of_processors() */
52 #ifdef ENABLE_MULTITHREADED_COMPRESSION
68 # include <sys/uio.h> /* for `struct iovec' */
71 /* Return true if the specified resource is compressed and the compressed data
72 * can be reused with the specified output parameters. */
74 can_raw_copy(const struct wim_lookup_table_entry *lte,
75 int write_resource_flags, int out_ctype, u32 out_chunk_size)
77 if (lte->resource_location != RESOURCE_IN_WIM)
79 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
81 if (lte->rspec->ctype != out_ctype)
83 if (out_chunk_size != lte->rspec->cchunk_size)
85 if (lte->offset_in_res != 0)
87 if (lte->size != lte->rspec->uncompressed_size)
93 /* Return true if the specified resource must be recompressed when the specified
94 * output parameters are used. */
96 must_compress_stream(const struct wim_lookup_table_entry *lte,
97 int write_resource_flags, int out_ctype, u32 out_chunk_size)
99 return (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
100 && ((write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
101 || !can_raw_copy(lte, write_resource_flags,
102 out_ctype, out_chunk_size)));
106 compress_chunk(const void * uncompressed_data,
107 unsigned uncompressed_len,
108 void *compressed_data,
110 struct wimlib_lzx_context *comp_ctx)
113 case WIMLIB_COMPRESSION_TYPE_XPRESS:
114 return wimlib_xpress_compress(uncompressed_data,
117 case WIMLIB_COMPRESSION_TYPE_LZX:
118 return wimlib_lzx_compress2(uncompressed_data,
122 case WIMLIB_COMPRESSION_TYPE_LZMS:
124 WARNING("LZMS compression not yet implemented!");
133 /* Chunk table that's located at the beginning of each compressed resource in
134 * the WIM. (This is not the on-disk format; the on-disk format just has an
135 * array of offsets.) */
137 u64 original_resource_size;
140 unsigned bytes_per_chunk_entry;
146 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
147 * integers, including the first offset of 0, which will not be written.
149 u8 offsets[] _aligned_attribute(8);
152 /* Allocate and initializes a chunk table, then reserve space for it in the
153 * output file unless writing a pipable resource. */
155 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
156 struct filedes *out_fd,
158 struct chunk_table **chunk_tab_ret,
163 unsigned bytes_per_chunk_entry;
165 struct chunk_table *chunk_tab;
169 num_chunks = DIV_ROUND_UP(size, out_chunk_size);
170 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
171 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
172 chunk_tab = CALLOC(1, alloc_size);
175 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
177 return WIMLIB_ERR_NOMEM;
179 chunk_tab->num_chunks = num_chunks;
180 chunk_tab->original_resource_size = size;
181 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
182 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
184 chunk_tab->cur_offset_p = chunk_tab->offsets;
186 /* We don't know the correct offsets yet; so just write zeroes to
187 * reserve space for the table, so we can go back to it later after
188 * we've written the compressed chunks following it.
190 * Special case: if writing a pipable WIM, compressed resources are in a
191 * modified format (see comment above write_pipable_wim()) and do not
192 * have a chunk table at the beginning, so don't reserve any space for
194 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
195 ret = full_write(out_fd, chunk_tab->offsets,
196 chunk_tab->table_disk_size);
198 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
204 *chunk_tab_ret = chunk_tab;
208 /* Add the offset for the next chunk to the chunk table being constructed for a
209 * compressed stream. */
211 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
213 if (chunk_tab->bytes_per_chunk_entry == 4) {
214 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
215 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
216 chunk_tab->cur_offset_u32 += out_chunk_size;
218 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
219 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
220 chunk_tab->cur_offset_u64 += out_chunk_size;
224 /* Finishes a WIM chunk table and writes it to the output file at the correct
227 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
228 struct filedes *out_fd,
229 off_t res_start_offset,
230 int write_resource_flags)
234 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
235 ret = full_write(out_fd,
237 chunk_tab->bytes_per_chunk_entry,
238 chunk_tab->table_disk_size);
240 ret = full_pwrite(out_fd,
242 chunk_tab->bytes_per_chunk_entry,
243 chunk_tab->table_disk_size,
247 ERROR_WITH_ERRNO("Write error");
251 /* Write the header for a stream in a pipable WIM.
254 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
255 struct filedes *out_fd,
256 int additional_reshdr_flags)
258 struct pwm_stream_hdr stream_hdr;
262 stream_hdr.magic = PWM_STREAM_MAGIC;
263 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
264 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
265 zero_out_hash(stream_hdr.hash);
267 wimlib_assert(!lte->unhashed);
268 copy_hash(stream_hdr.hash, lte->hash);
271 reshdr_flags = lte->flags & ~(WIM_RESHDR_FLAG_COMPRESSED | WIM_RESHDR_FLAG_CONCAT);
272 reshdr_flags |= additional_reshdr_flags;
273 stream_hdr.flags = cpu_to_le32(reshdr_flags);
274 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
276 ERROR_WITH_ERRNO("Error writing stream header");
281 seek_and_truncate(struct filedes *out_fd, off_t offset)
283 if (filedes_seek(out_fd, offset) == -1 ||
284 ftruncate(out_fd->fd, offset))
286 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
287 return WIMLIB_ERR_WRITE;
293 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
295 u8 md[SHA1_HASH_SIZE];
297 sha1_final(md, sha_ctx);
299 copy_hash(lte->hash, md);
300 } else if (!hashes_equal(md, lte->hash)) {
301 ERROR("WIM resource has incorrect hash!");
302 if (lte_filename_valid(lte)) {
303 ERROR("We were reading it from \"%"TS"\"; maybe "
304 "it changed while we were reading it.",
307 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
312 struct write_resource_ctx {
315 struct wimlib_lzx_context *comp_ctx;
316 struct chunk_table *chunk_tab;
317 struct filedes *out_fd;
324 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
326 struct write_resource_ctx *ctx = _ctx;
327 const void *out_chunk;
328 unsigned out_chunk_size;
330 void *compressed_chunk = NULL;
331 unsigned compressed_size;
332 bool compressed_chunk_malloced = false;
335 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
338 out_chunk_size = chunk_size;
339 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
341 /* Compress the chunk. */
342 if (chunk_size <= STACK_MAX) {
343 compressed_chunk = alloca(chunk_size);
345 compressed_chunk = MALLOC(chunk_size);
346 if (compressed_chunk == NULL)
347 return WIMLIB_ERR_NOMEM;
348 compressed_chunk_malloced = true;
351 compressed_size = compress_chunk(chunk, chunk_size,
355 /* Use compressed data if compression to less than input size
357 if (compressed_size) {
358 out_chunk = compressed_chunk;
359 out_chunk_size = compressed_size;
363 if (ctx->chunk_tab) {
364 /* Update chunk table accounting. */
365 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
367 /* If writing compressed chunks to a pipable WIM, before the
368 * chunk data write a chunk header that provides the compressed
370 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
371 struct pwm_chunk_hdr chunk_hdr = {
372 .compressed_size = cpu_to_le32(out_chunk_size),
374 ret = full_write(ctx->out_fd, &chunk_hdr,
381 /* Write the chunk data. */
382 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
387 if (compressed_chunk_malloced)
388 FREE(compressed_chunk);
392 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
393 goto out_free_memory;
397 * write_wim_resource()-
399 * Write a resource to an output WIM.
402 * Lookup table entry for the resource, which could be in another WIM, in
403 * an external file, or in another location.
406 * File descriptor opened to the output WIM.
409 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
410 * compression algorithm to use.
413 * Compressed chunk size to use.
416 * On success, this is filled in with the offset, flags, compressed size,
417 * and uncompressed size of the resource in the output WIM.
420 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
421 * if it could otherwise be copied directly from the input;
422 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
423 * (and the output file descriptor may be a pipe).
426 * Location of LZX compression context pointer, which will be allocated or
427 * updated if needed. (Initialize to NULL.)
429 * Additional notes: The SHA1 message digest of the uncompressed data is
430 * calculated (except when doing a raw copy --- see below). If the @unhashed
431 * flag is set on the lookup table entry, this message digest is simply copied
432 * to it; otherwise, the message digest is compared with the existing one, and
433 * this function will fail if they do not match.
436 write_wim_resource(struct wim_lookup_table_entry *lte,
437 struct filedes *out_fd, int out_ctype,
439 struct wim_reshdr *out_reshdr,
441 struct wimlib_lzx_context **comp_ctx)
443 struct write_resource_ctx write_ctx;
444 off_t res_start_offset;
449 /* Mask out any irrelevant flags, since this function also uses this
450 * variable to store WIMLIB_READ_RESOURCE flags. */
451 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
453 /* Get current position in output WIM. */
454 res_start_offset = out_fd->offset;
456 /* If we are not forcing the data to be recompressed, and the input
457 * resource is located in a WIM with a compression mode compatible with
458 * the output, we can simply copy the compressed data without
459 * recompressing it. This also means we must skip calculating the SHA1,
460 * as we never will see the uncompressed data. */
461 if (can_raw_copy(lte, resource_flags, out_ctype, out_chunk_size)) {
462 /* Normally, for raw copies we can request a RAW_FULL read, but
463 * if we're reading from a pipable resource and writing a
464 * non-pipable resource or vice versa, then a RAW_CHUNKS read
465 * needs to be requested so that the written resource can be
466 * appropriately formatted. However, in neither case is any
467 * actual decompression needed. */
468 if (lte->rspec->is_pipable == !!(resource_flags &
469 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
471 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
472 read_size = lte->rspec->size_in_wim;
474 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
475 read_size = lte->size;
477 write_ctx.doing_sha = false;
479 write_ctx.doing_sha = true;
480 sha1_init(&write_ctx.sha_ctx);
481 read_size = lte->size;
484 /* Set the output compression mode and initialize chunk table if needed.
486 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
487 write_ctx.out_chunk_size = out_chunk_size;
488 write_ctx.chunk_tab = NULL;
489 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
490 wimlib_assert(out_chunk_size > 0);
491 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
492 /* Compression needed. */
493 write_ctx.out_ctype = out_ctype;
494 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
495 ret = wimlib_lzx_alloc_context(out_chunk_size,
500 write_ctx.comp_ctx = *comp_ctx;
502 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
503 /* Chunk table needed. */
504 ret = begin_wim_resource_chunk_tab(lte, out_fd,
506 &write_ctx.chunk_tab,
513 /* If writing a pipable resource, write the stream header and update
514 * @res_start_offset to be the end of the stream header. */
515 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
516 int reshdr_flags = 0;
517 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
518 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
519 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
521 goto out_free_chunk_tab;
522 res_start_offset = out_fd->offset;
525 /* Write the entire resource by reading the entire resource and feeding
526 * the data through write_resource_cb(). */
527 write_ctx.out_fd = out_fd;
528 write_ctx.resource_flags = resource_flags;
530 if (write_ctx.out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
531 in_chunk_size = lte_cchunk_size(lte);
533 in_chunk_size = out_chunk_size;
534 ret = read_stream_prefix(lte, read_size, write_resource_cb,
535 in_chunk_size, &write_ctx, resource_flags);
537 goto out_free_chunk_tab;
539 /* Verify SHA1 message digest of the resource, or set the hash for the
541 if (write_ctx.doing_sha) {
542 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
544 goto out_free_chunk_tab;
547 /* Write chunk table if needed. */
548 if (write_ctx.chunk_tab) {
549 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
554 goto out_free_chunk_tab;
557 /* Fill in out_reshdr with information about the newly written
559 out_reshdr->size_in_wim = out_fd->offset - res_start_offset;
560 out_reshdr->flags = lte->flags & ~WIM_RESHDR_FLAG_CONCAT;
561 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
562 out_reshdr->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
564 out_reshdr->flags |= WIM_RESHDR_FLAG_COMPRESSED;
565 out_reshdr->offset_in_wim = res_start_offset;
566 out_reshdr->uncompressed_size = lte->size;
568 /* Check for resources compressed to greater than their original size
569 * and write them uncompressed instead. (But never do this if writing
570 * to a pipe, and don't bother if we did a raw copy.) */
571 if (out_reshdr->size_in_wim > out_reshdr->uncompressed_size &&
572 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
573 WIMLIB_READ_RESOURCE_FLAG_RAW)))
575 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
576 "writing uncompressed instead",
577 out_reshdr->uncompressed_size, out_reshdr->size_in_wim);
578 ret = seek_and_truncate(out_fd, res_start_offset);
580 goto out_free_chunk_tab;
581 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
582 FREE(write_ctx.chunk_tab);
583 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
584 write_ctx.chunk_tab = NULL;
585 write_ctx.doing_sha = false;
586 goto try_write_again;
588 if (resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW) {
589 DEBUG("Copied raw compressed data "
590 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
591 out_reshdr->uncompressed_size, out_reshdr->size_in_wim,
592 out_reshdr->offset_in_wim, out_reshdr->flags);
593 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
594 DEBUG("Wrote compressed resource "
595 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
596 out_reshdr->uncompressed_size, out_reshdr->size_in_wim,
597 out_reshdr->offset_in_wim, out_reshdr->flags);
599 DEBUG("Wrote uncompressed resource "
600 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
601 out_reshdr->uncompressed_size,
602 out_reshdr->offset_in_wim, out_reshdr->flags);
606 FREE(write_ctx.chunk_tab);
611 /* Like write_wim_resource(), but the resource is specified by a buffer of
612 * uncompressed data rather a lookup table entry. Also writes the SHA1 message
613 * digest of the buffer to @hash_ret if it is non-NULL. */
615 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
616 int reshdr_flags, struct filedes *out_fd,
619 struct wim_reshdr *out_reshdr,
620 u8 *hash_ret, int write_resource_flags,
621 struct wimlib_lzx_context **comp_ctx)
624 struct wim_lookup_table_entry *lte;
626 /* Set up a temporary lookup table entry to provide to
627 * write_wim_resource(). */
629 lte = new_lookup_table_entry();
631 return WIMLIB_ERR_NOMEM;
633 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
634 lte->attached_buffer = (void*)buf;
635 lte->size = buf_size;
636 lte->flags = reshdr_flags;
638 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
639 sha1_buffer(buf, buf_size, lte->hash);
645 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
646 out_reshdr, write_resource_flags, comp_ctx);
650 copy_hash(hash_ret, lte->hash);
653 lte->resource_location = RESOURCE_NONEXISTENT;
654 free_lookup_table_entry(lte);
659 #ifdef ENABLE_MULTITHREADED_COMPRESSION
661 /* Blocking shared queue (solves the producer-consumer problem) */
662 struct shared_queue {
666 unsigned filled_slots;
668 pthread_mutex_t lock;
669 pthread_cond_t msg_avail_cond;
670 pthread_cond_t space_avail_cond;
674 shared_queue_init(struct shared_queue *q, unsigned size)
676 wimlib_assert(size != 0);
677 q->array = CALLOC(sizeof(q->array[0]), size);
684 if (pthread_mutex_init(&q->lock, NULL)) {
685 ERROR_WITH_ERRNO("Failed to initialize mutex");
688 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
689 ERROR_WITH_ERRNO("Failed to initialize condition variable");
690 goto err_destroy_lock;
692 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
693 ERROR_WITH_ERRNO("Failed to initialize condition variable");
694 goto err_destroy_msg_avail_cond;
697 err_destroy_msg_avail_cond:
698 pthread_cond_destroy(&q->msg_avail_cond);
700 pthread_mutex_destroy(&q->lock);
702 return WIMLIB_ERR_NOMEM;
706 shared_queue_destroy(struct shared_queue *q)
709 pthread_mutex_destroy(&q->lock);
710 pthread_cond_destroy(&q->msg_avail_cond);
711 pthread_cond_destroy(&q->space_avail_cond);
715 shared_queue_put(struct shared_queue *q, void *obj)
717 pthread_mutex_lock(&q->lock);
718 while (q->filled_slots == q->size)
719 pthread_cond_wait(&q->space_avail_cond, &q->lock);
721 q->back = (q->back + 1) % q->size;
722 q->array[q->back] = obj;
725 pthread_cond_broadcast(&q->msg_avail_cond);
726 pthread_mutex_unlock(&q->lock);
730 shared_queue_get(struct shared_queue *q)
734 pthread_mutex_lock(&q->lock);
735 while (q->filled_slots == 0)
736 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
738 obj = q->array[q->front];
739 q->array[q->front] = NULL;
740 q->front = (q->front + 1) % q->size;
743 pthread_cond_broadcast(&q->space_avail_cond);
744 pthread_mutex_unlock(&q->lock);
748 struct compressor_thread_params {
749 struct shared_queue *res_to_compress_queue;
750 struct shared_queue *compressed_res_queue;
752 struct wimlib_lzx_context *comp_ctx;
755 #define MAX_CHUNKS_PER_MSG 2
758 struct wim_lookup_table_entry *lte;
760 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
761 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
762 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
763 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
765 struct list_head list;
771 compress_chunks(struct message *msg, int out_ctype,
772 struct wimlib_lzx_context *comp_ctx)
774 for (unsigned i = 0; i < msg->num_chunks; i++) {
777 len = compress_chunk(msg->uncompressed_chunks[i],
778 msg->uncompressed_chunk_sizes[i],
779 msg->compressed_chunks[i],
786 /* To be written compressed */
787 out_chunk = msg->compressed_chunks[i];
790 /* To be written uncompressed */
791 out_chunk = msg->uncompressed_chunks[i];
792 out_len = msg->uncompressed_chunk_sizes[i];
794 msg->out_chunks[i].iov_base = out_chunk;
795 msg->out_chunks[i].iov_len = out_len;
799 /* Compressor thread routine. This is a lot simpler than the main thread
800 * routine: just repeatedly get a group of chunks from the
801 * res_to_compress_queue, compress them, and put them in the
802 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
805 compressor_thread_proc(void *arg)
807 struct compressor_thread_params *params = arg;
808 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
809 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
812 DEBUG("Compressor thread ready");
813 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
814 compress_chunks(msg, params->out_ctype, params->comp_ctx);
815 shared_queue_put(compressed_res_queue, msg);
817 DEBUG("Compressor thread terminating");
820 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
822 struct write_streams_progress_data {
823 wimlib_progress_func_t progress_func;
824 union wimlib_progress_info progress;
825 uint64_t next_progress;
826 WIMStruct *prev_wim_part;
830 do_write_streams_progress(struct write_streams_progress_data *progress_data,
831 struct wim_lookup_table_entry *lte,
832 bool stream_discarded)
834 union wimlib_progress_info *progress = &progress_data->progress;
837 if (stream_discarded) {
838 progress->write_streams.total_bytes -= lte->size;
839 if (progress_data->next_progress != ~(uint64_t)0 &&
840 progress_data->next_progress > progress->write_streams.total_bytes)
842 progress_data->next_progress = progress->write_streams.total_bytes;
845 progress->write_streams.completed_bytes += lte->size;
847 new_wim_part = false;
848 if (lte->resource_location == RESOURCE_IN_WIM &&
849 lte->rspec->wim != progress_data->prev_wim_part)
851 if (progress_data->prev_wim_part) {
853 progress->write_streams.completed_parts++;
855 progress_data->prev_wim_part = lte->rspec->wim;
857 progress->write_streams.completed_streams++;
858 if (progress_data->progress_func
859 && (progress->write_streams.completed_bytes >= progress_data->next_progress
862 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
864 if (progress_data->next_progress == progress->write_streams.total_bytes) {
865 progress_data->next_progress = ~(uint64_t)0;
867 progress_data->next_progress =
868 min(progress->write_streams.total_bytes,
869 progress->write_streams.completed_bytes +
870 progress->write_streams.total_bytes / 100);
875 struct serial_write_stream_ctx {
876 struct filedes *out_fd;
879 struct wimlib_lzx_context **comp_ctx;
880 int write_resource_flags;
884 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
886 struct serial_write_stream_ctx *ctx = _ctx;
887 return write_wim_resource(lte, ctx->out_fd,
891 ctx->write_resource_flags,
896 /* Write a list of streams, taking into account that some streams may be
897 * duplicates that are checksummed and discarded on the fly, and also delegating
898 * the actual writing of a stream to a function @write_stream_cb, which is
899 * passed the context @write_stream_ctx. */
901 do_write_stream_list(struct list_head *stream_list,
902 struct wim_lookup_table *lookup_table,
903 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
904 void *write_stream_ctx,
905 struct write_streams_progress_data *progress_data)
908 struct wim_lookup_table_entry *lte;
909 bool stream_discarded;
911 /* For each stream in @stream_list ... */
912 while (!list_empty(stream_list)) {
913 stream_discarded = false;
914 lte = container_of(stream_list->next,
915 struct wim_lookup_table_entry,
917 list_del(<e->write_streams_list);
918 if (lte->unhashed && !lte->unique_size) {
919 /* Unhashed stream that shares a size with some other
920 * stream in the WIM we are writing. The stream must be
921 * checksummed to know if we need to write it or not. */
922 struct wim_lookup_table_entry *tmp;
923 u32 orig_out_refcnt = lte->out_refcnt;
925 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
929 /* We found a duplicate stream. 'lte' was
930 * freed, so replace it with the duplicate. */
933 /* 'out_refcnt' was transferred to the
934 * duplicate, and we can detect if the duplicate
935 * stream was already referenced for writing by
936 * checking if its 'out_refcnt' is higher than
937 * that of the original stream. In such cases,
938 * the current stream can be discarded. We can
939 * also discard the current stream if it was
940 * previously marked as filtered (e.g. already
941 * present in the WIM being written). */
942 if (lte->out_refcnt > orig_out_refcnt ||
944 DEBUG("Discarding duplicate stream of "
947 lte->no_progress = 0;
948 stream_discarded = true;
949 goto skip_to_progress;
954 /* Here, @lte is either a hashed stream or an unhashed stream
955 * with a unique size. In either case we know that the stream
956 * has to be written. In either case the SHA1 message digest
957 * will be calculated over the stream while writing it; however,
958 * in the former case this is done merely to check the data,
959 * while in the latter case this is done because we do not have
960 * the SHA1 message digest yet. */
961 wimlib_assert(lte->out_refcnt != 0);
963 lte->no_progress = 0;
964 ret = (*write_stream_cb)(lte, write_stream_ctx);
967 /* In parallel mode, some streams are deferred for later,
968 * serialized processing; ignore them here. */
972 list_del(<e->unhashed_list);
973 lookup_table_insert(lookup_table, lte);
977 if (!lte->no_progress) {
978 do_write_streams_progress(progress_data,
979 lte, stream_discarded);
986 do_write_stream_list_serial(struct list_head *stream_list,
987 struct wim_lookup_table *lookup_table,
988 struct filedes *out_fd,
991 struct wimlib_lzx_context **comp_ctx,
992 int write_resource_flags,
993 struct write_streams_progress_data *progress_data)
995 struct serial_write_stream_ctx ctx = {
997 .out_ctype = out_ctype,
998 .out_chunk_size = out_chunk_size,
999 .write_resource_flags = write_resource_flags,
1000 .comp_ctx = comp_ctx,
1002 return do_write_stream_list(stream_list,
1004 serial_write_stream,
1010 write_flags_to_resource_flags(int write_flags)
1012 int resource_flags = 0;
1014 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
1015 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
1016 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
1017 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
1018 return resource_flags;
1022 write_stream_list_serial(struct list_head *stream_list,
1023 struct wim_lookup_table *lookup_table,
1024 struct filedes *out_fd,
1027 struct wimlib_lzx_context **comp_ctx,
1028 int write_resource_flags,
1029 struct write_streams_progress_data *progress_data)
1031 union wimlib_progress_info *progress = &progress_data->progress;
1032 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
1033 progress->write_streams.total_streams);
1034 progress->write_streams.num_threads = 1;
1035 if (progress_data->progress_func) {
1036 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1039 return do_write_stream_list_serial(stream_list,
1045 write_resource_flags,
1049 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1051 write_wim_chunks(struct message *msg, struct filedes *out_fd,
1052 struct chunk_table *chunk_tab,
1053 int write_resource_flags)
1056 struct pwm_chunk_hdr *chunk_hdrs;
1060 for (unsigned i = 0; i < msg->num_chunks; i++)
1061 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1063 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1064 nvecs = msg->num_chunks;
1065 vecs = msg->out_chunks;
1067 /* Special case: If writing a compressed resource to a pipable
1068 * WIM, prefix each compressed chunk with a header that gives
1069 * its compressed size. */
1070 nvecs = msg->num_chunks * 2;
1071 vecs = alloca(nvecs * sizeof(vecs[0]));
1072 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1074 for (unsigned i = 0; i < msg->num_chunks; i++) {
1075 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1076 vecs[i * 2].iov_base = &chunk_hdrs[i];
1077 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1078 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1079 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1082 ret = full_writev(out_fd, vecs, nvecs);
1084 ERROR_WITH_ERRNO("Write error");
1088 struct main_writer_thread_ctx {
1089 struct list_head *stream_list;
1090 struct wim_lookup_table *lookup_table;
1091 struct filedes *out_fd;
1092 off_t res_start_offset;
1095 struct wimlib_lzx_context **comp_ctx;
1096 int write_resource_flags;
1097 struct shared_queue *res_to_compress_queue;
1098 struct shared_queue *compressed_res_queue;
1099 size_t num_messages;
1100 struct write_streams_progress_data *progress_data;
1102 struct list_head available_msgs;
1103 struct list_head outstanding_streams;
1104 struct list_head serial_streams;
1105 size_t num_outstanding_messages;
1107 SHA_CTX next_sha_ctx;
1109 u64 next_num_chunks;
1110 struct wim_lookup_table_entry *next_lte;
1112 struct message *msgs;
1113 struct message *next_msg;
1114 struct chunk_table *cur_chunk_tab;
1118 init_message(struct message *msg, u32 out_chunk_size)
1120 msg->out_chunk_size = out_chunk_size;
1121 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1122 msg->compressed_chunks[i] = MALLOC(out_chunk_size);
1123 msg->uncompressed_chunks[i] = MALLOC(out_chunk_size);
1124 if (msg->compressed_chunks[i] == NULL ||
1125 msg->uncompressed_chunks[i] == NULL)
1126 return WIMLIB_ERR_NOMEM;
1132 destroy_message(struct message *msg)
1134 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1135 FREE(msg->compressed_chunks[i]);
1136 FREE(msg->uncompressed_chunks[i]);
1141 free_messages(struct message *msgs, size_t num_messages)
1144 for (size_t i = 0; i < num_messages; i++)
1145 destroy_message(&msgs[i]);
1150 static struct message *
1151 allocate_messages(size_t num_messages, u32 out_chunk_size)
1153 struct message *msgs;
1155 msgs = CALLOC(num_messages, sizeof(struct message));
1158 for (size_t i = 0; i < num_messages; i++) {
1159 if (init_message(&msgs[i], out_chunk_size)) {
1160 free_messages(msgs, num_messages);
1168 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1170 while (ctx->num_outstanding_messages--)
1171 shared_queue_get(ctx->compressed_res_queue);
1172 free_messages(ctx->msgs, ctx->num_messages);
1173 FREE(ctx->cur_chunk_tab);
1177 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1179 /* Pre-allocate all the buffers that will be needed to do the chunk
1181 ctx->msgs = allocate_messages(ctx->num_messages, ctx->out_chunk_size);
1182 if (ctx->msgs == NULL)
1183 return WIMLIB_ERR_NOMEM;
1185 /* Initially, all the messages are available to use. */
1186 INIT_LIST_HEAD(&ctx->available_msgs);
1187 for (size_t i = 0; i < ctx->num_messages; i++)
1188 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1190 /* outstanding_streams is the list of streams that currently have had
1191 * chunks sent off for compression.
1193 * The first stream in outstanding_streams is the stream that is
1194 * currently being written.
1196 * The last stream in outstanding_streams is the stream that is
1197 * currently being read and having chunks fed to the compressor threads.
1199 INIT_LIST_HEAD(&ctx->outstanding_streams);
1200 ctx->num_outstanding_messages = 0;
1202 /* Message currently being prepared. */
1203 ctx->next_msg = NULL;
1205 /* Resources that don't need any chunks compressed are added to this
1206 * list and written directly by the main thread. */
1207 INIT_LIST_HEAD(&ctx->serial_streams);
1209 /* Pointer to chunk table for stream currently being written. */
1210 ctx->cur_chunk_tab = NULL;
1216 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1218 struct message *msg;
1219 struct wim_lookup_table_entry *cur_lte;
1222 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1223 wimlib_assert(ctx->num_outstanding_messages != 0);
1225 cur_lte = container_of(ctx->outstanding_streams.next,
1226 struct wim_lookup_table_entry,
1227 being_compressed_list);
1229 /* Get the next message from the queue and process it.
1230 * The message will contain 1 or more data chunks that have been
1232 msg = shared_queue_get(ctx->compressed_res_queue);
1233 msg->complete = true;
1234 --ctx->num_outstanding_messages;
1236 /* Is this the next chunk in the current resource? If it's not (i.e.,
1237 * an earlier chunk in a same or different resource hasn't been
1238 * compressed yet), do nothing, and keep this message around until all
1239 * earlier chunks are received.
1241 * Otherwise, write all the chunks we can. */
1242 while (cur_lte != NULL &&
1243 !list_empty(&cur_lte->msg_list)
1244 && (msg = container_of(cur_lte->msg_list.next,
1248 list_move(&msg->list, &ctx->available_msgs);
1249 if (msg->begin_chunk == 0) {
1250 /* First set of chunks. */
1252 /* Write pipable WIM stream header if needed. */
1253 if (ctx->write_resource_flags &
1254 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1256 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1257 WIM_RESHDR_FLAG_COMPRESSED);
1262 /* Save current offset. */
1263 ctx->res_start_offset = ctx->out_fd->offset;
1265 /* Begin building the chunk table, and leave space for
1267 ret = begin_wim_resource_chunk_tab(cur_lte,
1269 ctx->out_chunk_size,
1270 &ctx->cur_chunk_tab,
1271 ctx->write_resource_flags);
1276 /* Write the compressed chunks from the message. */
1277 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1278 ctx->write_resource_flags);
1282 /* Was this the last chunk of the stream? If so, finish the
1283 * stream by writing the chunk table. */
1284 if (list_empty(&cur_lte->msg_list) &&
1285 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1289 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1291 ctx->res_start_offset,
1292 ctx->write_resource_flags);
1296 list_del(&cur_lte->being_compressed_list);
1298 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1300 FREE(ctx->cur_chunk_tab);
1301 ctx->cur_chunk_tab = NULL;
1303 /* Check for resources compressed to greater than or
1304 * equal to their original size and write them
1305 * uncompressed instead. (But never do this if writing
1307 if (res_csize >= cur_lte->size &&
1308 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1310 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1311 "writing uncompressed instead",
1312 cur_lte->size, res_csize);
1313 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1316 ret = write_wim_resource(cur_lte,
1318 WIMLIB_COMPRESSION_TYPE_NONE,
1320 &cur_lte->out_reshdr,
1321 ctx->write_resource_flags,
1326 cur_lte->out_reshdr.size_in_wim =
1329 cur_lte->out_reshdr.uncompressed_size =
1332 cur_lte->out_reshdr.offset_in_wim =
1333 ctx->res_start_offset;
1335 cur_lte->out_reshdr.flags =
1337 WIM_RESHDR_FLAG_COMPRESSED;
1339 DEBUG("Wrote compressed resource "
1340 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1341 cur_lte->out_reshdr.uncompressed_size,
1342 cur_lte->out_reshdr.size_in_wim,
1343 cur_lte->out_reshdr.offset_in_wim,
1344 cur_lte->out_reshdr.flags);
1347 do_write_streams_progress(ctx->progress_data,
1350 /* Since we just finished writing a stream, write any
1351 * streams that have been added to the serial_streams
1352 * list for direct writing by the main thread (e.g.
1353 * resources that don't need to be compressed because
1354 * the desired compression type is the same as the
1355 * previous compression type). */
1356 if (!list_empty(&ctx->serial_streams)) {
1357 ret = do_write_stream_list_serial(&ctx->serial_streams,
1361 ctx->out_chunk_size,
1363 ctx->write_resource_flags,
1364 ctx->progress_data);
1369 /* Advance to the next stream to write. */
1370 if (list_empty(&ctx->outstanding_streams)) {
1373 cur_lte = container_of(ctx->outstanding_streams.next,
1374 struct wim_lookup_table_entry,
1375 being_compressed_list);
1382 /* Called when the main thread has read a new chunk of data. */
1384 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1386 struct main_writer_thread_ctx *ctx = _ctx;
1388 struct message *next_msg;
1389 u64 next_chunk_in_msg;
1391 /* Update SHA1 message digest for the stream currently being read by the
1393 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1395 /* We send chunks of data to the compressor chunks in batches which we
1396 * refer to as "messages". @next_msg is the message that is currently
1397 * being prepared to send off. If it is NULL, that indicates that we
1398 * need to start a new message. */
1399 next_msg = ctx->next_msg;
1401 /* We need to start a new message. First check to see if there
1402 * is a message available in the list of available messages. If
1403 * so, we can just take one. If not, all the messages (there is
1404 * a fixed number of them, proportional to the number of
1405 * threads) have been sent off to the compressor threads, so we
1406 * receive messages from the compressor threads containing
1407 * compressed chunks of data.
1409 * We may need to receive multiple messages before one is
1410 * actually available to use because messages received that are
1411 * *not* for the very next set of chunks to compress must be
1412 * buffered until it's time to write those chunks. */
1413 while (list_empty(&ctx->available_msgs)) {
1414 ret = receive_compressed_chunks(ctx);
1419 next_msg = container_of(ctx->available_msgs.next,
1420 struct message, list);
1421 list_del(&next_msg->list);
1422 next_msg->complete = false;
1423 next_msg->begin_chunk = ctx->next_chunk;
1424 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1425 ctx->next_num_chunks - ctx->next_chunk);
1426 ctx->next_msg = next_msg;
1429 /* Fill in the next chunk to compress */
1430 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1432 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1433 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1436 if (++next_chunk_in_msg == next_msg->num_chunks) {
1437 /* Send off an array of chunks to compress */
1438 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1439 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1440 ++ctx->num_outstanding_messages;
1441 ctx->next_msg = NULL;
1447 main_writer_thread_finish(void *_ctx)
1449 struct main_writer_thread_ctx *ctx = _ctx;
1451 while (ctx->num_outstanding_messages != 0) {
1452 ret = receive_compressed_chunks(ctx);
1456 wimlib_assert(list_empty(&ctx->outstanding_streams));
1457 return do_write_stream_list_serial(&ctx->serial_streams,
1461 ctx->out_chunk_size,
1463 ctx->write_resource_flags,
1464 ctx->progress_data);
1468 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1469 struct main_writer_thread_ctx *ctx)
1473 /* Read the entire stream @lte, feeding its data chunks to the
1474 * compressor threads. Also SHA1-sum the stream; this is required in
1475 * the case that @lte is unhashed, and a nice additional verification
1476 * when @lte is already hashed. */
1477 sha1_init(&ctx->next_sha_ctx);
1478 ctx->next_chunk = 0;
1479 ctx->next_num_chunks = DIV_ROUND_UP(lte->size, ctx->out_chunk_size);
1480 ctx->next_lte = lte;
1481 INIT_LIST_HEAD(<e->msg_list);
1482 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1483 ret = read_stream_prefix(lte, lte->size, main_writer_thread_cb,
1484 ctx->out_chunk_size, ctx, 0);
1487 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1488 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1492 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1494 struct main_writer_thread_ctx *ctx = _ctx;
1497 if (lte->size < 1000 ||
1498 !must_compress_stream(lte, ctx->write_resource_flags,
1499 ctx->out_ctype, ctx->out_chunk_size))
1501 /* Stream is too small or isn't being compressed. Process it by
1502 * the main thread when we have a chance. We can't necessarily
1503 * process it right here, as the main thread could be in the
1504 * middle of writing a different stream. */
1505 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1509 ret = submit_stream_for_compression(lte, ctx);
1511 lte->no_progress = 1;
1516 get_default_num_threads(void)
1519 return win32_get_number_of_processors();
1521 return sysconf(_SC_NPROCESSORS_ONLN);
1525 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1526 * parameter and will perform compression using that many threads. Falls
1527 * back to write_stream_list_serial() on certain errors, such as a failure to
1528 * create the number of threads requested.
1530 * High level description of the algorithm for writing compressed streams in
1531 * parallel: We perform compression on chunks rather than on full files. The
1532 * currently executing thread becomes the main thread and is entirely in charge
1533 * of reading the data to compress (which may be in any location understood by
1534 * the resource code--- such as in an external file being captured, or in
1535 * another WIM file from which an image is being exported) and actually writing
1536 * the compressed data to the output file. Additional threads are "compressor
1537 * threads" and all execute the compressor_thread_proc, where they repeatedly
1538 * retrieve buffers of data from the main thread, compress them, and hand them
1539 * back to the main thread.
1541 * Certain streams, such as streams that do not need to be compressed (e.g.
1542 * input compression type same as output compression type) or streams of very
1543 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1544 * handled entirely by the main thread at an appropriate time.
1546 * At any given point in time, multiple streams may be having chunks compressed
1547 * concurrently. The stream that the main thread is currently *reading* may be
1548 * later in the list that the stream that the main thread is currently
1551 write_stream_list_parallel(struct list_head *stream_list,
1552 struct wim_lookup_table *lookup_table,
1553 struct filedes *out_fd,
1556 struct wimlib_lzx_context **comp_ctx,
1557 int write_resource_flags,
1558 struct write_streams_progress_data *progress_data,
1559 unsigned num_threads)
1562 struct shared_queue res_to_compress_queue;
1563 struct shared_queue compressed_res_queue;
1564 pthread_t *compressor_threads = NULL;
1565 union wimlib_progress_info *progress = &progress_data->progress;
1566 unsigned num_started_threads;
1567 bool can_retry = true;
1569 if (num_threads == 0) {
1570 long nthreads = get_default_num_threads();
1571 if (nthreads < 1 || nthreads > UINT_MAX) {
1572 WARNING("Could not determine number of processors! Assuming 1");
1573 goto out_serial_quiet;
1574 } else if (nthreads == 1) {
1575 goto out_serial_quiet;
1577 num_threads = nthreads;
1581 DEBUG("Writing stream list of size %"PRIu64" "
1582 "(parallel version, num_threads=%u)",
1583 progress->write_streams.total_streams, num_threads);
1585 progress->write_streams.num_threads = num_threads;
1587 static const size_t MESSAGES_PER_THREAD = 2;
1588 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1590 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1592 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1596 ret = shared_queue_init(&compressed_res_queue, queue_size);
1598 goto out_destroy_res_to_compress_queue;
1600 struct compressor_thread_params *params;
1602 params = CALLOC(num_threads, sizeof(params[0]));
1603 if (params == NULL) {
1604 ret = WIMLIB_ERR_NOMEM;
1605 goto out_destroy_compressed_res_queue;
1608 for (unsigned i = 0; i < num_threads; i++) {
1609 params[i].res_to_compress_queue = &res_to_compress_queue;
1610 params[i].compressed_res_queue = &compressed_res_queue;
1611 params[i].out_ctype = out_ctype;
1612 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1613 ret = wimlib_lzx_alloc_context(out_chunk_size,
1614 NULL, ¶ms[i].comp_ctx);
1616 goto out_free_params;
1620 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1621 if (compressor_threads == NULL) {
1622 ret = WIMLIB_ERR_NOMEM;
1623 goto out_free_params;
1626 for (unsigned i = 0; i < num_threads; i++) {
1627 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1628 ret = pthread_create(&compressor_threads[i], NULL,
1629 compressor_thread_proc, ¶ms[i]);
1633 ERROR_WITH_ERRNO("Failed to create compressor "
1635 i + 1, num_threads);
1636 num_started_threads = i;
1640 num_started_threads = num_threads;
1642 if (progress_data->progress_func) {
1643 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1647 struct main_writer_thread_ctx ctx;
1649 memset(&ctx, 0, sizeof(ctx));
1651 ctx.stream_list = stream_list;
1652 ctx.lookup_table = lookup_table;
1653 ctx.out_fd = out_fd;
1654 ctx.out_ctype = out_ctype;
1655 ctx.out_chunk_size = out_chunk_size;
1656 ctx.comp_ctx = comp_ctx;
1657 ctx.res_to_compress_queue = &res_to_compress_queue;
1658 ctx.compressed_res_queue = &compressed_res_queue;
1659 ctx.num_messages = queue_size;
1660 ctx.write_resource_flags = write_resource_flags;
1661 ctx.progress_data = progress_data;
1662 ret = main_writer_thread_init_ctx(&ctx);
1667 ret = do_write_stream_list(stream_list, lookup_table,
1668 main_thread_process_next_stream,
1669 &ctx, progress_data);
1671 goto out_destroy_ctx;
1673 /* The main thread has finished reading all streams that are going to be
1674 * compressed in parallel, and it now needs to wait for all remaining
1675 * chunks to be compressed so that the remaining streams can actually be
1676 * written to the output file. Furthermore, any remaining streams that
1677 * had processing deferred to the main thread need to be handled. These
1678 * tasks are done by the main_writer_thread_finish() function. */
1679 ret = main_writer_thread_finish(&ctx);
1681 main_writer_thread_destroy_ctx(&ctx);
1683 for (unsigned i = 0; i < num_started_threads; i++)
1684 shared_queue_put(&res_to_compress_queue, NULL);
1686 for (unsigned i = 0; i < num_started_threads; i++) {
1687 if (pthread_join(compressor_threads[i], NULL)) {
1688 WARNING_WITH_ERRNO("Failed to join compressor "
1690 i + 1, num_threads);
1693 FREE(compressor_threads);
1695 for (unsigned i = 0; i < num_threads; i++)
1696 wimlib_lzx_free_context(params[i].comp_ctx);
1698 out_destroy_compressed_res_queue:
1699 shared_queue_destroy(&compressed_res_queue);
1700 out_destroy_res_to_compress_queue:
1701 shared_queue_destroy(&res_to_compress_queue);
1702 if (!can_retry || (ret >= 0 && ret != WIMLIB_ERR_NOMEM))
1705 WARNING("Falling back to single-threaded compression");
1707 return write_stream_list_serial(stream_list,
1713 write_resource_flags,
1719 /* Write a list of streams to a WIM (@out_fd) using the compression type
1720 * @out_ctype, chunk size @out_chunk_size, and up to @num_threads compressor
1723 write_stream_list(struct list_head *stream_list,
1724 struct wim_lookup_table *lookup_table,
1725 struct filedes *out_fd, int out_ctype,
1727 struct wimlib_lzx_context **comp_ctx,
1729 unsigned num_threads, wimlib_progress_func_t progress_func)
1732 int write_resource_flags;
1734 u64 total_compression_bytes;
1735 unsigned total_parts;
1736 WIMStruct *prev_wim_part;
1738 struct wim_lookup_table_entry *lte;
1739 struct write_streams_progress_data progress_data;
1741 if (list_empty(stream_list)) {
1742 DEBUG("No streams to write.");
1746 write_resource_flags = write_flags_to_resource_flags(write_flags);
1748 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1749 out_fd->offset, write_resource_flags);
1751 /* Sort the stream list into a good order for reading. */
1752 ret = sort_stream_list_by_sequential_order(stream_list,
1753 offsetof(struct wim_lookup_table_entry,
1754 write_streams_list));
1758 /* Calculate the total size of the streams to be written. Note: this
1759 * will be the uncompressed size, as we may not know the compressed size
1760 * yet, and also this will assume that every unhashed stream will be
1761 * written (which will not necessarily be the case). */
1763 total_compression_bytes = 0;
1766 prev_wim_part = NULL;
1767 list_for_each_entry(lte, stream_list, write_streams_list) {
1769 total_bytes += lte->size;
1770 if (must_compress_stream(lte, write_resource_flags,
1771 out_ctype, out_chunk_size))
1772 total_compression_bytes += lte->size;
1773 if (lte->resource_location == RESOURCE_IN_WIM) {
1774 if (prev_wim_part != lte->rspec->wim) {
1775 prev_wim_part = lte->rspec->wim;
1781 memset(&progress_data, 0, sizeof(progress_data));
1782 progress_data.progress_func = progress_func;
1784 progress_data.progress.write_streams.total_bytes = total_bytes;
1785 progress_data.progress.write_streams.total_streams = num_streams;
1786 progress_data.progress.write_streams.completed_bytes = 0;
1787 progress_data.progress.write_streams.completed_streams = 0;
1788 progress_data.progress.write_streams.num_threads = num_threads;
1789 progress_data.progress.write_streams.compression_type = out_ctype;
1790 progress_data.progress.write_streams.total_parts = total_parts;
1791 progress_data.progress.write_streams.completed_parts = 0;
1793 progress_data.next_progress = 0;
1794 progress_data.prev_wim_part = NULL;
1796 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1797 if (total_compression_bytes >= 2000000 && num_threads != 1)
1798 ret = write_stream_list_parallel(stream_list,
1804 write_resource_flags,
1809 ret = write_stream_list_serial(stream_list,
1815 write_resource_flags,
1818 DEBUG("Successfully wrote stream list.");
1820 DEBUG("Failed to write stream list (ret=%d).", ret);
1824 struct stream_size_table {
1825 struct hlist_head *array;
1831 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1833 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1835 return WIMLIB_ERR_NOMEM;
1836 tab->num_entries = 0;
1837 tab->capacity = capacity;
1842 destroy_stream_size_table(struct stream_size_table *tab)
1848 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1850 struct stream_size_table *tab = _tab;
1852 struct wim_lookup_table_entry *same_size_lte;
1853 struct hlist_node *tmp;
1855 pos = hash_u64(lte->size) % tab->capacity;
1856 lte->unique_size = 1;
1857 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1858 if (same_size_lte->size == lte->size) {
1859 lte->unique_size = 0;
1860 same_size_lte->unique_size = 0;
1865 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1870 struct find_streams_ctx {
1873 struct list_head stream_list;
1874 struct stream_size_table stream_size_tab;
1878 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1879 struct find_streams_ctx *ctx,
1882 if (lte->out_refcnt == 0) {
1883 stream_size_table_insert(lte, &ctx->stream_size_tab);
1884 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1886 lte->out_refcnt += nref;
1890 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1893 struct find_streams_ctx *ctx = _ctx;
1894 lte->out_refcnt = 0;
1895 lte_reference_for_logical_write(lte, ctx,
1896 (lte->refcnt ? lte->refcnt : 1));
1901 inode_find_streams_to_write(struct wim_inode *inode,
1902 struct wim_lookup_table *table,
1903 struct find_streams_ctx *ctx)
1905 struct wim_lookup_table_entry *lte;
1908 for (i = 0; i <= inode->i_num_ads; i++) {
1909 lte = inode_stream_lte(inode, i, table);
1911 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1912 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1913 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1919 image_find_streams_to_write(WIMStruct *wim)
1921 struct find_streams_ctx *ctx;
1922 struct wim_image_metadata *imd;
1923 struct wim_inode *inode;
1924 struct wim_lookup_table_entry *lte;
1928 imd = wim_get_current_image_metadata(wim);
1930 image_for_each_unhashed_stream(lte, imd)
1931 lte->out_refcnt = 0;
1933 /* Go through this image's inodes to find any streams that have not been
1935 image_for_each_inode(inode, imd) {
1936 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1944 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1945 * the "logical write" of the WIM, meaning all streams that are referenced at
1946 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1947 * each stream being included in the logical write is set to the number of
1948 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1949 * stream being included in the logical write is set to indicate whether that
1950 * stream has a unique size relative to the streams being included in the
1951 * logical write. Still furthermore, 'part_number' on each stream being
1952 * included in the logical write is set to the part number given in the
1953 * in-memory header of @p wim.
1955 * This is considered a "logical write" because it does not take into account
1956 * filtering out streams already present in the WIM (in the case of an in place
1957 * overwrite) or present in other WIMs (in case of creating delta WIM).
1960 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1961 struct find_streams_ctx *ctx)
1965 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1966 (image == 1 && wim->hdr.image_count == 1)))
1968 /* Fast case: Assume that all streams are being written and
1969 * that the reference counts are correct. */
1970 struct wim_lookup_table_entry *lte;
1971 struct wim_image_metadata *imd;
1974 for_lookup_table_entry(wim->lookup_table,
1975 do_lte_full_reference_for_logical_write, ctx);
1976 for (i = 0; i < wim->hdr.image_count; i++) {
1977 imd = wim->image_metadata[i];
1978 image_for_each_unhashed_stream(lte, imd)
1979 do_lte_full_reference_for_logical_write(lte, ctx);
1982 /* Slow case: Walk through the images being written and
1983 * determine the streams referenced. */
1984 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1986 ret = for_image(wim, image, image_find_streams_to_write);
1995 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1997 struct find_streams_ctx *ctx = _ctx;
2000 /* Calculate and set lte->filtered. */
2001 if (lte->resource_location == RESOURCE_IN_WIM) {
2002 if (lte->rspec->wim == ctx->wim &&
2003 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
2004 filtered |= FILTERED_SAME_WIM;
2005 if (lte->rspec->wim != ctx->wim &&
2006 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
2007 filtered |= FILTERED_EXTERNAL_WIM;
2009 lte->filtered = filtered;
2011 /* Filtered streams get inserted into the stream size table too, unless
2012 * they already were. This is because streams that are checksummed
2013 * on-the-fly during the write should not be written if they are
2014 * duplicates of filtered stream. */
2015 if (lte->filtered && lte->out_refcnt == 0)
2016 stream_size_table_insert(lte, &ctx->stream_size_tab);
2021 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
2027 /* Given the list of streams to include in a logical write of a WIM, handle
2028 * filtering out streams already present in the WIM or already present in
2029 * external WIMs, depending on the write flags provided. */
2031 handle_stream_filtering(struct find_streams_ctx *ctx)
2033 struct wim_lookup_table_entry *lte, *tmp;
2035 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2036 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2038 for_lookup_table_entry(ctx->wim->lookup_table,
2039 mark_stream_not_filtered, ctx);
2043 for_lookup_table_entry(ctx->wim->lookup_table,
2044 process_filtered_stream, ctx);
2046 /* Streams in logical write list that were filtered can be removed. */
2047 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2050 list_del(<e->write_streams_list);
2053 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2054 * around prepare_logical_stream_list() to handle filtering out streams already
2055 * present in the WIM or already present in external WIMs, depending on the
2056 * write flags provided.
2058 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2060 * - 'out_refcnt' is set to the number of references found for the logical write.
2061 * This will be nonzero on all streams in the list returned by this function,
2062 * but will also be nonzero on streams not in the list that were included in
2063 * the logical write list, but filtered out from the returned list.
2064 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2065 * are not included in the list of streams returned by this function.
2066 * - 'unique_size' is set if the stream has a unique size among all streams in
2067 * the logical write plus any filtered streams in the entire WIM that could
2068 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2069 * stream being written.
2072 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2073 struct list_head *stream_list)
2077 struct find_streams_ctx ctx;
2079 INIT_LIST_HEAD(&ctx.stream_list);
2080 ret = init_stream_size_table(&ctx.stream_size_tab,
2081 wim->lookup_table->capacity);
2084 ctx.write_flags = write_flags;
2087 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2089 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2091 goto out_destroy_table;
2093 handle_stream_filtering(&ctx);
2094 list_transfer(&ctx.stream_list, stream_list);
2097 destroy_stream_size_table(&ctx.stream_size_tab);
2102 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2103 unsigned num_threads,
2104 wimlib_progress_func_t progress_func,
2105 struct list_head *stream_list_override)
2108 struct list_head _stream_list;
2109 struct list_head *stream_list;
2110 struct wim_lookup_table_entry *lte;
2112 if (stream_list_override == NULL) {
2113 /* Normal case: prepare stream list from image(s) being written.
2115 stream_list = &_stream_list;
2116 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2120 /* Currently only as a result of wimlib_split() being called:
2121 * use stream list already explicitly provided. Use existing
2122 * reference counts. */
2123 stream_list = stream_list_override;
2124 list_for_each_entry(lte, stream_list, write_streams_list)
2125 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2128 return write_stream_list(stream_list,
2131 wim->out_compression_type,
2132 wim->out_chunk_size,
2140 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2141 wimlib_progress_func_t progress_func)
2146 int write_resource_flags;
2148 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2149 DEBUG("Not writing any metadata resources.");
2153 write_resource_flags = write_flags_to_resource_flags(write_flags);
2155 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2156 wim->out_fd.offset);
2159 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2161 if (image == WIMLIB_ALL_IMAGES) {
2163 end_image = wim->hdr.image_count;
2165 start_image = image;
2169 for (int i = start_image; i <= end_image; i++) {
2170 struct wim_image_metadata *imd;
2172 imd = wim->image_metadata[i - 1];
2173 /* Build a new metadata resource only if image was modified from
2174 * the original (or was newly added). Otherwise just copy the
2176 if (imd->modified) {
2177 DEBUG("Image %u was modified; building and writing new "
2178 "metadata resource", i);
2179 ret = write_metadata_resource(wim, i,
2180 write_resource_flags);
2181 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2182 DEBUG("Image %u was not modified; re-using existing "
2183 "metadata resource.", i);
2184 wim_res_spec_to_hdr(imd->metadata_lte->rspec,
2185 &imd->metadata_lte->out_reshdr);
2188 DEBUG("Image %u was not modified; copying existing "
2189 "metadata resource.", i);
2190 ret = write_wim_resource(imd->metadata_lte,
2192 wim->out_compression_type,
2193 wim->out_chunk_size,
2194 &imd->metadata_lte->out_reshdr,
2195 write_resource_flags,
2202 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2207 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2210 DEBUG("Opening \"%"TS"\" for writing.", path);
2212 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2214 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2215 return WIMLIB_ERR_OPEN;
2217 filedes_init(&wim->out_fd, raw_fd);
2222 close_wim_writable(WIMStruct *wim, int write_flags)
2226 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2227 DEBUG("Closing WIM file.");
2228 if (filedes_valid(&wim->out_fd))
2229 if (filedes_close(&wim->out_fd))
2230 ret = WIMLIB_ERR_WRITE;
2232 filedes_invalidate(&wim->out_fd);
2239 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2240 * table, then overwrite the WIM header. By default, closes the WIM file
2241 * descriptor (@wim->out_fd) if successful.
2243 * write_flags is a bitwise OR of the following:
2245 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2246 * Include an integrity table.
2248 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2249 * fsync() the output file before closing it.
2251 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2252 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2253 * stream headers before the lookup table and XML data, and also
2254 * write the WIM header at the end instead of seeking to the
2255 * beginning. Can't be combined with
2256 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2258 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2259 * Don't write the lookup table.
2261 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2262 * When (if) writing the integrity table, re-use entries from the
2263 * existing integrity table, if possible.
2265 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2266 * After writing the XML data but before writing the integrity
2267 * table, write a temporary WIM header and flush the stream so that
2268 * the WIM is less likely to become corrupted upon abrupt program
2270 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2271 * Instead of overwriting the WIM header at the beginning of the
2272 * file, simply append it to the end of the file. (Used when
2274 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2275 * Do not close the file descriptor @wim->out_fd on either success
2277 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2278 * Use the existing <TOTALBYTES> stored in the in-memory XML
2279 * information, rather than setting it to the offset of the XML
2280 * data being written.
2283 finish_write(WIMStruct *wim, int image, int write_flags,
2284 wimlib_progress_func_t progress_func,
2285 struct list_head *stream_list_override)
2289 int write_resource_flags;
2290 off_t old_lookup_table_end;
2291 off_t new_lookup_table_end;
2294 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2296 write_resource_flags = write_flags_to_resource_flags(write_flags);
2298 /* In the WIM header, there is room for the resource entry for a
2299 * metadata resource labeled as the "boot metadata". This entry should
2300 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2301 * it should be a copy of the resource entry for the image that is
2302 * marked as bootable. This is not well documented... */
2303 if (wim->hdr.boot_idx == 0) {
2304 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2306 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2307 &wim->image_metadata[wim->hdr.boot_idx- 1
2308 ]->metadata_lte->out_reshdr);
2311 /* Write lookup table. (Save old position first.) */
2312 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2313 wim->hdr.lookup_table_reshdr.size_in_wim;
2314 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2315 ret = write_wim_lookup_table(wim, image, write_flags,
2316 &wim->hdr.lookup_table_reshdr,
2317 stream_list_override);
2322 /* Write XML data. */
2323 xml_totalbytes = wim->out_fd.offset;
2324 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2325 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2326 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2327 &wim->hdr.xml_data_reshdr,
2328 write_resource_flags);
2332 /* Write integrity table (optional). */
2333 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2334 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2335 struct wim_header checkpoint_hdr;
2336 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2337 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2338 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2339 ret = write_wim_header_at_offset(&checkpoint_hdr,
2345 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2346 old_lookup_table_end = 0;
2348 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2349 wim->hdr.lookup_table_reshdr.size_in_wim;
2351 ret = write_integrity_table(wim,
2352 new_lookup_table_end,
2353 old_lookup_table_end,
2358 /* No integrity table. */
2359 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2362 /* Now that all information in the WIM header has been determined, the
2363 * preliminary header written earlier can be overwritten, the header of
2364 * the existing WIM file can be overwritten, or the final header can be
2365 * written to the end of the pipable WIM. */
2366 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2368 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2369 hdr_offset = wim->out_fd.offset;
2370 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2371 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2375 /* Possibly sync file data to disk before closing. On POSIX systems, it
2376 * is necessary to do this before using rename() to overwrite an
2377 * existing file with a new file. Otherwise, data loss would occur if
2378 * the system is abruptly terminated when the metadata for the rename
2379 * operation has been written to disk, but the new file data has not.
2381 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2382 DEBUG("Syncing WIM file.");
2383 if (fsync(wim->out_fd.fd)) {
2384 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2385 return WIMLIB_ERR_WRITE;
2389 if (close_wim_writable(wim, write_flags)) {
2390 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2391 return WIMLIB_ERR_WRITE;
2397 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2399 lock_wim(WIMStruct *wim, int fd)
2402 if (fd != -1 && !wim->wim_locked) {
2403 ret = flock(fd, LOCK_EX | LOCK_NB);
2405 if (errno == EWOULDBLOCK) {
2406 ERROR("`%"TS"' is already being modified or has been "
2407 "mounted read-write\n"
2408 " by another process!", wim->filename);
2409 ret = WIMLIB_ERR_ALREADY_LOCKED;
2411 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2416 wim->wim_locked = 1;
2424 * write_pipable_wim():
2426 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2427 * capable of being applied from a pipe).
2429 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2430 * images can be applied from them sequentially when the file data is sent over
2431 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2432 * The modifications made to the WIM format for pipable WIMs are:
2434 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2435 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2436 * stops other software from trying to read the file as a normal WIM.
2438 * - The header at the beginning of the file does not contain all the normal
2439 * information; in particular it will have all 0's for the lookup table and
2440 * XML data resource entries. This is because this information cannot be
2441 * determined until the lookup table and XML data have been written.
2442 * Consequently, wimlib will write the full header at the very end of the
2443 * file. The header at the end, however, is only used when reading the WIM
2444 * from a seekable file (not a pipe).
2446 * - An extra copy of the XML data is placed directly after the header. This
2447 * allows image names and sizes to be determined at an appropriate time when
2448 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2449 * WIM is read from a seekable file (not a pipe).
2451 * - The format of resources, or streams, has been modified to allow them to be
2452 * used before the "lookup table" has been read. Each stream is prefixed with
2453 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2454 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2455 * uncompressed stream size, and flags that indicate whether the stream is
2456 * compressed. The data of uncompressed streams then follows literally, while
2457 * the data of compressed streams follows in a modified format. Compressed
2458 * streams do not begin with a chunk table, since the chunk table cannot be
2459 * written until all chunks have been compressed. Instead, each compressed
2460 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2461 * Furthermore, the chunk table is written at the end of the resource instead
2462 * of the start. Note: chunk offsets are given in the chunk table as if the
2463 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2464 * used if the WIM is being read from a seekable file (not a pipe).
2466 * - Metadata resources always come before other file resources (streams).
2467 * (This does not by itself constitute an incompatibility with normal WIMs,
2468 * since this is valid in normal WIMs.)
2470 * - At least up to the end of the file resources, all components must be packed
2471 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2472 * not by itself consititute an incompatibility with normal WIMs, since this
2473 * is valid in normal WIMs.)
2475 * Note: the lookup table, XML data, and header at the end are not used when
2476 * applying from a pipe. They exist to support functionality such as image
2477 * application and export when the WIM is *not* read from a pipe.
2479 * Layout of pipable WIM:
2481 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2482 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2483 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2485 * Layout of normal WIM:
2487 * +--------+-----------------------------+-------------------------+
2488 * | Header | File and metadata resources | Lookup table | XML data |
2489 * +--------+-----------------------------+-------------------------+
2491 * An optional integrity table can follow the final XML data in both normal and
2492 * pipable WIMs. However, due to implementation details, wimlib currently can
2493 * only include an integrity table in a pipable WIM when writing it to a
2494 * seekable file (not a pipe).
2496 * Do note that since pipable WIMs are not supported by Microsoft's software,
2497 * wimlib does not create them unless explicitly requested (with
2498 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2499 * characters to identify the file.
2502 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2503 unsigned num_threads, wimlib_progress_func_t progress_func,
2504 struct list_head *stream_list_override)
2507 struct wim_reshdr xml_reshdr;
2509 WARNING("Creating a pipable WIM, which will "
2511 " with Microsoft's software (wimgapi/imagex/Dism).");
2513 /* At this point, the header at the beginning of the file has already
2516 /* For efficiency, when wimlib adds an image to the WIM with
2517 * wimlib_add_image(), the SHA1 message digests of files is not
2518 * calculated; instead, they are calculated while the files are being
2519 * written. However, this does not work when writing a pipable WIM,
2520 * since when writing a stream to a pipable WIM, its SHA1 message digest
2521 * needs to be known before the stream data is written. Therefore,
2522 * before getting much farther, we need to pre-calculate the SHA1
2523 * message digests of all streams that will be written. */
2524 ret = wim_checksum_unhashed_streams(wim);
2528 /* Write extra copy of the XML data. */
2529 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2531 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2535 /* Write metadata resources for the image(s) being included in the
2537 ret = write_wim_metadata_resources(wim, image, write_flags,
2542 /* Write streams needed for the image(s) being included in the output
2543 * WIM, or streams needed for the split WIM part. */
2544 return write_wim_streams(wim, image, write_flags, num_threads,
2545 progress_func, stream_list_override);
2547 /* The lookup table, XML data, and header at end are handled by
2548 * finish_write(). */
2551 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2554 write_wim_part(WIMStruct *wim,
2555 const void *path_or_fd,
2558 unsigned num_threads,
2559 wimlib_progress_func_t progress_func,
2560 unsigned part_number,
2561 unsigned total_parts,
2562 struct list_head *stream_list_override,
2566 struct wim_header hdr_save;
2567 struct list_head lt_stream_list_override;
2569 if (total_parts == 1)
2570 DEBUG("Writing standalone WIM.");
2572 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2573 if (image == WIMLIB_ALL_IMAGES)
2574 DEBUG("Including all images.");
2576 DEBUG("Including image %d only.", image);
2577 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2578 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2580 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2581 DEBUG("Write flags: 0x%08x", write_flags);
2582 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2583 DEBUG("\tCHECK_INTEGRITY");
2584 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2586 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2587 DEBUG("\tRECOMPRESS");
2588 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2590 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2592 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2593 DEBUG("\tIGNORE_READONLY_FLAG");
2594 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2596 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2597 DEBUG("\tFILE_DESCRIPTOR");
2598 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2599 DEBUG("\tNO_METADATA");
2600 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2601 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2602 if (num_threads == 0)
2603 DEBUG("Number of threads: autodetect");
2605 DEBUG("Number of threads: %u", num_threads);
2606 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2607 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2608 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2609 "specified" : "generate new"));
2611 /* Internally, this is always called with a valid part number and total
2613 wimlib_assert(total_parts >= 1);
2614 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2616 /* A valid image (or all images) must be specified. */
2617 if (image != WIMLIB_ALL_IMAGES &&
2618 (image < 1 || image > wim->hdr.image_count))
2619 return WIMLIB_ERR_INVALID_IMAGE;
2621 /* If we need to write metadata resources, make sure the ::WIMStruct has
2622 * the needed information attached (e.g. is not a resource-only WIM,
2623 * such as a non-first part of a split WIM). */
2624 if (!wim_has_metadata(wim) &&
2625 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2626 return WIMLIB_ERR_METADATA_NOT_FOUND;
2628 /* Check for contradictory flags. */
2629 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2630 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2631 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2632 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2633 return WIMLIB_ERR_INVALID_PARAM;
2635 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2636 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2637 == (WIMLIB_WRITE_FLAG_PIPABLE |
2638 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2639 return WIMLIB_ERR_INVALID_PARAM;
2641 /* Save previous header, then start initializing the new one. */
2642 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2644 /* Set default integrity and pipable flags. */
2645 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2646 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2647 if (wim_is_pipable(wim))
2648 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2650 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2651 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2652 if (wim_has_integrity_table(wim))
2653 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2655 /* Set appropriate magic number. */
2656 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2657 wim->hdr.magic = PWM_MAGIC;
2659 wim->hdr.magic = WIM_MAGIC;
2661 /* Clear header flags that will be set automatically. */
2662 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2663 WIM_HDR_FLAG_RESOURCE_ONLY |
2664 WIM_HDR_FLAG_SPANNED |
2665 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2667 /* Set SPANNED header flag if writing part of a split WIM. */
2668 if (total_parts != 1)
2669 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2671 /* Set part number and total parts of split WIM. This will be 1 and 1
2672 * if the WIM is standalone. */
2673 wim->hdr.part_number = part_number;
2674 wim->hdr.total_parts = total_parts;
2676 /* Set compression type if different. */
2677 if (wim->compression_type != wim->out_compression_type) {
2678 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2679 wimlib_assert(ret == 0);
2682 /* Set chunk size if different. */
2683 wim->hdr.chunk_size = wim->out_chunk_size;
2685 /* Use GUID if specified; otherwise generate a new one. */
2687 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2688 else if (!wim->guid_set_explicitly)
2689 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2691 /* Clear references to resources that have not been written yet. */
2692 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2693 zero_reshdr(&wim->hdr.xml_data_reshdr);
2694 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2695 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2697 /* Set image count and boot index correctly for single image writes. */
2698 if (image != WIMLIB_ALL_IMAGES) {
2699 wim->hdr.image_count = 1;
2700 if (wim->hdr.boot_idx == image)
2701 wim->hdr.boot_idx = 1;
2703 wim->hdr.boot_idx = 0;
2706 /* Split WIMs can't be bootable. */
2707 if (total_parts != 1)
2708 wim->hdr.boot_idx = 0;
2710 /* Initialize output file descriptor. */
2711 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2712 /* File descriptor was explicitly provided. Return error if
2713 * file descriptor is not seekable, unless writing a pipable WIM
2715 wim->out_fd.fd = *(const int*)path_or_fd;
2716 wim->out_fd.offset = 0;
2717 if (!filedes_is_seekable(&wim->out_fd)) {
2718 ret = WIMLIB_ERR_INVALID_PARAM;
2719 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2720 goto out_restore_hdr;
2721 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2722 ERROR("Can't include integrity check when "
2723 "writing pipable WIM to pipe!");
2724 goto out_restore_hdr;
2729 /* Filename of WIM to write was provided; open file descriptor
2731 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2732 O_TRUNC | O_CREAT | O_RDWR);
2734 goto out_restore_hdr;
2737 /* Write initial header. This is merely a "dummy" header since it
2738 * doesn't have all the information yet, so it will be overwritten later
2739 * (unless writing a pipable WIM). */
2740 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2741 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2742 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2743 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2745 goto out_restore_hdr;
2747 if (stream_list_override) {
2748 struct wim_lookup_table_entry *lte;
2749 INIT_LIST_HEAD(<_stream_list_override);
2750 list_for_each_entry(lte, stream_list_override,
2753 list_add_tail(<e->lookup_table_list,
2754 <_stream_list_override);
2758 /* Write metadata resources and streams. */
2759 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2760 /* Default case: create a normal (non-pipable) WIM. */
2761 ret = write_wim_streams(wim, image, write_flags, num_threads,
2762 progress_func, stream_list_override);
2764 goto out_restore_hdr;
2766 ret = write_wim_metadata_resources(wim, image, write_flags,
2769 goto out_restore_hdr;
2771 /* Non-default case: create pipable WIM. */
2772 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2773 progress_func, stream_list_override);
2775 goto out_restore_hdr;
2776 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2779 if (stream_list_override)
2780 stream_list_override = <_stream_list_override;
2782 /* Write lookup table, XML data, and (optional) integrity table. */
2783 ret = finish_write(wim, image, write_flags, progress_func,
2784 stream_list_override);
2786 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2787 (void)close_wim_writable(wim, write_flags);
2788 DEBUG("ret=%d", ret);
2792 /* Write a standalone WIM to a file or file descriptor. */
2794 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2795 int image, int write_flags, unsigned num_threads,
2796 wimlib_progress_func_t progress_func)
2798 return write_wim_part(wim, path_or_fd, image, write_flags,
2799 num_threads, progress_func, 1, 1, NULL, NULL);
2802 /* API function documented in wimlib.h */
2804 wimlib_write(WIMStruct *wim, const tchar *path,
2805 int image, int write_flags, unsigned num_threads,
2806 wimlib_progress_func_t progress_func)
2809 return WIMLIB_ERR_INVALID_PARAM;
2811 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2813 return write_standalone_wim(wim, path, image, write_flags,
2814 num_threads, progress_func);
2817 /* API function documented in wimlib.h */
2819 wimlib_write_to_fd(WIMStruct *wim, int fd,
2820 int image, int write_flags, unsigned num_threads,
2821 wimlib_progress_func_t progress_func)
2824 return WIMLIB_ERR_INVALID_PARAM;
2826 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2827 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2829 return write_standalone_wim(wim, &fd, image, write_flags,
2830 num_threads, progress_func);
2834 any_images_modified(WIMStruct *wim)
2836 for (int i = 0; i < wim->hdr.image_count; i++)
2837 if (wim->image_metadata[i]->modified)
2843 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2845 const WIMStruct *wim = _wim;
2846 off_t end_offset = *(const off_t*)wim->private;
2848 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2849 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2850 return WIMLIB_ERR_RESOURCE_ORDER;
2854 /* Make sure no file or metadata resources are located after the XML data (or
2855 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2856 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2858 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2863 wim->private = &end_offset;
2864 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2868 for (i = 0; i < wim->hdr.image_count; i++) {
2869 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2877 * Overwrite a WIM, possibly appending streams to it.
2879 * A WIM looks like (or is supposed to look like) the following:
2881 * Header (212 bytes)
2882 * Streams and metadata resources (variable size)
2883 * Lookup table (variable size)
2884 * XML data (variable size)
2885 * Integrity table (optional) (variable size)
2887 * If we are not adding any streams or metadata resources, the lookup table is
2888 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2889 * header. This operation is potentially unsafe if the program is abruptly
2890 * terminated while the XML data or integrity table are being overwritten, but
2891 * before the new header has been written. To partially alleviate this problem,
2892 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2893 * finish_write() to cause a temporary WIM header to be written after the XML
2894 * data has been written. This may prevent the WIM from becoming corrupted if
2895 * the program is terminated while the integrity table is being calculated (but
2896 * no guarantees, due to write re-ordering...).
2898 * If we are adding new streams or images (metadata resources), the lookup table
2899 * needs to be changed, and those streams need to be written. In this case, we
2900 * try to perform a safe update of the WIM file by writing the streams *after*
2901 * the end of the previous WIM, then writing the new lookup table, XML data, and
2902 * (optionally) integrity table following the new streams. This will produce a
2903 * layout like the following:
2905 * Header (212 bytes)
2906 * (OLD) Streams and metadata resources (variable size)
2907 * (OLD) Lookup table (variable size)
2908 * (OLD) XML data (variable size)
2909 * (OLD) Integrity table (optional) (variable size)
2910 * (NEW) Streams and metadata resources (variable size)
2911 * (NEW) Lookup table (variable size)
2912 * (NEW) XML data (variable size)
2913 * (NEW) Integrity table (optional) (variable size)
2915 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2916 * the header is overwritten to point to the new lookup table, XML data, and
2917 * integrity table, to produce the following layout:
2919 * Header (212 bytes)
2920 * Streams and metadata resources (variable size)
2921 * Nothing (variable size)
2922 * More Streams and metadata resources (variable size)
2923 * Lookup table (variable size)
2924 * XML data (variable size)
2925 * Integrity table (optional) (variable size)
2927 * This method allows an image to be appended to a large WIM very quickly, and
2928 * is is crash-safe except in the case of write re-ordering, but the
2929 * disadvantage is that a small hole is left in the WIM where the old lookup
2930 * table, xml data, and integrity table were. (These usually only take up a
2931 * small amount of space compared to the streams, however.)
2934 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2935 unsigned num_threads,
2936 wimlib_progress_func_t progress_func)
2939 struct list_head stream_list;
2941 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2942 struct wim_header hdr_save;
2944 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2946 /* Set default integrity flag. */
2947 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2948 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2949 if (wim_has_integrity_table(wim))
2950 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2952 /* Set additional flags for overwrite. */
2953 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2954 WIMLIB_WRITE_FLAG_STREAMS_OK;
2956 /* Make sure that the integrity table (if present) is after the XML
2957 * data, and that there are no stream resources, metadata resources, or
2958 * lookup tables after the XML data. Otherwise, these data would be
2960 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2961 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2962 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2963 wim->hdr.lookup_table_reshdr.size_in_wim;
2964 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2965 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2966 WARNING("Didn't expect the integrity table to be before the XML data");
2967 return WIMLIB_ERR_RESOURCE_ORDER;
2970 if (old_lookup_table_end > old_xml_begin) {
2971 WARNING("Didn't expect the lookup table to be after the XML data");
2972 return WIMLIB_ERR_RESOURCE_ORDER;
2975 /* Set @old_wim_end, which indicates the point beyond which we don't
2976 * allow any file and metadata resources to appear without returning
2977 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2978 * overwrite these resources). */
2979 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2980 /* If no images have been modified and no images have been
2981 * deleted, a new lookup table does not need to be written. We
2982 * shall write the new XML data and optional integrity table
2983 * immediately after the lookup table. Note that this may
2984 * overwrite an existing integrity table. */
2985 DEBUG("Skipping writing lookup table "
2986 "(no images modified or deleted)");
2987 old_wim_end = old_lookup_table_end;
2988 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2989 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2990 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2991 /* Old WIM has an integrity table; begin writing new streams
2993 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2994 wim->hdr.integrity_table_reshdr.size_in_wim;
2996 /* No existing integrity table; begin writing new streams after
2997 * the old XML data. */
2998 old_wim_end = old_xml_end;
3001 ret = check_resource_offsets(wim, old_wim_end);
3005 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
3010 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3014 ret = lock_wim(wim, wim->out_fd.fd);
3018 /* Save original header so it can be restored in case of error */
3019 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3021 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3022 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3023 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3025 ERROR_WITH_ERRNO("Error updating WIM header flags");
3026 goto out_restore_memory_hdr;
3029 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3030 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3031 ret = WIMLIB_ERR_WRITE;
3032 goto out_restore_physical_hdr;
3035 ret = write_stream_list(&stream_list,
3038 wim->compression_type,
3047 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3048 write_flags, progress_func);
3052 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3053 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3054 progress_func, NULL);
3058 goto out_unlock_wim;
3061 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3062 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3063 wim->filename, old_wim_end);
3064 /* Return value of ftruncate() is ignored because this is
3065 * already an error path. */
3066 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3068 out_restore_physical_hdr:
3069 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3070 out_restore_memory_hdr:
3071 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3073 (void)close_wim_writable(wim, write_flags);
3075 wim->wim_locked = 0;
3080 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3081 unsigned num_threads,
3082 wimlib_progress_func_t progress_func)
3084 size_t wim_name_len;
3087 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3089 /* Write the WIM to a temporary file in the same directory as the
3091 wim_name_len = tstrlen(wim->filename);
3092 tchar tmpfile[wim_name_len + 10];
3093 tmemcpy(tmpfile, wim->filename, wim_name_len);
3094 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3095 tmpfile[wim_name_len + 9] = T('\0');
3097 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3098 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3099 num_threads, progress_func);
3107 /* Rename the new WIM file to the original WIM file. Note: on Windows
3108 * this actually calls win32_rename_replacement(), not _wrename(), so
3109 * that removing the existing destination file can be handled. */
3110 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3111 ret = trename(tmpfile, wim->filename);
3113 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3114 tmpfile, wim->filename);
3121 return WIMLIB_ERR_RENAME;
3124 if (progress_func) {
3125 union wimlib_progress_info progress;
3126 progress.rename.from = tmpfile;
3127 progress.rename.to = wim->filename;
3128 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3133 /* API function documented in wimlib.h */
3135 wimlib_overwrite(WIMStruct *wim, int write_flags,
3136 unsigned num_threads,
3137 wimlib_progress_func_t progress_func)
3142 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3144 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3145 return WIMLIB_ERR_INVALID_PARAM;
3148 return WIMLIB_ERR_NO_FILENAME;
3150 orig_hdr_flags = wim->hdr.flags;
3151 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3152 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3153 ret = can_modify_wim(wim);
3154 wim->hdr.flags = orig_hdr_flags;
3158 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3159 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3160 WIMLIB_WRITE_FLAG_PIPABLE))
3161 && !(wim_is_pipable(wim))
3162 && wim->compression_type == wim->out_compression_type
3163 && wim->chunk_size == wim->out_chunk_size)
3165 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3167 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3169 WARNING("Falling back to re-building entire WIM");
3171 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,