]> wimlib.net Git - wimlib/blobdiff - src/write.c
overwrite_wim_inplace(): cleanup
[wimlib] / src / write.c
index 94e4fc9fea04700bfb08c198554484d033bf1843..6ae5599337b9552f556134effd691838feaa3318 100644 (file)
  *
  * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
  * compressed file resources, etc.
+ */
+
+/*
+ * Copyright (C) 2012, 2013 Eric Biggers
  *
- * Copyright (C) 2010 Carl Thijssen
- * Copyright (C) 2012 Eric Biggers
- *
- * wimlib - Library for working with WIM files 
+ * This file is part of wimlib, a library for working with WIM files.
  *
- * This library is free software; you can redistribute it and/or modify it under
- * the terms of the GNU Lesser General Public License as published by the Free
- * Software Foundation; either version 2.1 of the License, or (at your option) any
- * later version.
+ * wimlib is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 3 of the License, or (at your option)
+ * any later version.
  *
- * This library is distributed in the hope that it will be useful, but WITHOUT ANY
- * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
- * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+ * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ * A PARTICULAR PURPOSE. See the GNU General Public License for more
+ * details.
  *
- * You should have received a copy of the GNU Lesser General Public License along
- * with this library; if not, write to the Free Software Foundation, Inc., 59
- * Temple Place, Suite 330, Boston, MA 02111-1307 USA 
+ * You should have received a copy of the GNU General Public License
+ * along with wimlib; if not, see http://www.gnu.org/licenses/.
  */
+
+#include "config.h"
+
+#if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
+/* On BSD, this should be included before "list.h" so that "list.h" can
+ * overwrite the LIST_HEAD macro. */
+#  include <sys/file.h>
+#endif
+
+#ifdef __WIN32__
+#  include "win32.h"
+#endif
+
+#include "list.h"
 #include "wimlib_internal.h"
-#include "io.h"
-#include "lookup_table.h"
+#include "buffer_io.h"
 #include "dentry.h"
-#include "sha1.h"
-#include "lzx.h"
+#include "lookup_table.h"
 #include "xml.h"
-#include "xpress.h"
+
+#ifdef ENABLE_MULTITHREADED_COMPRESSION
+#  include <pthread.h>
+#endif
+
 #include <unistd.h>
+#include <errno.h>
+
+#ifdef WITH_NTFS_3G
+#  include <time.h>
+#  include <ntfs-3g/attrib.h>
+#  include <ntfs-3g/inode.h>
+#  include <ntfs-3g/dir.h>
+#endif
+
+#ifdef HAVE_ALLOCA_H
+#  include <alloca.h>
+#else
+#  include <stdlib.h>
+#endif
+
+#include <limits.h>
+
+#if defined(__WIN32__) && !defined(INVALID_HANDLE_VALUE)
+#  define INVALID_HANDLE_VALUE ((HANDLE)(-1))
+#endif
+
+/* Chunk table that's located at the beginning of each compressed resource in
+ * the WIM.  (This is not the on-disk format; the on-disk format just has an
+ * array of offsets.) */
+struct chunk_table {
+       off_t file_offset;
+       u64 num_chunks;
+       u64 original_resource_size;
+       u64 bytes_per_chunk_entry;
+       u64 table_disk_size;
+       u64 cur_offset;
+       u64 *cur_offset_p;
+       u64 offsets[0];
+};
 
+/*
+ * Allocates and initializes a chunk table, and reserves space for it in the
+ * output file.
+ */
+static int
+begin_wim_resource_chunk_tab(const struct wim_lookup_table_entry *lte,
+                            FILE *out_fp,
+                            off_t file_offset,
+                            struct chunk_table **chunk_tab_ret)
+{
+       u64 size = wim_resource_size(lte);
+       u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
+       size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
+       struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
+       int ret;
 
+       if (!chunk_tab) {
+               ERROR("Failed to allocate chunk table for %"PRIu64" byte "
+                     "resource", size);
+               ret = WIMLIB_ERR_NOMEM;
+               goto out;
+       }
+       chunk_tab->file_offset = file_offset;
+       chunk_tab->num_chunks = num_chunks;
+       chunk_tab->original_resource_size = size;
+       chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
+       chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
+                                    (num_chunks - 1);
+       chunk_tab->cur_offset = 0;
+       chunk_tab->cur_offset_p = chunk_tab->offsets;
+
+       if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
+                  chunk_tab->table_disk_size) {
+               ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
+                                "file resource");
+               FREE(chunk_tab);
+               ret = WIMLIB_ERR_WRITE;
+               goto out;
+       }
 
-/* Used for buffering FILE IO */
-#define BUFFER_SIZE 4096
+       ret = 0;
+       *chunk_tab_ret = chunk_tab;
+out:
+       return ret;
+}
 
 /*
- * Copies bytes between two file streams.
+ * compress_func_t- Pointer to a function to compresses a chunk
+ *                  of a WIM resource.  This may be either
+ *                  wimlib_xpress_compress() (xpress-compress.c) or
+ *                  wimlib_lzx_compress() (lzx-compress.c).
+ *
+ * @chunk:       Uncompressed data of the chunk.
+ * @chunk_size:          Size of the uncompressed chunk, in bytes.
+ * @out:         Pointer to output buffer of size at least (@chunk_size - 1) bytes.
  *
- * Copies @len bytes from @in to @out, at the current position in @out, and at
- * an offset of @in_offset in @in.
+ * Returns the size of the compressed data written to @out in bytes, or 0 if the
+ * data could not be compressed to (@chunk_size - 1) bytes or fewer.
+ *
+ * As a special requirement, the compression code is optimized for the WIM
+ * format and therefore requires (@chunk_size <= 32768).
+ *
+ * As another special requirement, the compression code will read up to 8 bytes
+ * off the end of the @chunk array for performance reasons.  The values of these
+ * bytes will not affect the output of the compression, but the calling code
+ * must make sure that the buffer holding the uncompressed chunk is actually at
+ * least (@chunk_size + 8) bytes, or at least that these extra bytes are in
+ * mapped memory that will not cause a memory access violation if accessed.
  */
-static int copy_between_files(FILE *in, off_t in_offset, FILE *out, size_t len)
-{
-       u8 buf[BUFFER_SIZE];
-       size_t n;
-
-       if (fseeko(in, in_offset, SEEK_SET) != 0) {
-               ERROR("Failed to seek to byte %"PRIu64" of input file: %m\n",
-                               in_offset);
-               return WIMLIB_ERR_READ;
-       }
-       /* To reduce memory usage and improve speed, read and write BUFFER_SIZE
-        * bytes at a time. */
-       while (len != 0) {
-               n = min(len, BUFFER_SIZE);
-               if (fread(buf, 1, n, in) != n) {
-                       if (feof(in)) {
-                               ERROR("Unexpected EOF when copying data "
-                                               "between files\n");
-                       } else {
-                               ERROR("Error copying data between files: %m\n");
-                       }
-                       return WIMLIB_ERR_READ;
-               }
+typedef unsigned (*compress_func_t)(const void *chunk, unsigned chunk_size,
+                                   void *out);
 
-               if (fwrite(buf, 1, n, out) != n) {
-                       ERROR("Error copying data between files: %m\n");
-                       return WIMLIB_ERR_WRITE;
+compress_func_t
+get_compress_func(int out_ctype)
+{
+       if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
+               return wimlib_lzx_compress;
+       else
+               return wimlib_xpress_compress;
+}
+
+/*
+ * Writes a chunk of a WIM resource to an output file.
+ *
+ * @chunk:       Uncompressed data of the chunk.
+ * @chunk_size:          Size of the chunk (<= WIM_CHUNK_SIZE)
+ * @out_fp:      FILE * to write the chunk to.
+ * @compress:     Compression function to use (NULL if writing uncompressed
+ *                     data).
+ * @chunk_tab:   Pointer to chunk table being created.  It is updated with the
+ *                     offset of the chunk we write.
+ *
+ * Returns 0 on success; nonzero on failure.
+ */
+static int
+write_wim_resource_chunk(const void *chunk, unsigned chunk_size,
+                        FILE *out_fp, compress_func_t compress,
+                        struct chunk_table *chunk_tab)
+{
+       const u8 *out_chunk;
+       unsigned out_chunk_size;
+       if (compress) {
+               u8 *compressed_chunk = alloca(chunk_size);
+
+               out_chunk_size = compress(chunk, chunk_size, compressed_chunk);
+               if (out_chunk_size) {
+                       /* Write compressed */
+                       out_chunk = compressed_chunk;
+               } else {
+                       /* Write uncompressed */
+                       out_chunk = chunk;
+                       out_chunk_size = chunk_size;
                }
-               len -= n;
+               *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
+               chunk_tab->cur_offset += out_chunk_size;
+       } else {
+               /* Write uncompressed */
+               out_chunk = chunk;
+               out_chunk_size = chunk_size;
+       }
+       if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
+               ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
+               return WIMLIB_ERR_WRITE;
        }
        return 0;
 }
 
-
-/* 
- * Uncompresses a WIM file resource and writes it uncompressed to a file stream.
+/*
+ * Finishes a WIM chunk table and writes it to the output file at the correct
+ * offset.
  *
- * @in:                    The file stream that contains the file resource.
- * @size:           The size of the resource in the input file.
- * @original_size:  The original (uncompressed) size of the resource. 
- * @offset:        The offset of the start of the resource in @in.
- * @input_ctype:    The compression type of the resource in @in.
- * @out:           The file stream to write the file resource to.
+ * The final size of the full compressed resource is returned in the
+ * @compressed_size_p.
  */
-static int uncompress_resource(FILE *in, u64 size, u64 original_size,
-                              off_t offset, int input_ctype, FILE *out)
+static int
+finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
+                             FILE *out_fp, u64 *compressed_size_p)
 {
-       int ret;
-       u8 buf[WIM_CHUNK_SIZE];
-       /* Determine how many compressed chunks the file is divided into. */
-       u64 num_chunks;
-       u64 i;
-       u64 uncompressed_offset;
-       u64 uncompressed_chunk_size;
-       
-       num_chunks = (original_size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
-
-       for (i = 0; i < num_chunks; i++) {
-
-               uncompressed_offset = i * WIM_CHUNK_SIZE;
-               uncompressed_chunk_size = min(WIM_CHUNK_SIZE, 
-                                       original_size - uncompressed_offset);
-
-               ret = read_resource(in, size, original_size, offset, input_ctype, 
-                                       uncompressed_chunk_size, 
-                                       uncompressed_offset, buf);
-               if (ret != 0)
-                       return ret;
+       size_t bytes_written;
+       if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
+               ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
+                                "WIM file", chunk_tab->file_offset);
+               return WIMLIB_ERR_WRITE;
+       }
 
-               if (fwrite(buf, 1, uncompressed_chunk_size, out) != 
-                                               uncompressed_chunk_size) {
-                       ERROR("Failed to write file resource: %m\n");
-                       return WIMLIB_ERR_WRITE;
-               }
+       if (chunk_tab->bytes_per_chunk_entry == 8) {
+               array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
+       } else {
+               for (u64 i = 0; i < chunk_tab->num_chunks; i++)
+                       ((u32*)chunk_tab->offsets)[i] =
+                               cpu_to_le32(chunk_tab->offsets[i]);
        }
+       bytes_written = fwrite((u8*)chunk_tab->offsets +
+                                       chunk_tab->bytes_per_chunk_entry,
+                              1, chunk_tab->table_disk_size, out_fp);
+       if (bytes_written != chunk_tab->table_disk_size) {
+               ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
+                                "file resource");
+               return WIMLIB_ERR_WRITE;
+       }
+       if (fseeko(out_fp, 0, SEEK_END) != 0) {
+               ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
+               return WIMLIB_ERR_WRITE;
+       }
+       *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
        return 0;
 }
 
-/* 
- * Transfers a file resource between two files, writing it compressed.  The file
- * resource in the input file may be either compressed or uncompressed.
- * Alternatively, the input resource may be in-memory, but it must be
- * uncompressed.
- *
- * @in:                    The file stream that contains the file resource.  Ignored
- *                     if uncompressed_resource != NULL.
- * @uncompressed_resource:     If this pointer is not NULL, it points to an
- *                                     array of @original_size bytes that are
- *                                     the uncompressed input resource.
- * @size:           The size of the resource in the input file.
- * @original_size:  The original (uncompressed) size of the resource. 
- * @offset:        The offset of the start of the resource in @in.  Ignored
- *                     if uncompressed_resource != NULL.
- * @input_ctype:    The compression type of the resource in @in.  Ignored if
- *                     uncompressed_resource != NULL.
- * @out:           The file stream to write the file resource to.
- * @output_type:    The compression type to use when writing the resource to
- *                     @out.
- * @new_size_ret:   A location into which the new compressed size of the file
- *                     resource in returned.
- */
-static int recompress_resource(FILE *in, const u8 uncompressed_resource[], 
-                                       u64 size, u64 original_size,
-                                       off_t offset, int input_ctype, FILE *out,
-                                       int output_ctype, u64 *new_size_ret)
+static int
+finalize_and_check_sha1(SHA_CTX *sha_ctx, struct wim_lookup_table_entry *lte)
 {
-       int ret;
-       int (*compress)(const void *, uint, void *, uint *);
-       if (output_ctype == WIM_COMPRESSION_TYPE_LZX)
-               compress = lzx_compress;
-       else
-               compress = xpress_compress;
+       u8 md[SHA1_HASH_SIZE];
+       sha1_final(md, sha_ctx);
+       if (lte->unhashed) {
+               copy_hash(lte->hash, md);
+       } else if (!hashes_equal(md, lte->hash)) {
+               ERROR("WIM resource has incorrect hash!");
+               if (lte_filename_valid(lte)) {
+                       ERROR("We were reading it from \"%"TS"\"; maybe "
+                             "it changed while we were reading it.",
+                             lte->file_on_disk);
+               }
+               return WIMLIB_ERR_INVALID_RESOURCE_HASH;
+       }
+       return 0;
+}
 
-       u8 uncompressed_buf[WIM_CHUNK_SIZE];
-       u8 compressed_buf[WIM_CHUNK_SIZE - 1];
 
-       /* Determine how many compressed chunks the file needs to be divided
-        * into. */
-       u64 num_chunks = (original_size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
+struct write_resource_ctx {
+       compress_func_t compress;
+       struct chunk_table *chunk_tab;
+       FILE *out_fp;
+       SHA_CTX sha_ctx;
+       bool doing_sha;
+};
 
-       u64 num_chunk_entries = num_chunks - 1;
+static int
+write_resource_cb(const void *chunk, size_t chunk_size, void *_ctx)
+{
+       struct write_resource_ctx *ctx = _ctx;
 
-       /* Size of the chunk entries--- 8 bytes for files over 4GB, otherwise 4
-        * bytes */
-       uint chunk_entry_size = (original_size >= (u64)1 << 32) ?  8 : 4;
+       if (ctx->doing_sha)
+               sha1_update(&ctx->sha_ctx, chunk, chunk_size);
 
-       /* Array in which to construct the chunk offset table. */
-       u64 chunk_offsets[num_chunk_entries];
+       if (ctx->compress) {
+               return write_wim_resource_chunk(chunk, chunk_size,
+                                               ctx->out_fp, ctx->compress,
+                                               ctx->chunk_tab);
+       } else {
+               if (fwrite(chunk, 1, chunk_size, ctx->out_fp) != chunk_size) {
+                       ERROR_WITH_ERRNO("Error writing to output WIM");
+                       return WIMLIB_ERR_WRITE;
+               } else {
+                       return 0;
+               }
+       }
+}
 
-       /* Offset of the start of the chunk table in the output file. */
-       off_t chunk_tab_offset = ftello(out);
+/*
+ * Write a resource to an output WIM.
+ *
+ * @lte:  Lookup table entry for the resource, which could be in another WIM,
+ *        in an external file, or in another location.
+ *
+ * @out_fp:  FILE * opened to the output WIM.
+ *
+ * @out_ctype:  One of the WIMLIB_COMPRESSION_TYPE_* constants to indicate
+ *              which compression algorithm to use.
+ *
+ * @out_res_entry:  On success, this is filled in with the offset, flags,
+ *                  compressed size, and uncompressed size of the resource
+ *                  in the output WIM.
+ *
+ * @flags:  WIMLIB_RESOURCE_FLAG_RECOMPRESS to force data to be recompressed
+ *          even if it could otherwise be copied directly from the input.
+ *
+ * Additional notes:  The SHA1 message digest of the uncompressed data is
+ * calculated (except when doing a raw copy --- see below).  If the @unhashed
+ * flag is set on the lookup table entry, this message digest is simply copied
+ * to it; otherwise, the message digest is compared with the existing one, and
+ * the function will fail if they do not match.
+ */
+int
+write_wim_resource(struct wim_lookup_table_entry *lte,
+                  FILE *out_fp, int out_ctype,
+                  struct resource_entry *out_res_entry,
+                  int flags)
+{
+       struct write_resource_ctx write_ctx;
+       u64 read_size;
+       u64 new_size;
+       off_t offset;
+       int ret;
 
-       /* Total size of the chunk table (as written to the file) */
-       u64 chunk_tab_size = chunk_entry_size * num_chunk_entries;
+       flags &= ~WIMLIB_RESOURCE_FLAG_RECOMPRESS;
 
-       /* Reserve space for the chunk table. */
-       if (fwrite(chunk_offsets, 1, chunk_tab_size, out) != chunk_tab_size) {
-               ERROR("Failed to write chunk offset table: %m\n");
+       /* Get current position in output WIM */
+       offset = ftello(out_fp);
+       if (offset == -1) {
+               ERROR_WITH_ERRNO("Can't get position in output WIM");
                return WIMLIB_ERR_WRITE;
        }
 
-       /* Read each chunk of the file, compress it, write it to the output
-        * file, and update th chunk offset table. */
-       u64 cur_chunk_offset = 0;
-       for (u64 i = 0; i < num_chunks; i++) {
+       /* If we are not forcing the data to be recompressed, and the input
+        * resource is located in a WIM with the same compression type as that
+        * desired other than no compression, we can simply copy the compressed
+        * data without recompressing it.  This also means we must skip
+        * calculating the SHA1, as we never will see the uncompressed data. */
+       if (!(flags & WIMLIB_RESOURCE_FLAG_RECOMPRESS) &&
+           lte->resource_location == RESOURCE_IN_WIM &&
+           out_ctype != WIMLIB_COMPRESSION_TYPE_NONE &&
+           wimlib_get_compression_type(lte->wim) == out_ctype)
+       {
+               flags |= WIMLIB_RESOURCE_FLAG_RAW;
+               write_ctx.doing_sha = false;
+               read_size = lte->resource_entry.size;
+       } else {
+               write_ctx.doing_sha = true;
+               sha1_init(&write_ctx.sha_ctx);
+               read_size = lte->resource_entry.original_size;
+       }
 
-               u64 uncompressed_offset = i * WIM_CHUNK_SIZE;
-               u64 uncompressed_chunk_size = min(WIM_CHUNK_SIZE, 
-                                       original_size - uncompressed_offset);
+       /* Initialize the chunk table and set the compression function if
+        * compressing the resource. */
+       if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
+           (flags & WIMLIB_RESOURCE_FLAG_RAW)) {
+               write_ctx.compress = NULL;
+               write_ctx.chunk_tab = NULL;
+       } else {
+               write_ctx.compress = get_compress_func(out_ctype);
+               ret = begin_wim_resource_chunk_tab(lte, out_fp,
+                                                  offset,
+                                                  &write_ctx.chunk_tab);
+               if (ret)
+                       return ret;
+       }
 
-               const u8 *uncompressed_p;
-               if (uncompressed_resource != NULL) {
-                       uncompressed_p = uncompressed_resource + 
-                                                       uncompressed_offset;
+       /* Write the entire resource by reading the entire resource and feeding
+        * the data through the write_resource_cb function. */
+       write_ctx.out_fp = out_fp;
+try_write_again:
+       ret = read_resource_prefix(lte, read_size,
+                                  write_resource_cb, &write_ctx, flags);
+       if (ret)
+               goto out_free_chunk_tab;
+
+       /* Verify SHA1 message digest of the resource, or set the hash for the
+        * first time. */
+       if (write_ctx.doing_sha) {
+               ret = finalize_and_check_sha1(&write_ctx.sha_ctx, lte);
+               if (ret)
+                       goto out_free_chunk_tab;
+       }
 
-               } else {
-                       /* Read chunk i of the file into uncompressed_buf. */
-                       ret = read_resource(in, size, original_size, offset, input_ctype, 
-                                               uncompressed_chunk_size, 
-                                               uncompressed_offset, 
-                                               uncompressed_buf);
-                       if (ret != 0)
-                               return ret;
-                       uncompressed_p = uncompressed_buf;
+       out_res_entry->flags = lte->resource_entry.flags;
+       out_res_entry->original_size = wim_resource_size(lte);
+       out_res_entry->offset = offset;
+       if (flags & WIMLIB_RESOURCE_FLAG_RAW) {
+               /* Doing a raw write:  The new compressed size is the same as
+                * the compressed size in the other WIM. */
+               new_size = lte->resource_entry.size;
+       } else if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE) {
+               /* Using WIMLIB_COMPRESSION_TYPE_NONE:  The new compressed size
+                * is the original size. */
+               new_size = lte->resource_entry.original_size;
+               out_res_entry->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
+       } else {
+               /* Using a different compression type:  Call
+                * finish_wim_resource_chunk_tab() and it will provide the new
+                * compressed size. */
+               ret = finish_wim_resource_chunk_tab(write_ctx.chunk_tab, out_fp,
+                                                   &new_size);
+               if (ret)
+                       goto out_free_chunk_tab;
+               if (new_size >= wim_resource_size(lte)) {
+                       /* Oops!  We compressed the resource to larger than the original
+                        * size.  Write the resource uncompressed instead. */
+                       if (fseeko(out_fp, offset, SEEK_SET) ||
+                           fflush(out_fp) ||
+                           ftruncate(fileno(out_fp),
+                                     offset + wim_resource_size(lte)))
+                       {
+                               ERROR_WITH_ERRNO("Failed to flush and/or truncate "
+                                                "output WIM file");
+                               ret = WIMLIB_ERR_WRITE;
+                               goto out_free_chunk_tab;
+                       }
+                       DEBUG("Compressed %"PRIu64" => %"PRIu64" bytes; "
+                             "writing uncompressed instead",
+                             wim_resource_size(lte), new_size);
+                       write_ctx.compress = NULL;
+                       write_ctx.doing_sha = false;
+                       out_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
+                       goto try_write_again;
                }
+               out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
+       }
+       out_res_entry->size = new_size;
+       ret = 0;
+out_free_chunk_tab:
+       FREE(write_ctx.chunk_tab);
+       return ret;
+}
+
+#ifdef ENABLE_MULTITHREADED_COMPRESSION
+
+/* Blocking shared queue (solves the producer-consumer problem) */
+struct shared_queue {
+       unsigned size;
+       unsigned front;
+       unsigned back;
+       unsigned filled_slots;
+       void **array;
+       pthread_mutex_t lock;
+       pthread_cond_t msg_avail_cond;
+       pthread_cond_t space_avail_cond;
+};
+
+static int
+shared_queue_init(struct shared_queue *q, unsigned size)
+{
+       wimlib_assert(size != 0);
+       q->array = CALLOC(sizeof(q->array[0]), size);
+       if (!q->array)
+               return WIMLIB_ERR_NOMEM;
+       q->filled_slots = 0;
+       q->front = 0;
+       q->back = size - 1;
+       q->size = size;
+       pthread_mutex_init(&q->lock, NULL);
+       pthread_cond_init(&q->msg_avail_cond, NULL);
+       pthread_cond_init(&q->space_avail_cond, NULL);
+       return 0;
+}
+
+static void
+shared_queue_destroy(struct shared_queue *q)
+{
+       FREE(q->array);
+       pthread_mutex_destroy(&q->lock);
+       pthread_cond_destroy(&q->msg_avail_cond);
+       pthread_cond_destroy(&q->space_avail_cond);
+}
+
+static void
+shared_queue_put(struct shared_queue *q, void *obj)
+{
+       pthread_mutex_lock(&q->lock);
+       while (q->filled_slots == q->size)
+               pthread_cond_wait(&q->space_avail_cond, &q->lock);
 
-               if (i != 0)
-                       chunk_offsets[i - 1] = cur_chunk_offset;
+       q->back = (q->back + 1) % q->size;
+       q->array[q->back] = obj;
+       q->filled_slots++;
 
-               uint compressed_len;
+       pthread_cond_broadcast(&q->msg_avail_cond);
+       pthread_mutex_unlock(&q->lock);
+}
+
+static void *
+shared_queue_get(struct shared_queue *q)
+{
+       void *obj;
+
+       pthread_mutex_lock(&q->lock);
+       while (q->filled_slots == 0)
+               pthread_cond_wait(&q->msg_avail_cond, &q->lock);
 
-               ret = compress(uncompressed_p, uncompressed_chunk_size, 
-                              compressed_buf, &compressed_len);
+       obj = q->array[q->front];
+       q->array[q->front] = NULL;
+       q->front = (q->front + 1) % q->size;
+       q->filled_slots--;
 
-               /* if compress() returned nonzero, the compressed chunk would
-                * have been at least as large as the uncompressed chunk.  In
-                * this situation, the WIM format requires that the uncompressed
-                * chunk be written instead. */
-               const u8 *buf_to_write;
-               uint len_to_write;
-               if (ret == 0) {
-                       buf_to_write = compressed_buf;
-                       len_to_write = compressed_len;
+       pthread_cond_broadcast(&q->space_avail_cond);
+       pthread_mutex_unlock(&q->lock);
+       return obj;
+}
+
+struct compressor_thread_params {
+       struct shared_queue *res_to_compress_queue;
+       struct shared_queue *compressed_res_queue;
+       compress_func_t compress;
+};
+
+#define MAX_CHUNKS_PER_MSG 2
+
+struct message {
+       struct wim_lookup_table_entry *lte;
+       u8 *uncompressed_chunks[MAX_CHUNKS_PER_MSG];
+       u8 *out_compressed_chunks[MAX_CHUNKS_PER_MSG];
+       u8 *compressed_chunks[MAX_CHUNKS_PER_MSG];
+       unsigned uncompressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
+       unsigned compressed_chunk_sizes[MAX_CHUNKS_PER_MSG];
+       unsigned num_chunks;
+       struct list_head list;
+       bool complete;
+       u64 begin_chunk;
+};
+
+static void
+compress_chunks(struct message *msg, compress_func_t compress)
+{
+       for (unsigned i = 0; i < msg->num_chunks; i++) {
+               DEBUG2("compress chunk %u of %u", i, msg->num_chunks);
+               unsigned len = compress(msg->uncompressed_chunks[i],
+                                       msg->uncompressed_chunk_sizes[i],
+                                       msg->compressed_chunks[i]);
+               if (len) {
+                       /* To be written compressed */
+                       msg->out_compressed_chunks[i] = msg->compressed_chunks[i];
+                       msg->compressed_chunk_sizes[i] = len;
                } else {
-                       buf_to_write = uncompressed_p;
-                       len_to_write = uncompressed_chunk_size;
-               }
+                       /* To be written uncompressed */
+                       msg->out_compressed_chunks[i] = msg->uncompressed_chunks[i];
+                       msg->compressed_chunk_sizes[i] = msg->uncompressed_chunk_sizes[i];
 
-               if (fwrite(buf_to_write, 1, len_to_write, out) != len_to_write) {
-                       ERROR("Failed to write compressed file resource: %m\n");
-                       return WIMLIB_ERR_WRITE;
                }
-               cur_chunk_offset += len_to_write;
        }
+}
 
-       /* The chunk offset after the last chunk, plus the size of the chunk
-        * table, gives the total compressed size of the resource. */
-       *new_size_ret = cur_chunk_offset + chunk_tab_size;
-
-       /* Now that all entries of the chunk table are determined, rewind the
-        * stream to where the chunk table was, and write it back out. */
+/* Compressor thread routine.  This is a lot simpler than the main thread
+ * routine: just repeatedly get a group of chunks from the
+ * res_to_compress_queue, compress them, and put them in the
+ * compressed_res_queue.  A NULL pointer indicates that the thread should stop.
+ * */
+static void *
+compressor_thread_proc(void *arg)
+{
+       struct compressor_thread_params *params = arg;
+       struct shared_queue *res_to_compress_queue = params->res_to_compress_queue;
+       struct shared_queue *compressed_res_queue = params->compressed_res_queue;
+       compress_func_t compress = params->compress;
+       struct message *msg;
+
+       DEBUG("Compressor thread ready");
+       while ((msg = shared_queue_get(res_to_compress_queue)) != NULL) {
+               compress_chunks(msg, compress);
+               shared_queue_put(compressed_res_queue, msg);
+       }
+       DEBUG("Compressor thread terminating");
+       return NULL;
+}
+#endif /* ENABLE_MULTITHREADED_COMPRESSION */
 
-       if (fseeko(out, chunk_tab_offset, SEEK_SET) != 0) {
-               ERROR("Failed to seek to beginning of chunk table: %m\n");
-               return WIMLIB_ERR_READ;
+static void
+do_write_streams_progress(union wimlib_progress_info *progress,
+                         wimlib_progress_func_t progress_func,
+                         uint64_t size_added)
+{
+       progress->write_streams.completed_bytes += size_added;
+       progress->write_streams.completed_streams++;
+       if (progress_func &&
+           progress->write_streams.completed_bytes >= progress->write_streams._private)
+       {
+               progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
+                             progress);
+               if (progress->write_streams._private == progress->write_streams.total_bytes) {
+                       progress->write_streams._private = ~0;
+               } else {
+                       progress->write_streams._private =
+                               min(progress->write_streams.total_bytes,
+                                   progress->write_streams.completed_bytes +
+                                       progress->write_streams.total_bytes / 100);
+               }
        }
+}
 
-       if (chunk_entry_size == 8) {
-               array_to_le64(chunk_offsets, num_chunk_entries);
+static int
+do_write_stream_list(struct list_head *stream_list,
+                    struct wim_lookup_table *lookup_table,
+                    FILE *out_fp,
+                    int out_ctype,
+                    int write_resource_flags,
+                    wimlib_progress_func_t progress_func,
+                    union wimlib_progress_info *progress)
+{
+       int ret = 0;
+       struct wim_lookup_table_entry *lte;
+
+       /* For each stream in @stream_list ... */
+       while (!list_empty(stream_list)) {
+               lte = container_of(stream_list->next,
+                                  struct wim_lookup_table_entry,
+                                  write_streams_list);
+               list_del(&lte->write_streams_list);
+               if (lte->unhashed && !lte->unique_size) {
+                       /* Unhashed stream that shares a size with some other
+                        * stream in the WIM we are writing.  The stream must be
+                        * checksummed to know if we need to write it or not. */
+                       struct wim_lookup_table_entry *tmp;
+                       u32 orig_refcnt = lte->out_refcnt;
+
+                       ret = hash_unhashed_stream(lte,
+                                                  lookup_table,
+                                                  &tmp);
+                       if (ret)
+                               break;
+                       if (tmp != lte) {
+                               lte = tmp;
+                               /* We found a duplicate stream. */
+                               if (orig_refcnt != tmp->out_refcnt) {
+                                       /* We have already written, or are going
+                                        * to write, the duplicate stream.  So
+                                        * just skip to the next stream. */
+                                       DEBUG("Discarding duplicate stream of length %"PRIu64,
+                                             wim_resource_size(lte));
+                                       goto skip_to_progress;
+                               }
+                       }
+               }
 
-               if (fwrite(chunk_offsets, 1, chunk_tab_size, out) != 
-                               chunk_tab_size) {
-                       ERROR("Failed to write chunk table: %m\n");
-                       return WIMLIB_ERR_WRITE;
+               /* Here, @lte is either a hashed stream or an unhashed stream
+                * with a unique size.  In either case we know that the stream
+                * has to be written.  In either case the SHA1 message digest
+                * will be calculated over the stream while writing it; however,
+                * in the former case this is done merely to check the data,
+                * while in the latter case this is done because we do not have
+                * the SHA1 message digest yet.  */
+               wimlib_assert(lte->out_refcnt != 0);
+               ret = write_wim_resource(lte,
+                                        out_fp,
+                                        out_ctype,
+                                        &lte->output_resource_entry,
+                                        write_resource_flags);
+               if (ret)
+                       break;
+               if (lte->unhashed) {
+                       list_del(&lte->unhashed_list);
+                       lookup_table_insert(lookup_table, lte);
+                       lte->unhashed = 0;
                }
-       } else {
-               u32 chunk_entries_small[num_chunk_entries];
-               for (u64 i = 0; i < num_chunk_entries; i++)
-                       chunk_entries_small[i] = to_le32(chunk_offsets[i]);
-               if (fwrite(chunk_entries_small, 1, chunk_tab_size, out) != 
-                               chunk_tab_size) {
-                       ERROR("Failed to write chunk table: %m\n");
+       skip_to_progress:
+               do_write_streams_progress(progress,
+                                         progress_func,
+                                         wim_resource_size(lte));
+       }
+       return ret;
+}
+
+static int
+write_stream_list_serial(struct list_head *stream_list,
+                        struct wim_lookup_table *lookup_table,
+                        FILE *out_fp,
+                        int out_ctype,
+                        int write_flags,
+                        wimlib_progress_func_t progress_func,
+                        union wimlib_progress_info *progress)
+{
+       int write_resource_flags = 0;
+       if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
+               write_resource_flags |= WIMLIB_RESOURCE_FLAG_RECOMPRESS;
+
+       progress->write_streams.num_threads = 1;
+       if (progress_func)
+               progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
+       return do_write_stream_list(stream_list,
+                                   lookup_table,
+                                   out_fp,
+                                   out_ctype,
+                                   write_resource_flags,
+                                   progress_func,
+                                   progress);
+}
+
+#ifdef ENABLE_MULTITHREADED_COMPRESSION
+static int
+write_wim_chunks(struct message *msg, FILE *out_fp,
+                struct chunk_table *chunk_tab)
+{
+       for (unsigned i = 0; i < msg->num_chunks; i++) {
+               unsigned chunk_csize = msg->compressed_chunk_sizes[i];
+
+               DEBUG2("Write wim chunk %u of %u (csize = %u)",
+                     i, msg->num_chunks, chunk_csize);
+
+               if (fwrite(msg->out_compressed_chunks[i], 1, chunk_csize, out_fp)
+                   != chunk_csize)
+               {
+                       ERROR_WITH_ERRNO("Failed to write WIM chunk");
                        return WIMLIB_ERR_WRITE;
                }
-       }
 
-       if (fseeko(out, 0, SEEK_END) != 0) {
-               ERROR("Failed to seek to end of output file: %m\n");
-               return WIMLIB_ERR_WRITE;
+               *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
+               chunk_tab->cur_offset += chunk_csize;
        }
+       return 0;
+}
 
+struct main_writer_thread_ctx {
+       struct list_head *stream_list;
+       struct wim_lookup_table *lookup_table;
+       FILE *out_fp;
+       int out_ctype;
+       struct shared_queue *res_to_compress_queue;
+       struct shared_queue *compressed_res_queue;
+       size_t num_messages;
+       int write_flags;
+       wimlib_progress_func_t progress_func;
+       union wimlib_progress_info *progress;
+
+       struct list_head available_msgs;
+       struct list_head outstanding_streams;
+       struct list_head serial_streams;
+       u64 next_chunk;
+       u64 next_num_chunks;
+       struct message *msgs;
+       struct message *next_msg;
+       size_t next_chunk_in_msg;
+       struct wim_lookup_table_entry *cur_lte;
+       struct chunk_table *cur_chunk_tab;
+       struct wim_lookup_table_entry *next_lte;
+       SHA_CTX sha_ctx;
+       u8 next_hash[20];
+};
+
+static int
+init_message(struct message *msg)
+{
+       for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
+               msg->compressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
+               msg->uncompressed_chunks[i] = MALLOC(WIM_CHUNK_SIZE);
+               if (msg->compressed_chunks[i] == NULL ||
+                   msg->uncompressed_chunks[i] == NULL)
+                       return WIMLIB_ERR_NOMEM;
+       }
        return 0;
 }
 
-int write_resource_from_memory(const u8 resource[], int out_ctype,
-                              u64 resource_original_size, FILE *out,
-                              u64 *resource_size_ret)
+static void
+destroy_message(struct message *msg)
 {
-       if (out_ctype == WIM_COMPRESSION_TYPE_NONE) {
-               if (fwrite(resource, 1, resource_original_size, out) != 
-                                       resource_original_size) {
-                       ERROR("Failed to write resource of length "
-                                       "%"PRIu64": %m\n", 
-                                       resource_original_size);
-                       return WIMLIB_ERR_WRITE;
+       for (size_t i = 0; i < MAX_CHUNKS_PER_MSG; i++) {
+               FREE(msg->compressed_chunks[i]);
+               FREE(msg->uncompressed_chunks[i]);
+       }
+}
+
+static void
+free_messages(struct message *msgs, size_t num_messages)
+{
+       if (msgs) {
+               for (size_t i = 0; i < num_messages; i++)
+                       destroy_message(&msgs[i]);
+               FREE(msgs);
+       }
+}
+
+static struct message *
+allocate_messages(size_t num_messages)
+{
+       struct message *msgs;
+
+       msgs = CALLOC(num_messages, sizeof(struct message));
+       if (!msgs)
+               return NULL;
+       for (size_t i = 0; i < num_messages; i++) {
+               if (init_message(&msgs[i])) {
+                       free_messages(msgs, num_messages);
+                       return NULL;
                }
-               *resource_size_ret = resource_original_size;
-               return 0;
-       } else {
-               return recompress_resource(NULL, resource, resource_original_size,
-                               resource_original_size, 0, 0, out, out_ctype, 
-                                                       resource_size_ret);
-       }
-}
-
-
-/* 
- * Transfers a file resource from a FILE* opened for reading to a FILE* opened
- * for writing, possibly changing the compression type. 
- *
- * @in:                        The FILE* that contains the file resource.
- * @size:              The (compressed) size of the file resource.
- * @original_size:     The uncompressed size of the file resource.
- * @offset:            The offset of the file resource in the input file.
- * @input_ctype:       The compression type of the file resource in the input
- *                             file.
- * @out:               The FILE* for the output file.  The file resource is 
- *                             written at the current position of @out.
- * @output_ctype:      The compression type to which the file resource will be
- *                             converted.
- * @output_res_entry:  A pointer to a resource entry that, upon successful
- *                             return of this function,  will have the size,
- *                             original size, offset, and flags fields filled
- *                             in for the file resource written to the output
- *                             file.
- */
-static int transfer_file_resource(FILE *in, u64 size, u64 original_size, 
-                                 off_t offset, int input_ctype, FILE *out, 
-                                 int output_ctype, 
-                                 struct resource_entry *output_res_entry)
+       }
+       return msgs;
+}
+
+static void
+main_writer_thread_destroy_ctx(struct main_writer_thread_ctx *ctx)
+{
+       free_messages(ctx->msgs, ctx->num_messages);
+       FREE(ctx->cur_chunk_tab);
+}
+
+
+static int
+main_writer_thread_init_ctx(struct main_writer_thread_ctx *ctx)
+{
+       /* Pre-allocate all the buffers that will be needed to do the chunk
+        * compression. */
+       ctx->msgs = allocate_messages(ctx->num_messages);
+       if (!ctx->msgs)
+               return WIMLIB_ERR_NOMEM;
+
+       /* Initially, all the messages are available to use. */
+       INIT_LIST_HEAD(&ctx->available_msgs);
+       for (size_t i = 0; i < ctx->num_messages; i++)
+               list_add_tail(&ctx->msgs[i].list, &ctx->available_msgs);
+
+       /* outstanding_streams is the list of streams that currently have had
+        * chunks sent off for compression.
+        *
+        * The first stream in outstanding_streams is the stream that is
+        * currently being written (cur_lte).
+        *
+        * The last stream in outstanding_streams is the stream that is
+        * currently being read and chunks fed to the compressor threads.  */
+       INIT_LIST_HEAD(&ctx->outstanding_streams);
+
+       /* Resources that don't need any chunks compressed are added to this
+        * list and written directly by the main thread. */
+       INIT_LIST_HEAD(&ctx->serial_streams);
+
+       ctx->cur_lte = NULL;
+       return 0;
+}
+
+static int
+receive_compressed_chunks(struct main_writer_thread_ctx *ctx)
 {
+       struct message *msg;
+       struct wim_lookup_table_entry *cur_lte;
        int ret;
 
-       /* Handle zero-length files */
-       if (original_size == 0) {
-               memset(output_res_entry, 0, sizeof(*output_res_entry));
-               return 0;
-       }
+       wimlib_assert(!list_empty(&ctx->outstanding_streams));
+
+       /* Get the next message from the queue and process it.
+        * The message will contain 1 or more data chunks that have been
+        * compressed. */
+       msg = shared_queue_get(ctx->compressed_res_queue);
+       msg->complete = true;
+       cur_lte = ctx->cur_lte;
+
+       /* Is this the next chunk in the current resource?  If it's not
+        * (i.e., an earlier chunk in a same or different resource
+        * hasn't been compressed yet), do nothing, and keep this
+        * message around until all earlier chunks are received.
+        *
+        * Otherwise, write all the chunks we can. */
+       while (cur_lte != NULL &&
+              !list_empty(&cur_lte->msg_list) &&
+              (msg = container_of(cur_lte->msg_list.next,
+                                  struct message,
+                                  list))->complete)
+       {
+               if (msg->begin_chunk == 0) {
+
+                       /* This is the first set of chunks.  Leave space
+                        * for the chunk table in the output file. */
+                       off_t cur_offset = ftello(ctx->out_fp);
+                       if (cur_offset == -1) {
+                               ret = WIMLIB_ERR_WRITE;
+                               goto out;
+                       }
+                       ret = begin_wim_resource_chunk_tab(cur_lte,
+                                                          ctx->out_fp,
+                                                          cur_offset,
+                                                          &ctx->cur_chunk_tab);
+                       if (ret)
+                               goto out;
+               }
 
-       /* Get current offset in the output file. */
-       output_res_entry->offset = ftello(out);
-       if (output_res_entry->offset == -1) {
-               ERROR("Failed to get output position: %m\n");
-               return WIMLIB_ERR_WRITE;
+               /* Write the compressed chunks from the message. */
+               ret = write_wim_chunks(msg, ctx->out_fp, ctx->cur_chunk_tab);
+               if (ret)
+                       goto out;
+
+               list_del(&msg->list);
+
+               /* This message is available to use for different chunks
+                * now. */
+               list_add(&msg->list, &ctx->available_msgs);
+
+               /* Was this the last chunk of the stream?  If so, finish
+                * it. */
+               if (list_empty(&cur_lte->msg_list) &&
+                   msg->begin_chunk + msg->num_chunks == ctx->cur_chunk_tab->num_chunks)
+               {
+                       DEBUG2("Finish wim chunk tab");
+                       u64 res_csize;
+                       ret = finish_wim_resource_chunk_tab(ctx->cur_chunk_tab,
+                                                           ctx->out_fp,
+                                                           &res_csize);
+                       if (ret)
+                               goto out;
+
+#if 0
+                       if (res_csize >= wim_resource_size(cur_lte)) {
+                               /* Oops!  We compressed the resource to
+                                * larger than the original size.  Write
+                                * the resource uncompressed instead. */
+                               ret = write_uncompressed_resource_and_truncate(
+                                                cur_lte,
+                                                ctx->out_fp,
+                                                ctx->cur_chunk_tab->file_offset,
+                                                &cur_lte->output_resource_entry);
+                               if (ret)
+                                       goto out;
+                       } else
+#endif
+                       {
+                               cur_lte->output_resource_entry.size =
+                                       res_csize;
+
+                               cur_lte->output_resource_entry.original_size =
+                                       cur_lte->resource_entry.original_size;
+
+                               cur_lte->output_resource_entry.offset =
+                                       ctx->cur_chunk_tab->file_offset;
+
+                               cur_lte->output_resource_entry.flags =
+                                       cur_lte->resource_entry.flags |
+                                               WIM_RESHDR_FLAG_COMPRESSED;
+                       }
+                       do_write_streams_progress(ctx->progress, ctx->progress_func,
+                                                 wim_resource_size(cur_lte));
+                       FREE(ctx->cur_chunk_tab);
+                       ctx->cur_chunk_tab = NULL;
+
+                       struct list_head *next = cur_lte->write_streams_list.next;
+                       list_del(&cur_lte->write_streams_list);
+
+                       if (next == &ctx->outstanding_streams)
+                               cur_lte = NULL;
+                       else
+                               cur_lte = container_of(cur_lte->write_streams_list.next,
+                                                      struct wim_lookup_table_entry,
+                                                      write_streams_list);
+
+                       /* Since we just finished writing a stream, write any
+                        * streams that have been added to the serial_streams
+                        * list for direct writing by the main thread (e.g.
+                        * resources that don't need to be compressed because
+                        * the desired compression type is the same as the
+                        * previous compression type). */
+                       ret = do_write_stream_list(&ctx->serial_streams,
+                                                  ctx->lookup_table,
+                                                  ctx->out_fp,
+                                                  ctx->out_ctype,
+                                                  ctx->progress_func,
+                                                  ctx->progress,
+                                                  0);
+                       if (ret)
+                               goto out;
+               }
        }
+out:
+       ctx->cur_lte = cur_lte;
+       return ret;
+}
 
-       if (output_ctype == input_ctype) {
-               /* The same compression types; simply copy the resource. */
+static int
+main_writer_thread_cb(const void *chunk, size_t chunk_size, void *_ctx)
+{
+       struct main_writer_thread_ctx *ctx = _ctx;
+       int ret;
+       struct message *next_msg;
 
-               ret = copy_between_files(in, offset, out, size);
-               if (ret != 0)
-                       return ret;
-               output_res_entry->size = size;
-       } else {
-               /* Different compression types. */
-
-               if (output_ctype == WIM_COMPRESSION_TYPE_NONE) {
-                       /* Uncompress a compressed file resource */
-                       ret = uncompress_resource(in, size,
-                                               original_size, offset, 
-                                               input_ctype, out);
-                       if (ret != 0)
-                               return ret;
-                       output_res_entry->size = original_size;
-               } else {
-                       u64 new_size;
-                       /* Compress an uncompressed file resource, or compress a
-                        * compressed file resource using a different
-                        * compression type (the latter is currently unsupported
-                        * since only LZX compression is supported. */
-                       ret = recompress_resource(in, NULL, size, original_size,
-                                               offset, input_ctype, out, 
-                                               output_ctype, &new_size);
-                       if (ret != 0)
+       next_msg = ctx->next_msg;
+
+       sha1_update(&ctx->sha_ctx, chunk, chunk_size);
+
+       if (!next_msg) {
+               if (list_empty(&ctx->available_msgs)) {
+                       ret = receive_compressed_chunks(ctx);
+                       if (ret)
                                return ret;
-                       output_res_entry->size = new_size;
                }
 
+               wimlib_assert(!list_empty(&ctx->available_msgs));
+
+               next_msg = container_of(ctx->available_msgs.next,
+                                      struct message,
+                                      list);
+               list_del(&next_msg->list);
+               next_msg->complete = false;
+               next_msg->begin_chunk = ctx->next_chunk;
+               next_msg->num_chunks = min(MAX_CHUNKS_PER_MSG,
+                                          ctx->next_num_chunks - ctx->next_chunk);
+               ctx->next_chunk_in_msg = 0;
        }
 
-       output_res_entry->original_size = original_size;
-       if (output_ctype == WIM_COMPRESSION_TYPE_NONE)
-               output_res_entry->flags = 0;
-       else
-               output_res_entry->flags = WIM_RESHDR_FLAG_COMPRESSED;
+       wimlib_assert(next_msg != NULL);
+       wimlib_assert(ctx->next_chunk_in_msg < next_msg->num_chunks);
+
+       next_msg->uncompressed_chunk_sizes[ctx->next_chunk_in_msg] = chunk_size;
+       memcpy(next_msg->uncompressed_chunks[ctx->next_chunk_in_msg],
+              chunk, chunk_size);
+
+       if (++ctx->next_chunk_in_msg == next_msg->num_chunks) {
+               shared_queue_put(ctx->res_to_compress_queue,
+                                next_msg);
+               ctx->next_msg = NULL;
+       }
        return 0;
 }
 
-/* 
- * Writes a file resource to the output file. 
+static int
+submit_stream_for_compression(struct wim_lookup_table_entry *lte,
+                             struct main_writer_thread_ctx *ctx)
+{
+       int ret;
+
+       sha1_init(&ctx->sha_ctx);
+       ctx->next_num_chunks = wim_resource_chunks(lte);
+       ret = read_resource_prefix(lte, wim_resource_size(lte),
+                                  main_writer_thread_cb, ctx, 0);
+       if (ret)
+               return ret;
+       ret = finalize_and_check_sha1(&ctx->sha_ctx, lte);
+       if (ret)
+               return ret;
+}
+
+/*
+ * This function is executed by the main thread when the resources are being
+ * compressed in parallel.  The main thread is in change of all reading of the
+ * uncompressed data and writing of the compressed data.  The compressor threads
+ * *only* do compression from/to in-memory buffers.
  *
- * @dentry:  The dentry for the file resource.
- * @wim_p:  A pointer to the WIMStruct.  The fields of interest to this
- *     function are the input and output file streams and the lookup table. 
- * @return zero on success, nonzero on failure. 
+ * Each unit of work given to a compressor thread is up to MAX_CHUNKS_PER_MSG
+ * chunks of compressed data to compress, represented in a `struct message'.
+ * Each message is passed from the main thread to a worker thread through the
+ * res_to_compress_queue, and it is passed back through the
+ * compressed_res_queue.
  */
-static int write_file_resource(struct dentry *dentry, void *wim_p)
-{
-       WIMStruct *w;
-       FILE *out;
-       FILE *in;
-       struct lookup_table_entry *lte;
-       int in_wim_ctype;
-       int out_wim_ctype;
-       int input_res_ctype;
-       struct resource_entry *input_res_entry;
-       struct resource_entry *output_res_entry;
-       u64 len;
+static int
+main_writer_thread_proc(struct main_writer_thread_ctx *ctx)
+{
        int ret;
+       struct list_head *stream_list;
+       struct wim_lookup_table_entry *lte;
+
+       ret = main_writer_thread_init_ctx(ctx);
+       if (ret)
+               goto out_destroy_ctx;
+
+       stream_list = ctx->stream_list;
+       while (!list_empty(stream_list)) {
+               lte = container_of(stream_list->next,
+                                  struct wim_lookup_table_entry,
+                                  write_streams_list);
+               list_del(&lte->write_streams_list);
+               if (lte->unhashed && !lte->unique_size) {
+                       struct wim_lookup_table_entry *tmp;
+                       u32 orig_refcnt = lte->out_refcnt;
+
+                       ret = hash_unhashed_stream(lte, ctx->lookup_table, &tmp);
+                       if (ret)
+                               goto out_destroy_ctx;
+                       if (tmp != lte) {
+                               lte = tmp;
+                               if (orig_refcnt != tmp->out_refcnt) {
+                                       DEBUG("Discarding duplicate stream of length %"PRIu64,
+                                             wim_resource_size(lte));
+                                       goto skip_to_progress;
+                               }
+                       }
+               }
 
-       w = wim_p;
-       out = w->out_fp;
+               if (wim_resource_size(lte) < 1000 ||
+                   ctx->out_ctype == WIMLIB_COMPRESSION_TYPE_NONE ||
+                   (lte->resource_location == RESOURCE_IN_WIM &&
+                    wimlib_get_compression_type(lte->wim) == ctx->out_ctype))
+               {
+                       list_add(&lte->write_streams_list,
+                                &ctx->serial_streams);
+               } else {
+                       ret = submit_stream_for_compression(lte, ctx);
+                       if (ret)
+                               goto out_destroy_ctx;
+                       if (lte->unhashed) {
+                               list_del(&lte->unhashed_list);
+                               lookup_table_insert(ctx->lookup_table, lte);
+                               lte->unhashed = 0;
+                       }
+               }
+       skip_to_progress:
+               do_write_streams_progress(ctx->progress,
+                                         ctx->progress_func,
+                                         wim_resource_size(lte));
+       }
 
-       /* Directories don't need file resources. */
-       if (dentry_is_directory(dentry))
-               return 0;
+       while (!list_empty(&ctx->outstanding_streams)) {
+               ret = receive_compressed_chunks(ctx);
+               if (ret)
+                       goto out_destroy_ctx;
+       }
+       ret = 0;
+out_destroy_ctx:
+       main_writer_thread_destroy_ctx(ctx);
+       return ret;
+}
 
-       /* Get the lookup entry for the file resource. */
-       lte = wim_lookup_resource(w, dentry);
-       if (!lte)
-               return 0;
+static long
+get_default_num_threads()
+{
+#ifdef __WIN32__
+       return win32_get_number_of_processors();
+#else
+       return sysconf(_SC_NPROCESSORS_ONLN);
+#endif
+}
 
-       /* No need to write file resources twice.  (This indicates file
-        * resources that are part of a hard link set.) */
-       if (++lte->out_refcnt != 1)
-               return 0;
+static int
+write_stream_list_parallel(struct list_head *stream_list,
+                          struct wim_lookup_table *lookup_table,
+                          FILE *out_fp,
+                          int out_ctype,
+                          int write_flags,
+                          unsigned num_threads,
+                          wimlib_progress_func_t progress_func,
+                          union wimlib_progress_info *progress)
+{
+       int ret;
+       struct shared_queue res_to_compress_queue;
+       struct shared_queue compressed_res_queue;
+       pthread_t *compressor_threads = NULL;
+
+       if (num_threads == 0) {
+               long nthreads = get_default_num_threads();
+               if (nthreads < 1 || nthreads > UINT_MAX) {
+                       WARNING("Could not determine number of processors! Assuming 1");
+                       goto out_serial;
+               } else {
+                       num_threads = nthreads;
+               }
+       }
+
+       progress->write_streams.num_threads = num_threads;
+
+       static const double MESSAGES_PER_THREAD = 2.0;
+       size_t queue_size = (size_t)(num_threads * MESSAGES_PER_THREAD);
+
+       DEBUG("Initializing shared queues (queue_size=%zu)", queue_size);
+
+       ret = shared_queue_init(&res_to_compress_queue, queue_size);
+       if (ret != 0)
+               goto out_serial;
 
-       out_wim_ctype = wimlib_get_compression_type(w);
-       output_res_entry = &lte->output_resource_entry;
+       ret = shared_queue_init(&compressed_res_queue, queue_size);
+       if (ret != 0)
+               goto out_destroy_res_to_compress_queue;
 
-       /* Figure out if we can read the resource from the WIM file, or
-        * if we have to read it from the filesystem outside. */
-       if (lte->file_on_disk) {
+       struct compressor_thread_params params;
+       params.res_to_compress_queue = &res_to_compress_queue;
+       params.compressed_res_queue = &compressed_res_queue;
+       params.compress = get_compress_func(out_ctype);
 
-               /* Read from disk (uncompressed) */
+       compressor_threads = MALLOC(num_threads * sizeof(pthread_t));
+       if (!compressor_threads) {
+               ret = WIMLIB_ERR_NOMEM;
+               goto out_destroy_compressed_res_queue;
+       }
 
-               len = lte->resource_entry.original_size;
+       for (unsigned i = 0; i < num_threads; i++) {
+               DEBUG("pthread_create thread %u", i);
+               ret = pthread_create(&compressor_threads[i], NULL,
+                                    compressor_thread_proc, &params);
+               if (ret != 0) {
+                       ret = -1;
+                       ERROR_WITH_ERRNO("Failed to create compressor "
+                                        "thread %u", i);
+                       num_threads = i;
+                       goto out_join;
+               }
+       }
 
-               in = fopen(lte->file_on_disk, "rb");
-               if (!in) {
-                       ERROR("Failed to open the file `%s': %m\n",
-                                       lte->file_on_disk);
-                       return WIMLIB_ERR_OPEN;
+       if (progress_func)
+               progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS, progress);
+
+       struct main_writer_thread_ctx ctx;
+       memset(&ctx, 0, sizeof(ctx));
+       ctx.stream_list           = stream_list;
+       ctx.lookup_table          = lookup_table;
+       ctx.out_fp                = out_fp;
+       ctx.out_ctype             = out_ctype;
+       ctx.res_to_compress_queue = &res_to_compress_queue;
+       ctx.compressed_res_queue  = &compressed_res_queue;
+       ctx.num_messages          = queue_size;
+       ctx.write_flags           = write_flags;
+       ctx.progress_func         = progress_func;
+       ctx.progress              = progress;
+       ret = main_writer_thread_proc(&ctx);
+out_join:
+       for (unsigned i = 0; i < num_threads; i++)
+               shared_queue_put(&res_to_compress_queue, NULL);
+
+       for (unsigned i = 0; i < num_threads; i++) {
+               if (pthread_join(compressor_threads[i], NULL)) {
+                       WARNING_WITH_ERRNO("Failed to join compressor "
+                                          "thread %u", i);
                }
+       }
+       FREE(compressor_threads);
+out_destroy_compressed_res_queue:
+       shared_queue_destroy(&compressed_res_queue);
+out_destroy_res_to_compress_queue:
+       shared_queue_destroy(&res_to_compress_queue);
+       if (ret >= 0 && ret != WIMLIB_ERR_NOMEM)
+               return ret;
+out_serial:
+       WARNING("Falling back to single-threaded compression");
+       return write_stream_list_serial(stream_list,
+                                       lookup_table,
+                                       out_fp,
+                                       out_ctype,
+                                       write_flags,
+                                       progress_func,
+                                       progress);
 
-               if (w->verbose)
-                       puts(lte->file_on_disk);
+}
+#endif
 
-               ret = transfer_file_resource(in, len, len, 0,
-                                            WIM_COMPRESSION_TYPE_NONE, out, 
-                                            out_wim_ctype, output_res_entry);
-               fclose(in);
-       } else {
+/*
+ * Write a list of streams to a WIM (@out_fp) using the compression type
+ * @out_ctype and up to @num_threads compressor threads.
+ */
+static int
+write_stream_list(struct list_head *stream_list,
+                 struct wim_lookup_table *lookup_table,
+                 FILE *out_fp, int out_ctype, int write_flags,
+                 unsigned num_threads, wimlib_progress_func_t progress_func)
+{
+       struct wim_lookup_table_entry *lte;
+       size_t num_streams = 0;
+       u64 total_bytes = 0;
+       u64 total_compression_bytes = 0;
+       union wimlib_progress_info progress;
+       int ret;
 
-               /* Read from input WIM (possibly compressed) */
+       if (list_empty(stream_list))
+               return 0;
 
-               /* It may be a different WIM file, in the case of
-                * exporting images from one WIM file to another */
-               if (lte->other_wim_fp) {
-                       /* Different WIM file. */
-                       in = lte->other_wim_fp;
-                       in_wim_ctype = lte->other_wim_ctype;
-               } else {
-                       /* Same WIM file. */
-                       in = w->fp;
-                       in_wim_ctype = out_wim_ctype;
+       /* Calculate the total size of the streams to be written.  Note: this
+        * will be the uncompressed size, as we may not know the compressed size
+        * yet, and also this will assume that every unhashed stream will be
+        * written (which will not necessarily be the case). */
+       list_for_each_entry(lte, stream_list, write_streams_list) {
+               num_streams++;
+               total_bytes += wim_resource_size(lte);
+               if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE
+                      && (wim_resource_compression_type(lte) != out_ctype ||
+                          (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)))
+               {
+                       total_compression_bytes += wim_resource_size(lte);
                }
-               input_res_entry = &lte->resource_entry;
-               input_res_ctype = resource_compression_type(
-                                       in_wim_ctype, 
-                                       input_res_entry->flags);
-
-               ret = transfer_file_resource(in, 
-                                       input_res_entry->size,
-                                       input_res_entry->original_size, 
-                                       input_res_entry->offset,
-                                       input_res_ctype, 
-                                       out, 
-                                       out_wim_ctype,
-                                       output_res_entry);
        }
+       progress.write_streams.total_bytes       = total_bytes;
+       progress.write_streams.total_streams     = num_streams;
+       progress.write_streams.completed_bytes   = 0;
+       progress.write_streams.completed_streams = 0;
+       progress.write_streams.num_threads       = num_threads;
+       progress.write_streams.compression_type  = out_ctype;
+       progress.write_streams._private          = 0;
+
+#ifdef ENABLE_MULTITHREADED_COMPRESSION
+       if (total_compression_bytes >= 1000000 && num_threads != 1)
+               ret = write_stream_list_parallel(stream_list,
+                                                lookup_table,
+                                                out_fp,
+                                                out_ctype,
+                                                write_flags,
+                                                num_threads,
+                                                progress_func,
+                                                &progress);
+       else
+#endif
+               ret = write_stream_list_serial(stream_list,
+                                              lookup_table,
+                                              out_fp,
+                                              out_ctype,
+                                              write_flags,
+                                              progress_func,
+                                              &progress);
        return ret;
 }
 
-/* Reopens the FILE* for a WIM read-write. */
-static int reopen_rw(WIMStruct *w)
+struct stream_size_table {
+       struct hlist_head *array;
+       size_t num_entries;
+       size_t capacity;
+};
+
+static int
+init_stream_size_table(struct stream_size_table *tab, size_t capacity)
+{
+       tab->array = CALLOC(capacity, sizeof(tab->array[0]));
+       if (!tab->array)
+               return WIMLIB_ERR_NOMEM;
+       tab->num_entries = 0;
+       tab->capacity = capacity;
+       return 0;
+}
+
+static void
+destroy_stream_size_table(struct stream_size_table *tab)
 {
-       FILE *fp;
+       FREE(tab->array);
+}
 
-       if (fclose(w->fp) != 0)
-               ERROR("Failed to close the file `%s': %m\n", w->filename);
-       fp = fopen(w->filename, "r+b");
-       if (!fp) {
-               ERROR("Failed to open `%s' for reading and writing: "
-                               "%m\n", w->filename);
-               return WIMLIB_ERR_OPEN;
+static int
+stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
+{
+       struct stream_size_table *tab = _tab;
+       size_t pos;
+       struct wim_lookup_table_entry *same_size_lte;
+       struct hlist_node *tmp;
+
+       pos = hash_u64(wim_resource_size(lte)) % tab->capacity;
+       lte->unique_size = 1;
+       hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
+               if (wim_resource_size(same_size_lte) == wim_resource_size(lte)) {
+                       lte->unique_size = 0;
+                       same_size_lte->unique_size = 0;
+                       break;
+               }
        }
-       w->fp = fp;
+
+       hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
+       tab->num_entries++;
        return 0;
 }
 
 
+struct lte_overwrite_prepare_args {
+       WIMStruct *wim;
+       off_t end_offset;
+       struct list_head stream_list;
+       struct stream_size_table stream_size_tab;
+};
+
+/* First phase of preparing streams for an in-place overwrite.  This is called
+ * on all streams, both hashed and unhashed, except the metadata resources. */
+static int
+lte_overwrite_prepare(struct wim_lookup_table_entry *lte, void *_args)
+{
+       struct lte_overwrite_prepare_args *args = _args;
 
-/* 
- * Writes a WIM file to the original file that it was read from, overwriting it.
+       wimlib_assert(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
+       if (lte->resource_location != RESOURCE_IN_WIM || lte->wim != args->wim)
+               list_add_tail(&lte->write_streams_list, &args->stream_list);
+       lte->out_refcnt = lte->refcnt;
+       stream_size_table_insert(lte, &args->stream_size_tab);
+       return 0;
+}
+
+/* Second phase of preparing streams for an in-place overwrite.  This is called
+ * on existing metadata resources and hashed streams, but not unhashed streams.
+ *
+ * NOTE: lte->output_resource_entry is in union with lte->hash_list_2, so
+ * lte_overwrite_prepare_2() must be called after lte_overwrite_prepare(), as
+ * the latter uses lte->hash_list_2, while the former expects to set
+ * lte->output_resource_entry. */
+static int
+lte_overwrite_prepare_2(struct wim_lookup_table_entry *lte, void *_args)
+{
+       struct lte_overwrite_prepare_args *args = _args;
+
+       if (lte->resource_location == RESOURCE_IN_WIM && lte->wim == args->wim) {
+               /* We can't do an in place overwrite on the WIM if there are
+                * streams after the XML data. */
+               if (lte->resource_entry.offset +
+                   lte->resource_entry.size > args->end_offset)
+               {
+               #ifdef ENABLE_ERROR_MESSAGES
+                       ERROR("The following resource is after the XML data:");
+                       print_lookup_table_entry(lte, stderr);
+               #endif
+                       return WIMLIB_ERR_RESOURCE_ORDER;
+               }
+               copy_resource_entry(&lte->output_resource_entry,
+                                   &lte->resource_entry);
+       }
+       return 0;
+}
+
+/* Given a WIM that we are going to overwrite in place with zero or more
+ * additional streams added, construct a list the list of new unique streams
+ * ('struct wim_lookup_table_entry's) that must be written, plus any unhashed
+ * streams that need to be added but may be identical to other hashed or
+ * unhashed streams.  These unhashed streams are checksummed while the streams
+ * are being written.  To aid this process, the member @unique_size is set to 1
+ * on streams that have a unique size and therefore must be written.
+ *
+ * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
+ * indicate the number of times the stream is referenced in only the streams
+ * that are being written; this may still be adjusted later when unhashed
+ * streams are being resolved.
  */
-WIMLIBAPI int wimlib_overwrite(WIMStruct *w, int flags)
+static int
+prepare_streams_for_overwrite(WIMStruct *wim, off_t end_offset,
+                             struct list_head *stream_list)
 {
-       const char *wimfile_name;
-       size_t wim_name_len;
        int ret;
-       
-       wimfile_name = w->filename;
+       struct lte_overwrite_prepare_args args;
+       unsigned i;
+
+       args.wim = wim;
+       args.end_offset = end_offset;
+       ret = init_stream_size_table(&args.stream_size_tab,
+                                    wim->lookup_table->capacity);
+       if (ret)
+               return ret;
 
-       DEBUG("Replacing WIM file `%s'\n", wimfile_name);
+       INIT_LIST_HEAD(&args.stream_list);
+       for (i = 0; i < wim->hdr.image_count; i++) {
+               struct wim_image_metadata *imd;
+               struct wim_lookup_table_entry *lte;
 
-       if (!wimfile_name)
-               return WIMLIB_ERR_NO_FILENAME;
+               imd = wim->image_metadata[i];
+               image_for_each_unhashed_stream(lte, imd)
+                       lte_overwrite_prepare(lte, &args);
+       }
+       for_lookup_table_entry(wim->lookup_table, lte_overwrite_prepare, &args);
+       list_transfer(&args.stream_list, stream_list);
+
+       for (i = 0; i < wim->hdr.image_count; i++) {
+               ret = lte_overwrite_prepare_2(wim->image_metadata[i]->metadata_lte,
+                                             &args);
+               if (ret)
+                       goto out_destroy_stream_size_table;
+       }
+       ret = for_lookup_table_entry(wim->lookup_table,
+                                    lte_overwrite_prepare_2, &args);
+out_destroy_stream_size_table:
+       destroy_stream_size_table(&args.stream_size_tab);
+       return ret;
+}
 
-       /* Write the WIM to a temporary file. */
-       /* XXX should the temporary file be somewhere else? */
-       wim_name_len = strlen(wimfile_name);
-       char tmpfile[wim_name_len + 10];
-       memcpy(tmpfile, wimfile_name, wim_name_len);
-       randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
-       tmpfile[wim_name_len + 9] = '\0';
 
-       ret = wimlib_write(w, tmpfile, WIM_ALL_IMAGES, flags);
-       if (ret != 0) {
-               ERROR("Failed to write the WIM file `%s'!\n", tmpfile);
-               return ret;
-       }
+struct find_streams_ctx {
+       struct list_head stream_list;
+       struct stream_size_table stream_size_tab;
+};
 
-       DEBUG("Closing original WIM file.\n");
-       /* Close the original WIM file that was opened for reading. */
-       if (w->fp) {
-               if (fclose(w->fp) != 0) {
-                       WARNING("Failed to close the file `%s'\n",
-                                       wimfile_name);
+static void
+inode_find_streams_to_write(struct wim_inode *inode,
+                           struct wim_lookup_table *table,
+                           struct list_head *stream_list,
+                           struct stream_size_table *tab)
+{
+       struct wim_lookup_table_entry *lte;
+       for (unsigned i = 0; i <= inode->i_num_ads; i++) {
+               lte = inode_stream_lte(inode, i, table);
+               if (lte) {
+                       if (lte->out_refcnt == 0) {
+                               if (lte->unhashed)
+                                       stream_size_table_insert(lte, tab);
+                               list_add_tail(&lte->write_streams_list, stream_list);
+                       }
+                       lte->out_refcnt += inode->i_nlink;
                }
-               w->fp = NULL;
        }
+}
 
-       DEBUG("Renaming `%s' to `%s'\n", tmpfile, wimfile_name);
-
-       /* Rename the new file to the old file .*/
-       if (rename(tmpfile, wimfile_name) != 0) {
-               ERROR("Failed to rename `%s' to `%s': %m\n", tmpfile, 
-                                                               wimfile_name);
-               /* Remove temporary file. */
-               if (unlink(tmpfile) != 0)
-                       ERROR("Failed to remove `%s': %m\n", tmpfile);
-               return WIMLIB_ERR_RENAME;
+static int
+image_find_streams_to_write(WIMStruct *w)
+{
+       struct find_streams_ctx *ctx;
+       struct wim_image_metadata *imd;
+       struct wim_inode *inode;
+       struct wim_lookup_table_entry *lte;
+
+       ctx = w->private;
+       imd = wim_get_current_image_metadata(w);
+
+       image_for_each_unhashed_stream(lte, imd)
+               lte->out_refcnt = 0;
+
+       /* Go through this image's inodes to find any streams that have not been
+        * found yet. */
+       image_for_each_inode(inode, imd) {
+               inode_find_streams_to_write(inode, w->lookup_table,
+                                           &ctx->stream_list,
+                                           &ctx->stream_size_tab);
        }
-
        return 0;
 }
 
-
-WIMLIBAPI int wimlib_overwrite_xml_and_header(WIMStruct *w, int flags)
+/* Given a WIM that from which one or all of the images is being written, build
+ * the list of unique streams ('struct wim_lookup_table_entry's) that must be
+ * written, plus any unhashed streams that need to be written but may be
+ * identical to other hashed or unhashed streams being written.  These unhashed
+ * streams are checksummed while the streams are being written.  To aid this
+ * process, the member @unique_size is set to 1 on streams that have a unique
+ * size and therefore must be written.
+ *
+ * The out_refcnt member of each 'struct wim_lookup_table_entry' is set to
+ * indicate the number of times the stream is referenced in only the streams
+ * that are being written; this may still be adjusted later when unhashed
+ * streams are being resolved.
+ */
+static int
+prepare_stream_list(WIMStruct *wim, int image, struct list_head *stream_list)
 {
        int ret;
-       FILE *fp;
-       u8 *integrity_table = NULL;
-       off_t xml_end;
-       off_t xml_size;
-       size_t bytes_written;
+       struct find_streams_ctx ctx;
 
-       DEBUG("Overwriting XML and header of `%s', flags = %d\n", 
-                               w->filename, flags);
-       if (!w->filename)
-               return WIMLIB_ERR_NO_FILENAME;
+       for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
+       ret = init_stream_size_table(&ctx.stream_size_tab,
+                                    wim->lookup_table->capacity);
+       if (ret)
+               return ret;
+       for_lookup_table_entry(wim->lookup_table, stream_size_table_insert,
+                              &ctx.stream_size_tab);
+       INIT_LIST_HEAD(&ctx.stream_list);
+       wim->private = &ctx;
+       ret = for_image(wim, image, image_find_streams_to_write);
+       destroy_stream_size_table(&ctx.stream_size_tab);
+       if (ret == 0)
+               list_transfer(&ctx.stream_list, stream_list);
+       return ret;
+}
 
-       ret = reopen_rw(w);
-       if (ret != 0)
+/* Writes the streams for the specified @image in @wim to @wim->out_fp.
+ */
+static int
+write_wim_streams(WIMStruct *wim, int image, int write_flags,
+                 unsigned num_threads,
+                 wimlib_progress_func_t progress_func)
+{
+       int ret;
+       struct list_head stream_list;
+
+       ret = prepare_stream_list(wim, image, &stream_list);
+       if (ret)
                return ret;
+       return write_stream_list(&stream_list,
+                                wim->lookup_table,
+                                wim->out_fp,
+                                wimlib_get_compression_type(wim),
+                                write_flags,
+                                num_threads,
+                                progress_func);
+}
 
-       fp = w->fp;
-
-       /* The old integrity table is still OK, as the SHA1 message digests in
-        * the integrity table include neither the header nor the XML data.
-        * Save it for later if it exists and an integrity table was required.
-        * */
-       if (flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY && 
-                       w->hdr.integrity.offset != 0) {
-               DEBUG("Reading existing integrity table.\n");
-               integrity_table = MALLOC(w->hdr.integrity.size);
-               if (!integrity_table)
-                       return WIMLIB_ERR_NOMEM;
+/*
+ * Finish writing a WIM file: write the lookup table, xml data, and integrity
+ * table (optional), then overwrite the WIM header.
+ *
+ * write_flags is a bitwise OR of the following:
+ *
+ *     (public)  WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
+ *             Include an integrity table.
+ *
+ *     (public)  WIMLIB_WRITE_FLAG_SHOW_PROGRESS:
+ *             Show progress information when (if) writing the integrity table.
+ *
+ *     (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
+ *             Don't write the lookup table.
+ *
+ *     (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
+ *             When (if) writing the integrity table, re-use entries from the
+ *             existing integrity table, if possible.
+ *
+ *     (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
+ *             After writing the XML data but before writing the integrity
+ *             table, write a temporary WIM header and flush the stream so that
+ *             the WIM is less likely to become corrupted upon abrupt program
+ *             termination.
+ *
+ *     (private) WIMLIB_WRITE_FLAG_FSYNC:
+ *             fsync() the output file before closing it.
+ *
+ */
+int
+finish_write(WIMStruct *w, int image, int write_flags,
+            wimlib_progress_func_t progress_func)
+{
+       int ret;
+       struct wim_header hdr;
+       FILE *out = w->out_fp;
+
+       /* @hdr will be the header for the new WIM.  First copy all the data
+        * from the header in the WIMStruct; then set all the fields that may
+        * have changed, including the resource entries, boot index, and image
+        * count.  */
+       memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
 
-               ret = read_uncompressed_resource(fp, w->hdr.integrity.offset,
-                                                w->hdr.integrity.original_size,
-                                                integrity_table);
-               if (ret != 0)
-                       goto err;
-               DEBUG("Done reading existing integrity table.\n");
+       /* Set image count and boot index correctly for single image writes */
+       if (image != WIMLIB_ALL_IMAGES) {
+               hdr.image_count = 1;
+               if (hdr.boot_idx == image)
+                       hdr.boot_idx = 1;
+               else
+                       hdr.boot_idx = 0;
        }
 
-       DEBUG("Overwriting XML data.\n");
-       /* Overwrite the XML data. */
-       if (fseeko(fp, w->hdr.xml_res_entry.offset, SEEK_SET) != 0) {
-               ERROR("Failed to seek to byte %"PRIu64" for XML data: "
-                               "%m\n", w->hdr.xml_res_entry.offset);
-               ret = WIMLIB_ERR_WRITE;
-               goto err;
+       /* In the WIM header, there is room for the resource entry for a
+        * metadata resource labeled as the "boot metadata".  This entry should
+        * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
+        * it should be a copy of the resource entry for the image that is
+        * marked as bootable.  This is not well documented...  */
+       if (hdr.boot_idx == 0) {
+               zero_resource_entry(&hdr.boot_metadata_res_entry);
+       } else {
+               copy_resource_entry(&hdr.boot_metadata_res_entry,
+                           &w->image_metadata[ hdr.boot_idx- 1
+                                       ]->metadata_lte->output_resource_entry);
        }
-       ret = write_xml_data(w->wim_info, WIM_ALL_IMAGES, fp);
-       if (ret != 0)
-               goto err;
 
-       DEBUG("Updating XML resource entry.\n");
-       /* Update the XML resource entry in the WIM header. */
-       xml_end = ftello(fp);
-       if (xml_end == -1) {
-               ret = WIMLIB_ERR_WRITE;
-               goto err;
-       }
-       xml_size = xml_end - w->hdr.xml_res_entry.offset;
-       w->hdr.xml_res_entry.size = xml_size;
-       w->hdr.xml_res_entry.original_size = xml_size;
-
-       if (flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
-               DEBUG("Writing integrity table.\n");
-               w->hdr.integrity.offset        = xml_end;
-               if (integrity_table) {
-                       /* The existing integrity table was saved. */
-                       bytes_written = fwrite(integrity_table, 1, 
-                                              w->hdr.integrity.size, fp);
-                       if (bytes_written != w->hdr.integrity.size) {
-                               ERROR("Failed to write integrity table: %m\n");
+       if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
+               ret = write_lookup_table(w, image, &hdr.lookup_table_res_entry);
+               if (ret)
+                       goto out_close_wim;
+       }
+
+       ret = write_xml_data(w->wim_info, image, out,
+                            (write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE) ?
+                             wim_info_get_total_bytes(w->wim_info) : 0,
+                            &hdr.xml_res_entry);
+       if (ret)
+               goto out_close_wim;
+
+       if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
+               if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
+                       struct wim_header checkpoint_hdr;
+                       memcpy(&checkpoint_hdr, &hdr, sizeof(struct wim_header));
+                       zero_resource_entry(&checkpoint_hdr.integrity);
+                       if (fseeko(out, 0, SEEK_SET)) {
+                               ERROR_WITH_ERRNO("Failed to seek to beginning "
+                                                "of WIM being written");
                                ret = WIMLIB_ERR_WRITE;
-                               goto err;
+                               goto out_close_wim;
                        }
-                       FREE(integrity_table);
+                       ret = write_header(&checkpoint_hdr, out);
+                       if (ret)
+                               goto out_close_wim;
+
+                       if (fflush(out) != 0) {
+                               ERROR_WITH_ERRNO("Can't write data to WIM");
+                               ret = WIMLIB_ERR_WRITE;
+                               goto out_close_wim;
+                       }
+
+                       if (fseeko(out, 0, SEEK_END) != 0) {
+                               ERROR_WITH_ERRNO("Failed to seek to end "
+                                                "of WIM being written");
+                               ret = WIMLIB_ERR_WRITE;
+                               goto out_close_wim;
+                       }
+               }
+
+               off_t old_lookup_table_end;
+               off_t new_lookup_table_end;
+               if (write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE) {
+                       old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
+                                              w->hdr.lookup_table_res_entry.size;
                } else {
-                       /* There was no existing integrity table, so a new one
-                        * must be calculated. */
-                       ret = write_integrity_table(fp, WIM_HEADER_DISK_SIZE,
-                                       w->hdr.lookup_table_res_entry.offset + 
-                                       w->hdr.lookup_table_res_entry.size,
-                                       flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS);
-                       if (ret != 0)
-                               goto err;
-
-                       off_t integrity_size           = ftello(fp) - xml_end;
-                       w->hdr.integrity.size          = integrity_size;
-                       w->hdr.integrity.original_size = integrity_size;
-                       w->hdr.integrity.flags         = 0;
+                       old_lookup_table_end = 0;
                }
+               new_lookup_table_end = hdr.lookup_table_res_entry.offset +
+                                      hdr.lookup_table_res_entry.size;
+
+               ret = write_integrity_table(out,
+                                           &hdr.integrity,
+                                           new_lookup_table_end,
+                                           old_lookup_table_end,
+                                           progress_func);
+               if (ret)
+                       goto out_close_wim;
        } else {
-               DEBUG("Truncating file to end of XML data.\n");
-               /* No integrity table to write.  The file should be truncated
-                * because it's possible that the old file was longer (due to it
-                * including an integrity table, or due to its XML data being
-                * longer) */
-               if (fflush(fp) != 0) {
-                       ERROR("Failed to flush stream for file `%s': %m\n",
-                                       w->filename);
-                       return WIMLIB_ERR_WRITE;
-               }
-               if (ftruncate(fileno(fp), xml_end) != 0) {
-                       ERROR("Failed to truncate `%s' to %"PRIu64" "
-                                       "bytes: %m\n", 
-                                       w->filename, xml_end);
-                       return WIMLIB_ERR_WRITE;
-               }
-               memset(&w->hdr.integrity, 0, sizeof(struct resource_entry));
+               zero_resource_entry(&hdr.integrity);
        }
 
-       DEBUG("Overwriting header.\n");
-       /* Overwrite the header. */
-       if (fseeko(fp, 0, SEEK_SET) != 0) {
-               ERROR("Failed to seek to beginning of `%s': %m\n",
-                               w->filename);
-               return WIMLIB_ERR_WRITE;
+       if (fseeko(out, 0, SEEK_SET) != 0) {
+               ERROR_WITH_ERRNO("Failed to seek to beginning of WIM "
+                                "being written");
+               ret = WIMLIB_ERR_WRITE;
+               goto out_close_wim;
        }
 
-       ret = write_header(&w->hdr, fp);
-       if (ret != 0)
-               return ret;;
+       ret = write_header(&hdr, out);
+       if (ret)
+               goto out_close_wim;
 
-       DEBUG("Closing file.\n");
-       if (fclose(fp) != 0) {
-               ERROR("Failed to close `%s': %m\n", w->filename);
-               return WIMLIB_ERR_WRITE;
+       if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
+               if (fflush(out) != 0
+                   || fsync(fileno(out)) != 0)
+               {
+                       ERROR_WITH_ERRNO("Error flushing data to WIM file");
+                       ret = WIMLIB_ERR_WRITE;
+               }
        }
-       w->fp = NULL;
-       DEBUG("Done.\n");
-       return 0;
-err:
-       FREE(integrity_table);
+out_close_wim:
+       if (fclose(out) != 0) {
+               ERROR_WITH_ERRNO("Failed to close the output WIM file");
+               if (ret == 0)
+                       ret = WIMLIB_ERR_WRITE;
+       }
+       w->out_fp = NULL;
        return ret;
 }
 
-/* Write the metadata resource for the current image. */
-static int write_metadata_resource(WIMStruct *w)
+#if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
+int
+lock_wim(WIMStruct *w, FILE *fp)
 {
-       FILE *out;
-       u8 *buf;
-       u8 *p;
-       int ret;
-       off_t subdir_offset;
-       struct dentry *root;
-       struct lookup_table_entry *lte;
-       struct resource_entry *res_entry;
-       off_t metadata_offset;
-       u64 metadata_original_size;
-       u64 metadata_compressed_size;
-       int metadata_ctype;
-       u8  hash[WIM_HASH_SIZE];
-
-       DEBUG("Writing metadata resource for image %u\n", w->current_image);
-
-       out = w->out_fp;
-       root = wim_root_dentry(w);
-       metadata_ctype = wimlib_get_compression_type(w);
-       metadata_offset = ftello(out);
-       if (metadata_offset == -1)
-               return WIMLIB_ERR_WRITE;
-
-       subdir_offset = 8 + root->length + 8;
-       calculate_subdir_offsets(root, &subdir_offset);
-       metadata_original_size = subdir_offset;
-       buf = MALLOC(metadata_original_size);
-       if (!buf) {
-               ERROR("Failed to allocate %"PRIu64" bytes for "
-                               "metadata resource\n", metadata_original_size);
-               return WIMLIB_ERR_NOMEM;
+       int ret = 0;
+       if (fp && !w->wim_locked) {
+               ret = flock(fileno(fp), LOCK_EX | LOCK_NB);
+               if (ret != 0) {
+                       if (errno == EWOULDBLOCK) {
+                               ERROR("`%"TS"' is already being modified or has been "
+                                     "mounted read-write\n"
+                                     "        by another process!", w->filename);
+                               ret = WIMLIB_ERR_ALREADY_LOCKED;
+                       } else {
+                               WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
+                                                  w->filename);
+                               ret = 0;
+                       }
+               } else {
+                       w->wim_locked = 1;
+               }
        }
-       p = buf;
-       #if 0
-       /* Write the security data. */
-       p = write_security_data(wim_security_data(w), p);
-       #else
-       p = put_u32(p, 8); /* Total length of security data. */
-       p = put_u32(p, 0); /* Number of security data entries. */
-       #endif
-
-       DEBUG("Writing dentry tree.\n");
-       p = write_dentry_tree(root, p);
-
-       /* Like file resources, the lookup table entry for a metadata resource
-        * uses for the hash code a SHA1 message digest of its uncompressed
-        * contents. */
-       sha1_buffer(buf, metadata_original_size, hash);
-
-       ret = write_resource_from_memory(buf, 
-                                        metadata_ctype,
-                                        metadata_original_size, 
-                                        out,
-                                        &metadata_compressed_size);
-       FREE(buf);
-       if (ret != 0)
-               return ret;
+       return ret;
+}
+#endif
 
-       /* Update the lookup table entry, including the hash and output resource
-        * entry fields, for this image's metadata resource.  */
-       lte = wim_metadata_lookup_table_entry(w);
-       res_entry = &lte->output_resource_entry;
-       lte->out_refcnt++;
-       if (memcmp(hash, lte->hash, WIM_HASH_SIZE) != 0) {
-               lookup_table_unlink(w->lookup_table, lte);
-               memcpy(lte->hash, hash, WIM_HASH_SIZE);
-               lookup_table_insert(w->lookup_table, lte);
-       }
-       res_entry->original_size = metadata_original_size;
-       res_entry->offset        = metadata_offset;
-       res_entry->size          = metadata_compressed_size;
-       res_entry->flags         = WIM_RESHDR_FLAG_METADATA;
-       if (metadata_ctype != WIM_COMPRESSION_TYPE_NONE)
-               res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
-       return 0;
+static int
+open_wim_writable(WIMStruct *w, const tchar *path,
+                 bool trunc, bool also_readable)
+{
+       const tchar *mode;
+       if (trunc)
+               if (also_readable)
+                       mode = T("w+b");
+               else
+                       mode = T("wb");
+       else
+               mode = T("r+b");
+
+       wimlib_assert(w->out_fp == NULL);
+       w->out_fp = tfopen(path, mode);
+       if (w->out_fp) {
+               return 0;
+       } else {
+               ERROR_WITH_ERRNO("Failed to open `%"TS"' for writing", path);
+               return WIMLIB_ERR_OPEN;
+       }
 }
 
-/* Write the file resources for the current image. */
-static int write_file_resources(WIMStruct *w)
+
+void
+close_wim_writable(WIMStruct *w)
 {
+       if (w->out_fp) {
+               if (fclose(w->out_fp) != 0) {
+                       WARNING_WITH_ERRNO("Failed to close output WIM");
+               }
+               w->out_fp = NULL;
+       }
+}
 
-       DEBUG("Writing file resources for image %u\n", w->current_image);
-       return for_dentry_in_tree(wim_root_dentry(w), write_file_resource, w);
+/* Open file stream and write dummy header for WIM. */
+int
+begin_write(WIMStruct *w, const tchar *path, int write_flags)
+{
+       int ret;
+       ret = open_wim_writable(w, path, true,
+                               (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
+       if (ret)
+               return ret;
+       /* Write dummy header. It will be overwritten later. */
+       return write_header(&w->hdr, w->out_fp);
 }
 
-/* Write lookup table, xml data, lookup table, and rewrite header */
-static int finish_write(WIMStruct *w, int image, FILE *out, int flags)
+/* Writes a stand-alone WIM to a file.  */
+WIMLIBAPI int
+wimlib_write(WIMStruct *w, const tchar *path,
+            int image, int write_flags, unsigned num_threads,
+            wimlib_progress_func_t progress_func)
 {
-       off_t lookup_table_offset;
-       off_t xml_data_offset;
-       off_t lookup_table_size;
-       off_t integrity_offset;
-       off_t xml_data_size;
-       off_t end_offset;
-       off_t integrity_size;
        int ret;
-       int i;
-       struct wim_header hdr;
 
-       lookup_table_offset = ftello(out);
-       if (lookup_table_offset == -1)
-               return WIMLIB_ERR_WRITE;
+       if (!path)
+               return WIMLIB_ERR_INVALID_PARAM;
 
-       DEBUG("Writing lookup table.\n");
-       /* Write the lookup table. */
-       ret = write_lookup_table(w->lookup_table, out);
-       if (ret != 0)
-               return ret;
+       write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
 
-       DEBUG("Writing XML data.\n");
+       if (image != WIMLIB_ALL_IMAGES &&
+            (image < 1 || image > w->hdr.image_count))
+               return WIMLIB_ERR_INVALID_IMAGE;
 
-       xml_data_offset = ftello(out);
-       if (xml_data_offset == -1)
-               return WIMLIB_ERR_WRITE;
+       if (w->hdr.total_parts != 1) {
+               ERROR("Cannot call wimlib_write() on part of a split WIM");
+               return WIMLIB_ERR_SPLIT_UNSUPPORTED;
+       }
 
-       /* @hdr will be the header for the new WIM.  First copy all the data
-        * from the header in the WIMStruct; then set all the fields that may
-        * have changed, including the resource entries, boot index, and image
-        * count.  */
-       memcpy(&hdr, &w->hdr, sizeof(struct wim_header));
-       lookup_table_size = xml_data_offset - lookup_table_offset;
-       hdr.lookup_table_res_entry.offset        = lookup_table_offset;
-       hdr.lookup_table_res_entry.size          = lookup_table_size;
-       hdr.lookup_table_res_entry.original_size = lookup_table_size;
-       hdr.lookup_table_res_entry.flags         = WIM_RESHDR_FLAG_METADATA;
+       ret = begin_write(w, path, write_flags);
+       if (ret)
+               goto out_close_wim;
 
-       ret = write_xml_data(w->wim_info, image, out);
-       if (ret != 0)
-               return ret;
+       ret = write_wim_streams(w, image, write_flags, num_threads,
+                               progress_func);
+       if (ret)
+               goto out_close_wim;
 
-       integrity_offset = ftello(out);
-       if (integrity_offset == -1)
-               return WIMLIB_ERR_WRITE;
-       xml_data_size = integrity_offset - xml_data_offset;
-
-       hdr.xml_res_entry.offset                 = xml_data_offset;
-       hdr.xml_res_entry.size                   = xml_data_size;
-       hdr.xml_res_entry.original_size          = xml_data_size;
-       hdr.xml_res_entry.flags                  = 0;
-
-       if (flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
-               ret = write_integrity_table(out, WIM_HEADER_DISK_SIZE, 
-                                           xml_data_offset, 
-                                           flags & WIMLIB_WRITE_FLAG_SHOW_PROGRESS);
-               if (ret != 0)
-                       return ret;
-               end_offset = ftello(out);
-               if (end_offset == -1)
-                       return WIMLIB_ERR_WRITE;
-               integrity_size = end_offset - integrity_offset;
-               hdr.integrity.offset = integrity_offset;
-               hdr.integrity.size   = integrity_size;
-               hdr.integrity.original_size = integrity_size;
-       } else {
-               hdr.integrity.offset        = 0;
-               hdr.integrity.size          = 0;
-               hdr.integrity.original_size = 0;
-       }
-       hdr.integrity.flags = 0;
+       if (progress_func)
+               progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
 
-       DEBUG("Updating WIM header.\n");
+       ret = for_image(w, image, write_metadata_resource);
+       if (ret)
+               goto out_close_wim;
+
+       if (progress_func)
+               progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
+
+       ret = finish_write(w, image, write_flags, progress_func);
+       /* finish_write() closed the WIM for us */
+       goto out;
+out_close_wim:
+       close_wim_writable(w);
+out:
+       DEBUG("wimlib_write(path=%"TS") = %d", path, ret);
+       return ret;
+}
 
+static bool
+any_images_modified(WIMStruct *w)
+{
+       for (int i = 0; i < w->hdr.image_count; i++)
+               if (w->image_metadata[i]->modified)
+                       return true;
+       return false;
+}
 
-       /* 
-        * In the WIM header, there is room for the resource entry for a
-        * metadata resource labeled as the "boot metadata".  This entry should
-        * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
-        * it should be a copy of the resource entry for the image that is
-        * marked as bootable.  This is not well documented...
-        */
-       if (hdr.boot_idx == 0 || !w->image_metadata
-                       || (image != WIM_ALL_IMAGES && image != hdr.boot_idx)) {
-               memset(&hdr.boot_metadata_res_entry, 0, 
-                      sizeof(struct resource_entry));
-       } else {
-               memcpy(&hdr.boot_metadata_res_entry, 
-                      &w->image_metadata[hdr.boot_idx - 1].lookup_table_entry->
-                                       output_resource_entry,
-                                       sizeof(struct resource_entry));
+/*
+ * Overwrite a WIM, possibly appending streams to it.
+ *
+ * A WIM looks like (or is supposed to look like) the following:
+ *
+ *                   Header (212 bytes)
+ *                   Streams and metadata resources (variable size)
+ *                   Lookup table (variable size)
+ *                   XML data (variable size)
+ *                   Integrity table (optional) (variable size)
+ *
+ * If we are not adding any streams or metadata resources, the lookup table is
+ * unchanged--- so we only need to overwrite the XML data, integrity table, and
+ * header.  This operation is potentially unsafe if the program is abruptly
+ * terminated while the XML data or integrity table are being overwritten, but
+ * before the new header has been written.  To partially alleviate this problem,
+ * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
+ * finish_write() to cause a temporary WIM header to be written after the XML
+ * data has been written.  This may prevent the WIM from becoming corrupted if
+ * the program is terminated while the integrity table is being calculated (but
+ * no guarantees, due to write re-ordering...).
+ *
+ * If we are adding new streams or images (metadata resources), the lookup table
+ * needs to be changed, and those streams need to be written.  In this case, we
+ * try to perform a safe update of the WIM file by writing the streams *after*
+ * the end of the previous WIM, then writing the new lookup table, XML data, and
+ * (optionally) integrity table following the new streams.  This will produce a
+ * layout like the following:
+ *
+ *                   Header (212 bytes)
+ *                   (OLD) Streams and metadata resources (variable size)
+ *                   (OLD) Lookup table (variable size)
+ *                   (OLD) XML data (variable size)
+ *                   (OLD) Integrity table (optional) (variable size)
+ *                   (NEW) Streams and metadata resources (variable size)
+ *                   (NEW) Lookup table (variable size)
+ *                   (NEW) XML data (variable size)
+ *                   (NEW) Integrity table (optional) (variable size)
+ *
+ * At all points, the WIM is valid as nothing points to the new data yet.  Then,
+ * the header is overwritten to point to the new lookup table, XML data, and
+ * integrity table, to produce the following layout:
+ *
+ *                   Header (212 bytes)
+ *                   Streams and metadata resources (variable size)
+ *                   Nothing (variable size)
+ *                   More Streams and metadata resources (variable size)
+ *                   Lookup table (variable size)
+ *                   XML data (variable size)
+ *                   Integrity table (optional) (variable size)
+ *
+ * This method allows an image to be appended to a large WIM very quickly, and
+ * is is crash-safe except in the case of write re-ordering, but the
+ * disadvantage is that a small hole is left in the WIM where the old lookup
+ * table, xml data, and integrity table were.  (These usually only take up a
+ * small amount of space compared to the streams, however.)
+ */
+static int
+overwrite_wim_inplace(WIMStruct *w, int write_flags,
+                     unsigned num_threads,
+                     wimlib_progress_func_t progress_func)
+{
+       int ret;
+       struct list_head stream_list;
+       off_t old_wim_end;
+       u64 old_lookup_table_end, old_xml_begin, old_xml_end;
+
+       DEBUG("Overwriting `%"TS"' in-place", w->filename);
+
+       /* Make sure that the integrity table (if present) is after the XML
+        * data, and that there are no stream resources, metadata resources, or
+        * lookup tables after the XML data.  Otherwise, these data would be
+        * overwritten. */
+       old_xml_begin = w->hdr.xml_res_entry.offset;
+       old_xml_end = old_xml_begin + w->hdr.xml_res_entry.size;
+       old_lookup_table_end = w->hdr.lookup_table_res_entry.offset +
+                              w->hdr.lookup_table_res_entry.size;
+       if (w->hdr.integrity.offset != 0 && w->hdr.integrity.offset < old_xml_end) {
+               ERROR("Didn't expect the integrity table to be before the XML data");
+               return WIMLIB_ERR_RESOURCE_ORDER;
        }
 
-       /* Set image count and boot index correctly for single image writes */
-       if (image != WIM_ALL_IMAGES) {
-               hdr.image_count = 1;
-               if (hdr.boot_idx == image)
-                       hdr.boot_idx = 1;
-               else
-                       hdr.boot_idx = 0;
+       if (old_lookup_table_end > old_xml_begin) {
+               ERROR("Didn't expect the lookup table to be after the XML data");
+               return WIMLIB_ERR_RESOURCE_ORDER;
        }
 
+       /* Set @old_wim_end, which indicates the point beyond which we don't
+        * allow any file and metadata resources to appear without returning
+        * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
+        * overwrite these resources). */
+       if (!w->deletion_occurred && !any_images_modified(w)) {
+               /* If no images have been modified and no images have been
+                * deleted, a new lookup table does not need to be written.  We
+                * shall write the new XML data and optional integrity table
+                * immediately after the lookup table.  Note that this may
+                * overwrite an existing integrity table. */
+               DEBUG("Skipping writing lookup table "
+                     "(no images modified or deleted)");
+               old_wim_end = old_lookup_table_end;
+               write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
+                              WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
+       } else if (w->hdr.integrity.offset) {
+               /* Old WIM has an integrity table; begin writing new streams
+                * after it. */
+               old_wim_end = w->hdr.integrity.offset + w->hdr.integrity.size;
+       } else {
+               /* No existing integrity table; begin writing new streams after
+                * the old XML data. */
+               old_wim_end = old_xml_end;
+       }
+
+       ret = prepare_streams_for_overwrite(w, old_wim_end, &stream_list);
+       if (ret)
+               return ret;
+
+       ret = open_wim_writable(w, w->filename, false,
+                               (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) != 0);
+       if (ret)
+               return ret;
+
+       ret = lock_wim(w, w->out_fp);
+       if (ret) {
+               close_wim_writable(w);
+               return ret;
+       }
 
-       if (fseeko(out, 0, SEEK_SET) != 0)
+       if (fseeko(w->out_fp, old_wim_end, SEEK_SET) != 0) {
+               ERROR_WITH_ERRNO("Can't seek to end of WIM");
+               close_wim_writable(w);
+               w->wim_locked = 0;
                return WIMLIB_ERR_WRITE;
+       }
 
-       return write_header(&hdr, out);
+       DEBUG("Writing newly added streams (offset = %"PRIu64")",
+             old_wim_end);
+       ret = write_stream_list(&stream_list,
+                               w->lookup_table,
+                               w->out_fp,
+                               wimlib_get_compression_type(w),
+                               write_flags,
+                               num_threads,
+                               progress_func);
+       if (ret)
+               goto out_truncate;
+
+       for (int i = 0; i < w->hdr.image_count; i++) {
+               if (w->image_metadata[i]->modified) {
+                       select_wim_image(w, i + 1);
+                       ret = write_metadata_resource(w);
+                       if (ret)
+                               goto out_truncate;
+               }
+       }
+       write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
+       ret = finish_write(w, WIMLIB_ALL_IMAGES, write_flags,
+                          progress_func);
+out_truncate:
+       close_wim_writable(w);
+       if (ret != 0 && !(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
+               WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
+                       w->filename, old_wim_end);
+               /* Return value of truncate() is ignored because this is already
+                * an error path. */
+               (void)ttruncate(w->filename, old_wim_end);
+       }
+       w->wim_locked = 0;
+       return ret;
 }
 
-/* Writes the WIM to a file.  */
-WIMLIBAPI int wimlib_write(WIMStruct *w, const char *path, int image, int flags)
+static int
+overwrite_wim_via_tmpfile(WIMStruct *w, int write_flags,
+                         unsigned num_threads,
+                         wimlib_progress_func_t progress_func)
 {
+       size_t wim_name_len;
        int ret;
-       const char *mode;
-       FILE *out;
 
-       if (image != WIM_ALL_IMAGES && 
-                       (image < 1 || image > w->hdr.image_count))
-               return WIMLIB_ERR_INVALID_IMAGE;
-
-       if (image == WIM_ALL_IMAGES)
-               DEBUG("Writing all images to `%s'\n", path);
-       else
-               DEBUG("Writing image %d to `%s'\n", image, path);
-
-       /* checking the integrity requires going back over the file to read it.
-        * XXX 
-        * (It also would be possible to keep a running sha1sum as the file
-        * as written-- this would be faster, but a bit more complicated) */
-       if (flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) 
-               mode = "w+b";
-       else
-               mode = "wb";
+       DEBUG("Overwriting `%"TS"' via a temporary file", w->filename);
 
-       out = fopen(path, mode);
-       if (!out) {
-               ERROR("Failed to open the file `%s' for writing!\n", 
-                               path);
-               return WIMLIB_ERR_OPEN;
+       /* Write the WIM to a temporary file in the same directory as the
+        * original WIM. */
+       wim_name_len = tstrlen(w->filename);
+       tchar tmpfile[wim_name_len + 10];
+       tmemcpy(tmpfile, w->filename, wim_name_len);
+       randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
+       tmpfile[wim_name_len + 9] = T('\0');
+
+       ret = wimlib_write(w, tmpfile, WIMLIB_ALL_IMAGES,
+                          write_flags | WIMLIB_WRITE_FLAG_FSYNC,
+                          num_threads, progress_func);
+       if (ret) {
+               ERROR("Failed to write the WIM file `%"TS"'", tmpfile);
+               goto out_unlink;
        }
 
-       w->out_fp = out;
+       DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, w->filename);
 
-       /* Write dummy header. It will be overwritten later. */
-       ret = write_header(&w->hdr, out);
-       if (ret != 0)
-               goto done;
+#ifdef __WIN32__
+       /* Windows won't let you delete open files unless FILE_SHARE_DELETE was
+        * specified to CreateFile().  The WIM was opened with fopen(), which
+        * didn't provided this flag to CreateFile, so the handle must be closed
+        * before executing the rename(). */
+       if (w->fp != NULL) {
+               fclose(w->fp);
+               w->fp = NULL;
+       }
+#endif
 
-       for_lookup_table_entry(w->lookup_table, zero_out_refcnts, NULL);
+       /* Rename the new file to the old file .*/
+       if (trename(tmpfile, w->filename) != 0) {
+               ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
+                                tmpfile, w->filename);
+               ret = WIMLIB_ERR_RENAME;
+               goto out_unlink;
+       }
 
-       ret = for_image(w, image, write_file_resources);
-       if (ret != 0) {
-               ERROR("Failed to write file resources!\n");
-               goto done;
+       if (progress_func) {
+               union wimlib_progress_info progress;
+               progress.rename.from = tmpfile;
+               progress.rename.to = w->filename;
+               progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
        }
 
-       ret = for_image(w, image, write_metadata_resource);
+       /* Close the original WIM file that was opened for reading. */
+       if (w->fp != NULL) {
+               fclose(w->fp);
+               w->fp = NULL;
+       }
 
-       if (ret != 0) {
-               ERROR("Failed to write image metadata!\n");
-               goto done;
+       /* Re-open the WIM read-only. */
+       w->fp = tfopen(w->filename, T("rb"));
+       if (w->fp == NULL) {
+               ret = WIMLIB_ERR_REOPEN;
+               WARNING_WITH_ERRNO("Failed to re-open `%"TS"' read-only",
+                                  w->filename);
+               FREE(w->filename);
+               w->filename = NULL;
        }
+       goto out;
+out_unlink:
+       /* Remove temporary file. */
+       if (tunlink(tmpfile) != 0)
+               WARNING_WITH_ERRNO("Failed to remove `%"TS"'", tmpfile);
+out:
+       return ret;
+}
 
-       ret = finish_write(w, image, out, flags);
+/*
+ * Writes a WIM file to the original file that it was read from, overwriting it.
+ */
+WIMLIBAPI int
+wimlib_overwrite(WIMStruct *w, int write_flags,
+                unsigned num_threads,
+                wimlib_progress_func_t progress_func)
+{
+       write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
 
-done:
-       DEBUG("Closing output file.\n");
-       w->out_fp = NULL;
-       if (fclose(out) != 0) {
-               ERROR("Failed to close the file `%s': %m\n", path);
-               ret = WIMLIB_ERR_WRITE;
+       if (!w->filename)
+               return WIMLIB_ERR_NO_FILENAME;
+
+       if (w->hdr.total_parts != 1) {
+               ERROR("Cannot modify a split WIM");
+               return WIMLIB_ERR_SPLIT_UNSUPPORTED;
        }
-       return ret;
+
+       if ((!w->deletion_occurred || (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
+           && !(write_flags & WIMLIB_WRITE_FLAG_REBUILD))
+       {
+               int ret;
+               ret = overwrite_wim_inplace(w, write_flags, num_threads,
+                                           progress_func);
+               if (ret == WIMLIB_ERR_RESOURCE_ORDER)
+                       WARNING("Falling back to re-building entire WIM");
+               else
+                       return ret;
+       }
+       return overwrite_wim_via_tmpfile(w, write_flags, num_threads,
+                                        progress_func);
 }