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 == wim_resource_compression_type(lte)
78 && out_chunk_size == wim_resource_chunk_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;
153 size = wim_resource_size(lte);
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("Failed to write chunk table in compressed "
238 /* Write the header for a stream in a pipable WIM.
241 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
242 struct filedes *out_fd,
243 int additional_reshdr_flags)
245 struct pwm_stream_hdr stream_hdr;
249 stream_hdr.magic = PWM_STREAM_MAGIC;
250 stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
251 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
252 zero_out_hash(stream_hdr.hash);
254 wimlib_assert(!lte->unhashed);
255 copy_hash(stream_hdr.hash, lte->hash);
258 reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
259 reshdr_flags |= additional_reshdr_flags;
260 stream_hdr.flags = cpu_to_le32(reshdr_flags);
261 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
263 ERROR_WITH_ERRNO("Error writing stream header");
268 seek_and_truncate(struct filedes *out_fd, off_t offset)
270 if (filedes_seek(out_fd, offset) == -1 ||
271 ftruncate(out_fd->fd, offset))
273 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
274 return WIMLIB_ERR_WRITE;
280 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
282 u8 md[SHA1_HASH_SIZE];
284 sha1_final(md, sha_ctx);
286 copy_hash(lte->hash, md);
287 } else if (!hashes_equal(md, lte->hash)) {
288 ERROR("WIM resource has incorrect hash!");
289 if (lte_filename_valid(lte)) {
290 ERROR("We were reading it from \"%"TS"\"; maybe "
291 "it changed while we were reading it.",
294 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
299 struct write_resource_ctx {
302 struct wimlib_lzx_context *comp_ctx;
303 struct chunk_table *chunk_tab;
304 struct filedes *out_fd;
311 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
313 struct write_resource_ctx *ctx = _ctx;
314 const void *out_chunk;
315 unsigned out_chunk_size;
317 void *compressed_chunk = NULL;
318 unsigned compressed_size;
319 bool compressed_chunk_malloced = false;
320 size_t stack_max = 32768;
323 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
326 out_chunk_size = chunk_size;
327 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
329 /* Compress the chunk. */
330 if (chunk_size <= stack_max) {
331 compressed_chunk = alloca(chunk_size);
333 compressed_chunk = MALLOC(chunk_size);
334 if (compressed_chunk == NULL)
335 return WIMLIB_ERR_NOMEM;
336 compressed_chunk_malloced = true;
339 compressed_size = compress_chunk(chunk, chunk_size,
343 /* Use compressed data if compression to less than input size
345 if (compressed_size) {
346 out_chunk = compressed_chunk;
347 out_chunk_size = compressed_size;
351 if (ctx->chunk_tab) {
352 /* Update chunk table accounting. */
353 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
355 /* If writing compressed chunks to a pipable WIM, before the
356 * chunk data write a chunk header that provides the compressed
358 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
359 struct pwm_chunk_hdr chunk_hdr = {
360 .compressed_size = cpu_to_le32(out_chunk_size),
362 ret = full_write(ctx->out_fd, &chunk_hdr,
369 /* Write the chunk data. */
370 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
375 if (compressed_chunk_malloced)
376 FREE(compressed_chunk);
380 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
381 goto out_free_memory;
385 * write_wim_resource()-
387 * Write a resource to an output WIM.
390 * Lookup table entry for the resource, which could be in another WIM, in
391 * an external file, or in another location.
394 * File descriptor opened to the output WIM.
397 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
398 * compression algorithm 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 * the 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 resource_entry *out_res_entry,
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 the same compression type as that
443 * desired other than no compression, we can simply copy the compressed
444 * data without recompressing it. This also means we must skip
445 * calculating the SHA1, as we never will see the uncompressed data. */
446 if (can_raw_copy(lte, resource_flags, out_ctype, out_chunk_size)) {
447 /* Normally we can request a RAW_FULL read, but if we're reading
448 * from a pipable resource and writing a non-pipable resource or
449 * vice versa, then a RAW_CHUNKS read needs to be requested so
450 * that the written resource can be appropriately formatted.
451 * However, in neither case is any actual decompression needed.
453 if (lte->is_pipable == !!(resource_flags &
454 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
455 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
457 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
458 read_size = lte->resource_entry.size;
459 write_ctx.doing_sha = false;
461 write_ctx.doing_sha = true;
462 sha1_init(&write_ctx.sha_ctx);
463 read_size = lte->resource_entry.original_size;
466 /* If the output resource is to be compressed, initialize the chunk
467 * table and set the function to use for chunk compression. Exceptions:
468 * no compression function is needed if doing a raw copy; also, no chunk
469 * table is needed if doing a *full* (not per-chunk) raw copy. */
470 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
471 write_ctx.out_chunk_size = out_chunk_size;
472 write_ctx.chunk_tab = NULL;
473 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
474 wimlib_assert(out_chunk_size > 0);
475 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
476 write_ctx.out_ctype = out_ctype;
477 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
478 ret = wimlib_lzx_alloc_context(NULL, comp_ctx);
482 write_ctx.comp_ctx = *comp_ctx;
484 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
485 ret = begin_wim_resource_chunk_tab(lte, out_fd,
487 &write_ctx.chunk_tab,
494 /* If writing a pipable resource, write the stream header and update
495 * @res_start_offset to be the end of the stream header. */
496 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
497 int reshdr_flags = 0;
498 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
499 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
500 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
502 goto out_free_chunk_tab;
503 res_start_offset = out_fd->offset;
506 /* Write the entire resource by reading the entire resource and feeding
507 * the data through the write_resource_cb function. */
508 write_ctx.out_fd = out_fd;
509 write_ctx.resource_flags = resource_flags;
511 if (write_ctx.out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
512 in_chunk_size = wim_resource_chunk_size(lte);
514 in_chunk_size = out_chunk_size;
515 ret = read_resource_prefix(lte, read_size,
517 in_chunk_size, &write_ctx, resource_flags);
519 goto out_free_chunk_tab;
521 /* Verify SHA1 message digest of the resource, or set the hash for the
523 if (write_ctx.doing_sha) {
524 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
526 goto out_free_chunk_tab;
529 /* Write chunk table if needed. */
530 if (write_ctx.chunk_tab) {
531 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
536 goto out_free_chunk_tab;
539 /* Fill in out_res_entry with information about the newly written
541 out_res_entry->size = out_fd->offset - res_start_offset;
542 out_res_entry->flags = lte->resource_entry.flags;
543 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
544 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
546 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
547 out_res_entry->offset = res_start_offset;
548 out_res_entry->original_size = wim_resource_size(lte);
550 /* Check for resources compressed to greater than their original size
551 * and write them uncompressed instead. (But never do this if writing
552 * to a pipe, and don't bother if we did a raw copy.) */
553 if (out_res_entry->size > out_res_entry->original_size &&
554 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
555 WIMLIB_READ_RESOURCE_FLAG_RAW)))
557 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
558 "writing uncompressed instead",
559 out_res_entry->original_size, out_res_entry->size);
560 ret = seek_and_truncate(out_fd, res_start_offset);
562 goto out_free_chunk_tab;
563 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
564 FREE(write_ctx.chunk_tab);
565 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
566 write_ctx.chunk_tab = NULL;
567 write_ctx.doing_sha = false;
568 goto try_write_again;
570 if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
571 DEBUG("Copied raw compressed data "
572 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
573 out_res_entry->original_size, out_res_entry->size,
574 out_res_entry->offset, out_res_entry->flags);
575 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
576 DEBUG("Wrote compressed resource "
577 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
578 out_res_entry->original_size, out_res_entry->size,
579 out_res_entry->offset, out_res_entry->flags);
581 DEBUG("Wrote uncompressed resource "
582 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
583 out_res_entry->original_size,
584 out_res_entry->offset, out_res_entry->flags);
588 FREE(write_ctx.chunk_tab);
593 /* Like write_wim_resource(), but the resource is specified by a buffer of
594 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
595 * the buffer to @hash_ret. */
597 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
598 int reshdr_flags, struct filedes *out_fd,
601 struct resource_entry *out_res_entry,
602 u8 *hash_ret, int write_resource_flags,
603 struct wimlib_lzx_context **comp_ctx)
605 /* Set up a temporary lookup table entry to provide to
606 * write_wim_resource(). */
607 struct wim_lookup_table_entry lte;
610 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
611 lte.attached_buffer = (void*)buf;
612 lte.resource_entry.original_size = buf_size;
613 lte.resource_entry.flags = reshdr_flags;
614 lte.compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
616 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
617 sha1_buffer(buf, buf_size, lte.hash);
623 ret = write_wim_resource(<e, out_fd, out_ctype, out_chunk_size,
624 out_res_entry, write_resource_flags, comp_ctx);
628 copy_hash(hash_ret, lte.hash);
633 #ifdef ENABLE_MULTITHREADED_COMPRESSION
635 /* Blocking shared queue (solves the producer-consumer problem) */
636 struct shared_queue {
640 unsigned filled_slots;
642 pthread_mutex_t lock;
643 pthread_cond_t msg_avail_cond;
644 pthread_cond_t space_avail_cond;
648 shared_queue_init(struct shared_queue *q, unsigned size)
650 wimlib_assert(size != 0);
651 q->array = CALLOC(sizeof(q->array[0]), size);
658 if (pthread_mutex_init(&q->lock, NULL)) {
659 ERROR_WITH_ERRNO("Failed to initialize mutex");
662 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
663 ERROR_WITH_ERRNO("Failed to initialize condition variable");
664 goto err_destroy_lock;
666 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
667 ERROR_WITH_ERRNO("Failed to initialize condition variable");
668 goto err_destroy_msg_avail_cond;
671 err_destroy_msg_avail_cond:
672 pthread_cond_destroy(&q->msg_avail_cond);
674 pthread_mutex_destroy(&q->lock);
676 return WIMLIB_ERR_NOMEM;
680 shared_queue_destroy(struct shared_queue *q)
683 pthread_mutex_destroy(&q->lock);
684 pthread_cond_destroy(&q->msg_avail_cond);
685 pthread_cond_destroy(&q->space_avail_cond);
689 shared_queue_put(struct shared_queue *q, void *obj)
691 pthread_mutex_lock(&q->lock);
692 while (q->filled_slots == q->size)
693 pthread_cond_wait(&q->space_avail_cond, &q->lock);
695 q->back = (q->back + 1) % q->size;
696 q->array[q->back] = obj;
699 pthread_cond_broadcast(&q->msg_avail_cond);
700 pthread_mutex_unlock(&q->lock);
704 shared_queue_get(struct shared_queue *q)
708 pthread_mutex_lock(&q->lock);
709 while (q->filled_slots == 0)
710 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
712 obj = q->array[q->front];
713 q->array[q->front] = NULL;
714 q->front = (q->front + 1) % q->size;
717 pthread_cond_broadcast(&q->space_avail_cond);
718 pthread_mutex_unlock(&q->lock);
722 struct compressor_thread_params {
723 struct shared_queue *res_to_compress_queue;
724 struct shared_queue *compressed_res_queue;
726 struct wimlib_lzx_context *comp_ctx;
729 #define MAX_CHUNKS_PER_MSG 2
732 struct wim_lookup_table_entry *lte;
734 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
735 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
736 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
737 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
739 struct list_head list;
745 compress_chunks(struct message *msg, int out_ctype,
746 struct wimlib_lzx_context *comp_ctx)
748 for (unsigned i = 0; i < msg->num_chunks; i++) {
751 len = compress_chunk(msg->uncompressed_chunks[i],
752 msg->uncompressed_chunk_sizes[i],
753 msg->compressed_chunks[i],
760 /* To be written compressed */
761 out_chunk = msg->compressed_chunks[i];
764 /* To be written uncompressed */
765 out_chunk = msg->uncompressed_chunks[i];
766 out_len = msg->uncompressed_chunk_sizes[i];
768 msg->out_chunks[i].iov_base = out_chunk;
769 msg->out_chunks[i].iov_len = out_len;
773 /* Compressor thread routine. This is a lot simpler than the main thread
774 * routine: just repeatedly get a group of chunks from the
775 * res_to_compress_queue, compress them, and put them in the
776 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
779 compressor_thread_proc(void *arg)
781 struct compressor_thread_params *params = arg;
782 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
783 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
786 DEBUG("Compressor thread ready");
787 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
788 compress_chunks(msg, params->out_ctype, params->comp_ctx);
789 shared_queue_put(compressed_res_queue, msg);
791 DEBUG("Compressor thread terminating");
794 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
796 struct write_streams_progress_data {
797 wimlib_progress_func_t progress_func;
798 union wimlib_progress_info progress;
799 uint64_t next_progress;
800 WIMStruct *prev_wim_part;
804 do_write_streams_progress(struct write_streams_progress_data *progress_data,
805 struct wim_lookup_table_entry *lte,
806 bool stream_discarded)
808 union wimlib_progress_info *progress = &progress_data->progress;
811 if (stream_discarded) {
812 progress->write_streams.total_bytes -= wim_resource_size(lte);
813 if (progress_data->next_progress != ~(uint64_t)0 &&
814 progress_data->next_progress > progress->write_streams.total_bytes)
816 progress_data->next_progress = progress->write_streams.total_bytes;
819 progress->write_streams.completed_bytes += wim_resource_size(lte);
821 new_wim_part = false;
822 if (lte->resource_location == RESOURCE_IN_WIM &&
823 lte->wim != progress_data->prev_wim_part)
825 if (progress_data->prev_wim_part) {
827 progress->write_streams.completed_parts++;
829 progress_data->prev_wim_part = lte->wim;
831 progress->write_streams.completed_streams++;
832 if (progress_data->progress_func
833 && (progress->write_streams.completed_bytes >= progress_data->next_progress
836 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
838 if (progress_data->next_progress == progress->write_streams.total_bytes) {
839 progress_data->next_progress = ~(uint64_t)0;
841 progress_data->next_progress =
842 min(progress->write_streams.total_bytes,
843 progress->write_streams.completed_bytes +
844 progress->write_streams.total_bytes / 100);
849 struct serial_write_stream_ctx {
850 struct filedes *out_fd;
853 struct wimlib_lzx_context **comp_ctx;
854 int write_resource_flags;
858 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
860 struct serial_write_stream_ctx *ctx = _ctx;
861 return write_wim_resource(lte, ctx->out_fd,
864 <e->output_resource_entry,
865 ctx->write_resource_flags,
870 /* Write a list of streams, taking into account that some streams may be
871 * duplicates that are checksummed and discarded on the fly, and also delegating
872 * the actual writing of a stream to a function @write_stream_cb, which is
873 * passed the context @write_stream_ctx. */
875 do_write_stream_list(struct list_head *stream_list,
876 struct wim_lookup_table *lookup_table,
877 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
878 void *write_stream_ctx,
879 struct write_streams_progress_data *progress_data)
882 struct wim_lookup_table_entry *lte;
883 bool stream_discarded;
885 /* For each stream in @stream_list ... */
886 while (!list_empty(stream_list)) {
887 stream_discarded = false;
888 lte = container_of(stream_list->next,
889 struct wim_lookup_table_entry,
891 list_del(<e->write_streams_list);
892 if (lte->unhashed && !lte->unique_size) {
893 /* Unhashed stream that shares a size with some other
894 * stream in the WIM we are writing. The stream must be
895 * checksummed to know if we need to write it or not. */
896 struct wim_lookup_table_entry *tmp;
897 u32 orig_out_refcnt = lte->out_refcnt;
899 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
903 /* We found a duplicate stream. 'lte' was
904 * freed, so replace it with the duplicate. */
907 /* 'out_refcnt' was transferred to the
908 * duplicate, and we can detect if the duplicate
909 * stream was already referenced for writing by
910 * checking if its 'out_refcnt' is higher than
911 * that of the original stream. In such cases,
912 * the current stream can be discarded. We can
913 * also discard the current stream if it was
914 * previously marked as filtered (e.g. already
915 * present in the WIM being written). */
916 if (lte->out_refcnt > orig_out_refcnt ||
918 DEBUG("Discarding duplicate stream of "
920 wim_resource_size(lte));
921 lte->no_progress = 0;
922 stream_discarded = true;
923 goto skip_to_progress;
928 /* Here, @lte is either a hashed stream or an unhashed stream
929 * with a unique size. In either case we know that the stream
930 * has to be written. In either case the SHA1 message digest
931 * will be calculated over the stream while writing it; however,
932 * in the former case this is done merely to check the data,
933 * while in the latter case this is done because we do not have
934 * the SHA1 message digest yet. */
935 wimlib_assert(lte->out_refcnt != 0);
937 lte->no_progress = 0;
938 ret = (*write_stream_cb)(lte, write_stream_ctx);
941 /* In parallel mode, some streams are deferred for later,
942 * serialized processing; ignore them here. */
946 list_del(<e->unhashed_list);
947 lookup_table_insert(lookup_table, lte);
951 if (!lte->no_progress) {
952 do_write_streams_progress(progress_data,
953 lte, stream_discarded);
960 do_write_stream_list_serial(struct list_head *stream_list,
961 struct wim_lookup_table *lookup_table,
962 struct filedes *out_fd,
965 struct wimlib_lzx_context **comp_ctx,
966 int write_resource_flags,
967 struct write_streams_progress_data *progress_data)
969 struct serial_write_stream_ctx ctx = {
971 .out_ctype = out_ctype,
972 .out_chunk_size = out_chunk_size,
973 .write_resource_flags = write_resource_flags,
974 .comp_ctx = comp_ctx,
976 return do_write_stream_list(stream_list,
984 write_flags_to_resource_flags(int write_flags)
986 int resource_flags = 0;
988 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
989 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
990 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
991 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
992 return resource_flags;
996 write_stream_list_serial(struct list_head *stream_list,
997 struct wim_lookup_table *lookup_table,
998 struct filedes *out_fd,
1001 struct wimlib_lzx_context **comp_ctx,
1002 int write_resource_flags,
1003 struct write_streams_progress_data *progress_data)
1005 union wimlib_progress_info *progress = &progress_data->progress;
1006 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
1007 progress->write_streams.total_streams);
1008 progress->write_streams.num_threads = 1;
1009 if (progress_data->progress_func) {
1010 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1013 return do_write_stream_list_serial(stream_list,
1019 write_resource_flags,
1023 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1025 write_wim_chunks(struct message *msg, struct filedes *out_fd,
1026 struct chunk_table *chunk_tab,
1027 int write_resource_flags)
1030 struct pwm_chunk_hdr *chunk_hdrs;
1034 for (unsigned i = 0; i < msg->num_chunks; i++)
1035 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1037 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1038 nvecs = msg->num_chunks;
1039 vecs = msg->out_chunks;
1041 /* Special case: If writing a compressed resource to a pipable
1042 * WIM, prefix each compressed chunk with a header that gives
1043 * its compressed size. */
1044 nvecs = msg->num_chunks * 2;
1045 vecs = alloca(nvecs * sizeof(vecs[0]));
1046 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1048 for (unsigned i = 0; i < msg->num_chunks; i++) {
1049 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1050 vecs[i * 2].iov_base = &chunk_hdrs[i];
1051 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1052 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1053 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1056 ret = full_writev(out_fd, vecs, nvecs);
1058 ERROR_WITH_ERRNO("Failed to write WIM chunks");
1062 struct main_writer_thread_ctx {
1063 struct list_head *stream_list;
1064 struct wim_lookup_table *lookup_table;
1065 struct filedes *out_fd;
1066 off_t res_start_offset;
1069 struct wimlib_lzx_context **comp_ctx;
1070 int write_resource_flags;
1071 struct shared_queue *res_to_compress_queue;
1072 struct shared_queue *compressed_res_queue;
1073 size_t num_messages;
1074 struct write_streams_progress_data *progress_data;
1076 struct list_head available_msgs;
1077 struct list_head outstanding_streams;
1078 struct list_head serial_streams;
1079 size_t num_outstanding_messages;
1081 SHA_CTX next_sha_ctx;
1083 u64 next_num_chunks;
1084 struct wim_lookup_table_entry *next_lte;
1086 struct message *msgs;
1087 struct message *next_msg;
1088 struct chunk_table *cur_chunk_tab;
1092 init_message(struct message *msg, u32 out_chunk_size)
1094 msg->out_chunk_size = out_chunk_size;
1095 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1096 msg->compressed_chunks[i] = MALLOC(out_chunk_size);
1097 msg->uncompressed_chunks[i] = MALLOC(out_chunk_size);
1098 if (msg->compressed_chunks[i] == NULL ||
1099 msg->uncompressed_chunks[i] == NULL)
1100 return WIMLIB_ERR_NOMEM;
1106 destroy_message(struct message *msg)
1108 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1109 FREE(msg->compressed_chunks[i]);
1110 FREE(msg->uncompressed_chunks[i]);
1115 free_messages(struct message *msgs, size_t num_messages)
1118 for (size_t i = 0; i < num_messages; i++)
1119 destroy_message(&msgs[i]);
1124 static struct message *
1125 allocate_messages(size_t num_messages, u32 out_chunk_size)
1127 struct message *msgs;
1129 msgs = CALLOC(num_messages, sizeof(struct message));
1132 for (size_t i = 0; i < num_messages; i++) {
1133 if (init_message(&msgs[i], out_chunk_size)) {
1134 free_messages(msgs, num_messages);
1142 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1144 while (ctx->num_outstanding_messages--)
1145 shared_queue_get(ctx->compressed_res_queue);
1146 free_messages(ctx->msgs, ctx->num_messages);
1147 FREE(ctx->cur_chunk_tab);
1151 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1153 /* Pre-allocate all the buffers that will be needed to do the chunk
1155 ctx->msgs = allocate_messages(ctx->num_messages, ctx->out_chunk_size);
1157 return WIMLIB_ERR_NOMEM;
1159 /* Initially, all the messages are available to use. */
1160 INIT_LIST_HEAD(&ctx->available_msgs);
1161 for (size_t i = 0; i < ctx->num_messages; i++)
1162 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1164 /* outstanding_streams is the list of streams that currently have had
1165 * chunks sent off for compression.
1167 * The first stream in outstanding_streams is the stream that is
1168 * currently being written.
1170 * The last stream in outstanding_streams is the stream that is
1171 * currently being read and having chunks fed to the compressor threads.
1173 INIT_LIST_HEAD(&ctx->outstanding_streams);
1174 ctx->num_outstanding_messages = 0;
1176 ctx->next_msg = NULL;
1178 /* Resources that don't need any chunks compressed are added to this
1179 * list and written directly by the main thread. */
1180 INIT_LIST_HEAD(&ctx->serial_streams);
1182 ctx->cur_chunk_tab = NULL;
1188 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1190 struct message *msg;
1191 struct wim_lookup_table_entry *cur_lte;
1194 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1195 wimlib_assert(ctx->num_outstanding_messages != 0);
1197 cur_lte = container_of(ctx->outstanding_streams.next,
1198 struct wim_lookup_table_entry,
1199 being_compressed_list);
1201 /* Get the next message from the queue and process it.
1202 * The message will contain 1 or more data chunks that have been
1204 msg = shared_queue_get(ctx->compressed_res_queue);
1205 msg->complete = true;
1206 --ctx->num_outstanding_messages;
1208 /* Is this the next chunk in the current resource? If it's not
1209 * (i.e., an earlier chunk in a same or different resource
1210 * hasn't been compressed yet), do nothing, and keep this
1211 * message around until all earlier chunks are received.
1213 * Otherwise, write all the chunks we can. */
1214 while (cur_lte != NULL &&
1215 !list_empty(&cur_lte->msg_list)
1216 && (msg = container_of(cur_lte->msg_list.next,
1220 list_move(&msg->list, &ctx->available_msgs);
1221 if (msg->begin_chunk == 0) {
1222 /* First set of chunks. */
1224 /* Write pipable WIM stream header if needed. */
1225 if (ctx->write_resource_flags &
1226 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1228 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1229 WIM_RESHDR_FLAG_COMPRESSED);
1234 /* Save current offset. */
1235 ctx->res_start_offset = ctx->out_fd->offset;
1237 /* Begin building the chunk table, and leave space for
1239 ret = begin_wim_resource_chunk_tab(cur_lte,
1241 ctx->out_chunk_size,
1242 &ctx->cur_chunk_tab,
1243 ctx->write_resource_flags);
1249 /* Write the compressed chunks from the message. */
1250 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1251 ctx->write_resource_flags);
1255 /* Was this the last chunk of the stream? If so, finish
1257 if (list_empty(&cur_lte->msg_list) &&
1258 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1262 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1264 ctx->res_start_offset,
1265 ctx->write_resource_flags);
1269 list_del(&cur_lte->being_compressed_list);
1271 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1273 FREE(ctx->cur_chunk_tab);
1274 ctx->cur_chunk_tab = NULL;
1276 /* Check for resources compressed to greater than or
1277 * equal to their original size and write them
1278 * uncompressed instead. (But never do this if writing
1280 if (res_csize >= wim_resource_size(cur_lte) &&
1281 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1283 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1284 "writing uncompressed instead",
1285 wim_resource_size(cur_lte), res_csize);
1286 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1289 ret = write_wim_resource(cur_lte,
1291 WIMLIB_COMPRESSION_TYPE_NONE,
1293 &cur_lte->output_resource_entry,
1294 ctx->write_resource_flags,
1299 cur_lte->output_resource_entry.size =
1302 cur_lte->output_resource_entry.original_size =
1303 cur_lte->resource_entry.original_size;
1305 cur_lte->output_resource_entry.offset =
1306 ctx->res_start_offset;
1308 cur_lte->output_resource_entry.flags =
1309 cur_lte->resource_entry.flags |
1310 WIM_RESHDR_FLAG_COMPRESSED;
1312 DEBUG("Wrote compressed resource "
1313 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1314 cur_lte->output_resource_entry.original_size,
1315 cur_lte->output_resource_entry.size,
1316 cur_lte->output_resource_entry.offset,
1317 cur_lte->output_resource_entry.flags);
1320 do_write_streams_progress(ctx->progress_data,
1323 /* Since we just finished writing a stream, write any
1324 * streams that have been added to the serial_streams
1325 * list for direct writing by the main thread (e.g.
1326 * resources that don't need to be compressed because
1327 * the desired compression type is the same as the
1328 * previous compression type). */
1329 if (!list_empty(&ctx->serial_streams)) {
1330 ret = do_write_stream_list_serial(&ctx->serial_streams,
1334 ctx->out_chunk_size,
1336 ctx->write_resource_flags,
1337 ctx->progress_data);
1342 /* Advance to the next stream to write. */
1343 if (list_empty(&ctx->outstanding_streams)) {
1346 cur_lte = container_of(ctx->outstanding_streams.next,
1347 struct wim_lookup_table_entry,
1348 being_compressed_list);
1355 /* Called when the main thread has read a new chunk of data. */
1357 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1359 struct main_writer_thread_ctx *ctx = _ctx;
1361 struct message *next_msg;
1362 u64 next_chunk_in_msg;
1364 /* Update SHA1 message digest for the stream currently being read by the
1366 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1368 /* We send chunks of data to the compressor chunks in batches which we
1369 * refer to as "messages". @next_msg is the message that is currently
1370 * being prepared to send off. If it is NULL, that indicates that we
1371 * need to start a new message. */
1372 next_msg = ctx->next_msg;
1374 /* We need to start a new message. First check to see if there
1375 * is a message available in the list of available messages. If
1376 * so, we can just take one. If not, all the messages (there is
1377 * a fixed number of them, proportional to the number of
1378 * threads) have been sent off to the compressor threads, so we
1379 * receive messages from the compressor threads containing
1380 * compressed chunks of data.
1382 * We may need to receive multiple messages before one is
1383 * actually available to use because messages received that are
1384 * *not* for the very next set of chunks to compress must be
1385 * buffered until it's time to write those chunks. */
1386 while (list_empty(&ctx->available_msgs)) {
1387 ret = receive_compressed_chunks(ctx);
1392 next_msg = container_of(ctx->available_msgs.next,
1393 struct message, list);
1394 list_del(&next_msg->list);
1395 next_msg->complete = false;
1396 next_msg->begin_chunk = ctx->next_chunk;
1397 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1398 ctx->next_num_chunks - ctx->next_chunk);
1399 ctx->next_msg = next_msg;
1402 /* Fill in the next chunk to compress */
1403 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1405 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1406 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1409 if (++next_chunk_in_msg == next_msg->num_chunks) {
1410 /* Send off an array of chunks to compress */
1411 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1412 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1413 ++ctx->num_outstanding_messages;
1414 ctx->next_msg = NULL;
1420 main_writer_thread_finish(void *_ctx)
1422 struct main_writer_thread_ctx *ctx = _ctx;
1424 while (ctx->num_outstanding_messages != 0) {
1425 ret = receive_compressed_chunks(ctx);
1429 wimlib_assert(list_empty(&ctx->outstanding_streams));
1430 return do_write_stream_list_serial(&ctx->serial_streams,
1434 ctx->out_chunk_size,
1436 ctx->write_resource_flags,
1437 ctx->progress_data);
1441 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1442 struct main_writer_thread_ctx *ctx)
1446 /* Read the entire stream @lte, feeding its data chunks to the
1447 * compressor threads. Also SHA1-sum the stream; this is required in
1448 * the case that @lte is unhashed, and a nice additional verification
1449 * when @lte is already hashed. */
1450 sha1_init(&ctx->next_sha_ctx);
1451 ctx->next_chunk = 0;
1452 ctx->next_num_chunks = DIV_ROUND_UP(wim_resource_size(lte),
1453 ctx->out_chunk_size);
1454 ctx->next_lte = lte;
1455 INIT_LIST_HEAD(<e->msg_list);
1456 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1457 ret = read_resource_prefix(lte, wim_resource_size(lte),
1458 main_writer_thread_cb,
1459 ctx->out_chunk_size, ctx, 0);
1462 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1463 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1467 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1469 struct main_writer_thread_ctx *ctx = _ctx;
1472 if (wim_resource_size(lte) < 1000 ||
1473 !must_compress_stream(lte, ctx->write_resource_flags,
1474 ctx->out_ctype, ctx->out_chunk_size))
1476 /* Stream is too small or isn't being compressed. Process it by
1477 * the main thread when we have a chance. We can't necessarily
1478 * process it right here, as the main thread could be in the
1479 * middle of writing a different stream. */
1480 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1484 ret = submit_stream_for_compression(lte, ctx);
1486 lte->no_progress = 1;
1491 get_default_num_threads(void)
1494 return win32_get_number_of_processors();
1496 return sysconf(_SC_NPROCESSORS_ONLN);
1500 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1501 * parameter and will perform compression using that many threads. Falls
1502 * back to write_stream_list_serial() on certain errors, such as a failure to
1503 * create the number of threads requested.
1505 * High level description of the algorithm for writing compressed streams in
1506 * parallel: We perform compression on chunks rather than on full files. The
1507 * currently executing thread becomes the main thread and is entirely in charge
1508 * of reading the data to compress (which may be in any location understood by
1509 * the resource code--- such as in an external file being captured, or in
1510 * another WIM file from which an image is being exported) and actually writing
1511 * the compressed data to the output file. Additional threads are "compressor
1512 * threads" and all execute the compressor_thread_proc, where they repeatedly
1513 * retrieve buffers of data from the main thread, compress them, and hand them
1514 * back to the main thread.
1516 * Certain streams, such as streams that do not need to be compressed (e.g.
1517 * input compression type same as output compression type) or streams of very
1518 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1519 * handled entirely by the main thread at an appropriate time.
1521 * At any given point in time, multiple streams may be having chunks compressed
1522 * concurrently. The stream that the main thread is currently *reading* may be
1523 * later in the list that the stream that the main thread is currently
1527 write_stream_list_parallel(struct list_head *stream_list,
1528 struct wim_lookup_table *lookup_table,
1529 struct filedes *out_fd,
1532 struct wimlib_lzx_context **comp_ctx,
1533 int write_resource_flags,
1534 struct write_streams_progress_data *progress_data,
1535 unsigned num_threads)
1538 struct shared_queue res_to_compress_queue;
1539 struct shared_queue compressed_res_queue;
1540 pthread_t *compressor_threads = NULL;
1541 union wimlib_progress_info *progress = &progress_data->progress;
1543 if (num_threads == 0) {
1544 long nthreads = get_default_num_threads();
1545 if (nthreads < 1 || nthreads > UINT_MAX) {
1546 WARNING("Could not determine number of processors! Assuming 1");
1548 } else if (nthreads == 1) {
1549 goto out_serial_quiet;
1551 num_threads = nthreads;
1555 DEBUG("Writing stream list of size %"PRIu64" "
1556 "(parallel version, num_threads=%u)",
1557 progress->write_streams.total_streams, num_threads);
1559 progress->write_streams.num_threads = num_threads;
1561 static const size_t MESSAGES_PER_THREAD = 2;
1562 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1564 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1566 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1570 ret = shared_queue_init(&compressed_res_queue, queue_size);
1572 goto out_destroy_res_to_compress_queue;
1574 struct compressor_thread_params *params;
1576 params = CALLOC(num_threads, sizeof(params[0]));
1577 if (params == NULL) {
1578 ret = WIMLIB_ERR_NOMEM;
1579 goto out_destroy_compressed_res_queue;
1582 for (unsigned i = 0; i < num_threads; i++) {
1583 params[i].res_to_compress_queue = &res_to_compress_queue;
1584 params[i].compressed_res_queue = &compressed_res_queue;
1585 params[i].out_ctype = out_ctype;
1586 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1587 ret = wimlib_lzx_alloc_context(NULL, ¶ms[i].comp_ctx);
1589 goto out_free_params;
1593 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1594 if (!compressor_threads) {
1595 ret = WIMLIB_ERR_NOMEM;
1596 goto out_free_params;
1599 for (unsigned i = 0; i < num_threads; i++) {
1600 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1601 ret = pthread_create(&compressor_threads[i], NULL,
1602 compressor_thread_proc, ¶ms[i]);
1605 ERROR_WITH_ERRNO("Failed to create compressor "
1607 i + 1, num_threads);
1613 if (progress_data->progress_func) {
1614 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1618 struct main_writer_thread_ctx ctx;
1619 ctx.stream_list = stream_list;
1620 ctx.lookup_table = lookup_table;
1621 ctx.out_fd = out_fd;
1622 ctx.out_ctype = out_ctype;
1623 ctx.out_chunk_size = out_chunk_size;
1624 ctx.comp_ctx = comp_ctx;
1625 ctx.res_to_compress_queue = &res_to_compress_queue;
1626 ctx.compressed_res_queue = &compressed_res_queue;
1627 ctx.num_messages = queue_size;
1628 ctx.write_resource_flags = write_resource_flags;
1629 ctx.progress_data = progress_data;
1630 ret = main_writer_thread_init_ctx(&ctx);
1633 ret = do_write_stream_list(stream_list, lookup_table,
1634 main_thread_process_next_stream,
1635 &ctx, progress_data);
1637 goto out_destroy_ctx;
1639 /* The main thread has finished reading all streams that are going to be
1640 * compressed in parallel, and it now needs to wait for all remaining
1641 * chunks to be compressed so that the remaining streams can actually be
1642 * written to the output file. Furthermore, any remaining streams that
1643 * had processing deferred to the main thread need to be handled. These
1644 * tasks are done by the main_writer_thread_finish() function. */
1645 ret = main_writer_thread_finish(&ctx);
1647 main_writer_thread_destroy_ctx(&ctx);
1649 for (unsigned i = 0; i < num_threads; i++)
1650 shared_queue_put(&res_to_compress_queue, NULL);
1652 for (unsigned i = 0; i < num_threads; i++) {
1653 if (pthread_join(compressor_threads[i], NULL)) {
1654 WARNING_WITH_ERRNO("Failed to join compressor "
1656 i + 1, num_threads);
1659 FREE(compressor_threads);
1661 for (unsigned i = 0; i < num_threads; i++)
1662 wimlib_lzx_free_context(params[i].comp_ctx);
1664 out_destroy_compressed_res_queue:
1665 shared_queue_destroy(&compressed_res_queue);
1666 out_destroy_res_to_compress_queue:
1667 shared_queue_destroy(&res_to_compress_queue);
1668 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1671 WARNING("Falling back to single-threaded compression");
1673 return write_stream_list_serial(stream_list,
1679 write_resource_flags,
1686 * Write a list of streams to a WIM (@out_fd) using the compression type
1687 * @out_ctype and up to @num_threads compressor threads.
1690 write_stream_list(struct list_head *stream_list,
1691 struct wim_lookup_table *lookup_table,
1692 struct filedes *out_fd, int out_ctype,
1694 struct wimlib_lzx_context **comp_ctx,
1696 unsigned num_threads, wimlib_progress_func_t progress_func)
1698 struct wim_lookup_table_entry *lte;
1699 size_t num_streams = 0;
1700 u64 total_bytes = 0;
1701 u64 total_compression_bytes = 0;
1702 struct write_streams_progress_data progress_data;
1704 int write_resource_flags;
1705 unsigned total_parts = 0;
1706 WIMStruct *prev_wim_part = NULL;
1708 if (list_empty(stream_list)) {
1709 DEBUG("No streams to write.");
1713 write_resource_flags = write_flags_to_resource_flags(write_flags);
1715 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1716 out_fd->offset, write_resource_flags);
1718 sort_stream_list_by_sequential_order(stream_list,
1719 offsetof(struct wim_lookup_table_entry,
1720 write_streams_list));
1722 /* Calculate the total size of the streams to be written. Note: this
1723 * will be the uncompressed size, as we may not know the compressed size
1724 * yet, and also this will assume that every unhashed stream will be
1725 * written (which will not necessarily be the case). */
1726 list_for_each_entry(lte, stream_list, write_streams_list) {
1728 total_bytes += wim_resource_size(lte);
1729 if (must_compress_stream(lte, write_resource_flags,
1730 out_ctype, out_chunk_size))
1731 total_compression_bytes += wim_resource_size(lte);
1732 if (lte->resource_location == RESOURCE_IN_WIM) {
1733 if (prev_wim_part != lte->wim) {
1734 prev_wim_part = lte->wim;
1740 memset(&progress_data, 0, sizeof(progress_data));
1741 progress_data.progress_func = progress_func;
1743 progress_data.progress.write_streams.total_bytes = total_bytes;
1744 progress_data.progress.write_streams.total_streams = num_streams;
1745 progress_data.progress.write_streams.completed_bytes = 0;
1746 progress_data.progress.write_streams.completed_streams = 0;
1747 progress_data.progress.write_streams.num_threads = num_threads;
1748 progress_data.progress.write_streams.compression_type = out_ctype;
1749 progress_data.progress.write_streams.total_parts = total_parts;
1750 progress_data.progress.write_streams.completed_parts = 0;
1752 progress_data.next_progress = 0;
1753 progress_data.prev_wim_part = NULL;
1755 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1756 if (total_compression_bytes >= 2000000 && num_threads != 1)
1757 ret = write_stream_list_parallel(stream_list,
1763 write_resource_flags,
1768 ret = write_stream_list_serial(stream_list,
1774 write_resource_flags,
1777 DEBUG("Successfully wrote stream list.");
1779 DEBUG("Failed to write stream list.");
1783 struct stream_size_table {
1784 struct hlist_head *array;
1790 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1792 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1794 return WIMLIB_ERR_NOMEM;
1795 tab->num_entries = 0;
1796 tab->capacity = capacity;
1801 destroy_stream_size_table(struct stream_size_table *tab)
1807 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1809 struct stream_size_table *tab = _tab;
1811 struct wim_lookup_table_entry *same_size_lte;
1812 struct hlist_node *tmp;
1814 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1815 lte->unique_size = 1;
1816 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1817 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1818 lte->unique_size = 0;
1819 same_size_lte->unique_size = 0;
1824 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1829 struct find_streams_ctx {
1832 struct list_head stream_list;
1833 struct stream_size_table stream_size_tab;
1837 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1838 struct find_streams_ctx *ctx,
1841 if (lte->out_refcnt == 0) {
1842 stream_size_table_insert(lte, &ctx->stream_size_tab);
1843 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1845 lte->out_refcnt += nref;
1849 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1852 struct find_streams_ctx *ctx = _ctx;
1853 lte->out_refcnt = 0;
1854 lte_reference_for_logical_write(lte, ctx,
1855 (lte->refcnt ? lte->refcnt : 1));
1860 inode_find_streams_to_write(struct wim_inode *inode,
1861 struct wim_lookup_table *table,
1862 struct find_streams_ctx *ctx)
1864 struct wim_lookup_table_entry *lte;
1867 for (i = 0; i <= inode->i_num_ads; i++) {
1868 lte = inode_stream_lte(inode, i, table);
1870 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1871 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1872 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1878 image_find_streams_to_write(WIMStruct *wim)
1880 struct find_streams_ctx *ctx;
1881 struct wim_image_metadata *imd;
1882 struct wim_inode *inode;
1883 struct wim_lookup_table_entry *lte;
1887 imd = wim_get_current_image_metadata(wim);
1889 image_for_each_unhashed_stream(lte, imd)
1890 lte->out_refcnt = 0;
1892 /* Go through this image's inodes to find any streams that have not been
1894 image_for_each_inode(inode, imd) {
1895 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1903 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1904 * the "logical write" of the WIM, meaning all streams that are referenced at
1905 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1906 * each stream being included in the logical write is set to the number of
1907 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1908 * stream being included in the logical write is set to indicate whether that
1909 * stream has a unique size relative to the streams being included in the
1910 * logical write. Still furthermore, 'part_number' on each stream being
1911 * included in the logical write is set to the part number given in the
1912 * in-memory header of @p wim.
1914 * This is considered a "logical write" because it does not take into account
1915 * filtering out streams already present in the WIM (in the case of an in place
1916 * overwrite) or present in other WIMs (in case of creating delta WIM).
1919 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1920 struct find_streams_ctx *ctx)
1923 struct wim_lookup_table_entry *lte;
1925 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1926 (image == 1 && wim->hdr.image_count == 1)))
1928 /* Fast case: Assume that all streams are being written and
1929 * that the reference counts are correct. */
1930 struct wim_lookup_table_entry *lte;
1931 struct wim_image_metadata *imd;
1934 for_lookup_table_entry(wim->lookup_table,
1935 do_lte_full_reference_for_logical_write, ctx);
1936 for (i = 0; i < wim->hdr.image_count; i++) {
1937 imd = wim->image_metadata[i];
1938 image_for_each_unhashed_stream(lte, imd)
1939 do_lte_full_reference_for_logical_write(lte, ctx);
1942 /* Slow case: Walk through the images being written and
1943 * determine the streams referenced. */
1944 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1946 ret = for_image(wim, image, image_find_streams_to_write);
1951 list_for_each_entry(lte, &ctx->stream_list, write_streams_list)
1952 lte->part_number = wim->hdr.part_number;
1957 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1959 struct find_streams_ctx *ctx = _ctx;
1962 /* Calculate and set lte->filtered. */
1963 if (lte->resource_location == RESOURCE_IN_WIM) {
1964 if (lte->wim == ctx->wim &&
1965 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1966 filtered |= FILTERED_SAME_WIM;
1967 if (lte->wim != ctx->wim &&
1968 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1969 filtered |= FILTERED_EXTERNAL_WIM;
1971 lte->filtered = filtered;
1973 /* Filtered streams get inserted into the stream size table too, unless
1974 * they already were. This is because streams that are checksummed
1975 * on-the-fly during the write should not be written if they are
1976 * duplicates of filtered stream. */
1977 if (lte->filtered && lte->out_refcnt == 0)
1978 stream_size_table_insert(lte, &ctx->stream_size_tab);
1983 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
1989 /* Given the list of streams to include in a logical write of a WIM, handle
1990 * filtering out streams already present in the WIM or already present in
1991 * external WIMs, depending on the write flags provided. */
1993 handle_stream_filtering(struct find_streams_ctx *ctx)
1995 struct wim_lookup_table_entry *lte, *tmp;
1997 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
1998 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2000 for_lookup_table_entry(ctx->wim->lookup_table,
2001 mark_stream_not_filtered, ctx);
2005 for_lookup_table_entry(ctx->wim->lookup_table,
2006 process_filtered_stream, ctx);
2008 /* Streams in logical write list that were filtered can be removed. */
2009 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2012 list_del(<e->write_streams_list);
2015 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2016 * around prepare_logical_stream_list() to handle filtering out streams already
2017 * present in the WIM or already present in external WIMs, depending on the
2018 * write flags provided.
2020 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2022 * - 'out_refcnt' is set to the number of references found for the logical write.
2023 * This will be nonzero on all streams in the list returned by this function,
2024 * but will also be nonzero on streams not in the list that were included in
2025 * the logical write list, but filtered out from the returned list.
2026 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2027 * are not included in the list of streams returned by this function.
2028 * - 'unique_size' is set if the stream has a unique size among all streams in
2029 * the logical write plus any filtered streams in the entire WIM that could
2030 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2031 * stream being written.
2034 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2035 struct list_head *stream_list)
2039 struct find_streams_ctx ctx;
2041 INIT_LIST_HEAD(&ctx.stream_list);
2042 ret = init_stream_size_table(&ctx.stream_size_tab,
2043 wim->lookup_table->capacity);
2046 ctx.write_flags = write_flags;
2049 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2051 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2053 goto out_destroy_table;
2055 handle_stream_filtering(&ctx);
2056 list_transfer(&ctx.stream_list, stream_list);
2059 destroy_stream_size_table(&ctx.stream_size_tab);
2064 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2065 unsigned num_threads,
2066 wimlib_progress_func_t progress_func,
2067 struct list_head *stream_list_override)
2070 struct list_head _stream_list;
2071 struct list_head *stream_list;
2072 struct wim_lookup_table_entry *lte;
2074 if (stream_list_override == NULL) {
2075 /* Normal case: prepare stream list from image(s) being written.
2077 stream_list = &_stream_list;
2078 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2082 /* Currently only as a result of wimlib_split() being called:
2083 * use stream list already explicitly provided. Use existing
2084 * reference counts. */
2085 stream_list = stream_list_override;
2086 list_for_each_entry(lte, stream_list, write_streams_list) {
2087 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2088 lte->part_number = wim->hdr.part_number;
2092 return write_stream_list(stream_list,
2095 wim->out_compression_type,
2096 wim->out_chunk_size,
2104 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2105 wimlib_progress_func_t progress_func)
2110 int write_resource_flags;
2112 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2113 DEBUG("Not writing any metadata resources.");
2117 write_resource_flags = write_flags_to_resource_flags(write_flags);
2119 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2120 wim->out_fd.offset);
2123 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2125 if (image == WIMLIB_ALL_IMAGES) {
2127 end_image = wim->hdr.image_count;
2129 start_image = image;
2133 for (int i = start_image; i <= end_image; i++) {
2134 struct wim_image_metadata *imd;
2136 imd = wim->image_metadata[i - 1];
2137 /* Build a new metadata resource only if image was modified from
2138 * the original (or was newly added). Otherwise just copy the
2140 if (imd->modified) {
2141 DEBUG("Image %u was modified; building and writing new "
2142 "metadata resource", i);
2143 ret = write_metadata_resource(wim, i,
2144 write_resource_flags);
2145 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2146 DEBUG("Image %u was not modified; re-using existing "
2147 "metadata resource.", i);
2148 copy_resource_entry(&imd->metadata_lte->output_resource_entry,
2149 &imd->metadata_lte->resource_entry);
2152 DEBUG("Image %u was not modified; copying existing "
2153 "metadata resource.", i);
2154 ret = write_wim_resource(imd->metadata_lte,
2156 wim->out_compression_type,
2157 wim->out_chunk_size,
2158 &imd->metadata_lte->output_resource_entry,
2159 write_resource_flags,
2166 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2171 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2174 DEBUG("Opening \"%"TS"\" for writing.", path);
2176 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2178 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2179 return WIMLIB_ERR_OPEN;
2181 filedes_init(&wim->out_fd, raw_fd);
2186 close_wim_writable(WIMStruct *wim, int write_flags)
2190 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2191 DEBUG("Closing WIM file.");
2192 if (filedes_valid(&wim->out_fd))
2193 if (filedes_close(&wim->out_fd))
2194 ret = WIMLIB_ERR_WRITE;
2196 filedes_invalidate(&wim->out_fd);
2203 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2204 * table, then overwrite the WIM header. By default, closes the WIM file
2205 * descriptor (@wim->out_fd) if successful.
2207 * write_flags is a bitwise OR of the following:
2209 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2210 * Include an integrity table.
2212 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2213 * fsync() the output file before closing it.
2215 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2216 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2217 * stream headers before the lookup table and XML data, and also
2218 * write the WIM header at the end instead of seeking to the
2219 * beginning. Can't be combined with
2220 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2222 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2223 * Don't write the lookup table.
2225 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2226 * When (if) writing the integrity table, re-use entries from the
2227 * existing integrity table, if possible.
2229 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2230 * After writing the XML data but before writing the integrity
2231 * table, write a temporary WIM header and flush the stream so that
2232 * the WIM is less likely to become corrupted upon abrupt program
2234 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2235 * Instead of overwriting the WIM header at the beginning of the
2236 * file, simply append it to the end of the file. (Used when
2238 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2239 * Do not close the file descriptor @wim->out_fd on either success
2241 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2242 * Use the existing <TOTALBYTES> stored in the in-memory XML
2243 * information, rather than setting it to the offset of the XML
2244 * data being written.
2247 finish_write(WIMStruct *wim, int image, int write_flags,
2248 wimlib_progress_func_t progress_func,
2249 struct list_head *stream_list_override)
2253 int write_resource_flags;
2254 off_t old_lookup_table_end;
2255 off_t new_lookup_table_end;
2258 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2260 write_resource_flags = write_flags_to_resource_flags(write_flags);
2262 /* In the WIM header, there is room for the resource entry for a
2263 * metadata resource labeled as the "boot metadata". This entry should
2264 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2265 * it should be a copy of the resource entry for the image that is
2266 * marked as bootable. This is not well documented... */
2267 if (wim->hdr.boot_idx == 0) {
2268 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2270 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2271 &wim->image_metadata[wim->hdr.boot_idx- 1
2272 ]->metadata_lte->output_resource_entry);
2275 /* Write lookup table. (Save old position first.) */
2276 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2277 wim->hdr.lookup_table_res_entry.size;
2278 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2279 ret = write_wim_lookup_table(wim, image, write_flags,
2280 &wim->hdr.lookup_table_res_entry,
2281 stream_list_override);
2286 /* Write XML data. */
2287 xml_totalbytes = wim->out_fd.offset;
2288 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2289 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2290 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2291 &wim->hdr.xml_res_entry,
2292 write_resource_flags);
2296 /* Write integrity table (optional). */
2297 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2298 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2299 struct wim_header checkpoint_hdr;
2300 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2301 zero_resource_entry(&checkpoint_hdr.integrity);
2302 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2303 ret = write_wim_header_at_offset(&checkpoint_hdr,
2309 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2310 old_lookup_table_end = 0;
2312 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2313 wim->hdr.lookup_table_res_entry.size;
2315 ret = write_integrity_table(wim,
2316 new_lookup_table_end,
2317 old_lookup_table_end,
2322 /* No integrity table. */
2323 zero_resource_entry(&wim->hdr.integrity);
2326 /* Now that all information in the WIM header has been determined, the
2327 * preliminary header written earlier can be overwritten, the header of
2328 * the existing WIM file can be overwritten, or the final header can be
2329 * written to the end of the pipable WIM. */
2330 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2332 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2333 hdr_offset = wim->out_fd.offset;
2334 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2335 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2339 /* Possibly sync file data to disk before closing. On POSIX systems, it
2340 * is necessary to do this before using rename() to overwrite an
2341 * existing file with a new file. Otherwise, data loss would occur if
2342 * the system is abruptly terminated when the metadata for the rename
2343 * operation has been written to disk, but the new file data has not.
2345 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2346 DEBUG("Syncing WIM file.");
2347 if (fsync(wim->out_fd.fd)) {
2348 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2349 return WIMLIB_ERR_WRITE;
2353 if (close_wim_writable(wim, write_flags)) {
2354 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2355 return WIMLIB_ERR_WRITE;
2361 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2363 lock_wim(WIMStruct *wim, int fd)
2366 if (fd != -1 && !wim->wim_locked) {
2367 ret = flock(fd, LOCK_EX | LOCK_NB);
2369 if (errno == EWOULDBLOCK) {
2370 ERROR("`%"TS"' is already being modified or has been "
2371 "mounted read-write\n"
2372 " by another process!", wim->filename);
2373 ret = WIMLIB_ERR_ALREADY_LOCKED;
2375 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2380 wim->wim_locked = 1;
2388 * write_pipable_wim():
2390 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2391 * capable of being applied from a pipe).
2393 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2394 * images can be applied from them sequentially when the file data is sent over
2395 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2396 * The modifications made to the WIM format for pipable WIMs are:
2398 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2399 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2400 * stops other software from trying to read the file as a normal WIM.
2402 * - The header at the beginning of the file does not contain all the normal
2403 * information; in particular it will have all 0's for the lookup table and
2404 * XML data resource entries. This is because this information cannot be
2405 * determined until the lookup table and XML data have been written.
2406 * Consequently, wimlib will write the full header at the very end of the
2407 * file. The header at the end, however, is only used when reading the WIM
2408 * from a seekable file (not a pipe).
2410 * - An extra copy of the XML data is placed directly after the header. This
2411 * allows image names and sizes to be determined at an appropriate time when
2412 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2413 * WIM is read from a seekable file (not a pipe).
2415 * - The format of resources, or streams, has been modified to allow them to be
2416 * used before the "lookup table" has been read. Each stream is prefixed with
2417 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2418 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2419 * uncompressed stream size, and flags that indicate whether the stream is
2420 * compressed. The data of uncompressed streams then follows literally, while
2421 * the data of compressed streams follows in a modified format. Compressed
2422 * streams do not begin with a chunk table, since the chunk table cannot be
2423 * written until all chunks have been compressed. Instead, each compressed
2424 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2425 * Furthermore, the chunk table is written at the end of the resource instead
2426 * of the start. Note: chunk offsets are given in the chunk table as if the
2427 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2428 * used if the WIM is being read from a seekable file (not a pipe).
2430 * - Metadata resources always come before other file resources (streams).
2431 * (This does not by itself constitute an incompatibility with normal WIMs,
2432 * since this is valid in normal WIMs.)
2434 * - At least up to the end of the file resources, all components must be packed
2435 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2436 * not by itself consititute an incompatibility with normal WIMs, since this
2437 * is valid in normal WIMs.)
2439 * Note: the lookup table, XML data, and header at the end are not used when
2440 * applying from a pipe. They exist to support functionality such as image
2441 * application and export when the WIM is *not* read from a pipe.
2443 * Layout of pipable WIM:
2445 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2446 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2447 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2449 * Layout of normal WIM:
2451 * +--------+-----------------------------+-------------------------+
2452 * | Header | File and metadata resources | Lookup table | XML data |
2453 * +--------+-----------------------------+-------------------------+
2455 * An optional integrity table can follow the final XML data in both normal and
2456 * pipable WIMs. However, due to implementation details, wimlib currently can
2457 * only include an integrity table in a pipable WIM when writing it to a
2458 * seekable file (not a pipe).
2460 * Do note that since pipable WIMs are not supported by Microsoft's software,
2461 * wimlib does not create them unless explicitly requested (with
2462 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2463 * characters to identify the file.
2466 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2467 unsigned num_threads, wimlib_progress_func_t progress_func,
2468 struct list_head *stream_list_override)
2471 struct resource_entry xml_res_entry;
2473 WARNING("Creating a pipable WIM, which will "
2475 " with Microsoft's software (wimgapi/imagex/Dism).");
2477 /* At this point, the header at the beginning of the file has already
2480 /* For efficiency, when wimlib adds an image to the WIM with
2481 * wimlib_add_image(), the SHA1 message digests of files is not
2482 * calculated; instead, they are calculated while the files are being
2483 * written. However, this does not work when writing a pipable WIM,
2484 * since when writing a stream to a pipable WIM, its SHA1 message digest
2485 * needs to be known before the stream data is written. Therefore,
2486 * before getting much farther, we need to pre-calculate the SHA1
2487 * message digests of all streams that will be written. */
2488 ret = wim_checksum_unhashed_streams(wim);
2492 /* Write extra copy of the XML data. */
2493 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2495 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2499 /* Write metadata resources for the image(s) being included in the
2501 ret = write_wim_metadata_resources(wim, image, write_flags,
2506 /* Write streams needed for the image(s) being included in the output
2507 * WIM, or streams needed for the split WIM part. */
2508 return write_wim_streams(wim, image, write_flags, num_threads,
2509 progress_func, stream_list_override);
2511 /* The lookup table, XML data, and header at end are handled by
2512 * finish_write(). */
2515 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2518 write_wim_part(WIMStruct *wim,
2519 const void *path_or_fd,
2522 unsigned num_threads,
2523 wimlib_progress_func_t progress_func,
2524 unsigned part_number,
2525 unsigned total_parts,
2526 struct list_head *stream_list_override,
2530 struct wim_header hdr_save;
2531 struct list_head lt_stream_list_override;
2533 if (total_parts == 1)
2534 DEBUG("Writing standalone WIM.");
2536 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2537 if (image == WIMLIB_ALL_IMAGES)
2538 DEBUG("Including all images.");
2540 DEBUG("Including image %d only.", image);
2541 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2542 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2544 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2545 DEBUG("Write flags: 0x%08x", write_flags);
2546 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2547 DEBUG("\tCHECK_INTEGRITY");
2548 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2550 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2551 DEBUG("\tRECOMPRESS");
2552 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2554 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2556 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2557 DEBUG("\tIGNORE_READONLY_FLAG");
2558 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2560 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2561 DEBUG("\tFILE_DESCRIPTOR");
2562 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2563 DEBUG("\tNO_METADATA");
2564 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2565 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2566 if (num_threads == 0)
2567 DEBUG("Number of threads: autodetect");
2569 DEBUG("Number of threads: %u", num_threads);
2570 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2571 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2572 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2573 "specified" : "generate new"));
2575 /* Internally, this is always called with a valid part number and total
2577 wimlib_assert(total_parts >= 1);
2578 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2580 /* A valid image (or all images) must be specified. */
2581 if (image != WIMLIB_ALL_IMAGES &&
2582 (image < 1 || image > wim->hdr.image_count))
2583 return WIMLIB_ERR_INVALID_IMAGE;
2585 /* If we need to write metadata resources, make sure the ::WIMStruct has
2586 * the needed information attached (e.g. is not a resource-only WIM,
2587 * such as a non-first part of a split WIM). */
2588 if (!wim_has_metadata(wim) &&
2589 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2590 return WIMLIB_ERR_METADATA_NOT_FOUND;
2592 /* Check for contradictory flags. */
2593 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2594 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2595 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2596 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2597 return WIMLIB_ERR_INVALID_PARAM;
2599 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2600 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2601 == (WIMLIB_WRITE_FLAG_PIPABLE |
2602 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2603 return WIMLIB_ERR_INVALID_PARAM;
2605 /* Save previous header, then start initializing the new one. */
2606 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2608 /* Set default integrity and pipable flags. */
2609 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2610 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2611 if (wim_is_pipable(wim))
2612 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2614 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2615 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2616 if (wim_has_integrity_table(wim))
2617 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2619 /* Set appropriate magic number. */
2620 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2621 wim->hdr.magic = PWM_MAGIC;
2623 wim->hdr.magic = WIM_MAGIC;
2625 /* Clear header flags that will be set automatically. */
2626 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2627 WIM_HDR_FLAG_RESOURCE_ONLY |
2628 WIM_HDR_FLAG_SPANNED |
2629 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2631 /* Set SPANNED header flag if writing part of a split WIM. */
2632 if (total_parts != 1)
2633 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2635 /* Set part number and total parts of split WIM. This will be 1 and 1
2636 * if the WIM is standalone. */
2637 wim->hdr.part_number = part_number;
2638 wim->hdr.total_parts = total_parts;
2640 /* Set compression type if different. */
2641 if (wim->compression_type != wim->out_compression_type)
2642 wim->hdr.flags = get_wim_hdr_cflags(wim->out_compression_type);
2644 /* Set chunk size if different. */
2645 wim->hdr.chunk_size = wim->out_chunk_size;
2647 /* Use GUID if specified; otherwise generate a new one. */
2649 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2650 else if (!wim->guid_set_explicitly)
2651 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2653 /* Clear references to resources that have not been written yet. */
2654 zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2655 zero_resource_entry(&wim->hdr.xml_res_entry);
2656 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2657 zero_resource_entry(&wim->hdr.integrity);
2659 /* Set image count and boot index correctly for single image writes. */
2660 if (image != WIMLIB_ALL_IMAGES) {
2661 wim->hdr.image_count = 1;
2662 if (wim->hdr.boot_idx == image)
2663 wim->hdr.boot_idx = 1;
2665 wim->hdr.boot_idx = 0;
2668 /* Split WIMs can't be bootable. */
2669 if (total_parts != 1)
2670 wim->hdr.boot_idx = 0;
2672 /* Initialize output file descriptor. */
2673 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2674 /* File descriptor was explicitly provided. Return error if
2675 * file descriptor is not seekable, unless writing a pipable WIM
2677 wim->out_fd.fd = *(const int*)path_or_fd;
2678 wim->out_fd.offset = 0;
2679 if (!filedes_is_seekable(&wim->out_fd)) {
2680 ret = WIMLIB_ERR_INVALID_PARAM;
2681 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2682 goto out_restore_hdr;
2683 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2684 ERROR("Can't include integrity check when "
2685 "writing pipable WIM to pipe!");
2686 goto out_restore_hdr;
2691 /* Filename of WIM to write was provided; open file descriptor
2693 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2694 O_TRUNC | O_CREAT | O_RDWR);
2696 goto out_restore_hdr;
2699 /* Write initial header. This is merely a "dummy" header since it
2700 * doesn't have all the information yet, so it will be overwritten later
2701 * (unless writing a pipable WIM). */
2702 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2703 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2704 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2705 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2707 goto out_restore_hdr;
2709 if (stream_list_override) {
2710 struct wim_lookup_table_entry *lte;
2711 INIT_LIST_HEAD(<_stream_list_override);
2712 list_for_each_entry(lte, stream_list_override,
2715 list_add_tail(<e->lookup_table_list,
2716 <_stream_list_override);
2720 /* Write metadata resources and streams. */
2721 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2722 /* Default case: create a normal (non-pipable) WIM. */
2723 ret = write_wim_streams(wim, image, write_flags, num_threads,
2724 progress_func, stream_list_override);
2726 goto out_restore_hdr;
2728 ret = write_wim_metadata_resources(wim, image, write_flags,
2731 goto out_restore_hdr;
2733 /* Non-default case: create pipable WIM. */
2734 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2735 progress_func, stream_list_override);
2737 goto out_restore_hdr;
2738 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2741 if (stream_list_override)
2742 stream_list_override = <_stream_list_override;
2744 /* Write lookup table, XML data, and (optional) integrity table. */
2745 ret = finish_write(wim, image, write_flags, progress_func,
2746 stream_list_override);
2748 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2749 (void)close_wim_writable(wim, write_flags);
2750 DEBUG("ret=%d", ret);
2754 /* Write a standalone WIM to a file or file descriptor. */
2756 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2757 int image, int write_flags, unsigned num_threads,
2758 wimlib_progress_func_t progress_func)
2760 return write_wim_part(wim, path_or_fd, image, write_flags,
2761 num_threads, progress_func, 1, 1, NULL, NULL);
2764 /* API function documented in wimlib.h */
2766 wimlib_write(WIMStruct *wim, const tchar *path,
2767 int image, int write_flags, unsigned num_threads,
2768 wimlib_progress_func_t progress_func)
2771 return WIMLIB_ERR_INVALID_PARAM;
2773 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2775 return write_standalone_wim(wim, path, image, write_flags,
2776 num_threads, progress_func);
2779 /* API function documented in wimlib.h */
2781 wimlib_write_to_fd(WIMStruct *wim, int fd,
2782 int image, int write_flags, unsigned num_threads,
2783 wimlib_progress_func_t progress_func)
2786 return WIMLIB_ERR_INVALID_PARAM;
2788 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2789 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2791 return write_standalone_wim(wim, &fd, image, write_flags,
2792 num_threads, progress_func);
2796 any_images_modified(WIMStruct *wim)
2798 for (int i = 0; i < wim->hdr.image_count; i++)
2799 if (wim->image_metadata[i]->modified)
2805 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2807 const WIMStruct *wim = _wim;
2808 off_t end_offset = *(const off_t*)wim->private;
2810 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == wim &&
2811 lte->resource_entry.offset + lte->resource_entry.size > end_offset)
2812 return WIMLIB_ERR_RESOURCE_ORDER;
2816 /* Make sure no file or metadata resources are located after the XML data (or
2817 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2818 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2820 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2825 wim->private = &end_offset;
2826 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2830 for (i = 0; i < wim->hdr.image_count; i++) {
2831 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2839 * Overwrite a WIM, possibly appending streams to it.
2841 * A WIM looks like (or is supposed to look like) the following:
2843 * Header (212 bytes)
2844 * Streams and metadata resources (variable size)
2845 * Lookup table (variable size)
2846 * XML data (variable size)
2847 * Integrity table (optional) (variable size)
2849 * If we are not adding any streams or metadata resources, the lookup table is
2850 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2851 * header. This operation is potentially unsafe if the program is abruptly
2852 * terminated while the XML data or integrity table are being overwritten, but
2853 * before the new header has been written. To partially alleviate this problem,
2854 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2855 * finish_write() to cause a temporary WIM header to be written after the XML
2856 * data has been written. This may prevent the WIM from becoming corrupted if
2857 * the program is terminated while the integrity table is being calculated (but
2858 * no guarantees, due to write re-ordering...).
2860 * If we are adding new streams or images (metadata resources), the lookup table
2861 * needs to be changed, and those streams need to be written. In this case, we
2862 * try to perform a safe update of the WIM file by writing the streams *after*
2863 * the end of the previous WIM, then writing the new lookup table, XML data, and
2864 * (optionally) integrity table following the new streams. This will produce a
2865 * layout like the following:
2867 * Header (212 bytes)
2868 * (OLD) Streams and metadata resources (variable size)
2869 * (OLD) Lookup table (variable size)
2870 * (OLD) XML data (variable size)
2871 * (OLD) Integrity table (optional) (variable size)
2872 * (NEW) Streams and metadata resources (variable size)
2873 * (NEW) Lookup table (variable size)
2874 * (NEW) XML data (variable size)
2875 * (NEW) Integrity table (optional) (variable size)
2877 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2878 * the header is overwritten to point to the new lookup table, XML data, and
2879 * integrity table, to produce the following layout:
2881 * Header (212 bytes)
2882 * Streams and metadata resources (variable size)
2883 * Nothing (variable size)
2884 * More Streams and metadata resources (variable size)
2885 * Lookup table (variable size)
2886 * XML data (variable size)
2887 * Integrity table (optional) (variable size)
2889 * This method allows an image to be appended to a large WIM very quickly, and
2890 * is is crash-safe except in the case of write re-ordering, but the
2891 * disadvantage is that a small hole is left in the WIM where the old lookup
2892 * table, xml data, and integrity table were. (These usually only take up a
2893 * small amount of space compared to the streams, however.)
2896 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2897 unsigned num_threads,
2898 wimlib_progress_func_t progress_func)
2901 struct list_head stream_list;
2903 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2904 struct wim_header hdr_save;
2906 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2908 /* Set default integrity flag. */
2909 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2910 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2911 if (wim_has_integrity_table(wim))
2912 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2914 /* Set additional flags for overwrite. */
2915 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2916 WIMLIB_WRITE_FLAG_STREAMS_OK;
2918 /* Make sure that the integrity table (if present) is after the XML
2919 * data, and that there are no stream resources, metadata resources, or
2920 * lookup tables after the XML data. Otherwise, these data would be
2922 old_xml_begin = wim->hdr.xml_res_entry.offset;
2923 old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2924 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2925 wim->hdr.lookup_table_res_entry.size;
2926 if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2927 WARNING("Didn't expect the integrity table to be before the XML data");
2928 return WIMLIB_ERR_RESOURCE_ORDER;
2931 if (old_lookup_table_end > old_xml_begin) {
2932 WARNING("Didn't expect the lookup table to be after the XML data");
2933 return WIMLIB_ERR_RESOURCE_ORDER;
2936 /* Set @old_wim_end, which indicates the point beyond which we don't
2937 * allow any file and metadata resources to appear without returning
2938 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2939 * overwrite these resources). */
2940 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2941 /* If no images have been modified and no images have been
2942 * deleted, a new lookup table does not need to be written. We
2943 * shall write the new XML data and optional integrity table
2944 * immediately after the lookup table. Note that this may
2945 * overwrite an existing integrity table. */
2946 DEBUG("Skipping writing lookup table "
2947 "(no images modified or deleted)");
2948 old_wim_end = old_lookup_table_end;
2949 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2950 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2951 } else if (wim->hdr.integrity.offset) {
2952 /* Old WIM has an integrity table; begin writing new streams
2954 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2956 /* No existing integrity table; begin writing new streams after
2957 * the old XML data. */
2958 old_wim_end = old_xml_end;
2961 ret = check_resource_offsets(wim, old_wim_end);
2965 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2970 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2974 ret = lock_wim(wim, wim->out_fd.fd);
2978 /* Save original header so it can be restored in case of error */
2979 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2981 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2982 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2983 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2985 ERROR_WITH_ERRNO("Error updating WIM header flags");
2986 goto out_restore_memory_hdr;
2989 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2990 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2991 ret = WIMLIB_ERR_WRITE;
2992 goto out_restore_physical_hdr;
2995 ret = write_stream_list(&stream_list,
2998 wim->compression_type,
3007 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3008 write_flags, progress_func);
3012 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3013 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3014 progress_func, NULL);
3018 goto out_unlock_wim;
3021 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3022 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3023 wim->filename, old_wim_end);
3024 /* Return value of ftruncate() is ignored because this is
3025 * already an error path. */
3026 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3028 out_restore_physical_hdr:
3029 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3030 out_restore_memory_hdr:
3031 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3033 (void)close_wim_writable(wim, write_flags);
3035 wim->wim_locked = 0;
3040 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3041 unsigned num_threads,
3042 wimlib_progress_func_t progress_func)
3044 size_t wim_name_len;
3047 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3049 /* Write the WIM to a temporary file in the same directory as the
3051 wim_name_len = tstrlen(wim->filename);
3052 tchar tmpfile[wim_name_len + 10];
3053 tmemcpy(tmpfile, wim->filename, wim_name_len);
3054 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3055 tmpfile[wim_name_len + 9] = T('\0');
3057 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3058 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3059 num_threads, progress_func);
3067 /* Rename the new WIM file to the original WIM file. Note: on Windows
3068 * this actually calls win32_rename_replacement(), not _wrename(), so
3069 * that removing the existing destination file can be handled. */
3070 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3071 ret = trename(tmpfile, wim->filename);
3073 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3074 tmpfile, wim->filename);
3081 return WIMLIB_ERR_RENAME;
3084 if (progress_func) {
3085 union wimlib_progress_info progress;
3086 progress.rename.from = tmpfile;
3087 progress.rename.to = wim->filename;
3088 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3093 /* API function documented in wimlib.h */
3095 wimlib_overwrite(WIMStruct *wim, int write_flags,
3096 unsigned num_threads,
3097 wimlib_progress_func_t progress_func)
3102 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3104 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3105 return WIMLIB_ERR_INVALID_PARAM;
3108 return WIMLIB_ERR_NO_FILENAME;
3110 orig_hdr_flags = wim->hdr.flags;
3111 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3112 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3113 ret = can_modify_wim(wim);
3114 wim->hdr.flags = orig_hdr_flags;
3118 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3119 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3120 WIMLIB_WRITE_FLAG_PIPABLE))
3121 && !(wim_is_pipable(wim))
3122 && wim->compression_type == wim->out_compression_type
3123 && wim->chunk_size == wim->out_chunk_size)
3125 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3127 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3129 WARNING("Falling back to re-building entire WIM");
3131 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,