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