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