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