]> wimlib.net Git - wimlib/blob - src/write.c
Stream writing cleanups
[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 "config.h"
29
30 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
31 /* On BSD, this should be included before "list.h" so that "list.h" can
32  * overwrite the LIST_HEAD macro. */
33 #include <sys/file.h>
34 #endif
35
36 #include "list.h"
37 #include "wimlib_internal.h"
38 #include "io.h"
39 #include "dentry.h"
40 #include "lookup_table.h"
41 #include "xml.h"
42 #include "lzx.h"
43 #include "xpress.h"
44
45 #ifdef ENABLE_MULTITHREADED_COMPRESSION
46 #include <pthread.h>
47 #endif
48
49 #include <unistd.h>
50 #include <errno.h>
51
52 #ifdef WITH_NTFS_3G
53 #include <time.h>
54 #include <ntfs-3g/attrib.h>
55 #include <ntfs-3g/inode.h>
56 #include <ntfs-3g/dir.h>
57 #endif
58
59 #ifdef HAVE_ALLOCA_H
60 #include <alloca.h>
61 #else
62 #include <stdlib.h>
63 #endif
64
65 static int fflush_and_ftruncate(FILE *fp, off_t size)
66 {
67         int ret;
68
69         ret = fflush(fp);
70         if (ret != 0) {
71                 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
72                 return WIMLIB_ERR_WRITE;
73         }
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 == WIMLIB_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 table 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 static int
327 write_uncompressed_resource_and_truncate(struct lookup_table_entry *lte,
328                                          FILE *out_fp,
329                                          off_t file_offset,
330                                          struct resource_entry *out_res_entry)
331 {
332         int ret;
333         if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
334                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
335                                  "output WIM file", file_offset);
336                 return WIMLIB_ERR_WRITE;
337         }
338         ret = write_wim_resource(lte, out_fp, WIMLIB_COMPRESSION_TYPE_NONE,
339                                  out_res_entry, 0);
340         if (ret != 0)
341                 return ret;
342
343         return fflush_and_ftruncate(out_fp,
344                                     file_offset + wim_resource_size(lte));
345 }
346
347 /*
348  * Writes a WIM resource to a FILE * opened for writing.  The resource may be
349  * written uncompressed or compressed depending on the @out_ctype parameter.
350  *
351  * If by chance the resource compresses to more than the original size (this may
352  * happen with random data or files than are pre-compressed), the resource is
353  * instead written uncompressed (and this is reflected in the @out_res_entry by
354  * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
355  *
356  * @lte:        The lookup table entry for the WIM resource.
357  * @out_fp:     The FILE * to write the resource to.
358  * @out_ctype:  The compression type of the resource to write.  Note: if this is
359  *                      the same as the compression type of the WIM resource we
360  *                      need to read, we simply copy the data (i.e. we do not
361  *                      uncompress it, then compress it again).
362  * @out_res_entry:  If non-NULL, a resource entry that is filled in with the
363  *                  offset, original size, compressed size, and compression flag
364  *                  of the output resource.
365  *
366  * Returns 0 on success; nonzero on failure.
367  */
368 int write_wim_resource(struct lookup_table_entry *lte,
369                        FILE *out_fp, int out_ctype,
370                        struct resource_entry *out_res_entry,
371                        int flags)
372 {
373         u64 bytes_remaining;
374         u64 original_size;
375         u64 old_compressed_size;
376         u64 new_compressed_size;
377         u64 offset;
378         int ret;
379         struct chunk_table *chunk_tab = NULL;
380         bool raw;
381         off_t file_offset;
382         compress_func_t compress = NULL;
383 #ifdef WITH_NTFS_3G
384         ntfs_inode *ni = NULL;
385 #endif
386
387         wimlib_assert(lte);
388
389         /* Original size of the resource */
390         original_size = wim_resource_size(lte);
391
392         /* Compressed size of the resource (as it exists now) */
393         old_compressed_size = wim_resource_compressed_size(lte);
394
395         /* Current offset in output file */
396         file_offset = ftello(out_fp);
397         if (file_offset == -1) {
398                 ERROR_WITH_ERRNO("Failed to get offset in output "
399                                  "stream");
400                 return WIMLIB_ERR_WRITE;
401         }
402
403         /* Are the compression types the same?  If so, do a raw copy (copy
404          * without decompressing and recompressing the data). */
405         raw = (wim_resource_compression_type(lte) == out_ctype
406                && out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
407                && !(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS));
408
409         if (raw) {
410                 flags |= WIMLIB_RESOURCE_FLAG_RAW;
411                 bytes_remaining = old_compressed_size;
412         } else {
413                 flags &= ~WIMLIB_RESOURCE_FLAG_RAW;
414                 bytes_remaining = original_size;
415         }
416
417         /* Empty resource; nothing needs to be done, so just return success. */
418         if (bytes_remaining == 0)
419                 return 0;
420
421         /* Buffer for reading chunks for the resource */
422         u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
423
424         /* If we are writing a compressed resource and not doing a raw copy, we
425          * need to initialize the chunk table */
426         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && !raw) {
427                 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
428                                                    &chunk_tab);
429                 if (ret != 0)
430                         goto out;
431         }
432
433         /* If the WIM resource is in an external file, open a FILE * to it so we
434          * don't have to open a temporary one in read_wim_resource() for each
435          * chunk. */
436 #ifdef WITH_NTFS_3G
437         ret = prepare_resource_for_read(lte, &ni);
438 #else
439         ret = prepare_resource_for_read(lte);
440 #endif
441         if (ret != 0)
442                 goto out;
443
444         /* If we aren't doing a raw copy, we will compute the SHA1 message
445          * digest of the resource as we read it, and verify it's the same as the
446          * hash given in the lookup table entry once we've finished reading the
447          * resource. */
448         SHA_CTX ctx;
449         if (!raw) {
450                 sha1_init(&ctx);
451                 compress = get_compress_func(out_ctype);
452         }
453         offset = 0;
454
455         /* While there are still bytes remaining in the WIM resource, read a
456          * chunk of the resource, update SHA1, then write that chunk using the
457          * desired compression type. */
458         do {
459                 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
460                 ret = read_wim_resource(lte, buf, to_read, offset, flags);
461                 if (ret != 0)
462                         goto out_fclose;
463                 if (!raw)
464                         sha1_update(&ctx, buf, to_read);
465                 ret = write_wim_resource_chunk(buf, to_read, out_fp,
466                                                compress, chunk_tab);
467                 if (ret != 0)
468                         goto out_fclose;
469                 bytes_remaining -= to_read;
470                 offset += to_read;
471         } while (bytes_remaining);
472
473         /* Raw copy:  The new compressed size is the same as the old compressed
474          * size
475          *
476          * Using WIMLIB_COMPRESSION_TYPE_NONE:  The new compressed size is the
477          * original size
478          *
479          * Using a different compression type:  Call
480          * finish_wim_resource_chunk_tab() and it will provide the new
481          * compressed size.
482          */
483         if (raw) {
484                 new_compressed_size = old_compressed_size;
485         } else {
486                 if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
487                         new_compressed_size = original_size;
488                 else {
489                         ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
490                                                             &new_compressed_size);
491                         if (ret != 0)
492                                 goto out_fclose;
493                 }
494         }
495
496         /* Verify SHA1 message digest of the resource, unless we are doing a raw
497          * write (in which case we never even saw the uncompressed data).  Or,
498          * if the hash we had before is all 0's, just re-set it to be the new
499          * hash. */
500         if (!raw) {
501                 u8 md[SHA1_HASH_SIZE];
502                 sha1_final(md, &ctx);
503                 if (is_zero_hash(lte->hash)) {
504                         copy_hash(lte->hash, md);
505                 } else if (!hashes_equal(md, lte->hash)) {
506                         ERROR("WIM resource has incorrect hash!");
507                         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
508                                 ERROR("We were reading it from `%s'; maybe it changed "
509                                       "while we were reading it.",
510                                       lte->file_on_disk);
511                         }
512                         ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
513                         goto out_fclose;
514                 }
515         }
516
517         if (!raw && new_compressed_size >= original_size &&
518             out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
519         {
520                 /* Oops!  We compressed the resource to larger than the original
521                  * size.  Write the resource uncompressed instead. */
522                 ret = write_uncompressed_resource_and_truncate(lte,
523                                                                out_fp,
524                                                                file_offset,
525                                                                out_res_entry);
526                 if (ret != 0)
527                         goto out_fclose;
528         } else {
529                 if (out_res_entry) {
530                         out_res_entry->size          = new_compressed_size;
531                         out_res_entry->original_size = original_size;
532                         out_res_entry->offset        = file_offset;
533                         out_res_entry->flags         = lte->resource_entry.flags
534                                                         & ~WIM_RESHDR_FLAG_COMPRESSED;
535                         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE)
536                                 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
537                 }
538         }
539         ret = 0;
540 out_fclose:
541 #ifdef WITH_NTFS_3G
542         end_wim_resource_read(lte, ni);
543 #else
544         end_wim_resource_read(lte);
545 #endif
546 out:
547         FREE(chunk_tab);
548         return ret;
549 }
550
551 #ifdef ENABLE_MULTITHREADED_COMPRESSION
552
553 /* Blocking shared queue (solves the producer-consumer problem) */
554 struct shared_queue {
555         unsigned size;
556         unsigned front;
557         unsigned back;
558         unsigned filled_slots;
559         void **array;
560         pthread_mutex_t lock;
561         pthread_cond_t msg_avail_cond;
562         pthread_cond_t space_avail_cond;
563 };
564
565 static int shared_queue_init(struct shared_queue *q, unsigned size)
566 {
567         wimlib_assert(size != 0);
568         q->array = CALLOC(sizeof(q->array[0]), size);
569         if (!q->array)
570                 return WIMLIB_ERR_NOMEM;
571         q->filled_slots = 0;
572         q->front = 0;
573         q->back = size - 1;
574         q->size = size;
575         pthread_mutex_init(&q->lock, NULL);
576         pthread_cond_init(&q->msg_avail_cond, NULL);
577         pthread_cond_init(&q->space_avail_cond, NULL);
578         return 0;
579 }
580
581 static void shared_queue_destroy(struct shared_queue *q)
582 {
583         FREE(q->array);
584         pthread_mutex_destroy(&q->lock);
585         pthread_cond_destroy(&q->msg_avail_cond);
586         pthread_cond_destroy(&q->space_avail_cond);
587 }
588
589 static void shared_queue_put(struct shared_queue *q, void *obj)
590 {
591         pthread_mutex_lock(&q->lock);
592         while (q->filled_slots == q->size)
593                 pthread_cond_wait(&q->space_avail_cond, &q->lock);
594
595         q->back = (q->back + 1) % q->size;
596         q->array[q->back] = obj;
597         q->filled_slots++;
598
599         pthread_cond_broadcast(&q->msg_avail_cond);
600         pthread_mutex_unlock(&q->lock);
601 }
602
603 static void *shared_queue_get(struct shared_queue *q)
604 {
605         void *obj;
606
607         pthread_mutex_lock(&q->lock);
608         while (q->filled_slots == 0)
609                 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
610
611         obj = q->array[q->front];
612         q->array[q->front] = NULL;
613         q->front = (q->front + 1) % q->size;
614         q->filled_slots--;
615
616         pthread_cond_broadcast(&q->space_avail_cond);
617         pthread_mutex_unlock(&q->lock);
618         return obj;
619 }
620
621 struct compressor_thread_params {
622         struct shared_queue *res_to_compress_queue;
623         struct shared_queue *compressed_res_queue;
624         compress_func_t compress;
625 };
626
627 #define MAX_CHUNKS_PER_MSG 2
628
629 struct message {
630         struct lookup_table_entry *lte;
631         u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
632         u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
633         u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
634         unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
635         unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
636         unsigned num_chunks;
637         struct list_head list;
638         bool complete;
639         u64 begin_chunk;
640 };
641
642 static void compress_chunks(struct message *msg, compress_func_t compress)
643 {
644         for (unsigned i = 0; i < msg->num_chunks; i++) {
645                 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
646                 int ret = compress(msg->uncompressed_chunks[i],
647                                    msg->uncompressed_chunk_sizes[i],
648                                    msg->compressed_chunks[i],
649                                    &msg->compressed_chunk_sizes[i]);
650                 if (ret == 0) {
651                         msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
652                 } else {
653                         msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
654                         msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
655                 }
656         }
657 }
658
659 /* Compressor thread routine.  This is a lot simpler than the main thread
660  * routine: just repeatedly get a group of chunks from the
661  * res_to_compress_queue, compress them, and put them in the
662  * compressed_res_queue.  A NULL pointer indicates that the thread should stop.
663  * */
664 static void *compressor_thread_proc(void *arg)
665 {
666         struct compressor_thread_params *params = arg;
667         struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
668         struct shared_queue *compressed_res_queue = params->compressed_res_queue;
669         compress_func_t compress = params->compress;
670         struct message *msg;
671
672         DEBUG("Compressor thread ready");
673         while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
674                 compress_chunks(msg, compress);
675                 shared_queue_put(compressed_res_queue, msg);
676         }
677         DEBUG("Compressor thread terminating");
678         return NULL;
679 }
680 #endif
681
682 static int do_write_stream_list(struct list_head *my_resources,
683                                 FILE *out_fp,
684                                 int out_ctype,
685                                 wimlib_progress_func_t progress_func,
686                                 union wimlib_progress_info *progress,
687                                 int write_resource_flags)
688 {
689         int ret;
690         struct lookup_table_entry *lte, *tmp;
691
692         list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
693                 ret = write_wim_resource(lte,
694                                          out_fp,
695                                          out_ctype,
696                                          &lte->output_resource_entry,
697                                          write_resource_flags);
698                 if (ret != 0)
699                         return ret;
700                 list_del(&lte->staging_list);
701                 progress->write_streams.completed_bytes +=
702                         wim_resource_size(lte);
703                 progress->write_streams.completed_streams++;
704                 if (progress_func) {
705                         progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
706                                       progress);
707                 }
708         }
709         return 0;
710 }
711
712 static int write_stream_list_serial(struct list_head *stream_list,
713                                     FILE *out_fp,
714                                     int out_ctype,
715                                     int write_flags,
716                                     wimlib_progress_func_t progress_func,
717                                     union wimlib_progress_info *progress)
718 {
719         int write_resource_flags;
720
721         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
722                 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
723         else
724                 write_resource_flags = 0;
725         progress->write_streams.num_threads = 1;
726         if (progress_func)
727                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
728         return do_write_stream_list(stream_list, out_fp,
729                                     out_ctype, progress_func,
730                                     progress, write_resource_flags);
731 }
732
733 #ifdef ENABLE_MULTITHREADED_COMPRESSION
734 static int write_wim_chunks(struct message *msg, FILE *out_fp,
735                             struct chunk_table *chunk_tab)
736 {
737         for (unsigned i = 0; i < msg->num_chunks; i++) {
738                 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
739
740                 DEBUG2("Write wim chunk %u of %u (csize = %u)",
741                       i, msg->num_chunks, chunk_csize);
742
743                 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
744                     != chunk_csize)
745                 {
746                         ERROR_WITH_ERRNO("Failed to write WIM chunk");
747                         return WIMLIB_ERR_WRITE;
748                 }
749
750                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
751                 chunk_tab->cur_offset += chunk_csize;
752         }
753         return 0;
754 }
755
756 /*
757  * This function is executed by the main thread when the resources are being
758  * compressed in parallel.  The main thread is in change of all reading of the
759  * uncompressed data and writing of the compressed data.  The compressor threads
760  * *only* do compression from/to in-memory buffers.
761  *
762  * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
763  * chunks of compressed data to compress, represented in a `struct message'.
764  * Each message is passed from the main thread to a worker thread through the
765  * res_to_compress_queue, and it is passed back through the
766  * compressed_res_queue.
767  */
768 static int main_writer_thread_proc(struct list_head *stream_list,
769                                    FILE *out_fp,
770                                    int out_ctype,
771                                    struct shared_queue *res_to_compress_queue,
772                                    struct shared_queue *compressed_res_queue,
773                                    size_t num_messages,
774                                    int write_flags,
775                                    wimlib_progress_func_t progress_func,
776                                    union wimlib_progress_info *progress)
777 {
778         int ret;
779         struct chunk_table *cur_chunk_tab = NULL;
780         struct message *msgs = CALLOC(num_messages, sizeof(struct message));
781         struct lookup_table_entry *next_lte = NULL;
782
783         // Initially, all the messages are available to use.
784         LIST_HEAD(available_msgs);
785
786         if (!msgs) {
787                 ret = WIMLIB_ERR_NOMEM;
788                 goto out;
789         }
790
791         for (size_t i = 0; i < num_messages; i++)
792                 list_add(&msgs[i].list, &available_msgs);
793
794         // outstanding_resources is the list of resources that currently have
795         // had chunks sent off for compression.
796         //
797         // The first stream in outstanding_resources is the stream that is
798         // currently being written (cur_lte).
799         //
800         // The last stream in outstanding_resources is the stream that is
801         // currently being read and chunks fed to the compressor threads
802         // (next_lte).
803         //
804         // Depending on the number of threads and the sizes of the resource,
805         // the outstanding streams list may contain streams between cur_lte and
806         // next_lte that have all their chunks compressed or being compressed,
807         // but haven't been written yet.
808         //
809         LIST_HEAD(outstanding_resources);
810         struct list_head *next_resource = stream_list->next;
811         u64 next_chunk = 0;
812         u64 next_num_chunks = 0;
813
814         // As in write_wim_resource(), each resource we read is checksummed.
815         SHA_CTX next_sha_ctx;
816         u8 next_hash[SHA1_HASH_SIZE];
817
818         // Resources that don't need any chunks compressed are added to this
819         // list and written directly by the main thread.
820         LIST_HEAD(my_resources);
821
822         struct lookup_table_entry *cur_lte = NULL;
823         struct message *msg;
824
825 #ifdef WITH_NTFS_3G
826         ntfs_inode *ni = NULL;
827 #endif
828
829         DEBUG("Initializing buffers for uncompressed "
830               "and compressed data (%zu bytes needed)",
831               num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
832
833         // Pre-allocate all the buffers that will be needed to do the chunk
834         // compression.
835         for (size_t i = 0; i < num_messages; i++) {
836                 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
837                         msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
838
839                         // The extra 8 bytes is because longest_match() in lz.c
840                         // may read a little bit off the end of the uncompressed
841                         // data.  It doesn't need to be initialized--- we really
842                         // just need to avoid accessing an unmapped page.
843                         msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
844                         if (msgs[i].compressed_chunks[j] == NULL ||
845                             msgs[i].uncompressed_chunks[j] == NULL)
846                         {
847                                 ret = WIMLIB_ERR_NOMEM;
848                                 goto out;
849                         }
850                 }
851         }
852
853         // This loop is executed until all resources have been written, except
854         // possibly a few that have been added to the @my_resources list for
855         // writing later.
856         while (1) {
857                 // Send chunks to the compressor threads until either (a) there
858                 // are no more messages available since they were all sent off,
859                 // or (b) there are no more resources that need to be
860                 // compressed.
861                 while (!list_empty(&available_msgs)) {
862                         if (next_chunk == next_num_chunks) {
863                                 // If next_chunk == next_num_chunks, there are
864                                 // no more chunks to write in the current
865                                 // stream.  So, check the SHA1 message digest of
866                                 // the stream that was just finished (unless
867                                 // next_lte == NULL, which is the case the very
868                                 // first time this loop is entered, and also
869                                 // near the very end of the compression when
870                                 // there are no more streams.)  Then, advance to
871                                 // the next stream (if there is one).
872                                 if (next_lte != NULL) {
873                                 #ifdef WITH_NTFS_3G
874                                         end_wim_resource_read(next_lte, ni);
875                                         ni = NULL;
876                                 #else
877                                         end_wim_resource_read(next_lte);
878                                 #endif
879                                         DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
880                                                next_num_chunks);
881                                         sha1_final(next_hash, &next_sha_ctx);
882                                         if (!hashes_equal(next_lte->hash, next_hash)) {
883                                                 ERROR("WIM resource has incorrect hash!");
884                                                 if (next_lte->resource_location ==
885                                                     RESOURCE_IN_FILE_ON_DISK)
886                                                 {
887                                                         ERROR("We were reading it from `%s'; "
888                                                               "maybe it changed while we were "
889                                                               "reading it.",
890                                                               next_lte->file_on_disk);
891                                                 }
892                                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
893                                                 goto out;
894                                         }
895                                 }
896
897                                 // Advance to the next resource.
898                                 //
899                                 // If the next resource needs no compression, just write
900                                 // it with this thread (not now though--- we could be in
901                                 // the middle of writing another resource.)  Keep doing
902                                 // this until we either get to the end of the resources
903                                 // list, or we get to a resource that needs compression.
904                                 while (1) {
905                                         if (next_resource == stream_list) {
906                                                 // No more resources to send for
907                                                 // compression
908                                                 next_lte = NULL;
909                                                 break;
910                                         }
911                                         next_lte = container_of(next_resource,
912                                                                 struct lookup_table_entry,
913                                                                 staging_list);
914                                         next_resource = next_resource->next;
915                                         if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
916                                                && wim_resource_compression_type(next_lte) == out_ctype)
917                                             || wim_resource_size(next_lte) == 0)
918                                         {
919                                                 list_add_tail(&next_lte->staging_list,
920                                                               &my_resources);
921                                         } else {
922                                                 list_add_tail(&next_lte->staging_list,
923                                                               &outstanding_resources);
924                                                 next_chunk = 0;
925                                                 next_num_chunks = wim_resource_chunks(next_lte);
926                                                 sha1_init(&next_sha_ctx);
927                                                 INIT_LIST_HEAD(&next_lte->msg_list);
928                                         #ifdef WITH_NTFS_3G
929                                                 ret = prepare_resource_for_read(next_lte, &ni);
930                                         #else
931                                                 ret = prepare_resource_for_read(next_lte);
932                                         #endif
933
934                                                 if (ret != 0)
935                                                         goto out;
936                                                 if (cur_lte == NULL) {
937                                                         // Set cur_lte for the
938                                                         // first time
939                                                         cur_lte = next_lte;
940                                                 }
941                                                 break;
942                                         }
943                                 }
944                         }
945
946                         if (next_lte == NULL) {
947                                 // No more resources to send for compression
948                                 break;
949                         }
950
951                         // Get a message from the available messages
952                         // list
953                         msg = container_of(available_msgs.next,
954                                            struct message,
955                                            list);
956
957                         // ... and delete it from the available messages
958                         // list
959                         list_del(&msg->list);
960
961                         // Initialize the message with the chunks to
962                         // compress.
963                         msg->num_chunks = min(next_num_chunks - next_chunk,
964                                               MAX_CHUNKS_PER_MSG);
965                         msg->lte = next_lte;
966                         msg->complete = false;
967                         msg->begin_chunk = next_chunk;
968
969                         unsigned size = WIM_CHUNK_SIZE;
970                         for (unsigned i = 0; i < msg->num_chunks; i++) {
971
972                                 // Read chunk @next_chunk of the stream into the
973                                 // message so that a compressor thread can
974                                 // compress it.
975
976                                 if (next_chunk == next_num_chunks - 1) {
977                                         size = MODULO_NONZERO(wim_resource_size(next_lte),
978                                                               WIM_CHUNK_SIZE);
979                                 }
980
981                                 DEBUG2("Read resource (size=%u, offset=%zu)",
982                                       size, next_chunk * WIM_CHUNK_SIZE);
983
984                                 msg->uncompressed_chunk_sizes[i] = size;
985
986                                 ret = read_wim_resource(next_lte,
987                                                         msg->uncompressed_chunks[i],
988                                                         size,
989                                                         next_chunk * WIM_CHUNK_SIZE,
990                                                         0);
991                                 if (ret != 0)
992                                         goto out;
993                                 sha1_update(&next_sha_ctx,
994                                             msg->uncompressed_chunks[i], size);
995                                 next_chunk++;
996                         }
997
998                         // Send the compression request
999                         list_add_tail(&msg->list, &next_lte->msg_list);
1000                         shared_queue_put(res_to_compress_queue, msg);
1001                         DEBUG2("Compression request sent");
1002                 }
1003
1004                 // If there are no outstanding resources, there are no more
1005                 // resources that need to be written.
1006                 if (list_empty(&outstanding_resources)) {
1007                         ret = 0;
1008                         goto out;
1009                 }
1010
1011                 // Get the next message from the queue and process it.
1012                 // The message will contain 1 or more data chunks that have been
1013                 // compressed.
1014                 msg = shared_queue_get(compressed_res_queue);
1015                 msg->complete = true;
1016
1017                 // Is this the next chunk in the current resource?  If it's not
1018                 // (i.e., an earlier chunk in a same or different resource
1019                 // hasn't been compressed yet), do nothing, and keep this
1020                 // message around until all earlier chunks are received.
1021                 //
1022                 // Otherwise, write all the chunks we can.
1023                 while (cur_lte != NULL &&
1024                        (msg = container_of(cur_lte->msg_list.next,
1025                                            struct message,
1026                                            list))->complete)
1027                 {
1028                         DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1029                         if (msg->begin_chunk == 0) {
1030                                 DEBUG2("Begin chunk tab");
1031
1032                                 // This is the first set of chunks.  Leave space
1033                                 // for the chunk table in the output file.
1034                                 off_t cur_offset = ftello(out_fp);
1035                                 if (cur_offset == -1) {
1036                                         ret = WIMLIB_ERR_WRITE;
1037                                         goto out;
1038                                 }
1039                                 ret = begin_wim_resource_chunk_tab(cur_lte,
1040                                                                    out_fp,
1041                                                                    cur_offset,
1042                                                                    &cur_chunk_tab);
1043                                 if (ret != 0)
1044                                         goto out;
1045                         }
1046
1047                         // Write the compressed chunks from the message.
1048                         ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1049                         if (ret != 0)
1050                                 goto out;
1051
1052                         list_del(&msg->list);
1053
1054                         // This message is available to use for different chunks
1055                         // now.
1056                         list_add(&msg->list, &available_msgs);
1057
1058                         // Was this the last chunk of the stream?  If so, finish
1059                         // it.
1060                         if (list_empty(&cur_lte->msg_list) &&
1061                             msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1062                         {
1063                                 DEBUG2("Finish wim chunk tab");
1064                                 u64 res_csize;
1065                                 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1066                                                                     out_fp,
1067                                                                     &res_csize);
1068                                 if (ret != 0)
1069                                         goto out;
1070
1071                                 if (res_csize >= wim_resource_size(cur_lte)) {
1072                                         /* Oops!  We compressed the resource to
1073                                          * larger than the original size.  Write
1074                                          * the resource uncompressed instead. */
1075                                         ret = write_uncompressed_resource_and_truncate(
1076                                                          cur_lte,
1077                                                          out_fp,
1078                                                          cur_chunk_tab->file_offset,
1079                                                          &cur_lte->output_resource_entry);
1080                                         if (ret != 0)
1081                                                 goto out;
1082                                 } else {
1083                                         cur_lte->output_resource_entry.size =
1084                                                 res_csize;
1085
1086                                         cur_lte->output_resource_entry.original_size =
1087                                                 cur_lte->resource_entry.original_size;
1088
1089                                         cur_lte->output_resource_entry.offset =
1090                                                 cur_chunk_tab->file_offset;
1091
1092                                         cur_lte->output_resource_entry.flags =
1093                                                 cur_lte->resource_entry.flags |
1094                                                         WIM_RESHDR_FLAG_COMPRESSED;
1095                                 }
1096
1097                                 progress->write_streams.completed_bytes +=
1098                                                 wim_resource_size(cur_lte);
1099                                 progress->write_streams.completed_streams++;
1100
1101                                 if (progress_func) {
1102                                         progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1103                                                       progress);
1104                                 }
1105
1106                                 FREE(cur_chunk_tab);
1107                                 cur_chunk_tab = NULL;
1108
1109                                 struct list_head *next = cur_lte->staging_list.next;
1110                                 list_del(&cur_lte->staging_list);
1111
1112                                 if (next == &outstanding_resources)
1113                                         cur_lte = NULL;
1114                                 else
1115                                         cur_lte = container_of(cur_lte->staging_list.next,
1116                                                                struct lookup_table_entry,
1117                                                                staging_list);
1118
1119                                 // Since we just finished writing a stream,
1120                                 // write any streams that have been added to the
1121                                 // my_resources list for direct writing by the
1122                                 // main thread (e.g. resources that don't need
1123                                 // to be compressed because the desired
1124                                 // compression type is the same as the previous
1125                                 // compression type).
1126                                 ret = do_write_stream_list(&my_resources,
1127                                                            out_fp,
1128                                                            out_ctype,
1129                                                            progress_func,
1130                                                            progress,
1131                                                            0);
1132                                 if (ret != 0)
1133                                         goto out;
1134                         }
1135                 }
1136         }
1137
1138 out:
1139         if (ret == WIMLIB_ERR_NOMEM) {
1140                 ERROR("Could not allocate enough memory for "
1141                       "multi-threaded compression");
1142         }
1143
1144         if (next_lte) {
1145 #ifdef WITH_NTFS_3G
1146                 end_wim_resource_read(next_lte, ni);
1147 #else
1148                 end_wim_resource_read(next_lte);
1149 #endif
1150         }
1151
1152         if (ret == 0) {
1153                 ret = do_write_stream_list(&my_resources, out_fp,
1154                                            out_ctype, progress_func,
1155                                            progress, 0);
1156         } else {
1157                 if (msgs) {
1158                         size_t num_available_msgs = 0;
1159                         struct list_head *cur;
1160
1161                         list_for_each(cur, &available_msgs) {
1162                                 num_available_msgs++;
1163                         }
1164
1165                         while (num_available_msgs < num_messages) {
1166                                 shared_queue_get(compressed_res_queue);
1167                                 num_available_msgs++;
1168                         }
1169                 }
1170         }
1171
1172         if (msgs) {
1173                 for (size_t i = 0; i < num_messages; i++) {
1174                         for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1175                                 FREE(msgs[i].compressed_chunks[j]);
1176                                 FREE(msgs[i].uncompressed_chunks[j]);
1177                         }
1178                 }
1179                 FREE(msgs);
1180         }
1181
1182         FREE(cur_chunk_tab);
1183         return ret;
1184 }
1185
1186
1187 static int write_stream_list_parallel(struct list_head *stream_list,
1188                                       FILE *out_fp,
1189                                       int out_ctype,
1190                                       int write_flags,
1191                                       unsigned num_threads,
1192                                       wimlib_progress_func_t progress_func,
1193                                       union wimlib_progress_info *progress)
1194 {
1195         int ret;
1196         struct shared_queue res_to_compress_queue;
1197         struct shared_queue compressed_res_queue;
1198         pthread_t *compressor_threads = NULL;
1199
1200         if (num_threads == 0) {
1201                 long nthreads = sysconf(_SC_NPROCESSORS_ONLN);
1202                 if (nthreads < 1) {
1203                         WARNING("Could not determine number of processors! Assuming 1");
1204                         goto out_serial;
1205                 } else {
1206                         num_threads = nthreads;
1207                 }
1208         }
1209
1210         progress->write_streams.num_threads = num_threads;
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         if (!compressor_threads) {
1233                 ret = WIMLIB_ERR_NOMEM;
1234                 goto out_destroy_compressed_res_queue;
1235         }
1236
1237         for (unsigned i = 0; i < num_threads; i++) {
1238                 DEBUG("pthread_create thread %u", i);
1239                 ret = pthread_create(&compressor_threads[i], NULL,
1240                                      compressor_thread_proc, &params);
1241                 if (ret != 0) {
1242                         ret = -1;
1243                         ERROR_WITH_ERRNO("Failed to create compressor "
1244                                          "thread %u", i);
1245                         num_threads = i;
1246                         goto out_join;
1247                 }
1248         }
1249
1250         if (progress_func)
1251                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1252
1253         ret = main_writer_thread_proc(stream_list,
1254                                       out_fp,
1255                                       out_ctype,
1256                                       &res_to_compress_queue,
1257                                       &compressed_res_queue,
1258                                       queue_size,
1259                                       write_flags,
1260                                       progress_func,
1261                                       progress);
1262 out_join:
1263         for (unsigned i = 0; i < num_threads; i++)
1264                 shared_queue_put(&res_to_compress_queue, NULL);
1265
1266         for (unsigned i = 0; i < num_threads; i++) {
1267                 if (pthread_join(compressor_threads[i], NULL)) {
1268                         WARNING("Failed to join compressor thread %u: %s",
1269                                 i, strerror(errno));
1270                 }
1271         }
1272         FREE(compressor_threads);
1273 out_destroy_compressed_res_queue:
1274         shared_queue_destroy(&compressed_res_queue);
1275 out_destroy_res_to_compress_queue:
1276         shared_queue_destroy(&res_to_compress_queue);
1277         if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1278                 return ret;
1279 out_serial:
1280         WARNING("Falling back to single-threaded compression");
1281         return write_stream_list_serial(stream_list,
1282                                         out_fp,
1283                                         out_ctype,
1284                                         write_flags,
1285                                         progress_func,
1286                                         progress);
1287
1288 }
1289 #endif
1290
1291 /*
1292  * Write a list of streams to a WIM (@out_fp) using the compression type
1293  * @out_ctype and up to @num_threads compressor threads.
1294  */
1295 static int write_stream_list(struct list_head *stream_list, FILE *out_fp,
1296                              int out_ctype, int write_flags,
1297                              unsigned num_threads,
1298                              wimlib_progress_func_t progress_func)
1299 {
1300         struct lookup_table_entry *lte;
1301         size_t num_streams = 0;
1302         u64 total_bytes = 0;
1303         u64 total_compression_bytes = 0;
1304         union wimlib_progress_info progress;
1305
1306         list_for_each_entry(lte, stream_list, staging_list) {
1307                 num_streams++;
1308                 total_bytes += wim_resource_size(lte);
1309                 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1310                        && (wim_resource_compression_type(lte) != out_ctype ||
1311                            (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1312                 {
1313                         total_compression_bytes += wim_resource_size(lte);
1314                 }
1315         }
1316         progress.write_streams.total_bytes       = total_bytes;
1317         progress.write_streams.total_streams     = num_streams;
1318         progress.write_streams.completed_bytes   = 0;
1319         progress.write_streams.completed_streams = 0;
1320         progress.write_streams.num_threads       = num_threads;
1321         progress.write_streams.compression_type  = out_ctype;
1322
1323 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1324         if (total_compression_bytes >= 1000000 && num_threads != 1)
1325                 return write_stream_list_parallel(stream_list,
1326                                                   out_fp,
1327                                                   out_ctype,
1328                                                   write_flags,
1329                                                   num_threads,
1330                                                   progress_func,
1331                                                   &progress);
1332         else
1333 #endif
1334                 return write_stream_list_serial(stream_list,
1335                                                 out_fp,
1336                                                 out_ctype,
1337                                                 write_flags,
1338                                                 progress_func,
1339                                                 &progress);
1340 }
1341
1342
1343 static int dentry_find_streams_to_write(struct dentry *dentry,
1344                                         void *wim)
1345 {
1346         WIMStruct *w = wim;
1347         struct list_head *stream_list = w->private;
1348         struct lookup_table_entry *lte;
1349         for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1350                 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1351                 if (lte && ++lte->out_refcnt == 1)
1352                         list_add_tail(&lte->staging_list, stream_list);
1353         }
1354         return 0;
1355 }
1356
1357 static int find_streams_to_write(WIMStruct *w)
1358 {
1359         return for_dentry_in_tree(wim_root_dentry(w),
1360                                   dentry_find_streams_to_write, w);
1361 }
1362
1363 static int write_wim_streams(WIMStruct *w, int image, int write_flags,
1364                              unsigned num_threads,
1365                              wimlib_progress_func_t progress_func)
1366 {
1367
1368         for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1369         LIST_HEAD(stream_list);
1370         w->private = &stream_list;
1371         for_image(w, image, find_streams_to_write);
1372         return write_stream_list(&stream_list, w->out_fp,
1373                                  wimlib_get_compression_type(w), write_flags,
1374                                  num_threads, progress_func);
1375 }
1376
1377 /*
1378  * Finish writing a WIM file: write the lookup table, xml data, and integrity
1379  * table (optional), then overwrite the WIM header.
1380  *
1381  * write_flags is a bitwise OR of the following:
1382  *
1383  *      (public)  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1384  *              Include an integrity table.
1385  *
1386  *      (public)  WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1387  *              Show progress information when (if) writing the integrity table.
1388  *
1389  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1390  *              Don't write the lookup table.
1391  *
1392  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1393  *              When (if) writing the integrity table, re-use entries from the
1394  *              existing integrity table, if possible.
1395  *
1396  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1397  *              After writing the XML data but before writing the integrity
1398  *              table, write a temporary WIM header and flush the stream so that
1399  *              the WIM is less likely to become corrupted upon abrupt program
1400  *              termination.
1401  *
1402  *      (private) WIMLIB_WRITE_FLAG_FSYNC:
1403  *              fsync() the output file before closing it.
1404  *
1405  */
1406 int finish_write(WIMStruct *w, int image, int write_flags,
1407                  wimlib_progress_func_t progress_func)
1408 {
1409         int ret;
1410         struct wim_header hdr;
1411         FILE *out = w->out_fp;
1412
1413         /* @hdr will be the header for the new WIM.  First copy all the data
1414          * from the header in the WIMStruct; then set all the fields that may
1415          * have changed, including the resource entries, boot index, and image
1416          * count.  */
1417         memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1418
1419         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1420                 ret = write_lookup_table(w->lookup_table, out, &hdr.lookup_table_res_entry);
1421                 if (ret != 0)
1422                         goto out;
1423         }
1424
1425         ret = write_xml_data(w->wim_info, image, out,
1426                              (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1427                               wim_info_get_total_bytes(w->wim_info) : 0,
1428                              &hdr.xml_res_entry);
1429         if (ret != 0)
1430                 goto out;
1431
1432         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1433                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1434                         struct wim_header checkpoint_hdr;
1435                         memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1436                         memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1437                         if (fseeko(out, 0, SEEK_SET) != 0) {
1438                                 ERROR_WITH_ERRNO("Failed to seek to beginning "
1439                                                  "of WIM being written");
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                                 ERROR_WITH_ERRNO("Failed to seek to end "
1455                                                  "of WIM being written");
1456                                 ret = WIMLIB_ERR_WRITE;
1457                                 goto out;
1458                         }
1459                 }
1460
1461                 off_t old_lookup_table_end;
1462                 off_t new_lookup_table_end;
1463                 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1464                         old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1465                                                w->hdr.lookup_table_res_entry.size;
1466                 } else {
1467                         old_lookup_table_end = 0;
1468                 }
1469                 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1470                                        hdr.lookup_table_res_entry.size;
1471
1472                 ret = write_integrity_table(out,
1473                                             &hdr.integrity,
1474                                             new_lookup_table_end,
1475                                             old_lookup_table_end,
1476                                             progress_func);
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
1491         /* Set image count and boot index correctly for single image writes */
1492         if (image != WIMLIB_ALL_IMAGES) {
1493                 hdr.image_count = 1;
1494                 if (hdr.boot_idx == image)
1495                         hdr.boot_idx = 1;
1496                 else
1497                         hdr.boot_idx = 0;
1498         }
1499
1500         if (hdr.boot_idx == 0) {
1501                 memset(&hdr.boot_metadata_res_entry, 0,
1502                        sizeof(struct resource_entry));
1503         } else {
1504                 memcpy(&hdr.boot_metadata_res_entry,
1505                        &w->image_metadata[
1506                           hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1507                        sizeof(struct resource_entry));
1508         }
1509
1510         if (fseeko(out, 0, SEEK_SET) != 0) {
1511                 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1512                                  "being written");
1513                 ret = WIMLIB_ERR_WRITE;
1514                 goto out;
1515         }
1516
1517         ret = write_header(&hdr, out);
1518         if (ret != 0)
1519                 goto out;
1520
1521         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1522                 if (fflush(out) != 0
1523                     || fsync(fileno(out)) != 0)
1524                 {
1525                         ERROR_WITH_ERRNO("Error flushing data to WIM file");
1526                         ret = WIMLIB_ERR_WRITE;
1527                 }
1528         }
1529 out:
1530         if (fclose(out) != 0) {
1531                 ERROR_WITH_ERRNO("Failed to close the WIM file");
1532                 if (ret == 0)
1533                         ret = WIMLIB_ERR_WRITE;
1534         }
1535         w->out_fp = NULL;
1536         return ret;
1537 }
1538
1539 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1540 int lock_wim(FILE *fp, const char *path)
1541 {
1542         int ret = 0;
1543         if (fp) {
1544                 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1545                 if (ret != 0) {
1546                         if (errno == EWOULDBLOCK) {
1547                                 ERROR("`%s' is already being modified or has been "
1548                                       "mounted read-write\n"
1549                                       "        by another process!", path);
1550                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
1551                         } else {
1552                                 WARNING("Failed to lock `%s': %s",
1553                                         path, strerror(errno));
1554                                 ret = 0;
1555                         }
1556                 }
1557         }
1558         return ret;
1559 }
1560 #endif
1561
1562 static int open_wim_writable(WIMStruct *w, const char *path,
1563                              bool trunc, bool readable)
1564 {
1565         const char *mode;
1566         if (trunc)
1567                 if (readable)
1568                         mode = "w+b";
1569                 else
1570                         mode = "wb";
1571         else
1572                 mode = "r+b";
1573
1574         wimlib_assert(w->out_fp == NULL);
1575         w->out_fp = fopen(path, mode);
1576         if (w->out_fp) {
1577                 return 0;
1578         } else {
1579                 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
1580                 return WIMLIB_ERR_OPEN;
1581         }
1582 }
1583
1584
1585 void close_wim_writable(WIMStruct *w)
1586 {
1587         if (w->out_fp) {
1588                 if (fclose(w->out_fp) != 0) {
1589                         WARNING("Failed to close output WIM: %s",
1590                                 strerror(errno));
1591                 }
1592                 w->out_fp = NULL;
1593         }
1594 }
1595
1596 /* Open file stream and write dummy header for WIM. */
1597 int begin_write(WIMStruct *w, const char *path, int write_flags)
1598 {
1599         int ret;
1600         ret = open_wim_writable(w, path, true,
1601                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1602         if (ret != 0)
1603                 return ret;
1604         /* Write dummy header. It will be overwritten later. */
1605         return write_header(&w->hdr, w->out_fp);
1606 }
1607
1608 /* Writes a stand-alone WIM to a file.  */
1609 WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path,
1610                            int image, int write_flags, unsigned num_threads,
1611                            wimlib_progress_func_t progress_func)
1612 {
1613         int ret;
1614
1615         if (!path)
1616                 return WIMLIB_ERR_INVALID_PARAM;
1617
1618         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1619
1620         if (image != WIMLIB_ALL_IMAGES &&
1621              (image < 1 || image > w->hdr.image_count))
1622                 return WIMLIB_ERR_INVALID_IMAGE;
1623
1624         if (w->hdr.total_parts != 1) {
1625                 ERROR("Cannot call wimlib_write() on part of a split WIM");
1626                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1627         }
1628
1629         ret = begin_write(w, path, write_flags);
1630         if (ret != 0)
1631                 goto out;
1632
1633         ret = write_wim_streams(w, image, write_flags, num_threads,
1634                                 progress_func);
1635         if (ret != 0)
1636                 goto out;
1637
1638         if (progress_func)
1639                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1640
1641         ret = for_image(w, image, write_metadata_resource);
1642         if (ret != 0)
1643                 goto out;
1644
1645         if (progress_func)
1646                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1647
1648         ret = finish_write(w, image, write_flags, progress_func);
1649 out:
1650         close_wim_writable(w);
1651         return ret;
1652 }
1653
1654 static int lte_overwrite_prepare(struct lookup_table_entry *lte,
1655                                  void *ignore)
1656 {
1657         memcpy(&lte->output_resource_entry, &lte->resource_entry,
1658                sizeof(struct resource_entry));
1659         lte->out_refcnt = 0;
1660         return 0;
1661 }
1662
1663 static int check_resource_offset(struct lookup_table_entry *lte, void *arg)
1664 {
1665         wimlib_assert(lte->out_refcnt <= lte->refcnt);
1666         if (lte->out_refcnt < lte->refcnt) {
1667                 off_t end_offset = *(u64*)arg;
1668                 if (lte->resource_entry.offset +
1669                     lte->resource_entry.size > end_offset)
1670                 {
1671                         ERROR("The following resource is after the XML data:");
1672                         print_lookup_table_entry(lte);
1673                         return WIMLIB_ERR_RESOURCE_ORDER;
1674                 }
1675         }
1676         return 0;
1677 }
1678
1679 static int find_new_streams(struct lookup_table_entry *lte, void *arg)
1680 {
1681         if (lte->out_refcnt == lte->refcnt) {
1682                 /* Newly added stream that is only referenced in the modified
1683                  * images.  Append it to the list of streams to write. */
1684                 list_add(&lte->staging_list, (struct list_head*)arg);
1685         } else {
1686                 /* Not a newly added stream.  But set out_refcnt to the full
1687                  * refcnt so that it's written correctly. */
1688                 lte->out_refcnt = lte->refcnt;
1689         }
1690         return 0;
1691 }
1692
1693 /*
1694  * Overwrite a WIM, possibly appending streams to it.
1695  *
1696  * A WIM looks like (or is supposed to look like) the following:
1697  *
1698  *                   Header (212 bytes)
1699  *                   Streams and metadata resources (variable size)
1700  *                   Lookup table (variable size)
1701  *                   XML data (variable size)
1702  *                   Integrity table (optional) (variable size)
1703  *
1704  * If we are not adding any streams or metadata resources, the lookup table is
1705  * unchanged--- so we only need to overwrite the XML data, integrity table, and
1706  * header.  This operation is potentially unsafe if the program is abruptly
1707  * terminated while the XML data or integrity table are being overwritten, but
1708  * before the new header has been written.  To partially alleviate this problem,
1709  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1710  * finish_write() to cause a temporary WIM header to be written after the XML
1711  * data has been written.  This may prevent the WIM from becoming corrupted if
1712  * the program is terminated while the integrity table is being calculated (but
1713  * no guarantees, due to write re-ordering...).
1714  *
1715  * If we are adding new streams or images (metadata resources), the lookup table
1716  * needs to be changed, and those streams need to be written.  In this case, we
1717  * try to perform a safe update of the WIM file by writing the streams *after*
1718  * the end of the previous WIM, then writing the new lookup table, XML data, and
1719  * (optionally) integrity table following the new streams.  This will produce a
1720  * layout like the following:
1721  *
1722  *                   Header (212 bytes)
1723  *                   (OLD) Streams and metadata resources (variable size)
1724  *                   (OLD) Lookup table (variable size)
1725  *                   (OLD) XML data (variable size)
1726  *                   (OLD) Integrity table (optional) (variable size)
1727  *                   (NEW) Streams and metadata resources (variable size)
1728  *                   (NEW) Lookup table (variable size)
1729  *                   (NEW) XML data (variable size)
1730  *                   (NEW) Integrity table (optional) (variable size)
1731  *
1732  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
1733  * the header is overwritten to point to the new lookup table, XML data, and
1734  * integrity table, to produce the following layout:
1735  *
1736  *                   Header (212 bytes)
1737  *                   Streams and metadata resources (variable size)
1738  *                   Nothing (variable size)
1739  *                   More Streams and metadata resources (variable size)
1740  *                   Lookup table (variable size)
1741  *                   XML data (variable size)
1742  *                   Integrity table (optional) (variable size)
1743  *
1744  * This method allows an image to be appended to a large WIM very quickly, and
1745  * is is crash-safe except in the case of write re-ordering, but the
1746  * disadvantage is that a small hole is left in the WIM where the old lookup
1747  * table, xml data, and integrity table were.  (These usually only take up a
1748  * small amount of space compared to the streams, however.)
1749  */
1750 static int overwrite_wim_inplace(WIMStruct *w, int write_flags,
1751                                  unsigned num_threads,
1752                                  wimlib_progress_func_t progress_func,
1753                                  int modified_image_idx)
1754 {
1755         int ret;
1756         struct list_head stream_list;
1757         off_t old_wim_end;
1758
1759         DEBUG("Overwriting `%s' in-place", w->filename);
1760
1761         /* Make sure that the integrity table (if present) is after the XML
1762          * data, and that there are no stream resources, metadata resources, or
1763          * lookup tables after the XML data.  Otherwise, these data would be
1764          * overwritten. */
1765         if (w->hdr.integrity.offset != 0 &&
1766             w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1767                 ERROR("Didn't expect the integrity table to be before the XML data");
1768                 return WIMLIB_ERR_RESOURCE_ORDER;
1769         }
1770
1771         if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1772                 ERROR("Didn't expect the lookup table to be after the XML data");
1773                 return WIMLIB_ERR_RESOURCE_ORDER;
1774         }
1775
1776         DEBUG("Identifying newly added streams");
1777         for_lookup_table_entry(w->lookup_table, lte_overwrite_prepare, NULL);
1778         INIT_LIST_HEAD(&stream_list);
1779         for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1780                 DEBUG("Identifiying streams in image %d", i + 1);
1781                 w->private = &stream_list;
1782                 for_dentry_in_tree(w->image_metadata[i].root_dentry,
1783                                    dentry_find_streams_to_write, w);
1784         }
1785
1786         if (w->hdr.integrity.offset)
1787                 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1788         else
1789                 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1790
1791         ret = for_lookup_table_entry(w->lookup_table, check_resource_offset,
1792                                      &old_wim_end);
1793         if (ret != 0)
1794                 return ret;
1795
1796         if (modified_image_idx == w->hdr.image_count && !w->deletion_occurred) {
1797                 /* If no images have been modified and no images have been
1798                  * deleted, a new lookup table does not need to be written. */
1799                 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1800                               w->hdr.lookup_table_res_entry.size;
1801                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1802                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1803         }
1804
1805         INIT_LIST_HEAD(&stream_list);
1806         for_lookup_table_entry(w->lookup_table, find_new_streams,
1807                                &stream_list);
1808
1809         ret = open_wim_writable(w, w->filename, false,
1810                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1811         if (ret != 0)
1812                 return ret;
1813
1814         ret = lock_wim(w->out_fp, w->filename);
1815         if (ret != 0) {
1816                 fclose(w->out_fp);
1817                 w->out_fp = NULL;
1818                 return ret;
1819         }
1820
1821         if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1822                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1823                 fclose(w->out_fp);
1824                 w->out_fp = NULL;
1825                 return WIMLIB_ERR_WRITE;
1826         }
1827
1828         if (!list_empty(&stream_list)) {
1829                 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1830                       old_wim_end);
1831                 ret = write_stream_list(&stream_list, w->out_fp,
1832                                         wimlib_get_compression_type(w),
1833                                         write_flags, num_threads,
1834                                         progress_func);
1835                 if (ret != 0)
1836                         goto out_ftruncate;
1837         } else {
1838                 DEBUG("No new streams were added");
1839         }
1840
1841         for (int i = modified_image_idx; i < w->hdr.image_count; i++) {
1842                 select_wim_image(w, i + 1);
1843                 ret = write_metadata_resource(w);
1844                 if (ret != 0)
1845                         goto out_ftruncate;
1846         }
1847         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1848         ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1849                            progress_func);
1850 out_ftruncate:
1851         close_wim_writable(w);
1852         if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1853                 WARNING("Truncating `%s' to its original size (%"PRIu64" bytes)",
1854                         w->filename, old_wim_end);
1855                 truncate(w->filename, old_wim_end);
1856         }
1857         return ret;
1858 }
1859
1860 static int overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1861                                      unsigned num_threads,
1862                                      wimlib_progress_func_t progress_func)
1863 {
1864         size_t wim_name_len;
1865         int ret;
1866
1867         DEBUG("Overwriting `%s' via a temporary file", w->filename);
1868
1869         /* Write the WIM to a temporary file in the same directory as the
1870          * original WIM. */
1871         wim_name_len = strlen(w->filename);
1872         char tmpfile[wim_name_len + 10];
1873         memcpy(tmpfile, w->filename, wim_name_len);
1874         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1875         tmpfile[wim_name_len + 9] = '\0';
1876
1877         ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1878                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1879                            num_threads, progress_func);
1880         if (ret != 0) {
1881                 ERROR("Failed to write the WIM file `%s'", tmpfile);
1882                 goto err;
1883         }
1884
1885         DEBUG("Renaming `%s' to `%s'", tmpfile, w->filename);
1886
1887         /* Rename the new file to the old file .*/
1888         if (rename(tmpfile, w->filename) != 0) {
1889                 ERROR_WITH_ERRNO("Failed to rename `%s' to `%s'",
1890                                  tmpfile, w->filename);
1891                 ret = WIMLIB_ERR_RENAME;
1892                 goto err;
1893         }
1894
1895         if (progress_func) {
1896                 union wimlib_progress_info progress;
1897                 progress.rename.from = tmpfile;
1898                 progress.rename.to = w->filename;
1899                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1900         }
1901
1902         /* Close the original WIM file that was opened for reading. */
1903         if (w->fp != NULL) {
1904                 fclose(w->fp);
1905                 w->fp = NULL;
1906         }
1907
1908         /* Re-open the WIM read-only. */
1909         w->fp = fopen(w->filename, "rb");
1910         if (w->fp == NULL) {
1911                 ret = WIMLIB_ERR_REOPEN;
1912                 WARNING("Failed to re-open `%s' read-only: %s",
1913                         w->filename, strerror(errno));
1914                 FREE(w->filename);
1915                 w->filename = NULL;
1916         }
1917         return ret;
1918 err:
1919         /* Remove temporary file. */
1920         if (unlink(tmpfile) != 0)
1921                 WARNING("Failed to remove `%s': %s", tmpfile, strerror(errno));
1922         return ret;
1923 }
1924
1925 /*
1926  * Writes a WIM file to the original file that it was read from, overwriting it.
1927  */
1928 WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int write_flags,
1929                                unsigned num_threads,
1930                                wimlib_progress_func_t progress_func)
1931 {
1932         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1933
1934         if (!w->filename)
1935                 return WIMLIB_ERR_NO_FILENAME;
1936
1937         if (w->hdr.total_parts != 1) {
1938                 ERROR("Cannot modify a split WIM");
1939                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1940         }
1941
1942         if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1943             && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1944         {
1945                 int i;
1946                 int modified_image_idx;
1947                 int ret;
1948
1949                 for (i = 0; i < w->hdr.image_count && !w->image_metadata[i].modified; i++)
1950                         ;
1951                 modified_image_idx = i;
1952                 for (; i < w->hdr.image_count && w->image_metadata[i].modified &&
1953                         !w->image_metadata[i].has_been_mounted_rw; i++)
1954                         ;
1955                 if (i == w->hdr.image_count) {
1956                         ret = overwrite_wim_inplace(w, write_flags, num_threads,
1957                                                     progress_func,
1958                                                     modified_image_idx);
1959                         if (ret == WIMLIB_ERR_RESOURCE_ORDER)
1960                                 WARNING("Falling back to re-building entire WIM");
1961                         else
1962                                 return ret;
1963                 }
1964         }
1965         return overwrite_wim_via_tmpfile(w, write_flags, num_threads,
1966                                          progress_func);
1967 }