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