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