]> wimlib.net Git - wimlib/blob - src/write.c
3fc9451d0effab99d127ee7fcec704c43ff4f69f
[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 int
742 do_write_stream_list(struct list_head *my_resources,
743                      FILE *out_fp,
744                      int out_ctype,
745                      wimlib_progress_func_t progress_func,
746                      union wimlib_progress_info *progress,
747                      int write_resource_flags)
748 {
749         int ret;
750         struct wim_lookup_table_entry *lte, *tmp;
751
752         list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
753                 ret = write_wim_resource(lte,
754                                          out_fp,
755                                          out_ctype,
756                                          &lte->output_resource_entry,
757                                          write_resource_flags);
758                 if (ret != 0)
759                         return ret;
760                 list_del(&lte->staging_list);
761                 progress->write_streams.completed_bytes +=
762                         wim_resource_size(lte);
763                 progress->write_streams.completed_streams++;
764                 if (progress_func) {
765                         progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
766                                       progress);
767                 }
768         }
769         return 0;
770 }
771
772 static int
773 write_stream_list_serial(struct list_head *stream_list,
774                          FILE *out_fp,
775                          int out_ctype,
776                          int write_flags,
777                          wimlib_progress_func_t progress_func,
778                          union wimlib_progress_info *progress)
779 {
780         int write_resource_flags;
781
782         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
783                 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
784         else
785                 write_resource_flags = 0;
786         progress->write_streams.num_threads = 1;
787         if (progress_func)
788                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
789         return do_write_stream_list(stream_list, out_fp,
790                                     out_ctype, progress_func,
791                                     progress, write_resource_flags);
792 }
793
794 #ifdef ENABLE_MULTITHREADED_COMPRESSION
795 static int
796 write_wim_chunks(struct message *msg, FILE *out_fp,
797                  struct chunk_table *chunk_tab)
798 {
799         for (unsigned i = 0; i < msg->num_chunks; i++) {
800                 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
801
802                 DEBUG2("Write wim chunk %u of %u (csize = %u)",
803                       i, msg->num_chunks, chunk_csize);
804
805                 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
806                     != chunk_csize)
807                 {
808                         ERROR_WITH_ERRNO("Failed to write WIM chunk");
809                         return WIMLIB_ERR_WRITE;
810                 }
811
812                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
813                 chunk_tab->cur_offset += chunk_csize;
814         }
815         return 0;
816 }
817
818 /*
819  * This function is executed by the main thread when the resources are being
820  * compressed in parallel.  The main thread is in change of all reading of the
821  * uncompressed data and writing of the compressed data.  The compressor threads
822  * *only* do compression from/to in-memory buffers.
823  *
824  * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
825  * chunks of compressed data to compress, represented in a `struct message'.
826  * Each message is passed from the main thread to a worker thread through the
827  * res_to_compress_queue, and it is passed back through the
828  * compressed_res_queue.
829  */
830 static int
831 main_writer_thread_proc(struct list_head *stream_list,
832                         FILE *out_fp,
833                         int out_ctype,
834                         struct shared_queue *res_to_compress_queue,
835                         struct shared_queue *compressed_res_queue,
836                         size_t num_messages,
837                         int write_flags,
838                         wimlib_progress_func_t progress_func,
839                         union wimlib_progress_info *progress)
840 {
841         int ret;
842         struct chunk_table *cur_chunk_tab = NULL;
843         struct message *msgs = CALLOC(num_messages, sizeof(struct message));
844         struct wim_lookup_table_entry *next_lte = NULL;
845
846         // Initially, all the messages are available to use.
847         LIST_HEAD(available_msgs);
848
849         if (!msgs) {
850                 ret = WIMLIB_ERR_NOMEM;
851                 goto out;
852         }
853
854         for (size_t i = 0; i < num_messages; i++)
855                 list_add(&msgs[i].list, &available_msgs);
856
857         // outstanding_resources is the list of resources that currently have
858         // had chunks sent off for compression.
859         //
860         // The first stream in outstanding_resources is the stream that is
861         // currently being written (cur_lte).
862         //
863         // The last stream in outstanding_resources is the stream that is
864         // currently being read and chunks fed to the compressor threads
865         // (next_lte).
866         //
867         // Depending on the number of threads and the sizes of the resource,
868         // the outstanding streams list may contain streams between cur_lte and
869         // next_lte that have all their chunks compressed or being compressed,
870         // but haven't been written yet.
871         //
872         LIST_HEAD(outstanding_resources);
873         struct list_head *next_resource = stream_list->next;
874         u64 next_chunk = 0;
875         u64 next_num_chunks = 0;
876
877         // As in write_wim_resource(), each resource we read is checksummed.
878         SHA_CTX next_sha_ctx;
879         u8 next_hash[SHA1_HASH_SIZE];
880
881         // Resources that don't need any chunks compressed are added to this
882         // list and written directly by the main thread.
883         LIST_HEAD(my_resources);
884
885         struct wim_lookup_table_entry *cur_lte = NULL;
886         struct message *msg;
887
888 #ifdef WITH_NTFS_3G
889         ntfs_inode *ni = NULL;
890 #endif
891
892         DEBUG("Initializing buffers for uncompressed "
893               "and compressed data (%zu bytes needed)",
894               num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
895
896         // Pre-allocate all the buffers that will be needed to do the chunk
897         // compression.
898         for (size_t i = 0; i < num_messages; i++) {
899                 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
900                         msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
901
902                         // The extra 8 bytes is because longest_match() in
903                         // lz77.c may read a little bit off the end of the
904                         // uncompressed data.  It doesn't need to be
905                         // initialized--- we really just need to avoid accessing
906                         // an unmapped page.
907                         msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
908                         if (msgs[i].compressed_chunks[j] == NULL ||
909                             msgs[i].uncompressed_chunks[j] == NULL)
910                         {
911                                 ret = WIMLIB_ERR_NOMEM;
912                                 goto out;
913                         }
914                 }
915         }
916
917         // This loop is executed until all resources have been written, except
918         // possibly a few that have been added to the @my_resources list for
919         // writing later.
920         while (1) {
921                 // Send chunks to the compressor threads until either (a) there
922                 // are no more messages available since they were all sent off,
923                 // or (b) there are no more resources that need to be
924                 // compressed.
925                 while (!list_empty(&available_msgs)) {
926                         if (next_chunk == next_num_chunks) {
927                                 // If next_chunk == next_num_chunks, there are
928                                 // no more chunks to write in the current
929                                 // stream.  So, check the SHA1 message digest of
930                                 // the stream that was just finished (unless
931                                 // next_lte == NULL, which is the case the very
932                                 // first time this loop is entered, and also
933                                 // near the very end of the compression when
934                                 // there are no more streams.)  Then, advance to
935                                 // the next stream (if there is one).
936                                 if (next_lte != NULL) {
937                                 #ifdef WITH_NTFS_3G
938                                         end_wim_resource_read(next_lte, ni);
939                                         ni = NULL;
940                                 #else
941                                         end_wim_resource_read(next_lte);
942                                 #endif
943                                         DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
944                                                next_num_chunks);
945                                         sha1_final(next_hash, &next_sha_ctx);
946                                         if (!hashes_equal(next_lte->hash, next_hash)) {
947                                                 ERROR("WIM resource has incorrect hash!");
948                                                 if (next_lte->resource_location ==
949                                                     RESOURCE_IN_FILE_ON_DISK)
950                                                 {
951                                                         ERROR("We were reading it from `%"TS"'; "
952                                                               "maybe it changed while we were "
953                                                               "reading it.",
954                                                               next_lte->file_on_disk);
955                                                 }
956                                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
957                                                 goto out;
958                                         }
959                                 }
960
961                                 // Advance to the next resource.
962                                 //
963                                 // If the next resource needs no compression, just write
964                                 // it with this thread (not now though--- we could be in
965                                 // the middle of writing another resource.)  Keep doing
966                                 // this until we either get to the end of the resources
967                                 // list, or we get to a resource that needs compression.
968                                 while (1) {
969                                         if (next_resource == stream_list) {
970                                                 // No more resources to send for
971                                                 // compression
972                                                 next_lte = NULL;
973                                                 break;
974                                         }
975                                         next_lte = container_of(next_resource,
976                                                                 struct wim_lookup_table_entry,
977                                                                 staging_list);
978                                         next_resource = next_resource->next;
979                                         if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
980                                                && wim_resource_compression_type(next_lte) == out_ctype)
981                                             || wim_resource_size(next_lte) == 0)
982                                         {
983                                                 list_add_tail(&next_lte->staging_list,
984                                                               &my_resources);
985                                         } else {
986                                                 list_add_tail(&next_lte->staging_list,
987                                                               &outstanding_resources);
988                                                 next_chunk = 0;
989                                                 next_num_chunks = wim_resource_chunks(next_lte);
990                                                 sha1_init(&next_sha_ctx);
991                                                 INIT_LIST_HEAD(&next_lte->msg_list);
992                                         #ifdef WITH_NTFS_3G
993                                                 ret = prepare_resource_for_read(next_lte, &ni);
994                                         #else
995                                                 ret = prepare_resource_for_read(next_lte);
996                                         #endif
997
998                                                 if (ret != 0)
999                                                         goto out;
1000                                                 if (cur_lte == NULL) {
1001                                                         // Set cur_lte for the
1002                                                         // first time
1003                                                         cur_lte = next_lte;
1004                                                 }
1005                                                 break;
1006                                         }
1007                                 }
1008                         }
1009
1010                         if (next_lte == NULL) {
1011                                 // No more resources to send for compression
1012                                 break;
1013                         }
1014
1015                         // Get a message from the available messages
1016                         // list
1017                         msg = container_of(available_msgs.next,
1018                                            struct message,
1019                                            list);
1020
1021                         // ... and delete it from the available messages
1022                         // list
1023                         list_del(&msg->list);
1024
1025                         // Initialize the message with the chunks to
1026                         // compress.
1027                         msg->num_chunks = min(next_num_chunks - next_chunk,
1028                                               MAX_CHUNKS_PER_MSG);
1029                         msg->lte = next_lte;
1030                         msg->complete = false;
1031                         msg->begin_chunk = next_chunk;
1032
1033                         unsigned size = WIM_CHUNK_SIZE;
1034                         for (unsigned i = 0; i < msg->num_chunks; i++) {
1035
1036                                 // Read chunk @next_chunk of the stream into the
1037                                 // message so that a compressor thread can
1038                                 // compress it.
1039
1040                                 if (next_chunk == next_num_chunks - 1) {
1041                                         size = MODULO_NONZERO(wim_resource_size(next_lte),
1042                                                               WIM_CHUNK_SIZE);
1043                                 }
1044
1045                                 DEBUG2("Read resource (size=%u, offset=%zu)",
1046                                       size, next_chunk * WIM_CHUNK_SIZE);
1047
1048                                 msg->uncompressed_chunk_sizes[i] = size;
1049
1050                                 ret = read_wim_resource(next_lte,
1051                                                         msg->uncompressed_chunks[i],
1052                                                         size,
1053                                                         next_chunk * WIM_CHUNK_SIZE,
1054                                                         0);
1055                                 if (ret != 0)
1056                                         goto out;
1057                                 sha1_update(&next_sha_ctx,
1058                                             msg->uncompressed_chunks[i], size);
1059                                 next_chunk++;
1060                         }
1061
1062                         // Send the compression request
1063                         list_add_tail(&msg->list, &next_lte->msg_list);
1064                         shared_queue_put(res_to_compress_queue, msg);
1065                         DEBUG2("Compression request sent");
1066                 }
1067
1068                 // If there are no outstanding resources, there are no more
1069                 // resources that need to be written.
1070                 if (list_empty(&outstanding_resources)) {
1071                         ret = 0;
1072                         goto out;
1073                 }
1074
1075                 // Get the next message from the queue and process it.
1076                 // The message will contain 1 or more data chunks that have been
1077                 // compressed.
1078                 msg = shared_queue_get(compressed_res_queue);
1079                 msg->complete = true;
1080
1081                 // Is this the next chunk in the current resource?  If it's not
1082                 // (i.e., an earlier chunk in a same or different resource
1083                 // hasn't been compressed yet), do nothing, and keep this
1084                 // message around until all earlier chunks are received.
1085                 //
1086                 // Otherwise, write all the chunks we can.
1087                 while (cur_lte != NULL &&
1088                        !list_empty(&cur_lte->msg_list) &&
1089                        (msg = container_of(cur_lte->msg_list.next,
1090                                            struct message,
1091                                            list))->complete)
1092                 {
1093                         DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
1094                         if (msg->begin_chunk == 0) {
1095                                 DEBUG2("Begin chunk tab");
1096
1097                                 // This is the first set of chunks.  Leave space
1098                                 // for the chunk table in the output file.
1099                                 off_t cur_offset = ftello(out_fp);
1100                                 if (cur_offset == -1) {
1101                                         ret = WIMLIB_ERR_WRITE;
1102                                         goto out;
1103                                 }
1104                                 ret = begin_wim_resource_chunk_tab(cur_lte,
1105                                                                    out_fp,
1106                                                                    cur_offset,
1107                                                                    &cur_chunk_tab);
1108                                 if (ret != 0)
1109                                         goto out;
1110                         }
1111
1112                         // Write the compressed chunks from the message.
1113                         ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
1114                         if (ret != 0)
1115                                 goto out;
1116
1117                         list_del(&msg->list);
1118
1119                         // This message is available to use for different chunks
1120                         // now.
1121                         list_add(&msg->list, &available_msgs);
1122
1123                         // Was this the last chunk of the stream?  If so, finish
1124                         // it.
1125                         if (list_empty(&cur_lte->msg_list) &&
1126                             msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
1127                         {
1128                                 DEBUG2("Finish wim chunk tab");
1129                                 u64 res_csize;
1130                                 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
1131                                                                     out_fp,
1132                                                                     &res_csize);
1133                                 if (ret != 0)
1134                                         goto out;
1135
1136                                 if (res_csize >= wim_resource_size(cur_lte)) {
1137                                         /* Oops!  We compressed the resource to
1138                                          * larger than the original size.  Write
1139                                          * the resource uncompressed instead. */
1140                                         ret = write_uncompressed_resource_and_truncate(
1141                                                          cur_lte,
1142                                                          out_fp,
1143                                                          cur_chunk_tab->file_offset,
1144                                                          &cur_lte->output_resource_entry);
1145                                         if (ret != 0)
1146                                                 goto out;
1147                                 } else {
1148                                         cur_lte->output_resource_entry.size =
1149                                                 res_csize;
1150
1151                                         cur_lte->output_resource_entry.original_size =
1152                                                 cur_lte->resource_entry.original_size;
1153
1154                                         cur_lte->output_resource_entry.offset =
1155                                                 cur_chunk_tab->file_offset;
1156
1157                                         cur_lte->output_resource_entry.flags =
1158                                                 cur_lte->resource_entry.flags |
1159                                                         WIM_RESHDR_FLAG_COMPRESSED;
1160                                 }
1161
1162                                 progress->write_streams.completed_bytes +=
1163                                                 wim_resource_size(cur_lte);
1164                                 progress->write_streams.completed_streams++;
1165
1166                                 if (progress_func) {
1167                                         progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1168                                                       progress);
1169                                 }
1170
1171                                 FREE(cur_chunk_tab);
1172                                 cur_chunk_tab = NULL;
1173
1174                                 struct list_head *next = cur_lte->staging_list.next;
1175                                 list_del(&cur_lte->staging_list);
1176
1177                                 if (next == &outstanding_resources)
1178                                         cur_lte = NULL;
1179                                 else
1180                                         cur_lte = container_of(cur_lte->staging_list.next,
1181                                                                struct wim_lookup_table_entry,
1182                                                                staging_list);
1183
1184                                 // Since we just finished writing a stream,
1185                                 // write any streams that have been added to the
1186                                 // my_resources list for direct writing by the
1187                                 // main thread (e.g. resources that don't need
1188                                 // to be compressed because the desired
1189                                 // compression type is the same as the previous
1190                                 // compression type).
1191                                 ret = do_write_stream_list(&my_resources,
1192                                                            out_fp,
1193                                                            out_ctype,
1194                                                            progress_func,
1195                                                            progress,
1196                                                            0);
1197                                 if (ret != 0)
1198                                         goto out;
1199                         }
1200                 }
1201         }
1202
1203 out:
1204         if (ret == WIMLIB_ERR_NOMEM) {
1205                 ERROR("Could not allocate enough memory for "
1206                       "multi-threaded compression");
1207         }
1208
1209         if (next_lte) {
1210 #ifdef WITH_NTFS_3G
1211                 end_wim_resource_read(next_lte, ni);
1212 #else
1213                 end_wim_resource_read(next_lte);
1214 #endif
1215         }
1216
1217         if (ret == 0) {
1218                 ret = do_write_stream_list(&my_resources, out_fp,
1219                                            out_ctype, progress_func,
1220                                            progress, 0);
1221         } else {
1222                 if (msgs) {
1223                         size_t num_available_msgs = 0;
1224                         struct list_head *cur;
1225
1226                         list_for_each(cur, &available_msgs) {
1227                                 num_available_msgs++;
1228                         }
1229
1230                         while (num_available_msgs < num_messages) {
1231                                 shared_queue_get(compressed_res_queue);
1232                                 num_available_msgs++;
1233                         }
1234                 }
1235         }
1236
1237         if (msgs) {
1238                 for (size_t i = 0; i < num_messages; i++) {
1239                         for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1240                                 FREE(msgs[i].compressed_chunks[j]);
1241                                 FREE(msgs[i].uncompressed_chunks[j]);
1242                         }
1243                 }
1244                 FREE(msgs);
1245         }
1246
1247         FREE(cur_chunk_tab);
1248         return ret;
1249 }
1250
1251 static long
1252 get_default_num_threads()
1253 {
1254 #ifdef __WIN32__
1255         return win32_get_number_of_processors();
1256 #else
1257         return sysconf(_SC_NPROCESSORS_ONLN);
1258 #endif
1259 }
1260
1261 static int
1262 write_stream_list_parallel(struct list_head *stream_list,
1263                            FILE *out_fp,
1264                            int out_ctype,
1265                            int write_flags,
1266                            unsigned num_threads,
1267                            wimlib_progress_func_t progress_func,
1268                            union wimlib_progress_info *progress)
1269 {
1270         int ret;
1271         struct shared_queue res_to_compress_queue;
1272         struct shared_queue compressed_res_queue;
1273         pthread_t *compressor_threads = NULL;
1274
1275         if (num_threads == 0) {
1276                 long nthreads = get_default_num_threads();
1277                 if (nthreads < 1 || nthreads > UINT_MAX) {
1278                         WARNING("Could not determine number of processors! Assuming 1");
1279                         goto out_serial;
1280                 } else {
1281                         num_threads = nthreads;
1282                 }
1283         }
1284
1285         progress->write_streams.num_threads = num_threads;
1286         wimlib_assert(stream_list->next != stream_list);
1287
1288         static const double MESSAGES_PER_THREAD = 2.0;
1289         size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1290
1291         DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1292
1293         ret = shared_queue_init(&res_to_compress_queue, queue_size);
1294         if (ret != 0)
1295                 goto out_serial;
1296
1297         ret = shared_queue_init(&compressed_res_queue, queue_size);
1298         if (ret != 0)
1299                 goto out_destroy_res_to_compress_queue;
1300
1301         struct compressor_thread_params params;
1302         params.res_to_compress_queue = &res_to_compress_queue;
1303         params.compressed_res_queue = &compressed_res_queue;
1304         params.compress = get_compress_func(out_ctype);
1305
1306         compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1307         if (!compressor_threads) {
1308                 ret = WIMLIB_ERR_NOMEM;
1309                 goto out_destroy_compressed_res_queue;
1310         }
1311
1312         for (unsigned i = 0; i < num_threads; i++) {
1313                 DEBUG("pthread_create thread %u", i);
1314                 ret = pthread_create(&compressor_threads[i], NULL,
1315                                      compressor_thread_proc, &params);
1316                 if (ret != 0) {
1317                         ret = -1;
1318                         ERROR_WITH_ERRNO("Failed to create compressor "
1319                                          "thread %u", i);
1320                         num_threads = i;
1321                         goto out_join;
1322                 }
1323         }
1324
1325         if (progress_func)
1326                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1327
1328         ret = main_writer_thread_proc(stream_list,
1329                                       out_fp,
1330                                       out_ctype,
1331                                       &res_to_compress_queue,
1332                                       &compressed_res_queue,
1333                                       queue_size,
1334                                       write_flags,
1335                                       progress_func,
1336                                       progress);
1337 out_join:
1338         for (unsigned i = 0; i < num_threads; i++)
1339                 shared_queue_put(&res_to_compress_queue, NULL);
1340
1341         for (unsigned i = 0; i < num_threads; i++) {
1342                 if (pthread_join(compressor_threads[i], NULL)) {
1343                         WARNING_WITH_ERRNO("Failed to join compressor "
1344                                            "thread %u", i);
1345                 }
1346         }
1347         FREE(compressor_threads);
1348 out_destroy_compressed_res_queue:
1349         shared_queue_destroy(&compressed_res_queue);
1350 out_destroy_res_to_compress_queue:
1351         shared_queue_destroy(&res_to_compress_queue);
1352         if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1353                 return ret;
1354 out_serial:
1355         WARNING("Falling back to single-threaded compression");
1356         return write_stream_list_serial(stream_list,
1357                                         out_fp,
1358                                         out_ctype,
1359                                         write_flags,
1360                                         progress_func,
1361                                         progress);
1362
1363 }
1364 #endif
1365
1366 /*
1367  * Write a list of streams to a WIM (@out_fp) using the compression type
1368  * @out_ctype and up to @num_threads compressor threads.
1369  */
1370 static int
1371 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1372                   int out_ctype, int write_flags,
1373                   unsigned num_threads,
1374                   wimlib_progress_func_t progress_func)
1375 {
1376         struct wim_lookup_table_entry *lte;
1377         size_t num_streams = 0;
1378         u64 total_bytes = 0;
1379         u64 total_compression_bytes = 0;
1380         union wimlib_progress_info progress;
1381
1382         list_for_each_entry(lte, stream_list, staging_list) {
1383                 num_streams++;
1384                 total_bytes += wim_resource_size(lte);
1385                 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1386                        && (wim_resource_compression_type(lte) != out_ctype ||
1387                            (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1388                 {
1389                         total_compression_bytes += wim_resource_size(lte);
1390                 }
1391         }
1392         progress.write_streams.total_bytes       = total_bytes;
1393         progress.write_streams.total_streams     = num_streams;
1394         progress.write_streams.completed_bytes   = 0;
1395         progress.write_streams.completed_streams = 0;
1396         progress.write_streams.num_threads       = num_threads;
1397         progress.write_streams.compression_type  = out_ctype;
1398
1399 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1400         if (total_compression_bytes >= 1000000 && num_threads != 1)
1401                 return write_stream_list_parallel(stream_list,
1402                                                   out_fp,
1403                                                   out_ctype,
1404                                                   write_flags,
1405                                                   num_threads,
1406                                                   progress_func,
1407                                                   &progress);
1408         else
1409 #endif
1410                 return write_stream_list_serial(stream_list,
1411                                                 out_fp,
1412                                                 out_ctype,
1413                                                 write_flags,
1414                                                 progress_func,
1415                                                 &progress);
1416 }
1417
1418 struct lte_overwrite_prepare_args {
1419         WIMStruct *wim;
1420         off_t end_offset;
1421         struct list_head *stream_list;
1422 };
1423
1424 static int
1425 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1426 {
1427         struct lte_overwrite_prepare_args *args = arg;
1428
1429         if (lte->resource_location == RESOURCE_IN_WIM &&
1430             lte->wim == args->wim &&
1431             lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1432         {
1433         #ifdef ENABLE_ERROR_MESSAGES
1434                 ERROR("The following resource is after the XML data:");
1435                 print_lookup_table_entry(lte, stderr);
1436         #endif
1437                 return WIMLIB_ERR_RESOURCE_ORDER;
1438         }
1439
1440         lte->out_refcnt = lte->refcnt;
1441         memcpy(&lte->output_resource_entry, &lte->resource_entry,
1442                sizeof(struct resource_entry));
1443         if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1444                 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1445                         list_add(&lte->staging_list, args->stream_list);
1446         return 0;
1447 }
1448
1449 static int
1450 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1451                     struct list_head *stream_list)
1452 {
1453         struct lte_overwrite_prepare_args args = {
1454                 .wim         = wim,
1455                 .end_offset  = end_offset,
1456                 .stream_list = stream_list,
1457         };
1458         int ret;
1459
1460         for (int i = 0; i < wim->hdr.image_count; i++) {
1461                 ret = lte_overwrite_prepare(wim->image_metadata[i].metadata_lte,
1462                                             &args);
1463                 if (ret)
1464                         return ret;
1465         }
1466         return for_lookup_table_entry(wim->lookup_table,
1467                                       lte_overwrite_prepare, &args);
1468 }
1469
1470 static int
1471 inode_find_streams_to_write(struct wim_inode *inode,
1472                             struct wim_lookup_table *table,
1473                             struct list_head *stream_list)
1474 {
1475         struct wim_lookup_table_entry *lte;
1476         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1477                 lte = inode_stream_lte(inode, i, table);
1478                 if (lte) {
1479                         if (lte->out_refcnt == 0)
1480                                 list_add_tail(&lte->staging_list, stream_list);
1481                         lte->out_refcnt += inode->i_nlink;
1482                 }
1483         }
1484         return 0;
1485 }
1486
1487 static int
1488 image_find_streams_to_write(WIMStruct *w)
1489 {
1490         struct wim_inode *inode;
1491         struct hlist_node *cur;
1492         struct hlist_head *inode_list;
1493
1494         inode_list = &wim_get_current_image_metadata(w)->inode_list;
1495         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1496                 inode_find_streams_to_write(inode, w->lookup_table,
1497                                             (struct list_head*)w->private);
1498         }
1499         return 0;
1500 }
1501
1502 static int
1503 write_wim_streams(WIMStruct *w, int image, int write_flags,
1504                              unsigned num_threads,
1505                              wimlib_progress_func_t progress_func)
1506 {
1507
1508         for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1509         LIST_HEAD(stream_list);
1510         w->private = &stream_list;
1511         for_image(w, image, image_find_streams_to_write);
1512         return write_stream_list(&stream_list, w->out_fp,
1513                                  wimlib_get_compression_type(w), write_flags,
1514                                  num_threads, progress_func);
1515 }
1516
1517 /*
1518  * Finish writing a WIM file: write the lookup table, xml data, and integrity
1519  * table (optional), then overwrite the WIM header.
1520  *
1521  * write_flags is a bitwise OR of the following:
1522  *
1523  *      (public)  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1524  *              Include an integrity table.
1525  *
1526  *      (public)  WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1527  *              Show progress information when (if) writing the integrity table.
1528  *
1529  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1530  *              Don't write the lookup table.
1531  *
1532  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1533  *              When (if) writing the integrity table, re-use entries from the
1534  *              existing integrity table, if possible.
1535  *
1536  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1537  *              After writing the XML data but before writing the integrity
1538  *              table, write a temporary WIM header and flush the stream so that
1539  *              the WIM is less likely to become corrupted upon abrupt program
1540  *              termination.
1541  *
1542  *      (private) WIMLIB_WRITE_FLAG_FSYNC:
1543  *              fsync() the output file before closing it.
1544  *
1545  */
1546 int
1547 finish_write(WIMStruct *w, int image, int write_flags,
1548              wimlib_progress_func_t progress_func)
1549 {
1550         int ret;
1551         struct wim_header hdr;
1552         FILE *out = w->out_fp;
1553
1554         /* @hdr will be the header for the new WIM.  First copy all the data
1555          * from the header in the WIMStruct; then set all the fields that may
1556          * have changed, including the resource entries, boot index, and image
1557          * count.  */
1558         memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1559
1560         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1561                 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1562                 if (ret != 0)
1563                         goto out;
1564         }
1565
1566         ret = write_xml_data(w->wim_info, image, out,
1567                              (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1568                               wim_info_get_total_bytes(w->wim_info) : 0,
1569                              &hdr.xml_res_entry);
1570         if (ret != 0)
1571                 goto out;
1572
1573         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1574                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1575                         struct wim_header checkpoint_hdr;
1576                         memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1577                         memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1578                         if (fseeko(out, 0, SEEK_SET) != 0) {
1579                                 ERROR_WITH_ERRNO("Failed to seek to beginning "
1580                                                  "of WIM being written");
1581                                 ret = WIMLIB_ERR_WRITE;
1582                                 goto out;
1583                         }
1584                         ret = write_header(&checkpoint_hdr, out);
1585                         if (ret != 0)
1586                                 goto out;
1587
1588                         if (fflush(out) != 0) {
1589                                 ERROR_WITH_ERRNO("Can't write data to WIM");
1590                                 ret = WIMLIB_ERR_WRITE;
1591                                 goto out;
1592                         }
1593
1594                         if (fseeko(out, 0, SEEK_END) != 0) {
1595                                 ERROR_WITH_ERRNO("Failed to seek to end "
1596                                                  "of WIM being written");
1597                                 ret = WIMLIB_ERR_WRITE;
1598                                 goto out;
1599                         }
1600                 }
1601
1602                 off_t old_lookup_table_end;
1603                 off_t new_lookup_table_end;
1604                 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1605                         old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1606                                                w->hdr.lookup_table_res_entry.size;
1607                 } else {
1608                         old_lookup_table_end = 0;
1609                 }
1610                 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1611                                        hdr.lookup_table_res_entry.size;
1612
1613                 ret = write_integrity_table(out,
1614                                             &hdr.integrity,
1615                                             new_lookup_table_end,
1616                                             old_lookup_table_end,
1617                                             progress_func);
1618                 if (ret != 0)
1619                         goto out;
1620         } else {
1621                 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1622         }
1623
1624         /*
1625          * In the WIM header, there is room for the resource entry for a
1626          * metadata resource labeled as the "boot metadata".  This entry should
1627          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
1628          * it should be a copy of the resource entry for the image that is
1629          * marked as bootable.  This is not well documented...
1630          */
1631
1632         /* Set image count and boot index correctly for single image writes */
1633         if (image != WIMLIB_ALL_IMAGES) {
1634                 hdr.image_count = 1;
1635                 if (hdr.boot_idx == image)
1636                         hdr.boot_idx = 1;
1637                 else
1638                         hdr.boot_idx = 0;
1639         }
1640
1641         if (hdr.boot_idx == 0) {
1642                 memset(&hdr.boot_metadata_res_entry, 0,
1643                        sizeof(struct resource_entry));
1644         } else {
1645                 memcpy(&hdr.boot_metadata_res_entry,
1646                        &w->image_metadata[
1647                           hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1648                        sizeof(struct resource_entry));
1649         }
1650
1651         if (fseeko(out, 0, SEEK_SET) != 0) {
1652                 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1653                                  "being written");
1654                 ret = WIMLIB_ERR_WRITE;
1655                 goto out;
1656         }
1657
1658         ret = write_header(&hdr, out);
1659         if (ret != 0)
1660                 goto out;
1661
1662         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1663                 if (fflush(out) != 0
1664                     || fsync(fileno(out)) != 0)
1665                 {
1666                         ERROR_WITH_ERRNO("Error flushing data to WIM file");
1667                         ret = WIMLIB_ERR_WRITE;
1668                 }
1669         }
1670 out:
1671         if (fclose(out) != 0) {
1672                 ERROR_WITH_ERRNO("Failed to close the WIM file");
1673                 if (ret == 0)
1674                         ret = WIMLIB_ERR_WRITE;
1675         }
1676         w->out_fp = NULL;
1677         return ret;
1678 }
1679
1680 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1681 int
1682 lock_wim(WIMStruct *w, FILE *fp)
1683 {
1684         int ret = 0;
1685         if (fp && !w->wim_locked) {
1686                 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1687                 if (ret != 0) {
1688                         if (errno == EWOULDBLOCK) {
1689                                 ERROR("`%"TS"' is already being modified or has been "
1690                                       "mounted read-write\n"
1691                                       "        by another process!", w->filename);
1692                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
1693                         } else {
1694                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1695                                                    w->filename);
1696                                 ret = 0;
1697                         }
1698                 } else {
1699                         w->wim_locked = 1;
1700                 }
1701         }
1702         return ret;
1703 }
1704 #endif
1705
1706 static int
1707 open_wim_writable(WIMStruct *w, const tchar *path,
1708                   bool trunc, bool also_readable)
1709 {
1710         const tchar *mode;
1711         if (trunc)
1712                 if (also_readable)
1713                         mode = T("w+b");
1714                 else
1715                         mode = T("wb");
1716         else
1717                 mode = T("r+b");
1718
1719         wimlib_assert(w->out_fp == NULL);
1720         w->out_fp = tfopen(path, mode);
1721         if (w->out_fp) {
1722                 return 0;
1723         } else {
1724                 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1725                 return WIMLIB_ERR_OPEN;
1726         }
1727 }
1728
1729
1730 void
1731 close_wim_writable(WIMStruct *w)
1732 {
1733         if (w->out_fp) {
1734                 if (fclose(w->out_fp) != 0) {
1735                         WARNING_WITH_ERRNO("Failed to close output WIM");
1736                 }
1737                 w->out_fp = NULL;
1738         }
1739 }
1740
1741 /* Open file stream and write dummy header for WIM. */
1742 int
1743 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1744 {
1745         int ret;
1746         ret = open_wim_writable(w, path, true,
1747                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1748         if (ret != 0)
1749                 return ret;
1750         /* Write dummy header. It will be overwritten later. */
1751         return write_header(&w->hdr, w->out_fp);
1752 }
1753
1754 /* Writes a stand-alone WIM to a file.  */
1755 WIMLIBAPI int
1756 wimlib_write(WIMStruct *w, const tchar *path,
1757              int image, int write_flags, unsigned num_threads,
1758              wimlib_progress_func_t progress_func)
1759 {
1760         int ret;
1761
1762         if (!path)
1763                 return WIMLIB_ERR_INVALID_PARAM;
1764
1765         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1766
1767         if (image != WIMLIB_ALL_IMAGES &&
1768              (image < 1 || image > w->hdr.image_count))
1769                 return WIMLIB_ERR_INVALID_IMAGE;
1770
1771         if (w->hdr.total_parts != 1) {
1772                 ERROR("Cannot call wimlib_write() on part of a split WIM");
1773                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1774         }
1775
1776         ret = begin_write(w, path, write_flags);
1777         if (ret != 0)
1778                 goto out;
1779
1780         ret = write_wim_streams(w, image, write_flags, num_threads,
1781                                 progress_func);
1782         if (ret != 0)
1783                 goto out;
1784
1785         if (progress_func)
1786                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1787
1788         ret = for_image(w, image, write_metadata_resource);
1789         if (ret != 0)
1790                 goto out;
1791
1792         if (progress_func)
1793                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1794
1795         ret = finish_write(w, image, write_flags, progress_func);
1796 out:
1797         close_wim_writable(w);
1798         DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1799         return ret;
1800 }
1801
1802 static bool
1803 any_images_modified(WIMStruct *w)
1804 {
1805         for (int i = 0; i < w->hdr.image_count; i++)
1806                 if (w->image_metadata[i].modified)
1807                         return true;
1808         return false;
1809 }
1810
1811 /*
1812  * Overwrite a WIM, possibly appending streams to it.
1813  *
1814  * A WIM looks like (or is supposed to look like) the following:
1815  *
1816  *                   Header (212 bytes)
1817  *                   Streams and metadata resources (variable size)
1818  *                   Lookup table (variable size)
1819  *                   XML data (variable size)
1820  *                   Integrity table (optional) (variable size)
1821  *
1822  * If we are not adding any streams or metadata resources, the lookup table is
1823  * unchanged--- so we only need to overwrite the XML data, integrity table, and
1824  * header.  This operation is potentially unsafe if the program is abruptly
1825  * terminated while the XML data or integrity table are being overwritten, but
1826  * before the new header has been written.  To partially alleviate this problem,
1827  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1828  * finish_write() to cause a temporary WIM header to be written after the XML
1829  * data has been written.  This may prevent the WIM from becoming corrupted if
1830  * the program is terminated while the integrity table is being calculated (but
1831  * no guarantees, due to write re-ordering...).
1832  *
1833  * If we are adding new streams or images (metadata resources), the lookup table
1834  * needs to be changed, and those streams need to be written.  In this case, we
1835  * try to perform a safe update of the WIM file by writing the streams *after*
1836  * the end of the previous WIM, then writing the new lookup table, XML data, and
1837  * (optionally) integrity table following the new streams.  This will produce a
1838  * layout like the following:
1839  *
1840  *                   Header (212 bytes)
1841  *                   (OLD) Streams and metadata resources (variable size)
1842  *                   (OLD) Lookup table (variable size)
1843  *                   (OLD) XML data (variable size)
1844  *                   (OLD) Integrity table (optional) (variable size)
1845  *                   (NEW) Streams and metadata resources (variable size)
1846  *                   (NEW) Lookup table (variable size)
1847  *                   (NEW) XML data (variable size)
1848  *                   (NEW) Integrity table (optional) (variable size)
1849  *
1850  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
1851  * the header is overwritten to point to the new lookup table, XML data, and
1852  * integrity table, to produce the following layout:
1853  *
1854  *                   Header (212 bytes)
1855  *                   Streams and metadata resources (variable size)
1856  *                   Nothing (variable size)
1857  *                   More Streams and metadata resources (variable size)
1858  *                   Lookup table (variable size)
1859  *                   XML data (variable size)
1860  *                   Integrity table (optional) (variable size)
1861  *
1862  * This method allows an image to be appended to a large WIM very quickly, and
1863  * is is crash-safe except in the case of write re-ordering, but the
1864  * disadvantage is that a small hole is left in the WIM where the old lookup
1865  * table, xml data, and integrity table were.  (These usually only take up a
1866  * small amount of space compared to the streams, however.)
1867  */
1868 static int
1869 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1870                       unsigned num_threads,
1871                       wimlib_progress_func_t progress_func)
1872 {
1873         int ret;
1874         struct list_head stream_list;
1875         off_t old_wim_end;
1876         bool found_modified_image;
1877
1878         DEBUG("Overwriting `%"TS"' in-place", w->filename);
1879
1880         /* Make sure that the integrity table (if present) is after the XML
1881          * data, and that there are no stream resources, metadata resources, or
1882          * lookup tables after the XML data.  Otherwise, these data would be
1883          * overwritten. */
1884         if (w->hdr.integrity.offset != 0 &&
1885             w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1886                 ERROR("Didn't expect the integrity table to be before the XML data");
1887                 return WIMLIB_ERR_RESOURCE_ORDER;
1888         }
1889
1890         if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1891                 ERROR("Didn't expect the lookup table to be after the XML data");
1892                 return WIMLIB_ERR_RESOURCE_ORDER;
1893         }
1894
1895
1896         if (w->hdr.integrity.offset)
1897                 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1898         else
1899                 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1900
1901         if (!w->deletion_occurred && !any_images_modified(w)) {
1902                 /* If no images have been modified and no images have been
1903                  * deleted, a new lookup table does not need to be written. */
1904                 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1905                               w->hdr.lookup_table_res_entry.size;
1906                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1907                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1908         }
1909         INIT_LIST_HEAD(&stream_list);
1910         ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1911         if (ret != 0)
1912                 return ret;
1913
1914         ret = open_wim_writable(w, w->filename, false,
1915                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1916         if (ret != 0)
1917                 return ret;
1918
1919         ret = lock_wim(w, w->out_fp);
1920         if (ret != 0) {
1921                 fclose(w->out_fp);
1922                 w->out_fp = NULL;
1923                 return ret;
1924         }
1925
1926         if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1927                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1928                 fclose(w->out_fp);
1929                 w->out_fp = NULL;
1930                 w->wim_locked = 0;
1931                 return WIMLIB_ERR_WRITE;
1932         }
1933
1934         if (!list_empty(&stream_list)) {
1935                 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1936                       old_wim_end);
1937                 ret = write_stream_list(&stream_list, w->out_fp,
1938                                         wimlib_get_compression_type(w),
1939                                         write_flags, num_threads,
1940                                         progress_func);
1941                 if (ret != 0)
1942                         goto out_ftruncate;
1943         } else {
1944                 DEBUG("No new streams were added");
1945         }
1946
1947         found_modified_image = false;
1948         for (int i = 0; i < w->hdr.image_count; i++) {
1949                 if (!found_modified_image)
1950                         found_modified_image = w->image_metadata[i].modified;
1951                 if (found_modified_image) {
1952                         select_wim_image(w, i + 1);
1953                         ret = write_metadata_resource(w);
1954                         if (ret != 0)
1955                                 goto out_ftruncate;
1956                 }
1957         }
1958         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1959         ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1960                            progress_func);
1961 out_ftruncate:
1962         close_wim_writable(w);
1963         if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1964                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1965                         w->filename, old_wim_end);
1966                 /* Return value of truncate() is ignored because this is already
1967                  * an error path. */
1968                 (void)ttruncate(w->filename, old_wim_end);
1969         }
1970         w->wim_locked = 0;
1971         return ret;
1972 }
1973
1974 static int
1975 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1976                           unsigned num_threads,
1977                           wimlib_progress_func_t progress_func)
1978 {
1979         size_t wim_name_len;
1980         int ret;
1981
1982         DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1983
1984         /* Write the WIM to a temporary file in the same directory as the
1985          * original WIM. */
1986         wim_name_len = tstrlen(w->filename);
1987         tchar tmpfile[wim_name_len + 10];
1988         tmemcpy(tmpfile, w->filename, wim_name_len);
1989         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1990         tmpfile[wim_name_len + 9] = T('\0');
1991
1992         ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1993                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1994                            num_threads, progress_func);
1995         if (ret != 0) {
1996                 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
1997                 goto err;
1998         }
1999
2000         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
2001
2002 #ifdef __WIN32__
2003         /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
2004          * specified to CreateFile().  The WIM was opened with fopen(), which
2005          * didn't provided this flag to CreateFile, so the handle must be closed
2006          * before executing the rename(). */
2007         if (w->fp != NULL) {
2008                 fclose(w->fp);
2009                 w->fp = NULL;
2010         }
2011 #endif
2012
2013         /* Rename the new file to the old file .*/
2014         if (trename(tmpfile, w->filename) != 0) {
2015                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2016                                  tmpfile, w->filename);
2017                 ret = WIMLIB_ERR_RENAME;
2018                 goto err;
2019         }
2020
2021         if (progress_func) {
2022                 union wimlib_progress_info progress;
2023                 progress.rename.from = tmpfile;
2024                 progress.rename.to = w->filename;
2025                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2026         }
2027
2028         /* Close the original WIM file that was opened for reading. */
2029         if (w->fp != NULL) {
2030                 fclose(w->fp);
2031                 w->fp = NULL;
2032         }
2033
2034         /* Re-open the WIM read-only. */
2035         w->fp = tfopen(w->filename, T("rb"));
2036         if (w->fp == NULL) {
2037                 ret = WIMLIB_ERR_REOPEN;
2038                 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
2039                                    w->filename);
2040                 FREE(w->filename);
2041                 w->filename = NULL;
2042         }
2043         return ret;
2044 err:
2045         /* Remove temporary file. */
2046         if (tunlink(tmpfile) != 0)
2047                 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
2048         return ret;
2049 }
2050
2051 /*
2052  * Writes a WIM file to the original file that it was read from, overwriting it.
2053  */
2054 WIMLIBAPI int
2055 wimlib_overwrite(WIMStruct *w, int write_flags,
2056                  unsigned num_threads,
2057                  wimlib_progress_func_t progress_func)
2058 {
2059         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2060
2061         if (!w->filename)
2062                 return WIMLIB_ERR_NO_FILENAME;
2063
2064         if (w->hdr.total_parts != 1) {
2065                 ERROR("Cannot modify a split WIM");
2066                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2067         }
2068
2069         if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2070             && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
2071         {
2072                 int ret;
2073                 ret = overwrite_wim_inplace(w, write_flags, num_threads,
2074                                             progress_func);
2075                 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
2076                         WARNING("Falling back to re-building entire WIM");
2077                 else
2078                         return ret;
2079         }
2080         return overwrite_wim_via_tmpfile(w, write_flags, num_threads,
2081                                          progress_func);
2082 }