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