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