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