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 &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, ctx, 0);
1486 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1487 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1491 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1493 struct main_writer_thread_ctx *ctx = _ctx;
1496 if (lte->size < 1000 ||
1497 !must_compress_stream(lte, ctx->write_resource_flags,
1498 ctx->out_ctype, ctx->out_chunk_size))
1500 /* Stream is too small or isn't being compressed. Process it by
1501 * the main thread when we have a chance. We can't necessarily
1502 * process it right here, as the main thread could be in the
1503 * middle of writing a different stream. */
1504 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1508 ret = submit_stream_for_compression(lte, ctx);
1510 lte->no_progress = 1;
1515 get_default_num_threads(void)
1518 return win32_get_number_of_processors();
1520 return sysconf(_SC_NPROCESSORS_ONLN);
1524 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1525 * parameter and will perform compression using that many threads. Falls
1526 * back to write_stream_list_serial() on certain errors, such as a failure to
1527 * create the number of threads requested.
1529 * High level description of the algorithm for writing compressed streams in
1530 * parallel: We perform compression on chunks rather than on full files. The
1531 * currently executing thread becomes the main thread and is entirely in charge
1532 * of reading the data to compress (which may be in any location understood by
1533 * the resource code--- such as in an external file being captured, or in
1534 * another WIM file from which an image is being exported) and actually writing
1535 * the compressed data to the output file. Additional threads are "compressor
1536 * threads" and all execute the compressor_thread_proc, where they repeatedly
1537 * retrieve buffers of data from the main thread, compress them, and hand them
1538 * back to the main thread.
1540 * Certain streams, such as streams that do not need to be compressed (e.g.
1541 * input compression type same as output compression type) or streams of very
1542 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1543 * handled entirely by the main thread at an appropriate time.
1545 * At any given point in time, multiple streams may be having chunks compressed
1546 * concurrently. The stream that the main thread is currently *reading* may be
1547 * later in the list that the stream that the main thread is currently
1550 write_stream_list_parallel(struct list_head *stream_list,
1551 struct wim_lookup_table *lookup_table,
1552 struct filedes *out_fd,
1555 struct wimlib_lzx_context **comp_ctx,
1556 int write_resource_flags,
1557 struct write_streams_progress_data *progress_data,
1558 unsigned num_threads)
1561 struct shared_queue res_to_compress_queue;
1562 struct shared_queue compressed_res_queue;
1563 pthread_t *compressor_threads = NULL;
1564 union wimlib_progress_info *progress = &progress_data->progress;
1565 unsigned num_started_threads;
1566 bool can_retry = true;
1568 if (num_threads == 0) {
1569 long nthreads = get_default_num_threads();
1570 if (nthreads < 1 || nthreads > UINT_MAX) {
1571 WARNING("Could not determine number of processors! Assuming 1");
1572 goto out_serial_quiet;
1573 } else if (nthreads == 1) {
1574 goto out_serial_quiet;
1576 num_threads = nthreads;
1580 DEBUG("Writing stream list of size %"PRIu64" "
1581 "(parallel version, num_threads=%u)",
1582 progress->write_streams.total_streams, num_threads);
1584 progress->write_streams.num_threads = num_threads;
1586 static const size_t MESSAGES_PER_THREAD = 2;
1587 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1589 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1591 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1595 ret = shared_queue_init(&compressed_res_queue, queue_size);
1597 goto out_destroy_res_to_compress_queue;
1599 struct compressor_thread_params *params;
1601 params = CALLOC(num_threads, sizeof(params[0]));
1602 if (params == NULL) {
1603 ret = WIMLIB_ERR_NOMEM;
1604 goto out_destroy_compressed_res_queue;
1607 for (unsigned i = 0; i < num_threads; i++) {
1608 params[i].res_to_compress_queue = &res_to_compress_queue;
1609 params[i].compressed_res_queue = &compressed_res_queue;
1610 params[i].out_ctype = out_ctype;
1611 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1612 ret = wimlib_lzx_alloc_context(out_chunk_size,
1613 NULL, ¶ms[i].comp_ctx);
1615 goto out_free_params;
1619 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1620 if (compressor_threads == NULL) {
1621 ret = WIMLIB_ERR_NOMEM;
1622 goto out_free_params;
1625 for (unsigned i = 0; i < num_threads; i++) {
1626 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1627 ret = pthread_create(&compressor_threads[i], NULL,
1628 compressor_thread_proc, ¶ms[i]);
1632 ERROR_WITH_ERRNO("Failed to create compressor "
1634 i + 1, num_threads);
1635 num_started_threads = i;
1639 num_started_threads = num_threads;
1641 if (progress_data->progress_func) {
1642 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1646 struct main_writer_thread_ctx ctx;
1648 memset(&ctx, 0, sizeof(ctx));
1650 ctx.stream_list = stream_list;
1651 ctx.lookup_table = lookup_table;
1652 ctx.out_fd = out_fd;
1653 ctx.out_ctype = out_ctype;
1654 ctx.out_chunk_size = out_chunk_size;
1655 ctx.comp_ctx = comp_ctx;
1656 ctx.res_to_compress_queue = &res_to_compress_queue;
1657 ctx.compressed_res_queue = &compressed_res_queue;
1658 ctx.num_messages = queue_size;
1659 ctx.write_resource_flags = write_resource_flags;
1660 ctx.progress_data = progress_data;
1661 ret = main_writer_thread_init_ctx(&ctx);
1666 ret = do_write_stream_list(stream_list, lookup_table,
1667 main_thread_process_next_stream,
1668 &ctx, progress_data);
1670 goto out_destroy_ctx;
1672 /* The main thread has finished reading all streams that are going to be
1673 * compressed in parallel, and it now needs to wait for all remaining
1674 * chunks to be compressed so that the remaining streams can actually be
1675 * written to the output file. Furthermore, any remaining streams that
1676 * had processing deferred to the main thread need to be handled. These
1677 * tasks are done by the main_writer_thread_finish() function. */
1678 ret = main_writer_thread_finish(&ctx);
1680 main_writer_thread_destroy_ctx(&ctx);
1682 for (unsigned i = 0; i < num_started_threads; i++)
1683 shared_queue_put(&res_to_compress_queue, NULL);
1685 for (unsigned i = 0; i < num_started_threads; i++) {
1686 if (pthread_join(compressor_threads[i], NULL)) {
1687 WARNING_WITH_ERRNO("Failed to join compressor "
1689 i + 1, num_threads);
1692 FREE(compressor_threads);
1694 for (unsigned i = 0; i < num_threads; i++)
1695 wimlib_lzx_free_context(params[i].comp_ctx);
1697 out_destroy_compressed_res_queue:
1698 shared_queue_destroy(&compressed_res_queue);
1699 out_destroy_res_to_compress_queue:
1700 shared_queue_destroy(&res_to_compress_queue);
1701 if (!can_retry || (ret >= 0 && ret != WIMLIB_ERR_NOMEM))
1704 WARNING("Falling back to single-threaded compression");
1706 return write_stream_list_serial(stream_list,
1712 write_resource_flags,
1718 /* Write a list of streams to a WIM (@out_fd) using the compression type
1719 * @out_ctype, chunk size @out_chunk_size, and up to @num_threads compressor
1722 write_stream_list(struct list_head *stream_list,
1723 struct wim_lookup_table *lookup_table,
1724 struct filedes *out_fd, int out_ctype,
1726 struct wimlib_lzx_context **comp_ctx,
1728 unsigned num_threads, wimlib_progress_func_t progress_func)
1731 int write_resource_flags;
1733 u64 total_compression_bytes;
1734 unsigned total_parts;
1735 WIMStruct *prev_wim_part;
1737 struct wim_lookup_table_entry *lte;
1738 struct write_streams_progress_data progress_data;
1740 if (list_empty(stream_list)) {
1741 DEBUG("No streams to write.");
1745 write_resource_flags = write_flags_to_resource_flags(write_flags);
1747 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1748 out_fd->offset, write_resource_flags);
1750 /* Sort the stream list into a good order for reading. */
1751 ret = sort_stream_list_by_sequential_order(stream_list,
1752 offsetof(struct wim_lookup_table_entry,
1753 write_streams_list));
1757 /* Calculate the total size of the streams to be written. Note: this
1758 * will be the uncompressed size, as we may not know the compressed size
1759 * yet, and also this will assume that every unhashed stream will be
1760 * written (which will not necessarily be the case). */
1762 total_compression_bytes = 0;
1765 prev_wim_part = NULL;
1766 list_for_each_entry(lte, stream_list, write_streams_list) {
1768 total_bytes += lte->size;
1769 if (must_compress_stream(lte, write_resource_flags,
1770 out_ctype, out_chunk_size))
1771 total_compression_bytes += lte->size;
1772 if (lte->resource_location == RESOURCE_IN_WIM) {
1773 if (prev_wim_part != lte->rspec->wim) {
1774 prev_wim_part = lte->rspec->wim;
1780 memset(&progress_data, 0, sizeof(progress_data));
1781 progress_data.progress_func = progress_func;
1783 progress_data.progress.write_streams.total_bytes = total_bytes;
1784 progress_data.progress.write_streams.total_streams = num_streams;
1785 progress_data.progress.write_streams.completed_bytes = 0;
1786 progress_data.progress.write_streams.completed_streams = 0;
1787 progress_data.progress.write_streams.num_threads = num_threads;
1788 progress_data.progress.write_streams.compression_type = out_ctype;
1789 progress_data.progress.write_streams.total_parts = total_parts;
1790 progress_data.progress.write_streams.completed_parts = 0;
1792 progress_data.next_progress = 0;
1793 progress_data.prev_wim_part = NULL;
1795 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1796 if (total_compression_bytes >= 2000000 && num_threads != 1)
1797 ret = write_stream_list_parallel(stream_list,
1803 write_resource_flags,
1808 ret = write_stream_list_serial(stream_list,
1814 write_resource_flags,
1817 DEBUG("Successfully wrote stream list.");
1819 DEBUG("Failed to write stream list (ret=%d).", ret);
1823 struct stream_size_table {
1824 struct hlist_head *array;
1830 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1832 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1834 return WIMLIB_ERR_NOMEM;
1835 tab->num_entries = 0;
1836 tab->capacity = capacity;
1841 destroy_stream_size_table(struct stream_size_table *tab)
1847 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1849 struct stream_size_table *tab = _tab;
1851 struct wim_lookup_table_entry *same_size_lte;
1852 struct hlist_node *tmp;
1854 pos = hash_u64(lte->size) % tab->capacity;
1855 lte->unique_size = 1;
1856 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1857 if (same_size_lte->size == lte->size) {
1858 lte->unique_size = 0;
1859 same_size_lte->unique_size = 0;
1864 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1869 struct find_streams_ctx {
1872 struct list_head stream_list;
1873 struct stream_size_table stream_size_tab;
1877 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1878 struct find_streams_ctx *ctx,
1881 if (lte->out_refcnt == 0) {
1882 stream_size_table_insert(lte, &ctx->stream_size_tab);
1883 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1885 lte->out_refcnt += nref;
1889 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1892 struct find_streams_ctx *ctx = _ctx;
1893 lte->out_refcnt = 0;
1894 lte_reference_for_logical_write(lte, ctx,
1895 (lte->refcnt ? lte->refcnt : 1));
1900 inode_find_streams_to_write(struct wim_inode *inode,
1901 struct wim_lookup_table *table,
1902 struct find_streams_ctx *ctx)
1904 struct wim_lookup_table_entry *lte;
1907 for (i = 0; i <= inode->i_num_ads; i++) {
1908 lte = inode_stream_lte(inode, i, table);
1910 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1911 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1912 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1918 image_find_streams_to_write(WIMStruct *wim)
1920 struct find_streams_ctx *ctx;
1921 struct wim_image_metadata *imd;
1922 struct wim_inode *inode;
1923 struct wim_lookup_table_entry *lte;
1927 imd = wim_get_current_image_metadata(wim);
1929 image_for_each_unhashed_stream(lte, imd)
1930 lte->out_refcnt = 0;
1932 /* Go through this image's inodes to find any streams that have not been
1934 image_for_each_inode(inode, imd) {
1935 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1943 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1944 * the "logical write" of the WIM, meaning all streams that are referenced at
1945 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1946 * each stream being included in the logical write is set to the number of
1947 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1948 * stream being included in the logical write is set to indicate whether that
1949 * stream has a unique size relative to the streams being included in the
1950 * logical write. Still furthermore, 'part_number' on each stream being
1951 * included in the logical write is set to the part number given in the
1952 * in-memory header of @p wim.
1954 * This is considered a "logical write" because it does not take into account
1955 * filtering out streams already present in the WIM (in the case of an in place
1956 * overwrite) or present in other WIMs (in case of creating delta WIM).
1959 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1960 struct find_streams_ctx *ctx)
1964 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1965 (image == 1 && wim->hdr.image_count == 1)))
1967 /* Fast case: Assume that all streams are being written and
1968 * that the reference counts are correct. */
1969 struct wim_lookup_table_entry *lte;
1970 struct wim_image_metadata *imd;
1973 for_lookup_table_entry(wim->lookup_table,
1974 do_lte_full_reference_for_logical_write, ctx);
1975 for (i = 0; i < wim->hdr.image_count; i++) {
1976 imd = wim->image_metadata[i];
1977 image_for_each_unhashed_stream(lte, imd)
1978 do_lte_full_reference_for_logical_write(lte, ctx);
1981 /* Slow case: Walk through the images being written and
1982 * determine the streams referenced. */
1983 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1985 ret = for_image(wim, image, image_find_streams_to_write);
1994 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1996 struct find_streams_ctx *ctx = _ctx;
1999 /* Calculate and set lte->filtered. */
2000 if (lte->resource_location == RESOURCE_IN_WIM) {
2001 if (lte->rspec->wim == ctx->wim &&
2002 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
2003 filtered |= FILTERED_SAME_WIM;
2004 if (lte->rspec->wim != ctx->wim &&
2005 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
2006 filtered |= FILTERED_EXTERNAL_WIM;
2008 lte->filtered = filtered;
2010 /* Filtered streams get inserted into the stream size table too, unless
2011 * they already were. This is because streams that are checksummed
2012 * on-the-fly during the write should not be written if they are
2013 * duplicates of filtered stream. */
2014 if (lte->filtered && lte->out_refcnt == 0)
2015 stream_size_table_insert(lte, &ctx->stream_size_tab);
2020 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
2026 /* Given the list of streams to include in a logical write of a WIM, handle
2027 * filtering out streams already present in the WIM or already present in
2028 * external WIMs, depending on the write flags provided. */
2030 handle_stream_filtering(struct find_streams_ctx *ctx)
2032 struct wim_lookup_table_entry *lte, *tmp;
2034 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2035 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2037 for_lookup_table_entry(ctx->wim->lookup_table,
2038 mark_stream_not_filtered, ctx);
2042 for_lookup_table_entry(ctx->wim->lookup_table,
2043 process_filtered_stream, ctx);
2045 /* Streams in logical write list that were filtered can be removed. */
2046 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2049 list_del(<e->write_streams_list);
2052 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2053 * around prepare_logical_stream_list() to handle filtering out streams already
2054 * present in the WIM or already present in external WIMs, depending on the
2055 * write flags provided.
2057 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2059 * - 'out_refcnt' is set to the number of references found for the logical write.
2060 * This will be nonzero on all streams in the list returned by this function,
2061 * but will also be nonzero on streams not in the list that were included in
2062 * the logical write list, but filtered out from the returned list.
2063 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2064 * are not included in the list of streams returned by this function.
2065 * - 'unique_size' is set if the stream has a unique size among all streams in
2066 * the logical write plus any filtered streams in the entire WIM that could
2067 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2068 * stream being written.
2071 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2072 struct list_head *stream_list)
2076 struct find_streams_ctx ctx;
2078 INIT_LIST_HEAD(&ctx.stream_list);
2079 ret = init_stream_size_table(&ctx.stream_size_tab,
2080 wim->lookup_table->capacity);
2083 ctx.write_flags = write_flags;
2086 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2088 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2090 goto out_destroy_table;
2092 handle_stream_filtering(&ctx);
2093 list_transfer(&ctx.stream_list, stream_list);
2096 destroy_stream_size_table(&ctx.stream_size_tab);
2101 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2102 unsigned num_threads,
2103 wimlib_progress_func_t progress_func,
2104 struct list_head *stream_list_override)
2107 struct list_head _stream_list;
2108 struct list_head *stream_list;
2109 struct wim_lookup_table_entry *lte;
2111 if (stream_list_override == NULL) {
2112 /* Normal case: prepare stream list from image(s) being written.
2114 stream_list = &_stream_list;
2115 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2119 /* Currently only as a result of wimlib_split() being called:
2120 * use stream list already explicitly provided. Use existing
2121 * reference counts. */
2122 stream_list = stream_list_override;
2123 list_for_each_entry(lte, stream_list, write_streams_list)
2124 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2127 return write_stream_list(stream_list,
2130 wim->out_compression_type,
2131 wim->out_chunk_size,
2139 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2140 wimlib_progress_func_t progress_func)
2145 int write_resource_flags;
2147 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2148 DEBUG("Not writing any metadata resources.");
2152 write_resource_flags = write_flags_to_resource_flags(write_flags);
2154 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2155 wim->out_fd.offset);
2158 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2160 if (image == WIMLIB_ALL_IMAGES) {
2162 end_image = wim->hdr.image_count;
2164 start_image = image;
2168 for (int i = start_image; i <= end_image; i++) {
2169 struct wim_image_metadata *imd;
2171 imd = wim->image_metadata[i - 1];
2172 /* Build a new metadata resource only if image was modified from
2173 * the original (or was newly added). Otherwise just copy the
2175 if (imd->modified) {
2176 DEBUG("Image %u was modified; building and writing new "
2177 "metadata resource", i);
2178 ret = write_metadata_resource(wim, i,
2179 write_resource_flags);
2180 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2181 DEBUG("Image %u was not modified; re-using existing "
2182 "metadata resource.", i);
2183 wim_res_spec_to_hdr(imd->metadata_lte->rspec,
2184 &imd->metadata_lte->out_reshdr);
2187 DEBUG("Image %u was not modified; copying existing "
2188 "metadata resource.", i);
2189 ret = write_wim_resource(imd->metadata_lte,
2191 wim->out_compression_type,
2192 wim->out_chunk_size,
2193 &imd->metadata_lte->out_reshdr,
2194 write_resource_flags,
2201 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2206 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2209 DEBUG("Opening \"%"TS"\" for writing.", path);
2211 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2213 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2214 return WIMLIB_ERR_OPEN;
2216 filedes_init(&wim->out_fd, raw_fd);
2221 close_wim_writable(WIMStruct *wim, int write_flags)
2225 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2226 DEBUG("Closing WIM file.");
2227 if (filedes_valid(&wim->out_fd))
2228 if (filedes_close(&wim->out_fd))
2229 ret = WIMLIB_ERR_WRITE;
2231 filedes_invalidate(&wim->out_fd);
2238 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2239 * table, then overwrite the WIM header. By default, closes the WIM file
2240 * descriptor (@wim->out_fd) if successful.
2242 * write_flags is a bitwise OR of the following:
2244 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2245 * Include an integrity table.
2247 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2248 * fsync() the output file before closing it.
2250 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2251 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2252 * stream headers before the lookup table and XML data, and also
2253 * write the WIM header at the end instead of seeking to the
2254 * beginning. Can't be combined with
2255 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2257 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2258 * Don't write the lookup table.
2260 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2261 * When (if) writing the integrity table, re-use entries from the
2262 * existing integrity table, if possible.
2264 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2265 * After writing the XML data but before writing the integrity
2266 * table, write a temporary WIM header and flush the stream so that
2267 * the WIM is less likely to become corrupted upon abrupt program
2269 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2270 * Instead of overwriting the WIM header at the beginning of the
2271 * file, simply append it to the end of the file. (Used when
2273 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2274 * Do not close the file descriptor @wim->out_fd on either success
2276 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2277 * Use the existing <TOTALBYTES> stored in the in-memory XML
2278 * information, rather than setting it to the offset of the XML
2279 * data being written.
2282 finish_write(WIMStruct *wim, int image, int write_flags,
2283 wimlib_progress_func_t progress_func,
2284 struct list_head *stream_list_override)
2288 int write_resource_flags;
2289 off_t old_lookup_table_end;
2290 off_t new_lookup_table_end;
2293 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2295 write_resource_flags = write_flags_to_resource_flags(write_flags);
2297 /* In the WIM header, there is room for the resource entry for a
2298 * metadata resource labeled as the "boot metadata". This entry should
2299 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2300 * it should be a copy of the resource entry for the image that is
2301 * marked as bootable. This is not well documented... */
2302 if (wim->hdr.boot_idx == 0) {
2303 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2305 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2306 &wim->image_metadata[wim->hdr.boot_idx- 1
2307 ]->metadata_lte->out_reshdr);
2310 /* Write lookup table. (Save old position first.) */
2311 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2312 wim->hdr.lookup_table_reshdr.size_in_wim;
2313 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2314 ret = write_wim_lookup_table(wim, image, write_flags,
2315 &wim->hdr.lookup_table_reshdr,
2316 stream_list_override);
2321 /* Write XML data. */
2322 xml_totalbytes = wim->out_fd.offset;
2323 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2324 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2325 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2326 &wim->hdr.xml_data_reshdr,
2327 write_resource_flags);
2331 /* Write integrity table (optional). */
2332 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2333 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2334 struct wim_header checkpoint_hdr;
2335 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2336 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2337 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2338 ret = write_wim_header_at_offset(&checkpoint_hdr,
2344 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2345 old_lookup_table_end = 0;
2347 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2348 wim->hdr.lookup_table_reshdr.size_in_wim;
2350 ret = write_integrity_table(wim,
2351 new_lookup_table_end,
2352 old_lookup_table_end,
2357 /* No integrity table. */
2358 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2361 /* Now that all information in the WIM header has been determined, the
2362 * preliminary header written earlier can be overwritten, the header of
2363 * the existing WIM file can be overwritten, or the final header can be
2364 * written to the end of the pipable WIM. */
2365 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2367 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2368 hdr_offset = wim->out_fd.offset;
2369 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2370 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2374 /* Possibly sync file data to disk before closing. On POSIX systems, it
2375 * is necessary to do this before using rename() to overwrite an
2376 * existing file with a new file. Otherwise, data loss would occur if
2377 * the system is abruptly terminated when the metadata for the rename
2378 * operation has been written to disk, but the new file data has not.
2380 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2381 DEBUG("Syncing WIM file.");
2382 if (fsync(wim->out_fd.fd)) {
2383 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2384 return WIMLIB_ERR_WRITE;
2388 if (close_wim_writable(wim, write_flags)) {
2389 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2390 return WIMLIB_ERR_WRITE;
2396 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2398 lock_wim(WIMStruct *wim, int fd)
2401 if (fd != -1 && !wim->wim_locked) {
2402 ret = flock(fd, LOCK_EX | LOCK_NB);
2404 if (errno == EWOULDBLOCK) {
2405 ERROR("`%"TS"' is already being modified or has been "
2406 "mounted read-write\n"
2407 " by another process!", wim->filename);
2408 ret = WIMLIB_ERR_ALREADY_LOCKED;
2410 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2415 wim->wim_locked = 1;
2423 * write_pipable_wim():
2425 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2426 * capable of being applied from a pipe).
2428 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2429 * images can be applied from them sequentially when the file data is sent over
2430 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2431 * The modifications made to the WIM format for pipable WIMs are:
2433 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2434 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2435 * stops other software from trying to read the file as a normal WIM.
2437 * - The header at the beginning of the file does not contain all the normal
2438 * information; in particular it will have all 0's for the lookup table and
2439 * XML data resource entries. This is because this information cannot be
2440 * determined until the lookup table and XML data have been written.
2441 * Consequently, wimlib will write the full header at the very end of the
2442 * file. The header at the end, however, is only used when reading the WIM
2443 * from a seekable file (not a pipe).
2445 * - An extra copy of the XML data is placed directly after the header. This
2446 * allows image names and sizes to be determined at an appropriate time when
2447 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2448 * WIM is read from a seekable file (not a pipe).
2450 * - The format of resources, or streams, has been modified to allow them to be
2451 * used before the "lookup table" has been read. Each stream is prefixed with
2452 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2453 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2454 * uncompressed stream size, and flags that indicate whether the stream is
2455 * compressed. The data of uncompressed streams then follows literally, while
2456 * the data of compressed streams follows in a modified format. Compressed
2457 * streams do not begin with a chunk table, since the chunk table cannot be
2458 * written until all chunks have been compressed. Instead, each compressed
2459 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2460 * Furthermore, the chunk table is written at the end of the resource instead
2461 * of the start. Note: chunk offsets are given in the chunk table as if the
2462 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2463 * used if the WIM is being read from a seekable file (not a pipe).
2465 * - Metadata resources always come before other file resources (streams).
2466 * (This does not by itself constitute an incompatibility with normal WIMs,
2467 * since this is valid in normal WIMs.)
2469 * - At least up to the end of the file resources, all components must be packed
2470 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2471 * not by itself consititute an incompatibility with normal WIMs, since this
2472 * is valid in normal WIMs.)
2474 * Note: the lookup table, XML data, and header at the end are not used when
2475 * applying from a pipe. They exist to support functionality such as image
2476 * application and export when the WIM is *not* read from a pipe.
2478 * Layout of pipable WIM:
2480 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2481 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2482 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2484 * Layout of normal WIM:
2486 * +--------+-----------------------------+-------------------------+
2487 * | Header | File and metadata resources | Lookup table | XML data |
2488 * +--------+-----------------------------+-------------------------+
2490 * An optional integrity table can follow the final XML data in both normal and
2491 * pipable WIMs. However, due to implementation details, wimlib currently can
2492 * only include an integrity table in a pipable WIM when writing it to a
2493 * seekable file (not a pipe).
2495 * Do note that since pipable WIMs are not supported by Microsoft's software,
2496 * wimlib does not create them unless explicitly requested (with
2497 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2498 * characters to identify the file.
2501 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2502 unsigned num_threads, wimlib_progress_func_t progress_func,
2503 struct list_head *stream_list_override)
2506 struct wim_reshdr xml_reshdr;
2508 WARNING("Creating a pipable WIM, which will "
2510 " with Microsoft's software (wimgapi/imagex/Dism).");
2512 /* At this point, the header at the beginning of the file has already
2515 /* For efficiency, when wimlib adds an image to the WIM with
2516 * wimlib_add_image(), the SHA1 message digests of files is not
2517 * calculated; instead, they are calculated while the files are being
2518 * written. However, this does not work when writing a pipable WIM,
2519 * since when writing a stream to a pipable WIM, its SHA1 message digest
2520 * needs to be known before the stream data is written. Therefore,
2521 * before getting much farther, we need to pre-calculate the SHA1
2522 * message digests of all streams that will be written. */
2523 ret = wim_checksum_unhashed_streams(wim);
2527 /* Write extra copy of the XML data. */
2528 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2530 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2534 /* Write metadata resources for the image(s) being included in the
2536 ret = write_wim_metadata_resources(wim, image, write_flags,
2541 /* Write streams needed for the image(s) being included in the output
2542 * WIM, or streams needed for the split WIM part. */
2543 return write_wim_streams(wim, image, write_flags, num_threads,
2544 progress_func, stream_list_override);
2546 /* The lookup table, XML data, and header at end are handled by
2547 * finish_write(). */
2550 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2553 write_wim_part(WIMStruct *wim,
2554 const void *path_or_fd,
2557 unsigned num_threads,
2558 wimlib_progress_func_t progress_func,
2559 unsigned part_number,
2560 unsigned total_parts,
2561 struct list_head *stream_list_override,
2565 struct wim_header hdr_save;
2566 struct list_head lt_stream_list_override;
2568 if (total_parts == 1)
2569 DEBUG("Writing standalone WIM.");
2571 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2572 if (image == WIMLIB_ALL_IMAGES)
2573 DEBUG("Including all images.");
2575 DEBUG("Including image %d only.", image);
2576 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2577 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2579 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2580 DEBUG("Write flags: 0x%08x", write_flags);
2581 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2582 DEBUG("\tCHECK_INTEGRITY");
2583 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2585 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2586 DEBUG("\tRECOMPRESS");
2587 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2589 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2591 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2592 DEBUG("\tIGNORE_READONLY_FLAG");
2593 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2595 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2596 DEBUG("\tFILE_DESCRIPTOR");
2597 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2598 DEBUG("\tNO_METADATA");
2599 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2600 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2601 if (num_threads == 0)
2602 DEBUG("Number of threads: autodetect");
2604 DEBUG("Number of threads: %u", num_threads);
2605 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2606 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2607 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2608 "specified" : "generate new"));
2610 /* Internally, this is always called with a valid part number and total
2612 wimlib_assert(total_parts >= 1);
2613 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2615 /* A valid image (or all images) must be specified. */
2616 if (image != WIMLIB_ALL_IMAGES &&
2617 (image < 1 || image > wim->hdr.image_count))
2618 return WIMLIB_ERR_INVALID_IMAGE;
2620 /* If we need to write metadata resources, make sure the ::WIMStruct has
2621 * the needed information attached (e.g. is not a resource-only WIM,
2622 * such as a non-first part of a split WIM). */
2623 if (!wim_has_metadata(wim) &&
2624 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2625 return WIMLIB_ERR_METADATA_NOT_FOUND;
2627 /* Check for contradictory flags. */
2628 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2629 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2630 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2631 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2632 return WIMLIB_ERR_INVALID_PARAM;
2634 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2635 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2636 == (WIMLIB_WRITE_FLAG_PIPABLE |
2637 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2638 return WIMLIB_ERR_INVALID_PARAM;
2640 /* Save previous header, then start initializing the new one. */
2641 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2643 /* Set default integrity and pipable flags. */
2644 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2645 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2646 if (wim_is_pipable(wim))
2647 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2649 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2650 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2651 if (wim_has_integrity_table(wim))
2652 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2654 /* Set appropriate magic number. */
2655 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2656 wim->hdr.magic = PWM_MAGIC;
2658 wim->hdr.magic = WIM_MAGIC;
2660 /* Clear header flags that will be set automatically. */
2661 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2662 WIM_HDR_FLAG_RESOURCE_ONLY |
2663 WIM_HDR_FLAG_SPANNED |
2664 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2666 /* Set SPANNED header flag if writing part of a split WIM. */
2667 if (total_parts != 1)
2668 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2670 /* Set part number and total parts of split WIM. This will be 1 and 1
2671 * if the WIM is standalone. */
2672 wim->hdr.part_number = part_number;
2673 wim->hdr.total_parts = total_parts;
2675 /* Set compression type if different. */
2676 if (wim->compression_type != wim->out_compression_type) {
2677 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2678 wimlib_assert(ret == 0);
2681 /* Set chunk size if different. */
2682 wim->hdr.chunk_size = wim->out_chunk_size;
2684 /* Use GUID if specified; otherwise generate a new one. */
2686 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2687 else if (!wim->guid_set_explicitly)
2688 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2690 /* Clear references to resources that have not been written yet. */
2691 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2692 zero_reshdr(&wim->hdr.xml_data_reshdr);
2693 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2694 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2696 /* Set image count and boot index correctly for single image writes. */
2697 if (image != WIMLIB_ALL_IMAGES) {
2698 wim->hdr.image_count = 1;
2699 if (wim->hdr.boot_idx == image)
2700 wim->hdr.boot_idx = 1;
2702 wim->hdr.boot_idx = 0;
2705 /* Split WIMs can't be bootable. */
2706 if (total_parts != 1)
2707 wim->hdr.boot_idx = 0;
2709 /* Initialize output file descriptor. */
2710 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2711 /* File descriptor was explicitly provided. Return error if
2712 * file descriptor is not seekable, unless writing a pipable WIM
2714 wim->out_fd.fd = *(const int*)path_or_fd;
2715 wim->out_fd.offset = 0;
2716 if (!filedes_is_seekable(&wim->out_fd)) {
2717 ret = WIMLIB_ERR_INVALID_PARAM;
2718 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2719 goto out_restore_hdr;
2720 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2721 ERROR("Can't include integrity check when "
2722 "writing pipable WIM to pipe!");
2723 goto out_restore_hdr;
2728 /* Filename of WIM to write was provided; open file descriptor
2730 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2731 O_TRUNC | O_CREAT | O_RDWR);
2733 goto out_restore_hdr;
2736 /* Write initial header. This is merely a "dummy" header since it
2737 * doesn't have all the information yet, so it will be overwritten later
2738 * (unless writing a pipable WIM). */
2739 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2740 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2741 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2742 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2744 goto out_restore_hdr;
2746 if (stream_list_override) {
2747 struct wim_lookup_table_entry *lte;
2748 INIT_LIST_HEAD(<_stream_list_override);
2749 list_for_each_entry(lte, stream_list_override,
2752 list_add_tail(<e->lookup_table_list,
2753 <_stream_list_override);
2757 /* Write metadata resources and streams. */
2758 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2759 /* Default case: create a normal (non-pipable) WIM. */
2760 ret = write_wim_streams(wim, image, write_flags, num_threads,
2761 progress_func, stream_list_override);
2763 goto out_restore_hdr;
2765 ret = write_wim_metadata_resources(wim, image, write_flags,
2768 goto out_restore_hdr;
2770 /* Non-default case: create pipable WIM. */
2771 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2772 progress_func, stream_list_override);
2774 goto out_restore_hdr;
2775 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2778 if (stream_list_override)
2779 stream_list_override = <_stream_list_override;
2781 /* Write lookup table, XML data, and (optional) integrity table. */
2782 ret = finish_write(wim, image, write_flags, progress_func,
2783 stream_list_override);
2785 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2786 (void)close_wim_writable(wim, write_flags);
2787 DEBUG("ret=%d", ret);
2791 /* Write a standalone WIM to a file or file descriptor. */
2793 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2794 int image, int write_flags, unsigned num_threads,
2795 wimlib_progress_func_t progress_func)
2797 return write_wim_part(wim, path_or_fd, image, write_flags,
2798 num_threads, progress_func, 1, 1, NULL, NULL);
2801 /* API function documented in wimlib.h */
2803 wimlib_write(WIMStruct *wim, const tchar *path,
2804 int image, int write_flags, unsigned num_threads,
2805 wimlib_progress_func_t progress_func)
2808 return WIMLIB_ERR_INVALID_PARAM;
2810 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2812 return write_standalone_wim(wim, path, image, write_flags,
2813 num_threads, progress_func);
2816 /* API function documented in wimlib.h */
2818 wimlib_write_to_fd(WIMStruct *wim, int fd,
2819 int image, int write_flags, unsigned num_threads,
2820 wimlib_progress_func_t progress_func)
2823 return WIMLIB_ERR_INVALID_PARAM;
2825 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2826 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2828 return write_standalone_wim(wim, &fd, image, write_flags,
2829 num_threads, progress_func);
2833 any_images_modified(WIMStruct *wim)
2835 for (int i = 0; i < wim->hdr.image_count; i++)
2836 if (wim->image_metadata[i]->modified)
2842 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2844 const WIMStruct *wim = _wim;
2845 off_t end_offset = *(const off_t*)wim->private;
2847 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2848 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2849 return WIMLIB_ERR_RESOURCE_ORDER;
2853 /* Make sure no file or metadata resources are located after the XML data (or
2854 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2855 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2857 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2862 wim->private = &end_offset;
2863 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2867 for (i = 0; i < wim->hdr.image_count; i++) {
2868 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2876 * Overwrite a WIM, possibly appending streams to it.
2878 * A WIM looks like (or is supposed to look like) the following:
2880 * Header (212 bytes)
2881 * Streams and metadata resources (variable size)
2882 * Lookup table (variable size)
2883 * XML data (variable size)
2884 * Integrity table (optional) (variable size)
2886 * If we are not adding any streams or metadata resources, the lookup table is
2887 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2888 * header. This operation is potentially unsafe if the program is abruptly
2889 * terminated while the XML data or integrity table are being overwritten, but
2890 * before the new header has been written. To partially alleviate this problem,
2891 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2892 * finish_write() to cause a temporary WIM header to be written after the XML
2893 * data has been written. This may prevent the WIM from becoming corrupted if
2894 * the program is terminated while the integrity table is being calculated (but
2895 * no guarantees, due to write re-ordering...).
2897 * If we are adding new streams or images (metadata resources), the lookup table
2898 * needs to be changed, and those streams need to be written. In this case, we
2899 * try to perform a safe update of the WIM file by writing the streams *after*
2900 * the end of the previous WIM, then writing the new lookup table, XML data, and
2901 * (optionally) integrity table following the new streams. This will produce a
2902 * layout like the following:
2904 * Header (212 bytes)
2905 * (OLD) Streams and metadata resources (variable size)
2906 * (OLD) Lookup table (variable size)
2907 * (OLD) XML data (variable size)
2908 * (OLD) Integrity table (optional) (variable size)
2909 * (NEW) Streams and metadata resources (variable size)
2910 * (NEW) Lookup table (variable size)
2911 * (NEW) XML data (variable size)
2912 * (NEW) Integrity table (optional) (variable size)
2914 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2915 * the header is overwritten to point to the new lookup table, XML data, and
2916 * integrity table, to produce the following layout:
2918 * Header (212 bytes)
2919 * Streams and metadata resources (variable size)
2920 * Nothing (variable size)
2921 * More Streams and metadata resources (variable size)
2922 * Lookup table (variable size)
2923 * XML data (variable size)
2924 * Integrity table (optional) (variable size)
2926 * This method allows an image to be appended to a large WIM very quickly, and
2927 * is is crash-safe except in the case of write re-ordering, but the
2928 * disadvantage is that a small hole is left in the WIM where the old lookup
2929 * table, xml data, and integrity table were. (These usually only take up a
2930 * small amount of space compared to the streams, however.)
2933 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2934 unsigned num_threads,
2935 wimlib_progress_func_t progress_func)
2938 struct list_head stream_list;
2940 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2941 struct wim_header hdr_save;
2943 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2945 /* Set default integrity flag. */
2946 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2947 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2948 if (wim_has_integrity_table(wim))
2949 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2951 /* Set additional flags for overwrite. */
2952 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2953 WIMLIB_WRITE_FLAG_STREAMS_OK;
2955 /* Make sure that the integrity table (if present) is after the XML
2956 * data, and that there are no stream resources, metadata resources, or
2957 * lookup tables after the XML data. Otherwise, these data would be
2959 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2960 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2961 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2962 wim->hdr.lookup_table_reshdr.size_in_wim;
2963 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2964 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2965 WARNING("Didn't expect the integrity table to be before the XML data");
2966 return WIMLIB_ERR_RESOURCE_ORDER;
2969 if (old_lookup_table_end > old_xml_begin) {
2970 WARNING("Didn't expect the lookup table to be after the XML data");
2971 return WIMLIB_ERR_RESOURCE_ORDER;
2974 /* Set @old_wim_end, which indicates the point beyond which we don't
2975 * allow any file and metadata resources to appear without returning
2976 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2977 * overwrite these resources). */
2978 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2979 /* If no images have been modified and no images have been
2980 * deleted, a new lookup table does not need to be written. We
2981 * shall write the new XML data and optional integrity table
2982 * immediately after the lookup table. Note that this may
2983 * overwrite an existing integrity table. */
2984 DEBUG("Skipping writing lookup table "
2985 "(no images modified or deleted)");
2986 old_wim_end = old_lookup_table_end;
2987 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2988 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2989 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2990 /* Old WIM has an integrity table; begin writing new streams
2992 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2993 wim->hdr.integrity_table_reshdr.size_in_wim;
2995 /* No existing integrity table; begin writing new streams after
2996 * the old XML data. */
2997 old_wim_end = old_xml_end;
3000 ret = check_resource_offsets(wim, old_wim_end);
3004 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
3009 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3013 ret = lock_wim(wim, wim->out_fd.fd);
3017 /* Save original header so it can be restored in case of error */
3018 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3020 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3021 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3022 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3024 ERROR_WITH_ERRNO("Error updating WIM header flags");
3025 goto out_restore_memory_hdr;
3028 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3029 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3030 ret = WIMLIB_ERR_WRITE;
3031 goto out_restore_physical_hdr;
3034 ret = write_stream_list(&stream_list,
3037 wim->compression_type,
3046 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3047 write_flags, progress_func);
3051 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3052 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3053 progress_func, NULL);
3057 goto out_unlock_wim;
3060 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3061 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3062 wim->filename, old_wim_end);
3063 /* Return value of ftruncate() is ignored because this is
3064 * already an error path. */
3065 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3067 out_restore_physical_hdr:
3068 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3069 out_restore_memory_hdr:
3070 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3072 (void)close_wim_writable(wim, write_flags);
3074 wim->wim_locked = 0;
3079 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3080 unsigned num_threads,
3081 wimlib_progress_func_t progress_func)
3083 size_t wim_name_len;
3086 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3088 /* Write the WIM to a temporary file in the same directory as the
3090 wim_name_len = tstrlen(wim->filename);
3091 tchar tmpfile[wim_name_len + 10];
3092 tmemcpy(tmpfile, wim->filename, wim_name_len);
3093 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3094 tmpfile[wim_name_len + 9] = T('\0');
3096 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3097 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3098 num_threads, progress_func);
3106 /* Rename the new WIM file to the original WIM file. Note: on Windows
3107 * this actually calls win32_rename_replacement(), not _wrename(), so
3108 * that removing the existing destination file can be handled. */
3109 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3110 ret = trename(tmpfile, wim->filename);
3112 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3113 tmpfile, wim->filename);
3120 return WIMLIB_ERR_RENAME;
3123 if (progress_func) {
3124 union wimlib_progress_info progress;
3125 progress.rename.from = tmpfile;
3126 progress.rename.to = wim->filename;
3127 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3132 /* API function documented in wimlib.h */
3134 wimlib_overwrite(WIMStruct *wim, int write_flags,
3135 unsigned num_threads,
3136 wimlib_progress_func_t progress_func)
3141 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3143 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3144 return WIMLIB_ERR_INVALID_PARAM;
3147 return WIMLIB_ERR_NO_FILENAME;
3149 orig_hdr_flags = wim->hdr.flags;
3150 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3151 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3152 ret = can_modify_wim(wim);
3153 wim->hdr.flags = orig_hdr_flags;
3157 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3158 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3159 WIMLIB_WRITE_FLAG_PIPABLE))
3160 && !(wim_is_pipable(wim))
3161 && wim->compression_type == wim->out_compression_type
3162 && wim->chunk_size == wim->out_chunk_size)
3164 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3166 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3168 WARNING("Falling back to re-building entire WIM");
3170 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,