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