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