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