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