]> wimlib.net Git - wimlib/blobdiff - src/mount.c
mount.c tweaks
[wimlib] / src / mount.c
index d5f43718d85833311514481feaa08897893aeab4..c130f618c2777deb6f89f4d6d5db26676b7bfe00 100644 (file)
 /* File descriptor to a file open on the WIM filesystem. */
 struct wimlib_fd {
        struct inode *f_inode;
-       struct lookup_table_entry *lte;
+       struct lookup_table_entry *f_lte;
        int staging_fd;
        u16 idx;
        u32 stream_id;
 };
 
-/* The WIMStruct for the mounted WIM. */
-static WIMStruct *w;
-
-/* Working directory when `imagex mount' is run. */
-static const char *working_directory;
-
-/* Name of the staging directory for a read-write mount.  Whenever a new file is
- * created, it is done so in the staging directory.  Furthermore, whenever a
- * file in the WIM is modified, it is extracted to the staging directory.  If
- * changes are commited when the WIM is unmounted, the file resources are merged
- * in from the staging directory when writing the new WIM. */
-static char *staging_dir_name;
-static size_t staging_dir_name_len;
-
-/* Flags passed to wimlib_mount(). */
-static int mount_flags;
+struct wimfs_context {
+       /* The WIMStruct for the mounted WIM. */
+       WIMStruct *wim;
+
+       /* Working directory when `imagex mount' is run. */
+       char *working_directory;
+
+       /* Name of the staging directory for a read-write mount.  Whenever a new file is
+        * created, it is done so in the staging directory.  Furthermore, whenever a
+        * file in the WIM is modified, it is extracted to the staging directory.  If
+        * changes are commited when the WIM is unmounted, the file resources are merged
+        * in from the staging directory when writing the new WIM. */
+       char *staging_dir_name;
+       size_t staging_dir_name_len;
+
+       /* Flags passed to wimlib_mount(). */
+       int mount_flags;
+
+       /* Next inode number to be assigned. */
+       u64 next_ino;
+
+       /* List of lookup table entries in the staging directory */
+       struct list_head staging_list;
+
+       /* Name and message queue descriptors for message queues between the filesystem
+        * daemon process and the unmount process.  These are used when the filesystem
+        * is unmounted and the process running wimlib_mount() (i.e. the `imagex
+        * unmount' command) needs to communicate with the filesystem daemon running
+        * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
+        * commands */
+       char *unmount_to_daemon_mq_name;
+       char *daemon_to_unmount_mq_name;
+       mqd_t unmount_to_daemon_mq;
+       mqd_t daemon_to_unmount_mq;
+};
 
-/* Name of the directory on which the WIM file is mounted. */
-static const char *mount_dir;
+static void init_wimfs_context(struct wimfs_context *ctx)
+{
+       memset(ctx, 0, sizeof(*ctx));
+       ctx->unmount_to_daemon_mq = (mqd_t)-1;
+       ctx->daemon_to_unmount_mq = (mqd_t)-1;
+       INIT_LIST_HEAD(&ctx->staging_list);
+}
 
-/* Next inode number to be assigned. */
-static u64 next_ino;
+static inline struct wimfs_context *wimfs_get_context()
+{
+       return (struct wimfs_context*)fuse_get_context()->private_data;
+}
 
-/* List of lookup table entries in the staging directory */
-static LIST_HEAD(staging_list);
+static inline WIMStruct *wimfs_get_WIMStruct()
+{
+       return wimfs_get_context()->wim;
+}
 
-static inline int get_lookup_flags()
+static inline int get_lookup_flags(const struct wimfs_context *ctx)
 {
-       if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
+       if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
                return LOOKUP_FLAG_ADS_OK;
        else
                return 0;
@@ -130,7 +158,7 @@ static int alloc_wimlib_fd(struct inode *inode,
                        return -EMFILE;
                num_new_fds = min(fds_per_alloc,
                                  max_fds - inode->num_allocated_fds);
-               
+
                fds = REALLOC(inode->fds,
                              (inode->num_allocated_fds + num_new_fds) *
                                sizeof(inode->fds[0]));
@@ -147,7 +175,7 @@ static int alloc_wimlib_fd(struct inode *inode,
                        if (!fd)
                                return -ENOMEM;
                        fd->f_inode    = inode;
-                       fd->lte        = lte;
+                       fd->f_lte      = lte;
                        fd->staging_fd = -1;
                        fd->idx        = i;
                        fd->stream_id  = stream_id;
@@ -180,23 +208,22 @@ static void inode_put_fd(struct inode *inode, struct wimlib_fd *fd)
 static int lte_put_fd(struct lookup_table_entry *lte, struct wimlib_fd *fd)
 {
        wimlib_assert(fd);
-       wimlib_assert(fd->lte == lte);
+       wimlib_assert(fd->f_lte == lte);
 
        if (!lte) /* Empty stream with no lookup table entry */
                return 0;
 
        /* Close staging file descriptor if needed. */
-       wimlib_assert(lte->num_opened_fds);
 
-       if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
-               wimlib_assert(lte->staging_file_name);
-               wimlib_assert(fd->staging_fd != -1);
+       if (lte->resource_location == RESOURCE_IN_STAGING_FILE
+            && fd->staging_fd != -1)
+       {
                if (close(fd->staging_fd) != 0) {
                        ERROR_WITH_ERRNO("Failed to close staging file");
                        return -errno;
                }
        }
-       lte_decrement_num_opened_fds(lte, w->lookup_table);
+       lte_decrement_num_opened_fds(lte);
        return 0;
 }
 
@@ -208,7 +235,7 @@ static int close_wimlib_fd(struct wimlib_fd *fd)
        DEBUG("Closing fd (inode = %lu, opened = %u, allocated = %u)",
              fd->f_inode->ino, fd->f_inode->num_opened_fds,
              fd->f_inode->num_allocated_fds);
-       ret = lte_put_fd(fd->lte, fd);
+       ret = lte_put_fd(fd->f_lte, fd);
        if (ret != 0)
                return ret;
 
@@ -251,7 +278,8 @@ static void remove_dentry(struct dentry *dentry,
  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
  *             error, for any reason possible from the creat() function.
  */
-static int create_staging_file(char **name_ret, int open_flags)
+static int create_staging_file(char **name_ret, int open_flags,
+                              struct wimfs_context *ctx)
 {
        size_t name_len;
        char *name;
@@ -259,7 +287,7 @@ static int create_staging_file(char **name_ret, int open_flags)
        int fd;
        int errno_save;
 
-       name_len = staging_dir_name_len + 1 + SHA1_HASH_SIZE;
+       name_len = ctx->staging_dir_name_len + 1 + SHA1_HASH_SIZE;
        name = MALLOC(name_len + 1);
        if (!name) {
                errno = ENOMEM;
@@ -268,9 +296,9 @@ static int create_staging_file(char **name_ret, int open_flags)
 
        do {
 
-               memcpy(name, staging_dir_name, staging_dir_name_len);
-               name[staging_dir_name_len] = '/';
-               randomize_char_array_with_alnum(name + staging_dir_name_len + 1,
+               memcpy(name, ctx->staging_dir_name, ctx->staging_dir_name_len);
+               name[ctx->staging_dir_name_len] = '/';
+               randomize_char_array_with_alnum(name + ctx->staging_dir_name_len + 1,
                                                SHA1_HASH_SIZE);
                name[name_len] = '\0';
 
@@ -287,7 +315,7 @@ static int create_staging_file(char **name_ret, int open_flags)
 
        DEBUG("Creating staging file `%s'", name);
 
-       fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600); 
+       fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600);
        if (fd == -1) {
                errno_save = errno;
                FREE(name);
@@ -298,7 +326,7 @@ static int create_staging_file(char **name_ret, int open_flags)
        return fd;
 }
 
-/* 
+/*
  * Extract a WIM resource to the staging directory.
  *
  * @inode:  Inode that contains the stream we are extracting
@@ -315,15 +343,19 @@ static int create_staging_file(char **name_ret, int open_flags)
 static int extract_resource_to_staging_dir(struct inode *inode,
                                           u32 stream_id,
                                           struct lookup_table_entry **lte,
-                                          off_t size)
+                                          off_t size,
+                                          struct wimfs_context *ctx)
 {
        char *staging_file_name;
        int ret;
        int fd;
        struct lookup_table_entry *old_lte, *new_lte;
 
+       DEBUG("Extracting resource to staging dir: inode %"PRIu64", "
+             "stream id %"PRIu32, inode->ino, stream_id);
+
        old_lte = *lte;
-       fd = create_staging_file(&staging_file_name, O_WRONLY);
+       fd = create_staging_file(&staging_file_name, O_WRONLY, ctx);
        if (fd == -1)
                return -errno;
 
@@ -348,7 +380,7 @@ static int extract_resource_to_staging_dir(struct inode *inode,
                 * to the stream we're trying to extract, so the lookup
                 * table entry can be re-used.  */
                DEBUG("Re-using lookup table entry");
-               lookup_table_unlink(w->lookup_table, old_lte);
+               lookup_table_unlink(ctx->wim->lookup_table, old_lte);
                new_lte = old_lte;
        } else {
                if (old_lte) {
@@ -359,7 +391,7 @@ static int extract_resource_to_staging_dir(struct inode *inode,
                         * */
                        wimlib_assert(old_lte->refcnt > inode->link_count);
                        DEBUG("Splitting lookup table entry "
-                             "(inode->link_count = %zu, old_lte->refcnt = %u)",
+                             "(inode->link_count = %u, old_lte->refcnt = %u)",
                              inode->link_count, old_lte->refcnt);
 
                }
@@ -375,7 +407,7 @@ static int extract_resource_to_staging_dir(struct inode *inode,
                 * opening it read-write.  Identify those file descriptors and
                 * change their lookup table entry pointers to point to the new
                 * lookup table entry, and open staging file descriptors for
-                * them. 
+                * them.
                 *
                 * At the same time, we need to count the number of these opened
                 * file descriptors to the new lookup table entry.  If there's
@@ -385,8 +417,9 @@ static int extract_resource_to_staging_dir(struct inode *inode,
                        struct wimlib_fd *fd = inode->fds[i];
                        if (fd) {
                                if (fd->stream_id == stream_id) {
-                                       wimlib_assert(fd->lte == old_lte);
-                                       fd->lte = new_lte;
+                                       wimlib_assert(fd->f_lte == old_lte);
+                                       wimlib_assert(fd->staging_fd == -1);
+                                       fd->f_lte = new_lte;
                                        new_lte->num_opened_fds++;
                                        fd->staging_fd = open(staging_file_name, O_RDONLY);
                                        if (fd->staging_fd == -1) {
@@ -397,7 +430,7 @@ static int extract_resource_to_staging_dir(struct inode *inode,
                                j++;
                        }
                }
-               DEBUG("%zu fd's were already opened to the file we extracted",
+               DEBUG("%hu fd's were already opened to the file we extracted",
                      new_lte->num_opened_fds);
                if (old_lte) {
                        old_lte->num_opened_fds -= new_lte->num_opened_fds;
@@ -407,9 +440,9 @@ static int extract_resource_to_staging_dir(struct inode *inode,
 
        new_lte->resource_entry.original_size = size;
        new_lte->refcnt                       = inode->link_count;
-       new_lte->staging_file_name            = staging_file_name;
        new_lte->resource_location            = RESOURCE_IN_STAGING_FILE;
-       new_lte->lte_inode                        = inode;
+       new_lte->staging_file_name            = staging_file_name;
+       new_lte->lte_inode                    = inode;
        random_hash(new_lte->hash);
 
        if (stream_id == 0)
@@ -419,15 +452,15 @@ static int extract_resource_to_staging_dir(struct inode *inode,
                        if (inode->ads_entries[i].stream_id == stream_id)
                                inode->ads_entries[i].lte = new_lte;
 
-       lookup_table_insert(w->lookup_table, new_lte);
-       list_add(&new_lte->staging_list, &staging_list);
+       lookup_table_insert(ctx->wim->lookup_table, new_lte);
+       list_add(&new_lte->staging_list, &ctx->staging_list);
        *lte = new_lte;
        return 0;
 out_revert_fd_changes:
        for (u16 i = 0, j = 0; j < new_lte->num_opened_fds; i++) {
                struct wimlib_fd *fd = inode->fds[i];
-               if (fd && fd->stream_id == stream_id && fd->lte == new_lte) {
-                       fd->lte = old_lte;
+               if (fd && fd->stream_id == stream_id && fd->f_lte == new_lte) {
+                       fd->f_lte = old_lte;
                        if (fd->staging_fd != -1) {
                                close(fd->staging_fd);
                                fd->staging_fd = -1;
@@ -435,7 +468,6 @@ out_revert_fd_changes:
                        j++;
                }
        }
-out_free_new_lte:
        free_lookup_table_entry(new_lte);
 out_delete_staging_file:
        unlink(staging_file_name);
@@ -443,43 +475,43 @@ out_delete_staging_file:
        return ret;
 }
 
-/* 
+/*
  * Creates a randomly named staging directory and returns its name into the
  * static variable staging_dir_name.
  *
  * If the staging directory cannot be created, staging_dir_name is set to NULL.
  * */
-static void make_staging_dir()
+static int make_staging_dir(struct wimfs_context *ctx)
 {
        /* XXX Give the user an option of where to stage files */
 
-       static char prefix[] = "wimlib-staging-";
-       static const size_t prefix_len = 15;
-       static const size_t suffix_len = 10;
+       static const char prefix[] = "wimlib-staging-";
+       static const size_t prefix_len = sizeof(prefix) - 1;
+       static const size_t random_suffix_len = 10;
 
-       size_t pwd_len = strlen(working_directory);
+       size_t pwd_len = strlen(ctx->working_directory);
 
-       staging_dir_name_len = pwd_len + 1 + prefix_len + suffix_len;
+       ctx->staging_dir_name_len = pwd_len + 1 + prefix_len + random_suffix_len;
 
-       staging_dir_name = MALLOC(staging_dir_name_len + 1);
-       if (!staging_dir_name) {
-               ERROR("Out of memory");
-               return;
-       }
+       ctx->staging_dir_name = MALLOC(ctx->staging_dir_name_len + 1);
+       if (!ctx->staging_dir_name)
+               return WIMLIB_ERR_NOMEM;
 
-       memcpy(staging_dir_name, working_directory, pwd_len);
-       staging_dir_name[pwd_len] = '/';
-       memcpy(staging_dir_name + pwd_len + 1, prefix, prefix_len);
-       randomize_char_array_with_alnum(staging_dir_name + pwd_len + 1 + prefix_len,
-                               suffix_len);
-       staging_dir_name[staging_dir_name_len] = '\0';
+       memcpy(ctx->staging_dir_name, ctx->working_directory, pwd_len);
+       ctx->staging_dir_name[pwd_len] = '/';
+       memcpy(ctx->staging_dir_name + pwd_len + 1, prefix, prefix_len);
+       randomize_char_array_with_alnum(ctx->staging_dir_name + pwd_len +
+                                       1 + prefix_len, random_suffix_len);
+       ctx->staging_dir_name[ctx->staging_dir_name_len] = '\0';
 
-       if (mkdir(staging_dir_name, 0700) != 0) {
+       if (mkdir(ctx->staging_dir_name, 0700) != 0) {
                ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
-                                staging_dir_name);
-               FREE(staging_dir_name);
-               staging_dir_name = NULL;
+                                ctx->staging_dir_name);
+               FREE(ctx->staging_dir_name);
+               ctx->staging_dir_name = NULL;
+               return WIMLIB_ERR_MKDIR;
        }
+       return 0;
 }
 
 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
@@ -487,36 +519,30 @@ static int remove_file_or_directory(const char *fpath, const struct stat *sb,
 {
        if (remove(fpath) == 0)
                return 0;
-       else
+       else {
+               ERROR_WITH_ERRNO("Cannot remove `%s'", fpath);
                return WIMLIB_ERR_DELETE_STAGING_DIR;
+       }
 }
 
 
-/* 
- * Deletes the staging directory and all the files contained in it. 
+/*
+ * Deletes the staging directory and all the files contained in it.
  */
-static int delete_staging_dir()
+static int delete_staging_dir(struct wimfs_context *ctx)
 {
        int ret;
-       
-       ret = nftw(staging_dir_name, remove_file_or_directory,10, FTW_DEPTH);
-       staging_dir_name = NULL;
+       wimlib_assert(ctx->staging_dir_name != NULL);
+       ret = nftw(ctx->staging_dir_name, remove_file_or_directory,
+                  10, FTW_DEPTH);
+       FREE(ctx->staging_dir_name);
+       ctx->staging_dir_name = NULL;
        return ret;
 }
 
-/* Name and message queue descriptors for message queues between the filesystem
- * daemon process and the unmount process.  These are used when the filesystem
- * is unmounted and the process running wimlib_mount() (i.e. the `imagex
- * unmount' command) needs to communicate with the filesystem daemon running
- * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
- * commands */
-static char *unmount_to_daemon_mq_name;
-static char *daemon_to_unmount_mq_name;
-static mqd_t unmount_to_daemon_mq;
-static mqd_t daemon_to_unmount_mq;
 
 /* Simple function that returns the concatenation of 4 strings. */
-static char *strcat_dup(const char *s1, const char *s2, const char *s3, 
+static char *strcat_dup(const char *s1, const char *s2, const char *s3,
                        const char *s4)
 {
        size_t len = strlen(s1) + strlen(s2) + strlen(s3) + strlen(s4) + 1;
@@ -551,17 +577,8 @@ static void s_slashes_underscores_g(char *s)
        }
 }
 
-/* 
- * Opens two POSIX message queue: one for sending messages from the unmount
- * process to the daemon process, and one to go the other way.  The names of the
- * message queues, which must be system-wide unique, are be based on the mount
- * point.  (There of course is still a possibility of a collision if one were to
- * unmount two identically named directories simultaneously...)
- *
- * @daemon specifies whether the calling process is the filesystem daemon or the
- * unmount process.
- */
-static int open_message_queues(bool daemon)
+static int set_message_queue_names(struct wimfs_context *ctx,
+                                  const char *mount_dir)
 {
        static const char *slash = "/";
        static const char *prefix = "wimlib-";
@@ -569,40 +586,67 @@ static int open_message_queues(bool daemon)
        static const char *d2u_suffix = "daemon-to-unmount-mq";
 
        const char *mount_dir_basename = path_basename(mount_dir);
-       int flags;
-       int ret;
 
-       unmount_to_daemon_mq_name = strcat_dup(slash, mount_dir_basename,
-                                               prefix, u2d_suffix);
-       if (!unmount_to_daemon_mq_name) {
+       ctx->unmount_to_daemon_mq_name = strcat_dup(slash, mount_dir_basename,
+                                                   prefix, u2d_suffix);
+       if (!ctx->unmount_to_daemon_mq_name) {
                ERROR("Out of memory");
                return WIMLIB_ERR_NOMEM;
        }
-       daemon_to_unmount_mq_name = strcat_dup(slash, mount_dir_basename,
-                                               prefix, d2u_suffix);
-       if (!daemon_to_unmount_mq_name) {
+       ctx->daemon_to_unmount_mq_name = strcat_dup(slash, mount_dir_basename,
+                                                   prefix, d2u_suffix);
+       if (!ctx->daemon_to_unmount_mq_name) {
                ERROR("Out of memory");
-               ret = WIMLIB_ERR_NOMEM;
-               goto err1;
+               FREE(ctx->unmount_to_daemon_mq_name);
+               ctx->unmount_to_daemon_mq_name = NULL;
+               return WIMLIB_ERR_NOMEM;
        }
 
-       remove_trailing_slashes(unmount_to_daemon_mq_name);
-       remove_trailing_slashes(daemon_to_unmount_mq_name);
-       s_slashes_underscores_g(unmount_to_daemon_mq_name + 1);
-       s_slashes_underscores_g(daemon_to_unmount_mq_name + 1);
+       remove_trailing_slashes(ctx->unmount_to_daemon_mq_name);
+       remove_trailing_slashes(ctx->daemon_to_unmount_mq_name);
+       s_slashes_underscores_g(ctx->unmount_to_daemon_mq_name + 1);
+       s_slashes_underscores_g(ctx->daemon_to_unmount_mq_name + 1);
+       return 0;
+}
+
+static void free_message_queue_names(struct wimfs_context *ctx)
+{
+       FREE(ctx->unmount_to_daemon_mq_name);
+       FREE(ctx->daemon_to_unmount_mq_name);
+       ctx->unmount_to_daemon_mq_name = NULL;
+       ctx->daemon_to_unmount_mq_name = NULL;
+}
+
+/*
+ * Opens two POSIX message queue: one for sending messages from the unmount
+ * process to the daemon process, and one to go the other way.  The names of the
+ * message queues, which must be system-wide unique, are be based on the mount
+ * point.  (There of course is still a possibility of a collision if one were to
+ * unmount two identically named directories simultaneously...)
+ *
+ * @daemon specifies whether the calling process is the filesystem daemon or the
+ * unmount process.
+ */
+static int open_message_queues(struct wimfs_context *ctx, bool daemon)
+{
+       int flags;
+       int ret;
+
+       wimlib_assert(ctx->unmount_to_daemon_mq_name != NULL &&
+                     ctx->daemon_to_unmount_mq_name != NULL);
 
        if (daemon)
                flags = O_RDONLY | O_CREAT;
        else
                flags = O_WRONLY | O_CREAT;
 
-       unmount_to_daemon_mq = mq_open(unmount_to_daemon_mq_name, flags, 
-                                      0700, NULL);
+       ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
+                                           flags, 0700, NULL);
 
-       if (unmount_to_daemon_mq == (mqd_t)-1) {
+       if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
                ERROR_WITH_ERRNO("mq_open()");
                ret = WIMLIB_ERR_MQUEUE;
-               goto err2;
+               goto out;
        }
 
        if (daemon)
@@ -610,40 +654,42 @@ static int open_message_queues(bool daemon)
        else
                flags = O_RDONLY | O_CREAT;
 
-       daemon_to_unmount_mq = mq_open(daemon_to_unmount_mq_name, flags, 
-                                      0700, NULL);
+       ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
+                                           flags, 0700, NULL);
 
-       if (daemon_to_unmount_mq == (mqd_t)-1) {
+       if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
                ERROR_WITH_ERRNO("mq_open()");
                ret = WIMLIB_ERR_MQUEUE;
-               goto err3;
+               goto out_close_unmount_to_daemon_mq;
        }
-       return 0;
-err3:
-       mq_close(unmount_to_daemon_mq);
-       mq_unlink(unmount_to_daemon_mq_name);
-err2:
-       FREE(daemon_to_unmount_mq_name);
-err1:
-       FREE(unmount_to_daemon_mq_name);
+       ret = 0;
+       goto out;
+out_close_unmount_to_daemon_mq:
+       mq_close(ctx->unmount_to_daemon_mq);
+       mq_unlink(ctx->unmount_to_daemon_mq_name);
+       ctx->unmount_to_daemon_mq = (mqd_t)-1;
+out:
        return ret;
 }
 
-static int mq_get_msgsize(mqd_t mq)
+/* Try to determine the maximum message size of a message queue.  The return
+ * value is the maximum message size, or a guess of 8192 bytes if it cannot be
+ * determined. */
+static long mq_get_msgsize(mqd_t mq)
 {
        static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
        FILE *fp;
        struct mq_attr attr;
-       int msgsize;
+       long msgsize;
 
-       if (mq_getattr(unmount_to_daemon_mq, &attr) == 0) {
+       if (mq_getattr(mq, &attr) == 0) {
                msgsize = attr.mq_msgsize;
        } else {
                ERROR_WITH_ERRNO("mq_getattr()");
                ERROR("Attempting to read %s", msgsize_max_file);
                fp = fopen(msgsize_max_file, "rb");
                if (fp) {
-                       if (fscanf(fp, "%d", &msgsize) != 1) {
+                       if (fscanf(fp, "%ld", &msgsize) != 1) {
                                ERROR("Assuming message size of 8192");
                                msgsize = 8192;
                        }
@@ -658,13 +704,44 @@ static int mq_get_msgsize(mqd_t mq)
        return msgsize;
 }
 
+static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
+                      char **mailbox_ret)
+{
+       long msgsize;
+       char *mailbox;
+
+       msgsize = mq_get_msgsize(mq);
+
+       if (msgsize < needed_msgsize) {
+               ERROR("Message queue max size must be at least %ld!",
+                     needed_msgsize);
+               return WIMLIB_ERR_MQUEUE;
+       }
+
+       mailbox = MALLOC(msgsize);
+       if (!mailbox) {
+               ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
+               return WIMLIB_ERR_NOMEM;
+       }
+       *msgsize_ret = msgsize;
+       *mailbox_ret = mailbox;
+       return 0;
+}
+
+static void unlink_message_queues(struct wimfs_context *ctx)
+{
+       mq_unlink(ctx->unmount_to_daemon_mq_name);
+       mq_unlink(ctx->daemon_to_unmount_mq_name);
+}
+
 /* Closes the message queues, which are allocated in static variables */
-static void close_message_queues()
+static void close_message_queues(struct wimfs_context *ctx)
 {
-       mq_close(unmount_to_daemon_mq);
-       mq_close(daemon_to_unmount_mq);
-       mq_unlink(unmount_to_daemon_mq_name);
-       mq_unlink(daemon_to_unmount_mq_name);
+       mq_close(ctx->unmount_to_daemon_mq);
+       ctx->unmount_to_daemon_mq = (mqd_t)(-1);
+       mq_close(ctx->daemon_to_unmount_mq);
+       ctx->daemon_to_unmount_mq = (mqd_t)(-1);
+       unlink_message_queues(ctx);
 }
 
 static int wimfs_access(const char *path, int mask)
@@ -673,6 +750,22 @@ static int wimfs_access(const char *path, int mask)
        return 0;
 }
 
+static void inode_update_lte_ptr(struct inode *inode,
+                                struct lookup_table_entry *old_lte,
+                                struct lookup_table_entry *new_lte)
+{
+       if (inode->lte == old_lte) {
+               inode->lte = new_lte;
+       } else {
+               for (unsigned i = 0; i < inode->num_ads; i++) {
+                       if (inode->ads_entries[i].lte == old_lte) {
+                               inode->ads_entries[i].lte = new_lte;
+                               break;
+                       }
+               }
+       }
+}
+
 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
                                      struct lookup_table *table)
 {
@@ -696,27 +789,34 @@ static int update_lte_of_staging_file(struct lookup_table_entry *lte,
                /* Merge duplicate lookup table entries */
                duplicate_lte->refcnt += lte->refcnt;
                list_del(&lte->staging_list);
+               inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
                free_lookup_table_entry(lte);
        } else {
                if (stat(lte->staging_file_name, &stbuf) != 0) {
                        ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
                        return WIMLIB_ERR_STAT;
                }
-               wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
-               lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
-               copy_hash(lte->hash, hash);
-               lte->resource_entry.original_size = stbuf.st_size;
-               lte->resource_entry.size = stbuf.st_size;
-               lte->lte_inode = NULL;
-               lookup_table_insert(table, lte);
+               if (stbuf.st_size == 0) {
+                       /* Zero-length stream.  No lookup table entry needed. */
+                       inode_update_lte_ptr(lte->lte_inode, lte, NULL);
+                       free_lookup_table_entry(lte);
+               } else {
+                       wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
+                       lte->resource_entry.original_size = stbuf.st_size;
+                       lte->resource_entry.size = stbuf.st_size;
+                       lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
+                       lte->lte_inode = NULL;
+                       copy_hash(lte->hash, hash);
+                       lookup_table_insert(table, lte);
+               }
        }
-
        return 0;
 }
 
 static int inode_close_fds(struct inode *inode)
 {
-       for (u16 i = 0, j = 0; j < inode->num_opened_fds; i++) {
+       u16 num_opened_fds = inode->num_opened_fds;
+       for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
                struct wimlib_fd *fd = inode->fds[i];
                if (fd) {
                        wimlib_assert(fd->f_inode == inode);
@@ -729,31 +829,24 @@ static int inode_close_fds(struct inode *inode)
        return 0;
 }
 
-/*static int dentry_close_fds(struct dentry *dentry, void *ignore)*/
-/*{*/
-       /*return inode_close_fds(dentry->d_inode);*/
-/*}*/
-
 /* Overwrites the WIM file, with changes saved. */
-static int rebuild_wim(WIMStruct *w, bool check_integrity)
+static int rebuild_wim(struct wimfs_context *ctx, bool check_integrity)
 {
        int ret;
        struct lookup_table_entry *lte, *tmp;
+       WIMStruct *w = ctx->wim;
 
 
        DEBUG("Closing all staging file descriptors.");
-       list_for_each_entry(lte, &staging_list, staging_list) {
+       list_for_each_entry(lte, &ctx->staging_list, staging_list) {
                ret = inode_close_fds(lte->lte_inode);
                if (ret != 0)
                        return ret;
        }
-       /*ret = for_dentry_in_tree(wim_root_dentry(w), dentry_close_fds, NULL);*/
-       /*if (ret != 0)*/
-               /*return ret;*/
 
        DEBUG("Calculating SHA1 checksums for all new staging files.");
-       list_for_each_entry_safe(lte, tmp, &staging_list, staging_list) {
-               ret = update_lte_of_staging_file(lte, w->lookup_table);
+       list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
+               ret = update_lte_of_staging_file(lte, ctx->wim->lookup_table);
                if (ret != 0)
                        return ret;
        }
@@ -777,7 +870,7 @@ static void wimfs_destroy(void *p)
         * through a message queue that indicates whether the --commit
         * option was specified or not. */
 
-       int msgsize;
+       long msgsize;
        struct timespec timeout;
        struct timeval now;
        ssize_t bytes_received;
@@ -785,15 +878,14 @@ static void wimfs_destroy(void *p)
        char commit;
        char check_integrity;
        char status;
+       char *mailbox;
+       struct wimfs_context *ctx = wimfs_get_context();
 
-       ret = open_message_queues(true);
-       if (ret != 0)
-               exit(1);
+       if (open_message_queues(ctx, true))
+               return;
 
-       msgsize = mq_get_msgsize(unmount_to_daemon_mq);
-       char msg[msgsize];
-       msg[0] = 0;
-       msg[1] = 0;
+       if (get_mailbox(ctx->unmount_to_daemon_mq, 2, &msgsize, &mailbox))
+               goto out_close_message_queues;
 
        /* Wait at most 3 seconds before giving up and discarding changes. */
        gettimeofday(&now, NULL);
@@ -802,48 +894,46 @@ static void wimfs_destroy(void *p)
        DEBUG("Waiting for message telling us whether to commit or not, and "
              "whether to include integrity checks.");
 
-       bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg, 
+       bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
                                         msgsize, NULL, &timeout);
-       commit = msg[0];
-       check_integrity = msg[1];
        if (bytes_received == -1) {
-               if (errno == ETIMEDOUT) {
-                       ERROR("Timed out.");
-               } else {
-                       ERROR_WITH_ERRNO("mq_timedreceive()");
-               }
+               ERROR_WITH_ERRNO("mq_timedreceive()");
                ERROR("Not committing.");
+               commit = 0;
+               check_integrity = 0;
        } else {
-               DEBUG("Received message: [%d %d]", msg[0], msg[1]);
+               DEBUG("Received message: [%d %d]", mailbox[0], mailbox[1]);
+               commit = mailbox[0];
+               check_integrity = mailbox[1];
        }
 
        status = 0;
-       if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
+       if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
                if (commit) {
-                       status = chdir(working_directory);
-                       if (status != 0) {
+                       ret = chdir(ctx->working_directory);
+                       if (ret == 0) {
+                               status = rebuild_wim(ctx, (check_integrity != 0));
+                       } else {
                                ERROR_WITH_ERRNO("chdir()");
                                status = WIMLIB_ERR_NOTDIR;
-                               goto done;
                        }
-                       status = rebuild_wim(w, (check_integrity != 0));
                }
-               ret = delete_staging_dir();
+               ret = delete_staging_dir(ctx);
                if (ret != 0) {
-                       ERROR_WITH_ERRNO("Failed to delete the staging "
-                                        "directory");
+                       ERROR("Failed to delete the staging directory");
                        if (status == 0)
                                status = ret;
                }
        } else {
                DEBUG("Read-only mount");
        }
-done:
-       DEBUG("Sending status %u", status);
-       ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
+       DEBUG("Sending status %hhd", status);
+       ret = mq_send(ctx->daemon_to_unmount_mq, &status, 1, 1);
        if (ret == -1)
                ERROR_WITH_ERRNO("Failed to send status to unmount process");
-       close_message_queues();
+       FREE(mailbox);
+out_close_message_queues:
+       close_message_queues(ctx);
 }
 
 #if 0
@@ -861,7 +951,7 @@ static int wimfs_fgetattr(const char *path, struct stat *stbuf,
                          struct fuse_file_info *fi)
 {
        struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
-       return inode_to_stbuf(fd->f_inode, fd->lte, stbuf);
+       return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
 }
 
 static int wimfs_ftruncate(const char *path, off_t size,
@@ -871,8 +961,8 @@ static int wimfs_ftruncate(const char *path, off_t size,
        int ret = ftruncate(fd->staging_fd, size);
        if (ret != 0)
                return ret;
-       if (fd->lte && size < fd->lte->resource_entry.original_size)
-               fd->lte->resource_entry.original_size = size;
+       if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
+               fd->f_lte->resource_entry.original_size = size;
        return 0;
 }
 
@@ -884,9 +974,10 @@ static int wimfs_getattr(const char *path, struct stat *stbuf)
        struct dentry *dentry;
        struct lookup_table_entry *lte;
        int ret;
+       struct wimfs_context *ctx = wimfs_get_context();
 
-       ret = lookup_resource(w, path,
-                             get_lookup_flags() | LOOKUP_FLAG_DIRECTORY_OK,
+       ret = lookup_resource(ctx->wim, path,
+                             get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
                              &dentry, &lte, NULL);
        if (ret != 0)
                return ret;
@@ -899,22 +990,24 @@ static int wimfs_getxattr(const char *path, const char *name, char *value,
                          size_t size)
 {
        int ret;
-       struct dentry *dentry;
+       struct inode *inode;
        struct ads_entry *ads_entry;
        size_t res_size;
        struct lookup_table_entry *lte;
+       struct wimfs_context *ctx = wimfs_get_context();
 
-       if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
+       if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
                return -ENOTSUP;
 
        if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
                return -ENOATTR;
        name += 5;
 
-       dentry = get_dentry(w, path);
-       if (!dentry)
+       inode = wim_pathname_to_inode(ctx->wim, path);
+       if (!inode)
                return -ENOENT;
-       ads_entry = inode_get_ads_entry(dentry->d_inode, name, NULL);
+
+       ads_entry = inode_get_ads_entry(inode, name, NULL);
        if (!ads_entry)
                return -ENOATTR;
 
@@ -923,11 +1016,14 @@ static int wimfs_getxattr(const char *path, const char *name, char *value,
 
        if (size == 0)
                return res_size;
+
        if (res_size > size)
                return -ERANGE;
+
        ret = read_full_wim_resource(lte, (u8*)value);
        if (ret != 0)
                return -EIO;
+
        return res_size;
 }
 #endif
@@ -939,6 +1035,7 @@ static int wimfs_link(const char *to, const char *from)
        const char *link_name;
        struct inode *inode;
        struct lookup_table_entry *lte;
+       WIMStruct *w = wimfs_get_WIMStruct();
 
        inode = wim_pathname_to_inode(w, to);
        if (!inode)
@@ -978,29 +1075,27 @@ static int wimfs_link(const char *to, const char *from)
 #ifdef ENABLE_XATTR
 static int wimfs_listxattr(const char *path, char *list, size_t size)
 {
-       struct dentry *dentry;
-       int ret;
-       char *p = list;
        size_t needed_size;
-       unsigned i;
        struct inode *inode;
-       if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
                return -ENOTSUP;
 
        /* List alternate data streams, or get the list size */
 
-       ret = lookup_resource(w, path, get_lookup_flags(), &dentry, NULL, NULL);
-       if (ret != 0)
-               return ret;
-       inode = dentry->d_inode;
+       inode = wim_pathname_to_inode(ctx->wim, path);
+       if (!inode)
+               return -ENOENT;
 
        if (size == 0) {
                needed_size = 0;
-               for (i = 0; i < inode->num_ads; i++)
+               for (u16 i = 0; i < inode->num_ads; i++)
                        needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
                return needed_size;
        } else {
-               for (i = 0; i < inode->num_ads; i++) {
+               char *p = list;
+               for (u16 i = 0; i < inode->num_ads; i++) {
                        needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
                        if (needed_size > size)
                                return -ERANGE;
@@ -1013,8 +1108,8 @@ static int wimfs_listxattr(const char *path, char *list, size_t size)
 }
 #endif
 
-/* 
- * Create a directory in the WIM.  
+/*
+ * Create a directory in the WIM.
  * @mode is currently ignored.
  */
 static int wimfs_mkdir(const char *path, mode_t mode)
@@ -1022,8 +1117,9 @@ static int wimfs_mkdir(const char *path, mode_t mode)
        struct dentry *parent;
        struct dentry *newdir;
        const char *basename;
-       
-       parent = get_parent_dentry(w, path);
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       parent = get_parent_dentry(ctx->wim, path);
        if (!parent)
                return -ENOENT;
 
@@ -1037,34 +1133,36 @@ static int wimfs_mkdir(const char *path, mode_t mode)
        newdir = new_dentry_with_inode(basename);
        newdir->d_inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
        newdir->d_inode->resolved = true;
-       newdir->d_inode->ino = next_ino++;
+       newdir->d_inode->ino = ctx->next_ino++;
        link_dentry(newdir, parent);
        return 0;
 }
 
-
 /* Creates a regular file. */
 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
 {
        const char *stream_name;
-       if ((mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
+       struct wimfs_context *ctx = wimfs_get_context();
+       if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
             && (stream_name = path_stream_name(path))) {
                /* Make an alternate data stream */
                struct ads_entry *new_entry;
-               struct dentry *dentry;
+               struct inode *inode;
 
                char *p = (char*)stream_name - 1;
                wimlib_assert(*p == ':');
                *p = '\0';
 
-               dentry = get_dentry(w, path);
-               if (!dentry || !dentry_is_regular_file(dentry))
+               inode = wim_pathname_to_inode(ctx->wim, path);
+               if (!inode)
                        return -ENOENT;
-               if (inode_get_ads_entry(dentry->d_inode, stream_name, NULL))
+               if (!inode_is_regular_file(inode))
+                       return -ENOENT;
+               if (inode_get_ads_entry(inode, stream_name, NULL))
                        return -EEXIST;
-               new_entry = inode_add_ads(dentry->d_inode, stream_name);
+               new_entry = inode_add_ads(inode, stream_name);
                if (!new_entry)
-                       return -ENOENT;
+                       return -ENOMEM;
        } else {
                struct dentry *dentry, *parent;
                const char *basename;
@@ -1073,7 +1171,7 @@ static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
 
                /* Make sure that the parent of @path exists and is a directory, and
                 * that the dentry named by @path does not already exist.  */
-               parent = get_parent_dentry(w, path);
+               parent = get_parent_dentry(ctx->wim, path);
                if (!parent)
                        return -ENOENT;
                if (!dentry_is_directory(parent))
@@ -1087,7 +1185,7 @@ static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
                if (!dentry)
                        return -ENOMEM;
                dentry->d_inode->resolved = true;
-               dentry->d_inode->ino = next_ino++;
+               dentry->d_inode->ino = ctx->next_ino++;
                link_dentry(dentry, parent);
        }
        return 0;
@@ -1104,9 +1202,10 @@ static int wimfs_open(const char *path, struct fuse_file_info *fi)
        struct inode *inode;
        u16 stream_idx;
        u32 stream_id;
+       struct wimfs_context *ctx = wimfs_get_context();
 
-       ret = lookup_resource(w, path, get_lookup_flags(), &dentry, &lte,
-                             &stream_idx);
+       ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
+                             &dentry, &lte, &stream_idx);
        if (ret != 0)
                return ret;
 
@@ -1128,7 +1227,7 @@ static int wimfs_open(const char *path, struct fuse_file_info *fi)
             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
                u64 size = (lte) ? wim_resource_size(lte) : 0;
                ret = extract_resource_to_staging_dir(inode, stream_id,
-                                                     &lte, size);
+                                                     &lte, size, ctx);
                if (ret != 0)
                        return ret;
        }
@@ -1154,8 +1253,9 @@ static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
        struct inode *inode;
        int ret;
        struct wimlib_fd *fd = NULL;
-       
-       inode = wim_pathname_to_inode(w, path);
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       inode = wim_pathname_to_inode(ctx->wim, path);
        if (!inode)
                return -ENOENT;
        if (!inode_is_directory(inode))
@@ -1167,9 +1267,9 @@ static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
 
 
 /*
- * Read data from a file in the WIM or in the staging directory. 
+ * Read data from a file in the WIM or in the staging directory.
  */
-static int wimfs_read(const char *path, char *buf, size_t size, 
+static int wimfs_read(const char *path, char *buf, size_t size,
                      off_t offset, struct fuse_file_info *fi)
 {
        struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
@@ -1177,13 +1277,13 @@ static int wimfs_read(const char *path, char *buf, size_t size,
        if (!fd)
                return -EBADF;
 
-       if (!fd->lte) /* Empty stream with no lookup table entry */
+       if (!fd->f_lte) /* Empty stream with no lookup table entry */
                return 0;
 
-       if (fd->lte->resource_location == RESOURCE_IN_STAGING_FILE) {
+       if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
                /* Read from staging file */
 
-               wimlib_assert(fd->lte->staging_file_name);
+               wimlib_assert(fd->f_lte->staging_file_name);
                wimlib_assert(fd->staging_fd != -1);
 
                ssize_t ret;
@@ -1198,14 +1298,14 @@ static int wimfs_read(const char *path, char *buf, size_t size,
        } else {
                /* Read from WIM */
 
-               u64 res_size = wim_resource_size(fd->lte);
-               
+               u64 res_size = wim_resource_size(fd->f_lte);
+
                if (offset > res_size)
                        return -EOVERFLOW;
 
                size = min(size, res_size - offset);
 
-               if (read_wim_resource(fd->lte, (u8*)buf,
+               if (read_wim_resource(fd->f_lte, (u8*)buf,
                                      size, offset, false) != 0)
                        return -EIO;
                return size;
@@ -1214,7 +1314,7 @@ static int wimfs_read(const char *path, char *buf, size_t size,
 
 /* Fills in the entries of the directory specified by @path using the
  * FUSE-provided function @filler.  */
-static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
+static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
                         off_t offset, struct fuse_file_info *fi)
 {
        struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
@@ -1245,14 +1345,15 @@ static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
 
 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
 {
-       struct dentry *dentry = get_dentry(w, path);
+       struct wimfs_context *ctx = wimfs_get_context();
+       struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
        int ret;
-       if (!dentry)
+       if (!inode)
                return -ENOENT;
-       if (!dentry_is_symlink(dentry))
+       if (!inode_is_symlink(inode))
                return -EINVAL;
 
-       ret = inode_readlink(dentry->d_inode, buf, buf_len, w);
+       ret = inode_readlink(inode, buf, buf_len, ctx->wim);
        if (ret > 0)
                ret = 0;
        return ret;
@@ -1276,24 +1377,26 @@ static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
 /* Remove an alternate data stream through the XATTR interface */
 static int wimfs_removexattr(const char *path, const char *name)
 {
-       struct dentry *dentry;
+       struct inode *inode;
        struct ads_entry *ads_entry;
        u16 ads_idx;
-       if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
                return -ENOTSUP;
 
        if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
                return -ENOATTR;
        name += 5;
 
-       dentry = get_dentry(w, path);
-       if (!dentry)
+       inode = wim_pathname_to_inode(ctx->wim, path);
+       if (!inode)
                return -ENOENT;
 
-       ads_entry = inode_get_ads_entry(dentry->d_inode, name, &ads_idx);
+       ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
        if (!ads_entry)
                return -ENOATTR;
-       inode_remove_ads(dentry->d_inode, ads_idx, w->lookup_table);
+       inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
        return 0;
 }
 #endif
@@ -1306,11 +1409,12 @@ static int wimfs_rename(const char *from, const char *to)
        struct dentry *parent_of_dst;
        char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
        u16 file_name_utf16_len, file_name_utf8_len;
+       WIMStruct *w = wimfs_get_WIMStruct();
        int ret;
 
        /* This rename() implementation currently only supports actual files
         * (not alternate data streams) */
-       
+
        src = get_dentry(w, from);
        if (!src)
                return -ENOENT;
@@ -1370,7 +1474,8 @@ static int wimfs_rename(const char *from, const char *to)
 static int wimfs_rmdir(const char *path)
 {
        struct dentry *dentry;
-       
+       WIMStruct *w = wimfs_get_WIMStruct();
+
        dentry = get_dentry(w, path);
        if (!dentry)
                return -ENOENT;
@@ -1394,15 +1499,16 @@ static int wimfs_setxattr(const char *path, const char *name,
        struct inode *inode;
        u8 value_hash[SHA1_HASH_SIZE];
        u16 ads_idx;
+       struct wimfs_context *ctx = wimfs_get_context();
 
-       if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
+       if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
                return -ENOTSUP;
 
        if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
                return -ENOATTR;
        name += 5;
 
-       inode = wim_pathname_to_inode(w, path);
+       inode = wim_pathname_to_inode(ctx->wim, path);
        if (!inode)
                return -ENOENT;
 
@@ -1410,7 +1516,7 @@ static int wimfs_setxattr(const char *path, const char *name,
        if (existing_ads_entry) {
                if (flags & XATTR_CREATE)
                        return -EEXIST;
-               inode_remove_ads(inode, ads_idx, w->lookup_table);
+               inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
        } else {
                if (flags & XATTR_REPLACE)
                        return -ENOATTR;
@@ -1421,7 +1527,7 @@ static int wimfs_setxattr(const char *path, const char *name,
 
        sha1_buffer((const u8*)value, size, value_hash);
 
-       existing_lte = __lookup_resource(w->lookup_table, value_hash);
+       existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
 
        if (existing_lte) {
                lte = existing_lte;
@@ -1443,7 +1549,7 @@ static int wimfs_setxattr(const char *path, const char *name,
                lte->resource_entry.size          = size;
                lte->resource_entry.flags         = 0;
                copy_hash(lte->hash, value_hash);
-               lookup_table_insert(w->lookup_table, lte);
+               lookup_table_insert(ctx->wim->lookup_table, lte);
        }
        new_ads_entry->lte = lte;
        return 0;
@@ -1455,8 +1561,9 @@ static int wimfs_symlink(const char *to, const char *from)
        struct dentry *dentry_parent, *dentry;
        const char *link_name;
        struct inode *inode;
-       
-       dentry_parent = get_parent_dentry(w, from);
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       dentry_parent = get_parent_dentry(ctx->wim, from);
        if (!dentry_parent)
                return -ENOENT;
        if (!dentry_is_directory(dentry_parent))
@@ -1473,10 +1580,10 @@ static int wimfs_symlink(const char *to, const char *from)
 
        inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
        inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
-       inode->ino         = next_ino++;
+       inode->ino         = ctx->next_ino++;
        inode->resolved    = true;
 
-       if (inode_set_symlink(inode, to, w->lookup_table, NULL) != 0)
+       if (inode_set_symlink(inode, to, ctx->wim->lookup_table, NULL) != 0)
                goto out_free_dentry;
 
        link_dentry(dentry, dentry_parent);
@@ -1496,9 +1603,10 @@ static int wimfs_truncate(const char *path, off_t size)
        u16 stream_idx;
        u32 stream_id;
        struct inode *inode;
-       
-       ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
-                             &lte, &stream_idx);
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
+                             &dentry, &lte, &stream_idx);
 
        if (ret != 0)
                return ret;
@@ -1524,7 +1632,7 @@ static int wimfs_truncate(const char *path, off_t size)
                /* File in WIM.  Extract it to the staging directory, but only
                 * the first @size bytes of it. */
                ret = extract_resource_to_staging_dir(inode, stream_id,
-                                                     &lte, size);
+                                                     &lte, size, ctx);
        }
        return ret;
 }
@@ -1534,27 +1642,27 @@ static int wimfs_unlink(const char *path)
 {
        struct dentry *dentry;
        struct lookup_table_entry *lte;
-       struct inode *inode;
        int ret;
        u16 stream_idx;
-       unsigned i;
-       
-       ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
-                             &lte, &stream_idx);
+       struct wimfs_context *ctx = wimfs_get_context();
+
+       ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
+                             &dentry, &lte, &stream_idx);
 
        if (ret != 0)
                return ret;
 
        if (stream_idx == 0)
-               remove_dentry(dentry, w->lookup_table);
+               remove_dentry(dentry, ctx->wim->lookup_table);
        else
-               inode_remove_ads(dentry->d_inode, stream_idx - 1, w->lookup_table);
+               inode_remove_ads(dentry->d_inode, stream_idx - 1,
+                                ctx->wim->lookup_table);
        return 0;
 }
 
 #ifdef HAVE_UTIMENSAT
-/* 
- * Change the timestamp on a file dentry. 
+/*
+ * Change the timestamp on a file dentry.
  *
  * Note that alternate data streams do not have their own timestamps.
  */
@@ -1562,6 +1670,8 @@ static int wimfs_utimens(const char *path, const struct timespec tv[2])
 {
        struct dentry *dentry;
        struct inode *inode;
+       WIMStruct *w = wimfs_get_WIMStruct();
+
        dentry = get_dentry(w, path);
        if (!dentry)
                return -ENOENT;
@@ -1597,10 +1707,10 @@ static int wimfs_utime(const char *path, struct utimbuf *times)
 }
 #endif
 
-/* Writes to a file in the WIM filesystem. 
+/* Writes to a file in the WIM filesystem.
  * It may be an alternate data stream, but here we don't even notice because we
  * just get a lookup table entry. */
-static int wimfs_write(const char *path, const char *buf, size_t size, 
+static int wimfs_write(const char *path, const char *buf, size_t size,
                       off_t offset, struct fuse_file_info *fi)
 {
        struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
@@ -1610,8 +1720,8 @@ static int wimfs_write(const char *path, const char *buf, size_t size,
        if (!fd)
                return -EBADF;
 
-       wimlib_assert(fd->lte);
-       wimlib_assert(fd->lte->staging_file_name);
+       wimlib_assert(fd->f_lte);
+       wimlib_assert(fd->f_lte->staging_file_name);
        wimlib_assert(fd->staging_fd != -1);
        wimlib_assert(fd->f_inode);
 
@@ -1676,19 +1786,20 @@ static struct fuse_operations wimfs_operations = {
 
 
 /* Mounts a WIM file. */
-WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
+WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
                           int flags, WIMStruct **additional_swms,
                           unsigned num_additional_swms)
 {
        int argc = 0;
        char *argv[16];
        int ret;
-       char *p;
+       char *dir_copy;
        struct lookup_table *joined_tab, *wim_tab_save;
        struct image_metadata *imd;
+       struct wimfs_context ctx;
 
        DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
-                       wim, image, dir, flags);
+             wim, image, dir, flags);
 
        if (!wim || !dir)
                return WIMLIB_ERR_INVALID_PARAM;
@@ -1707,7 +1818,7 @@ WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
                wim->lookup_table = joined_tab;
        }
 
-       ret = wimlib_select_image(wim, image);
+       ret = select_wim_image(wim, image);
 
        if (ret != 0)
                goto out;
@@ -1716,75 +1827,63 @@ WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
 
        DEBUG("Selected image %d", image);
 
-       next_ino = assign_inode_numbers(&imd->inode_list);
-
-       DEBUG("(next_ino = %"PRIu64")", next_ino);
-
-       /* Resolve all the lookup table entries of the dentry tree */
-       DEBUG("Resolving lookup table entries");
-       for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
-                          wim->lookup_table);
-
-       if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
-               imd->modified = true;
+       if (imd->root_dentry->refcnt != 1) {
+               ERROR("Cannot mount image that was just exported with "
+                     "wimlib_export()");
+               ret = WIMLIB_ERR_INVALID_PARAM;
+               goto out;
+       }
 
        if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
                       WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
                       WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
                flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
 
-       DEBUG("Getting current directory");
 
-       mount_dir = dir;
-       working_directory = getcwd(NULL, 0);
-       if (!working_directory) {
+       DEBUG("Initializing struct wimfs_context");
+       init_wimfs_context(&ctx);
+
+       DEBUG("Getting current directory");
+       ctx.working_directory = getcwd(NULL, 0);
+       if (!ctx.working_directory) {
                ERROR_WITH_ERRNO("Could not determine current directory");
                ret = WIMLIB_ERR_NOTDIR;
                goto out;
        }
 
-       DEBUG("Closing POSIX message queues");
-       /* XXX hack to get rid of the message queues if they already exist for
-        * some reason (maybe left over from a previous mount that wasn't
-        * unmounted correctly) */
-       ret = open_message_queues(true);
+       DEBUG("Unlinking message queues in case they already exist");
+       ret = set_message_queue_names(&ctx, dir);
        if (ret != 0)
-               goto out;
-       close_message_queues();
+               goto out_free_working_directory;
+       unlink_message_queues(&ctx);
 
        DEBUG("Preparing arguments to fuse_main()");
 
-
-       p = STRDUP(dir);
-       if (!p) {
-               ret = WIMLIB_ERR_NOMEM;
-               goto out;
-       }
+       dir_copy = STRDUP(dir);
+       if (!dir_copy)
+               goto out_free_message_queue_names;
 
        argv[argc++] = "imagex";
-       argv[argc++] = p;
+       argv[argc++] = dir_copy;
        argv[argc++] = "-s"; /* disable multi-threaded operation */
 
        if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
                argv[argc++] = "-d";
 
-       /* 
+       /*
         * We provide the use_ino option because we are going to assign inode
-        * numbers oursides.  We've already numbered the inodes with unique
-        * numbers in the assign_inode_numbers() function, and the static
-        * variable next_ino is set to the next available inode number.
+        * numbers oursides.  The inodes will be given unique numbers in the
+        * assign_inode_numbers() function, and the static variable @next_ino is
+        * set to the next available inode number.
         */
        char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
        argv[argc++] = "-o";
        argv[argc++] = optstring;
        if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
                /* Read-write mount.  Make the staging directory */
-               make_staging_dir();
-               if (!staging_dir_name) {
-                       FREE(p);
-                       ret = WIMLIB_ERR_MKDIR;
-                       goto out;
-               }
+               ret = make_staging_dir(&ctx);
+               if (ret != 0)
+                       goto out_free_dir_copy;
        } else {
                /* Read-only mount */
                strcat(optstring, ",ro");
@@ -1804,13 +1903,32 @@ WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
        }
 #endif
 
-       /* Set static variables. */
-       w = wim;
-       mount_flags = flags;
+       /* Mark dentry tree as modified if read-write mount. */
+       if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
+               imd->modified = true;
+
+       /* Resolve all the lookup table entries of the dentry tree */
+       DEBUG("Resolving lookup table entries");
+       for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
+                          wim->lookup_table);
 
-       ret = fuse_main(argc, argv, &wimfs_operations, NULL);
+       ctx.next_ino = assign_inode_numbers(&imd->inode_list);
+       DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
+
+       /* Finish initializing the filesystem context. */
+       ctx.wim = wim;
+       ctx.mount_flags = flags;
+
+       ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
        if (ret)
                ret = WIMLIB_ERR_FUSE;
+out_free_dir_copy:
+       FREE(dir_copy);
+out_free_message_queue_names:
+       free_message_queue_names(&ctx);
+out_free_working_directory:
+       FREE(ctx.working_directory);
+       ctx.working_directory = NULL;
 out:
        if (num_additional_swms) {
                free_lookup_table(wim->lookup_table);
@@ -1820,7 +1938,7 @@ out:
 }
 
 
-/* 
+/*
  * Unmounts the WIM file that was previously mounted on @dir by using
  * wimlib_mount().
  */
@@ -1832,31 +1950,36 @@ WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
        char msg[2];
        struct timeval now;
        struct timespec timeout;
-       int msgsize;
-       int errno_save;
+       long msgsize;
+       struct wimfs_context ctx;
+       char *mailbox;
 
-       mount_dir = dir;
+       init_wimfs_context(&ctx);
 
        /* Open message queues between the unmount process and the
         * filesystem daemon. */
-       ret = open_message_queues(false);
+       ret = set_message_queue_names(&ctx, dir);
        if (ret != 0)
-               return ret;
+               goto out;
+
+       ret = open_message_queues(&ctx, false);
+       if (ret != 0)
+               goto out_free_message_queue_names;
 
-       /* Send a message to the filesystem saying whether to commit or
+       /* Send a message to the filesystem daemon saying whether to commit or
         * not. */
        msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
        msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
 
-       DEBUG("Sending message: %s, %s", 
-                       (msg[0] == 0) ? "don't commit" : "commit",
-                       (msg[1] == 0) ? "don't check"  : "check");
-       ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
+       DEBUG("Sending message: %scommit, %scheck",
+                       (msg[0] ? "" : "don't "),
+                       (msg[1] ? "" : "don't "));
+       ret = mq_send(ctx.unmount_to_daemon_mq, msg, 2, 1);
        if (ret == -1) {
-               ERROR("Failed to notify filesystem daemon whether we want to "
-                     "commit changes or not");
-               close_message_queues();
-               return WIMLIB_ERR_MQUEUE;
+               ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
+                                "we want to commit changes or not");
+               ret = WIMLIB_ERR_MQUEUE;
+               goto out_close_message_queues;
        }
 
        /* Execute `fusermount -u', which is installed setuid root, to unmount
@@ -1868,26 +1991,29 @@ WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
         * send a message from this process to the filesystem daemon telling
         * whether --commit was specified or not.  However, after that, the
         * unmount process must wait for the filesystem daemon to finish writing
-        * the WIM file. 
+        * the WIM file.
         */
 
-
        pid = fork();
        if (pid == -1) {
                ERROR_WITH_ERRNO("Failed to fork()");
-               return WIMLIB_ERR_FORK;
+               ret = WIMLIB_ERR_FORK;
+               goto out_close_message_queues;
        }
        if (pid == 0) {
+               /* Child */
                execlp("fusermount", "fusermount", "-u", dir, NULL);
                ERROR_WITH_ERRNO("Failed to execute `fusermount'");
                exit(WIMLIB_ERR_FUSERMOUNT);
        }
 
+       /* Parent */
        ret = wait(&status);
        if (ret == -1) {
                ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
                                 "terminate");
-               return WIMLIB_ERR_FUSERMOUNT;
+               ret = WIMLIB_ERR_FUSERMOUNT;
+               goto out_close_message_queues;
        }
 
        if (status != 0) {
@@ -1900,26 +2026,32 @@ WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
                pid = fork();
                if (pid == -1) {
                        ERROR_WITH_ERRNO("Failed to fork()");
-                       return WIMLIB_ERR_FORK;
+                       ret = WIMLIB_ERR_FORK;
+                       goto out_close_message_queues;
                }
                if (pid == 0) {
+                       /* Child */
                        execlp("umount", "umount", dir, NULL);
                        ERROR_WITH_ERRNO("Failed to execute `umount'");
                        exit(WIMLIB_ERR_FUSERMOUNT);
                }
 
+               /* Parent */
                ret = wait(&status);
                if (ret == -1) {
                        ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
                                         "terminate");
-                       return WIMLIB_ERR_FUSERMOUNT;
+                       ret = WIMLIB_ERR_FUSERMOUNT;
+                       goto out_close_message_queues;
                }
                if (status != 0) {
                        ERROR("`umount' exited with failure status");
-                       return WIMLIB_ERR_FUSERMOUNT;
+                       ret = WIMLIB_ERR_FUSERMOUNT;
+                       goto out_close_message_queues;
                }
        }
 
+       wimlib_assert(status == 0);
 
        /* Wait for a message from the filesytem daemon indicating whether  the
         * filesystem was unmounted successfully (0) or an error occurred (1).
@@ -1930,42 +2062,51 @@ WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
         * filesystem daemon has crashed or failed for some reason.
         *
         * XXX come up with some method to determine if the filesystem
-        * daemon has really crashed or not. 
+        * daemon has really crashed or not.
         *
         * XXX Idea: have mount daemon write its PID into the WIM file header?
+        * No, this wouldn't work because we know the directory but not the WIM
+        * file...
         * */
 
        gettimeofday(&now, NULL);
        timeout.tv_sec = now.tv_sec + 600;
        timeout.tv_nsec = now.tv_usec * 1000;
 
-       msgsize = mq_get_msgsize(daemon_to_unmount_mq);
-       char mailbox[msgsize];
+       ret = get_mailbox(ctx.daemon_to_unmount_mq, 2, &msgsize, &mailbox);
+       if (ret != 0)
+               goto out_close_message_queues;
 
        mailbox[0] = 0;
        DEBUG("Waiting for message telling us whether the unmount was "
                        "successful or not.");
-       ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
-                             NULL, &timeout);
-       errno_save = errno;
-       close_message_queues();
+       ret = mq_timedreceive(ctx.daemon_to_unmount_mq, mailbox,
+                             msgsize, NULL, &timeout);
        if (ret == -1) {
-               if (errno_save == ETIMEDOUT) {
+               if (errno == ETIMEDOUT) {
                        ERROR("Timed out- probably the filesystem daemon "
                              "crashed and the WIM was not written "
                              "successfully.");
-                       return WIMLIB_ERR_TIMEOUT;
+                       ret = WIMLIB_ERR_TIMEOUT;
                } else {
-                       ERROR("mq_receive(): %s", strerror(errno_save));
-                       return WIMLIB_ERR_MQUEUE;
+                       ERROR_WITH_ERRNO("mq_receive()");
+                       ret = WIMLIB_ERR_MQUEUE;
                }
+               goto out_free_mailbox;
 
        }
-       DEBUG("Received message: %s",
-             (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
-       if (mailbox[0] != 0)
+       DEBUG("Received message: Unmount %s", (mailbox[0] ? "Failed" : "Ok"));
+       ret = mailbox[0];
+       if (ret)
                ERROR("Unmount failed");
-       return mailbox[0];
+out_free_mailbox:
+       FREE(mailbox);
+out_close_message_queues:
+       close_message_queues(&ctx);
+out_free_message_queue_names:
+       free_message_queue_names(&ctx);
+out:
+       return ret;
 }
 
 #else /* WITH_FUSE */
@@ -1973,7 +2114,7 @@ WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
 
 static inline int mount_unsupported_error()
 {
-       ERROR("WIMLIB was compiled with --without-fuse, which disables support "
+       ERROR("wimlib was compiled with --without-fuse, which disables support "
              "for mounting WIMs.");
        return WIMLIB_ERR_UNSUPPORTED;
 }
@@ -1983,7 +2124,7 @@ WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
        return mount_unsupported_error();
 }
 
-WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
+WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir,
                           int flags, WIMStruct **additional_swms,
                           unsigned num_additional_swms)
 {