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