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