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/.
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "list.h" so that "list.h" can
31 * overwrite the LIST_HEAD macro. */
32 # include <sys/file.h>
40 #include "wimlib_internal.h"
41 #include "buffer_io.h"
43 #include "lookup_table.h"
49 #ifdef ENABLE_MULTITHREADED_COMPRESSION
58 # include <ntfs-3g/attrib.h>
59 # include <ntfs-3g/inode.h>
60 # include <ntfs-3g/dir.h>
71 #if defined(__WIN32__) && !defined(INVALID_HANDLE_VALUE)
72 # define INVALID_HANDLE_VALUE ((HANDLE)(-1))
76 fflush_and_ftruncate(FILE *fp, off_t size)
82 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
83 return WIMLIB_ERR_WRITE;
85 ret = ftruncate(fileno(fp), size);
87 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
88 "%"PRIu64" bytes", size);
89 return WIMLIB_ERR_WRITE;
94 /* Chunk table that's located at the beginning of each compressed resource in
95 * the WIM. (This is not the on-disk format; the on-disk format just has an
96 * array of offsets.) */
100 u64 original_resource_size;
101 u64 bytes_per_chunk_entry;
109 * Allocates and initializes a chunk table, and reserves space for it in the
113 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
116 struct chunk_table **chunk_tab_ret)
118 u64 size = wim_resource_size(lte);
119 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
120 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
121 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
125 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
127 ret = WIMLIB_ERR_NOMEM;
130 chunk_tab->file_offset = file_offset;
131 chunk_tab->num_chunks = num_chunks;
132 chunk_tab->original_resource_size = size;
133 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
134 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
136 chunk_tab->cur_offset = 0;
137 chunk_tab->cur_offset_p = chunk_tab->offsets;
139 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
140 chunk_tab->table_disk_size) {
141 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
143 ret = WIMLIB_ERR_WRITE;
149 *chunk_tab_ret = chunk_tab;
154 * Pointer to function to compresses a chunk of a WIM resource.
156 * @chunk: Uncompressed data of the chunk.
157 * @chunk_size: Size of the uncompressed chunk in bytes.
158 * @compressed_chunk: Pointer to output buffer of size at least
159 * (@chunk_size - 1) bytes.
160 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
161 * of the compressed chunk will be
164 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
165 * compressed to any smaller than @chunk_size. This function cannot fail for
168 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
171 get_compress_func(int out_ctype)
173 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
176 return xpress_compress;
180 * Writes a chunk of a WIM resource to an output file.
182 * @chunk: Uncompressed data of the chunk.
183 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
184 * @out_fp: FILE * to write tho chunk to.
185 * @out_ctype: Compression type to use when writing the chunk (ignored if no
186 * chunk table provided)
187 * @chunk_tab: Pointer to chunk table being created. It is updated with the
188 * offset of the chunk we write.
190 * Returns 0 on success; nonzero on failure.
193 write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
194 FILE *out_fp, compress_func_t compress,
195 struct chunk_table *chunk_tab)
198 unsigned out_chunk_size;
200 u8 *compressed_chunk = alloca(chunk_size);
203 ret = compress(chunk, chunk_size, compressed_chunk,
206 out_chunk = compressed_chunk;
209 out_chunk_size = chunk_size;
211 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
212 chunk_tab->cur_offset += out_chunk_size;
215 out_chunk_size = chunk_size;
217 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
218 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
219 return WIMLIB_ERR_WRITE;
225 * Finishes a WIM chunk table and writes it to the output file at the correct
228 * The final size of the full compressed resource is returned in the
229 * @compressed_size_p.
232 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
233 FILE *out_fp, u64 *compressed_size_p)
235 size_t bytes_written;
236 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
237 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
238 "WIM file", chunk_tab->file_offset);
239 return WIMLIB_ERR_WRITE;
242 if (chunk_tab->bytes_per_chunk_entry == 8) {
243 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
245 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
246 ((u32*)chunk_tab->offsets)[i] =
247 cpu_to_le32(chunk_tab->offsets[i]);
249 bytes_written = fwrite((u8*)chunk_tab->offsets +
250 chunk_tab->bytes_per_chunk_entry,
251 1, chunk_tab->table_disk_size, out_fp);
252 if (bytes_written != chunk_tab->table_disk_size) {
253 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
255 return WIMLIB_ERR_WRITE;
257 if (fseeko(out_fp, 0, SEEK_END) != 0) {
258 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
259 return WIMLIB_ERR_WRITE;
261 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
265 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
266 * attribute pointer in the lookup table entry. */
268 prepare_resource_for_read(struct wim_lookup_table_entry *lte
271 , ntfs_inode **ni_ret
275 switch (lte->resource_location) {
276 case RESOURCE_IN_FILE_ON_DISK:
277 if (!lte->file_on_disk_fp) {
278 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
279 if (!lte->file_on_disk_fp) {
280 ERROR_WITH_ERRNO("Failed to open the file "
281 "`%s'", lte->file_on_disk);
282 return WIMLIB_ERR_OPEN;
287 case RESOURCE_IN_NTFS_VOLUME:
289 struct ntfs_location *loc = lte->ntfs_loc;
292 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path);
294 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
295 "volume", loc->path);
296 return WIMLIB_ERR_NTFS_3G;
298 lte->attr = ntfs_attr_open(ni,
299 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
301 loc->stream_name_nchars);
303 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
304 "NTFS volume", loc->path);
305 ntfs_inode_close(ni);
306 return WIMLIB_ERR_NTFS_3G;
314 if (lte->win32_file_on_disk_fp == INVALID_HANDLE_VALUE) {
315 lte->win32_file_on_disk_fp =
316 win32_open_file_data_only(lte->win32_file_on_disk);
317 if (lte->win32_file_on_disk_fp == INVALID_HANDLE_VALUE) {
318 ERROR("Win32 API: Can't open %ls", lte->win32_file_on_disk);
320 return WIMLIB_ERR_OPEN;
331 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
334 end_wim_resource_read(struct wim_lookup_table_entry *lte
340 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
341 && lte->file_on_disk_fp)
343 fclose(lte->file_on_disk_fp);
344 lte->file_on_disk_fp = NULL;
347 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
349 ntfs_attr_close(lte->attr);
353 ntfs_inode_close(ni);
357 else if (lte->resource_location == RESOURCE_WIN32
358 && lte->win32_file_on_disk_fp != INVALID_HANDLE_VALUE)
360 win32_close_file(lte->win32_file_on_disk_fp);
361 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
367 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
370 struct resource_entry *out_res_entry)
373 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
374 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
375 "output WIM file", file_offset);
376 return WIMLIB_ERR_WRITE;
378 ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
383 return fflush_and_ftruncate(out_fp,
384 file_offset + wim_resource_size(lte));
388 * Writes a WIM resource to a FILE * opened for writing. The resource may be
389 * written uncompressed or compressed depending on the @out_ctype parameter.
391 * If by chance the resource compresses to more than the original size (this may
392 * happen with random data or files than are pre-compressed), the resource is
393 * instead written uncompressed (and this is reflected in the @out_res_entry by
394 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
396 * @lte: The lookup table entry for the WIM resource.
397 * @out_fp: The FILE * to write the resource to.
398 * @out_ctype: The compression type of the resource to write. Note: if this is
399 * the same as the compression type of the WIM resource we
400 * need to read, we simply copy the data (i.e. we do not
401 * uncompress it, then compress it again).
402 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
403 * offset, original size, compressed size, and compression flag
404 * of the output resource.
406 * Returns 0 on success; nonzero on failure.
409 write_wim_resource(struct wim_lookup_table_entry *lte,
410 FILE *out_fp, int out_ctype,
411 struct resource_entry *out_res_entry,
416 u64 old_compressed_size;
417 u64 new_compressed_size;
420 struct chunk_table *chunk_tab = NULL;
423 compress_func_t compress = NULL;
425 ntfs_inode *ni = NULL;
430 /* Original size of the resource */
431 original_size = wim_resource_size(lte);
433 /* Compressed size of the resource (as it exists now) */
434 old_compressed_size = wim_resource_compressed_size(lte);
436 /* Current offset in output file */
437 file_offset = ftello(out_fp);
438 if (file_offset == -1) {
439 ERROR_WITH_ERRNO("Failed to get offset in output "
441 return WIMLIB_ERR_WRITE;
444 /* Are the compression types the same? If so, do a raw copy (copy
445 * without decompressing and recompressing the data). */
446 raw = (wim_resource_compression_type(lte) == out_ctype
447 && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
448 && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
451 flags |= WIMLIB_RESOURCE_FLAG_RAW;
452 bytes_remaining = old_compressed_size;
454 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
455 bytes_remaining = original_size;
458 /* Empty resource; nothing needs to be done, so just return success. */
459 if (bytes_remaining == 0)
462 /* Buffer for reading chunks for the resource */
463 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
465 /* If we are writing a compressed resource and not doing a raw copy, we
466 * need to initialize the chunk table */
467 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
468 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
474 /* If the WIM resource is in an external file, open a FILE * to it so we
475 * don't have to open a temporary one in read_wim_resource() for each
478 ret = prepare_resource_for_read(lte, &ni);
480 ret = prepare_resource_for_read(lte);
485 /* If we aren't doing a raw copy, we will compute the SHA1 message
486 * digest of the resource as we read it, and verify it's the same as the
487 * hash given in the lookup table entry once we've finished reading the
492 compress = get_compress_func(out_ctype);
496 /* While there are still bytes remaining in the WIM resource, read a
497 * chunk of the resource, update SHA1, then write that chunk using the
498 * desired compression type. */
500 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
501 ret = read_wim_resource(lte, buf, to_read, offset, flags);
505 sha1_update(&ctx, buf, to_read);
506 ret = write_wim_resource_chunk(buf, to_read, out_fp,
507 compress, chunk_tab);
510 bytes_remaining -= to_read;
512 } while (bytes_remaining);
514 /* Raw copy: The new compressed size is the same as the old compressed
517 * Using WIMLIB_COMPRESSION_TYPE_NONE: The new compressed size is the
520 * Using a different compression type: Call
521 * finish_wim_resource_chunk_tab() and it will provide the new
525 new_compressed_size = old_compressed_size;
527 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
528 new_compressed_size = original_size;
530 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
531 &new_compressed_size);
537 /* Verify SHA1 message digest of the resource, unless we are doing a raw
538 * write (in which case we never even saw the uncompressed data). Or,
539 * if the hash we had before is all 0's, just re-set it to be the new
542 u8 md[SHA1_HASH_SIZE];
543 sha1_final(md, &ctx);
544 if (is_zero_hash(lte->hash)) {
545 copy_hash(lte->hash, md);
546 } else if (!hashes_equal(md, lte->hash)) {
547 ERROR("WIM resource has incorrect hash!");
548 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
549 ERROR("We were reading it from `%s'; maybe it changed "
550 "while we were reading it.",
553 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
558 if (!raw && new_compressed_size >= original_size &&
559 out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
561 /* Oops! We compressed the resource to larger than the original
562 * size. Write the resource uncompressed instead. */
563 ret = write_uncompressed_resource_and_truncate(lte,
571 out_res_entry->size = new_compressed_size;
572 out_res_entry->original_size = original_size;
573 out_res_entry->offset = file_offset;
574 out_res_entry->flags = lte->resource_entry.flags
575 & ~WIM_RESHDR_FLAG_COMPRESSED;
576 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
577 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
583 end_wim_resource_read(lte, ni);
585 end_wim_resource_read(lte);
592 #ifdef ENABLE_MULTITHREADED_COMPRESSION
594 /* Blocking shared queue (solves the producer-consumer problem) */
595 struct shared_queue {
599 unsigned filled_slots;
601 pthread_mutex_t lock;
602 pthread_cond_t msg_avail_cond;
603 pthread_cond_t space_avail_cond;
607 shared_queue_init(struct shared_queue *q, unsigned size)
609 wimlib_assert(size != 0);
610 q->array = CALLOC(sizeof(q->array[0]), size);
612 return WIMLIB_ERR_NOMEM;
617 pthread_mutex_init(&q->lock, NULL);
618 pthread_cond_init(&q->msg_avail_cond, NULL);
619 pthread_cond_init(&q->space_avail_cond, NULL);
624 shared_queue_destroy(struct shared_queue *q)
627 pthread_mutex_destroy(&q->lock);
628 pthread_cond_destroy(&q->msg_avail_cond);
629 pthread_cond_destroy(&q->space_avail_cond);
633 shared_queue_put(struct shared_queue *q, void *obj)
635 pthread_mutex_lock(&q->lock);
636 while (q->filled_slots == q->size)
637 pthread_cond_wait(&q->space_avail_cond, &q->lock);
639 q->back = (q->back + 1) % q->size;
640 q->array[q->back] = obj;
643 pthread_cond_broadcast(&q->msg_avail_cond);
644 pthread_mutex_unlock(&q->lock);
648 shared_queue_get(struct shared_queue *q)
652 pthread_mutex_lock(&q->lock);
653 while (q->filled_slots == 0)
654 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
656 obj = q->array[q->front];
657 q->array[q->front] = NULL;
658 q->front = (q->front + 1) % q->size;
661 pthread_cond_broadcast(&q->space_avail_cond);
662 pthread_mutex_unlock(&q->lock);
666 struct compressor_thread_params {
667 struct shared_queue *res_to_compress_queue;
668 struct shared_queue *compressed_res_queue;
669 compress_func_t compress;
672 #define MAX_CHUNKS_PER_MSG 2
675 struct wim_lookup_table_entry *lte;
676 u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
677 u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
678 u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
679 unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
680 unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
682 struct list_head list;
688 compress_chunks(struct message *msg, compress_func_t compress)
690 for (unsigned i = 0; i < msg->num_chunks; i++) {
691 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
692 int ret = compress(msg->uncompressed_chunks[i],
693 msg->uncompressed_chunk_sizes[i],
694 msg->compressed_chunks[i],
695 &msg->compressed_chunk_sizes[i]);
697 msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
699 msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
700 msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
705 /* Compressor thread routine. This is a lot simpler than the main thread
706 * routine: just repeatedly get a group of chunks from the
707 * res_to_compress_queue, compress them, and put them in the
708 * compressed_res_queue. A NULL pointer indicates that the thread should stop.
711 compressor_thread_proc(void *arg)
713 struct compressor_thread_params *params = arg;
714 struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
715 struct shared_queue *compressed_res_queue = params->compressed_res_queue;
716 compress_func_t compress = params->compress;
719 DEBUG("Compressor thread ready");
720 while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
721 compress_chunks(msg, compress);
722 shared_queue_put(compressed_res_queue, msg);
724 DEBUG("Compressor thread terminating");
727 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
730 do_write_stream_list(struct list_head *my_resources,
733 wimlib_progress_func_t progress_func,
734 union wimlib_progress_info *progress,
735 int write_resource_flags)
738 struct wim_lookup_table_entry *lte, *tmp;
740 list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
741 ret = write_wim_resource(lte,
744 <e->output_resource_entry,
745 write_resource_flags);
748 list_del(<e->staging_list);
749 progress->write_streams.completed_bytes +=
750 wim_resource_size(lte);
751 progress->write_streams.completed_streams++;
753 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
761 write_stream_list_serial(struct list_head *stream_list,
765 wimlib_progress_func_t progress_func,
766 union wimlib_progress_info *progress)
768 int write_resource_flags;
770 if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
771 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
773 write_resource_flags = 0;
774 progress->write_streams.num_threads = 1;
776 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
777 return do_write_stream_list(stream_list, out_fp,
778 out_ctype, progress_func,
779 progress, write_resource_flags);
782 #ifdef ENABLE_MULTITHREADED_COMPRESSION
784 write_wim_chunks(struct message *msg, FILE *out_fp,
785 struct chunk_table *chunk_tab)
787 for (unsigned i = 0; i < msg->num_chunks; i++) {
788 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
790 DEBUG2("Write wim chunk %u of %u (csize = %u)",
791 i, msg->num_chunks, chunk_csize);
793 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
796 ERROR_WITH_ERRNO("Failed to write WIM chunk");
797 return WIMLIB_ERR_WRITE;
800 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
801 chunk_tab->cur_offset += chunk_csize;
807 * This function is executed by the main thread when the resources are being
808 * compressed in parallel. The main thread is in change of all reading of the
809 * uncompressed data and writing of the compressed data. The compressor threads
810 * *only* do compression from/to in-memory buffers.
812 * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
813 * chunks of compressed data to compress, represented in a `struct message'.
814 * Each message is passed from the main thread to a worker thread through the
815 * res_to_compress_queue, and it is passed back through the
816 * compressed_res_queue.
819 main_writer_thread_proc(struct list_head *stream_list,
822 struct shared_queue *res_to_compress_queue,
823 struct shared_queue *compressed_res_queue,
826 wimlib_progress_func_t progress_func,
827 union wimlib_progress_info *progress)
830 struct chunk_table *cur_chunk_tab = NULL;
831 struct message *msgs = CALLOC(num_messages, sizeof(struct message));
832 struct wim_lookup_table_entry *next_lte = NULL;
834 // Initially, all the messages are available to use.
835 LIST_HEAD(available_msgs);
838 ret = WIMLIB_ERR_NOMEM;
842 for (size_t i = 0; i < num_messages; i++)
843 list_add(&msgs[i].list, &available_msgs);
845 // outstanding_resources is the list of resources that currently have
846 // had chunks sent off for compression.
848 // The first stream in outstanding_resources is the stream that is
849 // currently being written (cur_lte).
851 // The last stream in outstanding_resources is the stream that is
852 // currently being read and chunks fed to the compressor threads
855 // Depending on the number of threads and the sizes of the resource,
856 // the outstanding streams list may contain streams between cur_lte and
857 // next_lte that have all their chunks compressed or being compressed,
858 // but haven't been written yet.
860 LIST_HEAD(outstanding_resources);
861 struct list_head *next_resource = stream_list->next;
863 u64 next_num_chunks = 0;
865 // As in write_wim_resource(), each resource we read is checksummed.
866 SHA_CTX next_sha_ctx;
867 u8 next_hash[SHA1_HASH_SIZE];
869 // Resources that don't need any chunks compressed are added to this
870 // list and written directly by the main thread.
871 LIST_HEAD(my_resources);
873 struct wim_lookup_table_entry *cur_lte = NULL;
877 ntfs_inode *ni = NULL;
880 DEBUG("Initializing buffers for uncompressed "
881 "and compressed data (%zu bytes needed)",
882 num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
884 // Pre-allocate all the buffers that will be needed to do the chunk
886 for (size_t i = 0; i < num_messages; i++) {
887 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
888 msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
890 // The extra 8 bytes is because longest_match() in
891 // lz77.c may read a little bit off the end of the
892 // uncompressed data. It doesn't need to be
893 // initialized--- we really just need to avoid accessing
895 msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
896 if (msgs[i].compressed_chunks[j] == NULL ||
897 msgs[i].uncompressed_chunks[j] == NULL)
899 ret = WIMLIB_ERR_NOMEM;
905 // This loop is executed until all resources have been written, except
906 // possibly a few that have been added to the @my_resources list for
909 // Send chunks to the compressor threads until either (a) there
910 // are no more messages available since they were all sent off,
911 // or (b) there are no more resources that need to be
913 while (!list_empty(&available_msgs)) {
914 if (next_chunk == next_num_chunks) {
915 // If next_chunk == next_num_chunks, there are
916 // no more chunks to write in the current
917 // stream. So, check the SHA1 message digest of
918 // the stream that was just finished (unless
919 // next_lte == NULL, which is the case the very
920 // first time this loop is entered, and also
921 // near the very end of the compression when
922 // there are no more streams.) Then, advance to
923 // the next stream (if there is one).
924 if (next_lte != NULL) {
926 end_wim_resource_read(next_lte, ni);
929 end_wim_resource_read(next_lte);
931 DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
933 sha1_final(next_hash, &next_sha_ctx);
934 if (!hashes_equal(next_lte->hash, next_hash)) {
935 ERROR("WIM resource has incorrect hash!");
936 if (next_lte->resource_location ==
937 RESOURCE_IN_FILE_ON_DISK)
939 ERROR("We were reading it from `%s'; "
940 "maybe it changed while we were "
942 next_lte->file_on_disk);
944 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
949 // Advance to the next resource.
951 // If the next resource needs no compression, just write
952 // it with this thread (not now though--- we could be in
953 // the middle of writing another resource.) Keep doing
954 // this until we either get to the end of the resources
955 // list, or we get to a resource that needs compression.
957 if (next_resource == stream_list) {
958 // No more resources to send for
963 next_lte = container_of(next_resource,
964 struct wim_lookup_table_entry,
966 next_resource = next_resource->next;
967 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
968 && wim_resource_compression_type(next_lte) == out_ctype)
969 || wim_resource_size(next_lte) == 0)
971 list_add_tail(&next_lte->staging_list,
974 list_add_tail(&next_lte->staging_list,
975 &outstanding_resources);
977 next_num_chunks = wim_resource_chunks(next_lte);
978 sha1_init(&next_sha_ctx);
979 INIT_LIST_HEAD(&next_lte->msg_list);
981 ret = prepare_resource_for_read(next_lte, &ni);
983 ret = prepare_resource_for_read(next_lte);
988 if (cur_lte == NULL) {
989 // Set cur_lte for the
998 if (next_lte == NULL) {
999 // No more resources to send for compression
1003 // Get a message from the available messages
1005 msg = container_of(available_msgs.next,
1009 // ... and delete it from the available messages
1011 list_del(&msg->list);
1013 // Initialize the message with the chunks to
1015 msg->num_chunks = min(next_num_chunks - next_chunk,
1016 MAX_CHUNKS_PER_MSG);
1017 msg->lte = next_lte;
1018 msg->complete = false;
1019 msg->begin_chunk = next_chunk;
1021 unsigned size = WIM_CHUNK_SIZE;
1022 for (unsigned i = 0; i < msg->num_chunks; i++) {
1024 // Read chunk @next_chunk of the stream into the
1025 // message so that a compressor thread can
1028 if (next_chunk == next_num_chunks - 1) {
1029 size = MODULO_NONZERO(wim_resource_size(next_lte),
1033 DEBUG2("Read resource (size=%u, offset=%zu)",
1034 size, next_chunk * WIM_CHUNK_SIZE);
1036 msg->uncompressed_chunk_sizes[i] = size;
1038 ret = read_wim_resource(next_lte,
1039 msg->uncompressed_chunks[i],
1041 next_chunk * WIM_CHUNK_SIZE,
1045 sha1_update(&next_sha_ctx,
1046 msg->uncompressed_chunks[i], size);
1050 // Send the compression request
1051 list_add_tail(&msg->list, &next_lte->msg_list);
1052 shared_queue_put(res_to_compress_queue, msg);
1053 DEBUG2("Compression request sent");
1056 // If there are no outstanding resources, there are no more
1057 // resources that need to be written.
1058 if (list_empty(&outstanding_resources)) {
1063 // Get the next message from the queue and process it.
1064 // The message will contain 1 or more data chunks that have been
1066 msg = shared_queue_get(compressed_res_queue);
1067 msg->complete = true;
1069 // Is this the next chunk in the current resource? If it's not
1070 // (i.e., an earlier chunk in a same or different resource
1071 // hasn't been compressed yet), do nothing, and keep this
1072 // message around until all earlier chunks are received.
1074 // Otherwise, write all the chunks we can.
1075 while (cur_lte != NULL &&
1076 !list_empty(&cur_lte->msg_list) &&
1077 (msg = container_of(cur_lte->msg_list.next,
1081 DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1082 if (msg->begin_chunk == 0) {
1083 DEBUG2("Begin chunk tab");
1085 // This is the first set of chunks. Leave space
1086 // for the chunk table in the output file.
1087 off_t cur_offset = ftello(out_fp);
1088 if (cur_offset == -1) {
1089 ret = WIMLIB_ERR_WRITE;
1092 ret = begin_wim_resource_chunk_tab(cur_lte,
1100 // Write the compressed chunks from the message.
1101 ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1105 list_del(&msg->list);
1107 // This message is available to use for different chunks
1109 list_add(&msg->list, &available_msgs);
1111 // Was this the last chunk of the stream? If so, finish
1113 if (list_empty(&cur_lte->msg_list) &&
1114 msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1116 DEBUG2("Finish wim chunk tab");
1118 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1124 if (res_csize >= wim_resource_size(cur_lte)) {
1125 /* Oops! We compressed the resource to
1126 * larger than the original size. Write
1127 * the resource uncompressed instead. */
1128 ret = write_uncompressed_resource_and_truncate(
1131 cur_chunk_tab->file_offset,
1132 &cur_lte->output_resource_entry);
1136 cur_lte->output_resource_entry.size =
1139 cur_lte->output_resource_entry.original_size =
1140 cur_lte->resource_entry.original_size;
1142 cur_lte->output_resource_entry.offset =
1143 cur_chunk_tab->file_offset;
1145 cur_lte->output_resource_entry.flags =
1146 cur_lte->resource_entry.flags |
1147 WIM_RESHDR_FLAG_COMPRESSED;
1150 progress->write_streams.completed_bytes +=
1151 wim_resource_size(cur_lte);
1152 progress->write_streams.completed_streams++;
1154 if (progress_func) {
1155 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1159 FREE(cur_chunk_tab);
1160 cur_chunk_tab = NULL;
1162 struct list_head *next = cur_lte->staging_list.next;
1163 list_del(&cur_lte->staging_list);
1165 if (next == &outstanding_resources)
1168 cur_lte = container_of(cur_lte->staging_list.next,
1169 struct wim_lookup_table_entry,
1172 // Since we just finished writing a stream,
1173 // write any streams that have been added to the
1174 // my_resources list for direct writing by the
1175 // main thread (e.g. resources that don't need
1176 // to be compressed because the desired
1177 // compression type is the same as the previous
1178 // compression type).
1179 ret = do_write_stream_list(&my_resources,
1192 if (ret == WIMLIB_ERR_NOMEM) {
1193 ERROR("Could not allocate enough memory for "
1194 "multi-threaded compression");
1199 end_wim_resource_read(next_lte, ni);
1201 end_wim_resource_read(next_lte);
1206 ret = do_write_stream_list(&my_resources, out_fp,
1207 out_ctype, progress_func,
1211 size_t num_available_msgs = 0;
1212 struct list_head *cur;
1214 list_for_each(cur, &available_msgs) {
1215 num_available_msgs++;
1218 while (num_available_msgs < num_messages) {
1219 shared_queue_get(compressed_res_queue);
1220 num_available_msgs++;
1226 for (size_t i = 0; i < num_messages; i++) {
1227 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1228 FREE(msgs[i].compressed_chunks[j]);
1229 FREE(msgs[i].uncompressed_chunks[j]);
1235 FREE(cur_chunk_tab);
1240 get_default_num_threads()
1243 return win32_get_number_of_processors();
1245 return sysconf(_SC_NPROCESSORS_ONLN);
1250 write_stream_list_parallel(struct list_head *stream_list,
1254 unsigned num_threads,
1255 wimlib_progress_func_t progress_func,
1256 union wimlib_progress_info *progress)
1259 struct shared_queue res_to_compress_queue;
1260 struct shared_queue compressed_res_queue;
1261 pthread_t *compressor_threads = NULL;
1263 if (num_threads == 0) {
1264 long nthreads = get_default_num_threads();
1265 if (nthreads < 1 || nthreads > UINT_MAX) {
1266 WARNING("Could not determine number of processors! Assuming 1");
1269 num_threads = nthreads;
1273 progress->write_streams.num_threads = num_threads;
1274 wimlib_assert(stream_list->next != stream_list);
1276 static const double MESSAGES_PER_THREAD = 2.0;
1277 size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1279 DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1281 ret = shared_queue_init(&res_to_compress_queue, queue_size);
1285 ret = shared_queue_init(&compressed_res_queue, queue_size);
1287 goto out_destroy_res_to_compress_queue;
1289 struct compressor_thread_params params;
1290 params.res_to_compress_queue = &res_to_compress_queue;
1291 params.compressed_res_queue = &compressed_res_queue;
1292 params.compress = get_compress_func(out_ctype);
1294 compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1295 if (!compressor_threads) {
1296 ret = WIMLIB_ERR_NOMEM;
1297 goto out_destroy_compressed_res_queue;
1300 for (unsigned i = 0; i < num_threads; i++) {
1301 DEBUG("pthread_create thread %u", i);
1302 ret = pthread_create(&compressor_threads[i], NULL,
1303 compressor_thread_proc, ¶ms);
1306 ERROR_WITH_ERRNO("Failed to create compressor "
1314 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1316 ret = main_writer_thread_proc(stream_list,
1319 &res_to_compress_queue,
1320 &compressed_res_queue,
1326 for (unsigned i = 0; i < num_threads; i++)
1327 shared_queue_put(&res_to_compress_queue, NULL);
1329 for (unsigned i = 0; i < num_threads; i++) {
1330 if (pthread_join(compressor_threads[i], NULL)) {
1331 WARNING_WITH_ERRNO("Failed to join compressor "
1335 FREE(compressor_threads);
1336 out_destroy_compressed_res_queue:
1337 shared_queue_destroy(&compressed_res_queue);
1338 out_destroy_res_to_compress_queue:
1339 shared_queue_destroy(&res_to_compress_queue);
1340 if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1343 WARNING("Falling back to single-threaded compression");
1344 return write_stream_list_serial(stream_list,
1355 * Write a list of streams to a WIM (@out_fp) using the compression type
1356 * @out_ctype and up to @num_threads compressor threads.
1359 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1360 int out_ctype, int write_flags,
1361 unsigned num_threads,
1362 wimlib_progress_func_t progress_func)
1364 struct wim_lookup_table_entry *lte;
1365 size_t num_streams = 0;
1366 u64 total_bytes = 0;
1367 u64 total_compression_bytes = 0;
1368 union wimlib_progress_info progress;
1370 list_for_each_entry(lte, stream_list, staging_list) {
1372 total_bytes += wim_resource_size(lte);
1373 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1374 && (wim_resource_compression_type(lte) != out_ctype ||
1375 (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1377 total_compression_bytes += wim_resource_size(lte);
1380 progress.write_streams.total_bytes = total_bytes;
1381 progress.write_streams.total_streams = num_streams;
1382 progress.write_streams.completed_bytes = 0;
1383 progress.write_streams.completed_streams = 0;
1384 progress.write_streams.num_threads = num_threads;
1385 progress.write_streams.compression_type = out_ctype;
1387 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1388 if (total_compression_bytes >= 1000000 && num_threads != 1)
1389 return write_stream_list_parallel(stream_list,
1398 return write_stream_list_serial(stream_list,
1406 struct lte_overwrite_prepare_args {
1409 struct list_head *stream_list;
1413 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1415 struct lte_overwrite_prepare_args *args = arg;
1417 if (lte->resource_location == RESOURCE_IN_WIM &&
1418 lte->wim == args->wim &&
1419 lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1421 #ifdef ENABLE_ERROR_MESSAGES
1422 ERROR("The following resource is after the XML data:");
1423 print_lookup_table_entry(lte, stderr);
1425 return WIMLIB_ERR_RESOURCE_ORDER;
1428 lte->out_refcnt = lte->refcnt;
1429 memcpy(<e->output_resource_entry, <e->resource_entry,
1430 sizeof(struct resource_entry));
1431 if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA)) {
1432 wimlib_assert(lte->resource_location != RESOURCE_NONEXISTENT);
1433 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1434 list_add(<e->staging_list, args->stream_list);
1440 wim_find_new_streams(WIMStruct *wim, off_t end_offset,
1441 struct list_head *stream_list)
1443 struct lte_overwrite_prepare_args args = {
1445 .end_offset = end_offset,
1446 .stream_list = stream_list,
1449 return for_lookup_table_entry(wim->lookup_table,
1450 lte_overwrite_prepare, &args);
1454 inode_find_streams_to_write(struct wim_inode *inode,
1455 struct wim_lookup_table *table,
1456 struct list_head *stream_list)
1458 struct wim_lookup_table_entry *lte;
1459 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1460 lte = inode_stream_lte(inode, i, table);
1462 if (lte->out_refcnt == 0)
1463 list_add_tail(<e->staging_list, stream_list);
1464 lte->out_refcnt += inode->i_nlink;
1471 image_find_streams_to_write(WIMStruct *w)
1473 struct wim_inode *inode;
1474 struct hlist_node *cur;
1475 struct hlist_head *inode_list;
1477 inode_list = &wim_get_current_image_metadata(w)->inode_list;
1478 hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1479 inode_find_streams_to_write(inode, w->lookup_table,
1480 (struct list_head*)w->private);
1486 write_wim_streams(WIMStruct *w, int image, int write_flags,
1487 unsigned num_threads,
1488 wimlib_progress_func_t progress_func)
1491 for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1492 LIST_HEAD(stream_list);
1493 w->private = &stream_list;
1494 for_image(w, image, image_find_streams_to_write);
1495 return write_stream_list(&stream_list, w->out_fp,
1496 wimlib_get_compression_type(w), write_flags,
1497 num_threads, progress_func);
1501 * Finish writing a WIM file: write the lookup table, xml data, and integrity
1502 * table (optional), then overwrite the WIM header.
1504 * write_flags is a bitwise OR of the following:
1506 * (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1507 * Include an integrity table.
1509 * (public) WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1510 * Show progress information when (if) writing the integrity table.
1512 * (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1513 * Don't write the lookup table.
1515 * (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1516 * When (if) writing the integrity table, re-use entries from the
1517 * existing integrity table, if possible.
1519 * (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1520 * After writing the XML data but before writing the integrity
1521 * table, write a temporary WIM header and flush the stream so that
1522 * the WIM is less likely to become corrupted upon abrupt program
1525 * (private) WIMLIB_WRITE_FLAG_FSYNC:
1526 * fsync() the output file before closing it.
1530 finish_write(WIMStruct *w, int image, int write_flags,
1531 wimlib_progress_func_t progress_func)
1534 struct wim_header hdr;
1535 FILE *out = w->out_fp;
1537 /* @hdr will be the header for the new WIM. First copy all the data
1538 * from the header in the WIMStruct; then set all the fields that may
1539 * have changed, including the resource entries, boot index, and image
1541 memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1543 if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1544 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1549 ret = write_xml_data(w->wim_info, image, out,
1550 (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1551 wim_info_get_total_bytes(w->wim_info) : 0,
1552 &hdr.xml_res_entry);
1556 if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1557 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1558 struct wim_header checkpoint_hdr;
1559 memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1560 memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1561 if (fseeko(out, 0, SEEK_SET) != 0) {
1562 ERROR_WITH_ERRNO("Failed to seek to beginning "
1563 "of WIM being written");
1564 ret = WIMLIB_ERR_WRITE;
1567 ret = write_header(&checkpoint_hdr, out);
1571 if (fflush(out) != 0) {
1572 ERROR_WITH_ERRNO("Can't write data to WIM");
1573 ret = WIMLIB_ERR_WRITE;
1577 if (fseeko(out, 0, SEEK_END) != 0) {
1578 ERROR_WITH_ERRNO("Failed to seek to end "
1579 "of WIM being written");
1580 ret = WIMLIB_ERR_WRITE;
1585 off_t old_lookup_table_end;
1586 off_t new_lookup_table_end;
1587 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1588 old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1589 w->hdr.lookup_table_res_entry.size;
1591 old_lookup_table_end = 0;
1593 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1594 hdr.lookup_table_res_entry.size;
1596 ret = write_integrity_table(out,
1598 new_lookup_table_end,
1599 old_lookup_table_end,
1604 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1608 * In the WIM header, there is room for the resource entry for a
1609 * metadata resource labeled as the "boot metadata". This entry should
1610 * be zeroed out if there is no bootable image (boot_idx 0). Otherwise,
1611 * it should be a copy of the resource entry for the image that is
1612 * marked as bootable. This is not well documented...
1615 /* Set image count and boot index correctly for single image writes */
1616 if (image != WIMLIB_ALL_IMAGES) {
1617 hdr.image_count = 1;
1618 if (hdr.boot_idx == image)
1624 if (hdr.boot_idx == 0) {
1625 memset(&hdr.boot_metadata_res_entry, 0,
1626 sizeof(struct resource_entry));
1628 memcpy(&hdr.boot_metadata_res_entry,
1630 hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1631 sizeof(struct resource_entry));
1634 if (fseeko(out, 0, SEEK_SET) != 0) {
1635 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1637 ret = WIMLIB_ERR_WRITE;
1641 ret = write_header(&hdr, out);
1645 if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1646 if (fflush(out) != 0
1647 || fsync(fileno(out)) != 0)
1649 ERROR_WITH_ERRNO("Error flushing data to WIM file");
1650 ret = WIMLIB_ERR_WRITE;
1654 if (fclose(out) != 0) {
1655 ERROR_WITH_ERRNO("Failed to close the WIM file");
1657 ret = WIMLIB_ERR_WRITE;
1663 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1665 lock_wim(WIMStruct *w, FILE *fp)
1668 if (fp && !w->wim_locked) {
1669 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1671 if (errno == EWOULDBLOCK) {
1672 ERROR("`%s' is already being modified or has been "
1673 "mounted read-write\n"
1674 " by another process!", w->filename);
1675 ret = WIMLIB_ERR_ALREADY_LOCKED;
1677 WARNING_WITH_ERRNO("Failed to lock `%s'",
1690 open_wim_writable(WIMStruct *w, const mbchar *path,
1691 bool trunc, bool readable)
1702 wimlib_assert(w->out_fp == NULL);
1703 w->out_fp = fopen(path, mode);
1707 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
1708 return WIMLIB_ERR_OPEN;
1714 close_wim_writable(WIMStruct *w)
1717 if (fclose(w->out_fp) != 0) {
1718 WARNING_WITH_ERRNO("Failed to close output WIM");
1724 /* Open file stream and write dummy header for WIM. */
1726 begin_write(WIMStruct *w, const mbchar *path, int write_flags)
1729 ret = open_wim_writable(w, path, true,
1730 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1733 /* Write dummy header. It will be overwritten later. */
1734 return write_header(&w->hdr, w->out_fp);
1737 /* Writes a stand-alone WIM to a file. */
1739 wimlib_write(WIMStruct *w, const mbchar *path,
1740 int image, int write_flags, unsigned num_threads,
1741 wimlib_progress_func_t progress_func)
1746 return WIMLIB_ERR_INVALID_PARAM;
1748 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1750 if (image != WIMLIB_ALL_IMAGES &&
1751 (image < 1 || image > w->hdr.image_count))
1752 return WIMLIB_ERR_INVALID_IMAGE;
1754 if (w->hdr.total_parts != 1) {
1755 ERROR("Cannot call wimlib_write() on part of a split WIM");
1756 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1759 ret = begin_write(w, path, write_flags);
1763 ret = write_wim_streams(w, image, write_flags, num_threads,
1769 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1771 ret = for_image(w, image, write_metadata_resource);
1776 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1778 ret = finish_write(w, image, write_flags, progress_func);
1780 close_wim_writable(w);
1781 DEBUG("wimlib_write(path=%s) = %d", path, ret);
1786 any_images_modified(WIMStruct *w)
1788 for (int i = 0; i < w->hdr.image_count; i++)
1789 if (w->image_metadata[i].modified)
1795 * Overwrite a WIM, possibly appending streams to it.
1797 * A WIM looks like (or is supposed to look like) the following:
1799 * Header (212 bytes)
1800 * Streams and metadata resources (variable size)
1801 * Lookup table (variable size)
1802 * XML data (variable size)
1803 * Integrity table (optional) (variable size)
1805 * If we are not adding any streams or metadata resources, the lookup table is
1806 * unchanged--- so we only need to overwrite the XML data, integrity table, and
1807 * header. This operation is potentially unsafe if the program is abruptly
1808 * terminated while the XML data or integrity table are being overwritten, but
1809 * before the new header has been written. To partially alleviate this problem,
1810 * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1811 * finish_write() to cause a temporary WIM header to be written after the XML
1812 * data has been written. This may prevent the WIM from becoming corrupted if
1813 * the program is terminated while the integrity table is being calculated (but
1814 * no guarantees, due to write re-ordering...).
1816 * If we are adding new streams or images (metadata resources), the lookup table
1817 * needs to be changed, and those streams need to be written. In this case, we
1818 * try to perform a safe update of the WIM file by writing the streams *after*
1819 * the end of the previous WIM, then writing the new lookup table, XML data, and
1820 * (optionally) integrity table following the new streams. This will produce a
1821 * layout like the following:
1823 * Header (212 bytes)
1824 * (OLD) Streams and metadata resources (variable size)
1825 * (OLD) Lookup table (variable size)
1826 * (OLD) XML data (variable size)
1827 * (OLD) Integrity table (optional) (variable size)
1828 * (NEW) Streams and metadata resources (variable size)
1829 * (NEW) Lookup table (variable size)
1830 * (NEW) XML data (variable size)
1831 * (NEW) Integrity table (optional) (variable size)
1833 * At all points, the WIM is valid as nothing points to the new data yet. Then,
1834 * the header is overwritten to point to the new lookup table, XML data, and
1835 * integrity table, to produce the following layout:
1837 * Header (212 bytes)
1838 * Streams and metadata resources (variable size)
1839 * Nothing (variable size)
1840 * More Streams and metadata resources (variable size)
1841 * Lookup table (variable size)
1842 * XML data (variable size)
1843 * Integrity table (optional) (variable size)
1845 * This method allows an image to be appended to a large WIM very quickly, and
1846 * is is crash-safe except in the case of write re-ordering, but the
1847 * disadvantage is that a small hole is left in the WIM where the old lookup
1848 * table, xml data, and integrity table were. (These usually only take up a
1849 * small amount of space compared to the streams, however.)
1852 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1853 unsigned num_threads,
1854 wimlib_progress_func_t progress_func)
1857 struct list_head stream_list;
1859 bool found_modified_image;
1861 DEBUG("Overwriting `%s' in-place", w->filename);
1863 /* Make sure that the integrity table (if present) is after the XML
1864 * data, and that there are no stream resources, metadata resources, or
1865 * lookup tables after the XML data. Otherwise, these data would be
1867 if (w->hdr.integrity.offset != 0 &&
1868 w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1869 ERROR("Didn't expect the integrity table to be before the XML data");
1870 return WIMLIB_ERR_RESOURCE_ORDER;
1873 if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1874 ERROR("Didn't expect the lookup table to be after the XML data");
1875 return WIMLIB_ERR_RESOURCE_ORDER;
1879 if (w->hdr.integrity.offset)
1880 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1882 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1884 if (!w->deletion_occurred && !any_images_modified(w)) {
1885 /* If no images have been modified and no images have been
1886 * deleted, a new lookup table does not need to be written. */
1887 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1888 w->hdr.lookup_table_res_entry.size;
1889 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1890 WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1892 INIT_LIST_HEAD(&stream_list);
1893 ret = wim_find_new_streams(w, old_wim_end, &stream_list);
1897 ret = open_wim_writable(w, w->filename, false,
1898 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1902 ret = lock_wim(w, w->out_fp);
1909 if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1910 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1914 return WIMLIB_ERR_WRITE;
1917 if (!list_empty(&stream_list)) {
1918 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1920 ret = write_stream_list(&stream_list, w->out_fp,
1921 wimlib_get_compression_type(w),
1922 write_flags, num_threads,
1927 DEBUG("No new streams were added");
1930 found_modified_image = false;
1931 for (int i = 0; i < w->hdr.image_count; i++) {
1932 if (!found_modified_image)
1933 found_modified_image = w->image_metadata[i].modified;
1934 if (found_modified_image) {
1935 select_wim_image(w, i + 1);
1936 ret = write_metadata_resource(w);
1941 write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1942 ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1945 close_wim_writable(w);
1946 if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1947 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1948 w->filename, old_wim_end);
1949 /* Return value of truncate() is ignored because this is already
1951 (void)truncate(w->filename, old_wim_end);
1958 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1959 unsigned num_threads,
1960 wimlib_progress_func_t progress_func)
1962 size_t wim_name_len;
1965 DEBUG("Overwriting `%s' via a temporary file", w->filename);
1967 /* Write the WIM to a temporary file in the same directory as the
1969 wim_name_len = strlen(w->filename);
1970 mbchar tmpfile[wim_name_len + 10];
1971 memcpy(tmpfile, w->filename, wim_name_len);
1972 randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1973 tmpfile[wim_name_len + 9] = '\0';
1975 ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1976 write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1977 num_threads, progress_func);
1979 ERROR("Failed to write the WIM file `%s'", tmpfile);
1983 DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1986 /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
1987 * specified to CreateFile(). The WIM was opened with fopen(), which
1988 * didn't provided this flag to CreateFile, so the handle must be closed
1989 * before executing the rename(). */
1990 if (w->fp != NULL) {
1996 /* Rename the new file to the old file .*/
1997 if (rename(tmpfile, w->filename) != 0) {
1998 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1999 tmpfile, w->filename);
2000 ret = WIMLIB_ERR_RENAME;
2004 if (progress_func) {
2005 union wimlib_progress_info progress;
2006 progress.rename.from = tmpfile;
2007 progress.rename.to = w->filename;
2008 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2011 /* Close the original WIM file that was opened for reading. */
2012 if (w->fp != NULL) {
2017 /* Re-open the WIM read-only. */
2018 w->fp = fopen(w->filename, "rb");
2019 if (w->fp == NULL) {
2020 ret = WIMLIB_ERR_REOPEN;
2021 WARNING_WITH_ERRNO("Failed to re-open `%s' read-only",
2028 /* Remove temporary file. */
2029 if (unlink(tmpfile) != 0)
2030 WARNING_WITH_ERRNO("Failed to remove `%s'", tmpfile);
2035 * Writes a WIM file to the original file that it was read from, overwriting it.
2038 wimlib_overwrite(WIMStruct *w, int write_flags,
2039 unsigned num_threads,
2040 wimlib_progress_func_t progress_func)
2042 write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2045 return WIMLIB_ERR_NO_FILENAME;
2047 if (w->hdr.total_parts != 1) {
2048 ERROR("Cannot modify a split WIM");
2049 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2052 if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2053 && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2056 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2058 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2059 WARNING("Falling back to re-building entire WIM");
2063 return overwrite_wim_via_tmpfile(w, write_flags, num_threads,