4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/header.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/lookup_table.h"
43 #include "wimlib/metadata.h"
44 #include "wimlib/resource.h"
45 #include "wimlib/write.h"
46 #include "wimlib/xml.h"
49 # include "wimlib/win32.h" /* win32_get_number_of_processors() */
52 #ifdef ENABLE_MULTITHREADED_COMPRESSION
68 # include <sys/uio.h> /* for `struct iovec' */
71 /* Return true if the specified resource is compressed and the compressed data
72 * can be reused with the specified output parameters. */
74 can_raw_copy(const struct wim_lookup_table_entry *lte,
75 int write_resource_flags, int out_ctype, u32 out_chunk_size)
77 return (out_ctype == wim_resource_compression_type(lte)
78 && out_chunk_size == wim_resource_chunk_size(lte)
79 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE);
83 /* Return true if the specified resource must be recompressed when the specified
84 * output parameters are used. */
86 must_compress_stream(const struct wim_lookup_table_entry *lte,
87 int write_resource_flags, int out_ctype, u32 out_chunk_size)
89 return (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
90 && ((write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
91 || !can_raw_copy(lte, write_resource_flags,
92 out_ctype, out_chunk_size)));
96 compress_chunk(const void * uncompressed_data,
97 unsigned uncompressed_len,
98 void *compressed_data,
100 struct wimlib_lzx_context *comp_ctx)
103 case WIMLIB_COMPRESSION_TYPE_XPRESS:
104 return wimlib_xpress_compress(uncompressed_data,
107 case WIMLIB_COMPRESSION_TYPE_LZX:
108 return wimlib_lzx_compress2(uncompressed_data,
118 /* Chunk table that's located at the beginning of each compressed resource in
119 * the WIM. (This is not the on-disk format; the on-disk format just has an
120 * array of offsets.) */
122 u64 original_resource_size;
125 unsigned bytes_per_chunk_entry;
131 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
132 * integers, including the first offset of 0, which will not be written.
134 u8 offsets[] _aligned_attribute(8);
137 /* Allocate and initializes a chunk table, then reserve space for it in the
138 * output file unless writing a pipable resource. */
140 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
141 struct filedes *out_fd,
143 struct chunk_table **chunk_tab_ret,
148 unsigned bytes_per_chunk_entry;
150 struct chunk_table *chunk_tab;
153 size = wim_resource_size(lte);
154 num_chunks = DIV_ROUND_UP(size, out_chunk_size);
155 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
156 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
157 chunk_tab = CALLOC(1, alloc_size);
160 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
162 return WIMLIB_ERR_NOMEM;
164 chunk_tab->num_chunks = num_chunks;
165 chunk_tab->original_resource_size = size;
166 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
167 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
169 chunk_tab->cur_offset_p = chunk_tab->offsets;
171 /* We don't know the correct offsets yet; so just write zeroes to
172 * reserve space for the table, so we can go back to it later after
173 * we've written the compressed chunks following it.
175 * Special case: if writing a pipable WIM, compressed resources are in a
176 * modified format (see comment above write_pipable_wim()) and do not
177 * have a chunk table at the beginning, so don't reserve any space for
179 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
180 ret = full_write(out_fd, chunk_tab->offsets,
181 chunk_tab->table_disk_size);
183 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
189 *chunk_tab_ret = chunk_tab;
193 /* Add the offset for the next chunk to the chunk table being constructed for a
194 * compressed stream. */
196 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
198 if (chunk_tab->bytes_per_chunk_entry == 4) {
199 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
200 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
201 chunk_tab->cur_offset_u32 += out_chunk_size;
203 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
204 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
205 chunk_tab->cur_offset_u64 += out_chunk_size;
209 /* Finishes a WIM chunk table and writes it to the output file at the correct
212 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
213 struct filedes *out_fd,
214 off_t res_start_offset,
215 int write_resource_flags)
219 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
220 ret = full_write(out_fd,
222 chunk_tab->bytes_per_chunk_entry,
223 chunk_tab->table_disk_size);
225 ret = full_pwrite(out_fd,
227 chunk_tab->bytes_per_chunk_entry,
228 chunk_tab->table_disk_size,
232 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
238 /* Write the header for a stream in a pipable WIM.
241 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
242 struct filedes *out_fd,
243 int additional_reshdr_flags)
245 struct pwm_stream_hdr stream_hdr;
249 stream_hdr.magic = PWM_STREAM_MAGIC;
250 stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
251 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
252 zero_out_hash(stream_hdr.hash);
254 wimlib_assert(!lte->unhashed);
255 copy_hash(stream_hdr.hash, lte->hash);
258 reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
259 reshdr_flags |= additional_reshdr_flags;
260 stream_hdr.flags = cpu_to_le32(reshdr_flags);
261 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
263 ERROR_WITH_ERRNO("Error writing stream header");
268 seek_and_truncate(struct filedes *out_fd, off_t offset)
270 if (filedes_seek(out_fd, offset) == -1 ||
271 ftruncate(out_fd->fd, offset))
273 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
274 return WIMLIB_ERR_WRITE;
280 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
282 u8 md[SHA1_HASH_SIZE];
284 sha1_final(md, sha_ctx);
286 copy_hash(lte->hash, md);
287 } else if (!hashes_equal(md, lte->hash)) {
288 ERROR("WIM resource has incorrect hash!");
289 if (lte_filename_valid(lte)) {
290 ERROR("We were reading it from \"%"TS"\"; maybe "
291 "it changed while we were reading it.",
294 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
299 struct write_resource_ctx {
302 struct wimlib_lzx_context *comp_ctx;
303 struct chunk_table *chunk_tab;
304 struct filedes *out_fd;
311 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
313 struct write_resource_ctx *ctx = _ctx;
314 const void *out_chunk;
315 unsigned out_chunk_size;
317 void *compressed_chunk = NULL;
318 unsigned compressed_size;
319 bool compressed_chunk_malloced = false;
320 size_t stack_max = 32768;
323 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
326 out_chunk_size = chunk_size;
327 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
329 /* Compress the chunk. */
330 if (chunk_size <= stack_max) {
331 compressed_chunk = alloca(chunk_size);
333 compressed_chunk = MALLOC(chunk_size);
334 if (compressed_chunk == NULL)
335 return WIMLIB_ERR_NOMEM;
336 compressed_chunk_malloced = true;
339 compressed_size = compress_chunk(chunk, chunk_size,
343 /* Use compressed data if compression to less than input size
345 if (compressed_size) {
346 out_chunk = compressed_chunk;
347 out_chunk_size = compressed_size;
351 if (ctx->chunk_tab) {
352 /* Update chunk table accounting. */
353 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
355 /* If writing compressed chunks to a pipable WIM, before the
356 * chunk data write a chunk header that provides the compressed
358 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
359 struct pwm_chunk_hdr chunk_hdr = {
360 .compressed_size = cpu_to_le32(out_chunk_size),
362 ret = full_write(ctx->out_fd, &chunk_hdr,
369 /* Write the chunk data. */
370 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
375 if (compressed_chunk_malloced)
376 FREE(compressed_chunk);
380 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
381 goto out_free_memory;
385 * write_wim_resource()-
387 * Write a resource to an output WIM.
390 * Lookup table entry for the resource, which could be in another WIM, in
391 * an external file, or in another location.
394 * File descriptor opened to the output WIM.
397 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
398 * compression algorithm to use.
401 * On success, this is filled in with the offset, flags, compressed size,
402 * and uncompressed size of the resource in the output WIM.
405 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
406 * if it could otherwise be copied directly from the input;
407 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
408 * (and the output file descriptor may be a pipe).
411 * Location of LZX compression context pointer, which will be allocated or
412 * updated if needed. (Initialize to NULL.)
414 * Additional notes: The SHA1 message digest of the uncompressed data is
415 * calculated (except when doing a raw copy --- see below). If the @unhashed
416 * flag is set on the lookup table entry, this message digest is simply copied
417 * to it; otherwise, the message digest is compared with the existing one, and
418 * the function will fail if they do not match.
421 write_wim_resource(struct wim_lookup_table_entry *lte,
422 struct filedes *out_fd, int out_ctype,
424 struct resource_entry *out_res_entry,
426 struct wimlib_lzx_context **comp_ctx)
428 struct write_resource_ctx write_ctx;
429 off_t res_start_offset;
434 /* Mask out any irrelevant flags, since this function also uses this
435 * variable to store WIMLIB_READ_RESOURCE flags. */
436 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
438 /* Get current position in output WIM. */
439 res_start_offset = out_fd->offset;
441 /* If we are not forcing the data to be recompressed, and the input
442 * resource is located in a WIM with the same compression type as that
443 * desired other than no compression, we can simply copy the compressed
444 * data without recompressing it. This also means we must skip
445 * calculating the SHA1, as we never will see the uncompressed data. */
446 if (can_raw_copy(lte, resource_flags, out_ctype, out_chunk_size)) {
447 /* Normally we can request a RAW_FULL read, but if we're reading
448 * from a pipable resource and writing a non-pipable resource or
449 * vice versa, then a RAW_CHUNKS read needs to be requested so
450 * that the written resource can be appropriately formatted.
451 * However, in neither case is any actual decompression needed.
453 if (lte->is_pipable == !!(resource_flags &
454 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
456 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
457 read_size = lte->resource_entry.size;
459 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
460 read_size = lte->resource_entry.original_size;
462 write_ctx.doing_sha = false;
464 write_ctx.doing_sha = true;
465 sha1_init(&write_ctx.sha_ctx);
466 read_size = lte->resource_entry.original_size;
469 /* If the output resource is to be compressed, initialize the chunk
470 * table and set the function to use for chunk compression. Exceptions:
471 * no compression function is needed if doing a raw copy; also, no chunk
472 * table is needed if doing a *full* (not per-chunk) raw copy. */
473 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
474 write_ctx.out_chunk_size = out_chunk_size;
475 write_ctx.chunk_tab = NULL;
476 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
477 wimlib_assert(out_chunk_size > 0);
478 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
479 write_ctx.out_ctype = out_ctype;
480 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
481 ret = wimlib_lzx_alloc_context(out_chunk_size,
486 write_ctx.comp_ctx = *comp_ctx;
488 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
489 ret = begin_wim_resource_chunk_tab(lte, out_fd,
491 &write_ctx.chunk_tab,
498 /* If writing a pipable resource, write the stream header and update
499 * @res_start_offset to be the end of the stream header. */
500 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
501 int reshdr_flags = 0;
502 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
503 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
504 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
506 goto out_free_chunk_tab;
507 res_start_offset = out_fd->offset;
510 /* Write the entire resource by reading the entire resource and feeding
511 * the data through the write_resource_cb function. */
512 write_ctx.out_fd = out_fd;
513 write_ctx.resource_flags = resource_flags;
515 if (write_ctx.out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
516 in_chunk_size = wim_resource_chunk_size(lte);
518 in_chunk_size = out_chunk_size;
519 ret = read_resource_prefix(lte, read_size,
521 in_chunk_size, &write_ctx, resource_flags);
523 goto out_free_chunk_tab;
525 /* Verify SHA1 message digest of the resource, or set the hash for the
527 if (write_ctx.doing_sha) {
528 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
530 goto out_free_chunk_tab;
533 /* Write chunk table if needed. */
534 if (write_ctx.chunk_tab) {
535 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
540 goto out_free_chunk_tab;
543 /* Fill in out_res_entry with information about the newly written
545 out_res_entry->size = out_fd->offset - res_start_offset;
546 out_res_entry->flags = lte->resource_entry.flags;
547 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
548 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
550 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
551 out_res_entry->offset = res_start_offset;
552 out_res_entry->original_size = wim_resource_size(lte);
554 /* Check for resources compressed to greater than their original size
555 * and write them uncompressed instead. (But never do this if writing
556 * to a pipe, and don't bother if we did a raw copy.) */
557 if (out_res_entry->size > out_res_entry->original_size &&
558 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
559 WIMLIB_READ_RESOURCE_FLAG_RAW)))
561 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
562 "writing uncompressed instead",
563 out_res_entry->original_size, out_res_entry->size);
564 ret = seek_and_truncate(out_fd, res_start_offset);
566 goto out_free_chunk_tab;
567 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
568 FREE(write_ctx.chunk_tab);
569 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
570 write_ctx.chunk_tab = NULL;
571 write_ctx.doing_sha = false;
572 goto try_write_again;
574 if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
575 DEBUG("Copied raw compressed data "
576 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
577 out_res_entry->original_size, out_res_entry->size,
578 out_res_entry->offset, out_res_entry->flags);
579 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
580 DEBUG("Wrote compressed resource "
581 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
582 out_res_entry->original_size, out_res_entry->size,
583 out_res_entry->offset, out_res_entry->flags);
585 DEBUG("Wrote uncompressed resource "
586 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
587 out_res_entry->original_size,
588 out_res_entry->offset, out_res_entry->flags);
592 FREE(write_ctx.chunk_tab);
597 /* Like write_wim_resource(), but the resource is specified by a buffer of
598 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
599 * the buffer to @hash_ret. */
601 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
602 int reshdr_flags, struct filedes *out_fd,
605 struct resource_entry *out_res_entry,
606 u8 *hash_ret, int write_resource_flags,
607 struct wimlib_lzx_context **comp_ctx)
609 /* Set up a temporary lookup table entry to provide to
610 * write_wim_resource(). */
611 struct wim_lookup_table_entry lte;
614 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
615 lte.attached_buffer = (void*)buf;
616 lte.resource_entry.original_size = buf_size;
617 lte.resource_entry.flags = reshdr_flags;
618 lte.compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
620 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
621 sha1_buffer(buf, buf_size, lte.hash);
627 ret = write_wim_resource(<e, out_fd, out_ctype, out_chunk_size,
628 out_res_entry, write_resource_flags, comp_ctx);
632 copy_hash(hash_ret, lte.hash);
637 #ifdef ENABLE_MULTITHREADED_COMPRESSION
639 /* Blocking shared queue (solves the producer-consumer problem) */
640 struct shared_queue {
644 unsigned filled_slots;
646 pthread_mutex_t lock;
647 pthread_cond_t msg_avail_cond;
648 pthread_cond_t space_avail_cond;
652 shared_queue_init(struct shared_queue *q, unsigned size)
654 wimlib_assert(size != 0);
655 q->array = CALLOC(sizeof(q->array[0]), size);
662 if (pthread_mutex_init(&q->lock, NULL)) {
663 ERROR_WITH_ERRNO("Failed to initialize mutex");
666 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
667 ERROR_WITH_ERRNO("Failed to initialize condition variable");
668 goto err_destroy_lock;
670 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
671 ERROR_WITH_ERRNO("Failed to initialize condition variable");
672 goto err_destroy_msg_avail_cond;
675 err_destroy_msg_avail_cond:
676 pthread_cond_destroy(&q->msg_avail_cond);
678 pthread_mutex_destroy(&q->lock);
680 return WIMLIB_ERR_NOMEM;
684 shared_queue_destroy(struct shared_queue *q)
687 pthread_mutex_destroy(&q->lock);
688 pthread_cond_destroy(&q->msg_avail_cond);
689 pthread_cond_destroy(&q->space_avail_cond);
693 shared_queue_put(struct shared_queue *q, void *obj)
695 pthread_mutex_lock(&q->lock);
696 while (q->filled_slots == q->size)
697 pthread_cond_wait(&q->space_avail_cond, &q->lock);
699 q->back = (q->back + 1) % q->size;
700 q->array[q->back] = obj;
703 pthread_cond_broadcast(&q->msg_avail_cond);
704 pthread_mutex_unlock(&q->lock);
708 shared_queue_get(struct shared_queue *q)
712 pthread_mutex_lock(&q->lock);
713 while (q->filled_slots == 0)
714 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
716 obj = q->array[q->front];
717 q->array[q->front] = NULL;
718 q->front = (q->front + 1) % q->size;
721 pthread_cond_broadcast(&q->space_avail_cond);
722 pthread_mutex_unlock(&q->lock);
726 struct compressor_thread_params {
727 struct shared_queue *res_to_compress_queue;
728 struct shared_queue *compressed_res_queue;
730 struct wimlib_lzx_context *comp_ctx;
733 #define MAX_CHUNKS_PER_MSG 2
736 struct wim_lookup_table_entry *lte;
738 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
739 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
740 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
741 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
743 struct list_head list;
749 compress_chunks(struct message *msg, int out_ctype,
750 struct wimlib_lzx_context *comp_ctx)
752 for (unsigned i = 0; i < msg->num_chunks; i++) {
755 len = compress_chunk(msg->uncompressed_chunks[i],
756 msg->uncompressed_chunk_sizes[i],
757 msg->compressed_chunks[i],
764 /* To be written compressed */
765 out_chunk = msg->compressed_chunks[i];
768 /* To be written uncompressed */
769 out_chunk = msg->uncompressed_chunks[i];
770 out_len = msg->uncompressed_chunk_sizes[i];
772 msg->out_chunks[i].iov_base = out_chunk;
773 msg->out_chunks[i].iov_len = out_len;
777 /* Compressor thread routine. This is a lot simpler than the main thread
778 * routine: just repeatedly get a group of chunks from the
779 * res_to_compress_queue, compress them, and put them in the
780 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
783 compressor_thread_proc(void *arg)
785 struct compressor_thread_params *params = arg;
786 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
787 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
790 DEBUG("Compressor thread ready");
791 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
792 compress_chunks(msg, params->out_ctype, params->comp_ctx);
793 shared_queue_put(compressed_res_queue, msg);
795 DEBUG("Compressor thread terminating");
798 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
800 struct write_streams_progress_data {
801 wimlib_progress_func_t progress_func;
802 union wimlib_progress_info progress;
803 uint64_t next_progress;
804 WIMStruct *prev_wim_part;
808 do_write_streams_progress(struct write_streams_progress_data *progress_data,
809 struct wim_lookup_table_entry *lte,
810 bool stream_discarded)
812 union wimlib_progress_info *progress = &progress_data->progress;
815 if (stream_discarded) {
816 progress->write_streams.total_bytes -= wim_resource_size(lte);
817 if (progress_data->next_progress != ~(uint64_t)0 &&
818 progress_data->next_progress > progress->write_streams.total_bytes)
820 progress_data->next_progress = progress->write_streams.total_bytes;
823 progress->write_streams.completed_bytes += wim_resource_size(lte);
825 new_wim_part = false;
826 if (lte->resource_location == RESOURCE_IN_WIM &&
827 lte->wim != progress_data->prev_wim_part)
829 if (progress_data->prev_wim_part) {
831 progress->write_streams.completed_parts++;
833 progress_data->prev_wim_part = lte->wim;
835 progress->write_streams.completed_streams++;
836 if (progress_data->progress_func
837 && (progress->write_streams.completed_bytes >= progress_data->next_progress
840 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
842 if (progress_data->next_progress == progress->write_streams.total_bytes) {
843 progress_data->next_progress = ~(uint64_t)0;
845 progress_data->next_progress =
846 min(progress->write_streams.total_bytes,
847 progress->write_streams.completed_bytes +
848 progress->write_streams.total_bytes / 100);
853 struct serial_write_stream_ctx {
854 struct filedes *out_fd;
857 struct wimlib_lzx_context **comp_ctx;
858 int write_resource_flags;
862 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
864 struct serial_write_stream_ctx *ctx = _ctx;
865 return write_wim_resource(lte, ctx->out_fd,
868 <e->output_resource_entry,
869 ctx->write_resource_flags,
874 /* Write a list of streams, taking into account that some streams may be
875 * duplicates that are checksummed and discarded on the fly, and also delegating
876 * the actual writing of a stream to a function @write_stream_cb, which is
877 * passed the context @write_stream_ctx. */
879 do_write_stream_list(struct list_head *stream_list,
880 struct wim_lookup_table *lookup_table,
881 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
882 void *write_stream_ctx,
883 struct write_streams_progress_data *progress_data)
886 struct wim_lookup_table_entry *lte;
887 bool stream_discarded;
889 /* For each stream in @stream_list ... */
890 while (!list_empty(stream_list)) {
891 stream_discarded = false;
892 lte = container_of(stream_list->next,
893 struct wim_lookup_table_entry,
895 list_del(<e->write_streams_list);
896 if (lte->unhashed && !lte->unique_size) {
897 /* Unhashed stream that shares a size with some other
898 * stream in the WIM we are writing. The stream must be
899 * checksummed to know if we need to write it or not. */
900 struct wim_lookup_table_entry *tmp;
901 u32 orig_out_refcnt = lte->out_refcnt;
903 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
907 /* We found a duplicate stream. 'lte' was
908 * freed, so replace it with the duplicate. */
911 /* 'out_refcnt' was transferred to the
912 * duplicate, and we can detect if the duplicate
913 * stream was already referenced for writing by
914 * checking if its 'out_refcnt' is higher than
915 * that of the original stream. In such cases,
916 * the current stream can be discarded. We can
917 * also discard the current stream if it was
918 * previously marked as filtered (e.g. already
919 * present in the WIM being written). */
920 if (lte->out_refcnt > orig_out_refcnt ||
922 DEBUG("Discarding duplicate stream of "
924 wim_resource_size(lte));
925 lte->no_progress = 0;
926 stream_discarded = true;
927 goto skip_to_progress;
932 /* Here, @lte is either a hashed stream or an unhashed stream
933 * with a unique size. In either case we know that the stream
934 * has to be written. In either case the SHA1 message digest
935 * will be calculated over the stream while writing it; however,
936 * in the former case this is done merely to check the data,
937 * while in the latter case this is done because we do not have
938 * the SHA1 message digest yet. */
939 wimlib_assert(lte->out_refcnt != 0);
941 lte->no_progress = 0;
942 ret = (*write_stream_cb)(lte, write_stream_ctx);
945 /* In parallel mode, some streams are deferred for later,
946 * serialized processing; ignore them here. */
950 list_del(<e->unhashed_list);
951 lookup_table_insert(lookup_table, lte);
955 if (!lte->no_progress) {
956 do_write_streams_progress(progress_data,
957 lte, stream_discarded);
964 do_write_stream_list_serial(struct list_head *stream_list,
965 struct wim_lookup_table *lookup_table,
966 struct filedes *out_fd,
969 struct wimlib_lzx_context **comp_ctx,
970 int write_resource_flags,
971 struct write_streams_progress_data *progress_data)
973 struct serial_write_stream_ctx ctx = {
975 .out_ctype = out_ctype,
976 .out_chunk_size = out_chunk_size,
977 .write_resource_flags = write_resource_flags,
978 .comp_ctx = comp_ctx,
980 return do_write_stream_list(stream_list,
988 write_flags_to_resource_flags(int write_flags)
990 int resource_flags = 0;
992 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
993 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
994 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
995 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
996 return resource_flags;
1000 write_stream_list_serial(struct list_head *stream_list,
1001 struct wim_lookup_table *lookup_table,
1002 struct filedes *out_fd,
1005 struct wimlib_lzx_context **comp_ctx,
1006 int write_resource_flags,
1007 struct write_streams_progress_data *progress_data)
1009 union wimlib_progress_info *progress = &progress_data->progress;
1010 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
1011 progress->write_streams.total_streams);
1012 progress->write_streams.num_threads = 1;
1013 if (progress_data->progress_func) {
1014 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1017 return do_write_stream_list_serial(stream_list,
1023 write_resource_flags,
1027 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1029 write_wim_chunks(struct message *msg, struct filedes *out_fd,
1030 struct chunk_table *chunk_tab,
1031 int write_resource_flags)
1034 struct pwm_chunk_hdr *chunk_hdrs;
1038 for (unsigned i = 0; i < msg->num_chunks; i++)
1039 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1041 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1042 nvecs = msg->num_chunks;
1043 vecs = msg->out_chunks;
1045 /* Special case: If writing a compressed resource to a pipable
1046 * WIM, prefix each compressed chunk with a header that gives
1047 * its compressed size. */
1048 nvecs = msg->num_chunks * 2;
1049 vecs = alloca(nvecs * sizeof(vecs[0]));
1050 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1052 for (unsigned i = 0; i < msg->num_chunks; i++) {
1053 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1054 vecs[i * 2].iov_base = &chunk_hdrs[i];
1055 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1056 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1057 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1060 ret = full_writev(out_fd, vecs, nvecs);
1062 ERROR_WITH_ERRNO("Failed to write WIM chunks");
1066 struct main_writer_thread_ctx {
1067 struct list_head *stream_list;
1068 struct wim_lookup_table *lookup_table;
1069 struct filedes *out_fd;
1070 off_t res_start_offset;
1073 struct wimlib_lzx_context **comp_ctx;
1074 int write_resource_flags;
1075 struct shared_queue *res_to_compress_queue;
1076 struct shared_queue *compressed_res_queue;
1077 size_t num_messages;
1078 struct write_streams_progress_data *progress_data;
1080 struct list_head available_msgs;
1081 struct list_head outstanding_streams;
1082 struct list_head serial_streams;
1083 size_t num_outstanding_messages;
1085 SHA_CTX next_sha_ctx;
1087 u64 next_num_chunks;
1088 struct wim_lookup_table_entry *next_lte;
1090 struct message *msgs;
1091 struct message *next_msg;
1092 struct chunk_table *cur_chunk_tab;
1096 init_message(struct message *msg, u32 out_chunk_size)
1098 msg->out_chunk_size = out_chunk_size;
1099 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1100 msg->compressed_chunks[i] = MALLOC(out_chunk_size);
1101 msg->uncompressed_chunks[i] = MALLOC(out_chunk_size);
1102 if (msg->compressed_chunks[i] == NULL ||
1103 msg->uncompressed_chunks[i] == NULL)
1104 return WIMLIB_ERR_NOMEM;
1110 destroy_message(struct message *msg)
1112 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1113 FREE(msg->compressed_chunks[i]);
1114 FREE(msg->uncompressed_chunks[i]);
1119 free_messages(struct message *msgs, size_t num_messages)
1122 for (size_t i = 0; i < num_messages; i++)
1123 destroy_message(&msgs[i]);
1128 static struct message *
1129 allocate_messages(size_t num_messages, u32 out_chunk_size)
1131 struct message *msgs;
1133 msgs = CALLOC(num_messages, sizeof(struct message));
1136 for (size_t i = 0; i < num_messages; i++) {
1137 if (init_message(&msgs[i], out_chunk_size)) {
1138 free_messages(msgs, num_messages);
1146 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1148 while (ctx->num_outstanding_messages--)
1149 shared_queue_get(ctx->compressed_res_queue);
1150 free_messages(ctx->msgs, ctx->num_messages);
1151 FREE(ctx->cur_chunk_tab);
1155 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1157 /* Pre-allocate all the buffers that will be needed to do the chunk
1159 ctx->msgs = allocate_messages(ctx->num_messages, ctx->out_chunk_size);
1161 return WIMLIB_ERR_NOMEM;
1163 /* Initially, all the messages are available to use. */
1164 INIT_LIST_HEAD(&ctx->available_msgs);
1165 for (size_t i = 0; i < ctx->num_messages; i++)
1166 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1168 /* outstanding_streams is the list of streams that currently have had
1169 * chunks sent off for compression.
1171 * The first stream in outstanding_streams is the stream that is
1172 * currently being written.
1174 * The last stream in outstanding_streams is the stream that is
1175 * currently being read and having chunks fed to the compressor threads.
1177 INIT_LIST_HEAD(&ctx->outstanding_streams);
1178 ctx->num_outstanding_messages = 0;
1180 ctx->next_msg = NULL;
1182 /* Resources that don't need any chunks compressed are added to this
1183 * list and written directly by the main thread. */
1184 INIT_LIST_HEAD(&ctx->serial_streams);
1186 ctx->cur_chunk_tab = NULL;
1192 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1194 struct message *msg;
1195 struct wim_lookup_table_entry *cur_lte;
1198 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1199 wimlib_assert(ctx->num_outstanding_messages != 0);
1201 cur_lte = container_of(ctx->outstanding_streams.next,
1202 struct wim_lookup_table_entry,
1203 being_compressed_list);
1205 /* Get the next message from the queue and process it.
1206 * The message will contain 1 or more data chunks that have been
1208 msg = shared_queue_get(ctx->compressed_res_queue);
1209 msg->complete = true;
1210 --ctx->num_outstanding_messages;
1212 /* Is this the next chunk in the current resource? If it's not
1213 * (i.e., an earlier chunk in a same or different resource
1214 * hasn't been compressed yet), do nothing, and keep this
1215 * message around until all earlier chunks are received.
1217 * Otherwise, write all the chunks we can. */
1218 while (cur_lte != NULL &&
1219 !list_empty(&cur_lte->msg_list)
1220 && (msg = container_of(cur_lte->msg_list.next,
1224 list_move(&msg->list, &ctx->available_msgs);
1225 if (msg->begin_chunk == 0) {
1226 /* First set of chunks. */
1228 /* Write pipable WIM stream header if needed. */
1229 if (ctx->write_resource_flags &
1230 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1232 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1233 WIM_RESHDR_FLAG_COMPRESSED);
1238 /* Save current offset. */
1239 ctx->res_start_offset = ctx->out_fd->offset;
1241 /* Begin building the chunk table, and leave space for
1243 ret = begin_wim_resource_chunk_tab(cur_lte,
1245 ctx->out_chunk_size,
1246 &ctx->cur_chunk_tab,
1247 ctx->write_resource_flags);
1253 /* Write the compressed chunks from the message. */
1254 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1255 ctx->write_resource_flags);
1259 /* Was this the last chunk of the stream? If so, finish
1261 if (list_empty(&cur_lte->msg_list) &&
1262 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1266 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1268 ctx->res_start_offset,
1269 ctx->write_resource_flags);
1273 list_del(&cur_lte->being_compressed_list);
1275 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1277 FREE(ctx->cur_chunk_tab);
1278 ctx->cur_chunk_tab = NULL;
1280 /* Check for resources compressed to greater than or
1281 * equal to their original size and write them
1282 * uncompressed instead. (But never do this if writing
1284 if (res_csize >= wim_resource_size(cur_lte) &&
1285 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1287 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1288 "writing uncompressed instead",
1289 wim_resource_size(cur_lte), res_csize);
1290 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1293 ret = write_wim_resource(cur_lte,
1295 WIMLIB_COMPRESSION_TYPE_NONE,
1297 &cur_lte->output_resource_entry,
1298 ctx->write_resource_flags,
1303 cur_lte->output_resource_entry.size =
1306 cur_lte->output_resource_entry.original_size =
1307 cur_lte->resource_entry.original_size;
1309 cur_lte->output_resource_entry.offset =
1310 ctx->res_start_offset;
1312 cur_lte->output_resource_entry.flags =
1313 cur_lte->resource_entry.flags |
1314 WIM_RESHDR_FLAG_COMPRESSED;
1316 DEBUG("Wrote compressed resource "
1317 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1318 cur_lte->output_resource_entry.original_size,
1319 cur_lte->output_resource_entry.size,
1320 cur_lte->output_resource_entry.offset,
1321 cur_lte->output_resource_entry.flags);
1324 do_write_streams_progress(ctx->progress_data,
1327 /* Since we just finished writing a stream, write any
1328 * streams that have been added to the serial_streams
1329 * list for direct writing by the main thread (e.g.
1330 * resources that don't need to be compressed because
1331 * the desired compression type is the same as the
1332 * previous compression type). */
1333 if (!list_empty(&ctx->serial_streams)) {
1334 ret = do_write_stream_list_serial(&ctx->serial_streams,
1338 ctx->out_chunk_size,
1340 ctx->write_resource_flags,
1341 ctx->progress_data);
1346 /* Advance to the next stream to write. */
1347 if (list_empty(&ctx->outstanding_streams)) {
1350 cur_lte = container_of(ctx->outstanding_streams.next,
1351 struct wim_lookup_table_entry,
1352 being_compressed_list);
1359 /* Called when the main thread has read a new chunk of data. */
1361 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1363 struct main_writer_thread_ctx *ctx = _ctx;
1365 struct message *next_msg;
1366 u64 next_chunk_in_msg;
1368 /* Update SHA1 message digest for the stream currently being read by the
1370 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1372 /* We send chunks of data to the compressor chunks in batches which we
1373 * refer to as "messages". @next_msg is the message that is currently
1374 * being prepared to send off. If it is NULL, that indicates that we
1375 * need to start a new message. */
1376 next_msg = ctx->next_msg;
1378 /* We need to start a new message. First check to see if there
1379 * is a message available in the list of available messages. If
1380 * so, we can just take one. If not, all the messages (there is
1381 * a fixed number of them, proportional to the number of
1382 * threads) have been sent off to the compressor threads, so we
1383 * receive messages from the compressor threads containing
1384 * compressed chunks of data.
1386 * We may need to receive multiple messages before one is
1387 * actually available to use because messages received that are
1388 * *not* for the very next set of chunks to compress must be
1389 * buffered until it's time to write those chunks. */
1390 while (list_empty(&ctx->available_msgs)) {
1391 ret = receive_compressed_chunks(ctx);
1396 next_msg = container_of(ctx->available_msgs.next,
1397 struct message, list);
1398 list_del(&next_msg->list);
1399 next_msg->complete = false;
1400 next_msg->begin_chunk = ctx->next_chunk;
1401 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1402 ctx->next_num_chunks - ctx->next_chunk);
1403 ctx->next_msg = next_msg;
1406 /* Fill in the next chunk to compress */
1407 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1409 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1410 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1413 if (++next_chunk_in_msg == next_msg->num_chunks) {
1414 /* Send off an array of chunks to compress */
1415 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1416 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1417 ++ctx->num_outstanding_messages;
1418 ctx->next_msg = NULL;
1424 main_writer_thread_finish(void *_ctx)
1426 struct main_writer_thread_ctx *ctx = _ctx;
1428 while (ctx->num_outstanding_messages != 0) {
1429 ret = receive_compressed_chunks(ctx);
1433 wimlib_assert(list_empty(&ctx->outstanding_streams));
1434 return do_write_stream_list_serial(&ctx->serial_streams,
1438 ctx->out_chunk_size,
1440 ctx->write_resource_flags,
1441 ctx->progress_data);
1445 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1446 struct main_writer_thread_ctx *ctx)
1450 /* Read the entire stream @lte, feeding its data chunks to the
1451 * compressor threads. Also SHA1-sum the stream; this is required in
1452 * the case that @lte is unhashed, and a nice additional verification
1453 * when @lte is already hashed. */
1454 sha1_init(&ctx->next_sha_ctx);
1455 ctx->next_chunk = 0;
1456 ctx->next_num_chunks = DIV_ROUND_UP(wim_resource_size(lte),
1457 ctx->out_chunk_size);
1458 ctx->next_lte = lte;
1459 INIT_LIST_HEAD(<e->msg_list);
1460 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1461 ret = read_resource_prefix(lte, wim_resource_size(lte),
1462 main_writer_thread_cb,
1463 ctx->out_chunk_size, ctx, 0);
1466 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1467 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1471 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1473 struct main_writer_thread_ctx *ctx = _ctx;
1476 if (wim_resource_size(lte) < 1000 ||
1477 !must_compress_stream(lte, ctx->write_resource_flags,
1478 ctx->out_ctype, ctx->out_chunk_size))
1480 /* Stream is too small or isn't being compressed. Process it by
1481 * the main thread when we have a chance. We can't necessarily
1482 * process it right here, as the main thread could be in the
1483 * middle of writing a different stream. */
1484 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1488 ret = submit_stream_for_compression(lte, ctx);
1490 lte->no_progress = 1;
1495 get_default_num_threads(void)
1498 return win32_get_number_of_processors();
1500 return sysconf(_SC_NPROCESSORS_ONLN);
1504 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1505 * parameter and will perform compression using that many threads. Falls
1506 * back to write_stream_list_serial() on certain errors, such as a failure to
1507 * create the number of threads requested.
1509 * High level description of the algorithm for writing compressed streams in
1510 * parallel: We perform compression on chunks rather than on full files. The
1511 * currently executing thread becomes the main thread and is entirely in charge
1512 * of reading the data to compress (which may be in any location understood by
1513 * the resource code--- such as in an external file being captured, or in
1514 * another WIM file from which an image is being exported) and actually writing
1515 * the compressed data to the output file. Additional threads are "compressor
1516 * threads" and all execute the compressor_thread_proc, where they repeatedly
1517 * retrieve buffers of data from the main thread, compress them, and hand them
1518 * back to the main thread.
1520 * Certain streams, such as streams that do not need to be compressed (e.g.
1521 * input compression type same as output compression type) or streams of very
1522 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1523 * handled entirely by the main thread at an appropriate time.
1525 * At any given point in time, multiple streams may be having chunks compressed
1526 * concurrently. The stream that the main thread is currently *reading* may be
1527 * later in the list that the stream that the main thread is currently
1531 write_stream_list_parallel(struct list_head *stream_list,
1532 struct wim_lookup_table *lookup_table,
1533 struct filedes *out_fd,
1536 struct wimlib_lzx_context **comp_ctx,
1537 int write_resource_flags,
1538 struct write_streams_progress_data *progress_data,
1539 unsigned num_threads)
1542 struct shared_queue res_to_compress_queue;
1543 struct shared_queue compressed_res_queue;
1544 pthread_t *compressor_threads = NULL;
1545 union wimlib_progress_info *progress = &progress_data->progress;
1547 if (num_threads == 0) {
1548 long nthreads = get_default_num_threads();
1549 if (nthreads < 1 || nthreads > UINT_MAX) {
1550 WARNING("Could not determine number of processors! Assuming 1");
1552 } else if (nthreads == 1) {
1553 goto out_serial_quiet;
1555 num_threads = nthreads;
1559 DEBUG("Writing stream list of size %"PRIu64" "
1560 "(parallel version, num_threads=%u)",
1561 progress->write_streams.total_streams, num_threads);
1563 progress->write_streams.num_threads = num_threads;
1565 static const size_t MESSAGES_PER_THREAD = 2;
1566 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1568 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1570 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1574 ret = shared_queue_init(&compressed_res_queue, queue_size);
1576 goto out_destroy_res_to_compress_queue;
1578 struct compressor_thread_params *params;
1580 params = CALLOC(num_threads, sizeof(params[0]));
1581 if (params == NULL) {
1582 ret = WIMLIB_ERR_NOMEM;
1583 goto out_destroy_compressed_res_queue;
1586 for (unsigned i = 0; i < num_threads; i++) {
1587 params[i].res_to_compress_queue = &res_to_compress_queue;
1588 params[i].compressed_res_queue = &compressed_res_queue;
1589 params[i].out_ctype = out_ctype;
1590 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1591 ret = wimlib_lzx_alloc_context(out_chunk_size,
1592 NULL, ¶ms[i].comp_ctx);
1594 goto out_free_params;
1598 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1599 if (!compressor_threads) {
1600 ret = WIMLIB_ERR_NOMEM;
1601 goto out_free_params;
1604 for (unsigned i = 0; i < num_threads; i++) {
1605 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1606 ret = pthread_create(&compressor_threads[i], NULL,
1607 compressor_thread_proc, ¶ms[i]);
1610 ERROR_WITH_ERRNO("Failed to create compressor "
1612 i + 1, num_threads);
1618 if (progress_data->progress_func) {
1619 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1623 struct main_writer_thread_ctx ctx;
1624 ctx.stream_list = stream_list;
1625 ctx.lookup_table = lookup_table;
1626 ctx.out_fd = out_fd;
1627 ctx.out_ctype = out_ctype;
1628 ctx.out_chunk_size = out_chunk_size;
1629 ctx.comp_ctx = comp_ctx;
1630 ctx.res_to_compress_queue = &res_to_compress_queue;
1631 ctx.compressed_res_queue = &compressed_res_queue;
1632 ctx.num_messages = queue_size;
1633 ctx.write_resource_flags = write_resource_flags;
1634 ctx.progress_data = progress_data;
1635 ret = main_writer_thread_init_ctx(&ctx);
1638 ret = do_write_stream_list(stream_list, lookup_table,
1639 main_thread_process_next_stream,
1640 &ctx, progress_data);
1642 goto out_destroy_ctx;
1644 /* The main thread has finished reading all streams that are going to be
1645 * compressed in parallel, and it now needs to wait for all remaining
1646 * chunks to be compressed so that the remaining streams can actually be
1647 * written to the output file. Furthermore, any remaining streams that
1648 * had processing deferred to the main thread need to be handled. These
1649 * tasks are done by the main_writer_thread_finish() function. */
1650 ret = main_writer_thread_finish(&ctx);
1652 main_writer_thread_destroy_ctx(&ctx);
1654 for (unsigned i = 0; i < num_threads; i++)
1655 shared_queue_put(&res_to_compress_queue, NULL);
1657 for (unsigned i = 0; i < num_threads; i++) {
1658 if (pthread_join(compressor_threads[i], NULL)) {
1659 WARNING_WITH_ERRNO("Failed to join compressor "
1661 i + 1, num_threads);
1664 FREE(compressor_threads);
1666 for (unsigned i = 0; i < num_threads; i++)
1667 wimlib_lzx_free_context(params[i].comp_ctx);
1669 out_destroy_compressed_res_queue:
1670 shared_queue_destroy(&compressed_res_queue);
1671 out_destroy_res_to_compress_queue:
1672 shared_queue_destroy(&res_to_compress_queue);
1673 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1676 WARNING("Falling back to single-threaded compression");
1678 return write_stream_list_serial(stream_list,
1684 write_resource_flags,
1691 * Write a list of streams to a WIM (@out_fd) using the compression type
1692 * @out_ctype and up to @num_threads compressor threads.
1695 write_stream_list(struct list_head *stream_list,
1696 struct wim_lookup_table *lookup_table,
1697 struct filedes *out_fd, int out_ctype,
1699 struct wimlib_lzx_context **comp_ctx,
1701 unsigned num_threads, wimlib_progress_func_t progress_func)
1703 struct wim_lookup_table_entry *lte;
1704 size_t num_streams = 0;
1705 u64 total_bytes = 0;
1706 u64 total_compression_bytes = 0;
1707 struct write_streams_progress_data progress_data;
1709 int write_resource_flags;
1710 unsigned total_parts = 0;
1711 WIMStruct *prev_wim_part = NULL;
1713 if (list_empty(stream_list)) {
1714 DEBUG("No streams to write.");
1718 write_resource_flags = write_flags_to_resource_flags(write_flags);
1720 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1721 out_fd->offset, write_resource_flags);
1723 sort_stream_list_by_sequential_order(stream_list,
1724 offsetof(struct wim_lookup_table_entry,
1725 write_streams_list));
1727 /* Calculate the total size of the streams to be written. Note: this
1728 * will be the uncompressed size, as we may not know the compressed size
1729 * yet, and also this will assume that every unhashed stream will be
1730 * written (which will not necessarily be the case). */
1731 list_for_each_entry(lte, stream_list, write_streams_list) {
1733 total_bytes += wim_resource_size(lte);
1734 if (must_compress_stream(lte, write_resource_flags,
1735 out_ctype, out_chunk_size))
1736 total_compression_bytes += wim_resource_size(lte);
1737 if (lte->resource_location == RESOURCE_IN_WIM) {
1738 if (prev_wim_part != lte->wim) {
1739 prev_wim_part = lte->wim;
1745 memset(&progress_data, 0, sizeof(progress_data));
1746 progress_data.progress_func = progress_func;
1748 progress_data.progress.write_streams.total_bytes = total_bytes;
1749 progress_data.progress.write_streams.total_streams = num_streams;
1750 progress_data.progress.write_streams.completed_bytes = 0;
1751 progress_data.progress.write_streams.completed_streams = 0;
1752 progress_data.progress.write_streams.num_threads = num_threads;
1753 progress_data.progress.write_streams.compression_type = out_ctype;
1754 progress_data.progress.write_streams.total_parts = total_parts;
1755 progress_data.progress.write_streams.completed_parts = 0;
1757 progress_data.next_progress = 0;
1758 progress_data.prev_wim_part = NULL;
1760 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1761 if (total_compression_bytes >= 2000000 && num_threads != 1)
1762 ret = write_stream_list_parallel(stream_list,
1768 write_resource_flags,
1773 ret = write_stream_list_serial(stream_list,
1779 write_resource_flags,
1782 DEBUG("Successfully wrote stream list.");
1784 DEBUG("Failed to write stream list.");
1788 struct stream_size_table {
1789 struct hlist_head *array;
1795 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1797 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1799 return WIMLIB_ERR_NOMEM;
1800 tab->num_entries = 0;
1801 tab->capacity = capacity;
1806 destroy_stream_size_table(struct stream_size_table *tab)
1812 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1814 struct stream_size_table *tab = _tab;
1816 struct wim_lookup_table_entry *same_size_lte;
1817 struct hlist_node *tmp;
1819 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1820 lte->unique_size = 1;
1821 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1822 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1823 lte->unique_size = 0;
1824 same_size_lte->unique_size = 0;
1829 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1834 struct find_streams_ctx {
1837 struct list_head stream_list;
1838 struct stream_size_table stream_size_tab;
1842 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1843 struct find_streams_ctx *ctx,
1846 if (lte->out_refcnt == 0) {
1847 stream_size_table_insert(lte, &ctx->stream_size_tab);
1848 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1850 lte->out_refcnt += nref;
1854 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1857 struct find_streams_ctx *ctx = _ctx;
1858 lte->out_refcnt = 0;
1859 lte_reference_for_logical_write(lte, ctx,
1860 (lte->refcnt ? lte->refcnt : 1));
1865 inode_find_streams_to_write(struct wim_inode *inode,
1866 struct wim_lookup_table *table,
1867 struct find_streams_ctx *ctx)
1869 struct wim_lookup_table_entry *lte;
1872 for (i = 0; i <= inode->i_num_ads; i++) {
1873 lte = inode_stream_lte(inode, i, table);
1875 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1876 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1877 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1883 image_find_streams_to_write(WIMStruct *wim)
1885 struct find_streams_ctx *ctx;
1886 struct wim_image_metadata *imd;
1887 struct wim_inode *inode;
1888 struct wim_lookup_table_entry *lte;
1892 imd = wim_get_current_image_metadata(wim);
1894 image_for_each_unhashed_stream(lte, imd)
1895 lte->out_refcnt = 0;
1897 /* Go through this image's inodes to find any streams that have not been
1899 image_for_each_inode(inode, imd) {
1900 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1908 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1909 * the "logical write" of the WIM, meaning all streams that are referenced at
1910 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1911 * each stream being included in the logical write is set to the number of
1912 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1913 * stream being included in the logical write is set to indicate whether that
1914 * stream has a unique size relative to the streams being included in the
1915 * logical write. Still furthermore, 'part_number' on each stream being
1916 * included in the logical write is set to the part number given in the
1917 * in-memory header of @p wim.
1919 * This is considered a "logical write" because it does not take into account
1920 * filtering out streams already present in the WIM (in the case of an in place
1921 * overwrite) or present in other WIMs (in case of creating delta WIM).
1924 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1925 struct find_streams_ctx *ctx)
1928 struct wim_lookup_table_entry *lte;
1930 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1931 (image == 1 && wim->hdr.image_count == 1)))
1933 /* Fast case: Assume that all streams are being written and
1934 * that the reference counts are correct. */
1935 struct wim_lookup_table_entry *lte;
1936 struct wim_image_metadata *imd;
1939 for_lookup_table_entry(wim->lookup_table,
1940 do_lte_full_reference_for_logical_write, ctx);
1941 for (i = 0; i < wim->hdr.image_count; i++) {
1942 imd = wim->image_metadata[i];
1943 image_for_each_unhashed_stream(lte, imd)
1944 do_lte_full_reference_for_logical_write(lte, ctx);
1947 /* Slow case: Walk through the images being written and
1948 * determine the streams referenced. */
1949 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1951 ret = for_image(wim, image, image_find_streams_to_write);
1956 list_for_each_entry(lte, &ctx->stream_list, write_streams_list)
1957 lte->part_number = wim->hdr.part_number;
1962 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1964 struct find_streams_ctx *ctx = _ctx;
1967 /* Calculate and set lte->filtered. */
1968 if (lte->resource_location == RESOURCE_IN_WIM) {
1969 if (lte->wim == ctx->wim &&
1970 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1971 filtered |= FILTERED_SAME_WIM;
1972 if (lte->wim != ctx->wim &&
1973 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1974 filtered |= FILTERED_EXTERNAL_WIM;
1976 lte->filtered = filtered;
1978 /* Filtered streams get inserted into the stream size table too, unless
1979 * they already were. This is because streams that are checksummed
1980 * on-the-fly during the write should not be written if they are
1981 * duplicates of filtered stream. */
1982 if (lte->filtered && lte->out_refcnt == 0)
1983 stream_size_table_insert(lte, &ctx->stream_size_tab);
1988 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
1994 /* Given the list of streams to include in a logical write of a WIM, handle
1995 * filtering out streams already present in the WIM or already present in
1996 * external WIMs, depending on the write flags provided. */
1998 handle_stream_filtering(struct find_streams_ctx *ctx)
2000 struct wim_lookup_table_entry *lte, *tmp;
2002 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2003 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2005 for_lookup_table_entry(ctx->wim->lookup_table,
2006 mark_stream_not_filtered, ctx);
2010 for_lookup_table_entry(ctx->wim->lookup_table,
2011 process_filtered_stream, ctx);
2013 /* Streams in logical write list that were filtered can be removed. */
2014 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2017 list_del(<e->write_streams_list);
2020 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2021 * around prepare_logical_stream_list() to handle filtering out streams already
2022 * present in the WIM or already present in external WIMs, depending on the
2023 * write flags provided.
2025 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2027 * - 'out_refcnt' is set to the number of references found for the logical write.
2028 * This will be nonzero on all streams in the list returned by this function,
2029 * but will also be nonzero on streams not in the list that were included in
2030 * the logical write list, but filtered out from the returned list.
2031 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2032 * are not included in the list of streams returned by this function.
2033 * - 'unique_size' is set if the stream has a unique size among all streams in
2034 * the logical write plus any filtered streams in the entire WIM that could
2035 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2036 * stream being written.
2039 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2040 struct list_head *stream_list)
2044 struct find_streams_ctx ctx;
2046 INIT_LIST_HEAD(&ctx.stream_list);
2047 ret = init_stream_size_table(&ctx.stream_size_tab,
2048 wim->lookup_table->capacity);
2051 ctx.write_flags = write_flags;
2054 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2056 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2058 goto out_destroy_table;
2060 handle_stream_filtering(&ctx);
2061 list_transfer(&ctx.stream_list, stream_list);
2064 destroy_stream_size_table(&ctx.stream_size_tab);
2069 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2070 unsigned num_threads,
2071 wimlib_progress_func_t progress_func,
2072 struct list_head *stream_list_override)
2075 struct list_head _stream_list;
2076 struct list_head *stream_list;
2077 struct wim_lookup_table_entry *lte;
2079 if (stream_list_override == NULL) {
2080 /* Normal case: prepare stream list from image(s) being written.
2082 stream_list = &_stream_list;
2083 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2087 /* Currently only as a result of wimlib_split() being called:
2088 * use stream list already explicitly provided. Use existing
2089 * reference counts. */
2090 stream_list = stream_list_override;
2091 list_for_each_entry(lte, stream_list, write_streams_list) {
2092 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2093 lte->part_number = wim->hdr.part_number;
2097 return write_stream_list(stream_list,
2100 wim->out_compression_type,
2101 wim->out_chunk_size,
2109 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2110 wimlib_progress_func_t progress_func)
2115 int write_resource_flags;
2117 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2118 DEBUG("Not writing any metadata resources.");
2122 write_resource_flags = write_flags_to_resource_flags(write_flags);
2124 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2125 wim->out_fd.offset);
2128 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2130 if (image == WIMLIB_ALL_IMAGES) {
2132 end_image = wim->hdr.image_count;
2134 start_image = image;
2138 for (int i = start_image; i <= end_image; i++) {
2139 struct wim_image_metadata *imd;
2141 imd = wim->image_metadata[i - 1];
2142 /* Build a new metadata resource only if image was modified from
2143 * the original (or was newly added). Otherwise just copy the
2145 if (imd->modified) {
2146 DEBUG("Image %u was modified; building and writing new "
2147 "metadata resource", i);
2148 ret = write_metadata_resource(wim, i,
2149 write_resource_flags);
2150 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2151 DEBUG("Image %u was not modified; re-using existing "
2152 "metadata resource.", i);
2153 copy_resource_entry(&imd->metadata_lte->output_resource_entry,
2154 &imd->metadata_lte->resource_entry);
2157 DEBUG("Image %u was not modified; copying existing "
2158 "metadata resource.", i);
2159 ret = write_wim_resource(imd->metadata_lte,
2161 wim->out_compression_type,
2162 wim->out_chunk_size,
2163 &imd->metadata_lte->output_resource_entry,
2164 write_resource_flags,
2171 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2176 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2179 DEBUG("Opening \"%"TS"\" for writing.", path);
2181 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2183 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2184 return WIMLIB_ERR_OPEN;
2186 filedes_init(&wim->out_fd, raw_fd);
2191 close_wim_writable(WIMStruct *wim, int write_flags)
2195 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2196 DEBUG("Closing WIM file.");
2197 if (filedes_valid(&wim->out_fd))
2198 if (filedes_close(&wim->out_fd))
2199 ret = WIMLIB_ERR_WRITE;
2201 filedes_invalidate(&wim->out_fd);
2208 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2209 * table, then overwrite the WIM header. By default, closes the WIM file
2210 * descriptor (@wim->out_fd) if successful.
2212 * write_flags is a bitwise OR of the following:
2214 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2215 * Include an integrity table.
2217 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2218 * fsync() the output file before closing it.
2220 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2221 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2222 * stream headers before the lookup table and XML data, and also
2223 * write the WIM header at the end instead of seeking to the
2224 * beginning. Can't be combined with
2225 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2227 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2228 * Don't write the lookup table.
2230 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2231 * When (if) writing the integrity table, re-use entries from the
2232 * existing integrity table, if possible.
2234 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2235 * After writing the XML data but before writing the integrity
2236 * table, write a temporary WIM header and flush the stream so that
2237 * the WIM is less likely to become corrupted upon abrupt program
2239 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2240 * Instead of overwriting the WIM header at the beginning of the
2241 * file, simply append it to the end of the file. (Used when
2243 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2244 * Do not close the file descriptor @wim->out_fd on either success
2246 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2247 * Use the existing <TOTALBYTES> stored in the in-memory XML
2248 * information, rather than setting it to the offset of the XML
2249 * data being written.
2252 finish_write(WIMStruct *wim, int image, int write_flags,
2253 wimlib_progress_func_t progress_func,
2254 struct list_head *stream_list_override)
2258 int write_resource_flags;
2259 off_t old_lookup_table_end;
2260 off_t new_lookup_table_end;
2263 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2265 write_resource_flags = write_flags_to_resource_flags(write_flags);
2267 /* In the WIM header, there is room for the resource entry for a
2268 * metadata resource labeled as the "boot metadata". This entry should
2269 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2270 * it should be a copy of the resource entry for the image that is
2271 * marked as bootable. This is not well documented... */
2272 if (wim->hdr.boot_idx == 0) {
2273 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2275 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2276 &wim->image_metadata[wim->hdr.boot_idx- 1
2277 ]->metadata_lte->output_resource_entry);
2280 /* Write lookup table. (Save old position first.) */
2281 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2282 wim->hdr.lookup_table_res_entry.size;
2283 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2284 ret = write_wim_lookup_table(wim, image, write_flags,
2285 &wim->hdr.lookup_table_res_entry,
2286 stream_list_override);
2291 /* Write XML data. */
2292 xml_totalbytes = wim->out_fd.offset;
2293 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2294 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2295 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2296 &wim->hdr.xml_res_entry,
2297 write_resource_flags);
2301 /* Write integrity table (optional). */
2302 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2303 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2304 struct wim_header checkpoint_hdr;
2305 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2306 zero_resource_entry(&checkpoint_hdr.integrity);
2307 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2308 ret = write_wim_header_at_offset(&checkpoint_hdr,
2314 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2315 old_lookup_table_end = 0;
2317 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2318 wim->hdr.lookup_table_res_entry.size;
2320 ret = write_integrity_table(wim,
2321 new_lookup_table_end,
2322 old_lookup_table_end,
2327 /* No integrity table. */
2328 zero_resource_entry(&wim->hdr.integrity);
2331 /* Now that all information in the WIM header has been determined, the
2332 * preliminary header written earlier can be overwritten, the header of
2333 * the existing WIM file can be overwritten, or the final header can be
2334 * written to the end of the pipable WIM. */
2335 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2337 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2338 hdr_offset = wim->out_fd.offset;
2339 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2340 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2344 /* Possibly sync file data to disk before closing. On POSIX systems, it
2345 * is necessary to do this before using rename() to overwrite an
2346 * existing file with a new file. Otherwise, data loss would occur if
2347 * the system is abruptly terminated when the metadata for the rename
2348 * operation has been written to disk, but the new file data has not.
2350 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2351 DEBUG("Syncing WIM file.");
2352 if (fsync(wim->out_fd.fd)) {
2353 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2354 return WIMLIB_ERR_WRITE;
2358 if (close_wim_writable(wim, write_flags)) {
2359 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2360 return WIMLIB_ERR_WRITE;
2366 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2368 lock_wim(WIMStruct *wim, int fd)
2371 if (fd != -1 && !wim->wim_locked) {
2372 ret = flock(fd, LOCK_EX | LOCK_NB);
2374 if (errno == EWOULDBLOCK) {
2375 ERROR("`%"TS"' is already being modified or has been "
2376 "mounted read-write\n"
2377 " by another process!", wim->filename);
2378 ret = WIMLIB_ERR_ALREADY_LOCKED;
2380 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2385 wim->wim_locked = 1;
2393 * write_pipable_wim():
2395 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2396 * capable of being applied from a pipe).
2398 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2399 * images can be applied from them sequentially when the file data is sent over
2400 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2401 * The modifications made to the WIM format for pipable WIMs are:
2403 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2404 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2405 * stops other software from trying to read the file as a normal WIM.
2407 * - The header at the beginning of the file does not contain all the normal
2408 * information; in particular it will have all 0's for the lookup table and
2409 * XML data resource entries. This is because this information cannot be
2410 * determined until the lookup table and XML data have been written.
2411 * Consequently, wimlib will write the full header at the very end of the
2412 * file. The header at the end, however, is only used when reading the WIM
2413 * from a seekable file (not a pipe).
2415 * - An extra copy of the XML data is placed directly after the header. This
2416 * allows image names and sizes to be determined at an appropriate time when
2417 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2418 * WIM is read from a seekable file (not a pipe).
2420 * - The format of resources, or streams, has been modified to allow them to be
2421 * used before the "lookup table" has been read. Each stream is prefixed with
2422 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2423 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2424 * uncompressed stream size, and flags that indicate whether the stream is
2425 * compressed. The data of uncompressed streams then follows literally, while
2426 * the data of compressed streams follows in a modified format. Compressed
2427 * streams do not begin with a chunk table, since the chunk table cannot be
2428 * written until all chunks have been compressed. Instead, each compressed
2429 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2430 * Furthermore, the chunk table is written at the end of the resource instead
2431 * of the start. Note: chunk offsets are given in the chunk table as if the
2432 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2433 * used if the WIM is being read from a seekable file (not a pipe).
2435 * - Metadata resources always come before other file resources (streams).
2436 * (This does not by itself constitute an incompatibility with normal WIMs,
2437 * since this is valid in normal WIMs.)
2439 * - At least up to the end of the file resources, all components must be packed
2440 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2441 * not by itself consititute an incompatibility with normal WIMs, since this
2442 * is valid in normal WIMs.)
2444 * Note: the lookup table, XML data, and header at the end are not used when
2445 * applying from a pipe. They exist to support functionality such as image
2446 * application and export when the WIM is *not* read from a pipe.
2448 * Layout of pipable WIM:
2450 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2451 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2452 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2454 * Layout of normal WIM:
2456 * +--------+-----------------------------+-------------------------+
2457 * | Header | File and metadata resources | Lookup table | XML data |
2458 * +--------+-----------------------------+-------------------------+
2460 * An optional integrity table can follow the final XML data in both normal and
2461 * pipable WIMs. However, due to implementation details, wimlib currently can
2462 * only include an integrity table in a pipable WIM when writing it to a
2463 * seekable file (not a pipe).
2465 * Do note that since pipable WIMs are not supported by Microsoft's software,
2466 * wimlib does not create them unless explicitly requested (with
2467 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2468 * characters to identify the file.
2471 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2472 unsigned num_threads, wimlib_progress_func_t progress_func,
2473 struct list_head *stream_list_override)
2476 struct resource_entry xml_res_entry;
2478 WARNING("Creating a pipable WIM, which will "
2480 " with Microsoft's software (wimgapi/imagex/Dism).");
2482 /* At this point, the header at the beginning of the file has already
2485 /* For efficiency, when wimlib adds an image to the WIM with
2486 * wimlib_add_image(), the SHA1 message digests of files is not
2487 * calculated; instead, they are calculated while the files are being
2488 * written. However, this does not work when writing a pipable WIM,
2489 * since when writing a stream to a pipable WIM, its SHA1 message digest
2490 * needs to be known before the stream data is written. Therefore,
2491 * before getting much farther, we need to pre-calculate the SHA1
2492 * message digests of all streams that will be written. */
2493 ret = wim_checksum_unhashed_streams(wim);
2497 /* Write extra copy of the XML data. */
2498 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2500 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2504 /* Write metadata resources for the image(s) being included in the
2506 ret = write_wim_metadata_resources(wim, image, write_flags,
2511 /* Write streams needed for the image(s) being included in the output
2512 * WIM, or streams needed for the split WIM part. */
2513 return write_wim_streams(wim, image, write_flags, num_threads,
2514 progress_func, stream_list_override);
2516 /* The lookup table, XML data, and header at end are handled by
2517 * finish_write(). */
2520 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2523 write_wim_part(WIMStruct *wim,
2524 const void *path_or_fd,
2527 unsigned num_threads,
2528 wimlib_progress_func_t progress_func,
2529 unsigned part_number,
2530 unsigned total_parts,
2531 struct list_head *stream_list_override,
2535 struct wim_header hdr_save;
2536 struct list_head lt_stream_list_override;
2538 if (total_parts == 1)
2539 DEBUG("Writing standalone WIM.");
2541 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2542 if (image == WIMLIB_ALL_IMAGES)
2543 DEBUG("Including all images.");
2545 DEBUG("Including image %d only.", image);
2546 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2547 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2549 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2550 DEBUG("Write flags: 0x%08x", write_flags);
2551 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2552 DEBUG("\tCHECK_INTEGRITY");
2553 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2555 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2556 DEBUG("\tRECOMPRESS");
2557 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2559 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2561 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2562 DEBUG("\tIGNORE_READONLY_FLAG");
2563 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2565 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2566 DEBUG("\tFILE_DESCRIPTOR");
2567 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2568 DEBUG("\tNO_METADATA");
2569 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2570 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2571 if (num_threads == 0)
2572 DEBUG("Number of threads: autodetect");
2574 DEBUG("Number of threads: %u", num_threads);
2575 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2576 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2577 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2578 "specified" : "generate new"));
2580 /* Internally, this is always called with a valid part number and total
2582 wimlib_assert(total_parts >= 1);
2583 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2585 /* A valid image (or all images) must be specified. */
2586 if (image != WIMLIB_ALL_IMAGES &&
2587 (image < 1 || image > wim->hdr.image_count))
2588 return WIMLIB_ERR_INVALID_IMAGE;
2590 /* If we need to write metadata resources, make sure the ::WIMStruct has
2591 * the needed information attached (e.g. is not a resource-only WIM,
2592 * such as a non-first part of a split WIM). */
2593 if (!wim_has_metadata(wim) &&
2594 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2595 return WIMLIB_ERR_METADATA_NOT_FOUND;
2597 /* Check for contradictory flags. */
2598 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2599 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2600 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2601 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2602 return WIMLIB_ERR_INVALID_PARAM;
2604 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2605 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2606 == (WIMLIB_WRITE_FLAG_PIPABLE |
2607 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2608 return WIMLIB_ERR_INVALID_PARAM;
2610 /* Save previous header, then start initializing the new one. */
2611 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2613 /* Set default integrity and pipable flags. */
2614 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2615 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2616 if (wim_is_pipable(wim))
2617 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2619 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2620 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2621 if (wim_has_integrity_table(wim))
2622 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2624 /* Set appropriate magic number. */
2625 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2626 wim->hdr.magic = PWM_MAGIC;
2628 wim->hdr.magic = WIM_MAGIC;
2630 /* Clear header flags that will be set automatically. */
2631 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2632 WIM_HDR_FLAG_RESOURCE_ONLY |
2633 WIM_HDR_FLAG_SPANNED |
2634 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2636 /* Set SPANNED header flag if writing part of a split WIM. */
2637 if (total_parts != 1)
2638 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2640 /* Set part number and total parts of split WIM. This will be 1 and 1
2641 * if the WIM is standalone. */
2642 wim->hdr.part_number = part_number;
2643 wim->hdr.total_parts = total_parts;
2645 /* Set compression type if different. */
2646 if (wim->compression_type != wim->out_compression_type)
2647 wim->hdr.flags = get_wim_hdr_cflags(wim->out_compression_type);
2649 /* Set chunk size if different. */
2650 wim->hdr.chunk_size = wim->out_chunk_size;
2652 /* Use GUID if specified; otherwise generate a new one. */
2654 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2655 else if (!wim->guid_set_explicitly)
2656 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2658 /* Clear references to resources that have not been written yet. */
2659 zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2660 zero_resource_entry(&wim->hdr.xml_res_entry);
2661 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2662 zero_resource_entry(&wim->hdr.integrity);
2664 /* Set image count and boot index correctly for single image writes. */
2665 if (image != WIMLIB_ALL_IMAGES) {
2666 wim->hdr.image_count = 1;
2667 if (wim->hdr.boot_idx == image)
2668 wim->hdr.boot_idx = 1;
2670 wim->hdr.boot_idx = 0;
2673 /* Split WIMs can't be bootable. */
2674 if (total_parts != 1)
2675 wim->hdr.boot_idx = 0;
2677 /* Initialize output file descriptor. */
2678 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2679 /* File descriptor was explicitly provided. Return error if
2680 * file descriptor is not seekable, unless writing a pipable WIM
2682 wim->out_fd.fd = *(const int*)path_or_fd;
2683 wim->out_fd.offset = 0;
2684 if (!filedes_is_seekable(&wim->out_fd)) {
2685 ret = WIMLIB_ERR_INVALID_PARAM;
2686 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2687 goto out_restore_hdr;
2688 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2689 ERROR("Can't include integrity check when "
2690 "writing pipable WIM to pipe!");
2691 goto out_restore_hdr;
2696 /* Filename of WIM to write was provided; open file descriptor
2698 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2699 O_TRUNC | O_CREAT | O_RDWR);
2701 goto out_restore_hdr;
2704 /* Write initial header. This is merely a "dummy" header since it
2705 * doesn't have all the information yet, so it will be overwritten later
2706 * (unless writing a pipable WIM). */
2707 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2708 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2709 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2710 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2712 goto out_restore_hdr;
2714 if (stream_list_override) {
2715 struct wim_lookup_table_entry *lte;
2716 INIT_LIST_HEAD(<_stream_list_override);
2717 list_for_each_entry(lte, stream_list_override,
2720 list_add_tail(<e->lookup_table_list,
2721 <_stream_list_override);
2725 /* Write metadata resources and streams. */
2726 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2727 /* Default case: create a normal (non-pipable) WIM. */
2728 ret = write_wim_streams(wim, image, write_flags, num_threads,
2729 progress_func, stream_list_override);
2731 goto out_restore_hdr;
2733 ret = write_wim_metadata_resources(wim, image, write_flags,
2736 goto out_restore_hdr;
2738 /* Non-default case: create pipable WIM. */
2739 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2740 progress_func, stream_list_override);
2742 goto out_restore_hdr;
2743 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2746 if (stream_list_override)
2747 stream_list_override = <_stream_list_override;
2749 /* Write lookup table, XML data, and (optional) integrity table. */
2750 ret = finish_write(wim, image, write_flags, progress_func,
2751 stream_list_override);
2753 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2754 (void)close_wim_writable(wim, write_flags);
2755 DEBUG("ret=%d", ret);
2759 /* Write a standalone WIM to a file or file descriptor. */
2761 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2762 int image, int write_flags, unsigned num_threads,
2763 wimlib_progress_func_t progress_func)
2765 return write_wim_part(wim, path_or_fd, image, write_flags,
2766 num_threads, progress_func, 1, 1, NULL, NULL);
2769 /* API function documented in wimlib.h */
2771 wimlib_write(WIMStruct *wim, const tchar *path,
2772 int image, int write_flags, unsigned num_threads,
2773 wimlib_progress_func_t progress_func)
2776 return WIMLIB_ERR_INVALID_PARAM;
2778 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2780 return write_standalone_wim(wim, path, image, write_flags,
2781 num_threads, progress_func);
2784 /* API function documented in wimlib.h */
2786 wimlib_write_to_fd(WIMStruct *wim, int fd,
2787 int image, int write_flags, unsigned num_threads,
2788 wimlib_progress_func_t progress_func)
2791 return WIMLIB_ERR_INVALID_PARAM;
2793 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2794 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2796 return write_standalone_wim(wim, &fd, image, write_flags,
2797 num_threads, progress_func);
2801 any_images_modified(WIMStruct *wim)
2803 for (int i = 0; i < wim->hdr.image_count; i++)
2804 if (wim->image_metadata[i]->modified)
2810 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2812 const WIMStruct *wim = _wim;
2813 off_t end_offset = *(const off_t*)wim->private;
2815 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == wim &&
2816 lte->resource_entry.offset + lte->resource_entry.size > end_offset)
2817 return WIMLIB_ERR_RESOURCE_ORDER;
2821 /* Make sure no file or metadata resources are located after the XML data (or
2822 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2823 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2825 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2830 wim->private = &end_offset;
2831 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2835 for (i = 0; i < wim->hdr.image_count; i++) {
2836 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2844 * Overwrite a WIM, possibly appending streams to it.
2846 * A WIM looks like (or is supposed to look like) the following:
2848 * Header (212 bytes)
2849 * Streams and metadata resources (variable size)
2850 * Lookup table (variable size)
2851 * XML data (variable size)
2852 * Integrity table (optional) (variable size)
2854 * If we are not adding any streams or metadata resources, the lookup table is
2855 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2856 * header. This operation is potentially unsafe if the program is abruptly
2857 * terminated while the XML data or integrity table are being overwritten, but
2858 * before the new header has been written. To partially alleviate this problem,
2859 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2860 * finish_write() to cause a temporary WIM header to be written after the XML
2861 * data has been written. This may prevent the WIM from becoming corrupted if
2862 * the program is terminated while the integrity table is being calculated (but
2863 * no guarantees, due to write re-ordering...).
2865 * If we are adding new streams or images (metadata resources), the lookup table
2866 * needs to be changed, and those streams need to be written. In this case, we
2867 * try to perform a safe update of the WIM file by writing the streams *after*
2868 * the end of the previous WIM, then writing the new lookup table, XML data, and
2869 * (optionally) integrity table following the new streams. This will produce a
2870 * layout like the following:
2872 * Header (212 bytes)
2873 * (OLD) Streams and metadata resources (variable size)
2874 * (OLD) Lookup table (variable size)
2875 * (OLD) XML data (variable size)
2876 * (OLD) Integrity table (optional) (variable size)
2877 * (NEW) Streams and metadata resources (variable size)
2878 * (NEW) Lookup table (variable size)
2879 * (NEW) XML data (variable size)
2880 * (NEW) Integrity table (optional) (variable size)
2882 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2883 * the header is overwritten to point to the new lookup table, XML data, and
2884 * integrity table, to produce the following layout:
2886 * Header (212 bytes)
2887 * Streams and metadata resources (variable size)
2888 * Nothing (variable size)
2889 * More Streams and metadata resources (variable size)
2890 * Lookup table (variable size)
2891 * XML data (variable size)
2892 * Integrity table (optional) (variable size)
2894 * This method allows an image to be appended to a large WIM very quickly, and
2895 * is is crash-safe except in the case of write re-ordering, but the
2896 * disadvantage is that a small hole is left in the WIM where the old lookup
2897 * table, xml data, and integrity table were. (These usually only take up a
2898 * small amount of space compared to the streams, however.)
2901 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2902 unsigned num_threads,
2903 wimlib_progress_func_t progress_func)
2906 struct list_head stream_list;
2908 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2909 struct wim_header hdr_save;
2911 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2913 /* Set default integrity flag. */
2914 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2915 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2916 if (wim_has_integrity_table(wim))
2917 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2919 /* Set additional flags for overwrite. */
2920 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2921 WIMLIB_WRITE_FLAG_STREAMS_OK;
2923 /* Make sure that the integrity table (if present) is after the XML
2924 * data, and that there are no stream resources, metadata resources, or
2925 * lookup tables after the XML data. Otherwise, these data would be
2927 old_xml_begin = wim->hdr.xml_res_entry.offset;
2928 old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2929 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2930 wim->hdr.lookup_table_res_entry.size;
2931 if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2932 WARNING("Didn't expect the integrity table to be before the XML data");
2933 return WIMLIB_ERR_RESOURCE_ORDER;
2936 if (old_lookup_table_end > old_xml_begin) {
2937 WARNING("Didn't expect the lookup table to be after the XML data");
2938 return WIMLIB_ERR_RESOURCE_ORDER;
2941 /* Set @old_wim_end, which indicates the point beyond which we don't
2942 * allow any file and metadata resources to appear without returning
2943 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2944 * overwrite these resources). */
2945 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2946 /* If no images have been modified and no images have been
2947 * deleted, a new lookup table does not need to be written. We
2948 * shall write the new XML data and optional integrity table
2949 * immediately after the lookup table. Note that this may
2950 * overwrite an existing integrity table. */
2951 DEBUG("Skipping writing lookup table "
2952 "(no images modified or deleted)");
2953 old_wim_end = old_lookup_table_end;
2954 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2955 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2956 } else if (wim->hdr.integrity.offset) {
2957 /* Old WIM has an integrity table; begin writing new streams
2959 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2961 /* No existing integrity table; begin writing new streams after
2962 * the old XML data. */
2963 old_wim_end = old_xml_end;
2966 ret = check_resource_offsets(wim, old_wim_end);
2970 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2975 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2979 ret = lock_wim(wim, wim->out_fd.fd);
2983 /* Save original header so it can be restored in case of error */
2984 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2986 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2987 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2988 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2990 ERROR_WITH_ERRNO("Error updating WIM header flags");
2991 goto out_restore_memory_hdr;
2994 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2995 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2996 ret = WIMLIB_ERR_WRITE;
2997 goto out_restore_physical_hdr;
3000 ret = write_stream_list(&stream_list,
3003 wim->compression_type,
3012 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3013 write_flags, progress_func);
3017 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3018 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3019 progress_func, NULL);
3023 goto out_unlock_wim;
3026 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3027 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3028 wim->filename, old_wim_end);
3029 /* Return value of ftruncate() is ignored because this is
3030 * already an error path. */
3031 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3033 out_restore_physical_hdr:
3034 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3035 out_restore_memory_hdr:
3036 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3038 (void)close_wim_writable(wim, write_flags);
3040 wim->wim_locked = 0;
3045 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3046 unsigned num_threads,
3047 wimlib_progress_func_t progress_func)
3049 size_t wim_name_len;
3052 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3054 /* Write the WIM to a temporary file in the same directory as the
3056 wim_name_len = tstrlen(wim->filename);
3057 tchar tmpfile[wim_name_len + 10];
3058 tmemcpy(tmpfile, wim->filename, wim_name_len);
3059 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3060 tmpfile[wim_name_len + 9] = T('\0');
3062 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3063 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3064 num_threads, progress_func);
3072 /* Rename the new WIM file to the original WIM file. Note: on Windows
3073 * this actually calls win32_rename_replacement(), not _wrename(), so
3074 * that removing the existing destination file can be handled. */
3075 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3076 ret = trename(tmpfile, wim->filename);
3078 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3079 tmpfile, wim->filename);
3086 return WIMLIB_ERR_RENAME;
3089 if (progress_func) {
3090 union wimlib_progress_info progress;
3091 progress.rename.from = tmpfile;
3092 progress.rename.to = wim->filename;
3093 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3098 /* API function documented in wimlib.h */
3100 wimlib_overwrite(WIMStruct *wim, int write_flags,
3101 unsigned num_threads,
3102 wimlib_progress_func_t progress_func)
3107 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3109 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3110 return WIMLIB_ERR_INVALID_PARAM;
3113 return WIMLIB_ERR_NO_FILENAME;
3115 orig_hdr_flags = wim->hdr.flags;
3116 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3117 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3118 ret = can_modify_wim(wim);
3119 wim->hdr.flags = orig_hdr_flags;
3123 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3124 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3125 WIMLIB_WRITE_FLAG_PIPABLE))
3126 && !(wim_is_pipable(wim))
3127 && wim->compression_type == wim->out_compression_type
3128 && wim->chunk_size == wim->out_chunk_size)
3130 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3132 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3134 WARNING("Falling back to re-building entire WIM");
3136 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,