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