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