4 * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5 * compressed file resources, etc.
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33 * overwrite the LIST_HEAD macro. */
34 # include <sys/file.h>
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/header.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/lookup_table.h"
43 #include "wimlib/metadata.h"
44 #include "wimlib/resource.h"
45 #include "wimlib/write.h"
46 #include "wimlib/xml.h"
49 # include "wimlib/win32.h" /* win32_get_number_of_processors() */
52 #ifdef ENABLE_MULTITHREADED_COMPRESSION
68 # include <sys/uio.h> /* for `struct iovec' */
71 /* Return true if the specified resource is compressed and the compressed data
72 * can be reused with the specified output parameters. */
74 can_raw_copy(const struct wim_lookup_table_entry *lte,
75 int write_resource_flags, int out_ctype, u32 out_chunk_size)
77 return (out_ctype == wim_resource_compression_type(lte)
78 && out_chunk_size == wim_resource_chunk_size(lte)
79 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE);
83 /* Return true if the specified resource must be recompressed when the specified
84 * output parameters are used. */
86 must_compress_stream(const struct wim_lookup_table_entry *lte,
87 int write_resource_flags, int out_ctype, u32 out_chunk_size)
89 return (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
90 && ((write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
91 || !can_raw_copy(lte, write_resource_flags,
92 out_ctype, out_chunk_size)));
96 compress_chunk(const void * uncompressed_data,
97 unsigned uncompressed_len,
98 void *compressed_data,
100 struct wimlib_lzx_context *comp_ctx)
103 case WIMLIB_COMPRESSION_TYPE_XPRESS:
104 return wimlib_xpress_compress(uncompressed_data,
107 case WIMLIB_COMPRESSION_TYPE_LZX:
108 return wimlib_lzx_compress2(uncompressed_data,
118 /* Chunk table that's located at the beginning of each compressed resource in
119 * the WIM. (This is not the on-disk format; the on-disk format just has an
120 * array of offsets.) */
122 u64 original_resource_size;
125 unsigned bytes_per_chunk_entry;
131 /* Beginning of chunk offsets, in either 32-bit or 64-bit little endian
132 * integers, including the first offset of 0, which will not be written.
134 u8 offsets[] _aligned_attribute(8);
137 /* Allocate and initializes a chunk table, then reserve space for it in the
138 * output file unless writing a pipable resource. */
140 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
141 struct filedes *out_fd,
143 struct chunk_table **chunk_tab_ret,
148 unsigned bytes_per_chunk_entry;
150 struct chunk_table *chunk_tab;
153 size = wim_resource_size(lte);
154 num_chunks = DIV_ROUND_UP(size, out_chunk_size);
155 bytes_per_chunk_entry = (size > (1ULL << 32)) ? 8 : 4;
156 alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
157 chunk_tab = CALLOC(1, alloc_size);
160 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
162 return WIMLIB_ERR_NOMEM;
164 chunk_tab->num_chunks = num_chunks;
165 chunk_tab->original_resource_size = size;
166 chunk_tab->bytes_per_chunk_entry = bytes_per_chunk_entry;
167 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
169 chunk_tab->cur_offset_p = chunk_tab->offsets;
171 /* We don't know the correct offsets yet; so just write zeroes to
172 * reserve space for the table, so we can go back to it later after
173 * we've written the compressed chunks following it.
175 * Special case: if writing a pipable WIM, compressed resources are in a
176 * modified format (see comment above write_pipable_wim()) and do not
177 * have a chunk table at the beginning, so don't reserve any space for
179 if (!(resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
180 ret = full_write(out_fd, chunk_tab->offsets,
181 chunk_tab->table_disk_size);
183 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
189 *chunk_tab_ret = chunk_tab;
193 /* Add the offset for the next chunk to the chunk table being constructed for a
194 * compressed stream. */
196 chunk_tab_record_chunk(struct chunk_table *chunk_tab, unsigned out_chunk_size)
198 if (chunk_tab->bytes_per_chunk_entry == 4) {
199 *(le32*)chunk_tab->cur_offset_p = cpu_to_le32(chunk_tab->cur_offset_u32);
200 chunk_tab->cur_offset_p = (le32*)chunk_tab->cur_offset_p + 1;
201 chunk_tab->cur_offset_u32 += out_chunk_size;
203 *(le64*)chunk_tab->cur_offset_p = cpu_to_le64(chunk_tab->cur_offset_u64);
204 chunk_tab->cur_offset_p = (le64*)chunk_tab->cur_offset_p + 1;
205 chunk_tab->cur_offset_u64 += out_chunk_size;
209 /* Finishes a WIM chunk table and writes it to the output file at the correct
212 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
213 struct filedes *out_fd,
214 off_t res_start_offset,
215 int write_resource_flags)
219 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
220 ret = full_write(out_fd,
222 chunk_tab->bytes_per_chunk_entry,
223 chunk_tab->table_disk_size);
225 ret = full_pwrite(out_fd,
227 chunk_tab->bytes_per_chunk_entry,
228 chunk_tab->table_disk_size,
232 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
238 /* Write the header for a stream in a pipable WIM.
241 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
242 struct filedes *out_fd,
243 int additional_reshdr_flags)
245 struct pwm_stream_hdr stream_hdr;
249 stream_hdr.magic = PWM_STREAM_MAGIC;
250 stream_hdr.uncompressed_size = cpu_to_le64(lte->resource_entry.original_size);
251 if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
252 zero_out_hash(stream_hdr.hash);
254 wimlib_assert(!lte->unhashed);
255 copy_hash(stream_hdr.hash, lte->hash);
258 reshdr_flags = lte->resource_entry.flags & ~WIM_RESHDR_FLAG_COMPRESSED;
259 reshdr_flags |= additional_reshdr_flags;
260 stream_hdr.flags = cpu_to_le32(reshdr_flags);
261 ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
263 ERROR_WITH_ERRNO("Error writing stream header");
268 seek_and_truncate(struct filedes *out_fd, off_t offset)
270 if (filedes_seek(out_fd, offset) == -1 ||
271 ftruncate(out_fd->fd, offset))
273 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
274 return WIMLIB_ERR_WRITE;
280 finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
282 u8 md[SHA1_HASH_SIZE];
284 sha1_final(md, sha_ctx);
286 copy_hash(lte->hash, md);
287 } else if (!hashes_equal(md, lte->hash)) {
288 ERROR("WIM resource has incorrect hash!");
289 if (lte_filename_valid(lte)) {
290 ERROR("We were reading it from \"%"TS"\"; maybe "
291 "it changed while we were reading it.",
294 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
299 struct write_resource_ctx {
302 struct wimlib_lzx_context *comp_ctx;
303 struct chunk_table *chunk_tab;
304 struct filedes *out_fd;
311 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
313 struct write_resource_ctx *ctx = _ctx;
314 const void *out_chunk;
315 unsigned out_chunk_size;
317 void *compressed_chunk = NULL;
318 unsigned compressed_size;
319 bool compressed_chunk_malloced = false;
320 size_t stack_max = 32768;
323 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
326 out_chunk_size = chunk_size;
327 if (ctx->out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
329 /* Compress the chunk. */
330 if (chunk_size <= stack_max) {
331 compressed_chunk = alloca(chunk_size);
333 compressed_chunk = MALLOC(chunk_size);
334 if (compressed_chunk == NULL)
335 return WIMLIB_ERR_NOMEM;
336 compressed_chunk_malloced = true;
339 compressed_size = compress_chunk(chunk, chunk_size,
343 /* Use compressed data if compression to less than input size
345 if (compressed_size) {
346 out_chunk = compressed_chunk;
347 out_chunk_size = compressed_size;
351 if (ctx->chunk_tab) {
352 /* Update chunk table accounting. */
353 chunk_tab_record_chunk(ctx->chunk_tab, out_chunk_size);
355 /* If writing compressed chunks to a pipable WIM, before the
356 * chunk data write a chunk header that provides the compressed
358 if (ctx->resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
359 struct pwm_chunk_hdr chunk_hdr = {
360 .compressed_size = cpu_to_le32(out_chunk_size),
362 ret = full_write(ctx->out_fd, &chunk_hdr,
369 /* Write the chunk data. */
370 ret = full_write(ctx->out_fd, out_chunk, out_chunk_size);
375 if (compressed_chunk_malloced)
376 FREE(compressed_chunk);
380 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
381 goto out_free_memory;
385 * write_wim_resource()-
387 * Write a resource to an output WIM.
390 * Lookup table entry for the resource, which could be in another WIM, in
391 * an external file, or in another location.
394 * File descriptor opened to the output WIM.
397 * One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate which
398 * compression algorithm to use.
401 * On success, this is filled in with the offset, flags, compressed size,
402 * and uncompressed size of the resource in the output WIM.
405 * * WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed even
406 * if it could otherwise be copied directly from the input;
407 * * WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE if writing a resource for a pipable WIM
408 * (and the output file descriptor may be a pipe).
411 * Location of LZX compression context pointer, which will be allocated or
412 * updated if needed. (Initialize to NULL.)
414 * Additional notes: The SHA1 message digest of the uncompressed data is
415 * calculated (except when doing a raw copy --- see below). If the @unhashed
416 * flag is set on the lookup table entry, this message digest is simply copied
417 * to it; otherwise, the message digest is compared with the existing one, and
418 * the function will fail if they do not match.
421 write_wim_resource(struct wim_lookup_table_entry *lte,
422 struct filedes *out_fd, int out_ctype,
424 struct resource_entry *out_res_entry,
426 struct wimlib_lzx_context **comp_ctx)
428 struct write_resource_ctx write_ctx;
429 off_t res_start_offset;
434 /* Mask out any irrelevant flags, since this function also uses this
435 * variable to store WIMLIB_READ_RESOURCE flags. */
436 resource_flags &= WIMLIB_WRITE_RESOURCE_MASK;
438 /* Get current position in output WIM. */
439 res_start_offset = out_fd->offset;
441 /* If we are not forcing the data to be recompressed, and the input
442 * resource is located in a WIM with the same compression type as that
443 * desired other than no compression, we can simply copy the compressed
444 * data without recompressing it. This also means we must skip
445 * calculating the SHA1, as we never will see the uncompressed data. */
446 if (can_raw_copy(lte, resource_flags, out_ctype, out_chunk_size)) {
447 /* Normally we can request a RAW_FULL read, but if we're reading
448 * from a pipable resource and writing a non-pipable resource or
449 * vice versa, then a RAW_CHUNKS read needs to be requested so
450 * that the written resource can be appropriately formatted.
451 * However, in neither case is any actual decompression needed.
453 if (lte->is_pipable == !!(resource_flags &
454 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
455 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_FULL;
457 resource_flags |= WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS;
458 read_size = lte->resource_entry.size;
459 write_ctx.doing_sha = false;
461 write_ctx.doing_sha = true;
462 sha1_init(&write_ctx.sha_ctx);
463 read_size = lte->resource_entry.original_size;
466 /* If the output resource is to be compressed, initialize the chunk
467 * table and set the function to use for chunk compression. Exceptions:
468 * no compression function is needed if doing a raw copy; also, no chunk
469 * table is needed if doing a *full* (not per-chunk) raw copy. */
470 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
471 write_ctx.out_chunk_size = out_chunk_size;
472 write_ctx.chunk_tab = NULL;
473 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
474 wimlib_assert(out_chunk_size > 0);
475 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW)) {
476 write_ctx.out_ctype = out_ctype;
477 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
478 ret = wimlib_lzx_alloc_context(out_chunk_size,
483 write_ctx.comp_ctx = *comp_ctx;
485 if (!(resource_flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL)) {
486 ret = begin_wim_resource_chunk_tab(lte, out_fd,
488 &write_ctx.chunk_tab,
495 /* If writing a pipable resource, write the stream header and update
496 * @res_start_offset to be the end of the stream header. */
497 if (resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
498 int reshdr_flags = 0;
499 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
500 reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
501 ret = write_pwm_stream_header(lte, out_fd, reshdr_flags);
503 goto out_free_chunk_tab;
504 res_start_offset = out_fd->offset;
507 /* Write the entire resource by reading the entire resource and feeding
508 * the data through the write_resource_cb function. */
509 write_ctx.out_fd = out_fd;
510 write_ctx.resource_flags = resource_flags;
512 if (write_ctx.out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
513 in_chunk_size = wim_resource_chunk_size(lte);
515 in_chunk_size = out_chunk_size;
516 ret = read_resource_prefix(lte, read_size,
518 in_chunk_size, &write_ctx, resource_flags);
520 goto out_free_chunk_tab;
522 /* Verify SHA1 message digest of the resource, or set the hash for the
524 if (write_ctx.doing_sha) {
525 ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
527 goto out_free_chunk_tab;
530 /* Write chunk table if needed. */
531 if (write_ctx.chunk_tab) {
532 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab,
537 goto out_free_chunk_tab;
540 /* Fill in out_res_entry with information about the newly written
542 out_res_entry->size = out_fd->offset - res_start_offset;
543 out_res_entry->flags = lte->resource_entry.flags;
544 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
545 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
547 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
548 out_res_entry->offset = res_start_offset;
549 out_res_entry->original_size = wim_resource_size(lte);
551 /* Check for resources compressed to greater than their original size
552 * and write them uncompressed instead. (But never do this if writing
553 * to a pipe, and don't bother if we did a raw copy.) */
554 if (out_res_entry->size > out_res_entry->original_size &&
555 !(resource_flags & (WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE |
556 WIMLIB_READ_RESOURCE_FLAG_RAW)))
558 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
559 "writing uncompressed instead",
560 out_res_entry->original_size, out_res_entry->size);
561 ret = seek_and_truncate(out_fd, res_start_offset);
563 goto out_free_chunk_tab;
564 out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
565 FREE(write_ctx.chunk_tab);
566 write_ctx.out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
567 write_ctx.chunk_tab = NULL;
568 write_ctx.doing_sha = false;
569 goto try_write_again;
571 if (resource_flags & (WIMLIB_READ_RESOURCE_FLAG_RAW)) {
572 DEBUG("Copied raw compressed data "
573 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
574 out_res_entry->original_size, out_res_entry->size,
575 out_res_entry->offset, out_res_entry->flags);
576 } else if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
577 DEBUG("Wrote compressed resource "
578 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
579 out_res_entry->original_size, out_res_entry->size,
580 out_res_entry->offset, out_res_entry->flags);
582 DEBUG("Wrote uncompressed resource "
583 "(%"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
584 out_res_entry->original_size,
585 out_res_entry->offset, out_res_entry->flags);
589 FREE(write_ctx.chunk_tab);
594 /* Like write_wim_resource(), but the resource is specified by a buffer of
595 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
596 * the buffer to @hash_ret. */
598 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
599 int reshdr_flags, struct filedes *out_fd,
602 struct resource_entry *out_res_entry,
603 u8 *hash_ret, int write_resource_flags,
604 struct wimlib_lzx_context **comp_ctx)
606 /* Set up a temporary lookup table entry to provide to
607 * write_wim_resource(). */
608 struct wim_lookup_table_entry lte;
611 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
612 lte.attached_buffer = (void*)buf;
613 lte.resource_entry.original_size = buf_size;
614 lte.resource_entry.flags = reshdr_flags;
615 lte.compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
617 if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
618 sha1_buffer(buf, buf_size, lte.hash);
624 ret = write_wim_resource(<e, out_fd, out_ctype, out_chunk_size,
625 out_res_entry, write_resource_flags, comp_ctx);
629 copy_hash(hash_ret, lte.hash);
634 #ifdef ENABLE_MULTITHREADED_COMPRESSION
636 /* Blocking shared queue (solves the producer-consumer problem) */
637 struct shared_queue {
641 unsigned filled_slots;
643 pthread_mutex_t lock;
644 pthread_cond_t msg_avail_cond;
645 pthread_cond_t space_avail_cond;
649 shared_queue_init(struct shared_queue *q, unsigned size)
651 wimlib_assert(size != 0);
652 q->array = CALLOC(sizeof(q->array[0]), size);
659 if (pthread_mutex_init(&q->lock, NULL)) {
660 ERROR_WITH_ERRNO("Failed to initialize mutex");
663 if (pthread_cond_init(&q->msg_avail_cond, NULL)) {
664 ERROR_WITH_ERRNO("Failed to initialize condition variable");
665 goto err_destroy_lock;
667 if (pthread_cond_init(&q->space_avail_cond, NULL)) {
668 ERROR_WITH_ERRNO("Failed to initialize condition variable");
669 goto err_destroy_msg_avail_cond;
672 err_destroy_msg_avail_cond:
673 pthread_cond_destroy(&q->msg_avail_cond);
675 pthread_mutex_destroy(&q->lock);
677 return WIMLIB_ERR_NOMEM;
681 shared_queue_destroy(struct shared_queue *q)
684 pthread_mutex_destroy(&q->lock);
685 pthread_cond_destroy(&q->msg_avail_cond);
686 pthread_cond_destroy(&q->space_avail_cond);
690 shared_queue_put(struct shared_queue *q, void *obj)
692 pthread_mutex_lock(&q->lock);
693 while (q->filled_slots == q->size)
694 pthread_cond_wait(&q->space_avail_cond, &q->lock);
696 q->back = (q->back + 1) % q->size;
697 q->array[q->back] = obj;
700 pthread_cond_broadcast(&q->msg_avail_cond);
701 pthread_mutex_unlock(&q->lock);
705 shared_queue_get(struct shared_queue *q)
709 pthread_mutex_lock(&q->lock);
710 while (q->filled_slots == 0)
711 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
713 obj = q->array[q->front];
714 q->array[q->front] = NULL;
715 q->front = (q->front + 1) % q->size;
718 pthread_cond_broadcast(&q->space_avail_cond);
719 pthread_mutex_unlock(&q->lock);
723 struct compressor_thread_params {
724 struct shared_queue *res_to_compress_queue;
725 struct shared_queue *compressed_res_queue;
727 struct wimlib_lzx_context *comp_ctx;
730 #define MAX_CHUNKS_PER_MSG 2
733 struct wim_lookup_table_entry *lte;
735 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
736 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
737 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
738 struct iovec out_chunks[MAX_CHUNKS_PER_MSG];
740 struct list_head list;
746 compress_chunks(struct message *msg, int out_ctype,
747 struct wimlib_lzx_context *comp_ctx)
749 for (unsigned i = 0; i < msg->num_chunks; i++) {
752 len = compress_chunk(msg->uncompressed_chunks[i],
753 msg->uncompressed_chunk_sizes[i],
754 msg->compressed_chunks[i],
761 /* To be written compressed */
762 out_chunk = msg->compressed_chunks[i];
765 /* To be written uncompressed */
766 out_chunk = msg->uncompressed_chunks[i];
767 out_len = msg->uncompressed_chunk_sizes[i];
769 msg->out_chunks[i].iov_base = out_chunk;
770 msg->out_chunks[i].iov_len = out_len;
774 /* Compressor thread routine. This is a lot simpler than the main thread
775 * routine: just repeatedly get a group of chunks from the
776 * res_to_compress_queue, compress them, and put them in the
777 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
780 compressor_thread_proc(void *arg)
782 struct compressor_thread_params *params = arg;
783 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
784 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
787 DEBUG("Compressor thread ready");
788 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
789 compress_chunks(msg, params->out_ctype, params->comp_ctx);
790 shared_queue_put(compressed_res_queue, msg);
792 DEBUG("Compressor thread terminating");
795 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
797 struct write_streams_progress_data {
798 wimlib_progress_func_t progress_func;
799 union wimlib_progress_info progress;
800 uint64_t next_progress;
801 WIMStruct *prev_wim_part;
805 do_write_streams_progress(struct write_streams_progress_data *progress_data,
806 struct wim_lookup_table_entry *lte,
807 bool stream_discarded)
809 union wimlib_progress_info *progress = &progress_data->progress;
812 if (stream_discarded) {
813 progress->write_streams.total_bytes -= wim_resource_size(lte);
814 if (progress_data->next_progress != ~(uint64_t)0 &&
815 progress_data->next_progress > progress->write_streams.total_bytes)
817 progress_data->next_progress = progress->write_streams.total_bytes;
820 progress->write_streams.completed_bytes += wim_resource_size(lte);
822 new_wim_part = false;
823 if (lte->resource_location == RESOURCE_IN_WIM &&
824 lte->wim != progress_data->prev_wim_part)
826 if (progress_data->prev_wim_part) {
828 progress->write_streams.completed_parts++;
830 progress_data->prev_wim_part = lte->wim;
832 progress->write_streams.completed_streams++;
833 if (progress_data->progress_func
834 && (progress->write_streams.completed_bytes >= progress_data->next_progress
837 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
839 if (progress_data->next_progress == progress->write_streams.total_bytes) {
840 progress_data->next_progress = ~(uint64_t)0;
842 progress_data->next_progress =
843 min(progress->write_streams.total_bytes,
844 progress->write_streams.completed_bytes +
845 progress->write_streams.total_bytes / 100);
850 struct serial_write_stream_ctx {
851 struct filedes *out_fd;
854 struct wimlib_lzx_context **comp_ctx;
855 int write_resource_flags;
859 serial_write_stream(struct wim_lookup_table_entry *lte, void *_ctx)
861 struct serial_write_stream_ctx *ctx = _ctx;
862 return write_wim_resource(lte, ctx->out_fd,
865 <e->output_resource_entry,
866 ctx->write_resource_flags,
871 /* Write a list of streams, taking into account that some streams may be
872 * duplicates that are checksummed and discarded on the fly, and also delegating
873 * the actual writing of a stream to a function @write_stream_cb, which is
874 * passed the context @write_stream_ctx. */
876 do_write_stream_list(struct list_head *stream_list,
877 struct wim_lookup_table *lookup_table,
878 int (*write_stream_cb)(struct wim_lookup_table_entry *, void *),
879 void *write_stream_ctx,
880 struct write_streams_progress_data *progress_data)
883 struct wim_lookup_table_entry *lte;
884 bool stream_discarded;
886 /* For each stream in @stream_list ... */
887 while (!list_empty(stream_list)) {
888 stream_discarded = false;
889 lte = container_of(stream_list->next,
890 struct wim_lookup_table_entry,
892 list_del(<e->write_streams_list);
893 if (lte->unhashed && !lte->unique_size) {
894 /* Unhashed stream that shares a size with some other
895 * stream in the WIM we are writing. The stream must be
896 * checksummed to know if we need to write it or not. */
897 struct wim_lookup_table_entry *tmp;
898 u32 orig_out_refcnt = lte->out_refcnt;
900 ret = hash_unhashed_stream(lte, lookup_table, &tmp);
904 /* We found a duplicate stream. 'lte' was
905 * freed, so replace it with the duplicate. */
908 /* 'out_refcnt' was transferred to the
909 * duplicate, and we can detect if the duplicate
910 * stream was already referenced for writing by
911 * checking if its 'out_refcnt' is higher than
912 * that of the original stream. In such cases,
913 * the current stream can be discarded. We can
914 * also discard the current stream if it was
915 * previously marked as filtered (e.g. already
916 * present in the WIM being written). */
917 if (lte->out_refcnt > orig_out_refcnt ||
919 DEBUG("Discarding duplicate stream of "
921 wim_resource_size(lte));
922 lte->no_progress = 0;
923 stream_discarded = true;
924 goto skip_to_progress;
929 /* Here, @lte is either a hashed stream or an unhashed stream
930 * with a unique size. In either case we know that the stream
931 * has to be written. In either case the SHA1 message digest
932 * will be calculated over the stream while writing it; however,
933 * in the former case this is done merely to check the data,
934 * while in the latter case this is done because we do not have
935 * the SHA1 message digest yet. */
936 wimlib_assert(lte->out_refcnt != 0);
938 lte->no_progress = 0;
939 ret = (*write_stream_cb)(lte, write_stream_ctx);
942 /* In parallel mode, some streams are deferred for later,
943 * serialized processing; ignore them here. */
947 list_del(<e->unhashed_list);
948 lookup_table_insert(lookup_table, lte);
952 if (!lte->no_progress) {
953 do_write_streams_progress(progress_data,
954 lte, stream_discarded);
961 do_write_stream_list_serial(struct list_head *stream_list,
962 struct wim_lookup_table *lookup_table,
963 struct filedes *out_fd,
966 struct wimlib_lzx_context **comp_ctx,
967 int write_resource_flags,
968 struct write_streams_progress_data *progress_data)
970 struct serial_write_stream_ctx ctx = {
972 .out_ctype = out_ctype,
973 .out_chunk_size = out_chunk_size,
974 .write_resource_flags = write_resource_flags,
975 .comp_ctx = comp_ctx,
977 return do_write_stream_list(stream_list,
985 write_flags_to_resource_flags(int write_flags)
987 int resource_flags = 0;
989 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
990 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
991 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
992 resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
993 return resource_flags;
997 write_stream_list_serial(struct list_head *stream_list,
998 struct wim_lookup_table *lookup_table,
999 struct filedes *out_fd,
1002 struct wimlib_lzx_context **comp_ctx,
1003 int write_resource_flags,
1004 struct write_streams_progress_data *progress_data)
1006 union wimlib_progress_info *progress = &progress_data->progress;
1007 DEBUG("Writing stream list of size %"PRIu64" (serial version)",
1008 progress->write_streams.total_streams);
1009 progress->write_streams.num_threads = 1;
1010 if (progress_data->progress_func) {
1011 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1014 return do_write_stream_list_serial(stream_list,
1020 write_resource_flags,
1024 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1026 write_wim_chunks(struct message *msg, struct filedes *out_fd,
1027 struct chunk_table *chunk_tab,
1028 int write_resource_flags)
1031 struct pwm_chunk_hdr *chunk_hdrs;
1035 for (unsigned i = 0; i < msg->num_chunks; i++)
1036 chunk_tab_record_chunk(chunk_tab, msg->out_chunks[i].iov_len);
1038 if (!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
1039 nvecs = msg->num_chunks;
1040 vecs = msg->out_chunks;
1042 /* Special case: If writing a compressed resource to a pipable
1043 * WIM, prefix each compressed chunk with a header that gives
1044 * its compressed size. */
1045 nvecs = msg->num_chunks * 2;
1046 vecs = alloca(nvecs * sizeof(vecs[0]));
1047 chunk_hdrs = alloca(msg->num_chunks * sizeof(chunk_hdrs[0]));
1049 for (unsigned i = 0; i < msg->num_chunks; i++) {
1050 chunk_hdrs[i].compressed_size = cpu_to_le32(msg->out_chunks[i].iov_len);
1051 vecs[i * 2].iov_base = &chunk_hdrs[i];
1052 vecs[i * 2].iov_len = sizeof(chunk_hdrs[i]);
1053 vecs[i * 2 + 1].iov_base = msg->out_chunks[i].iov_base;
1054 vecs[i * 2 + 1].iov_len = msg->out_chunks[i].iov_len;
1057 ret = full_writev(out_fd, vecs, nvecs);
1059 ERROR_WITH_ERRNO("Failed to write WIM chunks");
1063 struct main_writer_thread_ctx {
1064 struct list_head *stream_list;
1065 struct wim_lookup_table *lookup_table;
1066 struct filedes *out_fd;
1067 off_t res_start_offset;
1070 struct wimlib_lzx_context **comp_ctx;
1071 int write_resource_flags;
1072 struct shared_queue *res_to_compress_queue;
1073 struct shared_queue *compressed_res_queue;
1074 size_t num_messages;
1075 struct write_streams_progress_data *progress_data;
1077 struct list_head available_msgs;
1078 struct list_head outstanding_streams;
1079 struct list_head serial_streams;
1080 size_t num_outstanding_messages;
1082 SHA_CTX next_sha_ctx;
1084 u64 next_num_chunks;
1085 struct wim_lookup_table_entry *next_lte;
1087 struct message *msgs;
1088 struct message *next_msg;
1089 struct chunk_table *cur_chunk_tab;
1093 init_message(struct message *msg, u32 out_chunk_size)
1095 msg->out_chunk_size = out_chunk_size;
1096 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1097 msg->compressed_chunks[i] = MALLOC(out_chunk_size);
1098 msg->uncompressed_chunks[i] = MALLOC(out_chunk_size);
1099 if (msg->compressed_chunks[i] == NULL ||
1100 msg->uncompressed_chunks[i] == NULL)
1101 return WIMLIB_ERR_NOMEM;
1107 destroy_message(struct message *msg)
1109 for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
1110 FREE(msg->compressed_chunks[i]);
1111 FREE(msg->uncompressed_chunks[i]);
1116 free_messages(struct message *msgs, size_t num_messages)
1119 for (size_t i = 0; i < num_messages; i++)
1120 destroy_message(&msgs[i]);
1125 static struct message *
1126 allocate_messages(size_t num_messages, u32 out_chunk_size)
1128 struct message *msgs;
1130 msgs = CALLOC(num_messages, sizeof(struct message));
1133 for (size_t i = 0; i < num_messages; i++) {
1134 if (init_message(&msgs[i], out_chunk_size)) {
1135 free_messages(msgs, num_messages);
1143 main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
1145 while (ctx->num_outstanding_messages--)
1146 shared_queue_get(ctx->compressed_res_queue);
1147 free_messages(ctx->msgs, ctx->num_messages);
1148 FREE(ctx->cur_chunk_tab);
1152 main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
1154 /* Pre-allocate all the buffers that will be needed to do the chunk
1156 ctx->msgs = allocate_messages(ctx->num_messages, ctx->out_chunk_size);
1158 return WIMLIB_ERR_NOMEM;
1160 /* Initially, all the messages are available to use. */
1161 INIT_LIST_HEAD(&ctx->available_msgs);
1162 for (size_t i = 0; i < ctx->num_messages; i++)
1163 list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
1165 /* outstanding_streams is the list of streams that currently have had
1166 * chunks sent off for compression.
1168 * The first stream in outstanding_streams is the stream that is
1169 * currently being written.
1171 * The last stream in outstanding_streams is the stream that is
1172 * currently being read and having chunks fed to the compressor threads.
1174 INIT_LIST_HEAD(&ctx->outstanding_streams);
1175 ctx->num_outstanding_messages = 0;
1177 ctx->next_msg = NULL;
1179 /* Resources that don't need any chunks compressed are added to this
1180 * list and written directly by the main thread. */
1181 INIT_LIST_HEAD(&ctx->serial_streams);
1183 ctx->cur_chunk_tab = NULL;
1189 receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
1191 struct message *msg;
1192 struct wim_lookup_table_entry *cur_lte;
1195 wimlib_assert(!list_empty(&ctx->outstanding_streams));
1196 wimlib_assert(ctx->num_outstanding_messages != 0);
1198 cur_lte = container_of(ctx->outstanding_streams.next,
1199 struct wim_lookup_table_entry,
1200 being_compressed_list);
1202 /* Get the next message from the queue and process it.
1203 * The message will contain 1 or more data chunks that have been
1205 msg = shared_queue_get(ctx->compressed_res_queue);
1206 msg->complete = true;
1207 --ctx->num_outstanding_messages;
1209 /* Is this the next chunk in the current resource? If it's not
1210 * (i.e., an earlier chunk in a same or different resource
1211 * hasn't been compressed yet), do nothing, and keep this
1212 * message around until all earlier chunks are received.
1214 * Otherwise, write all the chunks we can. */
1215 while (cur_lte != NULL &&
1216 !list_empty(&cur_lte->msg_list)
1217 && (msg = container_of(cur_lte->msg_list.next,
1221 list_move(&msg->list, &ctx->available_msgs);
1222 if (msg->begin_chunk == 0) {
1223 /* First set of chunks. */
1225 /* Write pipable WIM stream header if needed. */
1226 if (ctx->write_resource_flags &
1227 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)
1229 ret = write_pwm_stream_header(cur_lte, ctx->out_fd,
1230 WIM_RESHDR_FLAG_COMPRESSED);
1235 /* Save current offset. */
1236 ctx->res_start_offset = ctx->out_fd->offset;
1238 /* Begin building the chunk table, and leave space for
1240 ret = begin_wim_resource_chunk_tab(cur_lte,
1242 ctx->out_chunk_size,
1243 &ctx->cur_chunk_tab,
1244 ctx->write_resource_flags);
1250 /* Write the compressed chunks from the message. */
1251 ret = write_wim_chunks(msg, ctx->out_fd, ctx->cur_chunk_tab,
1252 ctx->write_resource_flags);
1256 /* Was this the last chunk of the stream? If so, finish
1258 if (list_empty(&cur_lte->msg_list) &&
1259 msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
1263 ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
1265 ctx->res_start_offset,
1266 ctx->write_resource_flags);
1270 list_del(&cur_lte->being_compressed_list);
1272 res_csize = ctx->out_fd->offset - ctx->res_start_offset;
1274 FREE(ctx->cur_chunk_tab);
1275 ctx->cur_chunk_tab = NULL;
1277 /* Check for resources compressed to greater than or
1278 * equal to their original size and write them
1279 * uncompressed instead. (But never do this if writing
1281 if (res_csize >= wim_resource_size(cur_lte) &&
1282 !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
1284 DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
1285 "writing uncompressed instead",
1286 wim_resource_size(cur_lte), res_csize);
1287 ret = seek_and_truncate(ctx->out_fd, ctx->res_start_offset);
1290 ret = write_wim_resource(cur_lte,
1292 WIMLIB_COMPRESSION_TYPE_NONE,
1294 &cur_lte->output_resource_entry,
1295 ctx->write_resource_flags,
1300 cur_lte->output_resource_entry.size =
1303 cur_lte->output_resource_entry.original_size =
1304 cur_lte->resource_entry.original_size;
1306 cur_lte->output_resource_entry.offset =
1307 ctx->res_start_offset;
1309 cur_lte->output_resource_entry.flags =
1310 cur_lte->resource_entry.flags |
1311 WIM_RESHDR_FLAG_COMPRESSED;
1313 DEBUG("Wrote compressed resource "
1314 "(%"PRIu64" => %"PRIu64" bytes @ +%"PRIu64", flags=0x%02x)",
1315 cur_lte->output_resource_entry.original_size,
1316 cur_lte->output_resource_entry.size,
1317 cur_lte->output_resource_entry.offset,
1318 cur_lte->output_resource_entry.flags);
1321 do_write_streams_progress(ctx->progress_data,
1324 /* Since we just finished writing a stream, write any
1325 * streams that have been added to the serial_streams
1326 * list for direct writing by the main thread (e.g.
1327 * resources that don't need to be compressed because
1328 * the desired compression type is the same as the
1329 * previous compression type). */
1330 if (!list_empty(&ctx->serial_streams)) {
1331 ret = do_write_stream_list_serial(&ctx->serial_streams,
1335 ctx->out_chunk_size,
1337 ctx->write_resource_flags,
1338 ctx->progress_data);
1343 /* Advance to the next stream to write. */
1344 if (list_empty(&ctx->outstanding_streams)) {
1347 cur_lte = container_of(ctx->outstanding_streams.next,
1348 struct wim_lookup_table_entry,
1349 being_compressed_list);
1356 /* Called when the main thread has read a new chunk of data. */
1358 main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
1360 struct main_writer_thread_ctx *ctx = _ctx;
1362 struct message *next_msg;
1363 u64 next_chunk_in_msg;
1365 /* Update SHA1 message digest for the stream currently being read by the
1367 sha1_update(&ctx->next_sha_ctx, chunk, chunk_size);
1369 /* We send chunks of data to the compressor chunks in batches which we
1370 * refer to as "messages". @next_msg is the message that is currently
1371 * being prepared to send off. If it is NULL, that indicates that we
1372 * need to start a new message. */
1373 next_msg = ctx->next_msg;
1375 /* We need to start a new message. First check to see if there
1376 * is a message available in the list of available messages. If
1377 * so, we can just take one. If not, all the messages (there is
1378 * a fixed number of them, proportional to the number of
1379 * threads) have been sent off to the compressor threads, so we
1380 * receive messages from the compressor threads containing
1381 * compressed chunks of data.
1383 * We may need to receive multiple messages before one is
1384 * actually available to use because messages received that are
1385 * *not* for the very next set of chunks to compress must be
1386 * buffered until it's time to write those chunks. */
1387 while (list_empty(&ctx->available_msgs)) {
1388 ret = receive_compressed_chunks(ctx);
1393 next_msg = container_of(ctx->available_msgs.next,
1394 struct message, list);
1395 list_del(&next_msg->list);
1396 next_msg->complete = false;
1397 next_msg->begin_chunk = ctx->next_chunk;
1398 next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
1399 ctx->next_num_chunks - ctx->next_chunk);
1400 ctx->next_msg = next_msg;
1403 /* Fill in the next chunk to compress */
1404 next_chunk_in_msg = ctx->next_chunk - next_msg->begin_chunk;
1406 next_msg->uncompressed_chunk_sizes[next_chunk_in_msg] = chunk_size;
1407 memcpy(next_msg->uncompressed_chunks[next_chunk_in_msg],
1410 if (++next_chunk_in_msg == next_msg->num_chunks) {
1411 /* Send off an array of chunks to compress */
1412 list_add_tail(&next_msg->list, &ctx->next_lte->msg_list);
1413 shared_queue_put(ctx->res_to_compress_queue, next_msg);
1414 ++ctx->num_outstanding_messages;
1415 ctx->next_msg = NULL;
1421 main_writer_thread_finish(void *_ctx)
1423 struct main_writer_thread_ctx *ctx = _ctx;
1425 while (ctx->num_outstanding_messages != 0) {
1426 ret = receive_compressed_chunks(ctx);
1430 wimlib_assert(list_empty(&ctx->outstanding_streams));
1431 return do_write_stream_list_serial(&ctx->serial_streams,
1435 ctx->out_chunk_size,
1437 ctx->write_resource_flags,
1438 ctx->progress_data);
1442 submit_stream_for_compression(struct wim_lookup_table_entry *lte,
1443 struct main_writer_thread_ctx *ctx)
1447 /* Read the entire stream @lte, feeding its data chunks to the
1448 * compressor threads. Also SHA1-sum the stream; this is required in
1449 * the case that @lte is unhashed, and a nice additional verification
1450 * when @lte is already hashed. */
1451 sha1_init(&ctx->next_sha_ctx);
1452 ctx->next_chunk = 0;
1453 ctx->next_num_chunks = DIV_ROUND_UP(wim_resource_size(lte),
1454 ctx->out_chunk_size);
1455 ctx->next_lte = lte;
1456 INIT_LIST_HEAD(<e->msg_list);
1457 list_add_tail(<e->being_compressed_list, &ctx->outstanding_streams);
1458 ret = read_resource_prefix(lte, wim_resource_size(lte),
1459 main_writer_thread_cb,
1460 ctx->out_chunk_size, ctx, 0);
1463 wimlib_assert(ctx->next_chunk == ctx->next_num_chunks);
1464 return finalize_and_check_sha1(&ctx->next_sha_ctx, lte);
1468 main_thread_process_next_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1470 struct main_writer_thread_ctx *ctx = _ctx;
1473 if (wim_resource_size(lte) < 1000 ||
1474 !must_compress_stream(lte, ctx->write_resource_flags,
1475 ctx->out_ctype, ctx->out_chunk_size))
1477 /* Stream is too small or isn't being compressed. Process it by
1478 * the main thread when we have a chance. We can't necessarily
1479 * process it right here, as the main thread could be in the
1480 * middle of writing a different stream. */
1481 list_add_tail(<e->write_streams_list, &ctx->serial_streams);
1485 ret = submit_stream_for_compression(lte, ctx);
1487 lte->no_progress = 1;
1492 get_default_num_threads(void)
1495 return win32_get_number_of_processors();
1497 return sysconf(_SC_NPROCESSORS_ONLN);
1501 /* Equivalent to write_stream_list_serial(), except this takes a @num_threads
1502 * parameter and will perform compression using that many threads. Falls
1503 * back to write_stream_list_serial() on certain errors, such as a failure to
1504 * create the number of threads requested.
1506 * High level description of the algorithm for writing compressed streams in
1507 * parallel: We perform compression on chunks rather than on full files. The
1508 * currently executing thread becomes the main thread and is entirely in charge
1509 * of reading the data to compress (which may be in any location understood by
1510 * the resource code--- such as in an external file being captured, or in
1511 * another WIM file from which an image is being exported) and actually writing
1512 * the compressed data to the output file. Additional threads are "compressor
1513 * threads" and all execute the compressor_thread_proc, where they repeatedly
1514 * retrieve buffers of data from the main thread, compress them, and hand them
1515 * back to the main thread.
1517 * Certain streams, such as streams that do not need to be compressed (e.g.
1518 * input compression type same as output compression type) or streams of very
1519 * small size are placed in a list (main_writer_thread_ctx.serial_list) and
1520 * handled entirely by the main thread at an appropriate time.
1522 * At any given point in time, multiple streams may be having chunks compressed
1523 * concurrently. The stream that the main thread is currently *reading* may be
1524 * later in the list that the stream that the main thread is currently
1528 write_stream_list_parallel(struct list_head *stream_list,
1529 struct wim_lookup_table *lookup_table,
1530 struct filedes *out_fd,
1533 struct wimlib_lzx_context **comp_ctx,
1534 int write_resource_flags,
1535 struct write_streams_progress_data *progress_data,
1536 unsigned num_threads)
1539 struct shared_queue res_to_compress_queue;
1540 struct shared_queue compressed_res_queue;
1541 pthread_t *compressor_threads = NULL;
1542 union wimlib_progress_info *progress = &progress_data->progress;
1544 if (num_threads == 0) {
1545 long nthreads = get_default_num_threads();
1546 if (nthreads < 1 || nthreads > UINT_MAX) {
1547 WARNING("Could not determine number of processors! Assuming 1");
1549 } else if (nthreads == 1) {
1550 goto out_serial_quiet;
1552 num_threads = nthreads;
1556 DEBUG("Writing stream list of size %"PRIu64" "
1557 "(parallel version, num_threads=%u)",
1558 progress->write_streams.total_streams, num_threads);
1560 progress->write_streams.num_threads = num_threads;
1562 static const size_t MESSAGES_PER_THREAD = 2;
1563 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1565 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1567 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1571 ret = shared_queue_init(&compressed_res_queue, queue_size);
1573 goto out_destroy_res_to_compress_queue;
1575 struct compressor_thread_params *params;
1577 params = CALLOC(num_threads, sizeof(params[0]));
1578 if (params == NULL) {
1579 ret = WIMLIB_ERR_NOMEM;
1580 goto out_destroy_compressed_res_queue;
1583 for (unsigned i = 0; i < num_threads; i++) {
1584 params[i].res_to_compress_queue = &res_to_compress_queue;
1585 params[i].compressed_res_queue = &compressed_res_queue;
1586 params[i].out_ctype = out_ctype;
1587 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1588 ret = wimlib_lzx_alloc_context(out_chunk_size,
1589 NULL, ¶ms[i].comp_ctx);
1591 goto out_free_params;
1595 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1596 if (!compressor_threads) {
1597 ret = WIMLIB_ERR_NOMEM;
1598 goto out_free_params;
1601 for (unsigned i = 0; i < num_threads; i++) {
1602 DEBUG("pthread_create thread %u of %u", i + 1, num_threads);
1603 ret = pthread_create(&compressor_threads[i], NULL,
1604 compressor_thread_proc, ¶ms[i]);
1607 ERROR_WITH_ERRNO("Failed to create compressor "
1609 i + 1, num_threads);
1615 if (progress_data->progress_func) {
1616 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1620 struct main_writer_thread_ctx ctx;
1621 ctx.stream_list = stream_list;
1622 ctx.lookup_table = lookup_table;
1623 ctx.out_fd = out_fd;
1624 ctx.out_ctype = out_ctype;
1625 ctx.out_chunk_size = out_chunk_size;
1626 ctx.comp_ctx = comp_ctx;
1627 ctx.res_to_compress_queue = &res_to_compress_queue;
1628 ctx.compressed_res_queue = &compressed_res_queue;
1629 ctx.num_messages = queue_size;
1630 ctx.write_resource_flags = write_resource_flags;
1631 ctx.progress_data = progress_data;
1632 ret = main_writer_thread_init_ctx(&ctx);
1635 ret = do_write_stream_list(stream_list, lookup_table,
1636 main_thread_process_next_stream,
1637 &ctx, progress_data);
1639 goto out_destroy_ctx;
1641 /* The main thread has finished reading all streams that are going to be
1642 * compressed in parallel, and it now needs to wait for all remaining
1643 * chunks to be compressed so that the remaining streams can actually be
1644 * written to the output file. Furthermore, any remaining streams that
1645 * had processing deferred to the main thread need to be handled. These
1646 * tasks are done by the main_writer_thread_finish() function. */
1647 ret = main_writer_thread_finish(&ctx);
1649 main_writer_thread_destroy_ctx(&ctx);
1651 for (unsigned i = 0; i < num_threads; i++)
1652 shared_queue_put(&res_to_compress_queue, NULL);
1654 for (unsigned i = 0; i < num_threads; i++) {
1655 if (pthread_join(compressor_threads[i], NULL)) {
1656 WARNING_WITH_ERRNO("Failed to join compressor "
1658 i + 1, num_threads);
1661 FREE(compressor_threads);
1663 for (unsigned i = 0; i < num_threads; i++)
1664 wimlib_lzx_free_context(params[i].comp_ctx);
1666 out_destroy_compressed_res_queue:
1667 shared_queue_destroy(&compressed_res_queue);
1668 out_destroy_res_to_compress_queue:
1669 shared_queue_destroy(&res_to_compress_queue);
1670 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1673 WARNING("Falling back to single-threaded compression");
1675 return write_stream_list_serial(stream_list,
1681 write_resource_flags,
1688 * Write a list of streams to a WIM (@out_fd) using the compression type
1689 * @out_ctype and up to @num_threads compressor threads.
1692 write_stream_list(struct list_head *stream_list,
1693 struct wim_lookup_table *lookup_table,
1694 struct filedes *out_fd, int out_ctype,
1696 struct wimlib_lzx_context **comp_ctx,
1698 unsigned num_threads, wimlib_progress_func_t progress_func)
1700 struct wim_lookup_table_entry *lte;
1701 size_t num_streams = 0;
1702 u64 total_bytes = 0;
1703 u64 total_compression_bytes = 0;
1704 struct write_streams_progress_data progress_data;
1706 int write_resource_flags;
1707 unsigned total_parts = 0;
1708 WIMStruct *prev_wim_part = NULL;
1710 if (list_empty(stream_list)) {
1711 DEBUG("No streams to write.");
1715 write_resource_flags = write_flags_to_resource_flags(write_flags);
1717 DEBUG("Writing stream list (offset = %"PRIu64", write_resource_flags=0x%08x)",
1718 out_fd->offset, write_resource_flags);
1720 sort_stream_list_by_sequential_order(stream_list,
1721 offsetof(struct wim_lookup_table_entry,
1722 write_streams_list));
1724 /* Calculate the total size of the streams to be written. Note: this
1725 * will be the uncompressed size, as we may not know the compressed size
1726 * yet, and also this will assume that every unhashed stream will be
1727 * written (which will not necessarily be the case). */
1728 list_for_each_entry(lte, stream_list, write_streams_list) {
1730 total_bytes += wim_resource_size(lte);
1731 if (must_compress_stream(lte, write_resource_flags,
1732 out_ctype, out_chunk_size))
1733 total_compression_bytes += wim_resource_size(lte);
1734 if (lte->resource_location == RESOURCE_IN_WIM) {
1735 if (prev_wim_part != lte->wim) {
1736 prev_wim_part = lte->wim;
1742 memset(&progress_data, 0, sizeof(progress_data));
1743 progress_data.progress_func = progress_func;
1745 progress_data.progress.write_streams.total_bytes = total_bytes;
1746 progress_data.progress.write_streams.total_streams = num_streams;
1747 progress_data.progress.write_streams.completed_bytes = 0;
1748 progress_data.progress.write_streams.completed_streams = 0;
1749 progress_data.progress.write_streams.num_threads = num_threads;
1750 progress_data.progress.write_streams.compression_type = out_ctype;
1751 progress_data.progress.write_streams.total_parts = total_parts;
1752 progress_data.progress.write_streams.completed_parts = 0;
1754 progress_data.next_progress = 0;
1755 progress_data.prev_wim_part = NULL;
1757 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1758 if (total_compression_bytes >= 2000000 && num_threads != 1)
1759 ret = write_stream_list_parallel(stream_list,
1765 write_resource_flags,
1770 ret = write_stream_list_serial(stream_list,
1776 write_resource_flags,
1779 DEBUG("Successfully wrote stream list.");
1781 DEBUG("Failed to write stream list.");
1785 struct stream_size_table {
1786 struct hlist_head *array;
1792 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1794 tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1796 return WIMLIB_ERR_NOMEM;
1797 tab->num_entries = 0;
1798 tab->capacity = capacity;
1803 destroy_stream_size_table(struct stream_size_table *tab)
1809 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1811 struct stream_size_table *tab = _tab;
1813 struct wim_lookup_table_entry *same_size_lte;
1814 struct hlist_node *tmp;
1816 pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
1817 lte->unique_size = 1;
1818 hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1819 if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
1820 lte->unique_size = 0;
1821 same_size_lte->unique_size = 0;
1826 hlist_add_head(<e->hash_list_2, &tab->array[pos]);
1831 struct find_streams_ctx {
1834 struct list_head stream_list;
1835 struct stream_size_table stream_size_tab;
1839 lte_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1840 struct find_streams_ctx *ctx,
1843 if (lte->out_refcnt == 0) {
1844 stream_size_table_insert(lte, &ctx->stream_size_tab);
1845 list_add_tail(<e->write_streams_list, &ctx->stream_list);
1847 lte->out_refcnt += nref;
1851 do_lte_full_reference_for_logical_write(struct wim_lookup_table_entry *lte,
1854 struct find_streams_ctx *ctx = _ctx;
1855 lte->out_refcnt = 0;
1856 lte_reference_for_logical_write(lte, ctx,
1857 (lte->refcnt ? lte->refcnt : 1));
1862 inode_find_streams_to_write(struct wim_inode *inode,
1863 struct wim_lookup_table *table,
1864 struct find_streams_ctx *ctx)
1866 struct wim_lookup_table_entry *lte;
1869 for (i = 0; i <= inode->i_num_ads; i++) {
1870 lte = inode_stream_lte(inode, i, table);
1872 lte_reference_for_logical_write(lte, ctx, inode->i_nlink);
1873 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1874 return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1880 image_find_streams_to_write(WIMStruct *wim)
1882 struct find_streams_ctx *ctx;
1883 struct wim_image_metadata *imd;
1884 struct wim_inode *inode;
1885 struct wim_lookup_table_entry *lte;
1889 imd = wim_get_current_image_metadata(wim);
1891 image_for_each_unhashed_stream(lte, imd)
1892 lte->out_refcnt = 0;
1894 /* Go through this image's inodes to find any streams that have not been
1896 image_for_each_inode(inode, imd) {
1897 ret = inode_find_streams_to_write(inode, wim->lookup_table, ctx);
1905 * Build a list of streams (via `struct wim_lookup_table_entry's) included in
1906 * the "logical write" of the WIM, meaning all streams that are referenced at
1907 * least once by dentries in the the image(s) being written. 'out_refcnt' on
1908 * each stream being included in the logical write is set to the number of
1909 * references from dentries in the image(s). Furthermore, 'unique_size' on each
1910 * stream being included in the logical write is set to indicate whether that
1911 * stream has a unique size relative to the streams being included in the
1912 * logical write. Still furthermore, 'part_number' on each stream being
1913 * included in the logical write is set to the part number given in the
1914 * in-memory header of @p wim.
1916 * This is considered a "logical write" because it does not take into account
1917 * filtering out streams already present in the WIM (in the case of an in place
1918 * overwrite) or present in other WIMs (in case of creating delta WIM).
1921 prepare_logical_stream_list(WIMStruct *wim, int image, bool streams_ok,
1922 struct find_streams_ctx *ctx)
1925 struct wim_lookup_table_entry *lte;
1927 if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1928 (image == 1 && wim->hdr.image_count == 1)))
1930 /* Fast case: Assume that all streams are being written and
1931 * that the reference counts are correct. */
1932 struct wim_lookup_table_entry *lte;
1933 struct wim_image_metadata *imd;
1936 for_lookup_table_entry(wim->lookup_table,
1937 do_lte_full_reference_for_logical_write, ctx);
1938 for (i = 0; i < wim->hdr.image_count; i++) {
1939 imd = wim->image_metadata[i];
1940 image_for_each_unhashed_stream(lte, imd)
1941 do_lte_full_reference_for_logical_write(lte, ctx);
1944 /* Slow case: Walk through the images being written and
1945 * determine the streams referenced. */
1946 for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1948 ret = for_image(wim, image, image_find_streams_to_write);
1953 list_for_each_entry(lte, &ctx->stream_list, write_streams_list)
1954 lte->part_number = wim->hdr.part_number;
1959 process_filtered_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1961 struct find_streams_ctx *ctx = _ctx;
1964 /* Calculate and set lte->filtered. */
1965 if (lte->resource_location == RESOURCE_IN_WIM) {
1966 if (lte->wim == ctx->wim &&
1967 (ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE))
1968 filtered |= FILTERED_SAME_WIM;
1969 if (lte->wim != ctx->wim &&
1970 (ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS))
1971 filtered |= FILTERED_EXTERNAL_WIM;
1973 lte->filtered = filtered;
1975 /* Filtered streams get inserted into the stream size table too, unless
1976 * they already were. This is because streams that are checksummed
1977 * on-the-fly during the write should not be written if they are
1978 * duplicates of filtered stream. */
1979 if (lte->filtered && lte->out_refcnt == 0)
1980 stream_size_table_insert(lte, &ctx->stream_size_tab);
1985 mark_stream_not_filtered(struct wim_lookup_table_entry *lte, void *_ignore)
1991 /* Given the list of streams to include in a logical write of a WIM, handle
1992 * filtering out streams already present in the WIM or already present in
1993 * external WIMs, depending on the write flags provided. */
1995 handle_stream_filtering(struct find_streams_ctx *ctx)
1997 struct wim_lookup_table_entry *lte, *tmp;
1999 if (!(ctx->write_flags & (WIMLIB_WRITE_FLAG_OVERWRITE |
2000 WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS)))
2002 for_lookup_table_entry(ctx->wim->lookup_table,
2003 mark_stream_not_filtered, ctx);
2007 for_lookup_table_entry(ctx->wim->lookup_table,
2008 process_filtered_stream, ctx);
2010 /* Streams in logical write list that were filtered can be removed. */
2011 list_for_each_entry_safe(lte, tmp, &ctx->stream_list,
2014 list_del(<e->write_streams_list);
2017 /* Prepares list of streams to write for the specified WIM image(s). This wraps
2018 * around prepare_logical_stream_list() to handle filtering out streams already
2019 * present in the WIM or already present in external WIMs, depending on the
2020 * write flags provided.
2022 * Note: some additional data is stored in each `struct wim_lookup_table_entry':
2024 * - 'out_refcnt' is set to the number of references found for the logical write.
2025 * This will be nonzero on all streams in the list returned by this function,
2026 * but will also be nonzero on streams not in the list that were included in
2027 * the logical write list, but filtered out from the returned list.
2028 * - 'filtered' is set to nonzero if the stream was filtered. Filtered streams
2029 * are not included in the list of streams returned by this function.
2030 * - 'unique_size' is set if the stream has a unique size among all streams in
2031 * the logical write plus any filtered streams in the entire WIM that could
2032 * potentially turn out to have the same checksum as a yet-to-be-checksummed
2033 * stream being written.
2036 prepare_stream_list(WIMStruct *wim, int image, int write_flags,
2037 struct list_head *stream_list)
2041 struct find_streams_ctx ctx;
2043 INIT_LIST_HEAD(&ctx.stream_list);
2044 ret = init_stream_size_table(&ctx.stream_size_tab,
2045 wim->lookup_table->capacity);
2048 ctx.write_flags = write_flags;
2051 streams_ok = ((write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK) != 0);
2053 ret = prepare_logical_stream_list(wim, image, streams_ok, &ctx);
2055 goto out_destroy_table;
2057 handle_stream_filtering(&ctx);
2058 list_transfer(&ctx.stream_list, stream_list);
2061 destroy_stream_size_table(&ctx.stream_size_tab);
2066 write_wim_streams(WIMStruct *wim, int image, int write_flags,
2067 unsigned num_threads,
2068 wimlib_progress_func_t progress_func,
2069 struct list_head *stream_list_override)
2072 struct list_head _stream_list;
2073 struct list_head *stream_list;
2074 struct wim_lookup_table_entry *lte;
2076 if (stream_list_override == NULL) {
2077 /* Normal case: prepare stream list from image(s) being written.
2079 stream_list = &_stream_list;
2080 ret = prepare_stream_list(wim, image, write_flags, stream_list);
2084 /* Currently only as a result of wimlib_split() being called:
2085 * use stream list already explicitly provided. Use existing
2086 * reference counts. */
2087 stream_list = stream_list_override;
2088 list_for_each_entry(lte, stream_list, write_streams_list) {
2089 lte->out_refcnt = (lte->refcnt ? lte->refcnt : 1);
2090 lte->part_number = wim->hdr.part_number;
2094 return write_stream_list(stream_list,
2097 wim->out_compression_type,
2098 wim->out_chunk_size,
2106 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2107 wimlib_progress_func_t progress_func)
2112 int write_resource_flags;
2114 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2115 DEBUG("Not writing any metadata resources.");
2119 write_resource_flags = write_flags_to_resource_flags(write_flags);
2121 DEBUG("Writing metadata resources (offset=%"PRIu64")",
2122 wim->out_fd.offset);
2125 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2127 if (image == WIMLIB_ALL_IMAGES) {
2129 end_image = wim->hdr.image_count;
2131 start_image = image;
2135 for (int i = start_image; i <= end_image; i++) {
2136 struct wim_image_metadata *imd;
2138 imd = wim->image_metadata[i - 1];
2139 /* Build a new metadata resource only if image was modified from
2140 * the original (or was newly added). Otherwise just copy the
2142 if (imd->modified) {
2143 DEBUG("Image %u was modified; building and writing new "
2144 "metadata resource", i);
2145 ret = write_metadata_resource(wim, i,
2146 write_resource_flags);
2147 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2148 DEBUG("Image %u was not modified; re-using existing "
2149 "metadata resource.", i);
2150 copy_resource_entry(&imd->metadata_lte->output_resource_entry,
2151 &imd->metadata_lte->resource_entry);
2154 DEBUG("Image %u was not modified; copying existing "
2155 "metadata resource.", i);
2156 ret = write_wim_resource(imd->metadata_lte,
2158 wim->out_compression_type,
2159 wim->out_chunk_size,
2160 &imd->metadata_lte->output_resource_entry,
2161 write_resource_flags,
2168 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2173 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2176 DEBUG("Opening \"%"TS"\" for writing.", path);
2178 raw_fd = topen(path, open_flags | O_BINARY, 0644);
2180 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2181 return WIMLIB_ERR_OPEN;
2183 filedes_init(&wim->out_fd, raw_fd);
2188 close_wim_writable(WIMStruct *wim, int write_flags)
2192 if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2193 DEBUG("Closing WIM file.");
2194 if (filedes_valid(&wim->out_fd))
2195 if (filedes_close(&wim->out_fd))
2196 ret = WIMLIB_ERR_WRITE;
2198 filedes_invalidate(&wim->out_fd);
2205 * Finish writing a WIM file: write the lookup table, xml data, and integrity
2206 * table, then overwrite the WIM header. By default, closes the WIM file
2207 * descriptor (@wim->out_fd) if successful.
2209 * write_flags is a bitwise OR of the following:
2211 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2212 * Include an integrity table.
2214 * (public) WIMLIB_WRITE_FLAG_FSYNC:
2215 * fsync() the output file before closing it.
2217 * (public) WIMLIB_WRITE_FLAG_PIPABLE:
2218 * Writing a pipable WIM, possibly to a pipe; include pipable WIM
2219 * stream headers before the lookup table and XML data, and also
2220 * write the WIM header at the end instead of seeking to the
2221 * beginning. Can't be combined with
2222 * WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2224 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2225 * Don't write the lookup table.
2227 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2228 * When (if) writing the integrity table, re-use entries from the
2229 * existing integrity table, if possible.
2231 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2232 * After writing the XML data but before writing the integrity
2233 * table, write a temporary WIM header and flush the stream so that
2234 * the WIM is less likely to become corrupted upon abrupt program
2236 * (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2237 * Instead of overwriting the WIM header at the beginning of the
2238 * file, simply append it to the end of the file. (Used when
2240 * (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2241 * Do not close the file descriptor @wim->out_fd on either success
2243 * (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2244 * Use the existing <TOTALBYTES> stored in the in-memory XML
2245 * information, rather than setting it to the offset of the XML
2246 * data being written.
2249 finish_write(WIMStruct *wim, int image, int write_flags,
2250 wimlib_progress_func_t progress_func,
2251 struct list_head *stream_list_override)
2255 int write_resource_flags;
2256 off_t old_lookup_table_end;
2257 off_t new_lookup_table_end;
2260 DEBUG("image=%d, write_flags=%08x", image, write_flags);
2262 write_resource_flags = write_flags_to_resource_flags(write_flags);
2264 /* In the WIM header, there is room for the resource entry for a
2265 * metadata resource labeled as the "boot metadata". This entry should
2266 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
2267 * it should be a copy of the resource entry for the image that is
2268 * marked as bootable. This is not well documented... */
2269 if (wim->hdr.boot_idx == 0) {
2270 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2272 copy_resource_entry(&wim->hdr.boot_metadata_res_entry,
2273 &wim->image_metadata[wim->hdr.boot_idx- 1
2274 ]->metadata_lte->output_resource_entry);
2277 /* Write lookup table. (Save old position first.) */
2278 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2279 wim->hdr.lookup_table_res_entry.size;
2280 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2281 ret = write_wim_lookup_table(wim, image, write_flags,
2282 &wim->hdr.lookup_table_res_entry,
2283 stream_list_override);
2288 /* Write XML data. */
2289 xml_totalbytes = wim->out_fd.offset;
2290 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2291 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2292 ret = write_wim_xml_data(wim, image, xml_totalbytes,
2293 &wim->hdr.xml_res_entry,
2294 write_resource_flags);
2298 /* Write integrity table (optional). */
2299 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2300 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2301 struct wim_header checkpoint_hdr;
2302 memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2303 zero_resource_entry(&checkpoint_hdr.integrity);
2304 checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2305 ret = write_wim_header_at_offset(&checkpoint_hdr,
2311 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2312 old_lookup_table_end = 0;
2314 new_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2315 wim->hdr.lookup_table_res_entry.size;
2317 ret = write_integrity_table(wim,
2318 new_lookup_table_end,
2319 old_lookup_table_end,
2324 /* No integrity table. */
2325 zero_resource_entry(&wim->hdr.integrity);
2328 /* Now that all information in the WIM header has been determined, the
2329 * preliminary header written earlier can be overwritten, the header of
2330 * the existing WIM file can be overwritten, or the final header can be
2331 * written to the end of the pipable WIM. */
2332 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2334 if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2335 hdr_offset = wim->out_fd.offset;
2336 DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2337 ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2341 /* Possibly sync file data to disk before closing. On POSIX systems, it
2342 * is necessary to do this before using rename() to overwrite an
2343 * existing file with a new file. Otherwise, data loss would occur if
2344 * the system is abruptly terminated when the metadata for the rename
2345 * operation has been written to disk, but the new file data has not.
2347 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2348 DEBUG("Syncing WIM file.");
2349 if (fsync(wim->out_fd.fd)) {
2350 ERROR_WITH_ERRNO("Error syncing data to WIM file");
2351 return WIMLIB_ERR_WRITE;
2355 if (close_wim_writable(wim, write_flags)) {
2356 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2357 return WIMLIB_ERR_WRITE;
2363 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2365 lock_wim(WIMStruct *wim, int fd)
2368 if (fd != -1 && !wim->wim_locked) {
2369 ret = flock(fd, LOCK_EX | LOCK_NB);
2371 if (errno == EWOULDBLOCK) {
2372 ERROR("`%"TS"' is already being modified or has been "
2373 "mounted read-write\n"
2374 " by another process!", wim->filename);
2375 ret = WIMLIB_ERR_ALREADY_LOCKED;
2377 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2382 wim->wim_locked = 1;
2390 * write_pipable_wim():
2392 * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2393 * capable of being applied from a pipe).
2395 * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2396 * images can be applied from them sequentially when the file data is sent over
2397 * a pipe. In addition, a pipable WIM can be written sequentially to a pipe.
2398 * The modifications made to the WIM format for pipable WIMs are:
2400 * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2401 * of "MSWIM\0\0\0". This lets wimlib know that the WIM is pipable and also
2402 * stops other software from trying to read the file as a normal WIM.
2404 * - The header at the beginning of the file does not contain all the normal
2405 * information; in particular it will have all 0's for the lookup table and
2406 * XML data resource entries. This is because this information cannot be
2407 * determined until the lookup table and XML data have been written.
2408 * Consequently, wimlib will write the full header at the very end of the
2409 * file. The header at the end, however, is only used when reading the WIM
2410 * from a seekable file (not a pipe).
2412 * - An extra copy of the XML data is placed directly after the header. This
2413 * allows image names and sizes to be determined at an appropriate time when
2414 * reading the WIM from a pipe. This copy of the XML data is ignored if the
2415 * WIM is read from a seekable file (not a pipe).
2417 * - The format of resources, or streams, has been modified to allow them to be
2418 * used before the "lookup table" has been read. Each stream is prefixed with
2419 * a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2420 * wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2421 * uncompressed stream size, and flags that indicate whether the stream is
2422 * compressed. The data of uncompressed streams then follows literally, while
2423 * the data of compressed streams follows in a modified format. Compressed
2424 * streams do not begin with a chunk table, since the chunk table cannot be
2425 * written until all chunks have been compressed. Instead, each compressed
2426 * chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2427 * Furthermore, the chunk table is written at the end of the resource instead
2428 * of the start. Note: chunk offsets are given in the chunk table as if the
2429 * `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2430 * used if the WIM is being read from a seekable file (not a pipe).
2432 * - Metadata resources always come before other file resources (streams).
2433 * (This does not by itself constitute an incompatibility with normal WIMs,
2434 * since this is valid in normal WIMs.)
2436 * - At least up to the end of the file resources, all components must be packed
2437 * as tightly as possible; there cannot be any "holes" in the WIM. (This does
2438 * not by itself consititute an incompatibility with normal WIMs, since this
2439 * is valid in normal WIMs.)
2441 * Note: the lookup table, XML data, and header at the end are not used when
2442 * applying from a pipe. They exist to support functionality such as image
2443 * application and export when the WIM is *not* read from a pipe.
2445 * Layout of pipable WIM:
2447 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2448 * | Header | XML data | Metadata resources | File resources | Lookup table | XML data | Header |
2449 * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2451 * Layout of normal WIM:
2453 * +--------+-----------------------------+-------------------------+
2454 * | Header | File and metadata resources | Lookup table | XML data |
2455 * +--------+-----------------------------+-------------------------+
2457 * An optional integrity table can follow the final XML data in both normal and
2458 * pipable WIMs. However, due to implementation details, wimlib currently can
2459 * only include an integrity table in a pipable WIM when writing it to a
2460 * seekable file (not a pipe).
2462 * Do note that since pipable WIMs are not supported by Microsoft's software,
2463 * wimlib does not create them unless explicitly requested (with
2464 * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2465 * characters to identify the file.
2468 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2469 unsigned num_threads, wimlib_progress_func_t progress_func,
2470 struct list_head *stream_list_override)
2473 struct resource_entry xml_res_entry;
2475 WARNING("Creating a pipable WIM, which will "
2477 " with Microsoft's software (wimgapi/imagex/Dism).");
2479 /* At this point, the header at the beginning of the file has already
2482 /* For efficiency, when wimlib adds an image to the WIM with
2483 * wimlib_add_image(), the SHA1 message digests of files is not
2484 * calculated; instead, they are calculated while the files are being
2485 * written. However, this does not work when writing a pipable WIM,
2486 * since when writing a stream to a pipable WIM, its SHA1 message digest
2487 * needs to be known before the stream data is written. Therefore,
2488 * before getting much farther, we need to pre-calculate the SHA1
2489 * message digests of all streams that will be written. */
2490 ret = wim_checksum_unhashed_streams(wim);
2494 /* Write extra copy of the XML data. */
2495 ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2497 WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2501 /* Write metadata resources for the image(s) being included in the
2503 ret = write_wim_metadata_resources(wim, image, write_flags,
2508 /* Write streams needed for the image(s) being included in the output
2509 * WIM, or streams needed for the split WIM part. */
2510 return write_wim_streams(wim, image, write_flags, num_threads,
2511 progress_func, stream_list_override);
2513 /* The lookup table, XML data, and header at end are handled by
2514 * finish_write(). */
2517 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2520 write_wim_part(WIMStruct *wim,
2521 const void *path_or_fd,
2524 unsigned num_threads,
2525 wimlib_progress_func_t progress_func,
2526 unsigned part_number,
2527 unsigned total_parts,
2528 struct list_head *stream_list_override,
2532 struct wim_header hdr_save;
2533 struct list_head lt_stream_list_override;
2535 if (total_parts == 1)
2536 DEBUG("Writing standalone WIM.");
2538 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2539 if (image == WIMLIB_ALL_IMAGES)
2540 DEBUG("Including all images.");
2542 DEBUG("Including image %d only.", image);
2543 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2544 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2546 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2547 DEBUG("Write flags: 0x%08x", write_flags);
2548 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2549 DEBUG("\tCHECK_INTEGRITY");
2550 if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2552 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2553 DEBUG("\tRECOMPRESS");
2554 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2556 if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2558 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2559 DEBUG("\tIGNORE_READONLY_FLAG");
2560 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2562 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2563 DEBUG("\tFILE_DESCRIPTOR");
2564 if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2565 DEBUG("\tNO_METADATA");
2566 if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2567 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2568 if (num_threads == 0)
2569 DEBUG("Number of threads: autodetect");
2571 DEBUG("Number of threads: %u", num_threads);
2572 DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2573 DEBUG("Stream list: %s", (stream_list_override ? "specified" : "autodetect"));
2574 DEBUG("GUID: %s", ((guid || wim->guid_set_explicitly) ?
2575 "specified" : "generate new"));
2577 /* Internally, this is always called with a valid part number and total
2579 wimlib_assert(total_parts >= 1);
2580 wimlib_assert(part_number >= 1 && part_number <= total_parts);
2582 /* A valid image (or all images) must be specified. */
2583 if (image != WIMLIB_ALL_IMAGES &&
2584 (image < 1 || image > wim->hdr.image_count))
2585 return WIMLIB_ERR_INVALID_IMAGE;
2587 /* If we need to write metadata resources, make sure the ::WIMStruct has
2588 * the needed information attached (e.g. is not a resource-only WIM,
2589 * such as a non-first part of a split WIM). */
2590 if (!wim_has_metadata(wim) &&
2591 !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2592 return WIMLIB_ERR_METADATA_NOT_FOUND;
2594 /* Check for contradictory flags. */
2595 if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2596 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2597 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2598 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2599 return WIMLIB_ERR_INVALID_PARAM;
2601 if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2602 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2603 == (WIMLIB_WRITE_FLAG_PIPABLE |
2604 WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2605 return WIMLIB_ERR_INVALID_PARAM;
2607 /* Save previous header, then start initializing the new one. */
2608 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2610 /* Set default integrity and pipable flags. */
2611 if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2612 WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2613 if (wim_is_pipable(wim))
2614 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2616 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2617 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2618 if (wim_has_integrity_table(wim))
2619 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2621 /* Set appropriate magic number. */
2622 if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2623 wim->hdr.magic = PWM_MAGIC;
2625 wim->hdr.magic = WIM_MAGIC;
2627 /* Clear header flags that will be set automatically. */
2628 wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY |
2629 WIM_HDR_FLAG_RESOURCE_ONLY |
2630 WIM_HDR_FLAG_SPANNED |
2631 WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2633 /* Set SPANNED header flag if writing part of a split WIM. */
2634 if (total_parts != 1)
2635 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2637 /* Set part number and total parts of split WIM. This will be 1 and 1
2638 * if the WIM is standalone. */
2639 wim->hdr.part_number = part_number;
2640 wim->hdr.total_parts = total_parts;
2642 /* Set compression type if different. */
2643 if (wim->compression_type != wim->out_compression_type)
2644 wim->hdr.flags = get_wim_hdr_cflags(wim->out_compression_type);
2646 /* Set chunk size if different. */
2647 wim->hdr.chunk_size = wim->out_chunk_size;
2649 /* Use GUID if specified; otherwise generate a new one. */
2651 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2652 else if (!wim->guid_set_explicitly)
2653 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2655 /* Clear references to resources that have not been written yet. */
2656 zero_resource_entry(&wim->hdr.lookup_table_res_entry);
2657 zero_resource_entry(&wim->hdr.xml_res_entry);
2658 zero_resource_entry(&wim->hdr.boot_metadata_res_entry);
2659 zero_resource_entry(&wim->hdr.integrity);
2661 /* Set image count and boot index correctly for single image writes. */
2662 if (image != WIMLIB_ALL_IMAGES) {
2663 wim->hdr.image_count = 1;
2664 if (wim->hdr.boot_idx == image)
2665 wim->hdr.boot_idx = 1;
2667 wim->hdr.boot_idx = 0;
2670 /* Split WIMs can't be bootable. */
2671 if (total_parts != 1)
2672 wim->hdr.boot_idx = 0;
2674 /* Initialize output file descriptor. */
2675 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2676 /* File descriptor was explicitly provided. Return error if
2677 * file descriptor is not seekable, unless writing a pipable WIM
2679 wim->out_fd.fd = *(const int*)path_or_fd;
2680 wim->out_fd.offset = 0;
2681 if (!filedes_is_seekable(&wim->out_fd)) {
2682 ret = WIMLIB_ERR_INVALID_PARAM;
2683 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2684 goto out_restore_hdr;
2685 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2686 ERROR("Can't include integrity check when "
2687 "writing pipable WIM to pipe!");
2688 goto out_restore_hdr;
2693 /* Filename of WIM to write was provided; open file descriptor
2695 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2696 O_TRUNC | O_CREAT | O_RDWR);
2698 goto out_restore_hdr;
2701 /* Write initial header. This is merely a "dummy" header since it
2702 * doesn't have all the information yet, so it will be overwritten later
2703 * (unless writing a pipable WIM). */
2704 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2705 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2706 ret = write_wim_header(&wim->hdr, &wim->out_fd);
2707 wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2709 goto out_restore_hdr;
2711 if (stream_list_override) {
2712 struct wim_lookup_table_entry *lte;
2713 INIT_LIST_HEAD(<_stream_list_override);
2714 list_for_each_entry(lte, stream_list_override,
2717 list_add_tail(<e->lookup_table_list,
2718 <_stream_list_override);
2722 /* Write metadata resources and streams. */
2723 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2724 /* Default case: create a normal (non-pipable) WIM. */
2725 ret = write_wim_streams(wim, image, write_flags, num_threads,
2726 progress_func, stream_list_override);
2728 goto out_restore_hdr;
2730 ret = write_wim_metadata_resources(wim, image, write_flags,
2733 goto out_restore_hdr;
2735 /* Non-default case: create pipable WIM. */
2736 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2737 progress_func, stream_list_override);
2739 goto out_restore_hdr;
2740 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2743 if (stream_list_override)
2744 stream_list_override = <_stream_list_override;
2746 /* Write lookup table, XML data, and (optional) integrity table. */
2747 ret = finish_write(wim, image, write_flags, progress_func,
2748 stream_list_override);
2750 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2751 (void)close_wim_writable(wim, write_flags);
2752 DEBUG("ret=%d", ret);
2756 /* Write a standalone WIM to a file or file descriptor. */
2758 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2759 int image, int write_flags, unsigned num_threads,
2760 wimlib_progress_func_t progress_func)
2762 return write_wim_part(wim, path_or_fd, image, write_flags,
2763 num_threads, progress_func, 1, 1, NULL, NULL);
2766 /* API function documented in wimlib.h */
2768 wimlib_write(WIMStruct *wim, const tchar *path,
2769 int image, int write_flags, unsigned num_threads,
2770 wimlib_progress_func_t progress_func)
2773 return WIMLIB_ERR_INVALID_PARAM;
2775 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2777 return write_standalone_wim(wim, path, image, write_flags,
2778 num_threads, progress_func);
2781 /* API function documented in wimlib.h */
2783 wimlib_write_to_fd(WIMStruct *wim, int fd,
2784 int image, int write_flags, unsigned num_threads,
2785 wimlib_progress_func_t progress_func)
2788 return WIMLIB_ERR_INVALID_PARAM;
2790 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2791 write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2793 return write_standalone_wim(wim, &fd, image, write_flags,
2794 num_threads, progress_func);
2798 any_images_modified(WIMStruct *wim)
2800 for (int i = 0; i < wim->hdr.image_count; i++)
2801 if (wim->image_metadata[i]->modified)
2807 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2809 const WIMStruct *wim = _wim;
2810 off_t end_offset = *(const off_t*)wim->private;
2812 if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == wim &&
2813 lte->resource_entry.offset + lte->resource_entry.size > end_offset)
2814 return WIMLIB_ERR_RESOURCE_ORDER;
2818 /* Make sure no file or metadata resources are located after the XML data (or
2819 * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2820 * place and we return WIMLIB_ERR_RESOURCE_ORDER. */
2822 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2827 wim->private = &end_offset;
2828 ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2832 for (i = 0; i < wim->hdr.image_count; i++) {
2833 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2841 * Overwrite a WIM, possibly appending streams to it.
2843 * A WIM looks like (or is supposed to look like) the following:
2845 * Header (212 bytes)
2846 * Streams and metadata resources (variable size)
2847 * Lookup table (variable size)
2848 * XML data (variable size)
2849 * Integrity table (optional) (variable size)
2851 * If we are not adding any streams or metadata resources, the lookup table is
2852 * unchanged--- so we only need to overwrite the XML data, integrity table, and
2853 * header. This operation is potentially unsafe if the program is abruptly
2854 * terminated while the XML data or integrity table are being overwritten, but
2855 * before the new header has been written. To partially alleviate this problem,
2856 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2857 * finish_write() to cause a temporary WIM header to be written after the XML
2858 * data has been written. This may prevent the WIM from becoming corrupted if
2859 * the program is terminated while the integrity table is being calculated (but
2860 * no guarantees, due to write re-ordering...).
2862 * If we are adding new streams or images (metadata resources), the lookup table
2863 * needs to be changed, and those streams need to be written. In this case, we
2864 * try to perform a safe update of the WIM file by writing the streams *after*
2865 * the end of the previous WIM, then writing the new lookup table, XML data, and
2866 * (optionally) integrity table following the new streams. This will produce a
2867 * layout like the following:
2869 * Header (212 bytes)
2870 * (OLD) Streams and metadata resources (variable size)
2871 * (OLD) Lookup table (variable size)
2872 * (OLD) XML data (variable size)
2873 * (OLD) Integrity table (optional) (variable size)
2874 * (NEW) Streams and metadata resources (variable size)
2875 * (NEW) Lookup table (variable size)
2876 * (NEW) XML data (variable size)
2877 * (NEW) Integrity table (optional) (variable size)
2879 * At all points, the WIM is valid as nothing points to the new data yet. Then,
2880 * the header is overwritten to point to the new lookup table, XML data, and
2881 * integrity table, to produce the following layout:
2883 * Header (212 bytes)
2884 * Streams and metadata resources (variable size)
2885 * Nothing (variable size)
2886 * More Streams and metadata resources (variable size)
2887 * Lookup table (variable size)
2888 * XML data (variable size)
2889 * Integrity table (optional) (variable size)
2891 * This method allows an image to be appended to a large WIM very quickly, and
2892 * is is crash-safe except in the case of write re-ordering, but the
2893 * disadvantage is that a small hole is left in the WIM where the old lookup
2894 * table, xml data, and integrity table were. (These usually only take up a
2895 * small amount of space compared to the streams, however.)
2898 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2899 unsigned num_threads,
2900 wimlib_progress_func_t progress_func)
2903 struct list_head stream_list;
2905 u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2906 struct wim_header hdr_save;
2908 DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2910 /* Set default integrity flag. */
2911 if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2912 WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2913 if (wim_has_integrity_table(wim))
2914 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2916 /* Set additional flags for overwrite. */
2917 write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2918 WIMLIB_WRITE_FLAG_STREAMS_OK;
2920 /* Make sure that the integrity table (if present) is after the XML
2921 * data, and that there are no stream resources, metadata resources, or
2922 * lookup tables after the XML data. Otherwise, these data would be
2924 old_xml_begin = wim->hdr.xml_res_entry.offset;
2925 old_xml_end = old_xml_begin + wim->hdr.xml_res_entry.size;
2926 old_lookup_table_end = wim->hdr.lookup_table_res_entry.offset +
2927 wim->hdr.lookup_table_res_entry.size;
2928 if (wim->hdr.integrity.offset != 0 && wim->hdr.integrity.offset < old_xml_end) {
2929 WARNING("Didn't expect the integrity table to be before the XML data");
2930 return WIMLIB_ERR_RESOURCE_ORDER;
2933 if (old_lookup_table_end > old_xml_begin) {
2934 WARNING("Didn't expect the lookup table to be after the XML data");
2935 return WIMLIB_ERR_RESOURCE_ORDER;
2938 /* Set @old_wim_end, which indicates the point beyond which we don't
2939 * allow any file and metadata resources to appear without returning
2940 * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2941 * overwrite these resources). */
2942 if (!wim->deletion_occurred && !any_images_modified(wim)) {
2943 /* If no images have been modified and no images have been
2944 * deleted, a new lookup table does not need to be written. We
2945 * shall write the new XML data and optional integrity table
2946 * immediately after the lookup table. Note that this may
2947 * overwrite an existing integrity table. */
2948 DEBUG("Skipping writing lookup table "
2949 "(no images modified or deleted)");
2950 old_wim_end = old_lookup_table_end;
2951 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2952 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2953 } else if (wim->hdr.integrity.offset) {
2954 /* Old WIM has an integrity table; begin writing new streams
2956 old_wim_end = wim->hdr.integrity.offset + wim->hdr.integrity.size;
2958 /* No existing integrity table; begin writing new streams after
2959 * the old XML data. */
2960 old_wim_end = old_xml_end;
2963 ret = check_resource_offsets(wim, old_wim_end);
2967 ret = prepare_stream_list(wim, WIMLIB_ALL_IMAGES, write_flags,
2972 ret = open_wim_writable(wim, wim->filename, O_RDWR);
2976 ret = lock_wim(wim, wim->out_fd.fd);
2980 /* Save original header so it can be restored in case of error */
2981 memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2983 /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2984 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2985 ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2987 ERROR_WITH_ERRNO("Error updating WIM header flags");
2988 goto out_restore_memory_hdr;
2991 if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2992 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2993 ret = WIMLIB_ERR_WRITE;
2994 goto out_restore_physical_hdr;
2997 ret = write_stream_list(&stream_list,
3000 wim->compression_type,
3009 ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3010 write_flags, progress_func);
3014 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3015 ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3016 progress_func, NULL);
3020 goto out_unlock_wim;
3023 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3024 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3025 wim->filename, old_wim_end);
3026 /* Return value of ftruncate() is ignored because this is
3027 * already an error path. */
3028 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3030 out_restore_physical_hdr:
3031 (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3032 out_restore_memory_hdr:
3033 memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3035 (void)close_wim_writable(wim, write_flags);
3037 wim->wim_locked = 0;
3042 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3043 unsigned num_threads,
3044 wimlib_progress_func_t progress_func)
3046 size_t wim_name_len;
3049 DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3051 /* Write the WIM to a temporary file in the same directory as the
3053 wim_name_len = tstrlen(wim->filename);
3054 tchar tmpfile[wim_name_len + 10];
3055 tmemcpy(tmpfile, wim->filename, wim_name_len);
3056 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3057 tmpfile[wim_name_len + 9] = T('\0');
3059 ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3060 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3061 num_threads, progress_func);
3069 /* Rename the new WIM file to the original WIM file. Note: on Windows
3070 * this actually calls win32_rename_replacement(), not _wrename(), so
3071 * that removing the existing destination file can be handled. */
3072 DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3073 ret = trename(tmpfile, wim->filename);
3075 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3076 tmpfile, wim->filename);
3083 return WIMLIB_ERR_RENAME;
3086 if (progress_func) {
3087 union wimlib_progress_info progress;
3088 progress.rename.from = tmpfile;
3089 progress.rename.to = wim->filename;
3090 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3095 /* API function documented in wimlib.h */
3097 wimlib_overwrite(WIMStruct *wim, int write_flags,
3098 unsigned num_threads,
3099 wimlib_progress_func_t progress_func)
3104 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3106 if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3107 return WIMLIB_ERR_INVALID_PARAM;
3110 return WIMLIB_ERR_NO_FILENAME;
3112 orig_hdr_flags = wim->hdr.flags;
3113 if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3114 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3115 ret = can_modify_wim(wim);
3116 wim->hdr.flags = orig_hdr_flags;
3120 if ((!wim->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3121 && !(write_flags & (WIMLIB_WRITE_FLAG_REBUILD |
3122 WIMLIB_WRITE_FLAG_PIPABLE))
3123 && !(wim_is_pipable(wim))
3124 && wim->compression_type == wim->out_compression_type
3125 && wim->chunk_size == wim->out_chunk_size)
3127 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3129 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3131 WARNING("Falling back to re-building entire WIM");
3133 return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,