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