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