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' */
72 compress_chunk(const void * uncompressed_data,
73 unsigned uncompressed_len,
74 void *compressed_data,
76 struct wimlib_lzx_context *comp_ctx)
79 case WIMLIB_COMPRESSION_TYPE_XPRESS:
80 return wimlib_xpress_compress(uncompressed_data,
83 case WIMLIB_COMPRESSION_TYPE_LZX:
84 return wimlib_lzx_compress2(uncompressed_data,
94 /* Chunk table that's located at the beginning of each compressed resource in
95 * the WIM. (This is not the on-disk format; the on-disk format just has an
96 * array of offsets.) */
98 u64 original_resource_size;
101 unsigned bytes_per_chunk_entry;
107 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
108 * integers, including the first offset of 0, which will not be written.
110 u8 offsets[] _aligned_attribute(8);
113 /* Allocate and initializes a chunk table, then reserve space for it in the
114 * output file unless writing a pipable resource. */
116 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
117 struct filedes *out_fd,
118 struct chunk_table **chunk_tab_ret,
123 unsigned bytes_per_chunk_entry;
125 struct chunk_table *chunk_tab;
128 size = wim_resource_size(lte);
129 num_chunks = wim_resource_chunks(lte);
130 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
131 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
132 chunk_tab = CALLOC(1, alloc_size);
135 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
137 return WIMLIB_ERR_NOMEM;
139 chunk_tab->num_chunks = num_chunks;
140 chunk_tab->original_resource_size = size;
141 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
142 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
144 chunk_tab->cur_offset_p = chunk_tab->offsets;
146 /* We don't know the correct offsets yet; so just write zeroes to
147 * reserve space for the table, so we can go back to it later after
148 * we've written the compressed chunks following it.
150 * Special case: if writing a pipable WIM, compressed resources are in a
151 * modified format (see comment above write_pipable_wim()) and do not
152 * have a chunk table at the beginning, so don't reserve any space for
154 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
155 ret = full_write(out_fd, chunk_tab->offsets,
156 chunk_tab->table_disk_size);
158 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
164 *chunk_tab_ret = chunk_tab;
168 /* Add the offset for the next chunk to the chunk table being constructed for a
169 * compressed stream. */
171 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
173 if (chunk_tab->bytes_per_chunk_entry == 4) {
174 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
175 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
176 chunk_tab->cur_offset_u32 += out_chunk_size;
178 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
179 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
180 chunk_tab->cur_offset_u64 += out_chunk_size;
184 /* Finishes a WIM chunk table and writes it to the output file at the correct
187 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
188 struct filedes *out_fd,
189 off_t res_start_offset,
190 int write_resource_flags)
194 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
195 ret = full_write(out_fd,
197 chunk_tab->bytes_per_chunk_entry,
198 chunk_tab->table_disk_size);
200 ret = full_pwrite(out_fd,
202 chunk_tab->bytes_per_chunk_entry,
203 chunk_tab->table_disk_size,
207 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
213 /* Write the header for a stream in a pipable WIM.
216 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
217 struct filedes *out_fd,
218 int additional_reshdr_flags)
220 struct pwm_stream_hdr stream_hdr;
224 stream_hdr.magic = PWM_STREAM_MAGIC;
225 stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
226 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
227 zero_out_hash(stream_hdr.hash);
229 wimlib_assert(!lte->unhashed);
230 copy_hash(stream_hdr.hash, lte->hash);
233 reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
234 reshdr_flags |= additional_reshdr_flags;
235 stream_hdr.flags = cpu_to_le32(reshdr_flags);
236 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
238 ERROR_WITH_ERRNO("Error writing stream header");
243 seek_and_truncate(struct filedes *out_fd, off_t offset)
245 if (filedes_seek(out_fd, offset) == -1 ||
246 ftruncate(out_fd->fd, offset))
248 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
249 return WIMLIB_ERR_WRITE;
255 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
257 u8 md[SHA1_HASH_SIZE];
259 sha1_final(md, sha_ctx);
261 copy_hash(lte->hash, md);
262 } else if (!hashes_equal(md, lte->hash)) {
263 ERROR("WIM resource has incorrect hash!");
264 if (lte_filename_valid(lte)) {
265 ERROR("We were reading it from \"%"TS"\"; maybe "
266 "it changed while we were reading it.",
269 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
274 struct write_resource_ctx {
276 struct wimlib_lzx_context *comp_ctx;
277 struct chunk_table *chunk_tab;
278 struct filedes *out_fd;
285 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
287 struct write_resource_ctx *ctx = _ctx;
288 const void *out_chunk;
289 unsigned out_chunk_size;
293 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
296 out_chunk_size = chunk_size;
297 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
298 void *compressed_chunk;
299 unsigned compressed_size;
301 /* Compress the chunk. */
302 compressed_chunk = alloca(chunk_size);
304 compressed_size = compress_chunk(chunk, chunk_size,
308 /* Use compressed data if compression to less than input size
310 if (compressed_size) {
311 out_chunk = compressed_chunk;
312 out_chunk_size = compressed_size;
316 if (ctx->chunk_tab) {
317 /* Update chunk table accounting. */
318 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
320 /* If writing compressed chunks to a pipable WIM, before the
321 * chunk data write a chunk header that provides the compressed
323 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
324 struct pwm_chunk_hdr chunk_hdr = {
325 .compressed_size = cpu_to_le32(out_chunk_size),
327 ret = full_write(ctx->out_fd, &chunk_hdr,
334 /* Write the chunk data. */
335 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
341 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
346 * write_wim_resource()-
348 * Write a resource to an output WIM.
351 * Lookup table entry for the resource, which could be in another WIM, in
352 * an external file, or in another location.
355 * File descriptor opened to the output WIM.
358 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
359 * compression algorithm to use.
362 * On success, this is filled in with the offset, flags, compressed size,
363 * and uncompressed size of the resource in the output WIM.
366 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
367 * if it could otherwise be copied directly from the input;
368 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
369 * (and the output file descriptor may be a pipe).
372 * Location of LZX compression context pointer, which will be allocated or
373 * updated if needed. (Initialize to NULL.)
375 * Additional notes: The SHA1 message digest of the uncompressed data is
376 * calculated (except when doing a raw copy --- see below). If the @unhashed
377 * flag is set on the lookup table entry, this message digest is simply copied
378 * to it; otherwise, the message digest is compared with the existing one, and
379 * the function will fail if they do not match.
382 write_wim_resource(struct wim_lookup_table_entry *lte,
383 struct filedes *out_fd, int out_ctype,
384 struct resource_entry *out_res_entry,
386 struct wimlib_lzx_context **comp_ctx)
388 struct write_resource_ctx write_ctx;
389 off_t res_start_offset;
393 /* Mask out any irrelevant flags, since this function also uses this
394 * variable to store WIMLIB_READ_RESOURCE flags. */
395 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
397 /* Get current position in output WIM. */
398 res_start_offset = out_fd->offset;
400 /* If we are not forcing the data to be recompressed, and the input
401 * resource is located in a WIM with the same compression type as that
402 * desired other than no compression, we can simply copy the compressed
403 * data without recompressing it. This also means we must skip
404 * calculating the SHA1, as we never will see the uncompressed data. */
405 if (lte->resource_location == RESOURCE_IN_WIM &&
406 out_ctype == wim_resource_compression_type(lte) &&
407 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
408 !(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS))
410 /* Normally we can request a RAW_FULL read, but if we're reading
411 * from a pipable resource and writing a non-pipable resource or
412 * vice versa, then a RAW_CHUNKS read needs to be requested so
413 * that the written resource can be appropriately formatted.
414 * However, in neither case is any actual decompression needed.
416 if (lte->is_pipable == !!(resource_flags &
417 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
418 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
420 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
421 write_ctx.doing_sha = false;
422 read_size = lte->resource_entry.size;
424 write_ctx.doing_sha = true;
425 sha1_init(&write_ctx.sha_ctx);
426 read_size = lte->resource_entry.original_size;
430 /* If the output resource is to be compressed, initialize the chunk
431 * table and set the function to use for chunk compression. Exceptions:
432 * no compression function is needed if doing a raw copy; also, no chunk
433 * table is needed if doing a *full* (not per-chunk) raw copy. */
434 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
435 write_ctx.chunk_tab = NULL;
436 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
437 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
438 write_ctx.out_ctype = out_ctype;
439 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
440 ret = wimlib_lzx_alloc_context(NULL, comp_ctx);
444 write_ctx.comp_ctx = *comp_ctx;
446 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
447 ret = begin_wim_resource_chunk_tab(lte, out_fd,
448 &write_ctx.chunk_tab,
455 /* If writing a pipable resource, write the stream header and update
456 * @res_start_offset to be the end of the stream header. */
457 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
458 int reshdr_flags = 0;
459 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
460 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
461 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
463 goto out_free_chunk_tab;
464 res_start_offset = out_fd->offset;
467 /* Write the entire resource by reading the entire resource and feeding
468 * the data through the write_resource_cb function. */
469 write_ctx.out_fd = out_fd;
470 write_ctx.resource_flags = resource_flags;
472 ret = read_resource_prefix(lte, read_size,
473 write_resource_cb, &write_ctx, resource_flags);
475 goto out_free_chunk_tab;
477 /* Verify SHA1 message digest of the resource, or set the hash for the
479 if (write_ctx.doing_sha) {
480 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
482 goto out_free_chunk_tab;
485 /* Write chunk table if needed. */
486 if (write_ctx.chunk_tab) {
487 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
492 goto out_free_chunk_tab;
495 /* Fill in out_res_entry with information about the newly written
497 out_res_entry->size = out_fd->offset - res_start_offset;
498 out_res_entry->flags = lte->resource_entry.flags;
499 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
500 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
502 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
503 out_res_entry->offset = res_start_offset;
504 out_res_entry->original_size = wim_resource_size(lte);
506 /* Check for resources compressed to greater than their original size
507 * and write them uncompressed instead. (But never do this if writing
508 * to a pipe, and don't bother if we did a raw copy.) */
509 if (out_res_entry->size > out_res_entry->original_size &&
510 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
511 WIMLIB_READ_RESOURCE_FLAG_RAW)))
513 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
514 "writing uncompressed instead",
515 out_res_entry->original_size, out_res_entry->size);
516 ret = seek_and_truncate(out_fd, res_start_offset);
518 goto out_free_chunk_tab;
519 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
520 FREE(write_ctx.chunk_tab);
521 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
522 write_ctx.chunk_tab = NULL;
523 write_ctx.doing_sha = false;
524 goto try_write_again;
526 if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
527 DEBUG("Copied raw compressed data "
528 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
529 out_res_entry->original_size, out_res_entry->size,
530 out_res_entry->offset, out_res_entry->flags);
531 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
532 DEBUG("Wrote compressed resource "
533 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
534 out_res_entry->original_size, out_res_entry->size,
535 out_res_entry->offset, out_res_entry->flags);
537 DEBUG("Wrote uncompressed resource "
538 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
539 out_res_entry->original_size,
540 out_res_entry->offset, out_res_entry->flags);
544 FREE(write_ctx.chunk_tab);
549 /* Like write_wim_resource(), but the resource is specified by a buffer of
550 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
551 * the buffer to @hash_ret. */
553 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
554 int reshdr_flags, struct filedes *out_fd,
556 struct resource_entry *out_res_entry,
557 u8 *hash_ret, int write_resource_flags,
558 struct wimlib_lzx_context **comp_ctx)
560 /* Set up a temporary lookup table entry to provide to
561 * write_wim_resource(). */
562 struct wim_lookup_table_entry lte;
565 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
566 lte.attached_buffer = (void*)buf;
567 lte.resource_entry.original_size = buf_size;
568 lte.resource_entry.flags = reshdr_flags;
570 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
571 sha1_buffer(buf, buf_size, lte.hash);
577 ret = write_wim_resource(<e, out_fd, out_ctype, out_res_entry,
578 write_resource_flags, comp_ctx);
582 copy_hash(hash_ret, lte.hash);
587 #ifdef ENABLE_MULTITHREADED_COMPRESSION
589 /* Blocking shared queue (solves the producer-consumer problem) */
590 struct shared_queue {
594 unsigned filled_slots;
596 pthread_mutex_t lock;
597 pthread_cond_t msg_avail_cond;
598 pthread_cond_t space_avail_cond;
602 shared_queue_init(struct shared_queue *q, unsigned size)
604 wimlib_assert(size != 0);
605 q->array = CALLOC(sizeof(q->array[0]), size);
612 if (pthread_mutex_init(&q->lock, NULL)) {
613 ERROR_WITH_ERRNO("Failed to initialize mutex");
616 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
617 ERROR_WITH_ERRNO("Failed to initialize condition variable");
618 goto err_destroy_lock;
620 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
621 ERROR_WITH_ERRNO("Failed to initialize condition variable");
622 goto err_destroy_msg_avail_cond;
625 err_destroy_msg_avail_cond:
626 pthread_cond_destroy(&q->msg_avail_cond);
628 pthread_mutex_destroy(&q->lock);
630 return WIMLIB_ERR_NOMEM;
634 shared_queue_destroy(struct shared_queue *q)
637 pthread_mutex_destroy(&q->lock);
638 pthread_cond_destroy(&q->msg_avail_cond);
639 pthread_cond_destroy(&q->space_avail_cond);
643 shared_queue_put(struct shared_queue *q, void *obj)
645 pthread_mutex_lock(&q->lock);
646 while (q->filled_slots == q->size)
647 pthread_cond_wait(&q->space_avail_cond, &q->lock);
649 q->back = (q->back + 1) % q->size;
650 q->array[q->back] = obj;
653 pthread_cond_broadcast(&q->msg_avail_cond);
654 pthread_mutex_unlock(&q->lock);
658 shared_queue_get(struct shared_queue *q)
662 pthread_mutex_lock(&q->lock);
663 while (q->filled_slots == 0)
664 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
666 obj = q->array[q->front];
667 q->array[q->front] = NULL;
668 q->front = (q->front + 1) % q->size;
671 pthread_cond_broadcast(&q->space_avail_cond);
672 pthread_mutex_unlock(&q->lock);
676 struct compressor_thread_params {
677 struct shared_queue *res_to_compress_queue;
678 struct shared_queue *compressed_res_queue;
680 struct wimlib_lzx_context *comp_ctx;
683 #define MAX_CHUNKS_PER_MSG 2
686 struct wim_lookup_table_entry *lte;
687 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
688 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
689 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
690 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
692 struct list_head list;
698 compress_chunks(struct message *msg, int out_ctype,
699 struct wimlib_lzx_context *comp_ctx)
701 for (unsigned i = 0; i < msg->num_chunks; i++) {
704 len = compress_chunk(msg->uncompressed_chunks[i],
705 msg->uncompressed_chunk_sizes[i],
706 msg->compressed_chunks[i],
713 /* To be written compressed */
714 out_chunk = msg->compressed_chunks[i];
717 /* To be written uncompressed */
718 out_chunk = msg->uncompressed_chunks[i];
719 out_len = msg->uncompressed_chunk_sizes[i];
721 msg->out_chunks[i].iov_base = out_chunk;
722 msg->out_chunks[i].iov_len = out_len;
726 /* Compressor thread routine. This is a lot simpler than the main thread
727 * routine: just repeatedly get a group of chunks from the
728 * res_to_compress_queue, compress them, and put them in the
729 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
732 compressor_thread_proc(void *arg)
734 struct compressor_thread_params *params = arg;
735 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
736 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
739 DEBUG("Compressor thread ready");
740 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
741 compress_chunks(msg, params->out_ctype, params->comp_ctx);
742 shared_queue_put(compressed_res_queue, msg);
744 DEBUG("Compressor thread terminating");
747 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
749 struct write_streams_progress_data {
750 wimlib_progress_func_t progress_func;
751 union wimlib_progress_info progress;
752 uint64_t next_progress;
753 WIMStruct *prev_wim_part;
757 do_write_streams_progress(struct write_streams_progress_data *progress_data,
758 struct wim_lookup_table_entry *lte,
759 bool stream_discarded)
761 union wimlib_progress_info *progress = &progress_data->progress;
764 if (stream_discarded) {
765 progress->write_streams.total_bytes -= wim_resource_size(lte);
766 if (progress_data->next_progress != ~(uint64_t)0 &&
767 progress_data->next_progress > progress->write_streams.total_bytes)
769 progress_data->next_progress = progress->write_streams.total_bytes;
772 progress->write_streams.completed_bytes += wim_resource_size(lte);
774 new_wim_part = false;
775 if (lte->resource_location == RESOURCE_IN_WIM &&
776 lte->wim != progress_data->prev_wim_part)
778 if (progress_data->prev_wim_part) {
780 progress->write_streams.completed_parts++;
782 progress_data->prev_wim_part = lte->wim;
784 progress->write_streams.completed_streams++;
785 if (progress_data->progress_func
786 && (progress->write_streams.completed_bytes >= progress_data->next_progress
789 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
791 if (progress_data->next_progress == progress->write_streams.total_bytes) {
792 progress_data->next_progress = ~(uint64_t)0;
794 progress_data->next_progress =
795 min(progress->write_streams.total_bytes,
796 progress->write_streams.completed_bytes +
797 progress->write_streams.total_bytes / 100);
802 struct serial_write_stream_ctx {
803 struct filedes *out_fd;
805 struct wimlib_lzx_context **comp_ctx;
806 int write_resource_flags;
810 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
812 struct serial_write_stream_ctx *ctx = _ctx;
813 return write_wim_resource(lte, ctx->out_fd,
814 ctx->out_ctype, <e->output_resource_entry,
815 ctx->write_resource_flags,
820 /* Write a list of streams, taking into account that some streams may be
821 * duplicates that are checksummed and discarded on the fly, and also delegating
822 * the actual writing of a stream to a function @write_stream_cb, which is
823 * passed the context @write_stream_ctx. */
825 do_write_stream_list(struct list_head *stream_list,
826 struct wim_lookup_table *lookup_table,
827 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
828 void *write_stream_ctx,
829 struct write_streams_progress_data *progress_data)
832 struct wim_lookup_table_entry *lte;
833 bool stream_discarded;
835 /* For each stream in @stream_list ... */
836 while (!list_empty(stream_list)) {
837 stream_discarded = false;
838 lte = container_of(stream_list->next,
839 struct wim_lookup_table_entry,
841 list_del(<e->write_streams_list);
842 if (lte->unhashed && !lte->unique_size) {
843 /* Unhashed stream that shares a size with some other
844 * stream in the WIM we are writing. The stream must be
845 * checksummed to know if we need to write it or not. */
846 struct wim_lookup_table_entry *tmp;
847 u32 orig_out_refcnt = lte->out_refcnt;
849 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
853 /* We found a duplicate stream. 'lte' was
854 * freed, so replace it with the duplicate. */
857 /* 'out_refcnt' was transferred to the
858 * duplicate, and we can detect if the duplicate
859 * stream was already referenced for writing by
860 * checking if its 'out_refcnt' is higher than
861 * that of the original stream. In such cases,
862 * the current stream can be discarded. We can
863 * also discard the current stream if it was
864 * previously marked as filtered (e.g. already
865 * present in the WIM being written). */
866 if (lte->out_refcnt > orig_out_refcnt ||
868 DEBUG("Discarding duplicate stream of "
870 wim_resource_size(lte));
871 lte->no_progress = 0;
872 stream_discarded = true;
873 goto skip_to_progress;
878 /* Here, @lte is either a hashed stream or an unhashed stream
879 * with a unique size. In either case we know that the stream
880 * has to be written. In either case the SHA1 message digest
881 * will be calculated over the stream while writing it; however,
882 * in the former case this is done merely to check the data,
883 * while in the latter case this is done because we do not have
884 * the SHA1 message digest yet. */
885 wimlib_assert(lte->out_refcnt != 0);
887 lte->no_progress = 0;
888 ret = (*write_stream_cb)(lte, write_stream_ctx);
891 /* In parallel mode, some streams are deferred for later,
892 * serialized processing; ignore them here. */
896 list_del(<e->unhashed_list);
897 lookup_table_insert(lookup_table, lte);
901 if (!lte->no_progress) {
902 do_write_streams_progress(progress_data,
903 lte, stream_discarded);
910 do_write_stream_list_serial(struct list_head *stream_list,
911 struct wim_lookup_table *lookup_table,
912 struct filedes *out_fd,
914 struct wimlib_lzx_context **comp_ctx,
915 int write_resource_flags,
916 struct write_streams_progress_data *progress_data)
918 struct serial_write_stream_ctx ctx = {
920 .out_ctype = out_ctype,
921 .write_resource_flags = write_resource_flags,
922 .comp_ctx = comp_ctx,
924 return do_write_stream_list(stream_list,
932 write_flags_to_resource_flags(int write_flags)
934 int resource_flags = 0;
936 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
937 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
938 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
939 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
940 return resource_flags;
944 write_stream_list_serial(struct list_head *stream_list,
945 struct wim_lookup_table *lookup_table,
946 struct filedes *out_fd,
948 struct wimlib_lzx_context **comp_ctx,
949 int write_resource_flags,
950 struct write_streams_progress_data *progress_data)
952 union wimlib_progress_info *progress = &progress_data->progress;
953 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
954 progress->write_streams.total_streams);
955 progress->write_streams.num_threads = 1;
956 if (progress_data->progress_func) {
957 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
960 return do_write_stream_list_serial(stream_list,
965 write_resource_flags,
969 #ifdef ENABLE_MULTITHREADED_COMPRESSION
971 write_wim_chunks(struct message *msg, struct filedes *out_fd,
972 struct chunk_table *chunk_tab,
973 int write_resource_flags)
976 struct pwm_chunk_hdr *chunk_hdrs;
980 for (unsigned i = 0; i < msg->num_chunks; i++)
981 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
983 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
984 nvecs = msg->num_chunks;
985 vecs = msg->out_chunks;
987 /* Special case: If writing a compressed resource to a pipable
988 * WIM, prefix each compressed chunk with a header that gives
989 * its compressed size. */
990 nvecs = msg->num_chunks * 2;
991 vecs = alloca(nvecs * sizeof(vecs[0]));
992 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
994 for (unsigned i = 0; i < msg->num_chunks; i++) {
995 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
996 vecs[i * 2].iov_base = &chunk_hdrs[i];
997 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
998 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
999 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1002 ret = full_writev(out_fd, vecs, nvecs);
1004 ERROR_WITH_ERRNO("Failed to write WIM chunks");
1008 struct main_writer_thread_ctx {
1009 struct list_head *stream_list;
1010 struct wim_lookup_table *lookup_table;
1011 struct filedes *out_fd;
1012 off_t res_start_offset;
1014 struct wimlib_lzx_context **comp_ctx;
1015 int write_resource_flags;
1016 struct shared_queue *res_to_compress_queue;
1017 struct shared_queue *compressed_res_queue;
1018 size_t num_messages;
1019 struct write_streams_progress_data *progress_data;
1021 struct list_head available_msgs;
1022 struct list_head outstanding_streams;
1023 struct list_head serial_streams;
1024 size_t num_outstanding_messages;
1026 SHA_CTX next_sha_ctx;
1028 u64 next_num_chunks;
1029 struct wim_lookup_table_entry *next_lte;
1031 struct message *msgs;
1032 struct message *next_msg;
1033 struct chunk_table *cur_chunk_tab;
1037 init_message(struct message *msg)
1039 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1040 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1041 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1042 if (msg->compressed_chunks[i] == NULL ||
1043 msg->uncompressed_chunks[i] == NULL)
1044 return WIMLIB_ERR_NOMEM;
1050 destroy_message(struct message *msg)
1052 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1053 FREE(msg->compressed_chunks[i]);
1054 FREE(msg->uncompressed_chunks[i]);
1059 free_messages(struct message *msgs, size_t num_messages)
1062 for (size_t i = 0; i < num_messages; i++)
1063 destroy_message(&msgs[i]);
1068 static struct message *
1069 allocate_messages(size_t num_messages)
1071 struct message *msgs;
1073 msgs = CALLOC(num_messages, sizeof(struct message));
1076 for (size_t i = 0; i < num_messages; i++) {
1077 if (init_message(&msgs[i])) {
1078 free_messages(msgs, num_messages);
1086 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1088 while (ctx->num_outstanding_messages--)
1089 shared_queue_get(ctx->compressed_res_queue);
1090 free_messages(ctx->msgs, ctx->num_messages);
1091 FREE(ctx->cur_chunk_tab);
1095 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1097 /* Pre-allocate all the buffers that will be needed to do the chunk
1099 ctx->msgs = allocate_messages(ctx->num_messages);
1101 return WIMLIB_ERR_NOMEM;
1103 /* Initially, all the messages are available to use. */
1104 INIT_LIST_HEAD(&ctx->available_msgs);
1105 for (size_t i = 0; i < ctx->num_messages; i++)
1106 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1108 /* outstanding_streams is the list of streams that currently have had
1109 * chunks sent off for compression.
1111 * The first stream in outstanding_streams is the stream that is
1112 * currently being written.
1114 * The last stream in outstanding_streams is the stream that is
1115 * currently being read and having chunks fed to the compressor threads.
1117 INIT_LIST_HEAD(&ctx->outstanding_streams);
1118 ctx->num_outstanding_messages = 0;
1120 ctx->next_msg = NULL;
1122 /* Resources that don't need any chunks compressed are added to this
1123 * list and written directly by the main thread. */
1124 INIT_LIST_HEAD(&ctx->serial_streams);
1126 ctx->cur_chunk_tab = NULL;
1132 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1134 struct message *msg;
1135 struct wim_lookup_table_entry *cur_lte;
1138 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1139 wimlib_assert(ctx->num_outstanding_messages != 0);
1141 cur_lte = container_of(ctx->outstanding_streams.next,
1142 struct wim_lookup_table_entry,
1143 being_compressed_list);
1145 /* Get the next message from the queue and process it.
1146 * The message will contain 1 or more data chunks that have been
1148 msg = shared_queue_get(ctx->compressed_res_queue);
1149 msg->complete = true;
1150 --ctx->num_outstanding_messages;
1152 /* Is this the next chunk in the current resource? If it's not
1153 * (i.e., an earlier chunk in a same or different resource
1154 * hasn't been compressed yet), do nothing, and keep this
1155 * message around until all earlier chunks are received.
1157 * Otherwise, write all the chunks we can. */
1158 while (cur_lte != NULL &&
1159 !list_empty(&cur_lte->msg_list)
1160 && (msg = container_of(cur_lte->msg_list.next,
1164 list_move(&msg->list, &ctx->available_msgs);
1165 if (msg->begin_chunk == 0) {
1166 /* First set of chunks. */
1168 /* Write pipable WIM stream header if needed. */
1169 if (ctx->write_resource_flags &
1170 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1172 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1173 WIM_RESHDR_FLAG_COMPRESSED);
1178 /* Save current offset. */
1179 ctx->res_start_offset = ctx->out_fd->offset;
1181 /* Begin building the chunk table, and leave space for
1183 ret = begin_wim_resource_chunk_tab(cur_lte,
1185 &ctx->cur_chunk_tab,
1186 ctx->write_resource_flags);
1192 /* Write the compressed chunks from the message. */
1193 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1194 ctx->write_resource_flags);
1198 /* Was this the last chunk of the stream? If so, finish
1200 if (list_empty(&cur_lte->msg_list) &&
1201 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1205 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1207 ctx->res_start_offset,
1208 ctx->write_resource_flags);
1212 list_del(&cur_lte->being_compressed_list);
1214 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1216 FREE(ctx->cur_chunk_tab);
1217 ctx->cur_chunk_tab = NULL;
1219 /* Check for resources compressed to greater than or
1220 * equal to their original size and write them
1221 * uncompressed instead. (But never do this if writing
1223 if (res_csize >= wim_resource_size(cur_lte) &&
1224 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1226 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1227 "writing uncompressed instead",
1228 wim_resource_size(cur_lte), res_csize);
1229 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1232 ret = write_wim_resource(cur_lte,
1234 WIMLIB_COMPRESSION_TYPE_NONE,
1235 &cur_lte->output_resource_entry,
1236 ctx->write_resource_flags,
1241 cur_lte->output_resource_entry.size =
1244 cur_lte->output_resource_entry.original_size =
1245 cur_lte->resource_entry.original_size;
1247 cur_lte->output_resource_entry.offset =
1248 ctx->res_start_offset;
1250 cur_lte->output_resource_entry.flags =
1251 cur_lte->resource_entry.flags |
1252 WIM_RESHDR_FLAG_COMPRESSED;
1254 DEBUG("Wrote compressed resource "
1255 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1256 cur_lte->output_resource_entry.original_size,
1257 cur_lte->output_resource_entry.size,
1258 cur_lte->output_resource_entry.offset,
1259 cur_lte->output_resource_entry.flags);
1262 do_write_streams_progress(ctx->progress_data,
1265 /* Since we just finished writing a stream, write any
1266 * streams that have been added to the serial_streams
1267 * list for direct writing by the main thread (e.g.
1268 * resources that don't need to be compressed because
1269 * the desired compression type is the same as the
1270 * previous compression type). */
1271 if (!list_empty(&ctx->serial_streams)) {
1272 ret = do_write_stream_list_serial(&ctx->serial_streams,
1277 ctx->write_resource_flags,
1278 ctx->progress_data);
1283 /* Advance to the next stream to write. */
1284 if (list_empty(&ctx->outstanding_streams)) {
1287 cur_lte = container_of(ctx->outstanding_streams.next,
1288 struct wim_lookup_table_entry,
1289 being_compressed_list);
1296 /* Called when the main thread has read a new chunk of data. */
1298 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1300 struct main_writer_thread_ctx *ctx = _ctx;
1302 struct message *next_msg;
1303 u64 next_chunk_in_msg;
1305 /* Update SHA1 message digest for the stream currently being read by the
1307 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1309 /* We send chunks of data to the compressor chunks in batches which we
1310 * refer to as "messages". @next_msg is the message that is currently
1311 * being prepared to send off. If it is NULL, that indicates that we
1312 * need to start a new message. */
1313 next_msg = ctx->next_msg;
1315 /* We need to start a new message. First check to see if there
1316 * is a message available in the list of available messages. If
1317 * so, we can just take one. If not, all the messages (there is
1318 * a fixed number of them, proportional to the number of
1319 * threads) have been sent off to the compressor threads, so we
1320 * receive messages from the compressor threads containing
1321 * compressed chunks of data.
1323 * We may need to receive multiple messages before one is
1324 * actually available to use because messages received that are
1325 * *not* for the very next set of chunks to compress must be
1326 * buffered until it's time to write those chunks. */
1327 while (list_empty(&ctx->available_msgs)) {
1328 ret = receive_compressed_chunks(ctx);
1333 next_msg = container_of(ctx->available_msgs.next,
1334 struct message, list);
1335 list_del(&next_msg->list);
1336 next_msg->complete = false;
1337 next_msg->begin_chunk = ctx->next_chunk;
1338 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1339 ctx->next_num_chunks - ctx->next_chunk);
1340 ctx->next_msg = next_msg;
1343 /* Fill in the next chunk to compress */
1344 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1346 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1347 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1350 if (++next_chunk_in_msg == next_msg->num_chunks) {
1351 /* Send off an array of chunks to compress */
1352 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1353 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1354 ++ctx->num_outstanding_messages;
1355 ctx->next_msg = NULL;
1361 main_writer_thread_finish(void *_ctx)
1363 struct main_writer_thread_ctx *ctx = _ctx;
1365 while (ctx->num_outstanding_messages != 0) {
1366 ret = receive_compressed_chunks(ctx);
1370 wimlib_assert(list_empty(&ctx->outstanding_streams));
1371 return do_write_stream_list_serial(&ctx->serial_streams,
1376 ctx->write_resource_flags,
1377 ctx->progress_data);
1381 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1382 struct main_writer_thread_ctx *ctx)
1386 /* Read the entire stream @lte, feeding its data chunks to the
1387 * compressor threads. Also SHA1-sum the stream; this is required in
1388 * the case that @lte is unhashed, and a nice additional verification
1389 * when @lte is already hashed. */
1390 sha1_init(&ctx->next_sha_ctx);
1391 ctx->next_chunk = 0;
1392 ctx->next_num_chunks = wim_resource_chunks(lte);
1393 ctx->next_lte = lte;
1394 INIT_LIST_HEAD(<e->msg_list);
1395 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1396 ret = read_resource_prefix(lte, wim_resource_size(lte),
1397 main_writer_thread_cb, ctx, 0);
1400 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1401 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1405 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1407 struct main_writer_thread_ctx *ctx = _ctx;
1410 if (wim_resource_size(lte) < 1000 ||
1411 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1412 (lte->resource_location == RESOURCE_IN_WIM &&
1413 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS) &&
1414 lte->wim->compression_type == ctx->out_ctype))
1416 /* Stream is too small or isn't being compressed. Process it by
1417 * the main thread when we have a chance. We can't necessarily
1418 * process it right here, as the main thread could be in the
1419 * middle of writing a different stream. */
1420 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1424 ret = submit_stream_for_compression(lte, ctx);
1426 lte->no_progress = 1;
1431 get_default_num_threads(void)
1434 return win32_get_number_of_processors();
1436 return sysconf(_SC_NPROCESSORS_ONLN);
1440 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1441 * parameter and will perform compression using that many threads. Falls
1442 * back to write_stream_list_serial() on certain errors, such as a failure to
1443 * create the number of threads requested.
1445 * High level description of the algorithm for writing compressed streams in
1446 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1447 * rather than on full files. The currently executing thread becomes the main
1448 * thread and is entirely in charge of reading the data to compress (which may
1449 * be in any location understood by the resource code--- such as in an external
1450 * file being captured, or in another WIM file from which an image is being
1451 * exported) and actually writing the compressed data to the output file.
1452 * Additional threads are "compressor threads" and all execute the
1453 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1454 * the main thread, compress them, and hand them back to the main thread.
1456 * Certain streams, such as streams that do not need to be compressed (e.g.
1457 * input compression type same as output compression type) or streams of very
1458 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1459 * handled entirely by the main thread at an appropriate time.
1461 * At any given point in time, multiple streams may be having chunks compressed
1462 * concurrently. The stream that the main thread is currently *reading* may be
1463 * later in the list that the stream that the main thread is currently
1467 write_stream_list_parallel(struct list_head *stream_list,
1468 struct wim_lookup_table *lookup_table,
1469 struct filedes *out_fd,
1471 struct wimlib_lzx_context **comp_ctx,
1472 int write_resource_flags,
1473 struct write_streams_progress_data *progress_data,
1474 unsigned num_threads)
1477 struct shared_queue res_to_compress_queue;
1478 struct shared_queue compressed_res_queue;
1479 pthread_t *compressor_threads = NULL;
1480 union wimlib_progress_info *progress = &progress_data->progress;
1482 if (num_threads == 0) {
1483 long nthreads = get_default_num_threads();
1484 if (nthreads < 1 || nthreads > UINT_MAX) {
1485 WARNING("Could not determine number of processors! Assuming 1");
1487 } else if (nthreads == 1) {
1488 goto out_serial_quiet;
1490 num_threads = nthreads;
1494 DEBUG("Writing stream list of size %"PRIu64" "
1495 "(parallel version, num_threads=%u)",
1496 progress->write_streams.total_streams, num_threads);
1498 progress->write_streams.num_threads = num_threads;
1500 static const size_t MESSAGES_PER_THREAD = 2;
1501 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1503 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1505 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1509 ret = shared_queue_init(&compressed_res_queue, queue_size);
1511 goto out_destroy_res_to_compress_queue;
1513 struct compressor_thread_params *params;
1515 params = CALLOC(num_threads, sizeof(params[0]));
1516 if (params == NULL) {
1517 ret = WIMLIB_ERR_NOMEM;
1518 goto out_destroy_compressed_res_queue;
1521 for (unsigned i = 0; i < num_threads; i++) {
1522 params[i].res_to_compress_queue = &res_to_compress_queue;
1523 params[i].compressed_res_queue = &compressed_res_queue;
1524 params[i].out_ctype = out_ctype;
1525 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1526 ret = wimlib_lzx_alloc_context(NULL, ¶ms[i].comp_ctx);
1528 goto out_free_params;
1532 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1533 if (!compressor_threads) {
1534 ret = WIMLIB_ERR_NOMEM;
1535 goto out_free_params;
1538 for (unsigned i = 0; i < num_threads; i++) {
1539 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1540 ret = pthread_create(&compressor_threads[i], NULL,
1541 compressor_thread_proc, ¶ms[i]);
1544 ERROR_WITH_ERRNO("Failed to create compressor "
1546 i + 1, num_threads);
1552 if (progress_data->progress_func) {
1553 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1557 struct main_writer_thread_ctx ctx;
1558 ctx.stream_list = stream_list;
1559 ctx.lookup_table = lookup_table;
1560 ctx.out_fd = out_fd;
1561 ctx.out_ctype = out_ctype;
1562 ctx.comp_ctx = comp_ctx;
1563 ctx.res_to_compress_queue = &res_to_compress_queue;
1564 ctx.compressed_res_queue = &compressed_res_queue;
1565 ctx.num_messages = queue_size;
1566 ctx.write_resource_flags = write_resource_flags;
1567 ctx.progress_data = progress_data;
1568 ret = main_writer_thread_init_ctx(&ctx);
1571 ret = do_write_stream_list(stream_list, lookup_table,
1572 main_thread_process_next_stream,
1573 &ctx, progress_data);
1575 goto out_destroy_ctx;
1577 /* The main thread has finished reading all streams that are going to be
1578 * compressed in parallel, and it now needs to wait for all remaining
1579 * chunks to be compressed so that the remaining streams can actually be
1580 * written to the output file. Furthermore, any remaining streams that
1581 * had processing deferred to the main thread need to be handled. These
1582 * tasks are done by the main_writer_thread_finish() function. */
1583 ret = main_writer_thread_finish(&ctx);
1585 main_writer_thread_destroy_ctx(&ctx);
1587 for (unsigned i = 0; i < num_threads; i++)
1588 shared_queue_put(&res_to_compress_queue, NULL);
1590 for (unsigned i = 0; i < num_threads; i++) {
1591 if (pthread_join(compressor_threads[i], NULL)) {
1592 WARNING_WITH_ERRNO("Failed to join compressor "
1594 i + 1, num_threads);
1597 FREE(compressor_threads);
1599 for (unsigned i = 0; i < num_threads; i++)
1600 wimlib_lzx_free_context(params[i].comp_ctx);
1602 out_destroy_compressed_res_queue:
1603 shared_queue_destroy(&compressed_res_queue);
1604 out_destroy_res_to_compress_queue:
1605 shared_queue_destroy(&res_to_compress_queue);
1606 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1609 WARNING("Falling back to single-threaded compression");
1611 return write_stream_list_serial(stream_list,
1616 write_resource_flags,
1623 * Write a list of streams to a WIM (@out_fd) using the compression type
1624 * @out_ctype and up to @num_threads compressor threads.
1627 write_stream_list(struct list_head *stream_list,
1628 struct wim_lookup_table *lookup_table,
1629 struct filedes *out_fd, int out_ctype,
1630 struct wimlib_lzx_context **comp_ctx,
1632 unsigned num_threads, wimlib_progress_func_t progress_func)
1634 struct wim_lookup_table_entry *lte;
1635 size_t num_streams = 0;
1636 u64 total_bytes = 0;
1637 u64 total_compression_bytes = 0;
1638 struct write_streams_progress_data progress_data;
1640 int write_resource_flags;
1641 unsigned total_parts = 0;
1642 WIMStruct *prev_wim_part = NULL;
1644 if (list_empty(stream_list)) {
1645 DEBUG("No streams to write.");
1649 write_resource_flags = write_flags_to_resource_flags(write_flags);
1651 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1652 out_fd->offset, write_resource_flags);
1654 sort_stream_list_by_sequential_order(stream_list,
1655 offsetof(struct wim_lookup_table_entry,
1656 write_streams_list));
1658 /* Calculate the total size of the streams to be written. Note: this
1659 * will be the uncompressed size, as we may not know the compressed size
1660 * yet, and also this will assume that every unhashed stream will be
1661 * written (which will not necessarily be the case). */
1662 list_for_each_entry(lte, stream_list, write_streams_list) {
1664 total_bytes += wim_resource_size(lte);
1665 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1666 && (wim_resource_compression_type(lte) != out_ctype ||
1667 (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)))
1669 total_compression_bytes += wim_resource_size(lte);
1671 if (lte->resource_location == RESOURCE_IN_WIM) {
1672 if (prev_wim_part != lte->wim) {
1673 prev_wim_part = lte->wim;
1679 memset(&progress_data, 0, sizeof(progress_data));
1680 progress_data.progress_func = progress_func;
1682 progress_data.progress.write_streams.total_bytes = total_bytes;
1683 progress_data.progress.write_streams.total_streams = num_streams;
1684 progress_data.progress.write_streams.completed_bytes = 0;
1685 progress_data.progress.write_streams.completed_streams = 0;
1686 progress_data.progress.write_streams.num_threads = num_threads;
1687 progress_data.progress.write_streams.compression_type = out_ctype;
1688 progress_data.progress.write_streams.total_parts = total_parts;
1689 progress_data.progress.write_streams.completed_parts = 0;
1691 progress_data.next_progress = 0;
1692 progress_data.prev_wim_part = NULL;
1694 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1695 if (total_compression_bytes >= 2000000 && num_threads != 1)
1696 ret = write_stream_list_parallel(stream_list,
1701 write_resource_flags,
1706 ret = write_stream_list_serial(stream_list,
1711 write_resource_flags,
1714 DEBUG("Successfully wrote stream list.");
1716 DEBUG("Failed to write stream list.");
1720 struct stream_size_table {
1721 struct hlist_head *array;
1727 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1729 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1731 return WIMLIB_ERR_NOMEM;
1732 tab->num_entries = 0;
1733 tab->capacity = capacity;
1738 destroy_stream_size_table(struct stream_size_table *tab)
1744 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1746 struct stream_size_table *tab = _tab;
1748 struct wim_lookup_table_entry *same_size_lte;
1749 struct hlist_node *tmp;
1751 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1752 lte->unique_size = 1;
1753 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1754 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1755 lte->unique_size = 0;
1756 same_size_lte->unique_size = 0;
1761 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1766 struct find_streams_ctx {
1769 struct list_head stream_list;
1770 struct stream_size_table stream_size_tab;
1774 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1775 struct find_streams_ctx *ctx,
1778 if (lte->out_refcnt == 0) {
1779 stream_size_table_insert(lte, &ctx->stream_size_tab);
1780 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1782 lte->out_refcnt += nref;
1786 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1789 struct find_streams_ctx *ctx = _ctx;
1790 lte->out_refcnt = 0;
1791 lte_reference_for_logical_write(lte, ctx,
1792 (lte->refcnt ? lte->refcnt : 1));
1797 inode_find_streams_to_write(struct wim_inode *inode,
1798 struct wim_lookup_table *table,
1799 struct find_streams_ctx *ctx)
1801 struct wim_lookup_table_entry *lte;
1804 for (i = 0; i <= inode->i_num_ads; i++) {
1805 lte = inode_stream_lte(inode, i, table);
1807 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1808 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1809 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1815 image_find_streams_to_write(WIMStruct *wim)
1817 struct find_streams_ctx *ctx;
1818 struct wim_image_metadata *imd;
1819 struct wim_inode *inode;
1820 struct wim_lookup_table_entry *lte;
1824 imd = wim_get_current_image_metadata(wim);
1826 image_for_each_unhashed_stream(lte, imd)
1827 lte->out_refcnt = 0;
1829 /* Go through this image's inodes to find any streams that have not been
1831 image_for_each_inode(inode, imd) {
1832 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1840 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1841 * the "logical write" of the WIM, meaning all streams that are referenced at
1842 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1843 * each stream being included in the logical write is set to the number of
1844 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1845 * stream being included in the logical write is set to indicate whether that
1846 * stream has a unique size relative to the streams being included in the
1847 * logical write. Still furthermore, 'part_number' on each stream being
1848 * included in the logical write is set to the part number given in the
1849 * in-memory header of @p wim.
1851 * This is considered a "logical write" because it does not take into account
1852 * filtering out streams already present in the WIM (in the case of an in place
1853 * overwrite) or present in other WIMs (in case of creating delta WIM).
1856 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1857 struct find_streams_ctx *ctx)
1860 struct wim_lookup_table_entry *lte;
1862 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1863 (image == 1 && wim->hdr.image_count == 1)))
1865 /* Fast case: Assume that all streams are being written and
1866 * that the reference counts are correct. */
1867 struct wim_lookup_table_entry *lte;
1868 struct wim_image_metadata *imd;
1871 for_lookup_table_entry(wim->lookup_table,
1872 do_lte_full_reference_for_logical_write, ctx);
1873 for (i = 0; i < wim->hdr.image_count; i++) {
1874 imd = wim->image_metadata[i];
1875 image_for_each_unhashed_stream(lte, imd)
1876 do_lte_full_reference_for_logical_write(lte, ctx);
1879 /* Slow case: Walk through the images being written and
1880 * determine the streams referenced. */
1881 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1883 ret = for_image(wim, image, image_find_streams_to_write);
1888 list_for_each_entry(lte, &ctx->stream_list, write_streams_list)
1889 lte->part_number = wim->hdr.part_number;
1894 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1896 struct find_streams_ctx *ctx = _ctx;
1899 /* Calculate and set lte->filtered. */
1900 if (lte->resource_location == RESOURCE_IN_WIM) {
1901 if (lte->wim == ctx->wim &&
1902 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1903 filtered |= FILTERED_SAME_WIM;
1904 if (lte->wim != ctx->wim &&
1905 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1906 filtered |= FILTERED_EXTERNAL_WIM;
1908 lte->filtered = filtered;
1910 /* Filtered streams get inserted into the stream size table too, unless
1911 * they already were. This is because streams that are checksummed
1912 * on-the-fly during the write should not be written if they are
1913 * duplicates of filtered stream. */
1914 if (lte->filtered && lte->out_refcnt == 0)
1915 stream_size_table_insert(lte, &ctx->stream_size_tab);
1920 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
1926 /* Given the list of streams to include in a logical write of a WIM, handle
1927 * filtering out streams already present in the WIM or already present in
1928 * external WIMs, depending on the write flags provided. */
1930 handle_stream_filtering(struct find_streams_ctx *ctx)
1932 struct wim_lookup_table_entry *lte, *tmp;
1934 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
1935 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
1937 for_lookup_table_entry(ctx->wim->lookup_table,
1938 mark_stream_not_filtered, ctx);
1942 for_lookup_table_entry(ctx->wim->lookup_table,
1943 process_filtered_stream, ctx);
1945 /* Streams in logical write list that were filtered can be removed. */
1946 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
1949 list_del(<e->write_streams_list);
1952 /* Prepares list of streams to write for the specified WIM image(s). This wraps
1953 * around prepare_logical_stream_list() to handle filtering out streams already
1954 * present in the WIM or already present in external WIMs, depending on the
1955 * write flags provided.
1957 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
1959 * - 'out_refcnt' is set to the number of references found for the logical write.
1960 * This will be nonzero on all streams in the list returned by this function,
1961 * but will also be nonzero on streams not in the list that were included in
1962 * the logical write list, but filtered out from the returned list.
1963 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
1964 * are not included in the list of streams returned by this function.
1965 * - 'unique_size' is set if the stream has a unique size among all streams in
1966 * the logical write plus any filtered streams in the entire WIM that could
1967 * potentially turn out to have the same checksum as a yet-to-be-checksummed
1968 * stream being written.
1971 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
1972 struct list_head *stream_list)
1976 struct find_streams_ctx ctx;
1978 INIT_LIST_HEAD(&ctx.stream_list);
1979 ret = init_stream_size_table(&ctx.stream_size_tab,
1980 wim->lookup_table->capacity);
1983 ctx.write_flags = write_flags;
1986 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
1988 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
1990 goto out_destroy_table;
1992 handle_stream_filtering(&ctx);
1993 list_transfer(&ctx.stream_list, stream_list);
1996 destroy_stream_size_table(&ctx.stream_size_tab);
2001 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2002 unsigned num_threads,
2003 wimlib_progress_func_t progress_func,
2004 struct list_head *stream_list_override)
2007 struct list_head _stream_list;
2008 struct list_head *stream_list;
2009 struct wim_lookup_table_entry *lte;
2011 if (stream_list_override == NULL) {
2012 /* Normal case: prepare stream list from image(s) being written.
2014 stream_list = &_stream_list;
2015 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2019 /* Currently only as a result of wimlib_split() being called:
2020 * use stream list already explicitly provided. Use existing
2021 * reference counts. */
2022 stream_list = stream_list_override;
2023 list_for_each_entry(lte, stream_list, write_streams_list) {
2024 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2025 lte->part_number = wim->hdr.part_number;
2029 return write_stream_list(stream_list,
2032 wim->compression_type,
2040 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2041 wimlib_progress_func_t progress_func)
2046 int write_resource_flags;
2048 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2049 DEBUG("Not writing any metadata resources.");
2053 write_resource_flags = write_flags_to_resource_flags(write_flags);
2055 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2056 wim->out_fd.offset);
2059 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2061 if (image == WIMLIB_ALL_IMAGES) {
2063 end_image = wim->hdr.image_count;
2065 start_image = image;
2069 for (int i = start_image; i <= end_image; i++) {
2070 struct wim_image_metadata *imd;
2072 imd = wim->image_metadata[i - 1];
2073 /* Build a new metadata resource only if image was modified from
2074 * the original (or was newly added). Otherwise just copy the
2076 if (imd->modified) {
2077 DEBUG("Image %u was modified; building and writing new "
2078 "metadata resource", i);
2079 ret = write_metadata_resource(wim, i,
2080 write_resource_flags);
2081 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2082 DEBUG("Image %u was not modified; re-using existing "
2083 "metadata resource.", i);
2084 copy_resource_entry(&imd->metadata_lte->output_resource_entry,
2085 &imd->metadata_lte->resource_entry);
2088 DEBUG("Image %u was not modified; copying existing "
2089 "metadata resource.", i);
2090 ret = write_wim_resource(imd->metadata_lte,
2092 wim->compression_type,
2093 &imd->metadata_lte->output_resource_entry,
2094 write_resource_flags,
2101 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2106 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2109 DEBUG("Opening \"%"TS"\" for writing.", path);
2111 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2113 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2114 return WIMLIB_ERR_OPEN;
2116 filedes_init(&wim->out_fd, raw_fd);
2121 close_wim_writable(WIMStruct *wim, int write_flags)
2125 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2126 DEBUG("Closing WIM file.");
2127 if (filedes_valid(&wim->out_fd))
2128 if (filedes_close(&wim->out_fd))
2129 ret = WIMLIB_ERR_WRITE;
2131 filedes_invalidate(&wim->out_fd);
2138 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2139 * table, then overwrite the WIM header. By default, closes the WIM file
2140 * descriptor (@wim->out_fd) if successful.
2142 * write_flags is a bitwise OR of the following:
2144 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2145 * Include an integrity table.
2147 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2148 * fsync() the output file before closing it.
2150 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2151 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2152 * stream headers before the lookup table and XML data, and also
2153 * write the WIM header at the end instead of seeking to the
2154 * beginning. Can't be combined with
2155 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2157 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2158 * Don't write the lookup table.
2160 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2161 * When (if) writing the integrity table, re-use entries from the
2162 * existing integrity table, if possible.
2164 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2165 * After writing the XML data but before writing the integrity
2166 * table, write a temporary WIM header and flush the stream so that
2167 * the WIM is less likely to become corrupted upon abrupt program
2169 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2170 * Instead of overwriting the WIM header at the beginning of the
2171 * file, simply append it to the end of the file. (Used when
2173 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2174 * Do not close the file descriptor @wim->out_fd on either success
2176 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2177 * Use the existing <TOTALBYTES> stored in the in-memory XML
2178 * information, rather than setting it to the offset of the XML
2179 * data being written.
2182 finish_write(WIMStruct *wim, int image, int write_flags,
2183 wimlib_progress_func_t progress_func,
2184 struct list_head *stream_list_override)
2188 int write_resource_flags;
2189 off_t old_lookup_table_end;
2190 off_t new_lookup_table_end;
2193 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2195 write_resource_flags = write_flags_to_resource_flags(write_flags);
2197 /* In the WIM header, there is room for the resource entry for a
2198 * metadata resource labeled as the "boot metadata". This entry should
2199 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2200 * it should be a copy of the resource entry for the image that is
2201 * marked as bootable. This is not well documented... */
2202 if (wim->hdr.boot_idx == 0) {
2203 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2205 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2206 &wim->image_metadata[wim->hdr.boot_idx- 1
2207 ]->metadata_lte->output_resource_entry);
2210 /* Write lookup table. (Save old position first.) */
2211 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2212 wim->hdr.lookup_table_res_entry.size;
2213 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2214 ret = write_wim_lookup_table(wim, image, write_flags,
2215 &wim->hdr.lookup_table_res_entry,
2216 stream_list_override);
2221 /* Write XML data. */
2222 xml_totalbytes = wim->out_fd.offset;
2223 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2224 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2225 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2226 &wim->hdr.xml_res_entry,
2227 write_resource_flags);
2231 /* Write integrity table (optional). */
2232 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2233 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2234 struct wim_header checkpoint_hdr;
2235 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2236 zero_resource_entry(&checkpoint_hdr.integrity);
2237 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2238 ret = write_wim_header_at_offset(&checkpoint_hdr,
2244 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2245 old_lookup_table_end = 0;
2247 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2248 wim->hdr.lookup_table_res_entry.size;
2250 ret = write_integrity_table(wim,
2251 new_lookup_table_end,
2252 old_lookup_table_end,
2257 /* No integrity table. */
2258 zero_resource_entry(&wim->hdr.integrity);
2261 /* Now that all information in the WIM header has been determined, the
2262 * preliminary header written earlier can be overwritten, the header of
2263 * the existing WIM file can be overwritten, or the final header can be
2264 * written to the end of the pipable WIM. */
2265 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2267 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2268 hdr_offset = wim->out_fd.offset;
2269 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2270 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2274 /* Possibly sync file data to disk before closing. On POSIX systems, it
2275 * is necessary to do this before using rename() to overwrite an
2276 * existing file with a new file. Otherwise, data loss would occur if
2277 * the system is abruptly terminated when the metadata for the rename
2278 * operation has been written to disk, but the new file data has not.
2280 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2281 DEBUG("Syncing WIM file.");
2282 if (fsync(wim->out_fd.fd)) {
2283 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2284 return WIMLIB_ERR_WRITE;
2288 if (close_wim_writable(wim, write_flags)) {
2289 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2290 return WIMLIB_ERR_WRITE;
2296 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2298 lock_wim(WIMStruct *wim, int fd)
2301 if (fd != -1 && !wim->wim_locked) {
2302 ret = flock(fd, LOCK_EX | LOCK_NB);
2304 if (errno == EWOULDBLOCK) {
2305 ERROR("`%"TS"' is already being modified or has been "
2306 "mounted read-write\n"
2307 " by another process!", wim->filename);
2308 ret = WIMLIB_ERR_ALREADY_LOCKED;
2310 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2315 wim->wim_locked = 1;
2323 * write_pipable_wim():
2325 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2326 * capable of being applied from a pipe).
2328 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2329 * images can be applied from them sequentially when the file data is sent over
2330 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2331 * The modifications made to the WIM format for pipable WIMs are:
2333 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2334 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2335 * stops other software from trying to read the file as a normal WIM.
2337 * - The header at the beginning of the file does not contain all the normal
2338 * information; in particular it will have all 0's for the lookup table and
2339 * XML data resource entries. This is because this information cannot be
2340 * determined until the lookup table and XML data have been written.
2341 * Consequently, wimlib will write the full header at the very end of the
2342 * file. The header at the end, however, is only used when reading the WIM
2343 * from a seekable file (not a pipe).
2345 * - An extra copy of the XML data is placed directly after the header. This
2346 * allows image names and sizes to be determined at an appropriate time when
2347 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2348 * WIM is read from a seekable file (not a pipe).
2350 * - The format of resources, or streams, has been modified to allow them to be
2351 * used before the "lookup table" has been read. Each stream is prefixed with
2352 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2353 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2354 * uncompressed stream size, and flags that indicate whether the stream is
2355 * compressed. The data of uncompressed streams then follows literally, while
2356 * the data of compressed streams follows in a modified format. Compressed
2357 * streams do not begin with a chunk table, since the chunk table cannot be
2358 * written until all chunks have been compressed. Instead, each compressed
2359 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2360 * Furthermore, the chunk table is written at the end of the resource instead
2361 * of the start. Note: chunk offsets are given in the chunk table as if the
2362 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2363 * used if the WIM is being read from a seekable file (not a pipe).
2365 * - Metadata resources always come before other file resources (streams).
2366 * (This does not by itself constitute an incompatibility with normal WIMs,
2367 * since this is valid in normal WIMs.)
2369 * - At least up to the end of the file resources, all components must be packed
2370 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2371 * not by itself consititute an incompatibility with normal WIMs, since this
2372 * is valid in normal WIMs.)
2374 * Note: the lookup table, XML data, and header at the end are not used when
2375 * applying from a pipe. They exist to support functionality such as image
2376 * application and export when the WIM is *not* read from a pipe.
2378 * Layout of pipable WIM:
2380 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2381 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2382 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2384 * Layout of normal WIM:
2386 * +--------+-----------------------------+-------------------------+
2387 * | Header | File and metadata resources | Lookup table | XML data |
2388 * +--------+-----------------------------+-------------------------+
2390 * An optional integrity table can follow the final XML data in both normal and
2391 * pipable WIMs. However, due to implementation details, wimlib currently can
2392 * only include an integrity table in a pipable WIM when writing it to a
2393 * seekable file (not a pipe).
2395 * Do note that since pipable WIMs are not supported by Microsoft's software,
2396 * wimlib does not create them unless explicitly requested (with
2397 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2398 * characters to identify the file.
2401 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2402 unsigned num_threads, wimlib_progress_func_t progress_func,
2403 struct list_head *stream_list_override)
2406 struct resource_entry xml_res_entry;
2408 WARNING("Creating a pipable WIM, which will "
2410 " with Microsoft's software (wimgapi/imagex/Dism).");
2412 /* At this point, the header at the beginning of the file has already
2415 /* For efficiency, when wimlib adds an image to the WIM with
2416 * wimlib_add_image(), the SHA1 message digests of files is not
2417 * calculated; instead, they are calculated while the files are being
2418 * written. However, this does not work when writing a pipable WIM,
2419 * since when writing a stream to a pipable WIM, its SHA1 message digest
2420 * needs to be known before the stream data is written. Therefore,
2421 * before getting much farther, we need to pre-calculate the SHA1
2422 * message digests of all streams that will be written. */
2423 ret = wim_checksum_unhashed_streams(wim);
2427 /* Write extra copy of the XML data. */
2428 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2430 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2434 /* Write metadata resources for the image(s) being included in the
2436 ret = write_wim_metadata_resources(wim, image, write_flags,
2441 /* Write streams needed for the image(s) being included in the output
2442 * WIM, or streams needed for the split WIM part. */
2443 return write_wim_streams(wim, image, write_flags, num_threads,
2444 progress_func, stream_list_override);
2446 /* The lookup table, XML data, and header at end are handled by
2447 * finish_write(). */
2450 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2453 write_wim_part(WIMStruct *wim,
2454 const void *path_or_fd,
2457 unsigned num_threads,
2458 wimlib_progress_func_t progress_func,
2459 unsigned part_number,
2460 unsigned total_parts,
2461 struct list_head *stream_list_override,
2465 struct wim_header hdr_save;
2466 struct list_head lt_stream_list_override;
2468 if (total_parts == 1)
2469 DEBUG("Writing standalone WIM.");
2471 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2472 if (image == WIMLIB_ALL_IMAGES)
2473 DEBUG("Including all images.");
2475 DEBUG("Including image %d only.", image);
2476 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2477 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2479 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2480 DEBUG("Write flags: 0x%08x", write_flags);
2481 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2482 DEBUG("\tCHECK_INTEGRITY");
2483 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2485 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2486 DEBUG("\tRECOMPRESS");
2487 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2489 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2491 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2492 DEBUG("\tIGNORE_READONLY_FLAG");
2493 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2495 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2496 DEBUG("\tFILE_DESCRIPTOR");
2497 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2498 DEBUG("\tNO_METADATA");
2499 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2500 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2501 if (num_threads == 0)
2502 DEBUG("Number of threads: autodetect");
2504 DEBUG("Number of threads: %u", num_threads);
2505 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2506 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2507 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2508 "specified" : "generate new"));
2510 /* Internally, this is always called with a valid part number and total
2512 wimlib_assert(total_parts >= 1);
2513 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2515 /* A valid image (or all images) must be specified. */
2516 if (image != WIMLIB_ALL_IMAGES &&
2517 (image < 1 || image > wim->hdr.image_count))
2518 return WIMLIB_ERR_INVALID_IMAGE;
2520 /* If we need to write metadata resources, make sure the ::WIMStruct has
2521 * the needed information attached (e.g. is not a resource-only WIM,
2522 * such as a non-first part of a split WIM). */
2523 if (!wim_has_metadata(wim) &&
2524 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2525 return WIMLIB_ERR_METADATA_NOT_FOUND;
2527 /* Check for contradictory flags. */
2528 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2529 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2530 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2531 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2532 return WIMLIB_ERR_INVALID_PARAM;
2534 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2535 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2536 == (WIMLIB_WRITE_FLAG_PIPABLE |
2537 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2538 return WIMLIB_ERR_INVALID_PARAM;
2540 /* Save previous header, then start initializing the new one. */
2541 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2543 /* Set default integrity and pipable flags. */
2544 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2545 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2546 if (wim_is_pipable(wim))
2547 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2549 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2550 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2551 if (wim_has_integrity_table(wim))
2552 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2554 /* Set appropriate magic number. */
2555 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2556 wim->hdr.magic = PWM_MAGIC;
2558 wim->hdr.magic = WIM_MAGIC;
2560 /* Clear header flags that will be set automatically. */
2561 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2562 WIM_HDR_FLAG_RESOURCE_ONLY |
2563 WIM_HDR_FLAG_SPANNED |
2564 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2566 /* Set SPANNED header flag if writing part of a split WIM. */
2567 if (total_parts != 1)
2568 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2570 /* Set part number and total parts of split WIM. This will be 1 and 1
2571 * if the WIM is standalone. */
2572 wim->hdr.part_number = part_number;
2573 wim->hdr.total_parts = total_parts;
2575 /* Use GUID if specified; otherwise generate a new one. */
2577 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2578 else if (!wim->guid_set_explicitly)
2579 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2581 /* Clear references to resources that have not been written yet. */
2582 zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2583 zero_resource_entry(&wim->hdr.xml_res_entry);
2584 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2585 zero_resource_entry(&wim->hdr.integrity);
2587 /* Set image count and boot index correctly for single image writes. */
2588 if (image != WIMLIB_ALL_IMAGES) {
2589 wim->hdr.image_count = 1;
2590 if (wim->hdr.boot_idx == image)
2591 wim->hdr.boot_idx = 1;
2593 wim->hdr.boot_idx = 0;
2596 /* Split WIMs can't be bootable. */
2597 if (total_parts != 1)
2598 wim->hdr.boot_idx = 0;
2600 /* Initialize output file descriptor. */
2601 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2602 /* File descriptor was explicitly provided. Return error if
2603 * file descriptor is not seekable, unless writing a pipable WIM
2605 wim->out_fd.fd = *(const int*)path_or_fd;
2606 wim->out_fd.offset = 0;
2607 if (!filedes_is_seekable(&wim->out_fd)) {
2608 ret = WIMLIB_ERR_INVALID_PARAM;
2609 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2610 goto out_restore_hdr;
2611 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2612 ERROR("Can't include integrity check when "
2613 "writing pipable WIM to pipe!");
2614 goto out_restore_hdr;
2619 /* Filename of WIM to write was provided; open file descriptor
2621 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2622 O_TRUNC | O_CREAT | O_RDWR);
2624 goto out_restore_hdr;
2627 /* Write initial header. This is merely a "dummy" header since it
2628 * doesn't have all the information yet, so it will be overwritten later
2629 * (unless writing a pipable WIM). */
2630 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2631 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2632 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2633 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2635 goto out_restore_hdr;
2637 if (stream_list_override) {
2638 struct wim_lookup_table_entry *lte;
2639 INIT_LIST_HEAD(<_stream_list_override);
2640 list_for_each_entry(lte, stream_list_override,
2643 list_add_tail(<e->lookup_table_list,
2644 <_stream_list_override);
2648 /* Write metadata resources and streams. */
2649 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2650 /* Default case: create a normal (non-pipable) WIM. */
2651 ret = write_wim_streams(wim, image, write_flags, num_threads,
2652 progress_func, stream_list_override);
2654 goto out_restore_hdr;
2656 ret = write_wim_metadata_resources(wim, image, write_flags,
2659 goto out_restore_hdr;
2661 /* Non-default case: create pipable WIM. */
2662 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2663 progress_func, stream_list_override);
2665 goto out_restore_hdr;
2666 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2669 if (stream_list_override)
2670 stream_list_override = <_stream_list_override;
2672 /* Write lookup table, XML data, and (optional) integrity table. */
2673 ret = finish_write(wim, image, write_flags, progress_func,
2674 stream_list_override);
2676 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2677 (void)close_wim_writable(wim, write_flags);
2678 DEBUG("ret=%d", ret);
2682 /* Write a standalone WIM to a file or file descriptor. */
2684 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2685 int image, int write_flags, unsigned num_threads,
2686 wimlib_progress_func_t progress_func)
2688 return write_wim_part(wim, path_or_fd, image, write_flags,
2689 num_threads, progress_func, 1, 1, NULL, NULL);
2692 /* API function documented in wimlib.h */
2694 wimlib_write(WIMStruct *wim, const tchar *path,
2695 int image, int write_flags, unsigned num_threads,
2696 wimlib_progress_func_t progress_func)
2699 return WIMLIB_ERR_INVALID_PARAM;
2701 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2703 return write_standalone_wim(wim, path, image, write_flags,
2704 num_threads, progress_func);
2707 /* API function documented in wimlib.h */
2709 wimlib_write_to_fd(WIMStruct *wim, int fd,
2710 int image, int write_flags, unsigned num_threads,
2711 wimlib_progress_func_t progress_func)
2714 return WIMLIB_ERR_INVALID_PARAM;
2716 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2717 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2719 return write_standalone_wim(wim, &fd, image, write_flags,
2720 num_threads, progress_func);
2724 any_images_modified(WIMStruct *wim)
2726 for (int i = 0; i < wim->hdr.image_count; i++)
2727 if (wim->image_metadata[i]->modified)
2733 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2735 const WIMStruct *wim = _wim;
2736 off_t end_offset = *(const off_t*)wim->private;
2738 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == wim &&
2739 lte->resource_entry.offset + lte->resource_entry.size > end_offset)
2740 return WIMLIB_ERR_RESOURCE_ORDER;
2744 /* Make sure no file or metadata resources are located after the XML data (or
2745 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2746 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2748 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2753 wim->private = &end_offset;
2754 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2758 for (i = 0; i < wim->hdr.image_count; i++) {
2759 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2767 * Overwrite a WIM, possibly appending streams to it.
2769 * A WIM looks like (or is supposed to look like) the following:
2771 * Header (212 bytes)
2772 * Streams and metadata resources (variable size)
2773 * Lookup table (variable size)
2774 * XML data (variable size)
2775 * Integrity table (optional) (variable size)
2777 * If we are not adding any streams or metadata resources, the lookup table is
2778 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2779 * header. This operation is potentially unsafe if the program is abruptly
2780 * terminated while the XML data or integrity table are being overwritten, but
2781 * before the new header has been written. To partially alleviate this problem,
2782 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2783 * finish_write() to cause a temporary WIM header to be written after the XML
2784 * data has been written. This may prevent the WIM from becoming corrupted if
2785 * the program is terminated while the integrity table is being calculated (but
2786 * no guarantees, due to write re-ordering...).
2788 * If we are adding new streams or images (metadata resources), the lookup table
2789 * needs to be changed, and those streams need to be written. In this case, we
2790 * try to perform a safe update of the WIM file by writing the streams *after*
2791 * the end of the previous WIM, then writing the new lookup table, XML data, and
2792 * (optionally) integrity table following the new streams. This will produce a
2793 * layout like the following:
2795 * Header (212 bytes)
2796 * (OLD) Streams and metadata resources (variable size)
2797 * (OLD) Lookup table (variable size)
2798 * (OLD) XML data (variable size)
2799 * (OLD) Integrity table (optional) (variable size)
2800 * (NEW) Streams and metadata resources (variable size)
2801 * (NEW) Lookup table (variable size)
2802 * (NEW) XML data (variable size)
2803 * (NEW) Integrity table (optional) (variable size)
2805 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2806 * the header is overwritten to point to the new lookup table, XML data, and
2807 * integrity table, to produce the following layout:
2809 * Header (212 bytes)
2810 * Streams and metadata resources (variable size)
2811 * Nothing (variable size)
2812 * More Streams and metadata resources (variable size)
2813 * Lookup table (variable size)
2814 * XML data (variable size)
2815 * Integrity table (optional) (variable size)
2817 * This method allows an image to be appended to a large WIM very quickly, and
2818 * is is crash-safe except in the case of write re-ordering, but the
2819 * disadvantage is that a small hole is left in the WIM where the old lookup
2820 * table, xml data, and integrity table were. (These usually only take up a
2821 * small amount of space compared to the streams, however.)
2824 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2825 unsigned num_threads,
2826 wimlib_progress_func_t progress_func)
2829 struct list_head stream_list;
2831 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2832 struct wim_header hdr_save;
2834 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2836 /* Set default integrity flag. */
2837 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2838 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2839 if (wim_has_integrity_table(wim))
2840 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2842 /* Set additional flags for overwrite. */
2843 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2844 WIMLIB_WRITE_FLAG_STREAMS_OK;
2846 /* Make sure that the integrity table (if present) is after the XML
2847 * data, and that there are no stream resources, metadata resources, or
2848 * lookup tables after the XML data. Otherwise, these data would be
2850 old_xml_begin = wim->hdr.xml_res_entry.offset;
2851 old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2852 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2853 wim->hdr.lookup_table_res_entry.size;
2854 if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2855 WARNING("Didn't expect the integrity table to be before the XML data");
2856 return WIMLIB_ERR_RESOURCE_ORDER;
2859 if (old_lookup_table_end > old_xml_begin) {
2860 WARNING("Didn't expect the lookup table to be after the XML data");
2861 return WIMLIB_ERR_RESOURCE_ORDER;
2864 /* Set @old_wim_end, which indicates the point beyond which we don't
2865 * allow any file and metadata resources to appear without returning
2866 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2867 * overwrite these resources). */
2868 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2869 /* If no images have been modified and no images have been
2870 * deleted, a new lookup table does not need to be written. We
2871 * shall write the new XML data and optional integrity table
2872 * immediately after the lookup table. Note that this may
2873 * overwrite an existing integrity table. */
2874 DEBUG("Skipping writing lookup table "
2875 "(no images modified or deleted)");
2876 old_wim_end = old_lookup_table_end;
2877 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2878 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2879 } else if (wim->hdr.integrity.offset) {
2880 /* Old WIM has an integrity table; begin writing new streams
2882 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2884 /* No existing integrity table; begin writing new streams after
2885 * the old XML data. */
2886 old_wim_end = old_xml_end;
2889 ret = check_resource_offsets(wim, old_wim_end);
2893 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2898 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2902 ret = lock_wim(wim, wim->out_fd.fd);
2906 /* Save original header so it can be restored in case of error */
2907 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2909 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2910 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2911 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2913 ERROR_WITH_ERRNO("Error updating WIM header flags");
2914 goto out_restore_memory_hdr;
2917 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2918 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2919 ret = WIMLIB_ERR_WRITE;
2920 goto out_restore_physical_hdr;
2923 ret = write_stream_list(&stream_list,
2926 wim->compression_type,
2934 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2935 write_flags, progress_func);
2939 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2940 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2941 progress_func, NULL);
2945 goto out_unlock_wim;
2948 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2949 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2950 wim->filename, old_wim_end);
2951 /* Return value of ftruncate() is ignored because this is
2952 * already an error path. */
2953 (void)ftruncate(wim->out_fd.fd, old_wim_end);
2955 out_restore_physical_hdr:
2956 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
2957 out_restore_memory_hdr:
2958 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2960 (void)close_wim_writable(wim, write_flags);
2962 wim->wim_locked = 0;
2967 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2968 unsigned num_threads,
2969 wimlib_progress_func_t progress_func)
2971 size_t wim_name_len;
2974 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2976 /* Write the WIM to a temporary file in the same directory as the
2978 wim_name_len = tstrlen(wim->filename);
2979 tchar tmpfile[wim_name_len + 10];
2980 tmemcpy(tmpfile, wim->filename, wim_name_len);
2981 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2982 tmpfile[wim_name_len + 9] = T('\0');
2984 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2985 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2986 num_threads, progress_func);
2994 /* Rename the new WIM file to the original WIM file. Note: on Windows
2995 * this actually calls win32_rename_replacement(), not _wrename(), so
2996 * that removing the existing destination file can be handled. */
2997 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
2998 ret = trename(tmpfile, wim->filename);
3000 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3001 tmpfile, wim->filename);
3008 return WIMLIB_ERR_RENAME;
3011 if (progress_func) {
3012 union wimlib_progress_info progress;
3013 progress.rename.from = tmpfile;
3014 progress.rename.to = wim->filename;
3015 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3020 /* API function documented in wimlib.h */
3022 wimlib_overwrite(WIMStruct *wim, int write_flags,
3023 unsigned num_threads,
3024 wimlib_progress_func_t progress_func)
3029 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3031 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3032 return WIMLIB_ERR_INVALID_PARAM;
3035 return WIMLIB_ERR_NO_FILENAME;
3037 orig_hdr_flags = wim->hdr.flags;
3038 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3039 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3040 ret = can_modify_wim(wim);
3041 wim->hdr.flags = orig_hdr_flags;
3045 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3046 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3047 WIMLIB_WRITE_FLAG_PIPABLE))
3048 && !(wim_is_pipable(wim)))
3050 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3052 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3054 WARNING("Falling back to re-building entire WIM");
3056 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,