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 (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
79 if (lte->resource_location != RESOURCE_IN_WIM)
81 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
83 if (lte->rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
85 if (!(lte->rspec->flags & WIM_RESHDR_FLAG_COMPRESSED))
87 if (lte->rspec->wim->compression_type != out_ctype)
89 if (lte->rspec->wim->chunk_size != out_chunk_size)
95 /* Return true if the specified resource must be recompressed when the specified
96 * output parameters are used. */
98 must_compress_stream(const struct wim_lookup_table_entry *lte,
99 int write_resource_flags, int out_ctype, u32 out_chunk_size)
101 return (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
102 && ((write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
103 || !can_raw_copy(lte, write_resource_flags,
104 out_ctype, out_chunk_size)));
108 compress_chunk(const void * uncompressed_data,
109 unsigned uncompressed_len,
110 void *compressed_data,
112 struct wimlib_lzx_context *comp_ctx)
115 case WIMLIB_COMPRESSION_TYPE_XPRESS:
116 return wimlib_xpress_compress(uncompressed_data,
119 case WIMLIB_COMPRESSION_TYPE_LZX:
120 return wimlib_lzx_compress2(uncompressed_data,
124 case WIMLIB_COMPRESSION_TYPE_LZMS:
126 WARNING("LZMS compression not yet implemented!");
135 /* Chunk table that's located at the beginning of each compressed resource in
136 * the WIM. (This is not the on-disk format; the on-disk format just has an
137 * array of offsets.) */
139 u64 original_resource_size;
142 unsigned bytes_per_chunk_entry;
148 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
149 * integers, including the first offset of 0, which will not be written.
151 u8 offsets[] _aligned_attribute(8);
154 /* Allocate and initializes a chunk table, then reserve space for it in the
155 * output file unless writing a pipable resource. */
157 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
158 struct filedes *out_fd,
160 struct chunk_table **chunk_tab_ret,
165 unsigned bytes_per_chunk_entry;
167 struct chunk_table *chunk_tab;
171 num_chunks = DIV_ROUND_UP(size, out_chunk_size);
172 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
173 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
174 chunk_tab = CALLOC(1, alloc_size);
177 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
179 return WIMLIB_ERR_NOMEM;
181 chunk_tab->num_chunks = num_chunks;
182 chunk_tab->original_resource_size = size;
183 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
184 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
186 chunk_tab->cur_offset_p = chunk_tab->offsets;
188 /* We don't know the correct offsets yet; so just write zeroes to
189 * reserve space for the table, so we can go back to it later after
190 * we've written the compressed chunks following it.
192 * Special case: if writing a pipable WIM, compressed resources are in a
193 * modified format (see comment above write_pipable_wim()) and do not
194 * have a chunk table at the beginning, so don't reserve any space for
196 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
197 ret = full_write(out_fd, chunk_tab->offsets,
198 chunk_tab->table_disk_size);
200 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
206 *chunk_tab_ret = chunk_tab;
210 /* Add the offset for the next chunk to the chunk table being constructed for a
211 * compressed stream. */
213 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
215 if (chunk_tab->bytes_per_chunk_entry == 4) {
216 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
217 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
218 chunk_tab->cur_offset_u32 += out_chunk_size;
220 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
221 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
222 chunk_tab->cur_offset_u64 += out_chunk_size;
226 /* Finishes a WIM chunk table and writes it to the output file at the correct
229 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
230 struct filedes *out_fd,
231 off_t res_start_offset,
232 int write_resource_flags)
236 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
237 ret = full_write(out_fd,
239 chunk_tab->bytes_per_chunk_entry,
240 chunk_tab->table_disk_size);
242 ret = full_pwrite(out_fd,
244 chunk_tab->bytes_per_chunk_entry,
245 chunk_tab->table_disk_size,
249 ERROR_WITH_ERRNO("Write error");
253 /* Write the header for a stream in a pipable WIM.
256 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
257 struct filedes *out_fd,
258 int additional_reshdr_flags)
260 struct pwm_stream_hdr stream_hdr;
264 stream_hdr.magic = PWM_STREAM_MAGIC;
265 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
266 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
267 zero_out_hash(stream_hdr.hash);
269 wimlib_assert(!lte->unhashed);
270 copy_hash(stream_hdr.hash, lte->hash);
273 reshdr_flags = lte->flags & ~(WIM_RESHDR_FLAG_COMPRESSED | WIM_RESHDR_FLAG_PACKED_STREAMS);
274 reshdr_flags |= additional_reshdr_flags;
275 stream_hdr.flags = cpu_to_le32(reshdr_flags);
276 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
278 ERROR_WITH_ERRNO("Error writing stream header");
283 seek_and_truncate(struct filedes *out_fd, off_t offset)
285 if (filedes_seek(out_fd, offset) == -1 ||
286 ftruncate(out_fd->fd, offset))
288 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
289 return WIMLIB_ERR_WRITE;
295 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
297 u8 md[SHA1_HASH_SIZE];
299 sha1_final(md, sha_ctx);
301 copy_hash(lte->hash, md);
302 } else if (!hashes_equal(md, lte->hash)) {
303 ERROR("WIM resource has incorrect hash!");
304 if (lte_filename_valid(lte)) {
305 ERROR("We were reading it from \"%"TS"\"; maybe "
306 "it changed while we were reading it.",
309 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
314 struct write_resource_ctx {
317 struct wimlib_lzx_context *comp_ctx;
318 struct chunk_table *chunk_tab;
319 struct filedes *out_fd;
326 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
328 struct write_resource_ctx *ctx = _ctx;
329 const void *out_chunk;
330 unsigned out_chunk_size;
332 void *compressed_chunk = NULL;
333 unsigned compressed_size;
334 bool compressed_chunk_malloced = false;
337 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
340 out_chunk_size = chunk_size;
341 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
343 /* Compress the chunk. */
344 if (chunk_size <= STACK_MAX) {
345 compressed_chunk = alloca(chunk_size);
347 compressed_chunk = MALLOC(chunk_size);
348 if (compressed_chunk == NULL)
349 return WIMLIB_ERR_NOMEM;
350 compressed_chunk_malloced = true;
353 compressed_size = compress_chunk(chunk, chunk_size,
357 /* Use compressed data if compression to less than input size
359 if (compressed_size) {
360 out_chunk = compressed_chunk;
361 out_chunk_size = compressed_size;
365 if (ctx->chunk_tab) {
366 /* Update chunk table accounting. */
367 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
369 /* If writing compressed chunks to a pipable WIM, before the
370 * chunk data write a chunk header that provides the compressed
372 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
373 struct pwm_chunk_hdr chunk_hdr = {
374 .compressed_size = cpu_to_le32(out_chunk_size),
376 ret = full_write(ctx->out_fd, &chunk_hdr,
383 /* Write the chunk data. */
384 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
389 if (compressed_chunk_malloced)
390 FREE(compressed_chunk);
394 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
395 goto out_free_memory;
399 * write_wim_resource()-
401 * Write a resource to an output WIM.
404 * Lookup table entry for the resource, which could be in another WIM, in
405 * an external file, or in another location.
408 * File descriptor opened to the output WIM.
411 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
412 * compression algorithm to use.
415 * Compressed chunk size to use.
418 * On success, this is filled in with the offset, flags, compressed size,
419 * and uncompressed size of the resource in the output WIM.
422 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
423 * if it could otherwise be copied directly from the input;
424 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
425 * (and the output file descriptor may be a pipe).
428 * Location of LZX compression context pointer, which will be allocated or
429 * updated if needed. (Initialize to NULL.)
431 * Additional notes: The SHA1 message digest of the uncompressed data is
432 * calculated (except when doing a raw copy --- see below). If the @unhashed
433 * flag is set on the lookup table entry, this message digest is simply copied
434 * to it; otherwise, the message digest is compared with the existing one, and
435 * this function will fail if they do not match.
438 write_wim_resource(struct wim_lookup_table_entry *lte,
439 struct filedes *out_fd, int out_ctype,
441 struct wim_reshdr *out_reshdr,
443 struct wimlib_lzx_context **comp_ctx)
445 struct write_resource_ctx write_ctx;
446 off_t res_start_offset;
450 /* Mask out any irrelevant flags, since this function also uses this
451 * variable to store WIMLIB_READ_RESOURCE flags. */
452 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
454 /* Get current position in output WIM. */
455 res_start_offset = out_fd->offset;
457 /* If we are not forcing the data to be recompressed, and the input
458 * resource is located in a WIM with a compression mode compatible with
459 * the output, we can simply copy the compressed data without
460 * recompressing it. This also means we must skip calculating the SHA1,
461 * as we never will see the uncompressed data. */
462 if (can_raw_copy(lte, resource_flags, out_ctype, out_chunk_size)) {
463 /* Normally, for raw copies we can request a RAW_FULL read, but
464 * if we're reading from a pipable resource and writing a
465 * non-pipable resource or vice versa, then a RAW_CHUNKS read
466 * needs to be requested so that the written resource can be
467 * appropriately formatted. However, in neither case is any
468 * actual decompression needed. */
469 if (lte->rspec->is_pipable == !!(resource_flags &
470 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
472 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
473 read_size = lte->rspec->size_in_wim;
475 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
476 read_size = lte->size;
478 write_ctx.doing_sha = false;
480 write_ctx.doing_sha = true;
481 sha1_init(&write_ctx.sha_ctx);
482 read_size = lte->size;
485 /* Set the output compression mode and initialize chunk table if needed.
487 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
488 write_ctx.out_chunk_size = out_chunk_size;
489 write_ctx.chunk_tab = NULL;
490 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
491 wimlib_assert(out_chunk_size > 0);
492 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
493 /* Compression needed. */
494 write_ctx.out_ctype = out_ctype;
495 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
496 ret = wimlib_lzx_alloc_context(out_chunk_size,
501 write_ctx.comp_ctx = *comp_ctx;
503 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
504 /* Chunk table needed. */
505 ret = begin_wim_resource_chunk_tab(lte, out_fd,
507 &write_ctx.chunk_tab,
514 /* If writing a pipable resource, write the stream header and update
515 * @res_start_offset to be the end of the stream header. */
516 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
517 int reshdr_flags = 0;
518 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
519 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
520 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
522 goto out_free_chunk_tab;
523 res_start_offset = out_fd->offset;
526 /* Write the entire resource by reading the entire resource and feeding
527 * the data through write_resource_cb(). */
528 write_ctx.out_fd = out_fd;
529 write_ctx.resource_flags = resource_flags;
531 ret = read_stream_prefix(lte, read_size, write_resource_cb,
532 &write_ctx, resource_flags);
534 goto out_free_chunk_tab;
536 /* Verify SHA1 message digest of the resource, or set the hash for the
538 if (write_ctx.doing_sha) {
539 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
541 goto out_free_chunk_tab;
544 /* Write chunk table if needed. */
545 if (write_ctx.chunk_tab) {
546 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
551 goto out_free_chunk_tab;
554 /* Fill in out_reshdr with information about the newly written
556 out_reshdr->size_in_wim = out_fd->offset - res_start_offset;
557 out_reshdr->flags = lte->flags & ~WIM_RESHDR_FLAG_PACKED_STREAMS;
558 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
559 out_reshdr->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
561 out_reshdr->flags |= WIM_RESHDR_FLAG_COMPRESSED;
562 out_reshdr->offset_in_wim = res_start_offset;
563 out_reshdr->uncompressed_size = lte->size;
565 /* Check for resources compressed to greater than their original size
566 * and write them uncompressed instead. (But never do this if writing
567 * to a pipe, and don't bother if we did a raw copy.) */
568 if (out_reshdr->size_in_wim > out_reshdr->uncompressed_size &&
569 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
570 WIMLIB_READ_RESOURCE_FLAG_RAW)))
572 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
573 "writing uncompressed instead",
574 out_reshdr->uncompressed_size, out_reshdr->size_in_wim);
575 ret = seek_and_truncate(out_fd, res_start_offset);
577 goto out_free_chunk_tab;
578 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
579 FREE(write_ctx.chunk_tab);
580 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
581 write_ctx.chunk_tab = NULL;
582 write_ctx.doing_sha = false;
583 goto try_write_again;
585 if (resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW) {
586 DEBUG("Copied raw compressed data "
587 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
588 out_reshdr->uncompressed_size, out_reshdr->size_in_wim,
589 out_reshdr->offset_in_wim, out_reshdr->flags);
590 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
591 DEBUG("Wrote compressed resource "
592 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
593 out_reshdr->uncompressed_size, out_reshdr->size_in_wim,
594 out_reshdr->offset_in_wim, out_reshdr->flags);
596 DEBUG("Wrote uncompressed resource "
597 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
598 out_reshdr->uncompressed_size,
599 out_reshdr->offset_in_wim, out_reshdr->flags);
603 FREE(write_ctx.chunk_tab);
608 /* Like write_wim_resource(), but the resource is specified by a buffer of
609 * uncompressed data rather a lookup table entry. Also writes the SHA1 message
610 * digest of the buffer to @hash_ret if it is non-NULL. */
612 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
613 int reshdr_flags, struct filedes *out_fd,
616 struct wim_reshdr *out_reshdr,
617 u8 *hash_ret, int write_resource_flags,
618 struct wimlib_lzx_context **comp_ctx)
621 struct wim_lookup_table_entry *lte;
623 /* Set up a temporary lookup table entry to provide to
624 * write_wim_resource(). */
626 lte = new_lookup_table_entry();
628 return WIMLIB_ERR_NOMEM;
630 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
631 lte->attached_buffer = (void*)buf;
632 lte->size = buf_size;
633 lte->flags = reshdr_flags;
635 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
636 sha1_buffer(buf, buf_size, lte->hash);
642 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
643 out_reshdr, write_resource_flags, comp_ctx);
647 copy_hash(hash_ret, lte->hash);
650 lte->resource_location = RESOURCE_NONEXISTENT;
651 free_lookup_table_entry(lte);
656 #ifdef ENABLE_MULTITHREADED_COMPRESSION
658 /* Blocking shared queue (solves the producer-consumer problem) */
659 struct shared_queue {
663 unsigned filled_slots;
665 pthread_mutex_t lock;
666 pthread_cond_t msg_avail_cond;
667 pthread_cond_t space_avail_cond;
671 shared_queue_init(struct shared_queue *q, unsigned size)
673 wimlib_assert(size != 0);
674 q->array = CALLOC(sizeof(q->array[0]), size);
681 if (pthread_mutex_init(&q->lock, NULL)) {
682 ERROR_WITH_ERRNO("Failed to initialize mutex");
685 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
686 ERROR_WITH_ERRNO("Failed to initialize condition variable");
687 goto err_destroy_lock;
689 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
690 ERROR_WITH_ERRNO("Failed to initialize condition variable");
691 goto err_destroy_msg_avail_cond;
694 err_destroy_msg_avail_cond:
695 pthread_cond_destroy(&q->msg_avail_cond);
697 pthread_mutex_destroy(&q->lock);
699 return WIMLIB_ERR_NOMEM;
703 shared_queue_destroy(struct shared_queue *q)
706 pthread_mutex_destroy(&q->lock);
707 pthread_cond_destroy(&q->msg_avail_cond);
708 pthread_cond_destroy(&q->space_avail_cond);
712 shared_queue_put(struct shared_queue *q, void *obj)
714 pthread_mutex_lock(&q->lock);
715 while (q->filled_slots == q->size)
716 pthread_cond_wait(&q->space_avail_cond, &q->lock);
718 q->back = (q->back + 1) % q->size;
719 q->array[q->back] = obj;
722 pthread_cond_broadcast(&q->msg_avail_cond);
723 pthread_mutex_unlock(&q->lock);
727 shared_queue_get(struct shared_queue *q)
731 pthread_mutex_lock(&q->lock);
732 while (q->filled_slots == 0)
733 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
735 obj = q->array[q->front];
736 q->array[q->front] = NULL;
737 q->front = (q->front + 1) % q->size;
740 pthread_cond_broadcast(&q->space_avail_cond);
741 pthread_mutex_unlock(&q->lock);
745 struct compressor_thread_params {
746 struct shared_queue *res_to_compress_queue;
747 struct shared_queue *compressed_res_queue;
749 struct wimlib_lzx_context *comp_ctx;
752 #define MAX_CHUNKS_PER_MSG 2
755 struct wim_lookup_table_entry *lte;
757 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
758 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
759 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
760 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
762 struct list_head list;
768 compress_chunks(struct message *msg, int out_ctype,
769 struct wimlib_lzx_context *comp_ctx)
771 for (unsigned i = 0; i < msg->num_chunks; i++) {
774 len = compress_chunk(msg->uncompressed_chunks[i],
775 msg->uncompressed_chunk_sizes[i],
776 msg->compressed_chunks[i],
783 /* To be written compressed */
784 out_chunk = msg->compressed_chunks[i];
787 /* To be written uncompressed */
788 out_chunk = msg->uncompressed_chunks[i];
789 out_len = msg->uncompressed_chunk_sizes[i];
791 msg->out_chunks[i].iov_base = out_chunk;
792 msg->out_chunks[i].iov_len = out_len;
796 /* Compressor thread routine. This is a lot simpler than the main thread
797 * routine: just repeatedly get a group of chunks from the
798 * res_to_compress_queue, compress them, and put them in the
799 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
802 compressor_thread_proc(void *arg)
804 struct compressor_thread_params *params = arg;
805 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
806 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
809 DEBUG("Compressor thread ready");
810 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
811 compress_chunks(msg, params->out_ctype, params->comp_ctx);
812 shared_queue_put(compressed_res_queue, msg);
814 DEBUG("Compressor thread terminating");
817 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
819 struct write_streams_progress_data {
820 wimlib_progress_func_t progress_func;
821 union wimlib_progress_info progress;
822 uint64_t next_progress;
823 WIMStruct *prev_wim_part;
827 do_write_streams_progress(struct write_streams_progress_data *progress_data,
828 struct wim_lookup_table_entry *lte,
829 bool stream_discarded)
831 union wimlib_progress_info *progress = &progress_data->progress;
834 if (stream_discarded) {
835 progress->write_streams.total_bytes -= lte->size;
836 if (progress_data->next_progress != ~(uint64_t)0 &&
837 progress_data->next_progress > progress->write_streams.total_bytes)
839 progress_data->next_progress = progress->write_streams.total_bytes;
842 progress->write_streams.completed_bytes += lte->size;
844 new_wim_part = false;
845 if (lte->resource_location == RESOURCE_IN_WIM &&
846 lte->rspec->wim != progress_data->prev_wim_part)
848 if (progress_data->prev_wim_part) {
850 progress->write_streams.completed_parts++;
852 progress_data->prev_wim_part = lte->rspec->wim;
854 progress->write_streams.completed_streams++;
855 if (progress_data->progress_func
856 && (progress->write_streams.completed_bytes >= progress_data->next_progress
859 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
861 if (progress_data->next_progress == progress->write_streams.total_bytes) {
862 progress_data->next_progress = ~(uint64_t)0;
864 progress_data->next_progress =
865 min(progress->write_streams.total_bytes,
866 progress->write_streams.completed_bytes +
867 progress->write_streams.total_bytes / 100);
872 struct serial_write_stream_ctx {
873 struct filedes *out_fd;
876 struct wimlib_lzx_context **comp_ctx;
877 int write_resource_flags;
881 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
883 struct serial_write_stream_ctx *ctx = _ctx;
884 return write_wim_resource(lte, ctx->out_fd,
888 ctx->write_resource_flags,
893 /* Write a list of streams, taking into account that some streams may be
894 * duplicates that are checksummed and discarded on the fly, and also delegating
895 * the actual writing of a stream to a function @write_stream_cb, which is
896 * passed the context @write_stream_ctx. */
898 do_write_stream_list(struct list_head *stream_list,
899 struct wim_lookup_table *lookup_table,
900 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
901 void *write_stream_ctx,
902 struct write_streams_progress_data *progress_data)
905 struct wim_lookup_table_entry *lte;
906 bool stream_discarded;
908 /* For each stream in @stream_list ... */
909 while (!list_empty(stream_list)) {
910 stream_discarded = false;
911 lte = container_of(stream_list->next,
912 struct wim_lookup_table_entry,
914 list_del(<e->write_streams_list);
915 if (lte->unhashed && !lte->unique_size) {
916 /* Unhashed stream that shares a size with some other
917 * stream in the WIM we are writing. The stream must be
918 * checksummed to know if we need to write it or not. */
919 struct wim_lookup_table_entry *tmp;
920 u32 orig_out_refcnt = lte->out_refcnt;
922 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
926 /* We found a duplicate stream. 'lte' was
927 * freed, so replace it with the duplicate. */
930 /* 'out_refcnt' was transferred to the
931 * duplicate, and we can detect if the duplicate
932 * stream was already referenced for writing by
933 * checking if its 'out_refcnt' is higher than
934 * that of the original stream. In such cases,
935 * the current stream can be discarded. We can
936 * also discard the current stream if it was
937 * previously marked as filtered (e.g. already
938 * present in the WIM being written). */
939 if (lte->out_refcnt > orig_out_refcnt ||
941 DEBUG("Discarding duplicate stream of "
944 lte->no_progress = 0;
945 stream_discarded = true;
946 goto skip_to_progress;
951 /* Here, @lte is either a hashed stream or an unhashed stream
952 * with a unique size. In either case we know that the stream
953 * has to be written. In either case the SHA1 message digest
954 * will be calculated over the stream while writing it; however,
955 * in the former case this is done merely to check the data,
956 * while in the latter case this is done because we do not have
957 * the SHA1 message digest yet. */
958 wimlib_assert(lte->out_refcnt != 0);
960 lte->no_progress = 0;
961 ret = (*write_stream_cb)(lte, write_stream_ctx);
964 /* In parallel mode, some streams are deferred for later,
965 * serialized processing; ignore them here. */
969 list_del(<e->unhashed_list);
970 lookup_table_insert(lookup_table, lte);
974 if (!lte->no_progress) {
975 do_write_streams_progress(progress_data,
976 lte, stream_discarded);
983 do_write_stream_list_serial(struct list_head *stream_list,
984 struct wim_lookup_table *lookup_table,
985 struct filedes *out_fd,
988 struct wimlib_lzx_context **comp_ctx,
989 int write_resource_flags,
990 struct write_streams_progress_data *progress_data)
992 struct serial_write_stream_ctx ctx = {
994 .out_ctype = out_ctype,
995 .out_chunk_size = out_chunk_size,
996 .write_resource_flags = write_resource_flags,
997 .comp_ctx = comp_ctx,
999 return do_write_stream_list(stream_list,
1001 serial_write_stream,
1007 write_flags_to_resource_flags(int write_flags)
1009 int resource_flags = 0;
1011 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
1012 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
1013 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
1014 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
1015 return resource_flags;
1019 write_stream_list_serial(struct list_head *stream_list,
1020 struct wim_lookup_table *lookup_table,
1021 struct filedes *out_fd,
1024 struct wimlib_lzx_context **comp_ctx,
1025 int write_resource_flags,
1026 struct write_streams_progress_data *progress_data)
1028 union wimlib_progress_info *progress = &progress_data->progress;
1029 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
1030 progress->write_streams.total_streams);
1031 progress->write_streams.num_threads = 1;
1032 if (progress_data->progress_func) {
1033 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1036 return do_write_stream_list_serial(stream_list,
1042 write_resource_flags,
1046 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1048 write_wim_chunks(struct message *msg, struct filedes *out_fd,
1049 struct chunk_table *chunk_tab,
1050 int write_resource_flags)
1053 struct pwm_chunk_hdr *chunk_hdrs;
1057 for (unsigned i = 0; i < msg->num_chunks; i++)
1058 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1060 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1061 nvecs = msg->num_chunks;
1062 vecs = msg->out_chunks;
1064 /* Special case: If writing a compressed resource to a pipable
1065 * WIM, prefix each compressed chunk with a header that gives
1066 * its compressed size. */
1067 nvecs = msg->num_chunks * 2;
1068 vecs = alloca(nvecs * sizeof(vecs[0]));
1069 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1071 for (unsigned i = 0; i < msg->num_chunks; i++) {
1072 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1073 vecs[i * 2].iov_base = &chunk_hdrs[i];
1074 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1075 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1076 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1079 ret = full_writev(out_fd, vecs, nvecs);
1081 ERROR_WITH_ERRNO("Write error");
1085 struct main_writer_thread_ctx {
1086 struct list_head *stream_list;
1087 struct wim_lookup_table *lookup_table;
1088 struct filedes *out_fd;
1089 off_t res_start_offset;
1092 struct wimlib_lzx_context **comp_ctx;
1093 int write_resource_flags;
1094 struct shared_queue *res_to_compress_queue;
1095 struct shared_queue *compressed_res_queue;
1096 size_t num_messages;
1097 struct write_streams_progress_data *progress_data;
1099 struct list_head available_msgs;
1100 struct list_head outstanding_streams;
1101 struct list_head serial_streams;
1102 size_t num_outstanding_messages;
1104 SHA_CTX next_sha_ctx;
1106 u64 next_num_chunks;
1107 struct wim_lookup_table_entry *next_lte;
1109 struct message *msgs;
1110 struct message *next_msg;
1111 struct chunk_table *cur_chunk_tab;
1115 init_message(struct message *msg, u32 out_chunk_size)
1117 msg->out_chunk_size = out_chunk_size;
1118 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1119 msg->compressed_chunks[i] = MALLOC(out_chunk_size);
1120 msg->uncompressed_chunks[i] = MALLOC(out_chunk_size);
1121 if (msg->compressed_chunks[i] == NULL ||
1122 msg->uncompressed_chunks[i] == NULL)
1123 return WIMLIB_ERR_NOMEM;
1129 destroy_message(struct message *msg)
1131 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1132 FREE(msg->compressed_chunks[i]);
1133 FREE(msg->uncompressed_chunks[i]);
1138 free_messages(struct message *msgs, size_t num_messages)
1141 for (size_t i = 0; i < num_messages; i++)
1142 destroy_message(&msgs[i]);
1147 static struct message *
1148 allocate_messages(size_t num_messages, u32 out_chunk_size)
1150 struct message *msgs;
1152 msgs = CALLOC(num_messages, sizeof(struct message));
1155 for (size_t i = 0; i < num_messages; i++) {
1156 if (init_message(&msgs[i], out_chunk_size)) {
1157 free_messages(msgs, num_messages);
1165 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1167 while (ctx->num_outstanding_messages--)
1168 shared_queue_get(ctx->compressed_res_queue);
1169 free_messages(ctx->msgs, ctx->num_messages);
1170 FREE(ctx->cur_chunk_tab);
1174 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1176 /* Pre-allocate all the buffers that will be needed to do the chunk
1178 ctx->msgs = allocate_messages(ctx->num_messages, ctx->out_chunk_size);
1179 if (ctx->msgs == NULL)
1180 return WIMLIB_ERR_NOMEM;
1182 /* Initially, all the messages are available to use. */
1183 INIT_LIST_HEAD(&ctx->available_msgs);
1184 for (size_t i = 0; i < ctx->num_messages; i++)
1185 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1187 /* outstanding_streams is the list of streams that currently have had
1188 * chunks sent off for compression.
1190 * The first stream in outstanding_streams is the stream that is
1191 * currently being written.
1193 * The last stream in outstanding_streams is the stream that is
1194 * currently being read and having chunks fed to the compressor threads.
1196 INIT_LIST_HEAD(&ctx->outstanding_streams);
1197 ctx->num_outstanding_messages = 0;
1199 /* Message currently being prepared. */
1200 ctx->next_msg = NULL;
1202 /* Resources that don't need any chunks compressed are added to this
1203 * list and written directly by the main thread. */
1204 INIT_LIST_HEAD(&ctx->serial_streams);
1206 /* Pointer to chunk table for stream currently being written. */
1207 ctx->cur_chunk_tab = NULL;
1213 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1215 struct message *msg;
1216 struct wim_lookup_table_entry *cur_lte;
1219 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1220 wimlib_assert(ctx->num_outstanding_messages != 0);
1222 cur_lte = container_of(ctx->outstanding_streams.next,
1223 struct wim_lookup_table_entry,
1224 being_compressed_list);
1226 /* Get the next message from the queue and process it.
1227 * The message will contain 1 or more data chunks that have been
1229 msg = shared_queue_get(ctx->compressed_res_queue);
1230 msg->complete = true;
1231 --ctx->num_outstanding_messages;
1233 /* Is this the next chunk in the current resource? If it's not (i.e.,
1234 * an earlier chunk in a same or different resource hasn't been
1235 * compressed yet), do nothing, and keep this message around until all
1236 * earlier chunks are received.
1238 * Otherwise, write all the chunks we can. */
1239 while (cur_lte != NULL &&
1240 !list_empty(&cur_lte->msg_list)
1241 && (msg = container_of(cur_lte->msg_list.next,
1245 list_move(&msg->list, &ctx->available_msgs);
1246 if (msg->begin_chunk == 0) {
1247 /* First set of chunks. */
1249 /* Write pipable WIM stream header if needed. */
1250 if (ctx->write_resource_flags &
1251 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1253 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1254 WIM_RESHDR_FLAG_COMPRESSED);
1259 /* Save current offset. */
1260 ctx->res_start_offset = ctx->out_fd->offset;
1262 /* Begin building the chunk table, and leave space for
1264 ret = begin_wim_resource_chunk_tab(cur_lte,
1266 ctx->out_chunk_size,
1267 &ctx->cur_chunk_tab,
1268 ctx->write_resource_flags);
1273 /* Write the compressed chunks from the message. */
1274 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1275 ctx->write_resource_flags);
1279 /* Was this the last chunk of the stream? If so, finish the
1280 * stream by writing the chunk table. */
1281 if (list_empty(&cur_lte->msg_list) &&
1282 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1286 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1288 ctx->res_start_offset,
1289 ctx->write_resource_flags);
1293 list_del(&cur_lte->being_compressed_list);
1295 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1297 FREE(ctx->cur_chunk_tab);
1298 ctx->cur_chunk_tab = NULL;
1300 /* Check for resources compressed to greater than or
1301 * equal to their original size and write them
1302 * uncompressed instead. (But never do this if writing
1304 if (res_csize >= cur_lte->size &&
1305 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1307 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1308 "writing uncompressed instead",
1309 cur_lte->size, res_csize);
1310 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1313 ret = write_wim_resource(cur_lte,
1315 WIMLIB_COMPRESSION_TYPE_NONE,
1317 &cur_lte->out_reshdr,
1318 ctx->write_resource_flags,
1323 cur_lte->out_reshdr.size_in_wim =
1326 cur_lte->out_reshdr.uncompressed_size =
1329 cur_lte->out_reshdr.offset_in_wim =
1330 ctx->res_start_offset;
1332 cur_lte->out_reshdr.flags =
1334 WIM_RESHDR_FLAG_COMPRESSED;
1336 DEBUG("Wrote compressed resource "
1337 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1338 cur_lte->out_reshdr.uncompressed_size,
1339 cur_lte->out_reshdr.size_in_wim,
1340 cur_lte->out_reshdr.offset_in_wim,
1341 cur_lte->out_reshdr.flags);
1344 do_write_streams_progress(ctx->progress_data,
1347 /* Since we just finished writing a stream, write any
1348 * streams that have been added to the serial_streams
1349 * list for direct writing by the main thread (e.g.
1350 * resources that don't need to be compressed because
1351 * the desired compression type is the same as the
1352 * previous compression type). */
1353 if (!list_empty(&ctx->serial_streams)) {
1354 ret = do_write_stream_list_serial(&ctx->serial_streams,
1358 ctx->out_chunk_size,
1360 ctx->write_resource_flags,
1361 ctx->progress_data);
1366 /* Advance to the next stream to write. */
1367 if (list_empty(&ctx->outstanding_streams)) {
1370 cur_lte = container_of(ctx->outstanding_streams.next,
1371 struct wim_lookup_table_entry,
1372 being_compressed_list);
1379 /* Called when the main thread has read a new chunk of data. */
1381 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1383 struct main_writer_thread_ctx *ctx = _ctx;
1385 struct message *next_msg;
1386 u64 next_chunk_in_msg;
1388 /* Update SHA1 message digest for the stream currently being read by the
1390 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1392 /* We send chunks of data to the compressor chunks in batches which we
1393 * refer to as "messages". @next_msg is the message that is currently
1394 * being prepared to send off. If it is NULL, that indicates that we
1395 * need to start a new message. */
1396 next_msg = ctx->next_msg;
1398 /* We need to start a new message. First check to see if there
1399 * is a message available in the list of available messages. If
1400 * so, we can just take one. If not, all the messages (there is
1401 * a fixed number of them, proportional to the number of
1402 * threads) have been sent off to the compressor threads, so we
1403 * receive messages from the compressor threads containing
1404 * compressed chunks of data.
1406 * We may need to receive multiple messages before one is
1407 * actually available to use because messages received that are
1408 * *not* for the very next set of chunks to compress must be
1409 * buffered until it's time to write those chunks. */
1410 while (list_empty(&ctx->available_msgs)) {
1411 ret = receive_compressed_chunks(ctx);
1416 next_msg = container_of(ctx->available_msgs.next,
1417 struct message, list);
1418 list_del(&next_msg->list);
1419 next_msg->complete = false;
1420 next_msg->begin_chunk = ctx->next_chunk;
1421 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1422 ctx->next_num_chunks - ctx->next_chunk);
1423 ctx->next_msg = next_msg;
1426 /* Fill in the next chunk to compress */
1427 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1429 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1430 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1433 if (++next_chunk_in_msg == next_msg->num_chunks) {
1434 /* Send off an array of chunks to compress */
1435 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1436 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1437 ++ctx->num_outstanding_messages;
1438 ctx->next_msg = NULL;
1444 main_writer_thread_finish(void *_ctx)
1446 struct main_writer_thread_ctx *ctx = _ctx;
1448 while (ctx->num_outstanding_messages != 0) {
1449 ret = receive_compressed_chunks(ctx);
1453 wimlib_assert(list_empty(&ctx->outstanding_streams));
1454 return do_write_stream_list_serial(&ctx->serial_streams,
1458 ctx->out_chunk_size,
1460 ctx->write_resource_flags,
1461 ctx->progress_data);
1465 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1466 struct main_writer_thread_ctx *ctx)
1470 /* Read the entire stream @lte, feeding its data chunks to the
1471 * compressor threads. Also SHA1-sum the stream; this is required in
1472 * the case that @lte is unhashed, and a nice additional verification
1473 * when @lte is already hashed. */
1474 sha1_init(&ctx->next_sha_ctx);
1475 ctx->next_chunk = 0;
1476 ctx->next_num_chunks = DIV_ROUND_UP(lte->size, ctx->out_chunk_size);
1477 ctx->next_lte = lte;
1478 INIT_LIST_HEAD(<e->msg_list);
1479 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1480 ret = read_stream_prefix(lte, lte->size, main_writer_thread_cb, ctx, 0);
1483 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1484 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1488 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1490 struct main_writer_thread_ctx *ctx = _ctx;
1493 if (lte->size < 1000 ||
1494 !must_compress_stream(lte, ctx->write_resource_flags,
1495 ctx->out_ctype, ctx->out_chunk_size))
1497 /* Stream is too small or isn't being compressed. Process it by
1498 * the main thread when we have a chance. We can't necessarily
1499 * process it right here, as the main thread could be in the
1500 * middle of writing a different stream. */
1501 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1505 ret = submit_stream_for_compression(lte, ctx);
1507 lte->no_progress = 1;
1512 get_default_num_threads(void)
1515 return win32_get_number_of_processors();
1517 return sysconf(_SC_NPROCESSORS_ONLN);
1521 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1522 * parameter and will perform compression using that many threads. Falls
1523 * back to write_stream_list_serial() on certain errors, such as a failure to
1524 * create the number of threads requested.
1526 * High level description of the algorithm for writing compressed streams in
1527 * parallel: We perform compression on chunks rather than on full files. The
1528 * currently executing thread becomes the main thread and is entirely in charge
1529 * of reading the data to compress (which may be in any location understood by
1530 * the resource code--- such as in an external file being captured, or in
1531 * another WIM file from which an image is being exported) and actually writing
1532 * the compressed data to the output file. Additional threads are "compressor
1533 * threads" and all execute the compressor_thread_proc, where they repeatedly
1534 * retrieve buffers of data from the main thread, compress them, and hand them
1535 * back to the main thread.
1537 * Certain streams, such as streams that do not need to be compressed (e.g.
1538 * input compression type same as output compression type) or streams of very
1539 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1540 * handled entirely by the main thread at an appropriate time.
1542 * At any given point in time, multiple streams may be having chunks compressed
1543 * concurrently. The stream that the main thread is currently *reading* may be
1544 * later in the list that the stream that the main thread is currently
1547 write_stream_list_parallel(struct list_head *stream_list,
1548 struct wim_lookup_table *lookup_table,
1549 struct filedes *out_fd,
1552 struct wimlib_lzx_context **comp_ctx,
1553 int write_resource_flags,
1554 struct write_streams_progress_data *progress_data,
1555 unsigned num_threads)
1558 struct shared_queue res_to_compress_queue;
1559 struct shared_queue compressed_res_queue;
1560 pthread_t *compressor_threads = NULL;
1561 union wimlib_progress_info *progress = &progress_data->progress;
1562 unsigned num_started_threads;
1563 bool can_retry = true;
1565 if (num_threads == 0) {
1566 long nthreads = get_default_num_threads();
1567 if (nthreads < 1 || nthreads > UINT_MAX) {
1568 WARNING("Could not determine number of processors! Assuming 1");
1569 goto out_serial_quiet;
1570 } else if (nthreads == 1) {
1571 goto out_serial_quiet;
1573 num_threads = nthreads;
1577 DEBUG("Writing stream list of size %"PRIu64" "
1578 "(parallel version, num_threads=%u)",
1579 progress->write_streams.total_streams, num_threads);
1581 progress->write_streams.num_threads = num_threads;
1583 static const size_t MESSAGES_PER_THREAD = 2;
1584 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1586 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1588 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1592 ret = shared_queue_init(&compressed_res_queue, queue_size);
1594 goto out_destroy_res_to_compress_queue;
1596 struct compressor_thread_params *params;
1598 params = CALLOC(num_threads, sizeof(params[0]));
1599 if (params == NULL) {
1600 ret = WIMLIB_ERR_NOMEM;
1601 goto out_destroy_compressed_res_queue;
1604 for (unsigned i = 0; i < num_threads; i++) {
1605 params[i].res_to_compress_queue = &res_to_compress_queue;
1606 params[i].compressed_res_queue = &compressed_res_queue;
1607 params[i].out_ctype = out_ctype;
1608 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1609 ret = wimlib_lzx_alloc_context(out_chunk_size,
1610 NULL, ¶ms[i].comp_ctx);
1612 goto out_free_params;
1616 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1617 if (compressor_threads == NULL) {
1618 ret = WIMLIB_ERR_NOMEM;
1619 goto out_free_params;
1622 for (unsigned i = 0; i < num_threads; i++) {
1623 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1624 ret = pthread_create(&compressor_threads[i], NULL,
1625 compressor_thread_proc, ¶ms[i]);
1629 ERROR_WITH_ERRNO("Failed to create compressor "
1631 i + 1, num_threads);
1632 num_started_threads = i;
1636 num_started_threads = num_threads;
1638 if (progress_data->progress_func) {
1639 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1643 struct main_writer_thread_ctx ctx;
1645 memset(&ctx, 0, sizeof(ctx));
1647 ctx.stream_list = stream_list;
1648 ctx.lookup_table = lookup_table;
1649 ctx.out_fd = out_fd;
1650 ctx.out_ctype = out_ctype;
1651 ctx.out_chunk_size = out_chunk_size;
1652 ctx.comp_ctx = comp_ctx;
1653 ctx.res_to_compress_queue = &res_to_compress_queue;
1654 ctx.compressed_res_queue = &compressed_res_queue;
1655 ctx.num_messages = queue_size;
1656 ctx.write_resource_flags = write_resource_flags;
1657 ctx.progress_data = progress_data;
1658 ret = main_writer_thread_init_ctx(&ctx);
1663 ret = do_write_stream_list(stream_list, lookup_table,
1664 main_thread_process_next_stream,
1665 &ctx, progress_data);
1667 goto out_destroy_ctx;
1669 /* The main thread has finished reading all streams that are going to be
1670 * compressed in parallel, and it now needs to wait for all remaining
1671 * chunks to be compressed so that the remaining streams can actually be
1672 * written to the output file. Furthermore, any remaining streams that
1673 * had processing deferred to the main thread need to be handled. These
1674 * tasks are done by the main_writer_thread_finish() function. */
1675 ret = main_writer_thread_finish(&ctx);
1677 main_writer_thread_destroy_ctx(&ctx);
1679 for (unsigned i = 0; i < num_started_threads; i++)
1680 shared_queue_put(&res_to_compress_queue, NULL);
1682 for (unsigned i = 0; i < num_started_threads; i++) {
1683 if (pthread_join(compressor_threads[i], NULL)) {
1684 WARNING_WITH_ERRNO("Failed to join compressor "
1686 i + 1, num_threads);
1689 FREE(compressor_threads);
1691 for (unsigned i = 0; i < num_threads; i++)
1692 wimlib_lzx_free_context(params[i].comp_ctx);
1694 out_destroy_compressed_res_queue:
1695 shared_queue_destroy(&compressed_res_queue);
1696 out_destroy_res_to_compress_queue:
1697 shared_queue_destroy(&res_to_compress_queue);
1698 if (!can_retry || (ret >= 0 && ret != WIMLIB_ERR_NOMEM))
1701 WARNING("Falling back to single-threaded compression");
1703 return write_stream_list_serial(stream_list,
1709 write_resource_flags,
1715 /* Write a list of streams to a WIM (@out_fd) using the compression type
1716 * @out_ctype, chunk size @out_chunk_size, and up to @num_threads compressor
1719 write_stream_list(struct list_head *stream_list,
1720 struct wim_lookup_table *lookup_table,
1721 struct filedes *out_fd, int out_ctype,
1723 struct wimlib_lzx_context **comp_ctx,
1725 unsigned num_threads, wimlib_progress_func_t progress_func)
1728 int write_resource_flags;
1730 u64 total_compression_bytes;
1731 unsigned total_parts;
1732 WIMStruct *prev_wim_part;
1734 struct wim_lookup_table_entry *lte;
1735 struct write_streams_progress_data progress_data;
1737 if (list_empty(stream_list)) {
1738 DEBUG("No streams to write.");
1742 write_resource_flags = write_flags_to_resource_flags(write_flags);
1744 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1745 out_fd->offset, write_resource_flags);
1747 /* Sort the stream list into a good order for reading. */
1748 ret = sort_stream_list_by_sequential_order(stream_list,
1749 offsetof(struct wim_lookup_table_entry,
1750 write_streams_list));
1754 /* Calculate the total size of the streams to be written. Note: this
1755 * will be the uncompressed size, as we may not know the compressed size
1756 * yet, and also this will assume that every unhashed stream will be
1757 * written (which will not necessarily be the case). */
1759 total_compression_bytes = 0;
1762 prev_wim_part = NULL;
1763 list_for_each_entry(lte, stream_list, write_streams_list) {
1765 total_bytes += lte->size;
1766 if (must_compress_stream(lte, write_resource_flags,
1767 out_ctype, out_chunk_size))
1768 total_compression_bytes += lte->size;
1769 if (lte->resource_location == RESOURCE_IN_WIM) {
1770 if (prev_wim_part != lte->rspec->wim) {
1771 prev_wim_part = lte->rspec->wim;
1777 memset(&progress_data, 0, sizeof(progress_data));
1778 progress_data.progress_func = progress_func;
1780 progress_data.progress.write_streams.total_bytes = total_bytes;
1781 progress_data.progress.write_streams.total_streams = num_streams;
1782 progress_data.progress.write_streams.completed_bytes = 0;
1783 progress_data.progress.write_streams.completed_streams = 0;
1784 progress_data.progress.write_streams.num_threads = num_threads;
1785 progress_data.progress.write_streams.compression_type = out_ctype;
1786 progress_data.progress.write_streams.total_parts = total_parts;
1787 progress_data.progress.write_streams.completed_parts = 0;
1789 progress_data.next_progress = 0;
1790 progress_data.prev_wim_part = NULL;
1792 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1793 if (total_compression_bytes >= 2000000 && num_threads != 1)
1794 ret = write_stream_list_parallel(stream_list,
1800 write_resource_flags,
1805 ret = write_stream_list_serial(stream_list,
1811 write_resource_flags,
1814 DEBUG("Successfully wrote stream list.");
1816 DEBUG("Failed to write stream list (ret=%d).", ret);
1820 struct stream_size_table {
1821 struct hlist_head *array;
1827 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1829 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1831 return WIMLIB_ERR_NOMEM;
1832 tab->num_entries = 0;
1833 tab->capacity = capacity;
1838 destroy_stream_size_table(struct stream_size_table *tab)
1844 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1846 struct stream_size_table *tab = _tab;
1848 struct wim_lookup_table_entry *same_size_lte;
1849 struct hlist_node *tmp;
1851 pos = hash_u64(lte->size) % tab->capacity;
1852 lte->unique_size = 1;
1853 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1854 if (same_size_lte->size == lte->size) {
1855 lte->unique_size = 0;
1856 same_size_lte->unique_size = 0;
1861 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1866 struct find_streams_ctx {
1869 struct list_head stream_list;
1870 struct stream_size_table stream_size_tab;
1874 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1875 struct find_streams_ctx *ctx,
1878 if (lte->out_refcnt == 0) {
1879 stream_size_table_insert(lte, &ctx->stream_size_tab);
1880 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1882 lte->out_refcnt += nref;
1886 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1889 struct find_streams_ctx *ctx = _ctx;
1890 lte->out_refcnt = 0;
1891 lte_reference_for_logical_write(lte, ctx,
1892 (lte->refcnt ? lte->refcnt : 1));
1897 inode_find_streams_to_write(struct wim_inode *inode,
1898 struct wim_lookup_table *table,
1899 struct find_streams_ctx *ctx)
1901 struct wim_lookup_table_entry *lte;
1904 for (i = 0; i <= inode->i_num_ads; i++) {
1905 lte = inode_stream_lte(inode, i, table);
1907 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1908 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1909 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1915 image_find_streams_to_write(WIMStruct *wim)
1917 struct find_streams_ctx *ctx;
1918 struct wim_image_metadata *imd;
1919 struct wim_inode *inode;
1920 struct wim_lookup_table_entry *lte;
1924 imd = wim_get_current_image_metadata(wim);
1926 image_for_each_unhashed_stream(lte, imd)
1927 lte->out_refcnt = 0;
1929 /* Go through this image's inodes to find any streams that have not been
1931 image_for_each_inode(inode, imd) {
1932 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1940 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1941 * the "logical write" of the WIM, meaning all streams that are referenced at
1942 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1943 * each stream being included in the logical write is set to the number of
1944 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1945 * stream being included in the logical write is set to indicate whether that
1946 * stream has a unique size relative to the streams being included in the
1947 * logical write. Still furthermore, 'part_number' on each stream being
1948 * included in the logical write is set to the part number given in the
1949 * in-memory header of @p wim.
1951 * This is considered a "logical write" because it does not take into account
1952 * filtering out streams already present in the WIM (in the case of an in place
1953 * overwrite) or present in other WIMs (in case of creating delta WIM).
1956 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1957 struct find_streams_ctx *ctx)
1961 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1962 (image == 1 && wim->hdr.image_count == 1)))
1964 /* Fast case: Assume that all streams are being written and
1965 * that the reference counts are correct. */
1966 struct wim_lookup_table_entry *lte;
1967 struct wim_image_metadata *imd;
1970 for_lookup_table_entry(wim->lookup_table,
1971 do_lte_full_reference_for_logical_write, ctx);
1972 for (i = 0; i < wim->hdr.image_count; i++) {
1973 imd = wim->image_metadata[i];
1974 image_for_each_unhashed_stream(lte, imd)
1975 do_lte_full_reference_for_logical_write(lte, ctx);
1978 /* Slow case: Walk through the images being written and
1979 * determine the streams referenced. */
1980 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1982 ret = for_image(wim, image, image_find_streams_to_write);
1991 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1993 struct find_streams_ctx *ctx = _ctx;
1996 /* Calculate and set lte->filtered. */
1997 if (lte->resource_location == RESOURCE_IN_WIM) {
1998 if (lte->rspec->wim == ctx->wim &&
1999 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
2000 filtered |= FILTERED_SAME_WIM;
2001 if (lte->rspec->wim != ctx->wim &&
2002 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
2003 filtered |= FILTERED_EXTERNAL_WIM;
2005 lte->filtered = filtered;
2007 /* Filtered streams get inserted into the stream size table too, unless
2008 * they already were. This is because streams that are checksummed
2009 * on-the-fly during the write should not be written if they are
2010 * duplicates of filtered stream. */
2011 if (lte->filtered && lte->out_refcnt == 0)
2012 stream_size_table_insert(lte, &ctx->stream_size_tab);
2017 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
2023 /* Given the list of streams to include in a logical write of a WIM, handle
2024 * filtering out streams already present in the WIM or already present in
2025 * external WIMs, depending on the write flags provided. */
2027 handle_stream_filtering(struct find_streams_ctx *ctx)
2029 struct wim_lookup_table_entry *lte, *tmp;
2031 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2032 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2034 for_lookup_table_entry(ctx->wim->lookup_table,
2035 mark_stream_not_filtered, ctx);
2039 for_lookup_table_entry(ctx->wim->lookup_table,
2040 process_filtered_stream, ctx);
2042 /* Streams in logical write list that were filtered can be removed. */
2043 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2046 list_del(<e->write_streams_list);
2049 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2050 * around prepare_logical_stream_list() to handle filtering out streams already
2051 * present in the WIM or already present in external WIMs, depending on the
2052 * write flags provided.
2054 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2056 * - 'out_refcnt' is set to the number of references found for the logical write.
2057 * This will be nonzero on all streams in the list returned by this function,
2058 * but will also be nonzero on streams not in the list that were included in
2059 * the logical write list, but filtered out from the returned list.
2060 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2061 * are not included in the list of streams returned by this function.
2062 * - 'unique_size' is set if the stream has a unique size among all streams in
2063 * the logical write plus any filtered streams in the entire WIM that could
2064 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2065 * stream being written.
2068 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2069 struct list_head *stream_list)
2073 struct find_streams_ctx ctx;
2075 INIT_LIST_HEAD(&ctx.stream_list);
2076 ret = init_stream_size_table(&ctx.stream_size_tab,
2077 wim->lookup_table->capacity);
2080 ctx.write_flags = write_flags;
2083 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2085 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2087 goto out_destroy_table;
2089 handle_stream_filtering(&ctx);
2090 list_transfer(&ctx.stream_list, stream_list);
2093 destroy_stream_size_table(&ctx.stream_size_tab);
2098 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2099 unsigned num_threads,
2100 wimlib_progress_func_t progress_func,
2101 struct list_head *stream_list_override)
2104 struct list_head _stream_list;
2105 struct list_head *stream_list;
2106 struct wim_lookup_table_entry *lte;
2108 if (stream_list_override == NULL) {
2109 /* Normal case: prepare stream list from image(s) being written.
2111 stream_list = &_stream_list;
2112 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2116 /* Currently only as a result of wimlib_split() being called:
2117 * use stream list already explicitly provided. Use existing
2118 * reference counts. */
2119 stream_list = stream_list_override;
2120 list_for_each_entry(lte, stream_list, write_streams_list)
2121 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2124 return write_stream_list(stream_list,
2127 wim->out_compression_type,
2128 wim->out_chunk_size,
2136 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2137 wimlib_progress_func_t progress_func)
2142 int write_resource_flags;
2144 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2145 DEBUG("Not writing any metadata resources.");
2149 write_resource_flags = write_flags_to_resource_flags(write_flags);
2151 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2152 wim->out_fd.offset);
2155 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2157 if (image == WIMLIB_ALL_IMAGES) {
2159 end_image = wim->hdr.image_count;
2161 start_image = image;
2165 for (int i = start_image; i <= end_image; i++) {
2166 struct wim_image_metadata *imd;
2168 imd = wim->image_metadata[i - 1];
2169 /* Build a new metadata resource only if image was modified from
2170 * the original (or was newly added). Otherwise just copy the
2172 if (imd->modified) {
2173 DEBUG("Image %u was modified; building and writing new "
2174 "metadata resource", i);
2175 ret = write_metadata_resource(wim, i,
2176 write_resource_flags);
2177 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2178 DEBUG("Image %u was not modified; re-using existing "
2179 "metadata resource.", i);
2180 wim_res_spec_to_hdr(imd->metadata_lte->rspec,
2181 &imd->metadata_lte->out_reshdr);
2184 DEBUG("Image %u was not modified; copying existing "
2185 "metadata resource.", i);
2186 ret = write_wim_resource(imd->metadata_lte,
2188 wim->out_compression_type,
2189 wim->out_chunk_size,
2190 &imd->metadata_lte->out_reshdr,
2191 write_resource_flags,
2198 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2203 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2206 DEBUG("Opening \"%"TS"\" for writing.", path);
2208 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2210 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2211 return WIMLIB_ERR_OPEN;
2213 filedes_init(&wim->out_fd, raw_fd);
2218 close_wim_writable(WIMStruct *wim, int write_flags)
2222 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2223 DEBUG("Closing WIM file.");
2224 if (filedes_valid(&wim->out_fd))
2225 if (filedes_close(&wim->out_fd))
2226 ret = WIMLIB_ERR_WRITE;
2228 filedes_invalidate(&wim->out_fd);
2235 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2236 * table, then overwrite the WIM header. By default, closes the WIM file
2237 * descriptor (@wim->out_fd) if successful.
2239 * write_flags is a bitwise OR of the following:
2241 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2242 * Include an integrity table.
2244 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2245 * fsync() the output file before closing it.
2247 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2248 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2249 * stream headers before the lookup table and XML data, and also
2250 * write the WIM header at the end instead of seeking to the
2251 * beginning. Can't be combined with
2252 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2254 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2255 * Don't write the lookup table.
2257 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2258 * When (if) writing the integrity table, re-use entries from the
2259 * existing integrity table, if possible.
2261 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2262 * After writing the XML data but before writing the integrity
2263 * table, write a temporary WIM header and flush the stream so that
2264 * the WIM is less likely to become corrupted upon abrupt program
2266 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2267 * Instead of overwriting the WIM header at the beginning of the
2268 * file, simply append it to the end of the file. (Used when
2270 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2271 * Do not close the file descriptor @wim->out_fd on either success
2273 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2274 * Use the existing <TOTALBYTES> stored in the in-memory XML
2275 * information, rather than setting it to the offset of the XML
2276 * data being written.
2279 finish_write(WIMStruct *wim, int image, int write_flags,
2280 wimlib_progress_func_t progress_func,
2281 struct list_head *stream_list_override)
2285 int write_resource_flags;
2286 off_t old_lookup_table_end;
2287 off_t new_lookup_table_end;
2290 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2292 write_resource_flags = write_flags_to_resource_flags(write_flags);
2294 /* In the WIM header, there is room for the resource entry for a
2295 * metadata resource labeled as the "boot metadata". This entry should
2296 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2297 * it should be a copy of the resource entry for the image that is
2298 * marked as bootable. This is not well documented... */
2299 if (wim->hdr.boot_idx == 0) {
2300 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2302 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2303 &wim->image_metadata[wim->hdr.boot_idx- 1
2304 ]->metadata_lte->out_reshdr);
2307 /* Write lookup table. (Save old position first.) */
2308 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2309 wim->hdr.lookup_table_reshdr.size_in_wim;
2310 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2311 ret = write_wim_lookup_table(wim, image, write_flags,
2312 &wim->hdr.lookup_table_reshdr,
2313 stream_list_override);
2318 /* Write XML data. */
2319 xml_totalbytes = wim->out_fd.offset;
2320 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2321 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2322 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2323 &wim->hdr.xml_data_reshdr,
2324 write_resource_flags);
2328 /* Write integrity table (optional). */
2329 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2330 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2331 struct wim_header checkpoint_hdr;
2332 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2333 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2334 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2335 ret = write_wim_header_at_offset(&checkpoint_hdr,
2341 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2342 old_lookup_table_end = 0;
2344 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2345 wim->hdr.lookup_table_reshdr.size_in_wim;
2347 ret = write_integrity_table(wim,
2348 new_lookup_table_end,
2349 old_lookup_table_end,
2354 /* No integrity table. */
2355 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2358 /* Now that all information in the WIM header has been determined, the
2359 * preliminary header written earlier can be overwritten, the header of
2360 * the existing WIM file can be overwritten, or the final header can be
2361 * written to the end of the pipable WIM. */
2362 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2364 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2365 hdr_offset = wim->out_fd.offset;
2366 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2367 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2371 /* Possibly sync file data to disk before closing. On POSIX systems, it
2372 * is necessary to do this before using rename() to overwrite an
2373 * existing file with a new file. Otherwise, data loss would occur if
2374 * the system is abruptly terminated when the metadata for the rename
2375 * operation has been written to disk, but the new file data has not.
2377 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2378 DEBUG("Syncing WIM file.");
2379 if (fsync(wim->out_fd.fd)) {
2380 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2381 return WIMLIB_ERR_WRITE;
2385 if (close_wim_writable(wim, write_flags)) {
2386 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2387 return WIMLIB_ERR_WRITE;
2393 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2395 lock_wim(WIMStruct *wim, int fd)
2398 if (fd != -1 && !wim->wim_locked) {
2399 ret = flock(fd, LOCK_EX | LOCK_NB);
2401 if (errno == EWOULDBLOCK) {
2402 ERROR("`%"TS"' is already being modified or has been "
2403 "mounted read-write\n"
2404 " by another process!", wim->filename);
2405 ret = WIMLIB_ERR_ALREADY_LOCKED;
2407 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2412 wim->wim_locked = 1;
2420 * write_pipable_wim():
2422 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2423 * capable of being applied from a pipe).
2425 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2426 * images can be applied from them sequentially when the file data is sent over
2427 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2428 * The modifications made to the WIM format for pipable WIMs are:
2430 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2431 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2432 * stops other software from trying to read the file as a normal WIM.
2434 * - The header at the beginning of the file does not contain all the normal
2435 * information; in particular it will have all 0's for the lookup table and
2436 * XML data resource entries. This is because this information cannot be
2437 * determined until the lookup table and XML data have been written.
2438 * Consequently, wimlib will write the full header at the very end of the
2439 * file. The header at the end, however, is only used when reading the WIM
2440 * from a seekable file (not a pipe).
2442 * - An extra copy of the XML data is placed directly after the header. This
2443 * allows image names and sizes to be determined at an appropriate time when
2444 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2445 * WIM is read from a seekable file (not a pipe).
2447 * - The format of resources, or streams, has been modified to allow them to be
2448 * used before the "lookup table" has been read. Each stream is prefixed with
2449 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2450 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2451 * uncompressed stream size, and flags that indicate whether the stream is
2452 * compressed. The data of uncompressed streams then follows literally, while
2453 * the data of compressed streams follows in a modified format. Compressed
2454 * streams do not begin with a chunk table, since the chunk table cannot be
2455 * written until all chunks have been compressed. Instead, each compressed
2456 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2457 * Furthermore, the chunk table is written at the end of the resource instead
2458 * of the start. Note: chunk offsets are given in the chunk table as if the
2459 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2460 * used if the WIM is being read from a seekable file (not a pipe).
2462 * - Metadata resources always come before other file resources (streams).
2463 * (This does not by itself constitute an incompatibility with normal WIMs,
2464 * since this is valid in normal WIMs.)
2466 * - At least up to the end of the file resources, all components must be packed
2467 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2468 * not by itself consititute an incompatibility with normal WIMs, since this
2469 * is valid in normal WIMs.)
2471 * Note: the lookup table, XML data, and header at the end are not used when
2472 * applying from a pipe. They exist to support functionality such as image
2473 * application and export when the WIM is *not* read from a pipe.
2475 * Layout of pipable WIM:
2477 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2478 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2479 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2481 * Layout of normal WIM:
2483 * +--------+-----------------------------+-------------------------+
2484 * | Header | File and metadata resources | Lookup table | XML data |
2485 * +--------+-----------------------------+-------------------------+
2487 * An optional integrity table can follow the final XML data in both normal and
2488 * pipable WIMs. However, due to implementation details, wimlib currently can
2489 * only include an integrity table in a pipable WIM when writing it to a
2490 * seekable file (not a pipe).
2492 * Do note that since pipable WIMs are not supported by Microsoft's software,
2493 * wimlib does not create them unless explicitly requested (with
2494 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2495 * characters to identify the file.
2498 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2499 unsigned num_threads, wimlib_progress_func_t progress_func,
2500 struct list_head *stream_list_override)
2503 struct wim_reshdr xml_reshdr;
2505 WARNING("Creating a pipable WIM, which will "
2507 " with Microsoft's software (wimgapi/imagex/Dism).");
2509 /* At this point, the header at the beginning of the file has already
2512 /* For efficiency, when wimlib adds an image to the WIM with
2513 * wimlib_add_image(), the SHA1 message digests of files is not
2514 * calculated; instead, they are calculated while the files are being
2515 * written. However, this does not work when writing a pipable WIM,
2516 * since when writing a stream to a pipable WIM, its SHA1 message digest
2517 * needs to be known before the stream data is written. Therefore,
2518 * before getting much farther, we need to pre-calculate the SHA1
2519 * message digests of all streams that will be written. */
2520 ret = wim_checksum_unhashed_streams(wim);
2524 /* Write extra copy of the XML data. */
2525 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2527 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2531 /* Write metadata resources for the image(s) being included in the
2533 ret = write_wim_metadata_resources(wim, image, write_flags,
2538 /* Write streams needed for the image(s) being included in the output
2539 * WIM, or streams needed for the split WIM part. */
2540 return write_wim_streams(wim, image, write_flags, num_threads,
2541 progress_func, stream_list_override);
2543 /* The lookup table, XML data, and header at end are handled by
2544 * finish_write(). */
2547 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2550 write_wim_part(WIMStruct *wim,
2551 const void *path_or_fd,
2554 unsigned num_threads,
2555 wimlib_progress_func_t progress_func,
2556 unsigned part_number,
2557 unsigned total_parts,
2558 struct list_head *stream_list_override,
2562 struct wim_header hdr_save;
2563 struct list_head lt_stream_list_override;
2565 if (total_parts == 1)
2566 DEBUG("Writing standalone WIM.");
2568 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2569 if (image == WIMLIB_ALL_IMAGES)
2570 DEBUG("Including all images.");
2572 DEBUG("Including image %d only.", image);
2573 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2574 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2576 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2577 DEBUG("Write flags: 0x%08x", write_flags);
2578 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2579 DEBUG("\tCHECK_INTEGRITY");
2580 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2582 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2583 DEBUG("\tRECOMPRESS");
2584 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2586 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2588 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2589 DEBUG("\tIGNORE_READONLY_FLAG");
2590 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2592 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2593 DEBUG("\tFILE_DESCRIPTOR");
2594 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2595 DEBUG("\tNO_METADATA");
2596 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2597 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2598 if (num_threads == 0)
2599 DEBUG("Number of threads: autodetect");
2601 DEBUG("Number of threads: %u", num_threads);
2602 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2603 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2604 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2605 "specified" : "generate new"));
2607 /* Internally, this is always called with a valid part number and total
2609 wimlib_assert(total_parts >= 1);
2610 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2612 /* A valid image (or all images) must be specified. */
2613 if (image != WIMLIB_ALL_IMAGES &&
2614 (image < 1 || image > wim->hdr.image_count))
2615 return WIMLIB_ERR_INVALID_IMAGE;
2617 /* If we need to write metadata resources, make sure the ::WIMStruct has
2618 * the needed information attached (e.g. is not a resource-only WIM,
2619 * such as a non-first part of a split WIM). */
2620 if (!wim_has_metadata(wim) &&
2621 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2622 return WIMLIB_ERR_METADATA_NOT_FOUND;
2624 /* Check for contradictory flags. */
2625 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2626 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2627 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2628 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2629 return WIMLIB_ERR_INVALID_PARAM;
2631 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2632 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2633 == (WIMLIB_WRITE_FLAG_PIPABLE |
2634 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2635 return WIMLIB_ERR_INVALID_PARAM;
2637 /* Save previous header, then start initializing the new one. */
2638 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2640 /* Set default integrity and pipable flags. */
2641 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2642 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2643 if (wim_is_pipable(wim))
2644 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2646 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2647 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2648 if (wim_has_integrity_table(wim))
2649 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2651 /* Set appropriate magic number. */
2652 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2653 wim->hdr.magic = PWM_MAGIC;
2655 wim->hdr.magic = WIM_MAGIC;
2657 /* Clear header flags that will be set automatically. */
2658 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2659 WIM_HDR_FLAG_RESOURCE_ONLY |
2660 WIM_HDR_FLAG_SPANNED |
2661 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2663 /* Set SPANNED header flag if writing part of a split WIM. */
2664 if (total_parts != 1)
2665 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2667 /* Set part number and total parts of split WIM. This will be 1 and 1
2668 * if the WIM is standalone. */
2669 wim->hdr.part_number = part_number;
2670 wim->hdr.total_parts = total_parts;
2672 /* Set compression type if different. */
2673 if (wim->compression_type != wim->out_compression_type) {
2674 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2675 wimlib_assert(ret == 0);
2678 /* Set chunk size if different. */
2679 wim->hdr.chunk_size = wim->out_chunk_size;
2681 /* Use GUID if specified; otherwise generate a new one. */
2683 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2684 else if (!wim->guid_set_explicitly)
2685 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2687 /* Clear references to resources that have not been written yet. */
2688 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2689 zero_reshdr(&wim->hdr.xml_data_reshdr);
2690 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2691 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2693 /* Set image count and boot index correctly for single image writes. */
2694 if (image != WIMLIB_ALL_IMAGES) {
2695 wim->hdr.image_count = 1;
2696 if (wim->hdr.boot_idx == image)
2697 wim->hdr.boot_idx = 1;
2699 wim->hdr.boot_idx = 0;
2702 /* Split WIMs can't be bootable. */
2703 if (total_parts != 1)
2704 wim->hdr.boot_idx = 0;
2706 /* Initialize output file descriptor. */
2707 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2708 /* File descriptor was explicitly provided. Return error if
2709 * file descriptor is not seekable, unless writing a pipable WIM
2711 wim->out_fd.fd = *(const int*)path_or_fd;
2712 wim->out_fd.offset = 0;
2713 if (!filedes_is_seekable(&wim->out_fd)) {
2714 ret = WIMLIB_ERR_INVALID_PARAM;
2715 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2716 goto out_restore_hdr;
2717 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2718 ERROR("Can't include integrity check when "
2719 "writing pipable WIM to pipe!");
2720 goto out_restore_hdr;
2725 /* Filename of WIM to write was provided; open file descriptor
2727 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2728 O_TRUNC | O_CREAT | O_RDWR);
2730 goto out_restore_hdr;
2733 /* Write initial header. This is merely a "dummy" header since it
2734 * doesn't have all the information yet, so it will be overwritten later
2735 * (unless writing a pipable WIM). */
2736 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2737 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2738 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2739 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2741 goto out_restore_hdr;
2743 if (stream_list_override) {
2744 struct wim_lookup_table_entry *lte;
2745 INIT_LIST_HEAD(<_stream_list_override);
2746 list_for_each_entry(lte, stream_list_override,
2749 list_add_tail(<e->lookup_table_list,
2750 <_stream_list_override);
2754 /* Write metadata resources and streams. */
2755 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2756 /* Default case: create a normal (non-pipable) WIM. */
2757 ret = write_wim_streams(wim, image, write_flags, num_threads,
2758 progress_func, stream_list_override);
2760 goto out_restore_hdr;
2762 ret = write_wim_metadata_resources(wim, image, write_flags,
2765 goto out_restore_hdr;
2767 /* Non-default case: create pipable WIM. */
2768 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2769 progress_func, stream_list_override);
2771 goto out_restore_hdr;
2772 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2775 if (stream_list_override)
2776 stream_list_override = <_stream_list_override;
2778 /* Write lookup table, XML data, and (optional) integrity table. */
2779 ret = finish_write(wim, image, write_flags, progress_func,
2780 stream_list_override);
2782 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2783 (void)close_wim_writable(wim, write_flags);
2784 DEBUG("ret=%d", ret);
2788 /* Write a standalone WIM to a file or file descriptor. */
2790 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2791 int image, int write_flags, unsigned num_threads,
2792 wimlib_progress_func_t progress_func)
2794 return write_wim_part(wim, path_or_fd, image, write_flags,
2795 num_threads, progress_func, 1, 1, NULL, NULL);
2798 /* API function documented in wimlib.h */
2800 wimlib_write(WIMStruct *wim, const tchar *path,
2801 int image, int write_flags, unsigned num_threads,
2802 wimlib_progress_func_t progress_func)
2805 return WIMLIB_ERR_INVALID_PARAM;
2807 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2809 return write_standalone_wim(wim, path, image, write_flags,
2810 num_threads, progress_func);
2813 /* API function documented in wimlib.h */
2815 wimlib_write_to_fd(WIMStruct *wim, int fd,
2816 int image, int write_flags, unsigned num_threads,
2817 wimlib_progress_func_t progress_func)
2820 return WIMLIB_ERR_INVALID_PARAM;
2822 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2823 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2825 return write_standalone_wim(wim, &fd, image, write_flags,
2826 num_threads, progress_func);
2830 any_images_modified(WIMStruct *wim)
2832 for (int i = 0; i < wim->hdr.image_count; i++)
2833 if (wim->image_metadata[i]->modified)
2839 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2841 const WIMStruct *wim = _wim;
2842 off_t end_offset = *(const off_t*)wim->private;
2844 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2845 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2846 return WIMLIB_ERR_RESOURCE_ORDER;
2850 /* Make sure no file or metadata resources are located after the XML data (or
2851 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2852 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2854 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2859 wim->private = &end_offset;
2860 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2864 for (i = 0; i < wim->hdr.image_count; i++) {
2865 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2873 * Overwrite a WIM, possibly appending streams to it.
2875 * A WIM looks like (or is supposed to look like) the following:
2877 * Header (212 bytes)
2878 * Streams and metadata resources (variable size)
2879 * Lookup table (variable size)
2880 * XML data (variable size)
2881 * Integrity table (optional) (variable size)
2883 * If we are not adding any streams or metadata resources, the lookup table is
2884 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2885 * header. This operation is potentially unsafe if the program is abruptly
2886 * terminated while the XML data or integrity table are being overwritten, but
2887 * before the new header has been written. To partially alleviate this problem,
2888 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2889 * finish_write() to cause a temporary WIM header to be written after the XML
2890 * data has been written. This may prevent the WIM from becoming corrupted if
2891 * the program is terminated while the integrity table is being calculated (but
2892 * no guarantees, due to write re-ordering...).
2894 * If we are adding new streams or images (metadata resources), the lookup table
2895 * needs to be changed, and those streams need to be written. In this case, we
2896 * try to perform a safe update of the WIM file by writing the streams *after*
2897 * the end of the previous WIM, then writing the new lookup table, XML data, and
2898 * (optionally) integrity table following the new streams. This will produce a
2899 * layout like the following:
2901 * Header (212 bytes)
2902 * (OLD) Streams and metadata resources (variable size)
2903 * (OLD) Lookup table (variable size)
2904 * (OLD) XML data (variable size)
2905 * (OLD) Integrity table (optional) (variable size)
2906 * (NEW) Streams and metadata resources (variable size)
2907 * (NEW) Lookup table (variable size)
2908 * (NEW) XML data (variable size)
2909 * (NEW) Integrity table (optional) (variable size)
2911 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2912 * the header is overwritten to point to the new lookup table, XML data, and
2913 * integrity table, to produce the following layout:
2915 * Header (212 bytes)
2916 * Streams and metadata resources (variable size)
2917 * Nothing (variable size)
2918 * More Streams and metadata resources (variable size)
2919 * Lookup table (variable size)
2920 * XML data (variable size)
2921 * Integrity table (optional) (variable size)
2923 * This method allows an image to be appended to a large WIM very quickly, and
2924 * is is crash-safe except in the case of write re-ordering, but the
2925 * disadvantage is that a small hole is left in the WIM where the old lookup
2926 * table, xml data, and integrity table were. (These usually only take up a
2927 * small amount of space compared to the streams, however.)
2930 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2931 unsigned num_threads,
2932 wimlib_progress_func_t progress_func)
2935 struct list_head stream_list;
2937 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2938 struct wim_header hdr_save;
2940 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2942 /* Set default integrity flag. */
2943 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2944 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2945 if (wim_has_integrity_table(wim))
2946 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2948 /* Set additional flags for overwrite. */
2949 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2950 WIMLIB_WRITE_FLAG_STREAMS_OK;
2952 /* Make sure that the integrity table (if present) is after the XML
2953 * data, and that there are no stream resources, metadata resources, or
2954 * lookup tables after the XML data. Otherwise, these data would be
2956 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2957 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2958 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2959 wim->hdr.lookup_table_reshdr.size_in_wim;
2960 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2961 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2962 WARNING("Didn't expect the integrity table to be before the XML data");
2963 return WIMLIB_ERR_RESOURCE_ORDER;
2966 if (old_lookup_table_end > old_xml_begin) {
2967 WARNING("Didn't expect the lookup table to be after the XML data");
2968 return WIMLIB_ERR_RESOURCE_ORDER;
2971 /* Set @old_wim_end, which indicates the point beyond which we don't
2972 * allow any file and metadata resources to appear without returning
2973 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2974 * overwrite these resources). */
2975 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2976 /* If no images have been modified and no images have been
2977 * deleted, a new lookup table does not need to be written. We
2978 * shall write the new XML data and optional integrity table
2979 * immediately after the lookup table. Note that this may
2980 * overwrite an existing integrity table. */
2981 DEBUG("Skipping writing lookup table "
2982 "(no images modified or deleted)");
2983 old_wim_end = old_lookup_table_end;
2984 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2985 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2986 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2987 /* Old WIM has an integrity table; begin writing new streams
2989 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2990 wim->hdr.integrity_table_reshdr.size_in_wim;
2992 /* No existing integrity table; begin writing new streams after
2993 * the old XML data. */
2994 old_wim_end = old_xml_end;
2997 ret = check_resource_offsets(wim, old_wim_end);
3001 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
3006 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3010 ret = lock_wim(wim, wim->out_fd.fd);
3014 /* Save original header so it can be restored in case of error */
3015 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3017 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3018 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3019 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3021 ERROR_WITH_ERRNO("Error updating WIM header flags");
3022 goto out_restore_memory_hdr;
3025 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3026 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3027 ret = WIMLIB_ERR_WRITE;
3028 goto out_restore_physical_hdr;
3031 ret = write_stream_list(&stream_list,
3034 wim->compression_type,
3043 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3044 write_flags, progress_func);
3048 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3049 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3050 progress_func, NULL);
3054 goto out_unlock_wim;
3057 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3058 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3059 wim->filename, old_wim_end);
3060 /* Return value of ftruncate() is ignored because this is
3061 * already an error path. */
3062 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3064 out_restore_physical_hdr:
3065 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3066 out_restore_memory_hdr:
3067 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3069 (void)close_wim_writable(wim, write_flags);
3071 wim->wim_locked = 0;
3076 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3077 unsigned num_threads,
3078 wimlib_progress_func_t progress_func)
3080 size_t wim_name_len;
3083 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3085 /* Write the WIM to a temporary file in the same directory as the
3087 wim_name_len = tstrlen(wim->filename);
3088 tchar tmpfile[wim_name_len + 10];
3089 tmemcpy(tmpfile, wim->filename, wim_name_len);
3090 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3091 tmpfile[wim_name_len + 9] = T('\0');
3093 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3094 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3095 num_threads, progress_func);
3103 /* Rename the new WIM file to the original WIM file. Note: on Windows
3104 * this actually calls win32_rename_replacement(), not _wrename(), so
3105 * that removing the existing destination file can be handled. */
3106 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3107 ret = trename(tmpfile, wim->filename);
3109 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3110 tmpfile, wim->filename);
3117 return WIMLIB_ERR_RENAME;
3120 if (progress_func) {
3121 union wimlib_progress_info progress;
3122 progress.rename.from = tmpfile;
3123 progress.rename.to = wim->filename;
3124 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3129 /* API function documented in wimlib.h */
3131 wimlib_overwrite(WIMStruct *wim, int write_flags,
3132 unsigned num_threads,
3133 wimlib_progress_func_t progress_func)
3138 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3140 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3141 return WIMLIB_ERR_INVALID_PARAM;
3144 return WIMLIB_ERR_NO_FILENAME;
3146 orig_hdr_flags = wim->hdr.flags;
3147 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3148 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3149 ret = can_modify_wim(wim);
3150 wim->hdr.flags = orig_hdr_flags;
3154 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3155 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3156 WIMLIB_WRITE_FLAG_PIPABLE))
3157 && !(wim_is_pipable(wim))
3158 && wim->compression_type == wim->out_compression_type
3159 && wim->chunk_size == wim->out_chunk_size)
3161 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3163 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3165 WARNING("Falling back to re-building entire WIM");
3167 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,