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