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 return (out_ctype == lte_ctype(lte)
78 && out_chunk_size == lte_cchunk_size(lte)
79 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE);
83 /* Return true if the specified resource must be recompressed when the specified
84 * output parameters are used. */
86 must_compress_stream(const struct wim_lookup_table_entry *lte,
87 int write_resource_flags, int out_ctype, u32 out_chunk_size)
89 return (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
90 && ((write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
91 || !can_raw_copy(lte, write_resource_flags,
92 out_ctype, out_chunk_size)));
96 compress_chunk(const void * uncompressed_data,
97 unsigned uncompressed_len,
98 void *compressed_data,
100 struct wimlib_lzx_context *comp_ctx)
103 case WIMLIB_COMPRESSION_TYPE_XPRESS:
104 return wimlib_xpress_compress(uncompressed_data,
107 case WIMLIB_COMPRESSION_TYPE_LZX:
108 return wimlib_lzx_compress2(uncompressed_data,
118 /* Chunk table that's located at the beginning of each compressed resource in
119 * the WIM. (This is not the on-disk format; the on-disk format just has an
120 * array of offsets.) */
122 u64 original_resource_size;
125 unsigned bytes_per_chunk_entry;
131 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
132 * integers, including the first offset of 0, which will not be written.
134 u8 offsets[] _aligned_attribute(8);
137 /* Allocate and initializes a chunk table, then reserve space for it in the
138 * output file unless writing a pipable resource. */
140 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
141 struct filedes *out_fd,
143 struct chunk_table **chunk_tab_ret,
148 unsigned bytes_per_chunk_entry;
150 struct chunk_table *chunk_tab;
154 num_chunks = DIV_ROUND_UP(size, out_chunk_size);
155 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
156 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
157 chunk_tab = CALLOC(1, alloc_size);
160 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
162 return WIMLIB_ERR_NOMEM;
164 chunk_tab->num_chunks = num_chunks;
165 chunk_tab->original_resource_size = size;
166 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
167 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
169 chunk_tab->cur_offset_p = chunk_tab->offsets;
171 /* We don't know the correct offsets yet; so just write zeroes to
172 * reserve space for the table, so we can go back to it later after
173 * we've written the compressed chunks following it.
175 * Special case: if writing a pipable WIM, compressed resources are in a
176 * modified format (see comment above write_pipable_wim()) and do not
177 * have a chunk table at the beginning, so don't reserve any space for
179 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
180 ret = full_write(out_fd, chunk_tab->offsets,
181 chunk_tab->table_disk_size);
183 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
189 *chunk_tab_ret = chunk_tab;
193 /* Add the offset for the next chunk to the chunk table being constructed for a
194 * compressed stream. */
196 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
198 if (chunk_tab->bytes_per_chunk_entry == 4) {
199 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
200 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
201 chunk_tab->cur_offset_u32 += out_chunk_size;
203 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
204 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
205 chunk_tab->cur_offset_u64 += out_chunk_size;
209 /* Finishes a WIM chunk table and writes it to the output file at the correct
212 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
213 struct filedes *out_fd,
214 off_t res_start_offset,
215 int write_resource_flags)
219 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
220 ret = full_write(out_fd,
222 chunk_tab->bytes_per_chunk_entry,
223 chunk_tab->table_disk_size);
225 ret = full_pwrite(out_fd,
227 chunk_tab->bytes_per_chunk_entry,
228 chunk_tab->table_disk_size,
232 ERROR_WITH_ERRNO("Write error");
236 /* Write the header for a stream in a pipable WIM.
239 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
240 struct filedes *out_fd,
241 int additional_reshdr_flags)
243 struct pwm_stream_hdr stream_hdr;
247 stream_hdr.magic = PWM_STREAM_MAGIC;
248 stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
249 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
250 zero_out_hash(stream_hdr.hash);
252 wimlib_assert(!lte->unhashed);
253 copy_hash(stream_hdr.hash, lte->hash);
256 reshdr_flags = lte->flags & ~WIM_RESHDR_FLAG_COMPRESSED;
257 reshdr_flags |= additional_reshdr_flags;
258 stream_hdr.flags = cpu_to_le32(reshdr_flags);
259 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
261 ERROR_WITH_ERRNO("Error writing stream header");
266 seek_and_truncate(struct filedes *out_fd, off_t offset)
268 if (filedes_seek(out_fd, offset) == -1 ||
269 ftruncate(out_fd->fd, offset))
271 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
272 return WIMLIB_ERR_WRITE;
278 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
280 u8 md[SHA1_HASH_SIZE];
282 sha1_final(md, sha_ctx);
284 copy_hash(lte->hash, md);
285 } else if (!hashes_equal(md, lte->hash)) {
286 ERROR("WIM resource has incorrect hash!");
287 if (lte_filename_valid(lte)) {
288 ERROR("We were reading it from \"%"TS"\"; maybe "
289 "it changed while we were reading it.",
292 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
297 struct write_resource_ctx {
300 struct wimlib_lzx_context *comp_ctx;
301 struct chunk_table *chunk_tab;
302 struct filedes *out_fd;
309 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
311 struct write_resource_ctx *ctx = _ctx;
312 const void *out_chunk;
313 unsigned out_chunk_size;
315 void *compressed_chunk = NULL;
316 unsigned compressed_size;
317 bool compressed_chunk_malloced = false;
320 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
323 out_chunk_size = chunk_size;
324 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
326 /* Compress the chunk. */
327 if (chunk_size <= STACK_MAX) {
328 compressed_chunk = alloca(chunk_size);
330 compressed_chunk = MALLOC(chunk_size);
331 if (compressed_chunk == NULL)
332 return WIMLIB_ERR_NOMEM;
333 compressed_chunk_malloced = true;
336 compressed_size = compress_chunk(chunk, chunk_size,
340 /* Use compressed data if compression to less than input size
342 if (compressed_size) {
343 out_chunk = compressed_chunk;
344 out_chunk_size = compressed_size;
348 if (ctx->chunk_tab) {
349 /* Update chunk table accounting. */
350 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
352 /* If writing compressed chunks to a pipable WIM, before the
353 * chunk data write a chunk header that provides the compressed
355 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
356 struct pwm_chunk_hdr chunk_hdr = {
357 .compressed_size = cpu_to_le32(out_chunk_size),
359 ret = full_write(ctx->out_fd, &chunk_hdr,
366 /* Write the chunk data. */
367 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
372 if (compressed_chunk_malloced)
373 FREE(compressed_chunk);
377 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
378 goto out_free_memory;
382 * write_wim_resource()-
384 * Write a resource to an output WIM.
387 * Lookup table entry for the resource, which could be in another WIM, in
388 * an external file, or in another location.
391 * File descriptor opened to the output WIM.
394 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
395 * compression algorithm to use.
398 * Compressed chunk size to use.
401 * On success, this is filled in with the offset, flags, compressed size,
402 * and uncompressed size of the resource in the output WIM.
405 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
406 * if it could otherwise be copied directly from the input;
407 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
408 * (and the output file descriptor may be a pipe).
411 * Location of LZX compression context pointer, which will be allocated or
412 * updated if needed. (Initialize to NULL.)
414 * Additional notes: The SHA1 message digest of the uncompressed data is
415 * calculated (except when doing a raw copy --- see below). If the @unhashed
416 * flag is set on the lookup table entry, this message digest is simply copied
417 * to it; otherwise, the message digest is compared with the existing one, and
418 * this function will fail if they do not match.
421 write_wim_resource(struct wim_lookup_table_entry *lte,
422 struct filedes *out_fd, int out_ctype,
424 struct wim_reshdr *out_reshdr,
426 struct wimlib_lzx_context **comp_ctx)
428 struct write_resource_ctx write_ctx;
429 off_t res_start_offset;
434 /* Mask out any irrelevant flags, since this function also uses this
435 * variable to store WIMLIB_READ_RESOURCE flags. */
436 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
438 /* Get current position in output WIM. */
439 res_start_offset = out_fd->offset;
441 /* If we are not forcing the data to be recompressed, and the input
442 * resource is located in a WIM with a compression mode compatible with
443 * the output, we can simply copy the compressed data without
444 * recompressing it. This also means we must skip calculating the SHA1,
445 * as we never will see the uncompressed data. */
446 if (can_raw_copy(lte, resource_flags, out_ctype, out_chunk_size)) {
447 /* Normally, for raw copies we can request a RAW_FULL read, but
448 * if we're reading from a pipable resource and writing a
449 * non-pipable resource or vice versa, then a RAW_CHUNKS read
450 * needs to be requested so that the written resource can be
451 * appropriately formatted. However, in neither case is any
452 * actual decompression needed. */
453 if (lte->rspec->is_pipable == !!(resource_flags &
454 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
456 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
457 read_size = lte->rspec->size_in_wim;
459 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
460 read_size = lte->size;
462 write_ctx.doing_sha = false;
464 write_ctx.doing_sha = true;
465 sha1_init(&write_ctx.sha_ctx);
466 read_size = lte->size;
469 /* Set the output compression mode and initialize chunk table if needed.
471 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
472 write_ctx.out_chunk_size = out_chunk_size;
473 write_ctx.chunk_tab = NULL;
474 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
475 wimlib_assert(out_chunk_size > 0);
476 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
477 /* Compression needed. */
478 write_ctx.out_ctype = out_ctype;
479 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
480 ret = wimlib_lzx_alloc_context(out_chunk_size,
485 write_ctx.comp_ctx = *comp_ctx;
487 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
488 /* Chunk table needed. */
489 ret = begin_wim_resource_chunk_tab(lte, out_fd,
491 &write_ctx.chunk_tab,
498 /* If writing a pipable resource, write the stream header and update
499 * @res_start_offset to be the end of the stream header. */
500 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
501 int reshdr_flags = 0;
502 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
503 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
504 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
506 goto out_free_chunk_tab;
507 res_start_offset = out_fd->offset;
510 /* Write the entire resource by reading the entire resource and feeding
511 * the data through write_resource_cb(). */
512 write_ctx.out_fd = out_fd;
513 write_ctx.resource_flags = resource_flags;
515 if (write_ctx.out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
516 in_chunk_size = lte_cchunk_size(lte);
518 in_chunk_size = out_chunk_size;
519 ret = read_resource_prefix(lte, read_size,
521 in_chunk_size, &write_ctx, resource_flags);
523 goto out_free_chunk_tab;
525 /* Verify SHA1 message digest of the resource, or set the hash for the
527 if (write_ctx.doing_sha) {
528 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
530 goto out_free_chunk_tab;
533 /* Write chunk table if needed. */
534 if (write_ctx.chunk_tab) {
535 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
540 goto out_free_chunk_tab;
543 /* Fill in out_reshdr with information about the newly written
545 out_reshdr->size_in_wim = out_fd->offset - res_start_offset;
546 out_reshdr->flags = lte->flags;
547 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
548 out_reshdr->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
550 out_reshdr->flags |= WIM_RESHDR_FLAG_COMPRESSED;
551 out_reshdr->offset_in_wim = res_start_offset;
552 out_reshdr->uncompressed_size = lte->size;
554 /* Check for resources compressed to greater than their original size
555 * and write them uncompressed instead. (But never do this if writing
556 * to a pipe, and don't bother if we did a raw copy.) */
557 if (out_reshdr->size_in_wim > out_reshdr->uncompressed_size &&
558 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
559 WIMLIB_READ_RESOURCE_FLAG_RAW)))
561 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
562 "writing uncompressed instead",
563 out_reshdr->uncompressed_size, out_reshdr->size_in_wim);
564 ret = seek_and_truncate(out_fd, res_start_offset);
566 goto out_free_chunk_tab;
567 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
568 FREE(write_ctx.chunk_tab);
569 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
570 write_ctx.chunk_tab = NULL;
571 write_ctx.doing_sha = false;
572 goto try_write_again;
574 if (resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW) {
575 DEBUG("Copied raw compressed data "
576 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
577 out_reshdr->uncompressed_size, out_reshdr->size_in_wim,
578 out_reshdr->offset_in_wim, out_reshdr->flags);
579 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
580 DEBUG("Wrote compressed resource "
581 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
582 out_reshdr->uncompressed_size, out_reshdr->size_in_wim,
583 out_reshdr->offset_in_wim, out_reshdr->flags);
585 DEBUG("Wrote uncompressed resource "
586 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
587 out_reshdr->uncompressed_size,
588 out_reshdr->offset_in_wim, out_reshdr->flags);
592 FREE(write_ctx.chunk_tab);
597 /* Like write_wim_resource(), but the resource is specified by a buffer of
598 * uncompressed data rather a lookup table entry. Also writes the SHA1 message
599 * digest of the buffer to @hash_ret if it is non-NULL. */
601 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
602 int reshdr_flags, struct filedes *out_fd,
605 struct wim_reshdr *out_reshdr,
606 u8 *hash_ret, int write_resource_flags,
607 struct wimlib_lzx_context **comp_ctx)
610 struct wim_lookup_table_entry *lte;
612 /* Set up a temporary lookup table entry to provide to
613 * write_wim_resource(). */
615 lte = new_lookup_table_entry();
617 return WIMLIB_ERR_NOMEM;
619 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
620 lte->attached_buffer = (void*)buf;
621 lte->size = buf_size;
622 lte->flags = reshdr_flags;
624 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
625 sha1_buffer(buf, buf_size, lte->hash);
631 ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
632 out_reshdr, write_resource_flags, comp_ctx);
636 copy_hash(hash_ret, lte->hash);
639 lte->resource_location = RESOURCE_NONEXISTENT;
640 free_lookup_table_entry(lte);
645 #ifdef ENABLE_MULTITHREADED_COMPRESSION
647 /* Blocking shared queue (solves the producer-consumer problem) */
648 struct shared_queue {
652 unsigned filled_slots;
654 pthread_mutex_t lock;
655 pthread_cond_t msg_avail_cond;
656 pthread_cond_t space_avail_cond;
660 shared_queue_init(struct shared_queue *q, unsigned size)
662 wimlib_assert(size != 0);
663 q->array = CALLOC(sizeof(q->array[0]), size);
670 if (pthread_mutex_init(&q->lock, NULL)) {
671 ERROR_WITH_ERRNO("Failed to initialize mutex");
674 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
675 ERROR_WITH_ERRNO("Failed to initialize condition variable");
676 goto err_destroy_lock;
678 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
679 ERROR_WITH_ERRNO("Failed to initialize condition variable");
680 goto err_destroy_msg_avail_cond;
683 err_destroy_msg_avail_cond:
684 pthread_cond_destroy(&q->msg_avail_cond);
686 pthread_mutex_destroy(&q->lock);
688 return WIMLIB_ERR_NOMEM;
692 shared_queue_destroy(struct shared_queue *q)
695 pthread_mutex_destroy(&q->lock);
696 pthread_cond_destroy(&q->msg_avail_cond);
697 pthread_cond_destroy(&q->space_avail_cond);
701 shared_queue_put(struct shared_queue *q, void *obj)
703 pthread_mutex_lock(&q->lock);
704 while (q->filled_slots == q->size)
705 pthread_cond_wait(&q->space_avail_cond, &q->lock);
707 q->back = (q->back + 1) % q->size;
708 q->array[q->back] = obj;
711 pthread_cond_broadcast(&q->msg_avail_cond);
712 pthread_mutex_unlock(&q->lock);
716 shared_queue_get(struct shared_queue *q)
720 pthread_mutex_lock(&q->lock);
721 while (q->filled_slots == 0)
722 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
724 obj = q->array[q->front];
725 q->array[q->front] = NULL;
726 q->front = (q->front + 1) % q->size;
729 pthread_cond_broadcast(&q->space_avail_cond);
730 pthread_mutex_unlock(&q->lock);
734 struct compressor_thread_params {
735 struct shared_queue *res_to_compress_queue;
736 struct shared_queue *compressed_res_queue;
738 struct wimlib_lzx_context *comp_ctx;
741 #define MAX_CHUNKS_PER_MSG 2
744 struct wim_lookup_table_entry *lte;
746 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
747 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
748 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
749 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
751 struct list_head list;
757 compress_chunks(struct message *msg, int out_ctype,
758 struct wimlib_lzx_context *comp_ctx)
760 for (unsigned i = 0; i < msg->num_chunks; i++) {
763 len = compress_chunk(msg->uncompressed_chunks[i],
764 msg->uncompressed_chunk_sizes[i],
765 msg->compressed_chunks[i],
772 /* To be written compressed */
773 out_chunk = msg->compressed_chunks[i];
776 /* To be written uncompressed */
777 out_chunk = msg->uncompressed_chunks[i];
778 out_len = msg->uncompressed_chunk_sizes[i];
780 msg->out_chunks[i].iov_base = out_chunk;
781 msg->out_chunks[i].iov_len = out_len;
785 /* Compressor thread routine. This is a lot simpler than the main thread
786 * routine: just repeatedly get a group of chunks from the
787 * res_to_compress_queue, compress them, and put them in the
788 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
791 compressor_thread_proc(void *arg)
793 struct compressor_thread_params *params = arg;
794 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
795 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
798 DEBUG("Compressor thread ready");
799 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
800 compress_chunks(msg, params->out_ctype, params->comp_ctx);
801 shared_queue_put(compressed_res_queue, msg);
803 DEBUG("Compressor thread terminating");
806 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
808 struct write_streams_progress_data {
809 wimlib_progress_func_t progress_func;
810 union wimlib_progress_info progress;
811 uint64_t next_progress;
812 WIMStruct *prev_wim_part;
816 do_write_streams_progress(struct write_streams_progress_data *progress_data,
817 struct wim_lookup_table_entry *lte,
818 bool stream_discarded)
820 union wimlib_progress_info *progress = &progress_data->progress;
823 if (stream_discarded) {
824 progress->write_streams.total_bytes -= lte->size;
825 if (progress_data->next_progress != ~(uint64_t)0 &&
826 progress_data->next_progress > progress->write_streams.total_bytes)
828 progress_data->next_progress = progress->write_streams.total_bytes;
831 progress->write_streams.completed_bytes += lte->size;
833 new_wim_part = false;
834 if (lte->resource_location == RESOURCE_IN_WIM &&
835 lte->rspec->wim != progress_data->prev_wim_part)
837 if (progress_data->prev_wim_part) {
839 progress->write_streams.completed_parts++;
841 progress_data->prev_wim_part = lte->rspec->wim;
843 progress->write_streams.completed_streams++;
844 if (progress_data->progress_func
845 && (progress->write_streams.completed_bytes >= progress_data->next_progress
848 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
850 if (progress_data->next_progress == progress->write_streams.total_bytes) {
851 progress_data->next_progress = ~(uint64_t)0;
853 progress_data->next_progress =
854 min(progress->write_streams.total_bytes,
855 progress->write_streams.completed_bytes +
856 progress->write_streams.total_bytes / 100);
861 struct serial_write_stream_ctx {
862 struct filedes *out_fd;
865 struct wimlib_lzx_context **comp_ctx;
866 int write_resource_flags;
870 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
872 struct serial_write_stream_ctx *ctx = _ctx;
873 return write_wim_resource(lte, ctx->out_fd,
877 ctx->write_resource_flags,
882 /* Write a list of streams, taking into account that some streams may be
883 * duplicates that are checksummed and discarded on the fly, and also delegating
884 * the actual writing of a stream to a function @write_stream_cb, which is
885 * passed the context @write_stream_ctx. */
887 do_write_stream_list(struct list_head *stream_list,
888 struct wim_lookup_table *lookup_table,
889 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
890 void *write_stream_ctx,
891 struct write_streams_progress_data *progress_data)
894 struct wim_lookup_table_entry *lte;
895 bool stream_discarded;
897 /* For each stream in @stream_list ... */
898 while (!list_empty(stream_list)) {
899 stream_discarded = false;
900 lte = container_of(stream_list->next,
901 struct wim_lookup_table_entry,
903 list_del(<e->write_streams_list);
904 if (lte->unhashed && !lte->unique_size) {
905 /* Unhashed stream that shares a size with some other
906 * stream in the WIM we are writing. The stream must be
907 * checksummed to know if we need to write it or not. */
908 struct wim_lookup_table_entry *tmp;
909 u32 orig_out_refcnt = lte->out_refcnt;
911 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
915 /* We found a duplicate stream. 'lte' was
916 * freed, so replace it with the duplicate. */
919 /* 'out_refcnt' was transferred to the
920 * duplicate, and we can detect if the duplicate
921 * stream was already referenced for writing by
922 * checking if its 'out_refcnt' is higher than
923 * that of the original stream. In such cases,
924 * the current stream can be discarded. We can
925 * also discard the current stream if it was
926 * previously marked as filtered (e.g. already
927 * present in the WIM being written). */
928 if (lte->out_refcnt > orig_out_refcnt ||
930 DEBUG("Discarding duplicate stream of "
933 lte->no_progress = 0;
934 stream_discarded = true;
935 goto skip_to_progress;
940 /* Here, @lte is either a hashed stream or an unhashed stream
941 * with a unique size. In either case we know that the stream
942 * has to be written. In either case the SHA1 message digest
943 * will be calculated over the stream while writing it; however,
944 * in the former case this is done merely to check the data,
945 * while in the latter case this is done because we do not have
946 * the SHA1 message digest yet. */
947 wimlib_assert(lte->out_refcnt != 0);
949 lte->no_progress = 0;
950 ret = (*write_stream_cb)(lte, write_stream_ctx);
953 /* In parallel mode, some streams are deferred for later,
954 * serialized processing; ignore them here. */
958 list_del(<e->unhashed_list);
959 lookup_table_insert(lookup_table, lte);
963 if (!lte->no_progress) {
964 do_write_streams_progress(progress_data,
965 lte, stream_discarded);
972 do_write_stream_list_serial(struct list_head *stream_list,
973 struct wim_lookup_table *lookup_table,
974 struct filedes *out_fd,
977 struct wimlib_lzx_context **comp_ctx,
978 int write_resource_flags,
979 struct write_streams_progress_data *progress_data)
981 struct serial_write_stream_ctx ctx = {
983 .out_ctype = out_ctype,
984 .out_chunk_size = out_chunk_size,
985 .write_resource_flags = write_resource_flags,
986 .comp_ctx = comp_ctx,
988 return do_write_stream_list(stream_list,
996 write_flags_to_resource_flags(int write_flags)
998 int resource_flags = 0;
1000 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
1001 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
1002 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
1003 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
1004 return resource_flags;
1008 write_stream_list_serial(struct list_head *stream_list,
1009 struct wim_lookup_table *lookup_table,
1010 struct filedes *out_fd,
1013 struct wimlib_lzx_context **comp_ctx,
1014 int write_resource_flags,
1015 struct write_streams_progress_data *progress_data)
1017 union wimlib_progress_info *progress = &progress_data->progress;
1018 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
1019 progress->write_streams.total_streams);
1020 progress->write_streams.num_threads = 1;
1021 if (progress_data->progress_func) {
1022 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1025 return do_write_stream_list_serial(stream_list,
1031 write_resource_flags,
1035 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1037 write_wim_chunks(struct message *msg, struct filedes *out_fd,
1038 struct chunk_table *chunk_tab,
1039 int write_resource_flags)
1042 struct pwm_chunk_hdr *chunk_hdrs;
1046 for (unsigned i = 0; i < msg->num_chunks; i++)
1047 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1049 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1050 nvecs = msg->num_chunks;
1051 vecs = msg->out_chunks;
1053 /* Special case: If writing a compressed resource to a pipable
1054 * WIM, prefix each compressed chunk with a header that gives
1055 * its compressed size. */
1056 nvecs = msg->num_chunks * 2;
1057 vecs = alloca(nvecs * sizeof(vecs[0]));
1058 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1060 for (unsigned i = 0; i < msg->num_chunks; i++) {
1061 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1062 vecs[i * 2].iov_base = &chunk_hdrs[i];
1063 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1064 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1065 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1068 ret = full_writev(out_fd, vecs, nvecs);
1070 ERROR_WITH_ERRNO("Write error");
1074 struct main_writer_thread_ctx {
1075 struct list_head *stream_list;
1076 struct wim_lookup_table *lookup_table;
1077 struct filedes *out_fd;
1078 off_t res_start_offset;
1081 struct wimlib_lzx_context **comp_ctx;
1082 int write_resource_flags;
1083 struct shared_queue *res_to_compress_queue;
1084 struct shared_queue *compressed_res_queue;
1085 size_t num_messages;
1086 struct write_streams_progress_data *progress_data;
1088 struct list_head available_msgs;
1089 struct list_head outstanding_streams;
1090 struct list_head serial_streams;
1091 size_t num_outstanding_messages;
1093 SHA_CTX next_sha_ctx;
1095 u64 next_num_chunks;
1096 struct wim_lookup_table_entry *next_lte;
1098 struct message *msgs;
1099 struct message *next_msg;
1100 struct chunk_table *cur_chunk_tab;
1104 init_message(struct message *msg, u32 out_chunk_size)
1106 msg->out_chunk_size = out_chunk_size;
1107 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1108 msg->compressed_chunks[i] = MALLOC(out_chunk_size);
1109 msg->uncompressed_chunks[i] = MALLOC(out_chunk_size);
1110 if (msg->compressed_chunks[i] == NULL ||
1111 msg->uncompressed_chunks[i] == NULL)
1112 return WIMLIB_ERR_NOMEM;
1118 destroy_message(struct message *msg)
1120 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1121 FREE(msg->compressed_chunks[i]);
1122 FREE(msg->uncompressed_chunks[i]);
1127 free_messages(struct message *msgs, size_t num_messages)
1130 for (size_t i = 0; i < num_messages; i++)
1131 destroy_message(&msgs[i]);
1136 static struct message *
1137 allocate_messages(size_t num_messages, u32 out_chunk_size)
1139 struct message *msgs;
1141 msgs = CALLOC(num_messages, sizeof(struct message));
1144 for (size_t i = 0; i < num_messages; i++) {
1145 if (init_message(&msgs[i], out_chunk_size)) {
1146 free_messages(msgs, num_messages);
1154 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1156 while (ctx->num_outstanding_messages--)
1157 shared_queue_get(ctx->compressed_res_queue);
1158 free_messages(ctx->msgs, ctx->num_messages);
1159 FREE(ctx->cur_chunk_tab);
1163 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1165 /* Pre-allocate all the buffers that will be needed to do the chunk
1167 ctx->msgs = allocate_messages(ctx->num_messages, ctx->out_chunk_size);
1168 if (ctx->msgs == NULL)
1169 return WIMLIB_ERR_NOMEM;
1171 /* Initially, all the messages are available to use. */
1172 INIT_LIST_HEAD(&ctx->available_msgs);
1173 for (size_t i = 0; i < ctx->num_messages; i++)
1174 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1176 /* outstanding_streams is the list of streams that currently have had
1177 * chunks sent off for compression.
1179 * The first stream in outstanding_streams is the stream that is
1180 * currently being written.
1182 * The last stream in outstanding_streams is the stream that is
1183 * currently being read and having chunks fed to the compressor threads.
1185 INIT_LIST_HEAD(&ctx->outstanding_streams);
1186 ctx->num_outstanding_messages = 0;
1188 /* Message currently being prepared. */
1189 ctx->next_msg = NULL;
1191 /* Resources that don't need any chunks compressed are added to this
1192 * list and written directly by the main thread. */
1193 INIT_LIST_HEAD(&ctx->serial_streams);
1195 /* Pointer to chunk table for stream currently being written. */
1196 ctx->cur_chunk_tab = NULL;
1202 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1204 struct message *msg;
1205 struct wim_lookup_table_entry *cur_lte;
1208 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1209 wimlib_assert(ctx->num_outstanding_messages != 0);
1211 cur_lte = container_of(ctx->outstanding_streams.next,
1212 struct wim_lookup_table_entry,
1213 being_compressed_list);
1215 /* Get the next message from the queue and process it.
1216 * The message will contain 1 or more data chunks that have been
1218 msg = shared_queue_get(ctx->compressed_res_queue);
1219 msg->complete = true;
1220 --ctx->num_outstanding_messages;
1222 /* Is this the next chunk in the current resource? If it's not (i.e.,
1223 * an earlier chunk in a same or different resource hasn't been
1224 * compressed yet), do nothing, and keep this message around until all
1225 * earlier chunks are received.
1227 * Otherwise, write all the chunks we can. */
1228 while (cur_lte != NULL &&
1229 !list_empty(&cur_lte->msg_list)
1230 && (msg = container_of(cur_lte->msg_list.next,
1234 list_move(&msg->list, &ctx->available_msgs);
1235 if (msg->begin_chunk == 0) {
1236 /* First set of chunks. */
1238 /* Write pipable WIM stream header if needed. */
1239 if (ctx->write_resource_flags &
1240 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1242 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1243 WIM_RESHDR_FLAG_COMPRESSED);
1248 /* Save current offset. */
1249 ctx->res_start_offset = ctx->out_fd->offset;
1251 /* Begin building the chunk table, and leave space for
1253 ret = begin_wim_resource_chunk_tab(cur_lte,
1255 ctx->out_chunk_size,
1256 &ctx->cur_chunk_tab,
1257 ctx->write_resource_flags);
1262 /* Write the compressed chunks from the message. */
1263 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1264 ctx->write_resource_flags);
1268 /* Was this the last chunk of the stream? If so, finish the
1269 * stream by writing the chunk table. */
1270 if (list_empty(&cur_lte->msg_list) &&
1271 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1275 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1277 ctx->res_start_offset,
1278 ctx->write_resource_flags);
1282 list_del(&cur_lte->being_compressed_list);
1284 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1286 FREE(ctx->cur_chunk_tab);
1287 ctx->cur_chunk_tab = NULL;
1289 /* Check for resources compressed to greater than or
1290 * equal to their original size and write them
1291 * uncompressed instead. (But never do this if writing
1293 if (res_csize >= cur_lte->size &&
1294 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1296 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1297 "writing uncompressed instead",
1298 cur_lte->size, res_csize);
1299 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1302 ret = write_wim_resource(cur_lte,
1304 WIMLIB_COMPRESSION_TYPE_NONE,
1306 &cur_lte->out_reshdr,
1307 ctx->write_resource_flags,
1312 cur_lte->out_reshdr.size_in_wim =
1315 cur_lte->out_reshdr.uncompressed_size =
1318 cur_lte->out_reshdr.offset_in_wim =
1319 ctx->res_start_offset;
1321 cur_lte->out_reshdr.flags =
1323 WIM_RESHDR_FLAG_COMPRESSED;
1325 DEBUG("Wrote compressed resource "
1326 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1327 cur_lte->out_reshdr.uncompressed_size,
1328 cur_lte->out_reshdr.size_in_wim,
1329 cur_lte->out_reshdr.offset_in_wim,
1330 cur_lte->out_reshdr.flags);
1333 do_write_streams_progress(ctx->progress_data,
1336 /* Since we just finished writing a stream, write any
1337 * streams that have been added to the serial_streams
1338 * list for direct writing by the main thread (e.g.
1339 * resources that don't need to be compressed because
1340 * the desired compression type is the same as the
1341 * previous compression type). */
1342 if (!list_empty(&ctx->serial_streams)) {
1343 ret = do_write_stream_list_serial(&ctx->serial_streams,
1347 ctx->out_chunk_size,
1349 ctx->write_resource_flags,
1350 ctx->progress_data);
1355 /* Advance to the next stream to write. */
1356 if (list_empty(&ctx->outstanding_streams)) {
1359 cur_lte = container_of(ctx->outstanding_streams.next,
1360 struct wim_lookup_table_entry,
1361 being_compressed_list);
1368 /* Called when the main thread has read a new chunk of data. */
1370 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1372 struct main_writer_thread_ctx *ctx = _ctx;
1374 struct message *next_msg;
1375 u64 next_chunk_in_msg;
1377 /* Update SHA1 message digest for the stream currently being read by the
1379 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1381 /* We send chunks of data to the compressor chunks in batches which we
1382 * refer to as "messages". @next_msg is the message that is currently
1383 * being prepared to send off. If it is NULL, that indicates that we
1384 * need to start a new message. */
1385 next_msg = ctx->next_msg;
1387 /* We need to start a new message. First check to see if there
1388 * is a message available in the list of available messages. If
1389 * so, we can just take one. If not, all the messages (there is
1390 * a fixed number of them, proportional to the number of
1391 * threads) have been sent off to the compressor threads, so we
1392 * receive messages from the compressor threads containing
1393 * compressed chunks of data.
1395 * We may need to receive multiple messages before one is
1396 * actually available to use because messages received that are
1397 * *not* for the very next set of chunks to compress must be
1398 * buffered until it's time to write those chunks. */
1399 while (list_empty(&ctx->available_msgs)) {
1400 ret = receive_compressed_chunks(ctx);
1405 next_msg = container_of(ctx->available_msgs.next,
1406 struct message, list);
1407 list_del(&next_msg->list);
1408 next_msg->complete = false;
1409 next_msg->begin_chunk = ctx->next_chunk;
1410 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1411 ctx->next_num_chunks - ctx->next_chunk);
1412 ctx->next_msg = next_msg;
1415 /* Fill in the next chunk to compress */
1416 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1418 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1419 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1422 if (++next_chunk_in_msg == next_msg->num_chunks) {
1423 /* Send off an array of chunks to compress */
1424 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1425 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1426 ++ctx->num_outstanding_messages;
1427 ctx->next_msg = NULL;
1433 main_writer_thread_finish(void *_ctx)
1435 struct main_writer_thread_ctx *ctx = _ctx;
1437 while (ctx->num_outstanding_messages != 0) {
1438 ret = receive_compressed_chunks(ctx);
1442 wimlib_assert(list_empty(&ctx->outstanding_streams));
1443 return do_write_stream_list_serial(&ctx->serial_streams,
1447 ctx->out_chunk_size,
1449 ctx->write_resource_flags,
1450 ctx->progress_data);
1454 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1455 struct main_writer_thread_ctx *ctx)
1459 /* Read the entire stream @lte, feeding its data chunks to the
1460 * compressor threads. Also SHA1-sum the stream; this is required in
1461 * the case that @lte is unhashed, and a nice additional verification
1462 * when @lte is already hashed. */
1463 sha1_init(&ctx->next_sha_ctx);
1464 ctx->next_chunk = 0;
1465 ctx->next_num_chunks = DIV_ROUND_UP(lte->size, ctx->out_chunk_size);
1466 ctx->next_lte = lte;
1467 INIT_LIST_HEAD(<e->msg_list);
1468 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1469 ret = read_resource_prefix(lte, lte->size,
1470 main_writer_thread_cb,
1471 ctx->out_chunk_size, ctx, 0);
1474 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1475 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1479 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1481 struct main_writer_thread_ctx *ctx = _ctx;
1484 if (lte->size < 1000 ||
1485 !must_compress_stream(lte, ctx->write_resource_flags,
1486 ctx->out_ctype, ctx->out_chunk_size))
1488 /* Stream is too small or isn't being compressed. Process it by
1489 * the main thread when we have a chance. We can't necessarily
1490 * process it right here, as the main thread could be in the
1491 * middle of writing a different stream. */
1492 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1496 ret = submit_stream_for_compression(lte, ctx);
1498 lte->no_progress = 1;
1503 get_default_num_threads(void)
1506 return win32_get_number_of_processors();
1508 return sysconf(_SC_NPROCESSORS_ONLN);
1512 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1513 * parameter and will perform compression using that many threads. Falls
1514 * back to write_stream_list_serial() on certain errors, such as a failure to
1515 * create the number of threads requested.
1517 * High level description of the algorithm for writing compressed streams in
1518 * parallel: We perform compression on chunks rather than on full files. The
1519 * currently executing thread becomes the main thread and is entirely in charge
1520 * of reading the data to compress (which may be in any location understood by
1521 * the resource code--- such as in an external file being captured, or in
1522 * another WIM file from which an image is being exported) and actually writing
1523 * the compressed data to the output file. Additional threads are "compressor
1524 * threads" and all execute the compressor_thread_proc, where they repeatedly
1525 * retrieve buffers of data from the main thread, compress them, and hand them
1526 * back to the main thread.
1528 * Certain streams, such as streams that do not need to be compressed (e.g.
1529 * input compression type same as output compression type) or streams of very
1530 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1531 * handled entirely by the main thread at an appropriate time.
1533 * At any given point in time, multiple streams may be having chunks compressed
1534 * concurrently. The stream that the main thread is currently *reading* may be
1535 * later in the list that the stream that the main thread is currently
1538 write_stream_list_parallel(struct list_head *stream_list,
1539 struct wim_lookup_table *lookup_table,
1540 struct filedes *out_fd,
1543 struct wimlib_lzx_context **comp_ctx,
1544 int write_resource_flags,
1545 struct write_streams_progress_data *progress_data,
1546 unsigned num_threads)
1549 struct shared_queue res_to_compress_queue;
1550 struct shared_queue compressed_res_queue;
1551 pthread_t *compressor_threads = NULL;
1552 union wimlib_progress_info *progress = &progress_data->progress;
1553 unsigned num_started_threads;
1554 bool can_retry = true;
1556 if (num_threads == 0) {
1557 long nthreads = get_default_num_threads();
1558 if (nthreads < 1 || nthreads > UINT_MAX) {
1559 WARNING("Could not determine number of processors! Assuming 1");
1560 goto out_serial_quiet;
1561 } else if (nthreads == 1) {
1562 goto out_serial_quiet;
1564 num_threads = nthreads;
1568 DEBUG("Writing stream list of size %"PRIu64" "
1569 "(parallel version, num_threads=%u)",
1570 progress->write_streams.total_streams, num_threads);
1572 progress->write_streams.num_threads = num_threads;
1574 static const size_t MESSAGES_PER_THREAD = 2;
1575 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1577 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1579 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1583 ret = shared_queue_init(&compressed_res_queue, queue_size);
1585 goto out_destroy_res_to_compress_queue;
1587 struct compressor_thread_params *params;
1589 params = CALLOC(num_threads, sizeof(params[0]));
1590 if (params == NULL) {
1591 ret = WIMLIB_ERR_NOMEM;
1592 goto out_destroy_compressed_res_queue;
1595 for (unsigned i = 0; i < num_threads; i++) {
1596 params[i].res_to_compress_queue = &res_to_compress_queue;
1597 params[i].compressed_res_queue = &compressed_res_queue;
1598 params[i].out_ctype = out_ctype;
1599 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1600 ret = wimlib_lzx_alloc_context(out_chunk_size,
1601 NULL, ¶ms[i].comp_ctx);
1603 goto out_free_params;
1607 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1608 if (compressor_threads == NULL) {
1609 ret = WIMLIB_ERR_NOMEM;
1610 goto out_free_params;
1613 for (unsigned i = 0; i < num_threads; i++) {
1614 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1615 ret = pthread_create(&compressor_threads[i], NULL,
1616 compressor_thread_proc, ¶ms[i]);
1620 ERROR_WITH_ERRNO("Failed to create compressor "
1622 i + 1, num_threads);
1623 num_started_threads = i;
1627 num_started_threads = num_threads;
1629 if (progress_data->progress_func) {
1630 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1634 struct main_writer_thread_ctx ctx;
1636 memset(&ctx, 0, sizeof(ctx));
1638 ctx.stream_list = stream_list;
1639 ctx.lookup_table = lookup_table;
1640 ctx.out_fd = out_fd;
1641 ctx.out_ctype = out_ctype;
1642 ctx.out_chunk_size = out_chunk_size;
1643 ctx.comp_ctx = comp_ctx;
1644 ctx.res_to_compress_queue = &res_to_compress_queue;
1645 ctx.compressed_res_queue = &compressed_res_queue;
1646 ctx.num_messages = queue_size;
1647 ctx.write_resource_flags = write_resource_flags;
1648 ctx.progress_data = progress_data;
1649 ret = main_writer_thread_init_ctx(&ctx);
1654 ret = do_write_stream_list(stream_list, lookup_table,
1655 main_thread_process_next_stream,
1656 &ctx, progress_data);
1658 goto out_destroy_ctx;
1660 /* The main thread has finished reading all streams that are going to be
1661 * compressed in parallel, and it now needs to wait for all remaining
1662 * chunks to be compressed so that the remaining streams can actually be
1663 * written to the output file. Furthermore, any remaining streams that
1664 * had processing deferred to the main thread need to be handled. These
1665 * tasks are done by the main_writer_thread_finish() function. */
1666 ret = main_writer_thread_finish(&ctx);
1668 main_writer_thread_destroy_ctx(&ctx);
1670 for (unsigned i = 0; i < num_started_threads; i++)
1671 shared_queue_put(&res_to_compress_queue, NULL);
1673 for (unsigned i = 0; i < num_started_threads; i++) {
1674 if (pthread_join(compressor_threads[i], NULL)) {
1675 WARNING_WITH_ERRNO("Failed to join compressor "
1677 i + 1, num_threads);
1680 FREE(compressor_threads);
1682 for (unsigned i = 0; i < num_threads; i++)
1683 wimlib_lzx_free_context(params[i].comp_ctx);
1685 out_destroy_compressed_res_queue:
1686 shared_queue_destroy(&compressed_res_queue);
1687 out_destroy_res_to_compress_queue:
1688 shared_queue_destroy(&res_to_compress_queue);
1689 if (!can_retry || (ret >= 0 && ret != WIMLIB_ERR_NOMEM))
1692 WARNING("Falling back to single-threaded compression");
1694 return write_stream_list_serial(stream_list,
1700 write_resource_flags,
1706 /* Write a list of streams to a WIM (@out_fd) using the compression type
1707 * @out_ctype, chunk size @out_chunk_size, and up to @num_threads compressor
1710 write_stream_list(struct list_head *stream_list,
1711 struct wim_lookup_table *lookup_table,
1712 struct filedes *out_fd, int out_ctype,
1714 struct wimlib_lzx_context **comp_ctx,
1716 unsigned num_threads, wimlib_progress_func_t progress_func)
1719 int write_resource_flags;
1721 u64 total_compression_bytes;
1722 unsigned total_parts;
1723 WIMStruct *prev_wim_part;
1725 struct wim_lookup_table_entry *lte;
1726 struct write_streams_progress_data progress_data;
1728 if (list_empty(stream_list)) {
1729 DEBUG("No streams to write.");
1733 write_resource_flags = write_flags_to_resource_flags(write_flags);
1735 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1736 out_fd->offset, write_resource_flags);
1738 /* Sort the stream list into a good order for reading. */
1739 ret = sort_stream_list_by_sequential_order(stream_list,
1740 offsetof(struct wim_lookup_table_entry,
1741 write_streams_list));
1745 /* Calculate the total size of the streams to be written. Note: this
1746 * will be the uncompressed size, as we may not know the compressed size
1747 * yet, and also this will assume that every unhashed stream will be
1748 * written (which will not necessarily be the case). */
1750 total_compression_bytes = 0;
1753 prev_wim_part = NULL;
1754 list_for_each_entry(lte, stream_list, write_streams_list) {
1756 total_bytes += lte->size;
1757 if (must_compress_stream(lte, write_resource_flags,
1758 out_ctype, out_chunk_size))
1759 total_compression_bytes += lte->size;
1760 if (lte->resource_location == RESOURCE_IN_WIM) {
1761 if (prev_wim_part != lte->rspec->wim) {
1762 prev_wim_part = lte->rspec->wim;
1768 memset(&progress_data, 0, sizeof(progress_data));
1769 progress_data.progress_func = progress_func;
1771 progress_data.progress.write_streams.total_bytes = total_bytes;
1772 progress_data.progress.write_streams.total_streams = num_streams;
1773 progress_data.progress.write_streams.completed_bytes = 0;
1774 progress_data.progress.write_streams.completed_streams = 0;
1775 progress_data.progress.write_streams.num_threads = num_threads;
1776 progress_data.progress.write_streams.compression_type = out_ctype;
1777 progress_data.progress.write_streams.total_parts = total_parts;
1778 progress_data.progress.write_streams.completed_parts = 0;
1780 progress_data.next_progress = 0;
1781 progress_data.prev_wim_part = NULL;
1783 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1784 if (total_compression_bytes >= 2000000 && num_threads != 1)
1785 ret = write_stream_list_parallel(stream_list,
1791 write_resource_flags,
1796 ret = write_stream_list_serial(stream_list,
1802 write_resource_flags,
1805 DEBUG("Successfully wrote stream list.");
1807 DEBUG("Failed to write stream list (ret=%d).", ret);
1811 struct stream_size_table {
1812 struct hlist_head *array;
1818 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1820 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1822 return WIMLIB_ERR_NOMEM;
1823 tab->num_entries = 0;
1824 tab->capacity = capacity;
1829 destroy_stream_size_table(struct stream_size_table *tab)
1835 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1837 struct stream_size_table *tab = _tab;
1839 struct wim_lookup_table_entry *same_size_lte;
1840 struct hlist_node *tmp;
1842 pos = hash_u64(lte->size) % tab->capacity;
1843 lte->unique_size = 1;
1844 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1845 if (same_size_lte->size == lte->size) {
1846 lte->unique_size = 0;
1847 same_size_lte->unique_size = 0;
1852 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1857 struct find_streams_ctx {
1860 struct list_head stream_list;
1861 struct stream_size_table stream_size_tab;
1865 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1866 struct find_streams_ctx *ctx,
1869 if (lte->out_refcnt == 0) {
1870 stream_size_table_insert(lte, &ctx->stream_size_tab);
1871 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1873 lte->out_refcnt += nref;
1877 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1880 struct find_streams_ctx *ctx = _ctx;
1881 lte->out_refcnt = 0;
1882 lte_reference_for_logical_write(lte, ctx,
1883 (lte->refcnt ? lte->refcnt : 1));
1888 inode_find_streams_to_write(struct wim_inode *inode,
1889 struct wim_lookup_table *table,
1890 struct find_streams_ctx *ctx)
1892 struct wim_lookup_table_entry *lte;
1895 for (i = 0; i <= inode->i_num_ads; i++) {
1896 lte = inode_stream_lte(inode, i, table);
1898 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1899 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1900 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1906 image_find_streams_to_write(WIMStruct *wim)
1908 struct find_streams_ctx *ctx;
1909 struct wim_image_metadata *imd;
1910 struct wim_inode *inode;
1911 struct wim_lookup_table_entry *lte;
1915 imd = wim_get_current_image_metadata(wim);
1917 image_for_each_unhashed_stream(lte, imd)
1918 lte->out_refcnt = 0;
1920 /* Go through this image's inodes to find any streams that have not been
1922 image_for_each_inode(inode, imd) {
1923 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1931 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1932 * the "logical write" of the WIM, meaning all streams that are referenced at
1933 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1934 * each stream being included in the logical write is set to the number of
1935 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1936 * stream being included in the logical write is set to indicate whether that
1937 * stream has a unique size relative to the streams being included in the
1938 * logical write. Still furthermore, 'part_number' on each stream being
1939 * included in the logical write is set to the part number given in the
1940 * in-memory header of @p wim.
1942 * This is considered a "logical write" because it does not take into account
1943 * filtering out streams already present in the WIM (in the case of an in place
1944 * overwrite) or present in other WIMs (in case of creating delta WIM).
1947 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1948 struct find_streams_ctx *ctx)
1952 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1953 (image == 1 && wim->hdr.image_count == 1)))
1955 /* Fast case: Assume that all streams are being written and
1956 * that the reference counts are correct. */
1957 struct wim_lookup_table_entry *lte;
1958 struct wim_image_metadata *imd;
1961 for_lookup_table_entry(wim->lookup_table,
1962 do_lte_full_reference_for_logical_write, ctx);
1963 for (i = 0; i < wim->hdr.image_count; i++) {
1964 imd = wim->image_metadata[i];
1965 image_for_each_unhashed_stream(lte, imd)
1966 do_lte_full_reference_for_logical_write(lte, ctx);
1969 /* Slow case: Walk through the images being written and
1970 * determine the streams referenced. */
1971 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1973 ret = for_image(wim, image, image_find_streams_to_write);
1982 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1984 struct find_streams_ctx *ctx = _ctx;
1987 /* Calculate and set lte->filtered. */
1988 if (lte->resource_location == RESOURCE_IN_WIM) {
1989 if (lte->rspec->wim == ctx->wim &&
1990 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1991 filtered |= FILTERED_SAME_WIM;
1992 if (lte->rspec->wim != ctx->wim &&
1993 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1994 filtered |= FILTERED_EXTERNAL_WIM;
1996 lte->filtered = filtered;
1998 /* Filtered streams get inserted into the stream size table too, unless
1999 * they already were. This is because streams that are checksummed
2000 * on-the-fly during the write should not be written if they are
2001 * duplicates of filtered stream. */
2002 if (lte->filtered && lte->out_refcnt == 0)
2003 stream_size_table_insert(lte, &ctx->stream_size_tab);
2008 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
2014 /* Given the list of streams to include in a logical write of a WIM, handle
2015 * filtering out streams already present in the WIM or already present in
2016 * external WIMs, depending on the write flags provided. */
2018 handle_stream_filtering(struct find_streams_ctx *ctx)
2020 struct wim_lookup_table_entry *lte, *tmp;
2022 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2023 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2025 for_lookup_table_entry(ctx->wim->lookup_table,
2026 mark_stream_not_filtered, ctx);
2030 for_lookup_table_entry(ctx->wim->lookup_table,
2031 process_filtered_stream, ctx);
2033 /* Streams in logical write list that were filtered can be removed. */
2034 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2037 list_del(<e->write_streams_list);
2040 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2041 * around prepare_logical_stream_list() to handle filtering out streams already
2042 * present in the WIM or already present in external WIMs, depending on the
2043 * write flags provided.
2045 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2047 * - 'out_refcnt' is set to the number of references found for the logical write.
2048 * This will be nonzero on all streams in the list returned by this function,
2049 * but will also be nonzero on streams not in the list that were included in
2050 * the logical write list, but filtered out from the returned list.
2051 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2052 * are not included in the list of streams returned by this function.
2053 * - 'unique_size' is set if the stream has a unique size among all streams in
2054 * the logical write plus any filtered streams in the entire WIM that could
2055 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2056 * stream being written.
2059 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2060 struct list_head *stream_list)
2064 struct find_streams_ctx ctx;
2066 INIT_LIST_HEAD(&ctx.stream_list);
2067 ret = init_stream_size_table(&ctx.stream_size_tab,
2068 wim->lookup_table->capacity);
2071 ctx.write_flags = write_flags;
2074 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2076 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2078 goto out_destroy_table;
2080 handle_stream_filtering(&ctx);
2081 list_transfer(&ctx.stream_list, stream_list);
2084 destroy_stream_size_table(&ctx.stream_size_tab);
2089 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2090 unsigned num_threads,
2091 wimlib_progress_func_t progress_func,
2092 struct list_head *stream_list_override)
2095 struct list_head _stream_list;
2096 struct list_head *stream_list;
2097 struct wim_lookup_table_entry *lte;
2099 if (stream_list_override == NULL) {
2100 /* Normal case: prepare stream list from image(s) being written.
2102 stream_list = &_stream_list;
2103 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2107 /* Currently only as a result of wimlib_split() being called:
2108 * use stream list already explicitly provided. Use existing
2109 * reference counts. */
2110 stream_list = stream_list_override;
2111 list_for_each_entry(lte, stream_list, write_streams_list)
2112 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2115 return write_stream_list(stream_list,
2118 wim->out_compression_type,
2119 wim->out_chunk_size,
2127 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2128 wimlib_progress_func_t progress_func)
2133 int write_resource_flags;
2135 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2136 DEBUG("Not writing any metadata resources.");
2140 write_resource_flags = write_flags_to_resource_flags(write_flags);
2142 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2143 wim->out_fd.offset);
2146 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2148 if (image == WIMLIB_ALL_IMAGES) {
2150 end_image = wim->hdr.image_count;
2152 start_image = image;
2156 for (int i = start_image; i <= end_image; i++) {
2157 struct wim_image_metadata *imd;
2159 imd = wim->image_metadata[i - 1];
2160 /* Build a new metadata resource only if image was modified from
2161 * the original (or was newly added). Otherwise just copy the
2163 if (imd->modified) {
2164 DEBUG("Image %u was modified; building and writing new "
2165 "metadata resource", i);
2166 ret = write_metadata_resource(wim, i,
2167 write_resource_flags);
2168 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2169 DEBUG("Image %u was not modified; re-using existing "
2170 "metadata resource.", i);
2171 wim_res_spec_to_hdr(imd->metadata_lte->rspec,
2172 &imd->metadata_lte->out_reshdr);
2175 DEBUG("Image %u was not modified; copying existing "
2176 "metadata resource.", i);
2177 ret = write_wim_resource(imd->metadata_lte,
2179 wim->out_compression_type,
2180 wim->out_chunk_size,
2181 &imd->metadata_lte->out_reshdr,
2182 write_resource_flags,
2189 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2194 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2197 DEBUG("Opening \"%"TS"\" for writing.", path);
2199 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2201 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2202 return WIMLIB_ERR_OPEN;
2204 filedes_init(&wim->out_fd, raw_fd);
2209 close_wim_writable(WIMStruct *wim, int write_flags)
2213 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2214 DEBUG("Closing WIM file.");
2215 if (filedes_valid(&wim->out_fd))
2216 if (filedes_close(&wim->out_fd))
2217 ret = WIMLIB_ERR_WRITE;
2219 filedes_invalidate(&wim->out_fd);
2226 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2227 * table, then overwrite the WIM header. By default, closes the WIM file
2228 * descriptor (@wim->out_fd) if successful.
2230 * write_flags is a bitwise OR of the following:
2232 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2233 * Include an integrity table.
2235 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2236 * fsync() the output file before closing it.
2238 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2239 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2240 * stream headers before the lookup table and XML data, and also
2241 * write the WIM header at the end instead of seeking to the
2242 * beginning. Can't be combined with
2243 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2245 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2246 * Don't write the lookup table.
2248 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2249 * When (if) writing the integrity table, re-use entries from the
2250 * existing integrity table, if possible.
2252 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2253 * After writing the XML data but before writing the integrity
2254 * table, write a temporary WIM header and flush the stream so that
2255 * the WIM is less likely to become corrupted upon abrupt program
2257 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2258 * Instead of overwriting the WIM header at the beginning of the
2259 * file, simply append it to the end of the file. (Used when
2261 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2262 * Do not close the file descriptor @wim->out_fd on either success
2264 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2265 * Use the existing <TOTALBYTES> stored in the in-memory XML
2266 * information, rather than setting it to the offset of the XML
2267 * data being written.
2270 finish_write(WIMStruct *wim, int image, int write_flags,
2271 wimlib_progress_func_t progress_func,
2272 struct list_head *stream_list_override)
2276 int write_resource_flags;
2277 off_t old_lookup_table_end;
2278 off_t new_lookup_table_end;
2281 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2283 write_resource_flags = write_flags_to_resource_flags(write_flags);
2285 /* In the WIM header, there is room for the resource entry for a
2286 * metadata resource labeled as the "boot metadata". This entry should
2287 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2288 * it should be a copy of the resource entry for the image that is
2289 * marked as bootable. This is not well documented... */
2290 if (wim->hdr.boot_idx == 0) {
2291 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2293 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2294 &wim->image_metadata[wim->hdr.boot_idx- 1
2295 ]->metadata_lte->out_reshdr);
2298 /* Write lookup table. (Save old position first.) */
2299 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2300 wim->hdr.lookup_table_reshdr.size_in_wim;
2301 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2302 ret = write_wim_lookup_table(wim, image, write_flags,
2303 &wim->hdr.lookup_table_reshdr,
2304 stream_list_override);
2309 /* Write XML data. */
2310 xml_totalbytes = wim->out_fd.offset;
2311 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2312 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2313 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2314 &wim->hdr.xml_data_reshdr,
2315 write_resource_flags);
2319 /* Write integrity table (optional). */
2320 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2321 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2322 struct wim_header checkpoint_hdr;
2323 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2324 zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2325 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2326 ret = write_wim_header_at_offset(&checkpoint_hdr,
2332 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2333 old_lookup_table_end = 0;
2335 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2336 wim->hdr.lookup_table_reshdr.size_in_wim;
2338 ret = write_integrity_table(wim,
2339 new_lookup_table_end,
2340 old_lookup_table_end,
2345 /* No integrity table. */
2346 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2349 /* Now that all information in the WIM header has been determined, the
2350 * preliminary header written earlier can be overwritten, the header of
2351 * the existing WIM file can be overwritten, or the final header can be
2352 * written to the end of the pipable WIM. */
2353 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2355 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2356 hdr_offset = wim->out_fd.offset;
2357 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2358 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2362 /* Possibly sync file data to disk before closing. On POSIX systems, it
2363 * is necessary to do this before using rename() to overwrite an
2364 * existing file with a new file. Otherwise, data loss would occur if
2365 * the system is abruptly terminated when the metadata for the rename
2366 * operation has been written to disk, but the new file data has not.
2368 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2369 DEBUG("Syncing WIM file.");
2370 if (fsync(wim->out_fd.fd)) {
2371 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2372 return WIMLIB_ERR_WRITE;
2376 if (close_wim_writable(wim, write_flags)) {
2377 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2378 return WIMLIB_ERR_WRITE;
2384 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2386 lock_wim(WIMStruct *wim, int fd)
2389 if (fd != -1 && !wim->wim_locked) {
2390 ret = flock(fd, LOCK_EX | LOCK_NB);
2392 if (errno == EWOULDBLOCK) {
2393 ERROR("`%"TS"' is already being modified or has been "
2394 "mounted read-write\n"
2395 " by another process!", wim->filename);
2396 ret = WIMLIB_ERR_ALREADY_LOCKED;
2398 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2403 wim->wim_locked = 1;
2411 * write_pipable_wim():
2413 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2414 * capable of being applied from a pipe).
2416 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2417 * images can be applied from them sequentially when the file data is sent over
2418 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2419 * The modifications made to the WIM format for pipable WIMs are:
2421 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2422 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2423 * stops other software from trying to read the file as a normal WIM.
2425 * - The header at the beginning of the file does not contain all the normal
2426 * information; in particular it will have all 0's for the lookup table and
2427 * XML data resource entries. This is because this information cannot be
2428 * determined until the lookup table and XML data have been written.
2429 * Consequently, wimlib will write the full header at the very end of the
2430 * file. The header at the end, however, is only used when reading the WIM
2431 * from a seekable file (not a pipe).
2433 * - An extra copy of the XML data is placed directly after the header. This
2434 * allows image names and sizes to be determined at an appropriate time when
2435 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2436 * WIM is read from a seekable file (not a pipe).
2438 * - The format of resources, or streams, has been modified to allow them to be
2439 * used before the "lookup table" has been read. Each stream is prefixed with
2440 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2441 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2442 * uncompressed stream size, and flags that indicate whether the stream is
2443 * compressed. The data of uncompressed streams then follows literally, while
2444 * the data of compressed streams follows in a modified format. Compressed
2445 * streams do not begin with a chunk table, since the chunk table cannot be
2446 * written until all chunks have been compressed. Instead, each compressed
2447 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2448 * Furthermore, the chunk table is written at the end of the resource instead
2449 * of the start. Note: chunk offsets are given in the chunk table as if the
2450 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2451 * used if the WIM is being read from a seekable file (not a pipe).
2453 * - Metadata resources always come before other file resources (streams).
2454 * (This does not by itself constitute an incompatibility with normal WIMs,
2455 * since this is valid in normal WIMs.)
2457 * - At least up to the end of the file resources, all components must be packed
2458 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2459 * not by itself consititute an incompatibility with normal WIMs, since this
2460 * is valid in normal WIMs.)
2462 * Note: the lookup table, XML data, and header at the end are not used when
2463 * applying from a pipe. They exist to support functionality such as image
2464 * application and export when the WIM is *not* read from a pipe.
2466 * Layout of pipable WIM:
2468 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2469 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2470 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2472 * Layout of normal WIM:
2474 * +--------+-----------------------------+-------------------------+
2475 * | Header | File and metadata resources | Lookup table | XML data |
2476 * +--------+-----------------------------+-------------------------+
2478 * An optional integrity table can follow the final XML data in both normal and
2479 * pipable WIMs. However, due to implementation details, wimlib currently can
2480 * only include an integrity table in a pipable WIM when writing it to a
2481 * seekable file (not a pipe).
2483 * Do note that since pipable WIMs are not supported by Microsoft's software,
2484 * wimlib does not create them unless explicitly requested (with
2485 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2486 * characters to identify the file.
2489 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2490 unsigned num_threads, wimlib_progress_func_t progress_func,
2491 struct list_head *stream_list_override)
2494 struct wim_reshdr xml_reshdr;
2496 WARNING("Creating a pipable WIM, which will "
2498 " with Microsoft's software (wimgapi/imagex/Dism).");
2500 /* At this point, the header at the beginning of the file has already
2503 /* For efficiency, when wimlib adds an image to the WIM with
2504 * wimlib_add_image(), the SHA1 message digests of files is not
2505 * calculated; instead, they are calculated while the files are being
2506 * written. However, this does not work when writing a pipable WIM,
2507 * since when writing a stream to a pipable WIM, its SHA1 message digest
2508 * needs to be known before the stream data is written. Therefore,
2509 * before getting much farther, we need to pre-calculate the SHA1
2510 * message digests of all streams that will be written. */
2511 ret = wim_checksum_unhashed_streams(wim);
2515 /* Write extra copy of the XML data. */
2516 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2518 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2522 /* Write metadata resources for the image(s) being included in the
2524 ret = write_wim_metadata_resources(wim, image, write_flags,
2529 /* Write streams needed for the image(s) being included in the output
2530 * WIM, or streams needed for the split WIM part. */
2531 return write_wim_streams(wim, image, write_flags, num_threads,
2532 progress_func, stream_list_override);
2534 /* The lookup table, XML data, and header at end are handled by
2535 * finish_write(). */
2538 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2541 write_wim_part(WIMStruct *wim,
2542 const void *path_or_fd,
2545 unsigned num_threads,
2546 wimlib_progress_func_t progress_func,
2547 unsigned part_number,
2548 unsigned total_parts,
2549 struct list_head *stream_list_override,
2553 struct wim_header hdr_save;
2554 struct list_head lt_stream_list_override;
2556 if (total_parts == 1)
2557 DEBUG("Writing standalone WIM.");
2559 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2560 if (image == WIMLIB_ALL_IMAGES)
2561 DEBUG("Including all images.");
2563 DEBUG("Including image %d only.", image);
2564 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2565 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2567 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2568 DEBUG("Write flags: 0x%08x", write_flags);
2569 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2570 DEBUG("\tCHECK_INTEGRITY");
2571 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2573 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2574 DEBUG("\tRECOMPRESS");
2575 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2577 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2579 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2580 DEBUG("\tIGNORE_READONLY_FLAG");
2581 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2583 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2584 DEBUG("\tFILE_DESCRIPTOR");
2585 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2586 DEBUG("\tNO_METADATA");
2587 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2588 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2589 if (num_threads == 0)
2590 DEBUG("Number of threads: autodetect");
2592 DEBUG("Number of threads: %u", num_threads);
2593 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2594 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2595 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2596 "specified" : "generate new"));
2598 /* Internally, this is always called with a valid part number and total
2600 wimlib_assert(total_parts >= 1);
2601 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2603 /* A valid image (or all images) must be specified. */
2604 if (image != WIMLIB_ALL_IMAGES &&
2605 (image < 1 || image > wim->hdr.image_count))
2606 return WIMLIB_ERR_INVALID_IMAGE;
2608 /* If we need to write metadata resources, make sure the ::WIMStruct has
2609 * the needed information attached (e.g. is not a resource-only WIM,
2610 * such as a non-first part of a split WIM). */
2611 if (!wim_has_metadata(wim) &&
2612 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2613 return WIMLIB_ERR_METADATA_NOT_FOUND;
2615 /* Check for contradictory flags. */
2616 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2617 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2618 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2619 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2620 return WIMLIB_ERR_INVALID_PARAM;
2622 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2623 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2624 == (WIMLIB_WRITE_FLAG_PIPABLE |
2625 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2626 return WIMLIB_ERR_INVALID_PARAM;
2628 /* Save previous header, then start initializing the new one. */
2629 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2631 /* Set default integrity and pipable flags. */
2632 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2633 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2634 if (wim_is_pipable(wim))
2635 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2637 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2638 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2639 if (wim_has_integrity_table(wim))
2640 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2642 /* Set appropriate magic number. */
2643 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2644 wim->hdr.magic = PWM_MAGIC;
2646 wim->hdr.magic = WIM_MAGIC;
2648 /* Clear header flags that will be set automatically. */
2649 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2650 WIM_HDR_FLAG_RESOURCE_ONLY |
2651 WIM_HDR_FLAG_SPANNED |
2652 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2654 /* Set SPANNED header flag if writing part of a split WIM. */
2655 if (total_parts != 1)
2656 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2658 /* Set part number and total parts of split WIM. This will be 1 and 1
2659 * if the WIM is standalone. */
2660 wim->hdr.part_number = part_number;
2661 wim->hdr.total_parts = total_parts;
2663 /* Set compression type if different. */
2664 if (wim->compression_type != wim->out_compression_type) {
2665 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2666 wimlib_assert(ret == 0);
2669 /* Set chunk size if different. */
2670 wim->hdr.chunk_size = wim->out_chunk_size;
2672 /* Use GUID if specified; otherwise generate a new one. */
2674 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2675 else if (!wim->guid_set_explicitly)
2676 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2678 /* Clear references to resources that have not been written yet. */
2679 zero_reshdr(&wim->hdr.lookup_table_reshdr);
2680 zero_reshdr(&wim->hdr.xml_data_reshdr);
2681 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2682 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2684 /* Set image count and boot index correctly for single image writes. */
2685 if (image != WIMLIB_ALL_IMAGES) {
2686 wim->hdr.image_count = 1;
2687 if (wim->hdr.boot_idx == image)
2688 wim->hdr.boot_idx = 1;
2690 wim->hdr.boot_idx = 0;
2693 /* Split WIMs can't be bootable. */
2694 if (total_parts != 1)
2695 wim->hdr.boot_idx = 0;
2697 /* Initialize output file descriptor. */
2698 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2699 /* File descriptor was explicitly provided. Return error if
2700 * file descriptor is not seekable, unless writing a pipable WIM
2702 wim->out_fd.fd = *(const int*)path_or_fd;
2703 wim->out_fd.offset = 0;
2704 if (!filedes_is_seekable(&wim->out_fd)) {
2705 ret = WIMLIB_ERR_INVALID_PARAM;
2706 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2707 goto out_restore_hdr;
2708 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2709 ERROR("Can't include integrity check when "
2710 "writing pipable WIM to pipe!");
2711 goto out_restore_hdr;
2716 /* Filename of WIM to write was provided; open file descriptor
2718 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2719 O_TRUNC | O_CREAT | O_RDWR);
2721 goto out_restore_hdr;
2724 /* Write initial header. This is merely a "dummy" header since it
2725 * doesn't have all the information yet, so it will be overwritten later
2726 * (unless writing a pipable WIM). */
2727 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2728 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2729 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2730 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2732 goto out_restore_hdr;
2734 if (stream_list_override) {
2735 struct wim_lookup_table_entry *lte;
2736 INIT_LIST_HEAD(<_stream_list_override);
2737 list_for_each_entry(lte, stream_list_override,
2740 list_add_tail(<e->lookup_table_list,
2741 <_stream_list_override);
2745 /* Write metadata resources and streams. */
2746 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2747 /* Default case: create a normal (non-pipable) WIM. */
2748 ret = write_wim_streams(wim, image, write_flags, num_threads,
2749 progress_func, stream_list_override);
2751 goto out_restore_hdr;
2753 ret = write_wim_metadata_resources(wim, image, write_flags,
2756 goto out_restore_hdr;
2758 /* Non-default case: create pipable WIM. */
2759 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2760 progress_func, stream_list_override);
2762 goto out_restore_hdr;
2763 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2766 if (stream_list_override)
2767 stream_list_override = <_stream_list_override;
2769 /* Write lookup table, XML data, and (optional) integrity table. */
2770 ret = finish_write(wim, image, write_flags, progress_func,
2771 stream_list_override);
2773 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2774 (void)close_wim_writable(wim, write_flags);
2775 DEBUG("ret=%d", ret);
2779 /* Write a standalone WIM to a file or file descriptor. */
2781 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2782 int image, int write_flags, unsigned num_threads,
2783 wimlib_progress_func_t progress_func)
2785 return write_wim_part(wim, path_or_fd, image, write_flags,
2786 num_threads, progress_func, 1, 1, NULL, NULL);
2789 /* API function documented in wimlib.h */
2791 wimlib_write(WIMStruct *wim, const tchar *path,
2792 int image, int write_flags, unsigned num_threads,
2793 wimlib_progress_func_t progress_func)
2796 return WIMLIB_ERR_INVALID_PARAM;
2798 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2800 return write_standalone_wim(wim, path, image, write_flags,
2801 num_threads, progress_func);
2804 /* API function documented in wimlib.h */
2806 wimlib_write_to_fd(WIMStruct *wim, int fd,
2807 int image, int write_flags, unsigned num_threads,
2808 wimlib_progress_func_t progress_func)
2811 return WIMLIB_ERR_INVALID_PARAM;
2813 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2814 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2816 return write_standalone_wim(wim, &fd, image, write_flags,
2817 num_threads, progress_func);
2821 any_images_modified(WIMStruct *wim)
2823 for (int i = 0; i < wim->hdr.image_count; i++)
2824 if (wim->image_metadata[i]->modified)
2830 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2832 const WIMStruct *wim = _wim;
2833 off_t end_offset = *(const off_t*)wim->private;
2835 if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2836 lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2837 return WIMLIB_ERR_RESOURCE_ORDER;
2841 /* Make sure no file or metadata resources are located after the XML data (or
2842 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2843 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2845 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2850 wim->private = &end_offset;
2851 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2855 for (i = 0; i < wim->hdr.image_count; i++) {
2856 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2864 * Overwrite a WIM, possibly appending streams to it.
2866 * A WIM looks like (or is supposed to look like) the following:
2868 * Header (212 bytes)
2869 * Streams and metadata resources (variable size)
2870 * Lookup table (variable size)
2871 * XML data (variable size)
2872 * Integrity table (optional) (variable size)
2874 * If we are not adding any streams or metadata resources, the lookup table is
2875 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2876 * header. This operation is potentially unsafe if the program is abruptly
2877 * terminated while the XML data or integrity table are being overwritten, but
2878 * before the new header has been written. To partially alleviate this problem,
2879 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2880 * finish_write() to cause a temporary WIM header to be written after the XML
2881 * data has been written. This may prevent the WIM from becoming corrupted if
2882 * the program is terminated while the integrity table is being calculated (but
2883 * no guarantees, due to write re-ordering...).
2885 * If we are adding new streams or images (metadata resources), the lookup table
2886 * needs to be changed, and those streams need to be written. In this case, we
2887 * try to perform a safe update of the WIM file by writing the streams *after*
2888 * the end of the previous WIM, then writing the new lookup table, XML data, and
2889 * (optionally) integrity table following the new streams. This will produce a
2890 * layout like the following:
2892 * Header (212 bytes)
2893 * (OLD) Streams and metadata resources (variable size)
2894 * (OLD) Lookup table (variable size)
2895 * (OLD) XML data (variable size)
2896 * (OLD) Integrity table (optional) (variable size)
2897 * (NEW) Streams and metadata resources (variable size)
2898 * (NEW) Lookup table (variable size)
2899 * (NEW) XML data (variable size)
2900 * (NEW) Integrity table (optional) (variable size)
2902 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2903 * the header is overwritten to point to the new lookup table, XML data, and
2904 * integrity table, to produce the following layout:
2906 * Header (212 bytes)
2907 * Streams and metadata resources (variable size)
2908 * Nothing (variable size)
2909 * More Streams and metadata resources (variable size)
2910 * Lookup table (variable size)
2911 * XML data (variable size)
2912 * Integrity table (optional) (variable size)
2914 * This method allows an image to be appended to a large WIM very quickly, and
2915 * is is crash-safe except in the case of write re-ordering, but the
2916 * disadvantage is that a small hole is left in the WIM where the old lookup
2917 * table, xml data, and integrity table were. (These usually only take up a
2918 * small amount of space compared to the streams, however.)
2921 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2922 unsigned num_threads,
2923 wimlib_progress_func_t progress_func)
2926 struct list_head stream_list;
2928 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2929 struct wim_header hdr_save;
2931 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2933 /* Set default integrity flag. */
2934 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2935 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2936 if (wim_has_integrity_table(wim))
2937 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2939 /* Set additional flags for overwrite. */
2940 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2941 WIMLIB_WRITE_FLAG_STREAMS_OK;
2943 /* Make sure that the integrity table (if present) is after the XML
2944 * data, and that there are no stream resources, metadata resources, or
2945 * lookup tables after the XML data. Otherwise, these data would be
2947 old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2948 old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2949 old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2950 wim->hdr.lookup_table_reshdr.size_in_wim;
2951 if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2952 wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2953 WARNING("Didn't expect the integrity table to be before the XML data");
2954 return WIMLIB_ERR_RESOURCE_ORDER;
2957 if (old_lookup_table_end > old_xml_begin) {
2958 WARNING("Didn't expect the lookup table to be after the XML data");
2959 return WIMLIB_ERR_RESOURCE_ORDER;
2962 /* Set @old_wim_end, which indicates the point beyond which we don't
2963 * allow any file and metadata resources to appear without returning
2964 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2965 * overwrite these resources). */
2966 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2967 /* If no images have been modified and no images have been
2968 * deleted, a new lookup table does not need to be written. We
2969 * shall write the new XML data and optional integrity table
2970 * immediately after the lookup table. Note that this may
2971 * overwrite an existing integrity table. */
2972 DEBUG("Skipping writing lookup table "
2973 "(no images modified or deleted)");
2974 old_wim_end = old_lookup_table_end;
2975 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2976 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2977 } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2978 /* Old WIM has an integrity table; begin writing new streams
2980 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2981 wim->hdr.integrity_table_reshdr.size_in_wim;
2983 /* No existing integrity table; begin writing new streams after
2984 * the old XML data. */
2985 old_wim_end = old_xml_end;
2988 ret = check_resource_offsets(wim, old_wim_end);
2992 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2997 ret = open_wim_writable(wim, wim->filename, O_RDWR);
3001 ret = lock_wim(wim, wim->out_fd.fd);
3005 /* Save original header so it can be restored in case of error */
3006 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
3008 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3009 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3010 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3012 ERROR_WITH_ERRNO("Error updating WIM header flags");
3013 goto out_restore_memory_hdr;
3016 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3017 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3018 ret = WIMLIB_ERR_WRITE;
3019 goto out_restore_physical_hdr;
3022 ret = write_stream_list(&stream_list,
3025 wim->compression_type,
3034 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3035 write_flags, progress_func);
3039 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3040 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3041 progress_func, NULL);
3045 goto out_unlock_wim;
3048 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3049 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3050 wim->filename, old_wim_end);
3051 /* Return value of ftruncate() is ignored because this is
3052 * already an error path. */
3053 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3055 out_restore_physical_hdr:
3056 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3057 out_restore_memory_hdr:
3058 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3060 (void)close_wim_writable(wim, write_flags);
3062 wim->wim_locked = 0;
3067 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3068 unsigned num_threads,
3069 wimlib_progress_func_t progress_func)
3071 size_t wim_name_len;
3074 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3076 /* Write the WIM to a temporary file in the same directory as the
3078 wim_name_len = tstrlen(wim->filename);
3079 tchar tmpfile[wim_name_len + 10];
3080 tmemcpy(tmpfile, wim->filename, wim_name_len);
3081 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3082 tmpfile[wim_name_len + 9] = T('\0');
3084 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3085 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3086 num_threads, progress_func);
3094 /* Rename the new WIM file to the original WIM file. Note: on Windows
3095 * this actually calls win32_rename_replacement(), not _wrename(), so
3096 * that removing the existing destination file can be handled. */
3097 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3098 ret = trename(tmpfile, wim->filename);
3100 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3101 tmpfile, wim->filename);
3108 return WIMLIB_ERR_RENAME;
3111 if (progress_func) {
3112 union wimlib_progress_info progress;
3113 progress.rename.from = tmpfile;
3114 progress.rename.to = wim->filename;
3115 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3120 /* API function documented in wimlib.h */
3122 wimlib_overwrite(WIMStruct *wim, int write_flags,
3123 unsigned num_threads,
3124 wimlib_progress_func_t progress_func)
3129 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3131 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3132 return WIMLIB_ERR_INVALID_PARAM;
3135 return WIMLIB_ERR_NO_FILENAME;
3137 orig_hdr_flags = wim->hdr.flags;
3138 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3139 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3140 ret = can_modify_wim(wim);
3141 wim->hdr.flags = orig_hdr_flags;
3145 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3146 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3147 WIMLIB_WRITE_FLAG_PIPABLE))
3148 && !(wim_is_pipable(wim))
3149 && wim->compression_type == wim->out_compression_type
3150 && wim->chunk_size == wim->out_chunk_size)
3152 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3154 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3156 WARNING("Falling back to re-building entire WIM");
3158 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,