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