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