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