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 alloc_lzx_context(int write_resource_flags, struct wimlib_lzx_context **ctx_pp)
74 struct wimlib_lzx_params params;
75 params.size_of_this = sizeof(params);
76 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_COMPRESS_SLOW)
77 params.algorithm = WIMLIB_LZX_ALGORITHM_SLOW;
79 params.algorithm = WIMLIB_LZX_ALGORITHM_FAST;
80 params.use_defaults = 1;
81 return wimlib_lzx_alloc_context(¶ms, ctx_pp);
85 compress_chunk(const void * uncompressed_data,
86 unsigned uncompressed_len,
87 void *compressed_data,
89 struct wimlib_lzx_context *comp_ctx)
92 case WIMLIB_COMPRESSION_TYPE_XPRESS:
93 return wimlib_xpress_compress(uncompressed_data,
96 case WIMLIB_COMPRESSION_TYPE_LZX:
97 return wimlib_lzx_compress2(uncompressed_data,
107 /* Chunk table that's located at the beginning of each compressed resource in
108 * the WIM. (This is not the on-disk format; the on-disk format just has an
109 * array of offsets.) */
111 u64 original_resource_size;
114 unsigned bytes_per_chunk_entry;
120 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
121 * integers, including the first offset of 0, which will not be written.
123 u8 offsets[] _aligned_attribute(8);
126 /* Allocate and initializes a chunk table, then reserve space for it in the
127 * output file unless writing a pipable resource. */
129 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
130 struct filedes *out_fd,
131 struct chunk_table **chunk_tab_ret,
136 unsigned bytes_per_chunk_entry;
138 struct chunk_table *chunk_tab;
141 size = wim_resource_size(lte);
142 num_chunks = wim_resource_chunks(lte);
143 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
144 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
145 chunk_tab = CALLOC(1, alloc_size);
148 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
150 return WIMLIB_ERR_NOMEM;
152 chunk_tab->num_chunks = num_chunks;
153 chunk_tab->original_resource_size = size;
154 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
155 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
157 chunk_tab->cur_offset_p = chunk_tab->offsets;
159 /* We don't know the correct offsets yet; so just write zeroes to
160 * reserve space for the table, so we can go back to it later after
161 * we've written the compressed chunks following it.
163 * Special case: if writing a pipable WIM, compressed resources are in a
164 * modified format (see comment above write_pipable_wim()) and do not
165 * have a chunk table at the beginning, so don't reserve any space for
167 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
168 ret = full_write(out_fd, chunk_tab->offsets,
169 chunk_tab->table_disk_size);
171 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
177 *chunk_tab_ret = chunk_tab;
181 /* Add the offset for the next chunk to the chunk table being constructed for a
182 * compressed stream. */
184 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
186 if (chunk_tab->bytes_per_chunk_entry == 4) {
187 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
188 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
189 chunk_tab->cur_offset_u32 += out_chunk_size;
191 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
192 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
193 chunk_tab->cur_offset_u64 += out_chunk_size;
197 /* Finishes a WIM chunk table and writes it to the output file at the correct
200 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
201 struct filedes *out_fd,
202 off_t res_start_offset,
203 int write_resource_flags)
207 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
208 ret = full_write(out_fd,
210 chunk_tab->bytes_per_chunk_entry,
211 chunk_tab->table_disk_size);
213 ret = full_pwrite(out_fd,
215 chunk_tab->bytes_per_chunk_entry,
216 chunk_tab->table_disk_size,
220 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
226 /* Write the header for a stream in a pipable WIM.
229 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
230 struct filedes *out_fd,
231 int additional_reshdr_flags)
233 struct pwm_stream_hdr stream_hdr;
237 stream_hdr.magic = PWM_STREAM_MAGIC;
238 stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
239 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
240 zero_out_hash(stream_hdr.hash);
242 wimlib_assert(!lte->unhashed);
243 copy_hash(stream_hdr.hash, lte->hash);
246 reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
247 reshdr_flags |= additional_reshdr_flags;
248 stream_hdr.flags = cpu_to_le32(reshdr_flags);
249 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
251 ERROR_WITH_ERRNO("Error writing stream header");
256 seek_and_truncate(struct filedes *out_fd, off_t offset)
258 if (filedes_seek(out_fd, offset) == -1 ||
259 ftruncate(out_fd->fd, offset))
261 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
262 return WIMLIB_ERR_WRITE;
268 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
270 u8 md[SHA1_HASH_SIZE];
272 sha1_final(md, sha_ctx);
274 copy_hash(lte->hash, md);
275 } else if (!hashes_equal(md, lte->hash)) {
276 ERROR("WIM resource has incorrect hash!");
277 if (lte_filename_valid(lte)) {
278 ERROR("We were reading it from \"%"TS"\"; maybe "
279 "it changed while we were reading it.",
282 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
287 struct write_resource_ctx {
289 struct wimlib_lzx_context *comp_ctx;
290 struct chunk_table *chunk_tab;
291 struct filedes *out_fd;
298 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
300 struct write_resource_ctx *ctx = _ctx;
301 const void *out_chunk;
302 unsigned out_chunk_size;
306 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
309 out_chunk_size = chunk_size;
310 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
311 void *compressed_chunk;
312 unsigned compressed_size;
314 /* Compress the chunk. */
315 compressed_chunk = alloca(chunk_size);
317 compressed_size = compress_chunk(chunk, chunk_size,
321 /* Use compressed data if compression to less than input size
323 if (compressed_size) {
324 out_chunk = compressed_chunk;
325 out_chunk_size = compressed_size;
329 if (ctx->chunk_tab) {
330 /* Update chunk table accounting. */
331 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
333 /* If writing compressed chunks to a pipable WIM, before the
334 * chunk data write a chunk header that provides the compressed
336 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
337 struct pwm_chunk_hdr chunk_hdr = {
338 .compressed_size = cpu_to_le32(out_chunk_size),
340 ret = full_write(ctx->out_fd, &chunk_hdr,
347 /* Write the chunk data. */
348 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
354 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
359 * write_wim_resource()-
361 * Write a resource to an output WIM.
364 * Lookup table entry for the resource, which could be in another WIM, in
365 * an external file, or in another location.
368 * File descriptor opened to the output WIM.
371 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
372 * compression algorithm to use.
375 * On success, this is filled in with the offset, flags, compressed size,
376 * and uncompressed size of the resource in the output WIM.
379 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
380 * if it could otherwise be copied directly from the input;
381 * * WIMLIB_WRITE_RESOURCE_FLAG_COMPRESS_SLOW to compress the data as much
383 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
384 * (and the output file descriptor may be a pipe).
387 * Location of LZX compression context pointer, which will be allocated or
388 * updated if needed. (Initialize to NULL.)
390 * Additional notes: The SHA1 message digest of the uncompressed data is
391 * calculated (except when doing a raw copy --- see below). If the @unhashed
392 * flag is set on the lookup table entry, this message digest is simply copied
393 * to it; otherwise, the message digest is compared with the existing one, and
394 * the function will fail if they do not match.
397 write_wim_resource(struct wim_lookup_table_entry *lte,
398 struct filedes *out_fd, int out_ctype,
399 struct resource_entry *out_res_entry,
401 struct wimlib_lzx_context **comp_ctx)
403 struct write_resource_ctx write_ctx;
404 off_t res_start_offset;
408 /* Mask out any irrelevant flags, since this function also uses this
409 * variable to store WIMLIB_READ_RESOURCE flags. */
410 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
412 /* Get current position in output WIM. */
413 res_start_offset = out_fd->offset;
415 /* If we are not forcing the data to be recompressed, and the input
416 * resource is located in a WIM with the same compression type as that
417 * desired other than no compression, we can simply copy the compressed
418 * data without recompressing it. This also means we must skip
419 * calculating the SHA1, as we never will see the uncompressed data. */
420 if (lte->resource_location == RESOURCE_IN_WIM &&
421 out_ctype == wim_resource_compression_type(lte) &&
422 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
423 !(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS))
425 /* Normally we can request a RAW_FULL read, but if we're reading
426 * from a pipable resource and writing a non-pipable resource or
427 * vice versa, then a RAW_CHUNKS read needs to be requested so
428 * that the written resource can be appropriately formatted.
429 * However, in neither case is any actual decompression needed.
431 if (lte->is_pipable == !!(resource_flags &
432 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
433 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
435 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
436 write_ctx.doing_sha = false;
437 read_size = lte->resource_entry.size;
439 write_ctx.doing_sha = true;
440 sha1_init(&write_ctx.sha_ctx);
441 read_size = lte->resource_entry.original_size;
445 /* If the output resource is to be compressed, initialize the chunk
446 * table and set the function to use for chunk compression. Exceptions:
447 * no compression function is needed if doing a raw copy; also, no chunk
448 * table is needed if doing a *full* (not per-chunk) raw copy. */
449 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
450 write_ctx.chunk_tab = NULL;
451 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
452 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
453 write_ctx.out_ctype = out_ctype;
454 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
455 ret = alloc_lzx_context(resource_flags, comp_ctx);
459 write_ctx.comp_ctx = *comp_ctx;
461 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
462 ret = begin_wim_resource_chunk_tab(lte, out_fd,
463 &write_ctx.chunk_tab,
470 /* If writing a pipable resource, write the stream header and update
471 * @res_start_offset to be the end of the stream header. */
472 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
473 int reshdr_flags = 0;
474 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
475 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
476 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
478 goto out_free_chunk_tab;
479 res_start_offset = out_fd->offset;
482 /* Write the entire resource by reading the entire resource and feeding
483 * the data through the write_resource_cb function. */
484 write_ctx.out_fd = out_fd;
485 write_ctx.resource_flags = resource_flags;
487 ret = read_resource_prefix(lte, read_size,
488 write_resource_cb, &write_ctx, resource_flags);
490 goto out_free_chunk_tab;
492 /* Verify SHA1 message digest of the resource, or set the hash for the
494 if (write_ctx.doing_sha) {
495 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
497 goto out_free_chunk_tab;
500 /* Write chunk table if needed. */
501 if (write_ctx.chunk_tab) {
502 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
507 goto out_free_chunk_tab;
510 /* Fill in out_res_entry with information about the newly written
512 out_res_entry->size = out_fd->offset - res_start_offset;
513 out_res_entry->flags = lte->resource_entry.flags;
514 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
515 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
517 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
518 out_res_entry->offset = res_start_offset;
519 out_res_entry->original_size = wim_resource_size(lte);
521 /* Check for resources compressed to greater than their original size
522 * and write them uncompressed instead. (But never do this if writing
523 * to a pipe, and don't bother if we did a raw copy.) */
524 if (out_res_entry->size > out_res_entry->original_size &&
525 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
526 WIMLIB_READ_RESOURCE_FLAG_RAW)))
528 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
529 "writing uncompressed instead",
530 out_res_entry->original_size, out_res_entry->size);
531 ret = seek_and_truncate(out_fd, res_start_offset);
533 goto out_free_chunk_tab;
534 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
535 FREE(write_ctx.chunk_tab);
536 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
537 write_ctx.chunk_tab = NULL;
538 write_ctx.doing_sha = false;
539 goto try_write_again;
541 if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
542 DEBUG("Copied raw compressed data "
543 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
544 out_res_entry->original_size, out_res_entry->size,
545 out_res_entry->offset, out_res_entry->flags);
546 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
547 DEBUG("Wrote compressed resource "
548 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
549 out_res_entry->original_size, out_res_entry->size,
550 out_res_entry->offset, out_res_entry->flags);
552 DEBUG("Wrote uncompressed resource "
553 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
554 out_res_entry->original_size,
555 out_res_entry->offset, out_res_entry->flags);
559 FREE(write_ctx.chunk_tab);
564 /* Like write_wim_resource(), but the resource is specified by a buffer of
565 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
566 * the buffer to @hash_ret. */
568 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
569 int reshdr_flags, struct filedes *out_fd,
571 struct resource_entry *out_res_entry,
572 u8 *hash_ret, int write_resource_flags,
573 struct wimlib_lzx_context **comp_ctx)
575 /* Set up a temporary lookup table entry to provide to
576 * write_wim_resource(). */
577 struct wim_lookup_table_entry lte;
580 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
581 lte.attached_buffer = (void*)buf;
582 lte.resource_entry.original_size = buf_size;
583 lte.resource_entry.flags = reshdr_flags;
585 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
586 sha1_buffer(buf, buf_size, lte.hash);
592 ret = write_wim_resource(<e, out_fd, out_ctype, out_res_entry,
593 write_resource_flags, comp_ctx);
597 copy_hash(hash_ret, lte.hash);
602 #ifdef ENABLE_MULTITHREADED_COMPRESSION
604 /* Blocking shared queue (solves the producer-consumer problem) */
605 struct shared_queue {
609 unsigned filled_slots;
611 pthread_mutex_t lock;
612 pthread_cond_t msg_avail_cond;
613 pthread_cond_t space_avail_cond;
617 shared_queue_init(struct shared_queue *q, unsigned size)
619 wimlib_assert(size != 0);
620 q->array = CALLOC(sizeof(q->array[0]), size);
627 if (pthread_mutex_init(&q->lock, NULL)) {
628 ERROR_WITH_ERRNO("Failed to initialize mutex");
631 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
632 ERROR_WITH_ERRNO("Failed to initialize condition variable");
633 goto err_destroy_lock;
635 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
636 ERROR_WITH_ERRNO("Failed to initialize condition variable");
637 goto err_destroy_msg_avail_cond;
640 err_destroy_msg_avail_cond:
641 pthread_cond_destroy(&q->msg_avail_cond);
643 pthread_mutex_destroy(&q->lock);
645 return WIMLIB_ERR_NOMEM;
649 shared_queue_destroy(struct shared_queue *q)
652 pthread_mutex_destroy(&q->lock);
653 pthread_cond_destroy(&q->msg_avail_cond);
654 pthread_cond_destroy(&q->space_avail_cond);
658 shared_queue_put(struct shared_queue *q, void *obj)
660 pthread_mutex_lock(&q->lock);
661 while (q->filled_slots == q->size)
662 pthread_cond_wait(&q->space_avail_cond, &q->lock);
664 q->back = (q->back + 1) % q->size;
665 q->array[q->back] = obj;
668 pthread_cond_broadcast(&q->msg_avail_cond);
669 pthread_mutex_unlock(&q->lock);
673 shared_queue_get(struct shared_queue *q)
677 pthread_mutex_lock(&q->lock);
678 while (q->filled_slots == 0)
679 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
681 obj = q->array[q->front];
682 q->array[q->front] = NULL;
683 q->front = (q->front + 1) % q->size;
686 pthread_cond_broadcast(&q->space_avail_cond);
687 pthread_mutex_unlock(&q->lock);
691 struct compressor_thread_params {
692 struct shared_queue *res_to_compress_queue;
693 struct shared_queue *compressed_res_queue;
695 struct wimlib_lzx_context *comp_ctx;
698 #define MAX_CHUNKS_PER_MSG 2
701 struct wim_lookup_table_entry *lte;
702 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
703 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
704 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
705 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
707 struct list_head list;
713 compress_chunks(struct message *msg, int out_ctype,
714 struct wimlib_lzx_context *comp_ctx)
716 for (unsigned i = 0; i < msg->num_chunks; i++) {
719 len = compress_chunk(msg->uncompressed_chunks[i],
720 msg->uncompressed_chunk_sizes[i],
721 msg->compressed_chunks[i],
728 /* To be written compressed */
729 out_chunk = msg->compressed_chunks[i];
732 /* To be written uncompressed */
733 out_chunk = msg->uncompressed_chunks[i];
734 out_len = msg->uncompressed_chunk_sizes[i];
736 msg->out_chunks[i].iov_base = out_chunk;
737 msg->out_chunks[i].iov_len = out_len;
741 /* Compressor thread routine. This is a lot simpler than the main thread
742 * routine: just repeatedly get a group of chunks from the
743 * res_to_compress_queue, compress them, and put them in the
744 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
747 compressor_thread_proc(void *arg)
749 struct compressor_thread_params *params = arg;
750 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
751 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
754 DEBUG("Compressor thread ready");
755 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
756 compress_chunks(msg, params->out_ctype, params->comp_ctx);
757 shared_queue_put(compressed_res_queue, msg);
759 DEBUG("Compressor thread terminating");
762 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
764 struct write_streams_progress_data {
765 wimlib_progress_func_t progress_func;
766 union wimlib_progress_info progress;
767 uint64_t next_progress;
768 WIMStruct *prev_wim_part;
772 do_write_streams_progress(struct write_streams_progress_data *progress_data,
773 struct wim_lookup_table_entry *lte,
774 bool stream_discarded)
776 union wimlib_progress_info *progress = &progress_data->progress;
779 if (stream_discarded) {
780 progress->write_streams.total_bytes -= wim_resource_size(lte);
781 if (progress_data->next_progress != ~(uint64_t)0 &&
782 progress_data->next_progress > progress->write_streams.total_bytes)
784 progress_data->next_progress = progress->write_streams.total_bytes;
787 progress->write_streams.completed_bytes += wim_resource_size(lte);
789 new_wim_part = false;
790 if (lte->resource_location == RESOURCE_IN_WIM &&
791 lte->wim != progress_data->prev_wim_part)
793 if (progress_data->prev_wim_part) {
795 progress->write_streams.completed_parts++;
797 progress_data->prev_wim_part = lte->wim;
799 progress->write_streams.completed_streams++;
800 if (progress_data->progress_func
801 && (progress->write_streams.completed_bytes >= progress_data->next_progress
804 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
806 if (progress_data->next_progress == progress->write_streams.total_bytes) {
807 progress_data->next_progress = ~(uint64_t)0;
809 progress_data->next_progress =
810 min(progress->write_streams.total_bytes,
811 progress->write_streams.completed_bytes +
812 progress->write_streams.total_bytes / 100);
817 struct serial_write_stream_ctx {
818 struct filedes *out_fd;
820 struct wimlib_lzx_context **comp_ctx;
821 int write_resource_flags;
825 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
827 struct serial_write_stream_ctx *ctx = _ctx;
828 return write_wim_resource(lte, ctx->out_fd,
829 ctx->out_ctype, <e->output_resource_entry,
830 ctx->write_resource_flags,
835 /* Write a list of streams, taking into account that some streams may be
836 * duplicates that are checksummed and discarded on the fly, and also delegating
837 * the actual writing of a stream to a function @write_stream_cb, which is
838 * passed the context @write_stream_ctx. */
840 do_write_stream_list(struct list_head *stream_list,
841 struct wim_lookup_table *lookup_table,
842 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
843 void *write_stream_ctx,
844 struct write_streams_progress_data *progress_data)
847 struct wim_lookup_table_entry *lte;
848 bool stream_discarded;
850 /* For each stream in @stream_list ... */
851 while (!list_empty(stream_list)) {
852 stream_discarded = false;
853 lte = container_of(stream_list->next,
854 struct wim_lookup_table_entry,
856 list_del(<e->write_streams_list);
857 if (lte->unhashed && !lte->unique_size) {
858 /* Unhashed stream that shares a size with some other
859 * stream in the WIM we are writing. The stream must be
860 * checksummed to know if we need to write it or not. */
861 struct wim_lookup_table_entry *tmp;
862 u32 orig_out_refcnt = lte->out_refcnt;
864 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
868 /* We found a duplicate stream. 'lte' was
869 * freed, so replace it with the duplicate. */
872 /* 'out_refcnt' was transferred to the
873 * duplicate, and we can detect if the duplicate
874 * stream was already referenced for writing by
875 * checking if its 'out_refcnt' is higher than
876 * that of the original stream. In such cases,
877 * the current stream can be discarded. We can
878 * also discard the current stream if it was
879 * previously marked as filtered (e.g. already
880 * present in the WIM being written). */
881 if (lte->out_refcnt > orig_out_refcnt ||
883 DEBUG("Discarding duplicate stream of "
885 wim_resource_size(lte));
886 lte->no_progress = 0;
887 stream_discarded = true;
888 goto skip_to_progress;
893 /* Here, @lte is either a hashed stream or an unhashed stream
894 * with a unique size. In either case we know that the stream
895 * has to be written. In either case the SHA1 message digest
896 * will be calculated over the stream while writing it; however,
897 * in the former case this is done merely to check the data,
898 * while in the latter case this is done because we do not have
899 * the SHA1 message digest yet. */
900 wimlib_assert(lte->out_refcnt != 0);
902 lte->no_progress = 0;
903 ret = (*write_stream_cb)(lte, write_stream_ctx);
906 /* In parallel mode, some streams are deferred for later,
907 * serialized processing; ignore them here. */
911 list_del(<e->unhashed_list);
912 lookup_table_insert(lookup_table, lte);
916 if (!lte->no_progress) {
917 do_write_streams_progress(progress_data,
918 lte, stream_discarded);
925 do_write_stream_list_serial(struct list_head *stream_list,
926 struct wim_lookup_table *lookup_table,
927 struct filedes *out_fd,
929 struct wimlib_lzx_context **comp_ctx,
930 int write_resource_flags,
931 struct write_streams_progress_data *progress_data)
933 struct serial_write_stream_ctx ctx = {
935 .out_ctype = out_ctype,
936 .write_resource_flags = write_resource_flags,
937 .comp_ctx = comp_ctx,
939 return do_write_stream_list(stream_list,
947 write_flags_to_resource_flags(int write_flags)
949 int resource_flags = 0;
951 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
952 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
953 if (write_flags & WIMLIB_WRITE_FLAG_COMPRESS_SLOW)
954 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_COMPRESS_SLOW;
955 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
956 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
957 return resource_flags;
961 write_stream_list_serial(struct list_head *stream_list,
962 struct wim_lookup_table *lookup_table,
963 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 union wimlib_progress_info *progress = &progress_data->progress;
970 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
971 progress->write_streams.total_streams);
972 progress->write_streams.num_threads = 1;
973 if (progress_data->progress_func) {
974 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
977 return do_write_stream_list_serial(stream_list,
982 write_resource_flags,
986 #ifdef ENABLE_MULTITHREADED_COMPRESSION
988 write_wim_chunks(struct message *msg, struct filedes *out_fd,
989 struct chunk_table *chunk_tab,
990 int write_resource_flags)
993 struct pwm_chunk_hdr *chunk_hdrs;
997 for (unsigned i = 0; i < msg->num_chunks; i++)
998 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1000 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1001 nvecs = msg->num_chunks;
1002 vecs = msg->out_chunks;
1004 /* Special case: If writing a compressed resource to a pipable
1005 * WIM, prefix each compressed chunk with a header that gives
1006 * its compressed size. */
1007 nvecs = msg->num_chunks * 2;
1008 vecs = alloca(nvecs * sizeof(vecs[0]));
1009 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1011 for (unsigned i = 0; i < msg->num_chunks; i++) {
1012 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1013 vecs[i * 2].iov_base = &chunk_hdrs[i];
1014 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1015 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1016 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1019 ret = full_writev(out_fd, vecs, nvecs);
1021 ERROR_WITH_ERRNO("Failed to write WIM chunks");
1025 struct main_writer_thread_ctx {
1026 struct list_head *stream_list;
1027 struct wim_lookup_table *lookup_table;
1028 struct filedes *out_fd;
1029 off_t res_start_offset;
1031 struct wimlib_lzx_context **comp_ctx;
1032 int write_resource_flags;
1033 struct shared_queue *res_to_compress_queue;
1034 struct shared_queue *compressed_res_queue;
1035 size_t num_messages;
1036 struct write_streams_progress_data *progress_data;
1038 struct list_head available_msgs;
1039 struct list_head outstanding_streams;
1040 struct list_head serial_streams;
1041 size_t num_outstanding_messages;
1043 SHA_CTX next_sha_ctx;
1045 u64 next_num_chunks;
1046 struct wim_lookup_table_entry *next_lte;
1048 struct message *msgs;
1049 struct message *next_msg;
1050 struct chunk_table *cur_chunk_tab;
1054 init_message(struct message *msg)
1056 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1057 msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1058 msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
1059 if (msg->compressed_chunks[i] == NULL ||
1060 msg->uncompressed_chunks[i] == NULL)
1061 return WIMLIB_ERR_NOMEM;
1067 destroy_message(struct message *msg)
1069 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1070 FREE(msg->compressed_chunks[i]);
1071 FREE(msg->uncompressed_chunks[i]);
1076 free_messages(struct message *msgs, size_t num_messages)
1079 for (size_t i = 0; i < num_messages; i++)
1080 destroy_message(&msgs[i]);
1085 static struct message *
1086 allocate_messages(size_t num_messages)
1088 struct message *msgs;
1090 msgs = CALLOC(num_messages, sizeof(struct message));
1093 for (size_t i = 0; i < num_messages; i++) {
1094 if (init_message(&msgs[i])) {
1095 free_messages(msgs, num_messages);
1103 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1105 while (ctx->num_outstanding_messages--)
1106 shared_queue_get(ctx->compressed_res_queue);
1107 free_messages(ctx->msgs, ctx->num_messages);
1108 FREE(ctx->cur_chunk_tab);
1112 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1114 /* Pre-allocate all the buffers that will be needed to do the chunk
1116 ctx->msgs = allocate_messages(ctx->num_messages);
1118 return WIMLIB_ERR_NOMEM;
1120 /* Initially, all the messages are available to use. */
1121 INIT_LIST_HEAD(&ctx->available_msgs);
1122 for (size_t i = 0; i < ctx->num_messages; i++)
1123 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1125 /* outstanding_streams is the list of streams that currently have had
1126 * chunks sent off for compression.
1128 * The first stream in outstanding_streams is the stream that is
1129 * currently being written.
1131 * The last stream in outstanding_streams is the stream that is
1132 * currently being read and having chunks fed to the compressor threads.
1134 INIT_LIST_HEAD(&ctx->outstanding_streams);
1135 ctx->num_outstanding_messages = 0;
1137 ctx->next_msg = NULL;
1139 /* Resources that don't need any chunks compressed are added to this
1140 * list and written directly by the main thread. */
1141 INIT_LIST_HEAD(&ctx->serial_streams);
1143 ctx->cur_chunk_tab = NULL;
1149 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1151 struct message *msg;
1152 struct wim_lookup_table_entry *cur_lte;
1155 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1156 wimlib_assert(ctx->num_outstanding_messages != 0);
1158 cur_lte = container_of(ctx->outstanding_streams.next,
1159 struct wim_lookup_table_entry,
1160 being_compressed_list);
1162 /* Get the next message from the queue and process it.
1163 * The message will contain 1 or more data chunks that have been
1165 msg = shared_queue_get(ctx->compressed_res_queue);
1166 msg->complete = true;
1167 --ctx->num_outstanding_messages;
1169 /* Is this the next chunk in the current resource? If it's not
1170 * (i.e., an earlier chunk in a same or different resource
1171 * hasn't been compressed yet), do nothing, and keep this
1172 * message around until all earlier chunks are received.
1174 * Otherwise, write all the chunks we can. */
1175 while (cur_lte != NULL &&
1176 !list_empty(&cur_lte->msg_list)
1177 && (msg = container_of(cur_lte->msg_list.next,
1181 list_move(&msg->list, &ctx->available_msgs);
1182 if (msg->begin_chunk == 0) {
1183 /* First set of chunks. */
1185 /* Write pipable WIM stream header if needed. */
1186 if (ctx->write_resource_flags &
1187 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1189 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1190 WIM_RESHDR_FLAG_COMPRESSED);
1195 /* Save current offset. */
1196 ctx->res_start_offset = ctx->out_fd->offset;
1198 /* Begin building the chunk table, and leave space for
1200 ret = begin_wim_resource_chunk_tab(cur_lte,
1202 &ctx->cur_chunk_tab,
1203 ctx->write_resource_flags);
1209 /* Write the compressed chunks from the message. */
1210 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1211 ctx->write_resource_flags);
1215 /* Was this the last chunk of the stream? If so, finish
1217 if (list_empty(&cur_lte->msg_list) &&
1218 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1222 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1224 ctx->res_start_offset,
1225 ctx->write_resource_flags);
1229 list_del(&cur_lte->being_compressed_list);
1231 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1233 FREE(ctx->cur_chunk_tab);
1234 ctx->cur_chunk_tab = NULL;
1236 /* Check for resources compressed to greater than or
1237 * equal to their original size and write them
1238 * uncompressed instead. (But never do this if writing
1240 if (res_csize >= wim_resource_size(cur_lte) &&
1241 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1243 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1244 "writing uncompressed instead",
1245 wim_resource_size(cur_lte), res_csize);
1246 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1249 ret = write_wim_resource(cur_lte,
1251 WIMLIB_COMPRESSION_TYPE_NONE,
1252 &cur_lte->output_resource_entry,
1253 ctx->write_resource_flags,
1258 cur_lte->output_resource_entry.size =
1261 cur_lte->output_resource_entry.original_size =
1262 cur_lte->resource_entry.original_size;
1264 cur_lte->output_resource_entry.offset =
1265 ctx->res_start_offset;
1267 cur_lte->output_resource_entry.flags =
1268 cur_lte->resource_entry.flags |
1269 WIM_RESHDR_FLAG_COMPRESSED;
1271 DEBUG("Wrote compressed resource "
1272 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1273 cur_lte->output_resource_entry.original_size,
1274 cur_lte->output_resource_entry.size,
1275 cur_lte->output_resource_entry.offset,
1276 cur_lte->output_resource_entry.flags);
1279 do_write_streams_progress(ctx->progress_data,
1282 /* Since we just finished writing a stream, write any
1283 * streams that have been added to the serial_streams
1284 * list for direct writing by the main thread (e.g.
1285 * resources that don't need to be compressed because
1286 * the desired compression type is the same as the
1287 * previous compression type). */
1288 if (!list_empty(&ctx->serial_streams)) {
1289 ret = do_write_stream_list_serial(&ctx->serial_streams,
1294 ctx->write_resource_flags,
1295 ctx->progress_data);
1300 /* Advance to the next stream to write. */
1301 if (list_empty(&ctx->outstanding_streams)) {
1304 cur_lte = container_of(ctx->outstanding_streams.next,
1305 struct wim_lookup_table_entry,
1306 being_compressed_list);
1313 /* Called when the main thread has read a new chunk of data. */
1315 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1317 struct main_writer_thread_ctx *ctx = _ctx;
1319 struct message *next_msg;
1320 u64 next_chunk_in_msg;
1322 /* Update SHA1 message digest for the stream currently being read by the
1324 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1326 /* We send chunks of data to the compressor chunks in batches which we
1327 * refer to as "messages". @next_msg is the message that is currently
1328 * being prepared to send off. If it is NULL, that indicates that we
1329 * need to start a new message. */
1330 next_msg = ctx->next_msg;
1332 /* We need to start a new message. First check to see if there
1333 * is a message available in the list of available messages. If
1334 * so, we can just take one. If not, all the messages (there is
1335 * a fixed number of them, proportional to the number of
1336 * threads) have been sent off to the compressor threads, so we
1337 * receive messages from the compressor threads containing
1338 * compressed chunks of data.
1340 * We may need to receive multiple messages before one is
1341 * actually available to use because messages received that are
1342 * *not* for the very next set of chunks to compress must be
1343 * buffered until it's time to write those chunks. */
1344 while (list_empty(&ctx->available_msgs)) {
1345 ret = receive_compressed_chunks(ctx);
1350 next_msg = container_of(ctx->available_msgs.next,
1351 struct message, list);
1352 list_del(&next_msg->list);
1353 next_msg->complete = false;
1354 next_msg->begin_chunk = ctx->next_chunk;
1355 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1356 ctx->next_num_chunks - ctx->next_chunk);
1357 ctx->next_msg = next_msg;
1360 /* Fill in the next chunk to compress */
1361 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1363 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1364 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1367 if (++next_chunk_in_msg == next_msg->num_chunks) {
1368 /* Send off an array of chunks to compress */
1369 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1370 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1371 ++ctx->num_outstanding_messages;
1372 ctx->next_msg = NULL;
1378 main_writer_thread_finish(void *_ctx)
1380 struct main_writer_thread_ctx *ctx = _ctx;
1382 while (ctx->num_outstanding_messages != 0) {
1383 ret = receive_compressed_chunks(ctx);
1387 wimlib_assert(list_empty(&ctx->outstanding_streams));
1388 return do_write_stream_list_serial(&ctx->serial_streams,
1393 ctx->write_resource_flags,
1394 ctx->progress_data);
1398 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1399 struct main_writer_thread_ctx *ctx)
1403 /* Read the entire stream @lte, feeding its data chunks to the
1404 * compressor threads. Also SHA1-sum the stream; this is required in
1405 * the case that @lte is unhashed, and a nice additional verification
1406 * when @lte is already hashed. */
1407 sha1_init(&ctx->next_sha_ctx);
1408 ctx->next_chunk = 0;
1409 ctx->next_num_chunks = wim_resource_chunks(lte);
1410 ctx->next_lte = lte;
1411 INIT_LIST_HEAD(<e->msg_list);
1412 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1413 ret = read_resource_prefix(lte, wim_resource_size(lte),
1414 main_writer_thread_cb, ctx, 0);
1417 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1418 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1422 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1424 struct main_writer_thread_ctx *ctx = _ctx;
1427 if (wim_resource_size(lte) < 1000 ||
1428 ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
1429 (lte->resource_location == RESOURCE_IN_WIM &&
1430 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS) &&
1431 lte->wim->compression_type == ctx->out_ctype))
1433 /* Stream is too small or isn't being compressed. Process it by
1434 * the main thread when we have a chance. We can't necessarily
1435 * process it right here, as the main thread could be in the
1436 * middle of writing a different stream. */
1437 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1441 ret = submit_stream_for_compression(lte, ctx);
1443 lte->no_progress = 1;
1448 get_default_num_threads(void)
1451 return win32_get_number_of_processors();
1453 return sysconf(_SC_NPROCESSORS_ONLN);
1457 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1458 * parameter and will perform compression using that many threads. Falls
1459 * back to write_stream_list_serial() on certain errors, such as a failure to
1460 * create the number of threads requested.
1462 * High level description of the algorithm for writing compressed streams in
1463 * parallel: We perform compression on chunks of size WIM_CHUNK_SIZE bytes
1464 * rather than on full files. The currently executing thread becomes the main
1465 * thread and is entirely in charge of reading the data to compress (which may
1466 * be in any location understood by the resource code--- such as in an external
1467 * file being captured, or in another WIM file from which an image is being
1468 * exported) and actually writing the compressed data to the output file.
1469 * Additional threads are "compressor threads" and all execute the
1470 * compressor_thread_proc, where they repeatedly retrieve buffers of data from
1471 * the main thread, compress them, and hand them back to the main thread.
1473 * Certain streams, such as streams that do not need to be compressed (e.g.
1474 * input compression type same as output compression type) or streams of very
1475 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1476 * handled entirely by the main thread at an appropriate time.
1478 * At any given point in time, multiple streams may be having chunks compressed
1479 * concurrently. The stream that the main thread is currently *reading* may be
1480 * later in the list that the stream that the main thread is currently
1484 write_stream_list_parallel(struct list_head *stream_list,
1485 struct wim_lookup_table *lookup_table,
1486 struct filedes *out_fd,
1488 struct wimlib_lzx_context **comp_ctx,
1489 int write_resource_flags,
1490 struct write_streams_progress_data *progress_data,
1491 unsigned num_threads)
1494 struct shared_queue res_to_compress_queue;
1495 struct shared_queue compressed_res_queue;
1496 pthread_t *compressor_threads = NULL;
1497 union wimlib_progress_info *progress = &progress_data->progress;
1499 if (num_threads == 0) {
1500 long nthreads = get_default_num_threads();
1501 if (nthreads < 1 || nthreads > UINT_MAX) {
1502 WARNING("Could not determine number of processors! Assuming 1");
1504 } else if (nthreads == 1) {
1505 goto out_serial_quiet;
1507 num_threads = nthreads;
1511 DEBUG("Writing stream list of size %"PRIu64" "
1512 "(parallel version, num_threads=%u)",
1513 progress->write_streams.total_streams, num_threads);
1515 progress->write_streams.num_threads = num_threads;
1517 static const size_t MESSAGES_PER_THREAD = 2;
1518 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1520 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1522 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1526 ret = shared_queue_init(&compressed_res_queue, queue_size);
1528 goto out_destroy_res_to_compress_queue;
1530 struct compressor_thread_params *params;
1532 params = CALLOC(num_threads, sizeof(params[0]));
1533 if (params == NULL) {
1534 ret = WIMLIB_ERR_NOMEM;
1535 goto out_destroy_compressed_res_queue;
1538 for (unsigned i = 0; i < num_threads; i++) {
1539 params[i].res_to_compress_queue = &res_to_compress_queue;
1540 params[i].compressed_res_queue = &compressed_res_queue;
1541 params[i].out_ctype = out_ctype;
1542 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1543 ret = alloc_lzx_context(write_resource_flags,
1544 ¶ms[i].comp_ctx);
1546 goto out_free_params;
1550 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1551 if (!compressor_threads) {
1552 ret = WIMLIB_ERR_NOMEM;
1553 goto out_free_params;
1556 for (unsigned i = 0; i < num_threads; i++) {
1557 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1558 ret = pthread_create(&compressor_threads[i], NULL,
1559 compressor_thread_proc, ¶ms[i]);
1562 ERROR_WITH_ERRNO("Failed to create compressor "
1564 i + 1, num_threads);
1570 if (progress_data->progress_func) {
1571 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1575 struct main_writer_thread_ctx ctx;
1576 ctx.stream_list = stream_list;
1577 ctx.lookup_table = lookup_table;
1578 ctx.out_fd = out_fd;
1579 ctx.out_ctype = out_ctype;
1580 ctx.comp_ctx = comp_ctx;
1581 ctx.res_to_compress_queue = &res_to_compress_queue;
1582 ctx.compressed_res_queue = &compressed_res_queue;
1583 ctx.num_messages = queue_size;
1584 ctx.write_resource_flags = write_resource_flags;
1585 ctx.progress_data = progress_data;
1586 ret = main_writer_thread_init_ctx(&ctx);
1589 ret = do_write_stream_list(stream_list, lookup_table,
1590 main_thread_process_next_stream,
1591 &ctx, progress_data);
1593 goto out_destroy_ctx;
1595 /* The main thread has finished reading all streams that are going to be
1596 * compressed in parallel, and it now needs to wait for all remaining
1597 * chunks to be compressed so that the remaining streams can actually be
1598 * written to the output file. Furthermore, any remaining streams that
1599 * had processing deferred to the main thread need to be handled. These
1600 * tasks are done by the main_writer_thread_finish() function. */
1601 ret = main_writer_thread_finish(&ctx);
1603 main_writer_thread_destroy_ctx(&ctx);
1605 for (unsigned i = 0; i < num_threads; i++)
1606 shared_queue_put(&res_to_compress_queue, NULL);
1608 for (unsigned i = 0; i < num_threads; i++) {
1609 if (pthread_join(compressor_threads[i], NULL)) {
1610 WARNING_WITH_ERRNO("Failed to join compressor "
1612 i + 1, num_threads);
1615 FREE(compressor_threads);
1617 for (unsigned i = 0; i < num_threads; i++)
1618 wimlib_lzx_free_context(params[i].comp_ctx);
1620 out_destroy_compressed_res_queue:
1621 shared_queue_destroy(&compressed_res_queue);
1622 out_destroy_res_to_compress_queue:
1623 shared_queue_destroy(&res_to_compress_queue);
1624 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1627 WARNING("Falling back to single-threaded compression");
1629 return write_stream_list_serial(stream_list,
1634 write_resource_flags,
1641 * Write a list of streams to a WIM (@out_fd) using the compression type
1642 * @out_ctype and up to @num_threads compressor threads.
1645 write_stream_list(struct list_head *stream_list,
1646 struct wim_lookup_table *lookup_table,
1647 struct filedes *out_fd, int out_ctype,
1648 struct wimlib_lzx_context **comp_ctx,
1650 unsigned num_threads, wimlib_progress_func_t progress_func)
1652 struct wim_lookup_table_entry *lte;
1653 size_t num_streams = 0;
1654 u64 total_bytes = 0;
1655 u64 total_compression_bytes = 0;
1656 struct write_streams_progress_data progress_data;
1658 int write_resource_flags;
1659 unsigned total_parts = 0;
1660 WIMStruct *prev_wim_part = NULL;
1662 if (list_empty(stream_list)) {
1663 DEBUG("No streams to write.");
1667 write_resource_flags = write_flags_to_resource_flags(write_flags);
1669 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1670 out_fd->offset, write_resource_flags);
1672 sort_stream_list_by_sequential_order(stream_list,
1673 offsetof(struct wim_lookup_table_entry,
1674 write_streams_list));
1676 /* Calculate the total size of the streams to be written. Note: this
1677 * will be the uncompressed size, as we may not know the compressed size
1678 * yet, and also this will assume that every unhashed stream will be
1679 * written (which will not necessarily be the case). */
1680 list_for_each_entry(lte, stream_list, write_streams_list) {
1682 total_bytes += wim_resource_size(lte);
1683 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1684 && (wim_resource_compression_type(lte) != out_ctype ||
1685 (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)))
1687 total_compression_bytes += wim_resource_size(lte);
1689 if (lte->resource_location == RESOURCE_IN_WIM) {
1690 if (prev_wim_part != lte->wim) {
1691 prev_wim_part = lte->wim;
1697 memset(&progress_data, 0, sizeof(progress_data));
1698 progress_data.progress_func = progress_func;
1700 progress_data.progress.write_streams.total_bytes = total_bytes;
1701 progress_data.progress.write_streams.total_streams = num_streams;
1702 progress_data.progress.write_streams.completed_bytes = 0;
1703 progress_data.progress.write_streams.completed_streams = 0;
1704 progress_data.progress.write_streams.num_threads = num_threads;
1705 progress_data.progress.write_streams.compression_type = out_ctype;
1706 progress_data.progress.write_streams.total_parts = total_parts;
1707 progress_data.progress.write_streams.completed_parts = 0;
1709 progress_data.next_progress = 0;
1710 progress_data.prev_wim_part = NULL;
1712 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1713 if (total_compression_bytes >= 2000000 && num_threads != 1)
1714 ret = write_stream_list_parallel(stream_list,
1719 write_resource_flags,
1724 ret = write_stream_list_serial(stream_list,
1729 write_resource_flags,
1732 DEBUG("Successfully wrote stream list.");
1734 DEBUG("Failed to write stream list.");
1738 struct stream_size_table {
1739 struct hlist_head *array;
1745 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1747 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1749 return WIMLIB_ERR_NOMEM;
1750 tab->num_entries = 0;
1751 tab->capacity = capacity;
1756 destroy_stream_size_table(struct stream_size_table *tab)
1762 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1764 struct stream_size_table *tab = _tab;
1766 struct wim_lookup_table_entry *same_size_lte;
1767 struct hlist_node *tmp;
1769 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1770 lte->unique_size = 1;
1771 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1772 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1773 lte->unique_size = 0;
1774 same_size_lte->unique_size = 0;
1779 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1784 struct find_streams_ctx {
1787 struct list_head stream_list;
1788 struct stream_size_table stream_size_tab;
1792 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1793 struct find_streams_ctx *ctx,
1796 if (lte->out_refcnt == 0) {
1797 stream_size_table_insert(lte, &ctx->stream_size_tab);
1798 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1800 lte->out_refcnt += nref;
1804 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1807 struct find_streams_ctx *ctx = _ctx;
1808 lte->out_refcnt = 0;
1809 lte_reference_for_logical_write(lte, ctx,
1810 (lte->refcnt ? lte->refcnt : 1));
1815 inode_find_streams_to_write(struct wim_inode *inode,
1816 struct wim_lookup_table *table,
1817 struct find_streams_ctx *ctx)
1819 struct wim_lookup_table_entry *lte;
1822 for (i = 0; i <= inode->i_num_ads; i++) {
1823 lte = inode_stream_lte(inode, i, table);
1825 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1826 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1827 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1833 image_find_streams_to_write(WIMStruct *wim)
1835 struct find_streams_ctx *ctx;
1836 struct wim_image_metadata *imd;
1837 struct wim_inode *inode;
1838 struct wim_lookup_table_entry *lte;
1842 imd = wim_get_current_image_metadata(wim);
1844 image_for_each_unhashed_stream(lte, imd)
1845 lte->out_refcnt = 0;
1847 /* Go through this image's inodes to find any streams that have not been
1849 image_for_each_inode(inode, imd) {
1850 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1858 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1859 * the "logical write" of the WIM, meaning all streams that are referenced at
1860 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1861 * each stream being included in the logical write is set to the number of
1862 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1863 * stream being included in the logical write is set to indicate whether that
1864 * stream has a unique size relative to the streams being included in the
1865 * logical write. Still furthermore, 'part_number' on each stream being
1866 * included in the logical write is set to the part number given in the
1867 * in-memory header of @p wim.
1869 * This is considered a "logical write" because it does not take into account
1870 * filtering out streams already present in the WIM (in the case of an in place
1871 * overwrite) or present in other WIMs (in case of creating delta WIM).
1874 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1875 struct find_streams_ctx *ctx)
1878 struct wim_lookup_table_entry *lte;
1880 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1881 (image == 1 && wim->hdr.image_count == 1)))
1883 /* Fast case: Assume that all streams are being written and
1884 * that the reference counts are correct. */
1885 struct wim_lookup_table_entry *lte;
1886 struct wim_image_metadata *imd;
1889 for_lookup_table_entry(wim->lookup_table,
1890 do_lte_full_reference_for_logical_write, ctx);
1891 for (i = 0; i < wim->hdr.image_count; i++) {
1892 imd = wim->image_metadata[i];
1893 image_for_each_unhashed_stream(lte, imd)
1894 do_lte_full_reference_for_logical_write(lte, ctx);
1897 /* Slow case: Walk through the images being written and
1898 * determine the streams referenced. */
1899 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1901 ret = for_image(wim, image, image_find_streams_to_write);
1906 list_for_each_entry(lte, &ctx->stream_list, write_streams_list)
1907 lte->part_number = wim->hdr.part_number;
1912 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1914 struct find_streams_ctx *ctx = _ctx;
1917 /* Calculate and set lte->filtered. */
1918 if (lte->resource_location == RESOURCE_IN_WIM) {
1919 if (lte->wim == ctx->wim &&
1920 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1921 filtered |= FILTERED_SAME_WIM;
1922 if (lte->wim != ctx->wim &&
1923 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1924 filtered |= FILTERED_EXTERNAL_WIM;
1926 lte->filtered = filtered;
1928 /* Filtered streams get inserted into the stream size table too, unless
1929 * they already were. This is because streams that are checksummed
1930 * on-the-fly during the write should not be written if they are
1931 * duplicates of filtered stream. */
1932 if (lte->filtered && lte->out_refcnt == 0)
1933 stream_size_table_insert(lte, &ctx->stream_size_tab);
1938 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
1944 /* Given the list of streams to include in a logical write of a WIM, handle
1945 * filtering out streams already present in the WIM or already present in
1946 * external WIMs, depending on the write flags provided. */
1948 handle_stream_filtering(struct find_streams_ctx *ctx)
1950 struct wim_lookup_table_entry *lte, *tmp;
1952 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
1953 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
1955 for_lookup_table_entry(ctx->wim->lookup_table,
1956 mark_stream_not_filtered, ctx);
1960 for_lookup_table_entry(ctx->wim->lookup_table,
1961 process_filtered_stream, ctx);
1963 /* Streams in logical write list that were filtered can be removed. */
1964 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
1967 list_del(<e->write_streams_list);
1970 /* Prepares list of streams to write for the specified WIM image(s). This wraps
1971 * around prepare_logical_stream_list() to handle filtering out streams already
1972 * present in the WIM or already present in external WIMs, depending on the
1973 * write flags provided.
1975 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
1977 * - 'out_refcnt' is set to the number of references found for the logical write.
1978 * This will be nonzero on all streams in the list returned by this function,
1979 * but will also be nonzero on streams not in the list that were included in
1980 * the logical write list, but filtered out from the returned list.
1981 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
1982 * are not included in the list of streams returned by this function.
1983 * - 'unique_size' is set if the stream has a unique size among all streams in
1984 * the logical write plus any filtered streams in the entire WIM that could
1985 * potentially turn out to have the same checksum as a yet-to-be-checksummed
1986 * stream being written.
1989 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
1990 struct list_head *stream_list)
1994 struct find_streams_ctx ctx;
1996 INIT_LIST_HEAD(&ctx.stream_list);
1997 ret = init_stream_size_table(&ctx.stream_size_tab,
1998 wim->lookup_table->capacity);
2001 ctx.write_flags = write_flags;
2004 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2006 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2008 goto out_destroy_table;
2010 handle_stream_filtering(&ctx);
2011 list_transfer(&ctx.stream_list, stream_list);
2014 destroy_stream_size_table(&ctx.stream_size_tab);
2019 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2020 unsigned num_threads,
2021 wimlib_progress_func_t progress_func,
2022 struct list_head *stream_list_override)
2025 struct list_head _stream_list;
2026 struct list_head *stream_list;
2027 struct wim_lookup_table_entry *lte;
2029 if (stream_list_override == NULL) {
2030 /* Normal case: prepare stream list from image(s) being written.
2032 stream_list = &_stream_list;
2033 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2037 /* Currently only as a result of wimlib_split() being called:
2038 * use stream list already explicitly provided. Use existing
2039 * reference counts. */
2040 stream_list = stream_list_override;
2041 list_for_each_entry(lte, stream_list, write_streams_list) {
2042 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2043 lte->part_number = wim->hdr.part_number;
2047 return write_stream_list(stream_list,
2050 wim->compression_type,
2058 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2059 wimlib_progress_func_t progress_func)
2064 int write_resource_flags;
2066 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2067 DEBUG("Not writing any metadata resources.");
2071 write_resource_flags = write_flags_to_resource_flags(write_flags);
2073 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2074 wim->out_fd.offset);
2077 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2079 if (image == WIMLIB_ALL_IMAGES) {
2081 end_image = wim->hdr.image_count;
2083 start_image = image;
2087 for (int i = start_image; i <= end_image; i++) {
2088 struct wim_image_metadata *imd;
2090 imd = wim->image_metadata[i - 1];
2091 /* Build a new metadata resource only if image was modified from
2092 * the original (or was newly added). Otherwise just copy the
2094 if (imd->modified) {
2095 DEBUG("Image %u was modified; building and writing new "
2096 "metadata resource", i);
2097 ret = write_metadata_resource(wim, i,
2098 write_resource_flags);
2099 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2100 DEBUG("Image %u was not modified; re-using existing "
2101 "metadata resource.", i);
2102 copy_resource_entry(&imd->metadata_lte->output_resource_entry,
2103 &imd->metadata_lte->resource_entry);
2106 DEBUG("Image %u was not modified; copying existing "
2107 "metadata resource.", i);
2108 ret = write_wim_resource(imd->metadata_lte,
2110 wim->compression_type,
2111 &imd->metadata_lte->output_resource_entry,
2112 write_resource_flags,
2119 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2124 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2127 DEBUG("Opening \"%"TS"\" for writing.", path);
2129 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2131 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2132 return WIMLIB_ERR_OPEN;
2134 filedes_init(&wim->out_fd, raw_fd);
2139 close_wim_writable(WIMStruct *wim, int write_flags)
2143 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR))
2144 if (filedes_valid(&wim->out_fd))
2145 if (filedes_close(&wim->out_fd))
2146 ret = WIMLIB_ERR_WRITE;
2147 filedes_invalidate(&wim->out_fd);
2154 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2155 * table, then overwrite the WIM header. By default, closes the WIM file
2156 * descriptor (@wim->out_fd) if successful.
2158 * write_flags is a bitwise OR of the following:
2160 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2161 * Include an integrity table.
2163 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2164 * fsync() the output file before closing it.
2166 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2167 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2168 * stream headers before the lookup table and XML data, and also
2169 * write the WIM header at the end instead of seeking to the
2170 * beginning. Can't be combined with
2171 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2173 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2174 * Don't write the lookup table.
2176 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2177 * When (if) writing the integrity table, re-use entries from the
2178 * existing integrity table, if possible.
2180 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2181 * After writing the XML data but before writing the integrity
2182 * table, write a temporary WIM header and flush the stream so that
2183 * the WIM is less likely to become corrupted upon abrupt program
2185 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2186 * Instead of overwriting the WIM header at the beginning of the
2187 * file, simply append it to the end of the file. (Used when
2189 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2190 * Do not close the file descriptor @wim->out_fd on either success
2192 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2193 * Use the existing <TOTALBYTES> stored in the in-memory XML
2194 * information, rather than setting it to the offset of the XML
2195 * data being written.
2198 finish_write(WIMStruct *wim, int image, int write_flags,
2199 wimlib_progress_func_t progress_func,
2200 struct list_head *stream_list_override)
2204 int write_resource_flags;
2205 off_t old_lookup_table_end;
2206 off_t new_lookup_table_end;
2209 write_resource_flags = write_flags_to_resource_flags(write_flags);
2211 /* In the WIM header, there is room for the resource entry for a
2212 * metadata resource labeled as the "boot metadata". This entry should
2213 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2214 * it should be a copy of the resource entry for the image that is
2215 * marked as bootable. This is not well documented... */
2216 if (wim->hdr.boot_idx == 0) {
2217 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2219 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2220 &wim->image_metadata[wim->hdr.boot_idx- 1
2221 ]->metadata_lte->output_resource_entry);
2224 /* Write lookup table. (Save old position first.) */
2225 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2226 wim->hdr.lookup_table_res_entry.size;
2227 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2228 ret = write_wim_lookup_table(wim, image, write_flags,
2229 &wim->hdr.lookup_table_res_entry,
2230 stream_list_override);
2235 /* Write XML data. */
2236 xml_totalbytes = wim->out_fd.offset;
2237 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2238 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2239 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2240 &wim->hdr.xml_res_entry,
2241 write_resource_flags);
2245 /* Write integrity table (optional). */
2246 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2247 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2248 struct wim_header checkpoint_hdr;
2249 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2250 zero_resource_entry(&checkpoint_hdr.integrity);
2251 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2252 ret = write_wim_header_at_offset(&checkpoint_hdr,
2258 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2259 old_lookup_table_end = 0;
2261 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2262 wim->hdr.lookup_table_res_entry.size;
2264 ret = write_integrity_table(wim,
2265 new_lookup_table_end,
2266 old_lookup_table_end,
2271 /* No integrity table. */
2272 zero_resource_entry(&wim->hdr.integrity);
2275 /* Now that all information in the WIM header has been determined, the
2276 * preliminary header written earlier can be overwritten, the header of
2277 * the existing WIM file can be overwritten, or the final header can be
2278 * written to the end of the pipable WIM. */
2279 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2281 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2282 hdr_offset = wim->out_fd.offset;
2283 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2287 /* Possibly sync file data to disk before closing. On POSIX systems, it
2288 * is necessary to do this before using rename() to overwrite an
2289 * existing file with a new file. Otherwise, data loss would occur if
2290 * the system is abruptly terminated when the metadata for the rename
2291 * operation has been written to disk, but the new file data has not.
2293 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2294 if (fsync(wim->out_fd.fd)) {
2295 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2296 return WIMLIB_ERR_WRITE;
2300 if (close_wim_writable(wim, write_flags)) {
2301 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2302 return WIMLIB_ERR_WRITE;
2308 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2310 lock_wim(WIMStruct *wim, int fd)
2313 if (fd != -1 && !wim->wim_locked) {
2314 ret = flock(fd, LOCK_EX | LOCK_NB);
2316 if (errno == EWOULDBLOCK) {
2317 ERROR("`%"TS"' is already being modified or has been "
2318 "mounted read-write\n"
2319 " by another process!", wim->filename);
2320 ret = WIMLIB_ERR_ALREADY_LOCKED;
2322 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2327 wim->wim_locked = 1;
2335 * write_pipable_wim():
2337 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2338 * capable of being applied from a pipe).
2340 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2341 * images can be applied from them sequentially when the file data is sent over
2342 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2343 * The modifications made to the WIM format for pipable WIMs are:
2345 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2346 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2347 * stops other software from trying to read the file as a normal WIM.
2349 * - The header at the beginning of the file does not contain all the normal
2350 * information; in particular it will have all 0's for the lookup table and
2351 * XML data resource entries. This is because this information cannot be
2352 * determined until the lookup table and XML data have been written.
2353 * Consequently, wimlib will write the full header at the very end of the
2354 * file. The header at the end, however, is only used when reading the WIM
2355 * from a seekable file (not a pipe).
2357 * - An extra copy of the XML data is placed directly after the header. This
2358 * allows image names and sizes to be determined at an appropriate time when
2359 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2360 * WIM is read from a seekable file (not a pipe).
2362 * - The format of resources, or streams, has been modified to allow them to be
2363 * used before the "lookup table" has been read. Each stream is prefixed with
2364 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2365 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2366 * uncompressed stream size, and flags that indicate whether the stream is
2367 * compressed. The data of uncompressed streams then follows literally, while
2368 * the data of compressed streams follows in a modified format. Compressed
2369 * streams do not begin with a chunk table, since the chunk table cannot be
2370 * written until all chunks have been compressed. Instead, each compressed
2371 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2372 * Furthermore, the chunk table is written at the end of the resource instead
2373 * of the start. Note: chunk offsets are given in the chunk table as if the
2374 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2375 * used if the WIM is being read from a seekable file (not a pipe).
2377 * - Metadata resources always come before other file resources (streams).
2378 * (This does not by itself constitute an incompatibility with normal WIMs,
2379 * since this is valid in normal WIMs.)
2381 * - At least up to the end of the file resources, all components must be packed
2382 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2383 * not by itself consititute an incompatibility with normal WIMs, since this
2384 * is valid in normal WIMs.)
2386 * Note: the lookup table, XML data, and header at the end are not used when
2387 * applying from a pipe. They exist to support functionality such as image
2388 * application and export when the WIM is *not* read from a pipe.
2390 * Layout of pipable WIM:
2392 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2393 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2394 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2396 * Layout of normal WIM:
2398 * +--------+-----------------------------+-------------------------+
2399 * | Header | File and metadata resources | Lookup table | XML data |
2400 * +--------+-----------------------------+-------------------------+
2402 * An optional integrity table can follow the final XML data in both normal and
2403 * pipable WIMs. However, due to implementation details, wimlib currently can
2404 * only include an integrity table in a pipable WIM when writing it to a
2405 * seekable file (not a pipe).
2407 * Do note that since pipable WIMs are not supported by Microsoft's software,
2408 * wimlib does not create them unless explicitly requested (with
2409 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2410 * characters to identify the file.
2413 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2414 unsigned num_threads, wimlib_progress_func_t progress_func,
2415 struct list_head *stream_list_override)
2418 struct resource_entry xml_res_entry;
2420 WARNING("Creating a pipable WIM, which will "
2422 " with Microsoft's software (wimgapi/imagex/Dism).");
2424 /* At this point, the header at the beginning of the file has already
2427 /* For efficiency, when wimlib adds an image to the WIM with
2428 * wimlib_add_image(), the SHA1 message digests of files is not
2429 * calculated; instead, they are calculated while the files are being
2430 * written. However, this does not work when writing a pipable WIM,
2431 * since when writing a stream to a pipable WIM, its SHA1 message digest
2432 * needs to be known before the stream data is written. Therefore,
2433 * before getting much farther, we need to pre-calculate the SHA1
2434 * message digests of all streams that will be written. */
2435 ret = wim_checksum_unhashed_streams(wim);
2439 /* Write extra copy of the XML data. */
2440 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2442 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2446 /* Write metadata resources for the image(s) being included in the
2448 ret = write_wim_metadata_resources(wim, image, write_flags,
2453 /* Write streams needed for the image(s) being included in the output
2454 * WIM, or streams needed for the split WIM part. */
2455 return write_wim_streams(wim, image, write_flags, num_threads,
2456 progress_func, stream_list_override);
2458 /* The lookup table, XML data, and header at end are handled by
2459 * finish_write(). */
2462 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2465 write_wim_part(WIMStruct *wim,
2466 const void *path_or_fd,
2469 unsigned num_threads,
2470 wimlib_progress_func_t progress_func,
2471 unsigned part_number,
2472 unsigned total_parts,
2473 struct list_head *stream_list_override,
2477 struct wim_header hdr_save;
2478 struct list_head lt_stream_list_override;
2480 if (total_parts == 1)
2481 DEBUG("Writing standalone WIM.");
2483 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2484 if (image == WIMLIB_ALL_IMAGES)
2485 DEBUG("Including all images.");
2487 DEBUG("Including image %d only.", image);
2488 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2489 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2491 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2492 DEBUG("Write flags: 0x%08x", write_flags);
2493 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2494 DEBUG("\tCHECK_INTEGRITY");
2495 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2497 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2498 DEBUG("\tRECOMPRESS");
2499 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2501 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2503 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2504 DEBUG("\tIGNORE_READONLY_FLAG");
2505 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2507 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2508 DEBUG("\tFILE_DESCRIPTOR");
2509 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2510 DEBUG("\tNO_METADATA");
2511 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2512 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2513 if (num_threads == 0)
2514 DEBUG("Number of threads: autodetect");
2516 DEBUG("Number of threads: %u", num_threads);
2517 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2518 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2519 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2520 "specified" : "generate new"));
2522 /* Internally, this is always called with a valid part number and total
2524 wimlib_assert(total_parts >= 1);
2525 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2527 /* A valid image (or all images) must be specified. */
2528 if (image != WIMLIB_ALL_IMAGES &&
2529 (image < 1 || image > wim->hdr.image_count))
2530 return WIMLIB_ERR_INVALID_IMAGE;
2532 /* If we need to write metadata resources, make sure the ::WIMStruct has
2533 * the needed information attached (e.g. is not a resource-only WIM,
2534 * such as a non-first part of a split WIM). */
2535 if (!wim_has_metadata(wim) &&
2536 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2537 return WIMLIB_ERR_METADATA_NOT_FOUND;
2539 /* Check for contradictory flags. */
2540 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2541 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2542 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2543 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2544 return WIMLIB_ERR_INVALID_PARAM;
2546 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2547 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2548 == (WIMLIB_WRITE_FLAG_PIPABLE |
2549 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2550 return WIMLIB_ERR_INVALID_PARAM;
2552 /* Save previous header, then start initializing the new one. */
2553 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2555 /* Set default integrity and pipable flags. */
2556 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2557 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2558 if (wim_is_pipable(wim))
2559 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2561 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2562 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2563 if (wim_has_integrity_table(wim))
2564 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2566 /* Set appropriate magic number. */
2567 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2568 wim->hdr.magic = PWM_MAGIC;
2570 wim->hdr.magic = WIM_MAGIC;
2572 /* Clear header flags that will be set automatically. */
2573 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2574 WIM_HDR_FLAG_RESOURCE_ONLY |
2575 WIM_HDR_FLAG_SPANNED |
2576 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2578 /* Set SPANNED header flag if writing part of a split WIM. */
2579 if (total_parts != 1)
2580 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2582 /* Set part number and total parts of split WIM. This will be 1 and 1
2583 * if the WIM is standalone. */
2584 wim->hdr.part_number = part_number;
2585 wim->hdr.total_parts = total_parts;
2587 /* Use GUID if specified; otherwise generate a new one. */
2589 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2590 else if (!wim->guid_set_explicitly)
2591 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2593 /* Clear references to resources that have not been written yet. */
2594 zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2595 zero_resource_entry(&wim->hdr.xml_res_entry);
2596 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2597 zero_resource_entry(&wim->hdr.integrity);
2599 /* Set image count and boot index correctly for single image writes. */
2600 if (image != WIMLIB_ALL_IMAGES) {
2601 wim->hdr.image_count = 1;
2602 if (wim->hdr.boot_idx == image)
2603 wim->hdr.boot_idx = 1;
2605 wim->hdr.boot_idx = 0;
2608 /* Split WIMs can't be bootable. */
2609 if (total_parts != 1)
2610 wim->hdr.boot_idx = 0;
2612 /* Initialize output file descriptor. */
2613 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2614 /* File descriptor was explicitly provided. Return error if
2615 * file descriptor is not seekable, unless writing a pipable WIM
2617 wim->out_fd.fd = *(const int*)path_or_fd;
2618 wim->out_fd.offset = 0;
2619 if (!filedes_is_seekable(&wim->out_fd)) {
2620 ret = WIMLIB_ERR_INVALID_PARAM;
2621 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2622 goto out_restore_hdr;
2623 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2624 ERROR("Can't include integrity check when "
2625 "writing pipable WIM to pipe!");
2626 goto out_restore_hdr;
2631 /* Filename of WIM to write was provided; open file descriptor
2633 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2634 O_TRUNC | O_CREAT | O_RDWR);
2636 goto out_restore_hdr;
2639 /* Write initial header. This is merely a "dummy" header since it
2640 * doesn't have all the information yet, so it will be overwritten later
2641 * (unless writing a pipable WIM). */
2642 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2643 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2644 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2645 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2647 goto out_restore_hdr;
2649 if (stream_list_override) {
2650 struct wim_lookup_table_entry *lte;
2651 INIT_LIST_HEAD(<_stream_list_override);
2652 list_for_each_entry(lte, stream_list_override,
2655 list_add_tail(<e->lookup_table_list,
2656 <_stream_list_override);
2660 /* Write metadata resources and streams. */
2661 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2662 /* Default case: create a normal (non-pipable) WIM. */
2663 ret = write_wim_streams(wim, image, write_flags, num_threads,
2664 progress_func, stream_list_override);
2666 goto out_restore_hdr;
2668 ret = write_wim_metadata_resources(wim, image, write_flags,
2671 goto out_restore_hdr;
2673 /* Non-default case: create pipable WIM. */
2674 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2675 progress_func, stream_list_override);
2677 goto out_restore_hdr;
2678 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2681 if (stream_list_override)
2682 stream_list_override = <_stream_list_override;
2684 /* Write lookup table, XML data, and (optional) integrity table. */
2685 ret = finish_write(wim, image, write_flags, progress_func,
2686 stream_list_override);
2688 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2689 (void)close_wim_writable(wim, write_flags);
2693 /* Write a standalone WIM to a file or file descriptor. */
2695 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2696 int image, int write_flags, unsigned num_threads,
2697 wimlib_progress_func_t progress_func)
2699 return write_wim_part(wim, path_or_fd, image, write_flags,
2700 num_threads, progress_func, 1, 1, NULL, NULL);
2703 /* API function documented in wimlib.h */
2705 wimlib_write(WIMStruct *wim, const tchar *path,
2706 int image, int write_flags, unsigned num_threads,
2707 wimlib_progress_func_t progress_func)
2710 return WIMLIB_ERR_INVALID_PARAM;
2712 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2714 return write_standalone_wim(wim, path, image, write_flags,
2715 num_threads, progress_func);
2718 /* API function documented in wimlib.h */
2720 wimlib_write_to_fd(WIMStruct *wim, int fd,
2721 int image, int write_flags, unsigned num_threads,
2722 wimlib_progress_func_t progress_func)
2725 return WIMLIB_ERR_INVALID_PARAM;
2727 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2728 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2730 return write_standalone_wim(wim, &fd, image, write_flags,
2731 num_threads, progress_func);
2735 any_images_modified(WIMStruct *wim)
2737 for (int i = 0; i < wim->hdr.image_count; i++)
2738 if (wim->image_metadata[i]->modified)
2744 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2746 const WIMStruct *wim = _wim;
2747 off_t end_offset = *(const off_t*)wim->private;
2749 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == wim &&
2750 lte->resource_entry.offset + lte->resource_entry.size > end_offset)
2751 return WIMLIB_ERR_RESOURCE_ORDER;
2755 /* Make sure no file or metadata resources are located after the XML data (or
2756 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2757 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2759 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2764 wim->private = &end_offset;
2765 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2769 for (i = 0; i < wim->hdr.image_count; i++) {
2770 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2778 * Overwrite a WIM, possibly appending streams to it.
2780 * A WIM looks like (or is supposed to look like) the following:
2782 * Header (212 bytes)
2783 * Streams and metadata resources (variable size)
2784 * Lookup table (variable size)
2785 * XML data (variable size)
2786 * Integrity table (optional) (variable size)
2788 * If we are not adding any streams or metadata resources, the lookup table is
2789 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2790 * header. This operation is potentially unsafe if the program is abruptly
2791 * terminated while the XML data or integrity table are being overwritten, but
2792 * before the new header has been written. To partially alleviate this problem,
2793 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2794 * finish_write() to cause a temporary WIM header to be written after the XML
2795 * data has been written. This may prevent the WIM from becoming corrupted if
2796 * the program is terminated while the integrity table is being calculated (but
2797 * no guarantees, due to write re-ordering...).
2799 * If we are adding new streams or images (metadata resources), the lookup table
2800 * needs to be changed, and those streams need to be written. In this case, we
2801 * try to perform a safe update of the WIM file by writing the streams *after*
2802 * the end of the previous WIM, then writing the new lookup table, XML data, and
2803 * (optionally) integrity table following the new streams. This will produce a
2804 * layout like the following:
2806 * Header (212 bytes)
2807 * (OLD) Streams and metadata resources (variable size)
2808 * (OLD) Lookup table (variable size)
2809 * (OLD) XML data (variable size)
2810 * (OLD) Integrity table (optional) (variable size)
2811 * (NEW) Streams and metadata resources (variable size)
2812 * (NEW) Lookup table (variable size)
2813 * (NEW) XML data (variable size)
2814 * (NEW) Integrity table (optional) (variable size)
2816 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2817 * the header is overwritten to point to the new lookup table, XML data, and
2818 * integrity table, to produce the following layout:
2820 * Header (212 bytes)
2821 * Streams and metadata resources (variable size)
2822 * Nothing (variable size)
2823 * More Streams and metadata resources (variable size)
2824 * Lookup table (variable size)
2825 * XML data (variable size)
2826 * Integrity table (optional) (variable size)
2828 * This method allows an image to be appended to a large WIM very quickly, and
2829 * is is crash-safe except in the case of write re-ordering, but the
2830 * disadvantage is that a small hole is left in the WIM where the old lookup
2831 * table, xml data, and integrity table were. (These usually only take up a
2832 * small amount of space compared to the streams, however.)
2835 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2836 unsigned num_threads,
2837 wimlib_progress_func_t progress_func)
2840 struct list_head stream_list;
2842 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2843 struct wim_header hdr_save;
2845 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2847 /* Set default integrity flag. */
2848 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2849 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2850 if (wim_has_integrity_table(wim))
2851 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2853 /* Set additional flags for overwrite. */
2854 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2855 WIMLIB_WRITE_FLAG_STREAMS_OK;
2857 /* Make sure that the integrity table (if present) is after the XML
2858 * data, and that there are no stream resources, metadata resources, or
2859 * lookup tables after the XML data. Otherwise, these data would be
2861 old_xml_begin = wim->hdr.xml_res_entry.offset;
2862 old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2863 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2864 wim->hdr.lookup_table_res_entry.size;
2865 if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2866 WARNING("Didn't expect the integrity table to be before the XML data");
2867 return WIMLIB_ERR_RESOURCE_ORDER;
2870 if (old_lookup_table_end > old_xml_begin) {
2871 WARNING("Didn't expect the lookup table to be after the XML data");
2872 return WIMLIB_ERR_RESOURCE_ORDER;
2875 /* Set @old_wim_end, which indicates the point beyond which we don't
2876 * allow any file and metadata resources to appear without returning
2877 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2878 * overwrite these resources). */
2879 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2880 /* If no images have been modified and no images have been
2881 * deleted, a new lookup table does not need to be written. We
2882 * shall write the new XML data and optional integrity table
2883 * immediately after the lookup table. Note that this may
2884 * overwrite an existing integrity table. */
2885 DEBUG("Skipping writing lookup table "
2886 "(no images modified or deleted)");
2887 old_wim_end = old_lookup_table_end;
2888 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2889 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2890 } else if (wim->hdr.integrity.offset) {
2891 /* Old WIM has an integrity table; begin writing new streams
2893 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2895 /* No existing integrity table; begin writing new streams after
2896 * the old XML data. */
2897 old_wim_end = old_xml_end;
2900 ret = check_resource_offsets(wim, old_wim_end);
2904 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2909 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2913 ret = lock_wim(wim, wim->out_fd.fd);
2917 /* Save original header so it can be restored in case of error */
2918 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2920 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2921 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2922 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2924 ERROR_WITH_ERRNO("Error updating WIM header flags");
2925 goto out_restore_memory_hdr;
2928 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2929 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2930 ret = WIMLIB_ERR_WRITE;
2931 goto out_restore_physical_hdr;
2934 ret = write_stream_list(&stream_list,
2937 wim->compression_type,
2945 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2946 write_flags, progress_func);
2950 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2951 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2952 progress_func, NULL);
2956 goto out_unlock_wim;
2959 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2960 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2961 wim->filename, old_wim_end);
2962 /* Return value of ftruncate() is ignored because this is
2963 * already an error path. */
2964 (void)ftruncate(wim->out_fd.fd, old_wim_end);
2966 out_restore_physical_hdr:
2967 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
2968 out_restore_memory_hdr:
2969 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2971 (void)close_wim_writable(wim, write_flags);
2973 wim->wim_locked = 0;
2978 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2979 unsigned num_threads,
2980 wimlib_progress_func_t progress_func)
2982 size_t wim_name_len;
2985 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2987 /* Write the WIM to a temporary file in the same directory as the
2989 wim_name_len = tstrlen(wim->filename);
2990 tchar tmpfile[wim_name_len + 10];
2991 tmemcpy(tmpfile, wim->filename, wim_name_len);
2992 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2993 tmpfile[wim_name_len + 9] = T('\0');
2995 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2996 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2997 num_threads, progress_func);
3005 /* Rename the new WIM file to the original WIM file. Note: on Windows
3006 * this actually calls win32_rename_replacement(), not _wrename(), so
3007 * that removing the existing destination file can be handled. */
3008 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3009 ret = trename(tmpfile, wim->filename);
3011 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3012 tmpfile, wim->filename);
3019 return WIMLIB_ERR_RENAME;
3022 if (progress_func) {
3023 union wimlib_progress_info progress;
3024 progress.rename.from = tmpfile;
3025 progress.rename.to = wim->filename;
3026 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3031 /* API function documented in wimlib.h */
3033 wimlib_overwrite(WIMStruct *wim, int write_flags,
3034 unsigned num_threads,
3035 wimlib_progress_func_t progress_func)
3040 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3042 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3043 return WIMLIB_ERR_INVALID_PARAM;
3046 return WIMLIB_ERR_NO_FILENAME;
3048 orig_hdr_flags = wim->hdr.flags;
3049 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3050 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3051 ret = can_modify_wim(wim);
3052 wim->hdr.flags = orig_hdr_flags;
3056 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3057 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3058 WIMLIB_WRITE_FLAG_PIPABLE))
3059 && !(wim_is_pipable(wim)))
3061 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3063 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3065 WARNING("Falling back to re-building entire WIM");
3067 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,