]> wimlib.net Git - wimlib/blob - src/write.c
Initial rewrite of resource code
[wimlib] / src / write.c
1 /*
2  * write.c
3  *
4  * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5  * compressed file resources, etc.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #include "config.h"
28
29 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
30 /* On BSD, this should be included before "list.h" so that "list.h" can
31  * overwrite the LIST_HEAD macro. */
32 #  include <sys/file.h>
33 #endif
34
35 #ifdef __WIN32__
36 #  include "win32.h"
37 #endif
38
39 #include "list.h"
40 #include "wimlib_internal.h"
41 #include "buffer_io.h"
42 #include "dentry.h"
43 #include "lookup_table.h"
44 #include "xml.h"
45
46 #ifdef ENABLE_MULTITHREADED_COMPRESSION
47 #  include <pthread.h>
48 #endif
49
50 #include <unistd.h>
51 #include <errno.h>
52
53 #ifdef WITH_NTFS_3G
54 #  include <time.h>
55 #  include <ntfs-3g/attrib.h>
56 #  include <ntfs-3g/inode.h>
57 #  include <ntfs-3g/dir.h>
58 #endif
59
60 #ifdef HAVE_ALLOCA_H
61 #  include <alloca.h>
62 #else
63 #  include <stdlib.h>
64 #endif
65
66 #include <limits.h>
67
68 #if defined(__WIN32__) && !defined(INVALID_HANDLE_VALUE)
69 #  define INVALID_HANDLE_VALUE ((HANDLE)(-1))
70 #endif
71
72 static int
73 fflush_and_ftruncate(FILE *fp, off_t size)
74 {
75         int ret;
76
77         ret = fflush(fp);
78         if (ret != 0) {
79                 ERROR_WITH_ERRNO("Failed to flush data to output WIM file");
80                 return WIMLIB_ERR_WRITE;
81         }
82         ret = ftruncate(fileno(fp), size);
83         if (ret != 0) {
84                 ERROR_WITH_ERRNO("Failed to truncate output WIM file to "
85                                  "%"PRIu64" bytes", size);
86                 return WIMLIB_ERR_WRITE;
87         }
88         return 0;
89 }
90
91 /* Chunk table that's located at the beginning of each compressed resource in
92  * the WIM.  (This is not the on-disk format; the on-disk format just has an
93  * array of offsets.) */
94 struct chunk_table {
95         off_t file_offset;
96         u64 num_chunks;
97         u64 original_resource_size;
98         u64 bytes_per_chunk_entry;
99         u64 table_disk_size;
100         u64 cur_offset;
101         u64 *cur_offset_p;
102         u64 offsets[0];
103 };
104
105 /*
106  * Allocates and initializes a chunk table, and reserves space for it in the
107  * output file.
108  */
109 static int
110 begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
111                              FILE *out_fp,
112                              off_t file_offset,
113                              struct chunk_table **chunk_tab_ret)
114 {
115         u64 size = wim_resource_size(lte);
116         u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
117         size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
118         struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
119         int ret;
120
121         if (!chunk_tab) {
122                 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
123                       "resource", size);
124                 ret = WIMLIB_ERR_NOMEM;
125                 goto out;
126         }
127         chunk_tab->file_offset = file_offset;
128         chunk_tab->num_chunks = num_chunks;
129         chunk_tab->original_resource_size = size;
130         chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
131         chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
132                                      (num_chunks - 1);
133         chunk_tab->cur_offset = 0;
134         chunk_tab->cur_offset_p = chunk_tab->offsets;
135
136         if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
137                    chunk_tab->table_disk_size) {
138                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
139                                  "file resource");
140                 ret = WIMLIB_ERR_WRITE;
141                 goto out;
142         }
143
144         ret = 0;
145 out:
146         *chunk_tab_ret = chunk_tab;
147         return ret;
148 }
149
150 /*
151  * compress_func_t- Pointer to a function to compresses a chunk
152  *                  of a WIM resource.  This may be either
153  *                  wimlib_xpress_compress() (xpress-compress.c) or
154  *                  wimlib_lzx_compress() (lzx-compress.c).
155  *
156  * @chunk:        Uncompressed data of the chunk.
157  * @chunk_size:   Size of the uncompressed chunk, in bytes.
158  * @out:          Pointer to output buffer of size at least (@chunk_size - 1) bytes.
159  *
160  * Returns the size of the compressed data written to @out in bytes, or 0 if the
161  * data could not be compressed to (@chunk_size - 1) bytes or fewer.
162  *
163  * As a special requirement, the compression code is optimized for the WIM
164  * format and therefore requires (@chunk_size <= 32768).
165  *
166  * As another special requirement, the compression code will read up to 8 bytes
167  * off the end of the @chunk array for performance reasons.  The values of these
168  * bytes will not affect the output of the compression, but the calling code
169  * must make sure that the buffer holding the uncompressed chunk is actually at
170  * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
171  * mapped memory that will not cause a memory access violation if accessed.
172  */
173 typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
174                                     void *out);
175
176 compress_func_t
177 get_compress_func(int out_ctype)
178 {
179         if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
180                 return wimlib_lzx_compress;
181         else
182                 return wimlib_xpress_compress;
183 }
184
185 /*
186  * Writes a chunk of a WIM resource to an output file.
187  *
188  * @chunk:        Uncompressed data of the chunk.
189  * @chunk_size:   Size of the chunk (<= WIM_CHUNK_SIZE)
190  * @out_fp:       FILE * to write tho chunk to.
191  * @out_ctype:    Compression type to use when writing the chunk (ignored if no
192  *                      chunk table provided)
193  * @chunk_tab:    Pointer to chunk table being created.  It is updated with the
194  *                      offset of the chunk we write.
195  *
196  * Returns 0 on success; nonzero on failure.
197  */
198 static int
199 write_wim_resource_chunk(const void *chunk, unsigned chunk_size,
200                          FILE *out_fp, compress_func_t compress,
201                          struct chunk_table *chunk_tab)
202 {
203         const u8 *out_chunk;
204         unsigned out_chunk_size;
205         if (chunk_tab) {
206                 u8 *compressed_chunk = alloca(chunk_size);
207
208                 out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
209                 if (out_chunk_size) {
210                         /* Write compressed */
211                         out_chunk = compressed_chunk;
212                 } else {
213                         /* Write uncompressed */
214                         out_chunk = chunk;
215                         out_chunk_size = chunk_size;
216                 }
217                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
218                 chunk_tab->cur_offset += out_chunk_size;
219         } else {
220                 /* Write uncompressed */
221                 out_chunk = chunk;
222                 out_chunk_size = chunk_size;
223         }
224         if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
225                 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
226                 return WIMLIB_ERR_WRITE;
227         }
228         return 0;
229 }
230
231 /*
232  * Finishes a WIM chunk table and writes it to the output file at the correct
233  * offset.
234  *
235  * The final size of the full compressed resource is returned in the
236  * @compressed_size_p.
237  */
238 static int
239 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
240                               FILE *out_fp, u64 *compressed_size_p)
241 {
242         size_t bytes_written;
243         if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
244                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
245                                  "WIM file", chunk_tab->file_offset);
246                 return WIMLIB_ERR_WRITE;
247         }
248
249         if (chunk_tab->bytes_per_chunk_entry == 8) {
250                 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
251         } else {
252                 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
253                         ((u32*)chunk_tab->offsets)[i] =
254                                 cpu_to_le32(chunk_tab->offsets[i]);
255         }
256         bytes_written = fwrite((u8*)chunk_tab->offsets +
257                                         chunk_tab->bytes_per_chunk_entry,
258                                1, chunk_tab->table_disk_size, out_fp);
259         if (bytes_written != chunk_tab->table_disk_size) {
260                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
261                                  "file resource");
262                 return WIMLIB_ERR_WRITE;
263         }
264         if (fseeko(out_fp, 0, SEEK_END) != 0) {
265                 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
266                 return WIMLIB_ERR_WRITE;
267         }
268         *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
269         return 0;
270 }
271
272 static int
273 write_uncompressed_resource_and_truncate(struct wim_lookup_table_entry *lte,
274                                          FILE *out_fp,
275                                          off_t file_offset,
276                                          struct resource_entry *out_res_entry)
277 {
278         int ret;
279         if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
280                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
281                                  "output WIM file", file_offset);
282                 return WIMLIB_ERR_WRITE;
283         }
284         ret = write_wim_resource(lte, out_fp,
285                                  WIMLIB_COMPRESSION_TYPE_NONE,
286                                  out_res_entry,
287                                  0);
288         if (ret)
289                 return ret;
290
291         return fflush_and_ftruncate(out_fp,
292                                     file_offset + wim_resource_size(lte));
293 }
294
295 struct write_resource_ctx {
296         compress_func_t compress;
297         struct chunk_table *chunk_tab;
298         FILE *out_fp;
299         SHA_CTX sha_ctx;
300         bool doing_sha;
301 };
302
303 static int
304 write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
305 {
306         struct write_resource_ctx *ctx = _ctx;
307
308         if (ctx->doing_sha)
309                 sha1_update(&ctx->sha_ctx, chunk, chunk_size);
310
311         if (ctx->compress) {
312                 return write_wim_resource_chunk(chunk, chunk_size,
313                                                 ctx->out_fp, ctx->compress,
314                                                 ctx->chunk_tab);
315         } else {
316                 if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
317                         ERROR_WITH_ERRNO("Error writing to output WIM");
318                         return WIMLIB_ERR_WRITE;
319                 } else {
320                         return 0;
321                 }
322         }
323 }
324
325 int
326 write_wim_resource(struct wim_lookup_table_entry *lte,
327                    FILE *out_fp, int out_ctype,
328                    struct resource_entry *out_res_entry,
329                    int flags)
330 {
331         struct write_resource_ctx write_ctx;
332         u64 new_size;
333         off_t offset;
334         int ret;
335
336         if (wim_resource_size(lte) == 0) {
337                 /* Empty resource; nothing needs to be done, so just return
338                  * success. */
339                 return 0;
340         }
341
342         offset = ftello(out_fp);
343         if (offset == -1) {
344                 ERROR_WITH_ERRNO("Can't get position in output WIM");
345                 return WIMLIB_ERR_WRITE;
346         }
347
348         /* Can we simply copy the compressed data without recompressing it? */
349
350         if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
351             lte->resource_location == RESOURCE_IN_WIM &&
352             wimlib_get_compression_type(lte->wim) == out_ctype)
353         {
354                 flags |= WIMLIB_RESOURCE_FLAG_RAW;
355                 write_ctx.doing_sha = false;
356         } else {
357                 write_ctx.doing_sha = true;
358                 sha1_init(&write_ctx.sha_ctx);
359         }
360
361         /* Initialize the chunk table and set the compression function if
362          * compressing the resource. */
363         if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
364             (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
365                 write_ctx.compress = NULL;
366                 write_ctx.chunk_tab = NULL;
367         } else {
368                 write_ctx.compress = get_compress_func(out_ctype);
369                 ret = begin_wim_resource_chunk_tab(lte, out_fp,
370                                                    offset,
371                                                    &write_ctx.chunk_tab);
372                 if (ret)
373                         return ret;
374         }
375
376         /* Write the data */
377         write_ctx.out_fp = out_fp;
378         ret = read_resource_prefix(lte, wim_resource_size(lte),
379                                    write_resource_cb, &write_ctx, 0);
380
381         /* Verify SHA1 message digest of the resource,  Or, if the hash we had
382          * before is all 0's, just re-set it to be the new hash. */
383         if (write_ctx.doing_sha) {
384                 u8 md[SHA1_HASH_SIZE];
385                 sha1_final(md, &write_ctx.sha_ctx);
386                 if (is_zero_hash(lte->hash)) {
387                         copy_hash(lte->hash, md);
388                 } else if (!hashes_equal(md, lte->hash)) {
389                         ERROR("WIM resource has incorrect hash!");
390                         if (lte_filename_valid(lte)) {
391                                 ERROR("We were reading it from \"%"TS"\"; maybe "
392                                       "it changed while we were reading it.",
393                                       lte->file_on_disk);
394                         }
395                         ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
396                         goto out_free_chunk_tab;
397                 }
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                 out_res_entry->flags = lte->resource_entry.flags;
408         } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
409                 /* Using WIMLIB_COMPRESSION_TYPE_NONE:  The new compressed size
410                  * is the original size. */
411                 new_size = lte->resource_entry.original_size;
412                 out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
413         } else {
414                 /* Using a different compression type:  Call
415                  * finish_wim_resource_chunk_tab() and it will provide the new
416                  * compressed size. */
417                 ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
418                                                     &new_size);
419                 if (ret)
420                         goto out_free_chunk_tab;
421                 if (new_size >= wim_resource_size(lte)) {
422                         /* Oops!  We compressed the resource to larger than the original
423                          * size.  Write the resource uncompressed instead. */
424                         ret = write_uncompressed_resource_and_truncate(lte,
425                                                                        out_fp,
426                                                                        offset,
427                                                                        out_res_entry);
428                         goto out_free_chunk_tab;
429                 }
430                 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
431         }
432         out_res_entry->size = new_size;
433         ret = 0;
434 out_free_chunk_tab:
435         FREE(write_ctx.chunk_tab);
436         return ret;
437 }
438
439 #ifdef ENABLE_MULTITHREADED_COMPRESSION
440
441 /* Blocking shared queue (solves the producer-consumer problem) */
442 struct shared_queue {
443         unsigned size;
444         unsigned front;
445         unsigned back;
446         unsigned filled_slots;
447         void **array;
448         pthread_mutex_t lock;
449         pthread_cond_t msg_avail_cond;
450         pthread_cond_t space_avail_cond;
451 };
452
453 static int
454 shared_queue_init(struct shared_queue *q, unsigned size)
455 {
456         wimlib_assert(size != 0);
457         q->array = CALLOC(sizeof(q->array[0]), size);
458         if (!q->array)
459                 return WIMLIB_ERR_NOMEM;
460         q->filled_slots = 0;
461         q->front = 0;
462         q->back = size - 1;
463         q->size = size;
464         pthread_mutex_init(&q->lock, NULL);
465         pthread_cond_init(&q->msg_avail_cond, NULL);
466         pthread_cond_init(&q->space_avail_cond, NULL);
467         return 0;
468 }
469
470 static void
471 shared_queue_destroy(struct shared_queue *q)
472 {
473         FREE(q->array);
474         pthread_mutex_destroy(&q->lock);
475         pthread_cond_destroy(&q->msg_avail_cond);
476         pthread_cond_destroy(&q->space_avail_cond);
477 }
478
479 static void
480 shared_queue_put(struct shared_queue *q, void *obj)
481 {
482         pthread_mutex_lock(&q->lock);
483         while (q->filled_slots == q->size)
484                 pthread_cond_wait(&q->space_avail_cond, &q->lock);
485
486         q->back = (q->back + 1) % q->size;
487         q->array[q->back] = obj;
488         q->filled_slots++;
489
490         pthread_cond_broadcast(&q->msg_avail_cond);
491         pthread_mutex_unlock(&q->lock);
492 }
493
494 static void *
495 shared_queue_get(struct shared_queue *q)
496 {
497         void *obj;
498
499         pthread_mutex_lock(&q->lock);
500         while (q->filled_slots == 0)
501                 pthread_cond_wait(&q->msg_avail_cond, &q->lock);
502
503         obj = q->array[q->front];
504         q->array[q->front] = NULL;
505         q->front = (q->front + 1) % q->size;
506         q->filled_slots--;
507
508         pthread_cond_broadcast(&q->space_avail_cond);
509         pthread_mutex_unlock(&q->lock);
510         return obj;
511 }
512
513 struct compressor_thread_params {
514         struct shared_queue *res_to_compress_queue;
515         struct shared_queue *compressed_res_queue;
516         compress_func_t compress;
517 };
518
519 #define MAX_CHUNKS_PER_MSG 2
520
521 struct message {
522         struct wim_lookup_table_entry *lte;
523         u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
524         u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
525         u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
526         unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
527         unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
528         unsigned num_chunks;
529         struct list_head list;
530         bool complete;
531         u64 begin_chunk;
532 };
533
534 static void
535 compress_chunks(struct message *msg, compress_func_t compress)
536 {
537         for (unsigned i = 0; i < msg->num_chunks; i++) {
538                 DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
539                 unsigned len = compress(msg->uncompressed_chunks[i],
540                                         msg->uncompressed_chunk_sizes[i],
541                                         msg->compressed_chunks[i]);
542                 if (len) {
543                         /* To be written compressed */
544                         msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
545                         msg->compressed_chunk_sizes[i] = len;
546                 } else {
547                         /* To be written uncompressed */
548                         msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
549                         msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
550
551                 }
552         }
553 }
554
555 /* Compressor thread routine.  This is a lot simpler than the main thread
556  * routine: just repeatedly get a group of chunks from the
557  * res_to_compress_queue, compress them, and put them in the
558  * compressed_res_queue.  A NULL pointer indicates that the thread should stop.
559  * */
560 static void *
561 compressor_thread_proc(void *arg)
562 {
563         struct compressor_thread_params *params = arg;
564         struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
565         struct shared_queue *compressed_res_queue = params->compressed_res_queue;
566         compress_func_t compress = params->compress;
567         struct message *msg;
568
569         DEBUG("Compressor thread ready");
570         while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
571                 compress_chunks(msg, compress);
572                 shared_queue_put(compressed_res_queue, msg);
573         }
574         DEBUG("Compressor thread terminating");
575         return NULL;
576 }
577 #endif /* ENABLE_MULTITHREADED_COMPRESSION */
578
579 static void
580 do_write_streams_progress(union wimlib_progress_info *progress,
581                           wimlib_progress_func_t progress_func,
582                           uint64_t size_added)
583 {
584         progress->write_streams.completed_bytes += size_added;
585         progress->write_streams.completed_streams++;
586         if (progress_func &&
587             progress->write_streams.completed_bytes >= progress->write_streams._private)
588         {
589                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
590                               progress);
591                 if (progress->write_streams._private == progress->write_streams.total_bytes) {
592                         progress->write_streams._private = ~0;
593                 } else {
594                         progress->write_streams._private =
595                                 min(progress->write_streams.total_bytes,
596                                     progress->write_streams.completed_bytes +
597                                         progress->write_streams.total_bytes / 100);
598                 }
599         }
600 }
601
602 static int
603 do_write_stream_list(struct list_head *my_resources,
604                      FILE *out_fp,
605                      int out_ctype,
606                      wimlib_progress_func_t progress_func,
607                      union wimlib_progress_info *progress,
608                      int write_resource_flags)
609 {
610         int ret;
611         struct wim_lookup_table_entry *lte, *tmp;
612
613         list_for_each_entry_safe(lte, tmp, my_resources, staging_list) {
614                 ret = write_wim_resource(lte,
615                                          out_fp,
616                                          out_ctype,
617                                          &lte->output_resource_entry,
618                                          write_resource_flags);
619                 if (ret != 0)
620                         return ret;
621                 list_del(&lte->staging_list);
622
623                 do_write_streams_progress(progress,
624                                           progress_func,
625                                           wim_resource_size(lte));
626         }
627         return 0;
628 }
629
630 static int
631 write_stream_list_serial(struct list_head *stream_list,
632                          FILE *out_fp,
633                          int out_ctype,
634                          int write_flags,
635                          wimlib_progress_func_t progress_func,
636                          union wimlib_progress_info *progress)
637 {
638         int write_resource_flags;
639
640         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
641                 write_resource_flags = WIMLIB_RESOURCE_FLAG_RECOMPRESS;
642         else
643                 write_resource_flags = 0;
644         progress->write_streams.num_threads = 1;
645         if (progress_func)
646                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
647         return do_write_stream_list(stream_list, out_fp,
648                                     out_ctype, progress_func,
649                                     progress, write_resource_flags);
650 }
651
652 #ifdef ENABLE_MULTITHREADED_COMPRESSION
653 static int
654 write_wim_chunks(struct message *msg, FILE *out_fp,
655                  struct chunk_table *chunk_tab)
656 {
657         for (unsigned i = 0; i < msg->num_chunks; i++) {
658                 unsigned chunk_csize = msg->compressed_chunk_sizes[i];
659
660                 DEBUG2("Write wim chunk %u of %u (csize = %u)",
661                       i, msg->num_chunks, chunk_csize);
662
663                 if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
664                     != chunk_csize)
665                 {
666                         ERROR_WITH_ERRNO("Failed to write WIM chunk");
667                         return WIMLIB_ERR_WRITE;
668                 }
669
670                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
671                 chunk_tab->cur_offset += chunk_csize;
672         }
673         return 0;
674 }
675
676 /*
677  * This function is executed by the main thread when the resources are being
678  * compressed in parallel.  The main thread is in change of all reading of the
679  * uncompressed data and writing of the compressed data.  The compressor threads
680  * *only* do compression from/to in-memory buffers.
681  *
682  * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
683  * chunks of compressed data to compress, represented in a `struct message'.
684  * Each message is passed from the main thread to a worker thread through the
685  * res_to_compress_queue, and it is passed back through the
686  * compressed_res_queue.
687  */
688 static int
689 main_writer_thread_proc(struct list_head *stream_list,
690                         FILE *out_fp,
691                         int out_ctype,
692                         struct shared_queue *res_to_compress_queue,
693                         struct shared_queue *compressed_res_queue,
694                         size_t num_messages,
695                         int write_flags,
696                         wimlib_progress_func_t progress_func,
697                         union wimlib_progress_info *progress)
698 {
699         int ret;
700         struct chunk_table *cur_chunk_tab = NULL;
701         struct message *msgs = CALLOC(num_messages, sizeof(struct message));
702         struct wim_lookup_table_entry *next_lte = NULL;
703
704         // Initially, all the messages are available to use.
705         LIST_HEAD(available_msgs);
706
707         if (!msgs) {
708                 ret = WIMLIB_ERR_NOMEM;
709                 goto out;
710         }
711
712         for (size_t i = 0; i < num_messages; i++)
713                 list_add(&msgs[i].list, &available_msgs);
714
715         // outstanding_resources is the list of resources that currently have
716         // had chunks sent off for compression.
717         //
718         // The first stream in outstanding_resources is the stream that is
719         // currently being written (cur_lte).
720         //
721         // The last stream in outstanding_resources is the stream that is
722         // currently being read and chunks fed to the compressor threads
723         // (next_lte).
724         //
725         // Depending on the number of threads and the sizes of the resource,
726         // the outstanding streams list may contain streams between cur_lte and
727         // next_lte that have all their chunks compressed or being compressed,
728         // but haven't been written yet.
729         //
730         LIST_HEAD(outstanding_resources);
731         struct list_head *next_resource = stream_list->next;
732         u64 next_chunk = 0;
733         u64 next_num_chunks = 0;
734
735         // As in write_wim_resource(), each resource we read is checksummed.
736         SHA_CTX next_sha_ctx;
737         u8 next_hash[SHA1_HASH_SIZE];
738
739         // Resources that don't need any chunks compressed are added to this
740         // list and written directly by the main thread.
741         LIST_HEAD(my_resources);
742
743         struct wim_lookup_table_entry *cur_lte = NULL;
744         struct message *msg;
745
746 #ifdef WITH_NTFS_3G
747         ntfs_inode *ni = NULL;
748 #endif
749
750         DEBUG("Initializing buffers for uncompressed "
751               "and compressed data (%zu bytes needed)",
752               num_messages * MAX_CHUNKS_PER_MSG * WIM_CHUNK_SIZE * 2);
753
754         // Pre-allocate all the buffers that will be needed to do the chunk
755         // compression.
756         for (size_t i = 0; i < num_messages; i++) {
757                 for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
758                         msgs[i].compressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE);
759
760                         // The extra 8 bytes is because longest_match() in
761                         // lz77.c may read a little bit off the end of the
762                         // uncompressed data.  It doesn't need to be
763                         // initialized--- we really just need to avoid accessing
764                         // an unmapped page.
765                         msgs[i].uncompressed_chunks[j] = MALLOC(WIM_CHUNK_SIZE + 8);
766                         if (msgs[i].compressed_chunks[j] == NULL ||
767                             msgs[i].uncompressed_chunks[j] == NULL)
768                         {
769                                 ret = WIMLIB_ERR_NOMEM;
770                                 goto out;
771                         }
772                 }
773         }
774
775         // This loop is executed until all resources have been written, except
776         // possibly a few that have been added to the @my_resources list for
777         // writing later.
778         while (1) {
779                 // Send chunks to the compressor threads until either (a) there
780                 // are no more messages available since they were all sent off,
781                 // or (b) there are no more resources that need to be
782                 // compressed.
783                 while (!list_empty(&available_msgs)) {
784                         if (next_chunk == next_num_chunks) {
785                                 // If next_chunk == next_num_chunks, there are
786                                 // no more chunks to write in the current
787                                 // stream.  So, check the SHA1 message digest of
788                                 // the stream that was just finished (unless
789                                 // next_lte == NULL, which is the case the very
790                                 // first time this loop is entered, and also
791                                 // near the very end of the compression when
792                                 // there are no more streams.)  Then, advance to
793                                 // the next stream (if there is one).
794                                 if (next_lte != NULL) {
795                                 #ifdef WITH_NTFS_3G
796                                         end_wim_resource_read(next_lte, ni);
797                                         ni = NULL;
798                                 #else
799                                         end_wim_resource_read(next_lte);
800                                 #endif
801                                         DEBUG2("Finalize SHA1 md (next_num_chunks=%zu)",
802                                                next_num_chunks);
803                                         sha1_final(next_hash, &next_sha_ctx);
804                                         if (!hashes_equal(next_lte->hash, next_hash)) {
805                                                 ERROR("WIM resource has incorrect hash!");
806                                                 if (next_lte->resource_location ==
807                                                     RESOURCE_IN_FILE_ON_DISK)
808                                                 {
809                                                         ERROR("We were reading it from `%"TS"'; "
810                                                               "maybe it changed while we were "
811                                                               "reading it.",
812                                                               next_lte->file_on_disk);
813                                                 }
814                                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
815                                                 goto out;
816                                         }
817                                 }
818
819                                 // Advance to the next resource.
820                                 //
821                                 // If the next resource needs no compression, just write
822                                 // it with this thread (not now though--- we could be in
823                                 // the middle of writing another resource.)  Keep doing
824                                 // this until we either get to the end of the resources
825                                 // list, or we get to a resource that needs compression.
826                                 while (1) {
827                                         if (next_resource == stream_list) {
828                                                 // No more resources to send for
829                                                 // compression
830                                                 next_lte = NULL;
831                                                 break;
832                                         }
833                                         next_lte = container_of(next_resource,
834                                                                 struct wim_lookup_table_entry,
835                                                                 staging_list);
836                                         next_resource = next_resource->next;
837                                         if ((!(write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
838                                                && wim_resource_compression_type(next_lte) == out_ctype)
839                                             || wim_resource_size(next_lte) == 0)
840                                         {
841                                                 list_add_tail(&next_lte->staging_list,
842                                                               &my_resources);
843                                         } else {
844                                                 list_add_tail(&next_lte->staging_list,
845                                                               &outstanding_resources);
846                                                 next_chunk = 0;
847                                                 next_num_chunks = wim_resource_chunks(next_lte);
848                                                 sha1_init(&next_sha_ctx);
849                                                 INIT_LIST_HEAD(&next_lte->msg_list);
850                                         #ifdef WITH_NTFS_3G
851                                                 ret = prepare_resource_for_read(next_lte, &ni);
852                                         #else
853                                                 ret = prepare_resource_for_read(next_lte);
854                                         #endif
855
856                                                 if (ret != 0)
857                                                         goto out;
858                                                 if (cur_lte == NULL) {
859                                                         // Set cur_lte for the
860                                                         // first time
861                                                         cur_lte = next_lte;
862                                                 }
863                                                 break;
864                                         }
865                                 }
866                         }
867
868                         if (next_lte == NULL) {
869                                 // No more resources to send for compression
870                                 break;
871                         }
872
873                         // Get a message from the available messages
874                         // list
875                         msg = container_of(available_msgs.next,
876                                            struct message,
877                                            list);
878
879                         // ... and delete it from the available messages
880                         // list
881                         list_del(&msg->list);
882
883                         // Initialize the message with the chunks to
884                         // compress.
885                         msg->num_chunks = min(next_num_chunks - next_chunk,
886                                               MAX_CHUNKS_PER_MSG);
887                         msg->lte = next_lte;
888                         msg->complete = false;
889                         msg->begin_chunk = next_chunk;
890
891                         unsigned size = WIM_CHUNK_SIZE;
892                         for (unsigned i = 0; i < msg->num_chunks; i++) {
893
894                                 // Read chunk @next_chunk of the stream into the
895                                 // message so that a compressor thread can
896                                 // compress it.
897
898                                 if (next_chunk == next_num_chunks - 1) {
899                                         size = MODULO_NONZERO(wim_resource_size(next_lte),
900                                                               WIM_CHUNK_SIZE);
901                                 }
902
903                                 DEBUG2("Read resource (size=%u, offset=%zu)",
904                                       size, next_chunk * WIM_CHUNK_SIZE);
905
906                                 msg->uncompressed_chunk_sizes[i] = size;
907
908                                 ret = read_wim_resource(next_lte,
909                                                         msg->uncompressed_chunks[i],
910                                                         size,
911                                                         next_chunk * WIM_CHUNK_SIZE,
912                                                         0);
913                                 if (ret != 0)
914                                         goto out;
915                                 sha1_update(&next_sha_ctx,
916                                             msg->uncompressed_chunks[i], size);
917                                 next_chunk++;
918                         }
919
920                         // Send the compression request
921                         list_add_tail(&msg->list, &next_lte->msg_list);
922                         shared_queue_put(res_to_compress_queue, msg);
923                         DEBUG2("Compression request sent");
924                 }
925
926                 // If there are no outstanding resources, there are no more
927                 // resources that need to be written.
928                 if (list_empty(&outstanding_resources)) {
929                         ret = 0;
930                         goto out;
931                 }
932
933                 // Get the next message from the queue and process it.
934                 // The message will contain 1 or more data chunks that have been
935                 // compressed.
936                 msg = shared_queue_get(compressed_res_queue);
937                 msg->complete = true;
938
939                 // Is this the next chunk in the current resource?  If it's not
940                 // (i.e., an earlier chunk in a same or different resource
941                 // hasn't been compressed yet), do nothing, and keep this
942                 // message around until all earlier chunks are received.
943                 //
944                 // Otherwise, write all the chunks we can.
945                 while (cur_lte != NULL &&
946                        !list_empty(&cur_lte->msg_list) &&
947                        (msg = container_of(cur_lte->msg_list.next,
948                                            struct message,
949                                            list))->complete)
950                 {
951                         DEBUG2("Complete msg (begin_chunk=%"PRIu64")", msg->begin_chunk);
952                         if (msg->begin_chunk == 0) {
953                                 DEBUG2("Begin chunk tab");
954
955                                 // This is the first set of chunks.  Leave space
956                                 // for the chunk table in the output file.
957                                 off_t cur_offset = ftello(out_fp);
958                                 if (cur_offset == -1) {
959                                         ret = WIMLIB_ERR_WRITE;
960                                         goto out;
961                                 }
962                                 ret = begin_wim_resource_chunk_tab(cur_lte,
963                                                                    out_fp,
964                                                                    cur_offset,
965                                                                    &cur_chunk_tab);
966                                 if (ret != 0)
967                                         goto out;
968                         }
969
970                         // Write the compressed chunks from the message.
971                         ret = write_wim_chunks(msg, out_fp, cur_chunk_tab);
972                         if (ret != 0)
973                                 goto out;
974
975                         list_del(&msg->list);
976
977                         // This message is available to use for different chunks
978                         // now.
979                         list_add(&msg->list, &available_msgs);
980
981                         // Was this the last chunk of the stream?  If so, finish
982                         // it.
983                         if (list_empty(&cur_lte->msg_list) &&
984                             msg->begin_chunk + msg->num_chunks == cur_chunk_tab->num_chunks)
985                         {
986                                 DEBUG2("Finish wim chunk tab");
987                                 u64 res_csize;
988                                 ret = finish_wim_resource_chunk_tab(cur_chunk_tab,
989                                                                     out_fp,
990                                                                     &res_csize);
991                                 if (ret != 0)
992                                         goto out;
993
994                                 if (res_csize >= wim_resource_size(cur_lte)) {
995                                         /* Oops!  We compressed the resource to
996                                          * larger than the original size.  Write
997                                          * the resource uncompressed instead. */
998                                         ret = write_uncompressed_resource_and_truncate(
999                                                          cur_lte,
1000                                                          out_fp,
1001                                                          cur_chunk_tab->file_offset,
1002                                                          &cur_lte->output_resource_entry);
1003                                         if (ret != 0)
1004                                                 goto out;
1005                                 } else {
1006                                         cur_lte->output_resource_entry.size =
1007                                                 res_csize;
1008
1009                                         cur_lte->output_resource_entry.original_size =
1010                                                 cur_lte->resource_entry.original_size;
1011
1012                                         cur_lte->output_resource_entry.offset =
1013                                                 cur_chunk_tab->file_offset;
1014
1015                                         cur_lte->output_resource_entry.flags =
1016                                                 cur_lte->resource_entry.flags |
1017                                                         WIM_RESHDR_FLAG_COMPRESSED;
1018                                 }
1019
1020                                 do_write_streams_progress(progress, progress_func,
1021                                                           wim_resource_size(cur_lte));
1022
1023                                 FREE(cur_chunk_tab);
1024                                 cur_chunk_tab = NULL;
1025
1026                                 struct list_head *next = cur_lte->staging_list.next;
1027                                 list_del(&cur_lte->staging_list);
1028
1029                                 if (next == &outstanding_resources)
1030                                         cur_lte = NULL;
1031                                 else
1032                                         cur_lte = container_of(cur_lte->staging_list.next,
1033                                                                struct wim_lookup_table_entry,
1034                                                                staging_list);
1035
1036                                 // Since we just finished writing a stream,
1037                                 // write any streams that have been added to the
1038                                 // my_resources list for direct writing by the
1039                                 // main thread (e.g. resources that don't need
1040                                 // to be compressed because the desired
1041                                 // compression type is the same as the previous
1042                                 // compression type).
1043                                 ret = do_write_stream_list(&my_resources,
1044                                                            out_fp,
1045                                                            out_ctype,
1046                                                            progress_func,
1047                                                            progress,
1048                                                            0);
1049                                 if (ret != 0)
1050                                         goto out;
1051                         }
1052                 }
1053         }
1054
1055 out:
1056         if (ret == WIMLIB_ERR_NOMEM) {
1057                 ERROR("Could not allocate enough memory for "
1058                       "multi-threaded compression");
1059         }
1060
1061         if (next_lte) {
1062 #ifdef WITH_NTFS_3G
1063                 end_wim_resource_read(next_lte, ni);
1064 #else
1065                 end_wim_resource_read(next_lte);
1066 #endif
1067         }
1068
1069         if (ret == 0) {
1070                 ret = do_write_stream_list(&my_resources, out_fp,
1071                                            out_ctype, progress_func,
1072                                            progress, 0);
1073         } else {
1074                 if (msgs) {
1075                         size_t num_available_msgs = 0;
1076                         struct list_head *cur;
1077
1078                         list_for_each(cur, &available_msgs) {
1079                                 num_available_msgs++;
1080                         }
1081
1082                         while (num_available_msgs < num_messages) {
1083                                 shared_queue_get(compressed_res_queue);
1084                                 num_available_msgs++;
1085                         }
1086                 }
1087         }
1088
1089         if (msgs) {
1090                 for (size_t i = 0; i < num_messages; i++) {
1091                         for (size_t j = 0; j < MAX_CHUNKS_PER_MSG; j++) {
1092                                 FREE(msgs[i].compressed_chunks[j]);
1093                                 FREE(msgs[i].uncompressed_chunks[j]);
1094                         }
1095                 }
1096                 FREE(msgs);
1097         }
1098
1099         FREE(cur_chunk_tab);
1100         return ret;
1101 }
1102
1103 static long
1104 get_default_num_threads()
1105 {
1106 #ifdef __WIN32__
1107         return win32_get_number_of_processors();
1108 #else
1109         return sysconf(_SC_NPROCESSORS_ONLN);
1110 #endif
1111 }
1112
1113 static int
1114 write_stream_list_parallel(struct list_head *stream_list,
1115                            FILE *out_fp,
1116                            int out_ctype,
1117                            int write_flags,
1118                            unsigned num_threads,
1119                            wimlib_progress_func_t progress_func,
1120                            union wimlib_progress_info *progress)
1121 {
1122         int ret;
1123         struct shared_queue res_to_compress_queue;
1124         struct shared_queue compressed_res_queue;
1125         pthread_t *compressor_threads = NULL;
1126
1127         if (num_threads == 0) {
1128                 long nthreads = get_default_num_threads();
1129                 if (nthreads < 1 || nthreads > UINT_MAX) {
1130                         WARNING("Could not determine number of processors! Assuming 1");
1131                         goto out_serial;
1132                 } else {
1133                         num_threads = nthreads;
1134                 }
1135         }
1136
1137         progress->write_streams.num_threads = num_threads;
1138         wimlib_assert(stream_list->next != stream_list);
1139
1140         static const double MESSAGES_PER_THREAD = 2.0;
1141         size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
1142
1143         DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
1144
1145         ret = shared_queue_init(&res_to_compress_queue, queue_size);
1146         if (ret != 0)
1147                 goto out_serial;
1148
1149         ret = shared_queue_init(&compressed_res_queue, queue_size);
1150         if (ret != 0)
1151                 goto out_destroy_res_to_compress_queue;
1152
1153         struct compressor_thread_params params;
1154         params.res_to_compress_queue = &res_to_compress_queue;
1155         params.compressed_res_queue = &compressed_res_queue;
1156         params.compress = get_compress_func(out_ctype);
1157
1158         compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
1159         if (!compressor_threads) {
1160                 ret = WIMLIB_ERR_NOMEM;
1161                 goto out_destroy_compressed_res_queue;
1162         }
1163
1164         for (unsigned i = 0; i < num_threads; i++) {
1165                 DEBUG("pthread_create thread %u", i);
1166                 ret = pthread_create(&compressor_threads[i], NULL,
1167                                      compressor_thread_proc, &params);
1168                 if (ret != 0) {
1169                         ret = -1;
1170                         ERROR_WITH_ERRNO("Failed to create compressor "
1171                                          "thread %u", i);
1172                         num_threads = i;
1173                         goto out_join;
1174                 }
1175         }
1176
1177         if (progress_func)
1178                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
1179
1180         ret = main_writer_thread_proc(stream_list,
1181                                       out_fp,
1182                                       out_ctype,
1183                                       &res_to_compress_queue,
1184                                       &compressed_res_queue,
1185                                       queue_size,
1186                                       write_flags,
1187                                       progress_func,
1188                                       progress);
1189 out_join:
1190         for (unsigned i = 0; i < num_threads; i++)
1191                 shared_queue_put(&res_to_compress_queue, NULL);
1192
1193         for (unsigned i = 0; i < num_threads; i++) {
1194                 if (pthread_join(compressor_threads[i], NULL)) {
1195                         WARNING_WITH_ERRNO("Failed to join compressor "
1196                                            "thread %u", i);
1197                 }
1198         }
1199         FREE(compressor_threads);
1200 out_destroy_compressed_res_queue:
1201         shared_queue_destroy(&compressed_res_queue);
1202 out_destroy_res_to_compress_queue:
1203         shared_queue_destroy(&res_to_compress_queue);
1204         if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
1205                 return ret;
1206 out_serial:
1207         WARNING("Falling back to single-threaded compression");
1208         return write_stream_list_serial(stream_list,
1209                                         out_fp,
1210                                         out_ctype,
1211                                         write_flags,
1212                                         progress_func,
1213                                         progress);
1214
1215 }
1216 #endif
1217
1218 /*
1219  * Write a list of streams to a WIM (@out_fp) using the compression type
1220  * @out_ctype and up to @num_threads compressor threads.
1221  */
1222 static int
1223 write_stream_list(struct list_head *stream_list, FILE *out_fp,
1224                   int out_ctype, int write_flags,
1225                   unsigned num_threads,
1226                   wimlib_progress_func_t progress_func)
1227 {
1228         struct wim_lookup_table_entry *lte;
1229         size_t num_streams = 0;
1230         u64 total_bytes = 0;
1231         u64 total_compression_bytes = 0;
1232         union wimlib_progress_info progress;
1233
1234         list_for_each_entry(lte, stream_list, staging_list) {
1235                 num_streams++;
1236                 total_bytes += wim_resource_size(lte);
1237                 if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
1238                        && (wim_resource_compression_type(lte) != out_ctype ||
1239                            (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
1240                 {
1241                         total_compression_bytes += wim_resource_size(lte);
1242                 }
1243         }
1244         progress.write_streams.total_bytes       = total_bytes;
1245         progress.write_streams.total_streams     = num_streams;
1246         progress.write_streams.completed_bytes   = 0;
1247         progress.write_streams.completed_streams = 0;
1248         progress.write_streams.num_threads       = num_threads;
1249         progress.write_streams.compression_type  = out_ctype;
1250         progress.write_streams._private          = 0;
1251
1252 #ifdef ENABLE_MULTITHREADED_COMPRESSION
1253         if (total_compression_bytes >= 1000000 && num_threads != 1)
1254                 return write_stream_list_parallel(stream_list,
1255                                                   out_fp,
1256                                                   out_ctype,
1257                                                   write_flags,
1258                                                   num_threads,
1259                                                   progress_func,
1260                                                   &progress);
1261         else
1262 #endif
1263                 return write_stream_list_serial(stream_list,
1264                                                 out_fp,
1265                                                 out_ctype,
1266                                                 write_flags,
1267                                                 progress_func,
1268                                                 &progress);
1269 }
1270
1271 struct lte_overwrite_prepare_args {
1272         WIMStruct *wim;
1273         off_t end_offset;
1274         struct list_head *stream_list;
1275 };
1276
1277 static int
1278 lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *arg)
1279 {
1280         struct lte_overwrite_prepare_args *args = arg;
1281
1282         if (lte->resource_location == RESOURCE_IN_WIM &&
1283             lte->wim == args->wim &&
1284             lte->resource_entry.offset + lte->resource_entry.size > args->end_offset)
1285         {
1286         #ifdef ENABLE_ERROR_MESSAGES
1287                 ERROR("The following resource is after the XML data:");
1288                 print_lookup_table_entry(lte, stderr);
1289         #endif
1290                 return WIMLIB_ERR_RESOURCE_ORDER;
1291         }
1292
1293         lte->out_refcnt = lte->refcnt;
1294         memcpy(&lte->output_resource_entry, &lte->resource_entry,
1295                sizeof(struct resource_entry));
1296         if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
1297                 if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
1298                         list_add(&lte->staging_list, args->stream_list);
1299         return 0;
1300 }
1301
1302 static int
1303 wim_prepare_streams(WIMStruct *wim, off_t end_offset,
1304                     struct list_head *stream_list)
1305 {
1306         struct lte_overwrite_prepare_args args = {
1307                 .wim         = wim,
1308                 .end_offset  = end_offset,
1309                 .stream_list = stream_list,
1310         };
1311         int ret;
1312
1313         for (int i = 0; i < wim->hdr.image_count; i++) {
1314                 ret = lte_overwrite_prepare(wim->image_metadata[i].metadata_lte,
1315                                             &args);
1316                 if (ret)
1317                         return ret;
1318         }
1319         return for_lookup_table_entry(wim->lookup_table,
1320                                       lte_overwrite_prepare, &args);
1321 }
1322
1323 static int
1324 inode_find_streams_to_write(struct wim_inode *inode,
1325                             struct wim_lookup_table *table,
1326                             struct list_head *stream_list)
1327 {
1328         struct wim_lookup_table_entry *lte;
1329         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1330                 lte = inode_stream_lte(inode, i, table);
1331                 if (lte) {
1332                         if (lte->out_refcnt == 0)
1333                                 list_add_tail(&lte->staging_list, stream_list);
1334                         lte->out_refcnt += inode->i_nlink;
1335                 }
1336         }
1337         return 0;
1338 }
1339
1340 static int
1341 image_find_streams_to_write(WIMStruct *w)
1342 {
1343         struct wim_inode *inode;
1344         struct hlist_node *cur;
1345         struct hlist_head *inode_list;
1346
1347         inode_list = &wim_get_current_image_metadata(w)->inode_list;
1348         hlist_for_each_entry(inode, cur, inode_list, i_hlist) {
1349                 inode_find_streams_to_write(inode, w->lookup_table,
1350                                             (struct list_head*)w->private);
1351         }
1352         return 0;
1353 }
1354
1355 static int
1356 write_wim_streams(WIMStruct *w, int image, int write_flags,
1357                              unsigned num_threads,
1358                              wimlib_progress_func_t progress_func)
1359 {
1360
1361         for_lookup_table_entry(w->lookup_table, lte_zero_out_refcnt, NULL);
1362         LIST_HEAD(stream_list);
1363         w->private = &stream_list;
1364         for_image(w, image, image_find_streams_to_write);
1365         return write_stream_list(&stream_list, w->out_fp,
1366                                  wimlib_get_compression_type(w), write_flags,
1367                                  num_threads, progress_func);
1368 }
1369
1370 /*
1371  * Finish writing a WIM file: write the lookup table, xml data, and integrity
1372  * table (optional), then overwrite the WIM header.
1373  *
1374  * write_flags is a bitwise OR of the following:
1375  *
1376  *      (public)  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1377  *              Include an integrity table.
1378  *
1379  *      (public)  WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
1380  *              Show progress information when (if) writing the integrity table.
1381  *
1382  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
1383  *              Don't write the lookup table.
1384  *
1385  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
1386  *              When (if) writing the integrity table, re-use entries from the
1387  *              existing integrity table, if possible.
1388  *
1389  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
1390  *              After writing the XML data but before writing the integrity
1391  *              table, write a temporary WIM header and flush the stream so that
1392  *              the WIM is less likely to become corrupted upon abrupt program
1393  *              termination.
1394  *
1395  *      (private) WIMLIB_WRITE_FLAG_FSYNC:
1396  *              fsync() the output file before closing it.
1397  *
1398  */
1399 int
1400 finish_write(WIMStruct *w, int image, int write_flags,
1401              wimlib_progress_func_t progress_func)
1402 {
1403         int ret;
1404         struct wim_header hdr;
1405         FILE *out = w->out_fp;
1406
1407         /* @hdr will be the header for the new WIM.  First copy all the data
1408          * from the header in the WIMStruct; then set all the fields that may
1409          * have changed, including the resource entries, boot index, and image
1410          * count.  */
1411         memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
1412
1413         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1414                 ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
1415                 if (ret != 0)
1416                         goto out;
1417         }
1418
1419         ret = write_xml_data(w->wim_info, image, out,
1420                              (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
1421                               wim_info_get_total_bytes(w->wim_info) : 0,
1422                              &hdr.xml_res_entry);
1423         if (ret != 0)
1424                 goto out;
1425
1426         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
1427                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
1428                         struct wim_header checkpoint_hdr;
1429                         memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
1430                         memset(&checkpoint_hdr.integrity, 0, sizeof(struct resource_entry));
1431                         if (fseeko(out, 0, SEEK_SET) != 0) {
1432                                 ERROR_WITH_ERRNO("Failed to seek to beginning "
1433                                                  "of WIM being written");
1434                                 ret = WIMLIB_ERR_WRITE;
1435                                 goto out;
1436                         }
1437                         ret = write_header(&checkpoint_hdr, out);
1438                         if (ret != 0)
1439                                 goto out;
1440
1441                         if (fflush(out) != 0) {
1442                                 ERROR_WITH_ERRNO("Can't write data to WIM");
1443                                 ret = WIMLIB_ERR_WRITE;
1444                                 goto out;
1445                         }
1446
1447                         if (fseeko(out, 0, SEEK_END) != 0) {
1448                                 ERROR_WITH_ERRNO("Failed to seek to end "
1449                                                  "of WIM being written");
1450                                 ret = WIMLIB_ERR_WRITE;
1451                                 goto out;
1452                         }
1453                 }
1454
1455                 off_t old_lookup_table_end;
1456                 off_t new_lookup_table_end;
1457                 if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
1458                         old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
1459                                                w->hdr.lookup_table_res_entry.size;
1460                 } else {
1461                         old_lookup_table_end = 0;
1462                 }
1463                 new_lookup_table_end = hdr.lookup_table_res_entry.offset +
1464                                        hdr.lookup_table_res_entry.size;
1465
1466                 ret = write_integrity_table(out,
1467                                             &hdr.integrity,
1468                                             new_lookup_table_end,
1469                                             old_lookup_table_end,
1470                                             progress_func);
1471                 if (ret != 0)
1472                         goto out;
1473         } else {
1474                 memset(&hdr.integrity, 0, sizeof(struct resource_entry));
1475         }
1476
1477         /*
1478          * In the WIM header, there is room for the resource entry for a
1479          * metadata resource labeled as the "boot metadata".  This entry should
1480          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
1481          * it should be a copy of the resource entry for the image that is
1482          * marked as bootable.  This is not well documented...
1483          */
1484
1485         /* Set image count and boot index correctly for single image writes */
1486         if (image != WIMLIB_ALL_IMAGES) {
1487                 hdr.image_count = 1;
1488                 if (hdr.boot_idx == image)
1489                         hdr.boot_idx = 1;
1490                 else
1491                         hdr.boot_idx = 0;
1492         }
1493
1494         if (hdr.boot_idx == 0) {
1495                 memset(&hdr.boot_metadata_res_entry, 0,
1496                        sizeof(struct resource_entry));
1497         } else {
1498                 memcpy(&hdr.boot_metadata_res_entry,
1499                        &w->image_metadata[
1500                           hdr.boot_idx - 1].metadata_lte->output_resource_entry,
1501                        sizeof(struct resource_entry));
1502         }
1503
1504         if (fseeko(out, 0, SEEK_SET) != 0) {
1505                 ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
1506                                  "being written");
1507                 ret = WIMLIB_ERR_WRITE;
1508                 goto out;
1509         }
1510
1511         ret = write_header(&hdr, out);
1512         if (ret != 0)
1513                 goto out;
1514
1515         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
1516                 if (fflush(out) != 0
1517                     || fsync(fileno(out)) != 0)
1518                 {
1519                         ERROR_WITH_ERRNO("Error flushing data to WIM file");
1520                         ret = WIMLIB_ERR_WRITE;
1521                 }
1522         }
1523 out:
1524         if (fclose(out) != 0) {
1525                 ERROR_WITH_ERRNO("Failed to close the WIM file");
1526                 if (ret == 0)
1527                         ret = WIMLIB_ERR_WRITE;
1528         }
1529         w->out_fp = NULL;
1530         return ret;
1531 }
1532
1533 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
1534 int
1535 lock_wim(WIMStruct *w, FILE *fp)
1536 {
1537         int ret = 0;
1538         if (fp && !w->wim_locked) {
1539                 ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
1540                 if (ret != 0) {
1541                         if (errno == EWOULDBLOCK) {
1542                                 ERROR("`%"TS"' is already being modified or has been "
1543                                       "mounted read-write\n"
1544                                       "        by another process!", w->filename);
1545                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
1546                         } else {
1547                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
1548                                                    w->filename);
1549                                 ret = 0;
1550                         }
1551                 } else {
1552                         w->wim_locked = 1;
1553                 }
1554         }
1555         return ret;
1556 }
1557 #endif
1558
1559 static int
1560 open_wim_writable(WIMStruct *w, const tchar *path,
1561                   bool trunc, bool also_readable)
1562 {
1563         const tchar *mode;
1564         if (trunc)
1565                 if (also_readable)
1566                         mode = T("w+b");
1567                 else
1568                         mode = T("wb");
1569         else
1570                 mode = T("r+b");
1571
1572         wimlib_assert(w->out_fp == NULL);
1573         w->out_fp = tfopen(path, mode);
1574         if (w->out_fp) {
1575                 return 0;
1576         } else {
1577                 ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
1578                 return WIMLIB_ERR_OPEN;
1579         }
1580 }
1581
1582
1583 void
1584 close_wim_writable(WIMStruct *w)
1585 {
1586         if (w->out_fp) {
1587                 if (fclose(w->out_fp) != 0) {
1588                         WARNING_WITH_ERRNO("Failed to close output WIM");
1589                 }
1590                 w->out_fp = NULL;
1591         }
1592 }
1593
1594 /* Open file stream and write dummy header for WIM. */
1595 int
1596 begin_write(WIMStruct *w, const tchar *path, int write_flags)
1597 {
1598         int ret;
1599         ret = open_wim_writable(w, path, true,
1600                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1601         if (ret != 0)
1602                 return ret;
1603         /* Write dummy header. It will be overwritten later. */
1604         return write_header(&w->hdr, w->out_fp);
1605 }
1606
1607 /* Writes a stand-alone WIM to a file.  */
1608 WIMLIBAPI int
1609 wimlib_write(WIMStruct *w, const tchar *path,
1610              int image, int write_flags, unsigned num_threads,
1611              wimlib_progress_func_t progress_func)
1612 {
1613         int ret;
1614
1615         if (!path)
1616                 return WIMLIB_ERR_INVALID_PARAM;
1617
1618         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1619
1620         if (image != WIMLIB_ALL_IMAGES &&
1621              (image < 1 || image > w->hdr.image_count))
1622                 return WIMLIB_ERR_INVALID_IMAGE;
1623
1624         if (w->hdr.total_parts != 1) {
1625                 ERROR("Cannot call wimlib_write() on part of a split WIM");
1626                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1627         }
1628
1629         ret = begin_write(w, path, write_flags);
1630         if (ret != 0)
1631                 goto out;
1632
1633         ret = write_wim_streams(w, image, write_flags, num_threads,
1634                                 progress_func);
1635         if (ret != 0)
1636                 goto out;
1637
1638         if (progress_func)
1639                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1640
1641         ret = for_image(w, image, write_metadata_resource);
1642         if (ret != 0)
1643                 goto out;
1644
1645         if (progress_func)
1646                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1647
1648         ret = finish_write(w, image, write_flags, progress_func);
1649 out:
1650         close_wim_writable(w);
1651         DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
1652         return ret;
1653 }
1654
1655 static bool
1656 any_images_modified(WIMStruct *w)
1657 {
1658         for (int i = 0; i < w->hdr.image_count; i++)
1659                 if (w->image_metadata[i].modified)
1660                         return true;
1661         return false;
1662 }
1663
1664 /*
1665  * Overwrite a WIM, possibly appending streams to it.
1666  *
1667  * A WIM looks like (or is supposed to look like) the following:
1668  *
1669  *                   Header (212 bytes)
1670  *                   Streams and metadata resources (variable size)
1671  *                   Lookup table (variable size)
1672  *                   XML data (variable size)
1673  *                   Integrity table (optional) (variable size)
1674  *
1675  * If we are not adding any streams or metadata resources, the lookup table is
1676  * unchanged--- so we only need to overwrite the XML data, integrity table, and
1677  * header.  This operation is potentially unsafe if the program is abruptly
1678  * terminated while the XML data or integrity table are being overwritten, but
1679  * before the new header has been written.  To partially alleviate this problem,
1680  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
1681  * finish_write() to cause a temporary WIM header to be written after the XML
1682  * data has been written.  This may prevent the WIM from becoming corrupted if
1683  * the program is terminated while the integrity table is being calculated (but
1684  * no guarantees, due to write re-ordering...).
1685  *
1686  * If we are adding new streams or images (metadata resources), the lookup table
1687  * needs to be changed, and those streams need to be written.  In this case, we
1688  * try to perform a safe update of the WIM file by writing the streams *after*
1689  * the end of the previous WIM, then writing the new lookup table, XML data, and
1690  * (optionally) integrity table following the new streams.  This will produce a
1691  * layout like the following:
1692  *
1693  *                   Header (212 bytes)
1694  *                   (OLD) Streams and metadata resources (variable size)
1695  *                   (OLD) Lookup table (variable size)
1696  *                   (OLD) XML data (variable size)
1697  *                   (OLD) Integrity table (optional) (variable size)
1698  *                   (NEW) Streams and metadata resources (variable size)
1699  *                   (NEW) Lookup table (variable size)
1700  *                   (NEW) XML data (variable size)
1701  *                   (NEW) Integrity table (optional) (variable size)
1702  *
1703  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
1704  * the header is overwritten to point to the new lookup table, XML data, and
1705  * integrity table, to produce the following layout:
1706  *
1707  *                   Header (212 bytes)
1708  *                   Streams and metadata resources (variable size)
1709  *                   Nothing (variable size)
1710  *                   More Streams and metadata resources (variable size)
1711  *                   Lookup table (variable size)
1712  *                   XML data (variable size)
1713  *                   Integrity table (optional) (variable size)
1714  *
1715  * This method allows an image to be appended to a large WIM very quickly, and
1716  * is is crash-safe except in the case of write re-ordering, but the
1717  * disadvantage is that a small hole is left in the WIM where the old lookup
1718  * table, xml data, and integrity table were.  (These usually only take up a
1719  * small amount of space compared to the streams, however.)
1720  */
1721 static int
1722 overwrite_wim_inplace(WIMStruct *w, int write_flags,
1723                       unsigned num_threads,
1724                       wimlib_progress_func_t progress_func)
1725 {
1726         int ret;
1727         struct list_head stream_list;
1728         off_t old_wim_end;
1729
1730         DEBUG("Overwriting `%"TS"' in-place", w->filename);
1731
1732         /* Make sure that the integrity table (if present) is after the XML
1733          * data, and that there are no stream resources, metadata resources, or
1734          * lookup tables after the XML data.  Otherwise, these data would be
1735          * overwritten. */
1736         if (w->hdr.integrity.offset != 0 &&
1737             w->hdr.integrity.offset < w->hdr.xml_res_entry.offset) {
1738                 ERROR("Didn't expect the integrity table to be before the XML data");
1739                 return WIMLIB_ERR_RESOURCE_ORDER;
1740         }
1741
1742         if (w->hdr.lookup_table_res_entry.offset > w->hdr.xml_res_entry.offset) {
1743                 ERROR("Didn't expect the lookup table to be after the XML data");
1744                 return WIMLIB_ERR_RESOURCE_ORDER;
1745         }
1746
1747
1748         if (w->hdr.integrity.offset)
1749                 old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
1750         else
1751                 old_wim_end = w->hdr.xml_res_entry.offset + w->hdr.xml_res_entry.size;
1752
1753         if (!w->deletion_occurred && !any_images_modified(w)) {
1754                 /* If no images have been modified and no images have been
1755                  * deleted, a new lookup table does not need to be written. */
1756                 old_wim_end = w->hdr.lookup_table_res_entry.offset +
1757                               w->hdr.lookup_table_res_entry.size;
1758                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
1759                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
1760         }
1761         INIT_LIST_HEAD(&stream_list);
1762         ret = wim_prepare_streams(w, old_wim_end, &stream_list);
1763         if (ret != 0)
1764                 return ret;
1765
1766         ret = open_wim_writable(w, w->filename, false,
1767                                 (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
1768         if (ret != 0)
1769                 return ret;
1770
1771         ret = lock_wim(w, w->out_fp);
1772         if (ret != 0) {
1773                 fclose(w->out_fp);
1774                 w->out_fp = NULL;
1775                 return ret;
1776         }
1777
1778         if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
1779                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
1780                 fclose(w->out_fp);
1781                 w->out_fp = NULL;
1782                 w->wim_locked = 0;
1783                 return WIMLIB_ERR_WRITE;
1784         }
1785
1786         if (!list_empty(&stream_list)) {
1787                 DEBUG("Writing newly added streams (offset = %"PRIu64")",
1788                       old_wim_end);
1789                 ret = write_stream_list(&stream_list, w->out_fp,
1790                                         wimlib_get_compression_type(w),
1791                                         write_flags, num_threads,
1792                                         progress_func);
1793                 if (ret != 0)
1794                         goto out_ftruncate;
1795         } else {
1796                 DEBUG("No new streams were added");
1797         }
1798
1799         for (int i = 0; i < w->hdr.image_count; i++) {
1800                 if (w->image_metadata[i].modified) {
1801                         select_wim_image(w, i + 1);
1802                         ret = write_metadata_resource(w);
1803                         if (ret != 0)
1804                                 goto out_ftruncate;
1805                 }
1806         }
1807         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
1808         ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
1809                            progress_func);
1810 out_ftruncate:
1811         close_wim_writable(w);
1812         if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
1813                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
1814                         w->filename, old_wim_end);
1815                 /* Return value of truncate() is ignored because this is already
1816                  * an error path. */
1817                 (void)ttruncate(w->filename, old_wim_end);
1818         }
1819         w->wim_locked = 0;
1820         return ret;
1821 }
1822
1823 static int
1824 overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
1825                           unsigned num_threads,
1826                           wimlib_progress_func_t progress_func)
1827 {
1828         size_t wim_name_len;
1829         int ret;
1830
1831         DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
1832
1833         /* Write the WIM to a temporary file in the same directory as the
1834          * original WIM. */
1835         wim_name_len = tstrlen(w->filename);
1836         tchar tmpfile[wim_name_len + 10];
1837         tmemcpy(tmpfile, w->filename, wim_name_len);
1838         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
1839         tmpfile[wim_name_len + 9] = T('\0');
1840
1841         ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
1842                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
1843                            num_threads, progress_func);
1844         if (ret != 0) {
1845                 ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
1846                 goto err;
1847         }
1848
1849         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
1850
1851 #ifdef __WIN32__
1852         /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
1853          * specified to CreateFile().  The WIM was opened with fopen(), which
1854          * didn't provided this flag to CreateFile, so the handle must be closed
1855          * before executing the rename(). */
1856         if (w->fp != NULL) {
1857                 fclose(w->fp);
1858                 w->fp = NULL;
1859         }
1860 #endif
1861
1862         /* Rename the new file to the old file .*/
1863         if (trename(tmpfile, w->filename) != 0) {
1864                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
1865                                  tmpfile, w->filename);
1866                 ret = WIMLIB_ERR_RENAME;
1867                 goto err;
1868         }
1869
1870         if (progress_func) {
1871                 union wimlib_progress_info progress;
1872                 progress.rename.from = tmpfile;
1873                 progress.rename.to = w->filename;
1874                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
1875         }
1876
1877         /* Close the original WIM file that was opened for reading. */
1878         if (w->fp != NULL) {
1879                 fclose(w->fp);
1880                 w->fp = NULL;
1881         }
1882
1883         /* Re-open the WIM read-only. */
1884         w->fp = tfopen(w->filename, T("rb"));
1885         if (w->fp == NULL) {
1886                 ret = WIMLIB_ERR_REOPEN;
1887                 WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
1888                                    w->filename);
1889                 FREE(w->filename);
1890                 w->filename = NULL;
1891         }
1892         return ret;
1893 err:
1894         /* Remove temporary file. */
1895         if (tunlink(tmpfile) != 0)
1896                 WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
1897         return ret;
1898 }
1899
1900 /*
1901  * Writes a WIM file to the original file that it was read from, overwriting it.
1902  */
1903 WIMLIBAPI int
1904 wimlib_overwrite(WIMStruct *w, int write_flags,
1905                  unsigned num_threads,
1906                  wimlib_progress_func_t progress_func)
1907 {
1908         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
1909
1910         if (!w->filename)
1911                 return WIMLIB_ERR_NO_FILENAME;
1912
1913         if (w->hdr.total_parts != 1) {
1914                 ERROR("Cannot modify a split WIM");
1915                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1916         }
1917
1918         if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
1919             && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
1920         {
1921                 int ret;
1922                 ret = overwrite_wim_inplace(w, write_flags, num_threads,
1923                                             progress_func);
1924                 if (ret == WIMLIB_ERR_RESOURCE_ORDER)
1925                         WARNING("Falling back to re-building entire WIM");
1926                 else
1927                         return ret;
1928         }
1929         return overwrite_wim_via_tmpfile(w, write_flags, num_threads,
1930                                          progress_func);
1931 }