1eb695d5edca2dbd03a1404e3c7e3b6585f0a0e2
[wimlib] / src / write.c
1 /*
2  * write.c
3  *
4  * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5  * compressed file resources, etc.
6  */
7
8 /*
9  * Copyright (C) 2010 Carl Thijssen
10  * Copyright (C) 2012 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU General Public License as published by the Free
16  * Software Foundation; either version 3 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28 #include "wimlib_internal.h"
29 #include "io.h"
30 #include "dentry.h"
31 #include "lookup_table.h"
32 #include "xml.h"
33 #include "lzx.h"
34 #include "xpress.h"
35 #include <unistd.h>
36
37 #ifdef ENABLE_MULTITHREADED_COMPRESSION
38 #include <semaphore.h>
39 #include <pthread.h>
40 #include <errno.h>
41 #endif
42
43 #ifdef WITH_NTFS_3G
44 #include <time.h>
45 #include <ntfs-3g/attrib.h>
46 #include <ntfs-3g/inode.h>
47 #include <ntfs-3g/dir.h>
48 #endif
49
50
51 #ifdef HAVE_ALLOCA_H
52 #include <alloca.h>
53 #else
54 #include <stdlib.h>
55 #endif
56
57 static int do_fflush(FILE *fp)
58 {
59         int ret = fflush(fp);
60         if (ret != 0) {
61                 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
62                 return WIMLIB_ERR_WRITE;
63         }
64         return 0;
65 }
66
67 static int fflush_and_ftruncate(FILE *fp, off_t size)
68 {
69         int ret;
70
71         ret = do_fflush(fp);
72         if (ret != 0)
73                 return ret;
74         ret = ftruncate(fileno(fp), size);
75         if (ret != 0) {
76                 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
77                                  "%"PRIu64" bytes", size);
78                 return WIMLIB_ERR_WRITE;
79         }
80         return 0;
81 }
82
83 /* Chunk table that's located at the beginning of each compressed resource in
84  * the WIM.  (This is not the on-disk format; the on-disk format just has an
85  * array of offsets.) */
86 struct chunk_table {
87         off_t file_offset;
88         u64 num_chunks;
89         u64 original_resource_size;
90         u64 bytes_per_chunk_entry;
91         u64 table_disk_size;
92         u64 cur_offset;
93         u64 *cur_offset_p;
94         u64 offsets[0];
95 };
96
97 /*
98  * Allocates and initializes a chunk table, and reserves space for it in the
99  * output file.
100  */
101 static int
102 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
103                              FILE *out_fp,
104                              off_t file_offset,
105                              struct chunk_table **chunk_tab_ret)
106 {
107         u64 size = wim_resource_size(lte);
108         u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
109         size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
110         struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
111         int ret;
112
113         if (!chunk_tab) {
114                 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
115                       "resource", size);
116                 ret = WIMLIB_ERR_NOMEM;
117                 goto out;
118         }
119         chunk_tab->file_offset = file_offset;
120         chunk_tab->num_chunks = num_chunks;
121         chunk_tab->original_resource_size = size;
122         chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
123         chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
124                                      (num_chunks - 1);
125         chunk_tab->cur_offset = 0;
126         chunk_tab->cur_offset_p = chunk_tab->offsets;
127
128         if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
129                    chunk_tab->table_disk_size) {
130                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
131                                  "file resource");
132                 ret = WIMLIB_ERR_WRITE;
133                 goto out;
134         }
135
136         ret = 0;
137 out:
138         *chunk_tab_ret = chunk_tab;
139         return ret;
140 }
141
142 /*
143  * Pointer to function to compresses a chunk of a WIM resource.
144  *
145  * @chunk:              Uncompressed data of the chunk.
146  * @chunk_size:         Size of the uncompressed chunk in bytes.
147  * @compressed_chunk:   Pointer to output buffer of size at least
148  *                              (@chunk_size - 1) bytes.
149  * @compressed_chunk_len_ret:   Pointer to an unsigned int into which the size
150  *                                      of the compressed chunk will be
151  *                                      returned.
152  *
153  * Returns zero if compressed succeeded, and nonzero if the chunk could not be
154  * compressed to any smaller than @chunk_size.  This function cannot fail for
155  * any other reasons.
156  */
157 typedef int (*compress_func_t)(const void *, unsigned, void *, unsigned *);
158
159 compress_func_t get_compress_func(int out_ctype)
160 {
161         if (out_ctype == WIM_COMPRESSION_TYPE_LZX)
162                 return lzx_compress;
163         else
164                 return xpress_compress;
165 }
166
167 /*
168  * Writes a chunk of a WIM resource to an output file.
169  *
170  * @chunk:        Uncompressed data of the chunk.
171  * @chunk_size:   Size of the chunk (<= WIM_CHUNK_SIZE)
172  * @out_fp:       FILE * to write tho chunk to.
173  * @out_ctype:    Compression type to use when writing the chunk (ignored if no
174  *                      chunk table provided)
175  * @chunk_tab:    Pointer to chunk table being created.  It is updated with the
176  *                      offset of the chunk we write.
177  *
178  * Returns 0 on success; nonzero on failure.
179  */
180 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
181                                     FILE *out_fp, compress_func_t compress,
182                                     struct chunk_table *chunk_tab)
183 {
184         const u8 *out_chunk;
185         unsigned out_chunk_size;
186         if (chunk_tab) {
187                 u8 *compressed_chunk = alloca(chunk_size);
188                 int ret;
189
190                 ret = compress(chunk, chunk_size, compressed_chunk,
191                                &out_chunk_size);
192                 if (ret == 0) {
193                         out_chunk = compressed_chunk;
194                 } else {
195                         out_chunk = chunk;
196                         out_chunk_size = chunk_size;
197                 }
198                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
199                 chunk_tab->cur_offset += out_chunk_size;
200         } else {
201                 out_chunk = chunk;
202                 out_chunk_size = chunk_size;
203         }
204         if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
205                 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
206                 return WIMLIB_ERR_WRITE;
207         }
208         return 0;
209 }
210
211 /*
212  * Finishes a WIM chunk tale and writes it to the output file at the correct
213  * offset.
214  *
215  * The final size of the full compressed resource is returned in the
216  * @compressed_size_p.
217  */
218 static int
219 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
220                               FILE *out_fp, u64 *compressed_size_p)
221 {
222         size_t bytes_written;
223         if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
224                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
225                                  "WIM file", chunk_tab->file_offset);
226                 return WIMLIB_ERR_WRITE;
227         }
228
229         if (chunk_tab->bytes_per_chunk_entry == 8) {
230                 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
231         } else {
232                 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
233                         ((u32*)chunk_tab->offsets)[i] =
234                                 cpu_to_le32(chunk_tab->offsets[i]);
235         }
236         bytes_written = fwrite((u8*)chunk_tab->offsets +
237                                         chunk_tab->bytes_per_chunk_entry,
238                                1, chunk_tab->table_disk_size, out_fp);
239         if (bytes_written != chunk_tab->table_disk_size) {
240                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
241                                  "file resource");
242                 return WIMLIB_ERR_WRITE;
243         }
244         if (fseeko(out_fp, 0, SEEK_END) != 0) {
245                 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
246                 return WIMLIB_ERR_WRITE;
247         }
248         *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
249         return 0;
250 }
251
252 /* Prepare for multiple reads to a resource by caching a FILE * or NTFS
253  * attribute pointer in the lookup table entry. */
254 static int prepare_resource_for_read(struct lookup_table_entry *lte
255
256                                         #ifdef WITH_NTFS_3G
257                                         , ntfs_inode **ni_ret
258                                         #endif
259                 )
260 {
261         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
262              && !lte->file_on_disk_fp)
263         {
264                 wimlib_assert(lte->file_on_disk);
265                 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
266                 if (!lte->file_on_disk_fp) {
267                         ERROR_WITH_ERRNO("Failed to open the file `%s' for "
268                                          "reading", lte->file_on_disk);
269                         return WIMLIB_ERR_OPEN;
270                 }
271         }
272 #ifdef WITH_NTFS_3G
273         else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
274                   && !lte->attr)
275         {
276                 struct ntfs_location *loc = lte->ntfs_loc;
277                 ntfs_inode *ni;
278                 wimlib_assert(loc);
279                 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
280                 if (!ni) {
281                         ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
282                                          "volume", loc->path_utf8);
283                         return WIMLIB_ERR_NTFS_3G;
284                 }
285                 lte->attr = ntfs_attr_open(ni,
286                                            loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
287                                            (ntfschar*)loc->stream_name_utf16,
288                                            loc->stream_name_utf16_num_chars);
289                 if (!lte->attr) {
290                         ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
291                                          "NTFS volume", loc->path_utf8);
292                         ntfs_inode_close(ni);
293                         return WIMLIB_ERR_NTFS_3G;
294                 }
295                 *ni_ret = ni;
296         }
297 #endif
298         return 0;
299 }
300
301 /* Undo prepare_resource_for_read() by closing the cached FILE * or NTFS
302  * attribute. */
303 static void end_wim_resource_read(struct lookup_table_entry *lte
304                                 #ifdef WITH_NTFS_3G
305                                         , ntfs_inode *ni
306                                 #endif
307                                         )
308 {
309         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
310             && lte->file_on_disk_fp) {
311                 fclose(lte->file_on_disk_fp);
312                 lte->file_on_disk_fp = NULL;
313         }
314 #ifdef WITH_NTFS_3G
315         else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
316                 if (lte->attr) {
317                         ntfs_attr_close(lte->attr);
318                         lte->attr = NULL;
319                 }
320                 if (ni)
321                         ntfs_inode_close(ni);
322         }
323 #endif
324 }
325
326 /*
327  * Writes a WIM resource to a FILE * opened for writing.  The resource may be
328  * written uncompressed or compressed depending on the @out_ctype parameter.
329  *
330  * If by chance the resource compresses to more than the original size (this may
331  * happen with random data or files than are pre-compressed), the resource is
332  * instead written uncompressed (and this is reflected in the @out_res_entry by
333  * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
334  *
335  * @lte:        The lookup table entry for the WIM resource.
336  * @out_fp:     The FILE * to write the resource to.
337  * @out_ctype:  The compression type of the resource to write.  Note: if this is
338  *                      the same as the compression type of the WIM resource we
339  *                      need to read, we simply copy the data (i.e. we do not
340  *                      uncompress it, then compress it again).
341  * @out_res_entry:  If non-NULL, a resource entry that is filled in with the
342  *                  offset, original size, compressed size, and compression flag
343  *                  of the output resource.
344  *
345  * Returns 0 on success; nonzero on failure.
346  */
347 int write_wim_resource(struct lookup_table_entry *lte,
348                        FILE *out_fp, int out_ctype,
349                        struct resource_entry *out_res_entry,
350                        int flags)
351 {
352         u64 bytes_remaining;
353         u64 original_size;
354         u64 old_compressed_size;
355         u64 new_compressed_size;
356         u64 offset;
357         int ret;
358         struct chunk_table *chunk_tab = NULL;
359         bool raw;
360         off_t file_offset;
361         compress_func_t compress;
362 #ifdef WITH_NTFS_3G
363         ntfs_inode *ni = NULL;
364 #endif
365
366         wimlib_assert(lte);
367
368         /* Original size of the resource */
369         original_size = wim_resource_size(lte);
370
371         /* Compressed size of the resource (as it exists now) */
372         old_compressed_size = wim_resource_compressed_size(lte);
373
374         /* Current offset in output file */
375         file_offset = ftello(out_fp);
376         if (file_offset == -1) {
377                 ERROR_WITH_ERRNO("Failed to get offset in output "
378                                  "stream");
379                 return WIMLIB_ERR_WRITE;
380         }
381
382         /* Are the compression types the same?  If so, do a raw copy (copy
383          * without decompressing and recompressing the data). */
384         raw = (wim_resource_compression_type(lte) == out_ctype
385                && out_ctype != WIM_COMPRESSION_TYPE_NONE
386                && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
387
388         if (raw) {
389                 flags |= WIMLIB_RESOURCE_FLAG_RAW;
390                 bytes_remaining = old_compressed_size;
391         } else {
392                 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
393                 bytes_remaining = original_size;
394         }
395
396         /* Empty resource; nothing needs to be done, so just return success. */
397         if (bytes_remaining == 0)
398                 return 0;
399
400         /* Buffer for reading chunks for the resource */
401         u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
402
403         /* If we are writing a compressed resource and not doing a raw copy, we
404          * need to initialize the chunk table */
405         if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
406                 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
407                                                    &chunk_tab);
408                 if (ret != 0)
409                         goto out;
410         }
411
412         /* If the WIM resource is in an external file, open a FILE * to it so we
413          * don't have to open a temporary one in read_wim_resource() for each
414          * chunk. */
415 #ifdef WITH_NTFS_3G
416         ret = prepare_resource_for_read(lte, &ni);
417 #else
418         ret = prepare_resource_for_read(lte);
419 #endif
420         if (ret != 0)
421                 goto out;
422
423         /* If we aren't doing a raw copy, we will compute the SHA1 message
424          * digest of the resource as we read it, and verify it's the same as the
425          * hash given in the lookup table entry once we've finished reading the
426          * resource. */
427         SHA_CTX ctx;
428         if (!raw) {
429                 sha1_init(&ctx);
430                 compress = get_compress_func(out_ctype);
431         }
432         offset = 0;
433
434         /* While there are still bytes remaining in the WIM resource, read a
435          * chunk of the resource, update SHA1, then write that chunk using the
436          * desired compression type. */
437         do {
438                 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
439                 ret = read_wim_resource(lte, buf, to_read, offset, flags);
440                 if (ret != 0)
441                         goto out_fclose;
442                 if (!raw)
443                         sha1_update(&ctx, buf, to_read);
444                 ret = write_wim_resource_chunk(buf, to_read, out_fp,
445                                                compress, chunk_tab);
446                 if (ret != 0)
447                         goto out_fclose;
448                 bytes_remaining -= to_read;
449                 offset += to_read;
450         } while (bytes_remaining);
451
452         /* Raw copy:  The new compressed size is the same as the old compressed
453          * size
454          *
455          * Using WIM_COMPRESSION_TYPE_NONE:  The new compressed size is the
456          * original size
457          *
458          * Using a different compression type:  Call
459          * finish_wim_resource_chunk_tab() and it will provide the new
460          * compressed size.
461          */
462         if (raw) {
463                 new_compressed_size = old_compressed_size;
464         } else {
465                 if (out_ctype == WIM_COMPRESSION_TYPE_NONE)
466                         new_compressed_size = original_size;
467                 else {
468                         ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
469                                                             &new_compressed_size);
470                         if (ret != 0)
471                                 goto out_fclose;
472                 }
473         }
474
475         /* Verify SHA1 message digest of the resource, unless we are doing a raw
476          * write (in which case we never even saw the uncompressed data).  Or,
477          * if the hash we had before is all 0's, just re-set it to be the new
478          * hash. */
479         if (!raw) {
480                 u8 md[SHA1_HASH_SIZE];
481                 sha1_final(md, &ctx);
482                 if (is_zero_hash(lte->hash)) {
483                         copy_hash(lte->hash, md);
484                 } else if (!hashes_equal(md, lte->hash)) {
485                         ERROR("WIM resource has incorrect hash!");
486                         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
487                                 ERROR("We were reading it from `%s'; maybe it changed "
488                                       "while we were reading it.",
489                                       lte->file_on_disk);
490                         }
491                         ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
492                         goto out_fclose;
493                 }
494         }
495
496         if (!raw && new_compressed_size >= original_size &&
497             out_ctype != WIM_COMPRESSION_TYPE_NONE)
498         {
499                 /* Oops!  We compressed the resource to larger than the original
500                  * size.  Write the resource uncompressed instead. */
501                 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
502                         ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
503                                          "of output WIM file", file_offset);
504                         ret = WIMLIB_ERR_WRITE;
505                         goto out_fclose;
506                 }
507                 ret = write_wim_resource(lte, out_fp, WIM_COMPRESSION_TYPE_NONE,
508                                          out_res_entry, flags);
509                 if (ret != 0)
510                         goto out_fclose;
511
512                 ret = fflush_and_ftruncate(out_fp, file_offset + out_res_entry->size);
513                 if (ret != 0)
514                         goto out_fclose;
515         } else {
516                 if (out_res_entry) {
517                         out_res_entry->size          = new_compressed_size;
518                         out_res_entry->original_size = original_size;
519                         out_res_entry->offset        = file_offset;
520                         out_res_entry->flags         = lte->resource_entry.flags
521                                                         & ~WIM_RESHDR_FLAG_COMPRESSED;
522                         if (out_ctype != WIM_COMPRESSION_TYPE_NONE)
523                                 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
524                 }
525         }
526         ret = 0;
527 out_fclose:
528 #ifdef WITH_NTFS_3G
529         end_wim_resource_read(lte, ni);
530 #else
531         end_wim_resource_read(lte);
532 #endif
533 out:
534         FREE(chunk_tab);
535         return ret;
536 }
537
538 #ifdef ENABLE_MULTITHREADED_COMPRESSION
539 struct shared_queue {
540         sem_t filled_slots;
541         sem_t empty_slots;
542         pthread_mutex_t lock;
543         unsigned front;
544         unsigned back;
545         void **array;
546         unsigned size;
547 };
548
549 static int shared_queue_init(struct shared_queue *q, unsigned size)
550 {
551         q->array = CALLOC(sizeof(q->array[0]), size);
552         if (!q->array)
553                 return WIMLIB_ERR_NOMEM;
554
555         sem_init(&q->filled_slots, 0, 0);
556         sem_init(&q->empty_slots, 0, size);
557         pthread_mutex_init(&q->lock, NULL);
558         q->front = 0;
559         q->back = size - 1;
560         q->size = size;
561         return 0;
562 }
563
564 static void shared_queue_destroy(struct shared_queue *q)
565 {
566         sem_destroy(&q->filled_slots);
567         sem_destroy(&q->empty_slots);
568         pthread_mutex_destroy(&q->lock);
569         FREE(q->array);
570 }
571
572 static void shared_queue_put(struct shared_queue *q, void *obj)
573 {
574         sem_wait(&q->empty_slots);
575         pthread_mutex_lock(&q->lock);
576
577         q->back = (q->back + 1) % q->size;
578         q->array[q->back] = obj;
579
580         sem_post(&q->filled_slots);
581         pthread_mutex_unlock(&q->lock);
582 }
583
584 static void *shared_queue_get(struct shared_queue *q)
585 {
586         sem_wait(&q->filled_slots);
587         pthread_mutex_lock(&q->lock);
588
589         void *obj = q->array[q->front];
590         q->array[q->front] = NULL;
591         q->front = (q->front + 1) % q->size;
592
593         sem_post(&q->empty_slots);
594         pthread_mutex_unlock(&q->lock);
595         return obj;
596 }
597
598 struct compressor_thread_params {
599         struct shared_queue *res_to_compress_queue;
600         struct shared_queue *compressed_res_queue;
601         compress_func_t compress;
602 };
603
604 #define MAX_CHUNKS_PER_MSG 2
605
606 struct message {
607         struct lookup_table_entry *lte;
608         u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
609         u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
610         u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
611         unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
612         unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
613         unsigned num_chunks;
614         struct list_head list;
615         bool complete;
616         u64 begin_chunk;
617 };
618
619 static void compress_chunks(struct message *msg, compress_func_t compress)
620 {
621         for (unsigned i = 0; i < msg->num_chunks; i++) {
622                 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
623                 int ret = compress(msg->uncompressed_chunks[i],
624                                    msg->uncompressed_chunk_sizes[i],
625                                    msg->compressed_chunks[i],
626                                    &msg->compressed_chunk_sizes[i]);
627                 if (ret == 0) {
628                         msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
629                 } else {
630                         msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
631                         msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
632                 }
633         }
634 }
635
636 static void *compressor_thread_proc(void *arg)
637 {
638         struct compressor_thread_params *params = arg;
639         struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
640         struct shared_queue *compressed_res_queue = params->compressed_res_queue;
641         compress_func_t compress = params->compress;
642         struct message *msg;
643
644         DEBUG("Compressor thread ready");
645         while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
646                 compress_chunks(msg, compress);
647                 shared_queue_put(compressed_res_queue, msg);
648         }
649         DEBUG("Compressor thread terminating");
650 }
651 #endif
652
653 static void show_stream_write_progress(u64 *cur_size, u64 *next_size,
654                                        u64 total_size, u64 one_percent,
655                                        unsigned *cur_percent,
656                                        const struct lookup_table_entry *cur_lte)
657 {
658         if (*cur_size >= *next_size) {
659                 printf("\r%"PRIu64" MiB of %"PRIu64" MiB "
660                        "(uncompressed) written (%u%% done)",
661                        *cur_size >> 20,
662                        total_size >> 20, *cur_percent);
663                 fflush(stdout);
664                 *next_size += one_percent;
665                 (*cur_percent)++;
666         }
667         *cur_size += wim_resource_size(cur_lte);
668 }
669
670 static void finish_stream_write_progress(u64 total_size)
671 {
672         printf("\r%"PRIu64" MiB of %"PRIu64" MiB "
673                "(uncompressed) written (100%% done)\n",
674                total_size >> 20, total_size >> 20);
675         fflush(stdout);
676 }
677
678 static int write_stream_list_serial(struct list_head *stream_list,
679                                     FILE *out_fp, int out_ctype,
680                                     int write_flags, u64 total_size)
681 {
682         struct lookup_table_entry *lte;
683         int ret;
684
685         u64 one_percent = total_size / 100;
686         u64 cur_size = 0;
687         u64 next_size = 0;
688         unsigned cur_percent = 0;
689         int write_resource_flags = 0;
690
691         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
692                 write_resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
693
694         list_for_each_entry(lte, stream_list, staging_list) {
695                 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
696                         show_stream_write_progress(&cur_size, &next_size,
697                                                    total_size, one_percent,
698                                                    &cur_percent, lte);
699                 }
700                 ret = write_wim_resource(lte, out_fp, out_ctype,
701                                          &lte->output_resource_entry,
702                                          write_resource_flags);
703                 if (ret != 0)
704                         return ret;
705         }
706         if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
707                 finish_stream_write_progress(total_size);
708         return 0;
709 }
710
711 #ifdef ENABLE_MULTITHREADED_COMPRESSION
712 static int write_wim_chunks(struct message *msg, FILE *out_fp,
713                             struct chunk_table *chunk_tab)
714 {
715         for (unsigned i = 0; i < msg->num_chunks; i++) {
716                 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
717
718                 DEBUG2("Write wim chunk %u of %u (csize = %u)",
719                       i, msg->num_chunks, chunk_csize);
720
721                 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
722                     != chunk_csize)
723                 {
724                         ERROR_WITH_ERRNO("Failed to write WIM chunk");
725                         return WIMLIB_ERR_WRITE;
726                 }
727
728                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
729                 chunk_tab->cur_offset += chunk_csize;
730         }
731         return 0;
732 }
733
734 /*
735  * This function is executed by the main thread when the resources are being
736  * compressed in parallel.  The main thread is in change of all reading of the
737  * uncompressed data and writing of the compressed data.  The compressor threads
738  * *only* do compression from/to in-memory buffers.
739  *
740  * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
741  * chunks of compressed data to compress, represented in a `struct message'.
742  * Each message is passed from the main thread to a worker thread through the
743  * res_to_compress_queue, and it is passed back through the
744  * compressed_res_queue.
745  */
746 static int main_writer_thread_proc(struct list_head *stream_list,
747                                    FILE *out_fp,
748                                    int out_ctype,
749                                    struct shared_queue *res_to_compress_queue,
750                                    struct shared_queue *compressed_res_queue,
751                                    size_t queue_size,
752                                    int write_flags,
753                                    u64 total_size)
754 {
755         int ret;
756
757         struct message msgs[queue_size];
758         ZERO_ARRAY(msgs);
759
760         // Initially, all the messages are available to use.
761         LIST_HEAD(available_msgs);
762         for (size_t i = 0; i < ARRAY_LEN(msgs); i++)
763                 list_add(&msgs[i].list, &available_msgs);
764
765         // outstanding_resources is the list of resources that currently have
766         // had chunks sent off for compression.
767         //
768         // The first stream in outstanding_resources is the stream that is
769         // currently being written (cur_lte).
770         //
771         // The last stream in outstanding_resources is the stream that is
772         // currently being read and chunks fed to the compressor threads
773         // (next_lte).
774         //
775         // Depending on the number of threads and the sizes of the resource,
776         // the outstanding streams list may contain streams between cur_lte and
777         // next_lte that have all their chunks compressed or being compressed,
778         // but haven't been written yet.
779         //
780         LIST_HEAD(outstanding_resources);
781         struct list_head *next_resource = stream_list->next;
782         struct lookup_table_entry *next_lte = container_of(next_resource,
783                                                            struct lookup_table_entry,
784                                                            staging_list);
785         next_resource = next_resource->next;
786         u64 next_chunk = 0;
787         u64 next_num_chunks = wim_resource_chunks(next_lte);
788         INIT_LIST_HEAD(&next_lte->msg_list);
789         list_add_tail(&next_lte->staging_list, &outstanding_resources);
790
791         // As in write_wim_resource(), each resource we read is checksummed.
792         SHA_CTX next_sha_ctx;
793         sha1_init(&next_sha_ctx);
794         u8 next_hash[SHA1_HASH_SIZE];
795
796         // Resources that don't need any chunks compressed are added to this
797         // list and written directly by the main thread.
798         LIST_HEAD(my_resources);
799
800         struct lookup_table_entry *cur_lte = next_lte;
801         struct chunk_table *cur_chunk_tab = NULL;
802         struct lookup_table_entry *lte;
803         struct message *msg;
804
805         u64 one_percent = total_size / 100;
806         u64 cur_size = 0;
807         u64 next_size = 0;
808         unsigned cur_percent = 0;
809
810 #ifdef WITH_NTFS_3G
811         ntfs_inode *ni = NULL;
812 #endif
813
814 #ifdef WITH_NTFS_3G
815         ret = prepare_resource_for_read(next_lte, &ni);
816 #else
817         ret = prepare_resource_for_read(next_lte);
818 #endif
819         if (ret != 0)
820                 goto out;
821
822         DEBUG("Initializing buffers for uncompressed "
823               "and compressed data (%zu bytes needed)",
824               queue_size * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
825
826         // Pre-allocate all the buffers that will be needed to do the chunk
827         // compression.
828         for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
829                 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
830                         msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
831                         msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
832                         if (msgs[i].compressed_chunks[j] == NULL ||
833                             msgs[i].uncompressed_chunks[j] == NULL)
834                         {
835                                 ERROR("Could not allocate enough memory for "
836                                       "multi-threaded compression");
837                                 ret = WIMLIB_ERR_NOMEM;
838                                 goto out;
839                         }
840                 }
841         }
842
843         // This loop is executed until all resources have been written, except
844         // possibly a few that have been added to the @my_resources list for
845         // writing later.
846         while (1) {
847                 // Send chunks to the compressor threads until either (a) there
848                 // are no more messages available since they were all sent off,
849                 // or (b) there are no more resources that need to be
850                 // compressed.
851                 while (!list_empty(&available_msgs) && next_lte != NULL) {
852
853                         // Get a message from the available messages
854                         // list
855                         msg = container_of(available_msgs.next,
856                                            struct message,
857                                            list);
858
859                         // ... and delete it from the available messages
860                         // list
861                         list_del(&msg->list);
862
863                         // Initialize the message with the chunks to
864                         // compress.
865                         msg->num_chunks = min(next_num_chunks - next_chunk,
866                                               MAX_CHUNKS_PER_MSG);
867                         msg->lte = next_lte;
868                         msg->complete = false;
869                         msg->begin_chunk = next_chunk;
870
871                         unsigned size = WIM_CHUNK_SIZE;
872                         for (unsigned i = 0; i < msg->num_chunks; i++) {
873
874                                 // Read chunk @next_chunk of the stream into the
875                                 // message so that a compressor thread can
876                                 // compress it.
877
878                                 if (next_chunk == next_num_chunks - 1 &&
879                                      wim_resource_size(next_lte) % WIM_CHUNK_SIZE != 0)
880                                 {
881                                         size = wim_resource_size(next_lte) % WIM_CHUNK_SIZE;
882                                 }
883
884
885                                 DEBUG2("Read resource (size=%u, offset=%zu)",
886                                       size, next_chunk * WIM_CHUNK_SIZE);
887
888                                 msg->uncompressed_chunk_sizes[i] = size;
889
890                                 ret = read_wim_resource(next_lte,
891                                                         msg->uncompressed_chunks[i],
892                                                         size,
893                                                         next_chunk * WIM_CHUNK_SIZE,
894                                                         0);
895                                 if (ret != 0)
896                                         goto out;
897                                 sha1_update(&next_sha_ctx,
898                                             msg->uncompressed_chunks[i], size);
899                                 next_chunk++;
900                         }
901
902                         // Send the compression request
903                         list_add_tail(&msg->list, &next_lte->msg_list);
904                         shared_queue_put(res_to_compress_queue, msg);
905                         DEBUG2("Compression request sent");
906
907                         if (next_chunk != next_num_chunks)
908                                 // More chunks to send for this resource
909                                 continue;
910
911                         // Done sending compression requests for a resource!
912                         // Check the SHA1 message digest.
913                         DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)", next_num_chunks);
914                         sha1_final(next_hash, &next_sha_ctx);
915                         if (!hashes_equal(next_lte->hash, next_hash)) {
916                                 ERROR("WIM resource has incorrect hash!");
917                                 if (next_lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
918                                         ERROR("We were reading it from `%s'; maybe it changed "
919                                               "while we were reading it.",
920                                               next_lte->file_on_disk);
921                                 }
922                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
923                                 goto out;
924                         }
925
926                         // Advance to the next resource.
927                         //
928                         // If the next resource needs no compression, just write
929                         // it with this thread (not now though--- we could be in
930                         // the middle of writing another resource.)  Keep doing
931                         // this until we either get to the end of the resources
932                         // list, or we get to a resource that needs compression.
933
934                         while (1) {
935                                 if (next_resource == stream_list) {
936                                         next_lte = NULL;
937                                         break;
938                                 }
939                         #ifdef WITH_NTFS_3G
940                                 end_wim_resource_read(next_lte, ni);
941                                 ni = NULL;
942                         #else
943                                 end_wim_resource_read(next_lte);
944                         #endif
945
946                                 next_lte = container_of(next_resource,
947                                                         struct lookup_table_entry,
948                                                         staging_list);
949                                 next_resource = next_resource->next;
950                                 if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
951                                       && next_lte->resource_location == RESOURCE_IN_WIM
952                                       && wimlib_get_compression_type(next_lte->wim) == out_ctype)
953                                     || wim_resource_size(next_lte) == 0)
954                                 {
955                                         list_add_tail(&next_lte->staging_list,
956                                                       &my_resources);
957                                 } else {
958                                         list_add_tail(&next_lte->staging_list,
959                                                       &outstanding_resources);
960                                         next_chunk = 0;
961                                         next_num_chunks = wim_resource_chunks(next_lte);
962                                         sha1_init(&next_sha_ctx);
963                                         INIT_LIST_HEAD(&next_lte->msg_list);
964                                 #ifdef WITH_NTFS_3G
965                                         ret = prepare_resource_for_read(next_lte, &ni);
966                                 #else
967                                         ret = prepare_resource_for_read(next_lte);
968                                 #endif
969                                         if (ret != 0)
970                                                 goto out;
971                                         DEBUG2("Updated next_lte");
972                                         break;
973                                 }
974                         }
975                 }
976
977                 // If there are no outstanding resources, there are no more
978                 // resources that need to be written.
979                 if (list_empty(&outstanding_resources)) {
980                         DEBUG("No outstanding resources! Done");
981                         ret = 0;
982                         goto out;
983                 }
984
985                 // Get the next message from the queue and process it.
986                 // The message will contain 1 or more data chunks that have been
987                 // compressed.
988                 DEBUG2("Waiting for message");
989                 msg = shared_queue_get(compressed_res_queue);
990                 msg->complete = true;
991
992                 DEBUG2("Received msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
993
994                 list_for_each_entry(msg, &cur_lte->msg_list, list) {
995                         DEBUG2("complete=%d", msg->complete);
996                 }
997
998                 // Is this the next chunk in the current resource?  If it's not
999                 // (i.e., an earlier chunk in a same or different resource
1000                 // hasn't been compressed yet), do nothing, and keep this
1001                 // message around until all earlier chunks are received.
1002                 //
1003                 // Otherwise, write all the chunks we can.
1004                 while (!list_empty(&cur_lte->msg_list)
1005                         && (msg = container_of(cur_lte->msg_list.next,
1006                                                struct message,
1007                                                list))->complete)
1008                 {
1009                         DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1010                         if (msg->begin_chunk == 0) {
1011                                 DEBUG2("Begin chunk tab");
1012                                 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1013                                         show_stream_write_progress(&cur_size,
1014                                                                    &next_size,
1015                                                                    total_size,
1016                                                                    one_percent,
1017                                                                    &cur_percent,
1018                                                                    cur_lte);
1019                                 }
1020
1021                                 // This is the first set of chunks.  Leave space
1022                                 // for the chunk table in the output file.
1023                                 off_t cur_offset = ftello(out_fp);
1024                                 if (cur_offset == -1) {
1025                                         ret = WIMLIB_ERR_WRITE;
1026                                         goto out;
1027                                 }
1028                                 ret = begin_wim_resource_chunk_tab(cur_lte,
1029                                                                    out_fp,
1030                                                                    cur_offset,
1031                                                                    &cur_chunk_tab);
1032                                 if (ret != 0)
1033                                         goto out;
1034                         }
1035
1036                         // Write the compressed chunks from the message.
1037                         ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1038                         if (ret != 0)
1039                                 goto out;
1040
1041                         list_del(&msg->list);
1042
1043                         // This message is available to use for different chunks
1044                         // now.
1045                         list_add(&msg->list, &available_msgs);
1046
1047                         // Was this the last chunk of the stream?  If so,
1048                         // finish it.
1049                         if (list_empty(&cur_lte->msg_list) &&
1050                             msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1051                         {
1052                                 DEBUG2("Finish wim chunk tab");
1053                                 u64 res_csize;
1054                                 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1055                                                                     out_fp,
1056                                                                     &res_csize);
1057                                 if (ret != 0)
1058                                         goto out;
1059
1060
1061                                 cur_lte->output_resource_entry.size =
1062                                         res_csize;
1063
1064                                 cur_lte->output_resource_entry.original_size =
1065                                         cur_lte->resource_entry.original_size;
1066
1067                                 cur_lte->output_resource_entry.offset =
1068                                         cur_chunk_tab->file_offset;
1069
1070                                 cur_lte->output_resource_entry.flags =
1071                                         cur_lte->resource_entry.flags |
1072                                                 WIM_RESHDR_FLAG_COMPRESSED;
1073
1074                                 FREE(cur_chunk_tab);
1075                                 cur_chunk_tab = NULL;
1076
1077                                 struct list_head *next = cur_lte->staging_list.next;
1078                                 list_del(&cur_lte->staging_list);
1079
1080                                 if (next == &outstanding_resources) {
1081                                         DEBUG("No more outstanding resources");
1082                                         ret = 0;
1083                                         goto out;
1084                                 } else {
1085                                         cur_lte = container_of(cur_lte->staging_list.next,
1086                                                                struct lookup_table_entry,
1087                                                                staging_list);
1088                                 }
1089
1090                                 // Since we just finished writing a stream,
1091                                 // write any streams that have been added to the
1092                                 // my_resources list for direct writing by the
1093                                 // main thread (e.g. resources that don't need
1094                                 // to be compressed because the desired
1095                                 // compression type is the same as the previous
1096                                 // compression type).
1097                                 struct lookup_table_entry *tmp;
1098                                 list_for_each_entry_safe(lte,
1099                                                          tmp,
1100                                                          &my_resources,
1101                                                          staging_list)
1102                                 {
1103                                         if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1104                                                 show_stream_write_progress(&cur_size,
1105                                                                            &next_size,
1106                                                                            total_size,
1107                                                                            one_percent,
1108                                                                            &cur_percent,
1109                                                                            lte);
1110                                         }
1111
1112                                         ret = write_wim_resource(lte,
1113                                                                  out_fp,
1114                                                                  out_ctype,
1115                                                                  &lte->output_resource_entry,
1116                                                                  0);
1117                                         list_del(&lte->staging_list);
1118                                         if (ret != 0)
1119                                                 goto out;
1120                                 }
1121                         }
1122                 }
1123         }
1124
1125 out:
1126 #ifdef WITH_NTFS_3G
1127         end_wim_resource_read(cur_lte, ni);
1128 #else
1129         end_wim_resource_read(cur_lte);
1130 #endif
1131         if (ret == 0) {
1132                 list_for_each_entry(lte, &my_resources, staging_list) {
1133                         if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1134                                 show_stream_write_progress(&cur_size,
1135                                                            &next_size,
1136                                                            total_size,
1137                                                            one_percent,
1138                                                            &cur_percent,
1139                                                            lte);
1140                         }
1141                         ret = write_wim_resource(lte, out_fp,
1142                                                  out_ctype,
1143                                                  &lte->output_resource_entry,
1144                                                  0);
1145                         if (ret != 0)
1146                                 break;
1147                 }
1148                 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
1149                         finish_stream_write_progress(total_size);
1150         } else {
1151                 size_t num_available_msgs = 0;
1152                 struct list_head *cur;
1153
1154                 list_for_each(cur, &available_msgs) {
1155                         num_available_msgs++;
1156                 }
1157
1158                 while (num_available_msgs < ARRAY_LEN(msgs)) {
1159                         shared_queue_get(compressed_res_queue);
1160                         num_available_msgs++;
1161                 }
1162         }
1163
1164         DEBUG("Freeing messages");
1165
1166         for (size_t i = 0; i < ARRAY_LEN(msgs); i++) {
1167                 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1168                         FREE(msgs[i].compressed_chunks[j]);
1169                         FREE(msgs[i].uncompressed_chunks[j]);
1170                 }
1171         }
1172
1173         if (cur_chunk_tab != NULL)
1174                 FREE(cur_chunk_tab);
1175         return ret;
1176 }
1177
1178
1179 static const char *get_data_type(int ctype)
1180 {
1181         switch (ctype) {
1182         case WIM_COMPRESSION_TYPE_NONE:
1183                 return "uncompressed";
1184         case WIM_COMPRESSION_TYPE_LZX:
1185                 return "LZX-compressed";
1186         case WIM_COMPRESSION_TYPE_XPRESS:
1187                 return "XPRESS-compressed";
1188         }
1189 }
1190
1191 static int write_stream_list_parallel(struct list_head *stream_list,
1192                                       FILE *out_fp, int out_ctype,
1193                                       int write_flags, u64 total_size,
1194                                       unsigned num_threads)
1195 {
1196         int ret;
1197         struct shared_queue res_to_compress_queue;
1198         struct shared_queue compressed_res_queue;
1199         pthread_t *compressor_threads = NULL;
1200
1201         if (num_threads == 0) {
1202                 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1203                 if (nthreads < 1) {
1204                         WARNING("Could not determine number of processors! Assuming 1");
1205                         goto out_serial;
1206                 } else {
1207                         num_threads = nthreads;
1208                 }
1209         }
1210
1211         wimlib_assert(stream_list->next != stream_list);
1212
1213         static const double MESSAGES_PER_THREAD = 2.0;
1214         size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1215
1216         DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1217
1218         ret = shared_queue_init(&res_to_compress_queue, queue_size);
1219         if (ret != 0)
1220                 goto out_serial;
1221
1222         ret = shared_queue_init(&compressed_res_queue, queue_size);
1223         if (ret != 0)
1224                 goto out_destroy_res_to_compress_queue;
1225
1226         struct compressor_thread_params params;
1227         params.res_to_compress_queue = &res_to_compress_queue;
1228         params.compressed_res_queue = &compressed_res_queue;
1229         params.compress = get_compress_func(out_ctype);
1230
1231         compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1232
1233         for (unsigned i = 0; i < num_threads; i++) {
1234                 DEBUG("pthread_create thread %u", i);
1235                 ret = pthread_create(&compressor_threads[i], NULL,
1236                                      compressor_thread_proc, &params);
1237                 if (ret != 0) {
1238                         ret = -1;
1239                         ERROR_WITH_ERRNO("Failed to create compressor "
1240                                          "thread %u", i);
1241                         num_threads = i;
1242                         goto out_join;
1243                 }
1244         }
1245
1246         if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1247                 printf("Writing %s data using %u threads...\n",
1248                        get_data_type(out_ctype), num_threads);
1249         }
1250
1251         ret = main_writer_thread_proc(stream_list,
1252                                       out_fp,
1253                                       out_ctype,
1254                                       &res_to_compress_queue,
1255                                       &compressed_res_queue,
1256                                       queue_size,
1257                                       write_flags,
1258                                       total_size);
1259
1260 out_join:
1261         for (unsigned i = 0; i < num_threads; i++)
1262                 shared_queue_put(&res_to_compress_queue, NULL);
1263
1264         for (unsigned i = 0; i < num_threads; i++) {
1265                 if (pthread_join(compressor_threads[i], NULL)) {
1266                         WARNING("Failed to join compressor thread %u: %s",
1267                                 i, strerror(errno));
1268                 }
1269         }
1270         FREE(compressor_threads);
1271         shared_queue_destroy(&compressed_res_queue);
1272 out_destroy_res_to_compress_queue:
1273         shared_queue_destroy(&res_to_compress_queue);
1274         if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1275                 return ret;
1276 out_serial:
1277         WARNING("Falling back to single-threaded compression");
1278         return write_stream_list_serial(stream_list, out_fp,
1279                                         out_ctype, write_flags, total_size);
1280 }
1281 #endif
1282
1283 /*
1284  * Write a list of streams to a WIM (@out_fp) using the compression type
1285  * @out_ctype and up to @num_threads compressor threads.
1286  */
1287 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1288                              int out_ctype, int write_flags,
1289                              unsigned num_threads)
1290 {
1291         struct lookup_table_entry *lte;
1292         size_t num_streams = 0;
1293         u64 total_size = 0;
1294         bool compression_needed = false;
1295
1296         list_for_each_entry(lte, stream_list, staging_list) {
1297                 num_streams++;
1298                 total_size += wim_resource_size(lte);
1299                 if (!compression_needed
1300                     &&
1301                     (out_ctype != WIM_COMPRESSION_TYPE_NONE
1302                        && (lte->resource_location != RESOURCE_IN_WIM
1303                            || wimlib_get_compression_type(lte->wim) != out_ctype
1304                            || (write_flags & WIMLIB_WRITE_FLAG_REBUILD)))
1305                     && wim_resource_size(lte) != 0)
1306                         compression_needed = true;
1307         }
1308
1309         if (num_streams == 0) {
1310                 if (write_flags & WIMLIB_WRITE_FLAG_VERBOSE)
1311                         printf("No streams to write\n");
1312                 return 0;
1313         }
1314
1315         if (write_flags & WIMLIB_WRITE_FLAG_VERBOSE) {
1316                 printf("Preparing to write %zu streams "
1317                        "(%"PRIu64" total bytes uncompressed)\n",
1318                        num_streams, total_size);
1319                 printf("Using compression type %s\n",
1320                        wimlib_get_compression_type_string(out_ctype));
1321         }
1322
1323 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1324         if (compression_needed && total_size >= 1000000 && num_threads != 1) {
1325                 return write_stream_list_parallel(stream_list, out_fp,
1326                                                   out_ctype, write_flags,
1327                                                   total_size, num_threads);
1328         }
1329         else
1330 #endif
1331         {
1332                 if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) {
1333                         const char *reason = "";
1334                         if (!compression_needed)
1335                                 reason = " (no compression needed)";
1336                         printf("Writing %s data using 1 thread%s\n",
1337                                get_data_type(out_ctype), reason);
1338                 }
1339
1340                 return write_stream_list_serial(stream_list, out_fp,
1341                                                 out_ctype, write_flags,
1342                                                 total_size);
1343         }
1344 }
1345
1346
1347 static int dentry_find_streams_to_write(struct dentry *dentry,
1348                                         void *wim)
1349 {
1350         WIMStruct *w = wim;
1351         struct list_head *stream_list = w->private;
1352         struct lookup_table_entry *lte;
1353         for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1354                 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1355                 if (lte && ++lte->out_refcnt == 1)
1356                         list_add_tail(&lte->staging_list, stream_list);
1357         }
1358         return 0;
1359 }
1360
1361 static int find_streams_to_write(WIMStruct *w)
1362 {
1363         return for_dentry_in_tree(wim_root_dentry(w),
1364                                   dentry_find_streams_to_write, w);
1365 }
1366
1367 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1368                              unsigned num_threads)
1369 {
1370
1371         for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1372         LIST_HEAD(stream_list);
1373         w->private = &stream_list;
1374         for_image(w, image, find_streams_to_write);
1375         return write_stream_list(&stream_list, w->out_fp,
1376                                  wimlib_get_compression_type(w), write_flags,
1377                                  num_threads);
1378 }
1379
1380 /*
1381  * Finish writing a WIM file: write the lookup table, xml data, and integrity
1382  * table (optional), then overwrite the WIM header.
1383  *
1384  * write_flags is a bitwise OR of the following:
1385  *
1386  *      (public)  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1387  *              Include an integrity table.
1388  *
1389  *      (public)  WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1390  *              Show progress information when (if) writing the integrity table.
1391  *
1392  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1393  *              Don't write the lookup table.
1394  *
1395  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1396  *              When (if) writing the integrity table, re-use entries from the
1397  *              existing integrity table, if possible.
1398  *
1399  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1400  *              After writing the XML data but before writing the integrity
1401  *              table, write a temporary WIM header and flush the stream so that
1402  *              the WIM is less likely to become corrupted upon abrupt program
1403  *              termination.
1404  *
1405  *      (private) WIMLIB_WRITE_FLAG_FSYNC:
1406  *              fsync() the output file before closing it.
1407  *
1408  */
1409 int finish_write(WIMStruct *w, int image, int write_flags)
1410 {
1411         int ret;
1412         struct wim_header hdr;
1413         FILE *out = w->out_fp;
1414
1415         /* @hdr will be the header for the new WIM.  First copy all the data
1416          * from the header in the WIMStruct; then set all the fields that may
1417          * have changed, including the resource entries, boot index, and image
1418          * count.  */
1419         memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1420
1421         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1422                 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1423                 if (ret != 0)
1424                         goto out;
1425         }
1426
1427         ret = write_xml_data(w->wim_info, image, out,
1428                              (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1429                               wim_info_get_total_bytes(w->wim_info) : 0,
1430                              &hdr.xml_res_entry);
1431         if (ret != 0)
1432                 goto out;
1433
1434         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1435                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1436                         struct wim_header checkpoint_hdr;
1437                         memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1438                         memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1439                         if (fseeko(out, 0, SEEK_SET) != 0) {
1440                                 ret = WIMLIB_ERR_WRITE;
1441                                 goto out;
1442                         }
1443                         ret = write_header(&checkpoint_hdr, out);
1444                         if (ret != 0)
1445                                 goto out;
1446
1447                         if (fflush(out) != 0) {
1448                                 ERROR_WITH_ERRNO("Can't write data to WIM");
1449                                 ret = WIMLIB_ERR_WRITE;
1450                                 goto out;
1451                         }
1452
1453                         if (fseeko(out, 0, SEEK_END) != 0) {
1454                                 ret = WIMLIB_ERR_WRITE;
1455                                 goto out;
1456                         }
1457                 }
1458
1459                 off_t old_lookup_table_end;
1460                 off_t new_lookup_table_end;
1461                 bool show_progress;
1462                 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1463                         old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1464                                                w->hdr.lookup_table_res_entry.size;
1465                 } else {
1466                         old_lookup_table_end = 0;
1467                 }
1468                 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1469                                        hdr.lookup_table_res_entry.size;
1470                 show_progress = ((write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS) != 0);
1471
1472                 ret = write_integrity_table(out,
1473                                             &hdr.integrity,
1474                                             new_lookup_table_end,
1475                                             old_lookup_table_end,
1476                                             show_progress);
1477                 if (ret != 0)
1478                         goto out;
1479         } else {
1480                 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1481         }
1482
1483         /*
1484          * In the WIM header, there is room for the resource entry for a
1485          * metadata resource labeled as the "boot metadata".  This entry should
1486          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
1487          * it should be a copy of the resource entry for the image that is
1488          * marked as bootable.  This is not well documented...
1489          */
1490         if (hdr.boot_idx == 0 || !w->image_metadata
1491                         || (image != WIM_ALL_IMAGES && image != hdr.boot_idx)) {
1492                 memset(&hdr.boot_metadata_res_entry, 0,
1493                        sizeof(struct resource_entry));
1494         } else {
1495                 memcpy(&hdr.boot_metadata_res_entry,
1496                        &w->image_metadata[
1497                           hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1498                        sizeof(struct resource_entry));
1499         }
1500
1501         /* Set image count and boot index correctly for single image writes */
1502         if (image != WIM_ALL_IMAGES) {
1503                 hdr.image_count = 1;
1504                 if (hdr.boot_idx == image)
1505                         hdr.boot_idx = 1;
1506                 else
1507                         hdr.boot_idx = 0;
1508         }
1509
1510         if (fseeko(out, 0, SEEK_SET) != 0) {
1511                 ret = WIMLIB_ERR_WRITE;
1512                 goto out;
1513         }
1514
1515         ret = write_header(&hdr, out);
1516         if (ret != 0)
1517                 goto out;
1518
1519         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1520                 if (fflush(out) != 0
1521                     || fsync(fileno(out)) != 0)
1522                 {
1523                         ERROR_WITH_ERRNO("Error flushing data to WIM file");
1524                         ret = WIMLIB_ERR_WRITE;
1525                 }
1526         }
1527 out:
1528         if (fclose(out) != 0) {
1529                 ERROR_WITH_ERRNO("Failed to close the WIM file");
1530                 if (ret == 0)
1531                         ret = WIMLIB_ERR_WRITE;
1532         }
1533         w->out_fp = NULL;
1534         return ret;
1535 }
1536
1537 static void close_wim_writable(WIMStruct *w)
1538 {
1539         if (w->out_fp) {
1540                 if (fclose(w->out_fp) != 0) {
1541                         WARNING("Failed to close output WIM: %s",
1542                                 strerror(errno));
1543                 }
1544                 w->out_fp = NULL;
1545         }
1546 }
1547
1548 /* Open file stream and write dummy header for WIM. */
1549 int begin_write(WIMStruct *w, const char *path, int write_flags)
1550 {
1551         int ret;
1552         bool need_readable = false;
1553         bool trunc = true;
1554         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
1555                 need_readable = true;
1556
1557         ret = open_wim_writable(w, path, trunc, need_readable);
1558         if (ret != 0)
1559                 return ret;
1560         /* Write dummy header. It will be overwritten later. */
1561         return write_header(&w->hdr, w->out_fp);
1562 }
1563
1564 /* Writes a stand-alone WIM to a file.  */
1565 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1566                            int image, int write_flags, unsigned num_threads)
1567 {
1568         int ret;
1569
1570         if (!w || !path)
1571                 return WIMLIB_ERR_INVALID_PARAM;
1572
1573         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1574
1575         if (image != WIM_ALL_IMAGES &&
1576              (image < 1 || image > w->hdr.image_count))
1577                 return WIMLIB_ERR_INVALID_IMAGE;
1578
1579         if (w->hdr.total_parts != 1) {
1580                 ERROR("Cannot call wimlib_write() on part of a split WIM");
1581                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1582         }
1583
1584         if (image == WIM_ALL_IMAGES)
1585                 DEBUG("Writing all images to `%s'.", path);
1586         else
1587                 DEBUG("Writing image %d to `%s'.", image, path);
1588
1589         ret = begin_write(w, path, write_flags);
1590         if (ret != 0)
1591                 goto out;
1592
1593         ret = write_wim_streams(w, image, write_flags, num_threads);
1594         if (ret != 0)
1595                 goto out;
1596
1597         if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
1598                 printf("Writing image metadata...\n");
1599
1600         ret = for_image(w, image, write_metadata_resource);
1601         if (ret != 0)
1602                 goto out;
1603
1604         ret = finish_write(w, image, write_flags);
1605         if (ret == 0 && (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS))
1606                 printf("Successfully wrote `%s'\n", path);
1607 out:
1608         close_wim_writable(w);
1609         return ret;
1610 }
1611
1612 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1613                                  void *ignore)
1614 {
1615         memcpy(&lte->output_resource_entry, &lte->resource_entry,
1616                sizeof(struct resource_entry));
1617         lte->out_refcnt = 0;
1618         return 0;
1619 }
1620
1621 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1622 {
1623         off_t end_offset = *(u64*)arg;
1624
1625         wimlib_assert(lte->out_refcnt <= lte->refcnt);
1626         if (lte->out_refcnt < lte->refcnt) {
1627                 if (lte->resource_entry.offset + lte->resource_entry.size > end_offset) {
1628                         ERROR("The following resource is after the XML data:");
1629                         print_lookup_table_entry(lte);
1630                         return WIMLIB_ERR_RESOURCE_ORDER;
1631                 }
1632         }
1633         return 0;
1634 }
1635
1636 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1637 {
1638         if (lte->out_refcnt == lte->refcnt)
1639                 list_add(&lte->staging_list, (struct list_head*)arg);
1640         else
1641                 lte->out_refcnt = lte->refcnt;
1642         return 0;
1643 }
1644
1645 /*
1646  * Overwrite a WIM, possibly appending streams to it.
1647  *
1648  * A WIM looks like (or is supposed to look like) the following:
1649  *
1650  *                   Header (212 bytes)
1651  *                   Streams and metadata resources (variable size)
1652  *                   Lookup table (variable size)
1653  *                   XML data (variable size)
1654  *                   Integrity table (optional) (variable size)
1655  *
1656  * If we are not adding any streams or metadata resources, the lookup table is
1657  * unchanged--- so we only need to overwrite the XML data, integrity table, and
1658  * header.  This operation is potentially unsafe if the program is abruptly
1659  * terminated while the XML data or integrity table are being overwritten, but
1660  * before the new header has been written.  To partially alleviate this problem,
1661  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1662  * finish_write() to cause a temporary WIM header to be written after the XML
1663  * data has been written.  This may prevent the WIM from becoming corrupted if
1664  * the program is terminated while the integrity table is being calculated (but
1665  * no guarantees, due to write re-ordering...).
1666  *
1667  * If we are adding new streams or images (metadata resources), the lookup table
1668  * needs to be changed, and those streams need to be written.  In this case, we
1669  * try to perform a safe update of the WIM file by writing the streams *after*
1670  * the end of the previous WIM, then writing the new lookup table, XML data, and
1671  * (optionally) integrity table following the new streams.  This will produce a
1672  * layout like the following:
1673  *
1674  *                   Header (212 bytes)
1675  *                   (OLD) Streams and metadata resources (variable size)
1676  *                   (OLD) Lookup table (variable size)
1677  *                   (OLD) XML data (variable size)
1678  *                   (OLD) Integrity table (optional) (variable size)
1679  *                   (NEW) Streams and metadata resources (variable size)
1680  *                   (NEW) Lookup table (variable size)
1681  *                   (NEW) XML data (variable size)
1682  *                   (NEW) Integrity table (optional) (variable size)
1683  *
1684  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
1685  * the header is overwritten to point to the new lookup table, XML data, and
1686  * integrity table, to produce the following layout:
1687  *
1688  *                   Header (212 bytes)
1689  *                   Streams and metadata resources (variable size)
1690  *                   Nothing (variable size)
1691  *                   More Streams and metadata resources (variable size)
1692  *                   Lookup table (variable size)
1693  *                   XML data (variable size)
1694  *                   Integrity table (optional) (variable size)
1695  *
1696  * This method allows an image to be appended to a large WIM very quickly, and
1697  * is is crash-safe except in the case of write re-ordering, but the
1698  * disadvantage is that a small hole is left in the WIM where the old lookup
1699  * table, xml data, and integrity table were.  (These usually only take up a
1700  * small amount of space compared to the streams, however.
1701  */
1702 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1703                                  unsigned num_threads,
1704                                  int modified_image_idx)
1705 {
1706         int ret;
1707         struct list_head stream_list;
1708         off_t old_wim_end;
1709
1710         DEBUG("Overwriting `%s' in-place", w->filename);
1711
1712         /* Make sure that the integrity table (if present) is after the XML
1713          * data, and that there are no stream resources, metadata resources, or
1714          * lookup tables after the XML data.  Otherwise, these data would be
1715          * overwritten. */
1716         if (w->hdr.integrity.offset != 0 &&
1717             w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1718                 ERROR("Didn't expect the integrity table to be before the XML data");
1719                 return WIMLIB_ERR_RESOURCE_ORDER;
1720         }
1721
1722         if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1723                 ERROR("Didn't expect the lookup table to be after the XML data");
1724                 return WIMLIB_ERR_RESOURCE_ORDER;
1725         }
1726
1727         DEBUG("Identifying newly added streams");
1728         for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1729         INIT_LIST_HEAD(&stream_list);
1730         for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1731                 DEBUG("Identifiying streams in image %d", i + 1);
1732                 wimlib_assert(w->image_metadata[i].modified);
1733                 wimlib_assert(!w->image_metadata[i].has_been_mounted_rw);
1734                 wimlib_assert(w->image_metadata[i].root_dentry != NULL);
1735                 wimlib_assert(w->image_metadata[i].metadata_lte != NULL);
1736                 w->private = &stream_list;
1737                 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1738                                    dentry_find_streams_to_write, w);
1739         }
1740
1741         if (w->hdr.integrity.offset)
1742                 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1743         else
1744                 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1745
1746         ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1747                                      &old_wim_end);
1748         if (ret != 0)
1749                 return ret;
1750
1751         if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1752                 /* If no images have been modified and no images have been
1753                  * deleted, a new lookup table does not need to be written. */
1754                 wimlib_assert(list_empty(&stream_list));
1755                 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1756                               w->hdr.lookup_table_res_entry.size;
1757                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1758                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1759         }
1760
1761         INIT_LIST_HEAD(&stream_list);
1762         for_lookup_table_entry(w->lookup_table, find_new_streams,
1763                                &stream_list);
1764
1765         ret = open_wim_writable(w, w->filename, false,
1766                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1767         if (ret != 0)
1768                 return ret;
1769
1770         if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1771                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1772                 return WIMLIB_ERR_WRITE;
1773         }
1774
1775         if (!list_empty(&stream_list)) {
1776                 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1777                       old_wim_end);
1778                 ret = write_stream_list(&stream_list, w->out_fp,
1779                                         wimlib_get_compression_type(w),
1780                                         write_flags, num_threads);
1781                 if (ret != 0)
1782                         goto out_ftruncate;
1783         } else {
1784                 DEBUG("No new streams were added");
1785         }
1786
1787         for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1788                 select_wim_image(w, i + 1);
1789                 ret = write_metadata_resource(w);
1790                 if (ret != 0)
1791                         goto out_ftruncate;
1792         }
1793         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1794         ret = finish_write(w, WIM_ALL_IMAGES, write_flags);
1795 out_ftruncate:
1796         close_wim_writable(w);
1797         if (ret != 0) {
1798                 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1799                         w->filename, old_wim_end);
1800                 truncate(w->filename, old_wim_end);
1801         }
1802         return ret;
1803 }
1804
1805 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1806                                      unsigned num_threads)
1807 {
1808         size_t wim_name_len;
1809         int ret;
1810
1811         DEBUG("Overwrining `%s' via a temporary file", w->filename);
1812
1813         /* Write the WIM to a temporary file in the same directory as the
1814          * original WIM. */
1815         wim_name_len = strlen(w->filename);
1816         char tmpfile[wim_name_len + 10];
1817         memcpy(tmpfile, w->filename, wim_name_len);
1818         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1819         tmpfile[wim_name_len + 9] = '\0';
1820
1821         ret = wimlib_write(w, tmpfile, WIM_ALL_IMAGES,
1822                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1823                            num_threads);
1824         if (ret != 0) {
1825                 ERROR("Failed to write the WIM file `%s'", tmpfile);
1826                 goto err;
1827         }
1828
1829         /* Close the original WIM file that was opened for reading. */
1830         if (w->fp != NULL) {
1831                 fclose(w->fp);
1832                 w->fp = NULL;
1833         }
1834
1835         DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1836
1837         /* Rename the new file to the old file .*/
1838         if (rename(tmpfile, w->filename) != 0) {
1839                 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1840                                  tmpfile, w->filename);
1841                 ret = WIMLIB_ERR_RENAME;
1842                 goto err;
1843         }
1844
1845         if (write_flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS)
1846                 printf("Successfully renamed `%s' to `%s'\n", tmpfile, w->filename);
1847
1848         /* Re-open the WIM read-only. */
1849         w->fp = fopen(w->filename, "rb");
1850         if (w->fp == NULL) {
1851                 ret = WIMLIB_ERR_REOPEN;
1852                 WARNING("Failed to re-open `%s' read-only: %s",
1853                         w->filename, strerror(errno));
1854         }
1855         return ret;
1856 err:
1857         /* Remove temporary file. */
1858         if (unlink(tmpfile) != 0)
1859                 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1860         return ret;
1861 }
1862
1863 /*
1864  * Writes a WIM file to the original file that it was read from, overwriting it.
1865  */
1866 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1867                                unsigned num_threads)
1868 {
1869         if (!w)
1870                 return WIMLIB_ERR_INVALID_PARAM;
1871
1872         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1873
1874         if (!w->filename)
1875                 return WIMLIB_ERR_NO_FILENAME;
1876
1877         if (w->hdr.total_parts != 1) {
1878                 ERROR("Cannot modify a split WIM");
1879                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1880         }
1881
1882         if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1883             && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1884         {
1885                 int i, modified_image_idx;
1886                 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1887                         ;
1888                 modified_image_idx = i;
1889                 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1890                         !w->image_metadata[i].has_been_mounted_rw; i++)
1891                         ;
1892                 if (i == w->hdr.image_count) {
1893                         return overwrite_wim_inplace(w, write_flags, num_threads,
1894                                                      modified_image_idx);
1895                 }
1896         }
1897         return overwrite_wim_via_tmpfile(w, write_flags, num_threads);
1898 }
1899
1900 /* Deprecated */
1901 WIMLIBAPI int wimlib_overwrite_xml_and_header(WIMStruct *wim, int write_flags)
1902 {
1903         return wimlib_overwrite(wim, write_flags, 1);
1904 }