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