wimlib-imagex: Add and document --pack-chunk-size option
[wimlib] / programs / imagex.c
1 /*
2  * imagex.c
3  *
4  * Use wimlib to create, modify, extract, mount, unmount, or display information
5  * about a WIM file
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h" /* Need for PACKAGE_VERSION, etc. */
27 #endif
28
29 #include "wimlib.h"
30 #include "wimlib_tchar.h"
31
32 #include <ctype.h>
33 #include <errno.h>
34
35 #include <inttypes.h>
36 #include <libgen.h>
37 #include <limits.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 #include <locale.h>
44
45 #ifdef HAVE_ALLOCA_H
46 #  include <alloca.h>
47 #endif
48
49 #ifdef __WIN32__
50 #  include "imagex-win32.h"
51 #  define tbasename     win32_wbasename
52 #  define OS_PREFERRED_PATH_SEPARATOR L'\\'
53 #  define OS_PREFERRED_PATH_SEPARATOR_STRING L"\\"
54 #else /* __WIN32__ */
55 #  include <glob.h>
56 #  include <getopt.h>
57 #  include <langinfo.h>
58 #  define tbasename     basename
59 #  define OS_PREFERRED_PATH_SEPARATOR '/'
60 #  define OS_PREFERRED_PATH_SEPARATOR_STRING "/"
61 static inline void set_fd_to_binary_mode(int fd)
62 {
63 }
64 #endif /* !__WIN32 */
65
66 /* Don't confuse the user by presenting the mounting commands on Windows when
67  * they will never work.  However on UNIX-like systems we always present them,
68  * even if WITH_FUSE is not defined at this point, as to not tie the build of
69  * wimlib-imagex to a specific build of wimlib.  */
70 #ifdef __WIN32__
71 #  define WIM_MOUNTING_SUPPORTED 0
72 #else
73 #  define WIM_MOUNTING_SUPPORTED 1
74 #endif
75
76 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
77
78 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
79                                 opts, NULL)) != -1)
80
81 enum {
82         CMD_NONE = -1,
83         CMD_APPEND = 0,
84         CMD_APPLY,
85         CMD_CAPTURE,
86         CMD_DELETE,
87         CMD_DIR,
88         CMD_EXPORT,
89         CMD_EXTRACT,
90         CMD_INFO,
91         CMD_JOIN,
92 #if WIM_MOUNTING_SUPPORTED
93         CMD_MOUNT,
94         CMD_MOUNTRW,
95 #endif
96         CMD_OPTIMIZE,
97         CMD_SPLIT,
98 #if WIM_MOUNTING_SUPPORTED
99         CMD_UNMOUNT,
100 #endif
101         CMD_UPDATE,
102         CMD_MAX,
103 };
104
105 static void usage(int cmd, FILE *fp);
106 static void usage_all(FILE *fp);
107 static void recommend_man_page(int cmd, FILE *fp);
108 static const tchar *get_cmd_string(int cmd, bool nospace);
109
110 static int imagex_progress_func(enum wimlib_progress_msg msg,
111                                 const union wimlib_progress_info *info);
112
113 static bool imagex_be_quiet = false;
114 static FILE *imagex_info_file;
115
116 #define imagex_printf(format, ...) \
117                 tfprintf(imagex_info_file, format, ##__VA_ARGS__)
118
119 enum {
120         IMAGEX_ALLOW_OTHER_OPTION,
121         IMAGEX_BOOT_OPTION,
122         IMAGEX_CHECK_OPTION,
123         IMAGEX_CHUNK_SIZE_OPTION,
124         IMAGEX_COMMAND_OPTION,
125         IMAGEX_COMMIT_OPTION,
126         IMAGEX_COMPRESS_OPTION,
127         IMAGEX_COMPRESS_SLOW_OPTION,
128         IMAGEX_CONFIG_OPTION,
129         IMAGEX_DEBUG_OPTION,
130         IMAGEX_DELTA_FROM_OPTION,
131         IMAGEX_DEREFERENCE_OPTION,
132         IMAGEX_DEST_DIR_OPTION,
133         IMAGEX_EXTRACT_XML_OPTION,
134         IMAGEX_FLAGS_OPTION,
135         IMAGEX_FORCE_OPTION,
136         IMAGEX_HARDLINK_OPTION,
137         IMAGEX_HEADER_OPTION,
138         IMAGEX_INCLUDE_INVALID_NAMES_OPTION,
139         IMAGEX_LAZY_OPTION,
140         IMAGEX_LOOKUP_TABLE_OPTION,
141         IMAGEX_METADATA_OPTION,
142         IMAGEX_NORPFIX_OPTION,
143         IMAGEX_NOCHECK_OPTION,
144         IMAGEX_NO_ACLS_OPTION,
145         IMAGEX_NO_WILDCARDS_OPTION,
146         IMAGEX_NOT_PIPABLE_OPTION,
147         IMAGEX_PACK_CHUNK_SIZE_OPTION,
148         IMAGEX_PACK_STREAMS_OPTION,
149         IMAGEX_PATH_OPTION,
150         IMAGEX_PIPABLE_OPTION,
151         IMAGEX_REBUILD_OPTION,
152         IMAGEX_RECOMPRESS_OPTION,
153         IMAGEX_RECURSIVE_OPTION,
154         IMAGEX_REF_OPTION,
155         IMAGEX_RESUME_OPTION,
156         IMAGEX_RPFIX_OPTION,
157         IMAGEX_SOFT_OPTION,
158         IMAGEX_SOURCE_LIST_OPTION,
159         IMAGEX_STAGING_DIR_OPTION,
160         IMAGEX_STREAMS_INTERFACE_OPTION,
161         IMAGEX_STRICT_ACLS_OPTION,
162         IMAGEX_STRICT_WILDCARDS_OPTION,
163         IMAGEX_SYMLINK_OPTION,
164         IMAGEX_THREADS_OPTION,
165         IMAGEX_TO_STDOUT_OPTION,
166         IMAGEX_UNIX_DATA_OPTION,
167         IMAGEX_UPDATE_OF_OPTION,
168         IMAGEX_VERBOSE_OPTION,
169         IMAGEX_XML_OPTION,
170 };
171
172 static const struct option apply_options[] = {
173         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
174         {T("hardlink"),    no_argument,       NULL, IMAGEX_HARDLINK_OPTION},
175         {T("symlink"),     no_argument,       NULL, IMAGEX_SYMLINK_OPTION},
176         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
177         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
178         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
179         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
180         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
181         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
182         {T("rpfix"),       no_argument,       NULL, IMAGEX_RPFIX_OPTION},
183         {T("norpfix"),     no_argument,       NULL, IMAGEX_NORPFIX_OPTION},
184         {T("include-invalid-names"), no_argument,       NULL, IMAGEX_INCLUDE_INVALID_NAMES_OPTION},
185
186         /* --resume is undocumented for now as it needs improvement.  */
187         {T("resume"),      no_argument,       NULL, IMAGEX_RESUME_OPTION},
188         {NULL, 0, NULL, 0},
189 };
190
191 static const struct option capture_or_append_options[] = {
192         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
193         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
194         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
195         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
196         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
197         {T("compress-slow"), no_argument,     NULL, IMAGEX_COMPRESS_SLOW_OPTION},
198         {T("chunk-size"),  required_argument, NULL, IMAGEX_CHUNK_SIZE_OPTION},
199         {T("pack-chunk-size"), required_argument, NULL, IMAGEX_PACK_CHUNK_SIZE_OPTION},
200         {T("solid-chunk-size"),required_argument, NULL, IMAGEX_PACK_CHUNK_SIZE_OPTION},
201         {T("pack-streams"), no_argument,      NULL, IMAGEX_PACK_STREAMS_OPTION},
202         {T("solid"),       no_argument,      NULL, IMAGEX_PACK_STREAMS_OPTION},
203         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
204         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
205         {T("flags"),       required_argument, NULL, IMAGEX_FLAGS_OPTION},
206         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
207         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
208         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
209         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
210         {T("source-list"), no_argument,       NULL, IMAGEX_SOURCE_LIST_OPTION},
211         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
212         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
213         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
214         {T("rpfix"),       no_argument,       NULL, IMAGEX_RPFIX_OPTION},
215         {T("norpfix"),     no_argument,       NULL, IMAGEX_NORPFIX_OPTION},
216         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
217         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
218         {T("update-of"),   required_argument, NULL, IMAGEX_UPDATE_OF_OPTION},
219         {T("delta-from"),  required_argument, NULL, IMAGEX_DELTA_FROM_OPTION},
220         {NULL, 0, NULL, 0},
221 };
222
223 static const struct option delete_options[] = {
224         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
225         {T("soft"),  no_argument, NULL, IMAGEX_SOFT_OPTION},
226         {NULL, 0, NULL, 0},
227 };
228
229 static const struct option dir_options[] = {
230         {T("path"), required_argument, NULL, IMAGEX_PATH_OPTION},
231         {NULL, 0, NULL, 0},
232 };
233
234 static const struct option export_options[] = {
235         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
236         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
237         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
238         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
239         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
240         {T("pack-streams"),no_argument,       NULL, IMAGEX_PACK_STREAMS_OPTION},
241         {T("solid"),       no_argument,       NULL, IMAGEX_PACK_STREAMS_OPTION},
242         {T("chunk-size"),  required_argument, NULL, IMAGEX_CHUNK_SIZE_OPTION},
243         {T("pack-chunk-size"), required_argument, NULL, IMAGEX_PACK_CHUNK_SIZE_OPTION},
244         {T("solid-chunk-size"),required_argument, NULL, IMAGEX_PACK_CHUNK_SIZE_OPTION},
245         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
246         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
247         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
248         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
249         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
250         {NULL, 0, NULL, 0},
251 };
252
253 static const struct option extract_options[] = {
254         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
255         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
256         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
257         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
258         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
259         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
260         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
261         {T("dest-dir"),    required_argument, NULL, IMAGEX_DEST_DIR_OPTION},
262         {T("to-stdout"),   no_argument,       NULL, IMAGEX_TO_STDOUT_OPTION},
263         {T("include-invalid-names"), no_argument, NULL, IMAGEX_INCLUDE_INVALID_NAMES_OPTION},
264         {T("strict-wildcards"), no_argument,  NULL, IMAGEX_STRICT_WILDCARDS_OPTION},
265         {T("no-wildcards"), no_argument,      NULL, IMAGEX_NO_WILDCARDS_OPTION},
266         {NULL, 0, NULL, 0},
267 };
268
269 static const struct option info_options[] = {
270         {T("boot"),         no_argument,       NULL, IMAGEX_BOOT_OPTION},
271         {T("check"),        no_argument,       NULL, IMAGEX_CHECK_OPTION},
272         {T("nocheck"),      no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
273         {T("no-check"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
274         {T("extract-xml"),  required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
275         {T("header"),       no_argument,       NULL, IMAGEX_HEADER_OPTION},
276         {T("lookup-table"), no_argument,       NULL, IMAGEX_LOOKUP_TABLE_OPTION},
277         {T("metadata"),     no_argument,       NULL, IMAGEX_METADATA_OPTION},
278         {T("xml"),          no_argument,       NULL, IMAGEX_XML_OPTION},
279         {NULL, 0, NULL, 0},
280 };
281
282 static const struct option join_options[] = {
283         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
284         {NULL, 0, NULL, 0},
285 };
286
287 static const struct option mount_options[] = {
288         {T("check"),             no_argument,       NULL, IMAGEX_CHECK_OPTION},
289         {T("debug"),             no_argument,       NULL, IMAGEX_DEBUG_OPTION},
290         {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
291         {T("ref"),               required_argument, NULL, IMAGEX_REF_OPTION},
292         {T("staging-dir"),       required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
293         {T("unix-data"),         no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
294         {T("allow-other"),       no_argument,       NULL, IMAGEX_ALLOW_OTHER_OPTION},
295         {NULL, 0, NULL, 0},
296 };
297
298 static const struct option optimize_options[] = {
299         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
300         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
301         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
302         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
303         {T("recompress"),  no_argument,       NULL, IMAGEX_RECOMPRESS_OPTION},
304         {T("compress-slow"), no_argument,     NULL, IMAGEX_COMPRESS_SLOW_OPTION},
305         {T("recompress-slow"), no_argument,     NULL, IMAGEX_COMPRESS_SLOW_OPTION},
306         {T("chunk-size"),  required_argument, NULL, IMAGEX_CHUNK_SIZE_OPTION},
307         {T("pack-chunk-size"), required_argument, NULL, IMAGEX_PACK_CHUNK_SIZE_OPTION},
308         {T("solid-chunk-size"),required_argument, NULL, IMAGEX_PACK_CHUNK_SIZE_OPTION},
309         {T("pack-streams"),no_argument,       NULL, IMAGEX_PACK_STREAMS_OPTION},
310         {T("solid"),       no_argument,       NULL, IMAGEX_PACK_STREAMS_OPTION},
311         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
312         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
313         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
314         {NULL, 0, NULL, 0},
315 };
316
317 static const struct option split_options[] = {
318         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
319         {NULL, 0, NULL, 0},
320 };
321
322 static const struct option unmount_options[] = {
323         {T("commit"),  no_argument, NULL, IMAGEX_COMMIT_OPTION},
324         {T("check"),   no_argument, NULL, IMAGEX_CHECK_OPTION},
325         {T("rebuild"), no_argument, NULL, IMAGEX_REBUILD_OPTION},
326         {T("lazy"),    no_argument, NULL, IMAGEX_LAZY_OPTION},
327         {NULL, 0, NULL, 0},
328 };
329
330 static const struct option update_options[] = {
331         /* Careful: some of the options here set the defaults for update
332          * commands, but the flags given to an actual update command (and not to
333          * `imagex update' itself are also handled in
334          * update_command_add_option().  */
335         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
336         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
337         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
338         {T("command"),     required_argument, NULL, IMAGEX_COMMAND_OPTION},
339
340         /* Default delete options */
341         {T("force"),       no_argument,       NULL, IMAGEX_FORCE_OPTION},
342         {T("recursive"),   no_argument,       NULL, IMAGEX_RECURSIVE_OPTION},
343
344         /* Global add option */
345         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
346
347         /* Default add options */
348         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
349         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
350         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
351         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
352         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
353         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
354
355         {NULL, 0, NULL, 0},
356 };
357
358 #if 0
359 #       define _format_attribute(type, format_str, args_start) \
360                         __attribute__((format(type, format_str, args_start)))
361 #else
362 #       define _format_attribute(type, format_str, args_start)
363 #endif
364
365 /* Print formatted error message to stderr. */
366 static void _format_attribute(printf, 1, 2)
367 imagex_error(const tchar *format, ...)
368 {
369         va_list va;
370         va_start(va, format);
371         tfputs(T("ERROR: "), stderr);
372         tvfprintf(stderr, format, va);
373         tputc(T('\n'), stderr);
374         va_end(va);
375 }
376
377 /* Print formatted error message to stderr. */
378 static void _format_attribute(printf, 1, 2)
379 imagex_error_with_errno(const tchar *format, ...)
380 {
381         int errno_save = errno;
382         va_list va;
383         va_start(va, format);
384         tfputs(T("ERROR: "), stderr);
385         tvfprintf(stderr, format, va);
386         tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
387         va_end(va);
388 }
389
390 static int
391 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
392 {
393         if (image == WIMLIB_NO_IMAGE) {
394                 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
395                              "       Please specify a 1-based image index or "
396                              "image name.  To list the images\n"
397                              "       contained in the WIM archive, run\n"
398                              "\n"
399                              "           %"TS" \"%"TS"\"\n"),
400                              image_name, wim_name,
401                              get_cmd_string(CMD_INFO, false), wim_name);
402                 return WIMLIB_ERR_INVALID_IMAGE;
403         }
404         return 0;
405 }
406
407 static int
408 verify_image_is_single(int image)
409 {
410         if (image == WIMLIB_ALL_IMAGES) {
411                 imagex_error(T("Cannot specify all images for this action!"));
412                 return WIMLIB_ERR_INVALID_IMAGE;
413         }
414         return 0;
415 }
416
417 static int
418 verify_image_exists_and_is_single(int image, const tchar *image_name,
419                                   const tchar *wim_name)
420 {
421         int ret;
422         ret = verify_image_exists(image, image_name, wim_name);
423         if (ret == 0)
424                 ret = verify_image_is_single(image);
425         return ret;
426 }
427
428 /* Parse the argument to --compress */
429 static int
430 get_compression_type(const tchar *optarg)
431 {
432         if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
433                 return WIMLIB_COMPRESSION_TYPE_LZX;
434         else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
435                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
436         else if (!tstrcasecmp(optarg, T("recovery")) || !tstrcasecmp(optarg, T("lzms")))
437                 return WIMLIB_COMPRESSION_TYPE_LZMS;
438         else if (!tstrcasecmp(optarg, T("none")))
439                 return WIMLIB_COMPRESSION_TYPE_NONE;
440         else {
441                 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
442                              "\"maximum\", \"fast\", or \"none\"."), optarg);
443                 return WIMLIB_COMPRESSION_TYPE_INVALID;
444         }
445 }
446
447 static void
448 set_compress_slow(void)
449 {
450         static const struct wimlib_lzx_compressor_params lzx_slow_params = {
451                 .hdr = {
452                         .size = sizeof(struct wimlib_lzx_compressor_params),
453                 },
454                 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
455                 .alg_params = {
456                         .slow = {
457                                 .use_len2_matches = 1,
458                                 .nice_match_length = 96,
459                                 .num_optim_passes = 4,
460                                 .max_search_depth = 100,
461                                 .max_matches_per_pos = 10,
462                                 .main_nostat_cost = 15,
463                                 .len_nostat_cost = 15,
464                                 .aligned_nostat_cost = 7,
465                         },
466                 },
467         };
468
469         static const struct wimlib_lzms_compressor_params lzms_slow_params = {
470                 .hdr = {
471                         .size = sizeof(struct wimlib_lzms_compressor_params),
472                 },
473                 .min_match_length = 2,
474                 .max_match_length = UINT32_MAX,
475                 .nice_match_length = 96,
476                 .max_search_depth = 100,
477                 .max_matches_per_pos = 10,
478                 .optim_array_length = 1024,
479         };
480
481         wimlib_set_default_compressor_params(WIMLIB_COMPRESSION_TYPE_LZX,
482                                              &lzx_slow_params.hdr);
483
484         wimlib_set_default_compressor_params(WIMLIB_COMPRESSION_TYPE_LZMS,
485                                              &lzms_slow_params.hdr);
486 }
487
488 struct string_set {
489         const tchar **strings;
490         unsigned num_strings;
491         unsigned num_alloc_strings;
492 };
493
494 #define STRING_SET_INITIALIZER \
495         { .strings = NULL, .num_strings = 0, .num_alloc_strings = 0, }
496
497 #define STRING_SET(_strings) \
498         struct string_set _strings = STRING_SET_INITIALIZER
499
500 static int
501 string_set_append(struct string_set *set, const tchar *glob)
502 {
503         unsigned num_alloc_strings = set->num_alloc_strings;
504
505         if (set->num_strings == num_alloc_strings) {
506                 const tchar **new_strings;
507
508                 num_alloc_strings += 4;
509                 new_strings = realloc(set->strings,
510                                       sizeof(set->strings[0]) * num_alloc_strings);
511                 if (!new_strings) {
512                         imagex_error(T("Out of memory!"));
513                         return -1;
514                 }
515                 set->strings = new_strings;
516                 set->num_alloc_strings = num_alloc_strings;
517         }
518         set->strings[set->num_strings++] = glob;
519         return 0;
520 }
521
522 static void
523 string_set_destroy(struct string_set *set)
524 {
525         free(set->strings);
526 }
527
528 static int
529 wim_reference_globs(WIMStruct *wim, struct string_set *set, int open_flags)
530 {
531         return wimlib_reference_resource_files(wim, set->strings,
532                                                set->num_strings,
533                                                WIMLIB_REF_FLAG_GLOB_ENABLE,
534                                                open_flags,
535                                                imagex_progress_func);
536 }
537
538 static void
539 do_resource_not_found_warning(const tchar *wimfile,
540                               const struct wimlib_wim_info *info,
541                               const struct string_set *refglobs)
542 {
543         if (info->total_parts > 1) {
544                 if (refglobs->num_strings == 0) {
545                         imagex_error(T("\"%"TS"\" is part of a split WIM. "
546                                        "Use --ref to specify the other parts."),
547                                      wimfile);
548                 } else {
549                         imagex_error(T("Perhaps the '--ref' argument did not "
550                                        "specify all other parts of the split "
551                                        "WIM?"));
552                 }
553         } else {
554                 imagex_error(T("If this is a delta WIM, use the --ref argument "
555                                "to specify the WIM(s) on which it is based."));
556         }
557 }
558
559 /* Returns the size of a file given its name, or -1 if the file does not exist
560  * or its size cannot be determined.  */
561 static off_t
562 file_get_size(const tchar *filename)
563 {
564         struct stat st;
565         if (tstat(filename, &st) == 0)
566                 return st.st_size;
567         else
568                 return (off_t)-1;
569 }
570
571 enum {
572         PARSE_STRING_SUCCESS = 0,
573         PARSE_STRING_FAILURE = 1,
574         PARSE_STRING_NONE = 2,
575 };
576
577 /*
578  * Parses a string token from an array of characters.
579  *
580  * Tokens are either whitespace-delimited, or double or single-quoted.
581  *
582  * @line_p:  Pointer to the pointer to the line of data.  Will be updated
583  *           to point past the string token iff the return value is
584  *           PARSE_STRING_SUCCESS.  If *len_p > 0, (*line_p)[*len_p - 1] must
585  *           be '\0'.
586  *
587  * @len_p:   @len_p initially stores the length of the line of data, which may
588  *           be 0, and it will be updated to the number of bytes remaining in
589  *           the line iff the return value is PARSE_STRING_SUCCESS.
590  *
591  * @fn_ret:  Iff the return value is PARSE_STRING_SUCCESS, a pointer to the
592  *           parsed string token will be returned here.
593  *
594  * Returns: PARSE_STRING_SUCCESS if a string token was successfully parsed; or
595  *          PARSE_STRING_FAILURE if the data was invalid due to a missing
596  *          closing quote; or PARSE_STRING_NONE if the line ended before the
597  *          beginning of a string token was found.
598  */
599 static int
600 parse_string(tchar **line_p, size_t *len_p, tchar **fn_ret)
601 {
602         size_t len = *len_p;
603         tchar *line = *line_p;
604         tchar *fn;
605         tchar quote_char;
606
607         /* Skip leading whitespace */
608         for (;;) {
609                 if (len == 0)
610                         return PARSE_STRING_NONE;
611                 if (!istspace(*line) && *line != T('\0'))
612                         break;
613                 line++;
614                 len--;
615         }
616         quote_char = *line;
617         if (quote_char == T('"') || quote_char == T('\'')) {
618                 /* Quoted string */
619                 line++;
620                 len--;
621                 fn = line;
622                 line = tmemchr(line, quote_char, len);
623                 if (!line) {
624                         imagex_error(T("Missing closing quote: %"TS), fn - 1);
625                         return PARSE_STRING_FAILURE;
626                 }
627         } else {
628                 /* Unquoted string.  Go until whitespace.  Line is terminated
629                  * by '\0', so no need to check 'len'. */
630                 fn = line;
631                 do {
632                         line++;
633                 } while (!istspace(*line) && *line != T('\0'));
634         }
635         *line = T('\0');
636         len -= line - fn;
637         *len_p = len;
638         *line_p = line;
639         *fn_ret = fn;
640         return PARSE_STRING_SUCCESS;
641 }
642
643 /* Parses a line of data (not an empty line or comment) in the source list file
644  * format.  (See the man page for 'wimlib-imagex capture' for details on this
645  * format and the meaning.)
646  *
647  * @line:  Line of data to be parsed.  line[len - 1] must be '\0', unless
648  *         len == 0.  The data in @line will be modified by this function call.
649  *
650  * @len:   Length of the line of data.
651  *
652  * @source:  On success, the capture source and target described by the line is
653  *           written into this destination.  Note that it will contain pointers
654  *           to data in the @line array.
655  *
656  * Returns true if the line was valid; false otherwise.  */
657 static bool
658 parse_source_list_line(tchar *line, size_t len,
659                        struct wimlib_capture_source *source)
660 {
661         /* SOURCE [DEST] */
662         int ret;
663         ret = parse_string(&line, &len, &source->fs_source_path);
664         if (ret != PARSE_STRING_SUCCESS)
665                 return false;
666         ret = parse_string(&line, &len, &source->wim_target_path);
667         if (ret == PARSE_STRING_NONE)
668                 source->wim_target_path = source->fs_source_path;
669         return ret != PARSE_STRING_FAILURE;
670 }
671
672 /* Returns %true if the given line of length @len > 0 is a comment or empty line
673  * in the source list file format. */
674 static bool
675 is_comment_line(const tchar *line, size_t len)
676 {
677         for (;;) {
678                 if (*line == T('#'))
679                         return true;
680                 if (!istspace(*line) && *line != T('\0'))
681                         return false;
682                 ++line;
683                 --len;
684                 if (len == 0)
685                         return true;
686         }
687 }
688
689 static ssize_t
690 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
691 {
692         ssize_t nlines = 0;
693         tchar *contents = *contents_p;
694         size_t nchars = *nchars_p;
695         size_t i;
696
697         for (i = 0; i < nchars; i++)
698                 if (contents[i] == T('\n'))
699                         nlines++;
700
701         /* Handle last line not terminated by a newline */
702         if (nchars != 0 && contents[nchars - 1] != T('\n')) {
703                 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
704                 if (!contents) {
705                         imagex_error(T("Out of memory!"));
706                         return -1;
707                 }
708                 contents[nchars] = T('\n');
709                 *contents_p = contents;
710                 nchars++;
711                 nlines++;
712         }
713         *nchars_p = nchars;
714         return nlines;
715 }
716
717 /* Parses a file in the source list format.  (See the man page for
718  * 'wimlib-imagex capture' for details on this format and the meaning.)
719  *
720  * @source_list_contents:  Contents of the source list file.  Note that this
721  *                         buffer will be modified to save memory allocations,
722  *                         and cannot be freed until the returned array of
723  *                         wimlib_capture_source's has also been freed.
724  *
725  * @source_list_nbytes:    Number of bytes of data in the @source_list_contents
726  *                         buffer.
727  *
728  * @nsources_ret:          On success, the length of the returned array is
729  *                         returned here.
730  *
731  * Returns:   An array of `struct wimlib_capture_source's that can be passed to
732  * the wimlib_add_image_multisource() function to specify how a WIM image is to
733  * be created.  */
734 static struct wimlib_capture_source *
735 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
736                   size_t *nsources_ret)
737 {
738         ssize_t nlines;
739         tchar *p;
740         struct wimlib_capture_source *sources;
741         size_t i, j;
742
743         nlines = text_file_count_lines(source_list_contents_p,
744                                        &source_list_nchars);
745         if (nlines < 0)
746                 return NULL;
747
748         /* Always allocate at least 1 slot, just in case the implementation of
749          * calloc() returns NULL if 0 bytes are requested. */
750         sources = calloc(nlines ?: 1, sizeof(*sources));
751         if (!sources) {
752                 imagex_error(T("out of memory"));
753                 return NULL;
754         }
755         p = *source_list_contents_p;
756         j = 0;
757         for (i = 0; i < nlines; i++) {
758                 /* XXX: Could use rawmemchr() here instead, but it may not be
759                  * available on all platforms. */
760                 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
761                 size_t len = endp - p + 1;
762                 *endp = T('\0');
763                 if (!is_comment_line(p, len)) {
764                         if (!parse_source_list_line(p, len, &sources[j++])) {
765                                 free(sources);
766                                 return NULL;
767                         }
768                 }
769                 p = endp + 1;
770
771         }
772         *nsources_ret = j;
773         return sources;
774 }
775
776
777 enum capture_config_section {
778         CAPTURE_CONFIG_NO_SECTION,
779         CAPTURE_CONFIG_EXCLUSION_SECTION,
780         CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
781         CAPTURE_CONFIG_IGNORE_SECTION,
782 };
783
784 enum {
785         CAPTURE_CONFIG_INVALID_SECTION,
786         CAPTURE_CONFIG_CHANGED_SECTION,
787         CAPTURE_CONFIG_SAME_SECTION,
788 };
789
790 static int
791 check_config_section(tchar *line, size_t len,
792                      enum capture_config_section *cur_section)
793 {
794         while (istspace(*line))
795                 line++;
796
797         if (*line != T('['))
798                 return CAPTURE_CONFIG_SAME_SECTION;
799
800         line++;
801         tchar *endbrace = tstrrchr(line, T(']'));
802         if (!endbrace)
803                 return CAPTURE_CONFIG_SAME_SECTION;
804
805         if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
806                 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
807         } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
808                 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
809         } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
810                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
811                 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
812                          "of capture config file\n"),
813                        stderr);
814         } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
815                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
816                 tfputs(T("WARNING: Ignoring [AlignmentList] section "
817                          "of capture config file\n"),
818                        stderr);
819         } else {
820                 imagex_error(T("Invalid capture config file section \"%"TS"\""),
821                              line - 1);
822                 return CAPTURE_CONFIG_INVALID_SECTION;
823         }
824         return CAPTURE_CONFIG_CHANGED_SECTION;
825 }
826
827
828 static bool
829 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
830                          tchar *pat)
831 {
832         if (pat_list->num_pats == pat_list->num_allocated_pats) {
833                 tchar **pats;
834                 size_t num_allocated_pats = pat_list->num_pats + 8;
835
836                 pats = realloc(pat_list->pats,
837                                num_allocated_pats * sizeof(pat_list->pats[0]));
838                 if (!pats) {
839                         imagex_error(T("Out of memory!"));
840                         return false;
841                 }
842                 pat_list->pats = pats;
843                 pat_list->num_allocated_pats = num_allocated_pats;
844         }
845         pat_list->pats[pat_list->num_pats++] = pat;
846         return true;
847 }
848
849 static bool
850 parse_capture_config_line(tchar *line, size_t len,
851                           enum capture_config_section *cur_section,
852                           struct wimlib_capture_config *config)
853 {
854         tchar *filename;
855         int ret;
856
857         ret = check_config_section(line, len, cur_section);
858         if (ret == CAPTURE_CONFIG_INVALID_SECTION)
859                 return false;
860         if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
861                 return true;
862
863         switch (*cur_section) {
864         case CAPTURE_CONFIG_NO_SECTION:
865                 imagex_error(T("Line \"%"TS"\" is not in a section "
866                                "(such as [ExclusionList]"), line);
867                 return false;
868         case CAPTURE_CONFIG_EXCLUSION_SECTION:
869                 if (parse_string(&line, &len, &filename) != PARSE_STRING_SUCCESS)
870                         return false;
871                 return pattern_list_add_pattern(&config->exclusion_pats,
872                                                 filename);
873         case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
874                 if (parse_string(&line, &len, &filename) != PARSE_STRING_SUCCESS)
875                         return false;
876                 return pattern_list_add_pattern(&config->exclusion_exception_pats,
877                                                 filename);
878         case CAPTURE_CONFIG_IGNORE_SECTION:
879                 return true;
880         }
881         return false;
882 }
883
884 static int
885 parse_capture_config(tchar **contents_p, size_t nchars,
886                      struct wimlib_capture_config *config)
887 {
888         ssize_t nlines;
889         tchar *p;
890         size_t i;
891         enum capture_config_section cur_section;
892
893         memset(config, 0, sizeof(*config));
894
895         nlines = text_file_count_lines(contents_p, &nchars);
896         if (nlines < 0)
897                 return -1;
898
899         cur_section = CAPTURE_CONFIG_NO_SECTION;
900         p = *contents_p;
901         for (i = 0; i < nlines; i++) {
902                 tchar *endp = tmemchr(p, T('\n'), nchars);
903                 size_t len = endp - p + 1;
904                 *endp = T('\0');
905                 if (!is_comment_line(p, len))
906                         if (!parse_capture_config_line(p, len, &cur_section, config))
907                                 return -1;
908                 p = endp + 1;
909
910         }
911         return 0;
912 }
913
914 /* Reads the contents of a file into memory. */
915 static char *
916 file_get_contents(const tchar *filename, size_t *len_ret)
917 {
918         struct stat stbuf;
919         void *buf = NULL;
920         size_t len;
921         FILE *fp;
922
923         if (tstat(filename, &stbuf) != 0) {
924                 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
925                 goto out;
926         }
927         len = stbuf.st_size;
928
929         fp = tfopen(filename, T("rb"));
930         if (!fp) {
931                 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
932                 goto out;
933         }
934
935         buf = malloc(len ? len : 1);
936         if (!buf) {
937                 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
938                                "contents of file \"%"TS"\""), len, filename);
939                 goto out_fclose;
940         }
941         if (fread(buf, 1, len, fp) != len) {
942                 imagex_error_with_errno(T("Failed to read %zu bytes from the "
943                                           "file \"%"TS"\""), len, filename);
944                 goto out_free_buf;
945         }
946         *len_ret = len;
947         goto out_fclose;
948 out_free_buf:
949         free(buf);
950         buf = NULL;
951 out_fclose:
952         fclose(fp);
953 out:
954         return buf;
955 }
956
957 /* Read standard input until EOF and return the full contents in a malloc()ed
958  * buffer and the number of bytes of data in @len_ret.  Returns NULL on read
959  * error. */
960 static char *
961 stdin_get_contents(size_t *len_ret)
962 {
963         /* stdin can, of course, be a pipe or other non-seekable file, so the
964          * total length of the data cannot be pre-determined */
965         char *buf = NULL;
966         size_t newlen = 1024;
967         size_t pos = 0;
968         size_t inc = 1024;
969         for (;;) {
970                 char *p = realloc(buf, newlen);
971                 size_t bytes_read, bytes_to_read;
972                 if (!p) {
973                         imagex_error(T("out of memory while reading stdin"));
974                         break;
975                 }
976                 buf = p;
977                 bytes_to_read = newlen - pos;
978                 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
979                 pos += bytes_read;
980                 if (bytes_read != bytes_to_read) {
981                         if (feof(stdin)) {
982                                 *len_ret = pos;
983                                 return buf;
984                         } else {
985                                 imagex_error_with_errno(T("error reading stdin"));
986                                 break;
987                         }
988                 }
989                 newlen += inc;
990                 inc *= 3;
991                 inc /= 2;
992         }
993         free(buf);
994         return NULL;
995 }
996
997
998 static tchar *
999 translate_text_to_tstr(char *text, size_t num_bytes, size_t *num_tchars_ret)
1000 {
1001 #ifndef __WIN32__
1002         /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
1003          * */
1004         *num_tchars_ret = num_bytes;
1005         return text;
1006 #else /* !__WIN32__ */
1007         /* On Windows, translate the text to UTF-16LE */
1008         wchar_t *text_wstr;
1009         size_t num_wchars;
1010
1011         if (num_bytes >= 2 &&
1012             (((unsigned char)text[0] == 0xff && (unsigned char)text[1] == 0xfe) ||
1013              ((unsigned char)text[0] <= 0x7f && (unsigned char)text[1] == 0x00)))
1014         {
1015                 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
1016                  * with something that looks like an ASCII character encoded as
1017                  * a UTF-16LE code unit.  Assume the file is encoded as
1018                  * UTF-16LE.  This is not a 100% reliable check. */
1019                 num_wchars = num_bytes / 2;
1020                 text_wstr = (wchar_t*)text;
1021         } else {
1022                 /* File does not look like UTF-16LE.  Assume it is encoded in
1023                  * the current Windows code page.  I think these are always
1024                  * ASCII-compatible, so any so-called "plain-text" (ASCII) files
1025                  * should work as expected. */
1026                 text_wstr = win32_mbs_to_wcs(text,
1027                                              num_bytes,
1028                                              &num_wchars);
1029                 free(text);
1030         }
1031         *num_tchars_ret = num_wchars;
1032         return text_wstr;
1033 #endif /* __WIN32__ */
1034 }
1035
1036 static tchar *
1037 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
1038 {
1039         char *contents;
1040         size_t num_bytes;
1041
1042         contents = file_get_contents(filename, &num_bytes);
1043         if (!contents)
1044                 return NULL;
1045         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
1046 }
1047
1048 static tchar *
1049 stdin_get_text_contents(size_t *num_tchars_ret)
1050 {
1051         char *contents;
1052         size_t num_bytes;
1053
1054         contents = stdin_get_contents(&num_bytes);
1055         if (!contents)
1056                 return NULL;
1057         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
1058 }
1059
1060 #define TO_PERCENT(numerator, denominator) \
1061         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
1062
1063 #define GIBIBYTE_MIN_NBYTES 10000000000ULL
1064 #define MEBIBYTE_MIN_NBYTES 10000000ULL
1065 #define KIBIBYTE_MIN_NBYTES 10000ULL
1066
1067 static unsigned
1068 get_unit(uint64_t total_bytes, const tchar **name_ret)
1069 {
1070         if (total_bytes >= GIBIBYTE_MIN_NBYTES) {
1071                 *name_ret = T("GiB");
1072                 return 30;
1073         } else if (total_bytes >= MEBIBYTE_MIN_NBYTES) {
1074                 *name_ret = T("MiB");
1075                 return 20;
1076         } else if (total_bytes >= KIBIBYTE_MIN_NBYTES) {
1077                 *name_ret = T("KiB");
1078                 return 10;
1079         } else {
1080                 *name_ret = T("bytes");
1081                 return 0;
1082         }
1083 }
1084
1085 static struct wimlib_progress_info_scan last_scan_progress;
1086
1087 static void
1088 report_scan_progress(const struct wimlib_progress_info_scan *scan, bool done)
1089 {
1090         uint64_t prev_count, cur_count;
1091
1092         prev_count = last_scan_progress.num_nondirs_scanned +
1093                      last_scan_progress.num_dirs_scanned;
1094         cur_count = scan->num_nondirs_scanned + scan->num_dirs_scanned;
1095
1096         if (done || prev_count == 0 || cur_count >= prev_count + 100 ||
1097             cur_count % 128 == 0)
1098         {
1099                 unsigned unit_shift;
1100                 const tchar *unit_name;
1101
1102                 unit_shift = get_unit(scan->num_bytes_scanned, &unit_name);
1103                 imagex_printf(T("\r%"PRIu64" %"TS" scanned (%"PRIu64" files, "
1104                                 "%"PRIu64" directories)    "),
1105                               scan->num_bytes_scanned >> unit_shift,
1106                               unit_name,
1107                               scan->num_nondirs_scanned,
1108                               scan->num_dirs_scanned);
1109                 last_scan_progress = *scan;
1110         }
1111 }
1112
1113 /* Progress callback function passed to various wimlib functions. */
1114 static int
1115 imagex_progress_func(enum wimlib_progress_msg msg,
1116                      const union wimlib_progress_info *info)
1117 {
1118         unsigned percent_done;
1119         unsigned unit_shift;
1120         const tchar *unit_name;
1121
1122         if (imagex_be_quiet)
1123                 return 0;
1124         switch (msg) {
1125         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
1126                 {
1127                         static bool first = true;
1128                         if (first) {
1129                                 imagex_printf(T("Writing %"TS"-compressed data "
1130                                                 "using %u thread%"TS"\n"),
1131                                               wimlib_get_compression_type_string(
1132                                                         info->write_streams.compression_type),
1133                                         info->write_streams.num_threads,
1134                                         (info->write_streams.num_threads == 1) ? T("") : T("s"));
1135                                 first = false;
1136                         }
1137                 }
1138                 unit_shift = get_unit(info->write_streams.total_bytes, &unit_name);
1139                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
1140                                           info->write_streams.total_bytes);
1141
1142                 if (info->write_streams.total_parts <= 1) {
1143                         imagex_printf(T("\r%"PRIu64" %"TS" of %"PRIu64" %"TS" (uncompressed) "
1144                                 "written (%u%% done)"),
1145                                 info->write_streams.completed_bytes >> unit_shift,
1146                                 unit_name,
1147                                 info->write_streams.total_bytes >> unit_shift,
1148                                 unit_name,
1149                                 percent_done);
1150                 } else {
1151                         imagex_printf(T("\rWriting resources from part %u of %u: "
1152                                   "%"PRIu64 " %"TS" of %"PRIu64" %"TS" (%u%%) written"),
1153                                 (info->write_streams.completed_parts ==
1154                                         info->write_streams.total_parts) ?
1155                                                 info->write_streams.completed_parts :
1156                                                 info->write_streams.completed_parts + 1,
1157                                 info->write_streams.total_parts,
1158                                 info->write_streams.completed_bytes >> unit_shift,
1159                                 unit_name,
1160                                 info->write_streams.total_bytes >> unit_shift,
1161                                 unit_name,
1162                                 percent_done);
1163                 }
1164                 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
1165                         imagex_printf(T("\n"));
1166                 break;
1167         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
1168                 imagex_printf(T("Scanning \"%"TS"\""), info->scan.source);
1169                 if (*info->scan.wim_target_path) {
1170                         imagex_printf(T(" (loading as WIM path: "
1171                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\")...\n"),
1172                                info->scan.wim_target_path);
1173                 } else {
1174                         imagex_printf(T("\n"));
1175                 }
1176                 memset(&last_scan_progress, 0, sizeof(last_scan_progress));
1177                 break;
1178         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
1179                 switch (info->scan.status) {
1180                 case WIMLIB_SCAN_DENTRY_OK:
1181                         report_scan_progress(&info->scan, false);
1182                         break;
1183                 case WIMLIB_SCAN_DENTRY_EXCLUDED:
1184                         imagex_printf(T("\nExcluding \"%"TS"\" from capture\n"), info->scan.cur_path);
1185                         break;
1186                 case WIMLIB_SCAN_DENTRY_UNSUPPORTED:
1187                         imagex_printf(T("\nWARNING: Excluding unsupported file or directory\n"
1188                                         "         \"%"TS"\" from capture\n"), info->scan.cur_path);
1189                         break;
1190                 case WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK:
1191                         imagex_printf(T("\nWARNING: Ignoring absolute symbolic link "
1192                                         "with out-of-tree target:\n"
1193                                         "           \"%"TS"\" => \"%"TS"\"\n"
1194                                         "           (Use --norpfix to capture "
1195                                         "absolute symbolic links as-is)\n"),
1196                                         info->scan.cur_path, info->scan.symlink_target);
1197                         break;
1198                 }
1199                 break;
1200         case WIMLIB_PROGRESS_MSG_SCAN_END:
1201                 report_scan_progress(&info->scan, true);
1202                 imagex_printf(T("\n"));
1203                 break;
1204         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
1205                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1206                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1207                                           info->integrity.total_bytes);
1208                 imagex_printf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" %"TS" "
1209                         "of %"PRIu64" %"TS" (%u%%) done"),
1210                         info->integrity.filename,
1211                         info->integrity.completed_bytes >> unit_shift,
1212                         unit_name,
1213                         info->integrity.total_bytes >> unit_shift,
1214                         unit_name,
1215                         percent_done);
1216                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1217                         imagex_printf(T("\n"));
1218                 break;
1219         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
1220                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1221                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1222                                           info->integrity.total_bytes);
1223                 imagex_printf(T("\rCalculating integrity table for WIM: %"PRIu64" %"TS" "
1224                           "of %"PRIu64" %"TS" (%u%%) done"),
1225                         info->integrity.completed_bytes >> unit_shift,
1226                         unit_name,
1227                         info->integrity.total_bytes >> unit_shift,
1228                         unit_name,
1229                         percent_done);
1230                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1231                         imagex_printf(T("\n"));
1232                 break;
1233         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
1234                 imagex_printf(T("Applying image %d (\"%"TS"\") from \"%"TS"\" "
1235                           "to %"TS" \"%"TS"\"\n"),
1236                         info->extract.image,
1237                         info->extract.image_name,
1238                         info->extract.wimfile_name,
1239                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
1240                          T("NTFS volume") : T("directory")),
1241                         info->extract.target);
1242                 break;
1243         case WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN:
1244                 if (info->extract.extract_root_wim_source_path[0] != T('\0')) {
1245                         imagex_printf(T("Extracting "
1246                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\" "
1247                                   "from image %d (\"%"TS"\") "
1248                                   "in \"%"TS"\" to \"%"TS"\"\n"),
1249                                 info->extract.extract_root_wim_source_path,
1250                                 info->extract.image,
1251                                 info->extract.image_name,
1252                                 info->extract.wimfile_name,
1253                                 info->extract.target);
1254                 }
1255                 break;
1256         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1257                 percent_done = TO_PERCENT(info->extract.completed_bytes,
1258                                           info->extract.total_bytes);
1259                 unit_shift = get_unit(info->extract.total_bytes, &unit_name);
1260                 imagex_printf(T("\rExtracting files: "
1261                           "%"PRIu64" %"TS" of %"PRIu64" %"TS" (%u%%) done"),
1262                         info->extract.completed_bytes >> unit_shift,
1263                         unit_name,
1264                         info->extract.total_bytes >> unit_shift,
1265                         unit_name,
1266                         percent_done);
1267                 if (info->extract.completed_bytes >= info->extract.total_bytes)
1268                         imagex_printf(T("\n"));
1269                 break;
1270         case WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN:
1271                 if (info->extract.total_parts != 1) {
1272                         imagex_printf(T("\nReading split pipable WIM part %u of %u\n"),
1273                                       info->extract.part_number,
1274                                       info->extract.total_parts);
1275                 }
1276                 break;
1277         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1278                 if (info->extract.extract_root_wim_source_path[0] == T('\0'))
1279                         imagex_printf(T("Setting timestamps on all extracted files...\n"));
1280                 break;
1281         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1282                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1283                         imagex_printf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1284                                 info->extract.target);
1285                 }
1286                 break;
1287         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1288                 percent_done = TO_PERCENT(info->split.completed_bytes,
1289                                           info->split.total_bytes);
1290                 unit_shift = get_unit(info->split.total_bytes, &unit_name);
1291                 imagex_printf(T("Writing \"%"TS"\" (part %u of %u): %"PRIu64" %"TS" of "
1292                           "%"PRIu64" %"TS" (%u%%) written\n"),
1293                         info->split.part_name,
1294                         info->split.cur_part_number,
1295                         info->split.total_parts,
1296                         info->split.completed_bytes >> unit_shift,
1297                         unit_name,
1298                         info->split.total_bytes >> unit_shift,
1299                         unit_name,
1300                         percent_done);
1301                 break;
1302         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1303                 if (info->split.completed_bytes == info->split.total_bytes) {
1304                         imagex_printf(T("Finished writing split WIM part %u of %u\n"),
1305                                 info->split.cur_part_number,
1306                                 info->split.total_parts);
1307                 }
1308                 break;
1309         case WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND:
1310                 switch (info->update.command->op) {
1311                 case WIMLIB_UPDATE_OP_DELETE:
1312                         imagex_printf(T("Deleted WIM path "
1313                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1314                                 info->update.command->delete_.wim_path);
1315                         break;
1316                 case WIMLIB_UPDATE_OP_RENAME:
1317                         imagex_printf(T("Renamed WIM path "
1318                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\" => "
1319                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1320                                 info->update.command->rename.wim_source_path,
1321                                 info->update.command->rename.wim_target_path);
1322                         break;
1323                 case WIMLIB_UPDATE_OP_ADD:
1324                 default:
1325                         break;
1326                 }
1327                 break;
1328         default:
1329                 break;
1330         }
1331         fflush(imagex_info_file);
1332         return 0;
1333 }
1334
1335 static unsigned
1336 parse_num_threads(const tchar *optarg)
1337 {
1338         tchar *tmp;
1339         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1340         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1341                 imagex_error(T("Number of threads must be a non-negative integer!"));
1342                 return UINT_MAX;
1343         } else {
1344                 return ul_nthreads;
1345         }
1346 }
1347
1348 static uint32_t parse_chunk_size(const tchar *optarg)
1349 {
1350        tchar *tmp;
1351        unsigned long chunk_size = tstrtoul(optarg, &tmp, 10);
1352        if (chunk_size >= UINT32_MAX || *tmp || tmp == optarg) {
1353                imagex_error(T("Chunk size must be a non-negative integer!"));
1354                return UINT32_MAX;
1355        } else {
1356                return chunk_size;
1357        }
1358 }
1359
1360
1361 /*
1362  * Parse an option passed to an update command.
1363  *
1364  * @op:         One of WIMLIB_UPDATE_OP_* that indicates the command being
1365  *              parsed.
1366  *
1367  * @option:     Text string for the option (beginning with --)
1368  *
1369  * @cmd:        `struct wimlib_update_command' that is being constructed for
1370  *              this command.
1371  *
1372  * Returns true if the option was recognized; false if not.
1373  */
1374 static bool
1375 update_command_add_option(int op, const tchar *option,
1376                           struct wimlib_update_command *cmd)
1377 {
1378         bool recognized = true;
1379         switch (op) {
1380         case WIMLIB_UPDATE_OP_ADD:
1381                 if (!tstrcmp(option, T("--verbose")))
1382                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_VERBOSE;
1383                 else if (!tstrcmp(option, T("--unix-data")))
1384                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
1385                 else if (!tstrcmp(option, T("--no-acls")) || !tstrcmp(option, T("--noacls")))
1386                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
1387                 else if (!tstrcmp(option, T("--strict-acls")))
1388                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
1389                 else if (!tstrcmp(option, T("--dereference")))
1390                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
1391                 else
1392                         recognized = false;
1393                 break;
1394         case WIMLIB_UPDATE_OP_DELETE:
1395                 if (!tstrcmp(option, T("--force")))
1396                         cmd->delete_.delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
1397                 else if (!tstrcmp(option, T("--recursive")))
1398                         cmd->delete_.delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
1399                 else
1400                         recognized = false;
1401                 break;
1402         default:
1403                 recognized = false;
1404                 break;
1405         }
1406         return recognized;
1407 }
1408
1409 /* How many nonoption arguments each `imagex update' command expects */
1410 static const unsigned update_command_num_nonoptions[] = {
1411         [WIMLIB_UPDATE_OP_ADD] = 2,
1412         [WIMLIB_UPDATE_OP_DELETE] = 1,
1413         [WIMLIB_UPDATE_OP_RENAME] = 2,
1414 };
1415
1416 static void
1417 update_command_add_nonoption(int op, const tchar *nonoption,
1418                              struct wimlib_update_command *cmd,
1419                              unsigned num_nonoptions)
1420 {
1421         switch (op) {
1422         case WIMLIB_UPDATE_OP_ADD:
1423                 if (num_nonoptions == 0)
1424                         cmd->add.fs_source_path = (tchar*)nonoption;
1425                 else
1426                         cmd->add.wim_target_path = (tchar*)nonoption;
1427                 break;
1428         case WIMLIB_UPDATE_OP_DELETE:
1429                 cmd->delete_.wim_path = (tchar*)nonoption;
1430                 break;
1431         case WIMLIB_UPDATE_OP_RENAME:
1432                 if (num_nonoptions == 0)
1433                         cmd->rename.wim_source_path = (tchar*)nonoption;
1434                 else
1435                         cmd->rename.wim_target_path = (tchar*)nonoption;
1436                 break;
1437         }
1438 }
1439
1440 /*
1441  * Parse a command passed on stdin to `imagex update'.
1442  *
1443  * @line:       Text of the command.
1444  * @len:        Length of the line, including a null terminator
1445  *              at line[len - 1].
1446  *
1447  * @command:    A `struct wimlib_update_command' to fill in from the parsed
1448  *              line.
1449  *
1450  * @line_number: Line number of the command, for diagnostics.
1451  *
1452  * Returns true on success; returns false on parse error.
1453  */
1454 static bool
1455 parse_update_command(tchar *line, size_t len,
1456                      struct wimlib_update_command *command,
1457                      size_t line_number)
1458 {
1459         int ret;
1460         tchar *command_name;
1461         int op;
1462         size_t num_nonoptions;
1463
1464         /* Get the command name ("add", "delete", "rename") */
1465         ret = parse_string(&line, &len, &command_name);
1466         if (ret != PARSE_STRING_SUCCESS)
1467                 return false;
1468
1469         if (!tstrcasecmp(command_name, T("add"))) {
1470                 op = WIMLIB_UPDATE_OP_ADD;
1471         } else if (!tstrcasecmp(command_name, T("delete"))) {
1472                 op = WIMLIB_UPDATE_OP_DELETE;
1473         } else if (!tstrcasecmp(command_name, T("rename"))) {
1474                 op = WIMLIB_UPDATE_OP_RENAME;
1475         } else {
1476                 imagex_error(T("Unknown update command \"%"TS"\" on line %zu"),
1477                              command_name, line_number);
1478                 return false;
1479         }
1480         command->op = op;
1481
1482         /* Parse additional options and non-options as needed */
1483         num_nonoptions = 0;
1484         for (;;) {
1485                 tchar *next_string;
1486
1487                 ret = parse_string(&line, &len, &next_string);
1488                 if (ret == PARSE_STRING_NONE) /* End of line */
1489                         break;
1490                 else if (ret != PARSE_STRING_SUCCESS) /* Parse failure */
1491                         return false;
1492                 if (next_string[0] == T('-') && next_string[1] == T('-')) {
1493                         /* Option */
1494                         if (!update_command_add_option(op, next_string, command))
1495                         {
1496                                 imagex_error(T("Unrecognized option \"%"TS"\" to "
1497                                                "update command \"%"TS"\" on line %zu"),
1498                                              next_string, command_name, line_number);
1499
1500                                 return false;
1501                         }
1502                 } else {
1503                         /* Nonoption */
1504                         if (num_nonoptions == update_command_num_nonoptions[op])
1505                         {
1506                                 imagex_error(T("Unexpected argument \"%"TS"\" in "
1507                                                "update command on line %zu\n"
1508                                                "       (The \"%"TS"\" command only "
1509                                                "takes %zu nonoption arguments!)\n"),
1510                                              next_string, line_number,
1511                                              command_name, num_nonoptions);
1512                                 return false;
1513                         }
1514                         update_command_add_nonoption(op, next_string,
1515                                                      command, num_nonoptions);
1516                         num_nonoptions++;
1517                 }
1518         }
1519
1520         if (num_nonoptions != update_command_num_nonoptions[op]) {
1521                 imagex_error(T("Not enough arguments to update command "
1522                                "\"%"TS"\" on line %zu"), command_name, line_number);
1523                 return false;
1524         }
1525         return true;
1526 }
1527
1528 static struct wimlib_update_command *
1529 parse_update_command_file(tchar **cmd_file_contents_p, size_t cmd_file_nchars,
1530                           size_t *num_cmds_ret)
1531 {
1532         ssize_t nlines;
1533         tchar *p;
1534         struct wimlib_update_command *cmds;
1535         size_t i, j;
1536
1537         nlines = text_file_count_lines(cmd_file_contents_p,
1538                                        &cmd_file_nchars);
1539         if (nlines < 0)
1540                 return NULL;
1541
1542         /* Always allocate at least 1 slot, just in case the implementation of
1543          * calloc() returns NULL if 0 bytes are requested. */
1544         cmds = calloc(nlines ?: 1, sizeof(struct wimlib_update_command));
1545         if (!cmds) {
1546                 imagex_error(T("out of memory"));
1547                 return NULL;
1548         }
1549         p = *cmd_file_contents_p;
1550         j = 0;
1551         for (i = 0; i < nlines; i++) {
1552                 /* XXX: Could use rawmemchr() here instead, but it may not be
1553                  * available on all platforms. */
1554                 tchar *endp = tmemchr(p, T('\n'), cmd_file_nchars);
1555                 size_t len = endp - p + 1;
1556                 *endp = T('\0');
1557                 if (!is_comment_line(p, len)) {
1558                         if (!parse_update_command(p, len, &cmds[j++], i + 1)) {
1559                                 free(cmds);
1560                                 return NULL;
1561                         }
1562                 }
1563                 p = endp + 1;
1564         }
1565         *num_cmds_ret = j;
1566         return cmds;
1567 }
1568
1569 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1570  * one image from a WIM file to a NTFS volume.  */
1571 static int
1572 imagex_apply(int argc, tchar **argv, int cmd)
1573 {
1574         int c;
1575         int open_flags = 0;
1576         int image = WIMLIB_NO_IMAGE;
1577         WIMStruct *wim;
1578         struct wimlib_wim_info info;
1579         int ret;
1580         const tchar *wimfile;
1581         const tchar *target;
1582         const tchar *image_num_or_name = NULL;
1583         int extract_flags = 0;
1584
1585         STRING_SET(refglobs);
1586
1587         for_opt(c, apply_options) {
1588                 switch (c) {
1589                 case IMAGEX_CHECK_OPTION:
1590                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1591                         break;
1592                 case IMAGEX_HARDLINK_OPTION:
1593                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1594                         break;
1595                 case IMAGEX_SYMLINK_OPTION:
1596                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1597                         break;
1598                 case IMAGEX_VERBOSE_OPTION:
1599                         /* No longer does anything.  */
1600                         break;
1601                 case IMAGEX_REF_OPTION:
1602                         ret = string_set_append(&refglobs, optarg);
1603                         if (ret)
1604                                 goto out_free_refglobs;
1605                         break;
1606                 case IMAGEX_UNIX_DATA_OPTION:
1607                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1608                         break;
1609                 case IMAGEX_NO_ACLS_OPTION:
1610                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1611                         break;
1612                 case IMAGEX_STRICT_ACLS_OPTION:
1613                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1614                         break;
1615                 case IMAGEX_NORPFIX_OPTION:
1616                         extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1617                         break;
1618                 case IMAGEX_RPFIX_OPTION:
1619                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1620                         break;
1621                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
1622                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
1623                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
1624                         break;
1625                 case IMAGEX_RESUME_OPTION:
1626                         extract_flags |= WIMLIB_EXTRACT_FLAG_RESUME;
1627                         break;
1628                 default:
1629                         goto out_usage;
1630                 }
1631         }
1632         argc -= optind;
1633         argv += optind;
1634         if (argc != 2 && argc != 3)
1635                 goto out_usage;
1636
1637         wimfile = argv[0];
1638
1639         if (!tstrcmp(wimfile, T("-"))) {
1640                 /* Attempt to apply pipable WIM from standard input.  */
1641                 if (argc == 2) {
1642                         image_num_or_name = NULL;
1643                         target = argv[1];
1644                 } else {
1645                         image_num_or_name = argv[1];
1646                         target = argv[2];
1647                 }
1648                 wim = NULL;
1649         } else {
1650                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1651                                       imagex_progress_func);
1652                 if (ret)
1653                         goto out_free_refglobs;
1654
1655                 wimlib_get_wim_info(wim, &info);
1656
1657                 if (argc >= 3) {
1658                         /* Image explicitly specified.  */
1659                         image_num_or_name = argv[1];
1660                         image = wimlib_resolve_image(wim, image_num_or_name);
1661                         ret = verify_image_exists(image, image_num_or_name, wimfile);
1662                         if (ret)
1663                                 goto out_wimlib_free;
1664                         target = argv[2];
1665                 } else {
1666                         /* No image specified; default to image 1, but only if the WIM
1667                          * contains exactly one image.  */
1668
1669                         if (info.image_count != 1) {
1670                                 imagex_error(T("\"%"TS"\" contains %d images; "
1671                                                "Please select one (or all)."),
1672                                              wimfile, info.image_count);
1673                                 wimlib_free(wim);
1674                                 goto out_usage;
1675                         }
1676                         image = 1;
1677                         target = argv[1];
1678                 }
1679         }
1680
1681         if (refglobs.num_strings) {
1682                 if (wim == NULL) {
1683                         imagex_error(T("Can't specify --ref when applying from stdin!"));
1684                         ret = -1;
1685                         goto out_wimlib_free;
1686                 }
1687                 ret = wim_reference_globs(wim, &refglobs, open_flags);
1688                 if (ret)
1689                         goto out_wimlib_free;
1690         }
1691
1692 #ifndef __WIN32__
1693         {
1694                 /* Interpret a regular file or block device target as a NTFS
1695                  * volume.  */
1696                 struct stat stbuf;
1697
1698                 if (tstat(target, &stbuf)) {
1699                         if (errno != ENOENT) {
1700                                 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1701                                                         target);
1702                                 ret = -1;
1703                                 goto out_wimlib_free;
1704                         }
1705                 } else {
1706                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1707                                 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1708                 }
1709         }
1710 #endif
1711
1712         if (wim) {
1713                 ret = wimlib_extract_image(wim, image, target, extract_flags,
1714                                            imagex_progress_func);
1715         } else {
1716                 set_fd_to_binary_mode(STDIN_FILENO);
1717                 ret = wimlib_extract_image_from_pipe(STDIN_FILENO,
1718                                                      image_num_or_name,
1719                                                      target, extract_flags,
1720                                                      imagex_progress_func);
1721         }
1722         if (ret == 0) {
1723                 imagex_printf(T("Done applying WIM image.\n"));
1724         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
1725                 if (wim) {
1726                         do_resource_not_found_warning(wimfile, &info, &refglobs);
1727                 } else {
1728                         imagex_error(T(        "If you are applying an image "
1729                                                "from a split pipable WIM,\n"
1730                                        "       make sure you have "
1731                                        "concatenated together all parts."));
1732                 }
1733         }
1734 out_wimlib_free:
1735         wimlib_free(wim);
1736 out_free_refglobs:
1737         string_set_destroy(&refglobs);
1738         return ret;
1739
1740 out_usage:
1741         usage(CMD_APPLY, stderr);
1742         ret = -1;
1743         goto out_free_refglobs;
1744 }
1745
1746 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1747  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1748  * the desired image.  'wimlib-imagex append': add a new image to an existing
1749  * WIM file. */
1750 static int
1751 imagex_capture_or_append(int argc, tchar **argv, int cmd)
1752 {
1753         int c;
1754         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1755         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE |
1756                               WIMLIB_ADD_IMAGE_FLAG_WINCONFIG |
1757                               WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1758         int write_flags = 0;
1759         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
1760         uint32_t chunk_size = UINT32_MAX;
1761         uint32_t pack_chunk_size = UINT32_MAX;
1762         const tchar *wimfile;
1763         int wim_fd;
1764         const tchar *name;
1765         const tchar *desc;
1766         const tchar *flags_element = NULL;
1767
1768         WIMStruct *wim;
1769         STRING_SET(base_wimfiles);
1770         WIMStruct **base_wims;
1771
1772         WIMStruct *template_wim;
1773         const tchar *template_wimfile = NULL;
1774         const tchar *template_image_name_or_num = NULL;
1775         int template_image = WIMLIB_NO_IMAGE;
1776
1777         int ret;
1778         unsigned num_threads = 0;
1779
1780         tchar *source;
1781         tchar *source_copy;
1782
1783         const tchar *config_file = NULL;
1784         tchar *config_str;
1785         struct wimlib_capture_config *config;
1786
1787         bool source_list = false;
1788         size_t source_list_nchars = 0;
1789         tchar *source_list_contents;
1790         bool capture_sources_malloced;
1791         struct wimlib_capture_source *capture_sources;
1792         size_t num_sources;
1793         bool name_defaulted;
1794         bool compress_slow = false;
1795
1796         for_opt(c, capture_or_append_options) {
1797                 switch (c) {
1798                 case IMAGEX_BOOT_OPTION:
1799                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1800                         break;
1801                 case IMAGEX_CHECK_OPTION:
1802                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1803                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1804                         break;
1805                 case IMAGEX_NOCHECK_OPTION:
1806                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
1807                         break;
1808                 case IMAGEX_CONFIG_OPTION:
1809                         config_file = optarg;
1810                         add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1811                         break;
1812                 case IMAGEX_COMPRESS_OPTION:
1813                         compression_type = get_compression_type(optarg);
1814                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1815                                 goto out_err;
1816                         break;
1817                 case IMAGEX_COMPRESS_SLOW_OPTION:
1818                         compress_slow = true;
1819                         break;
1820                 case IMAGEX_CHUNK_SIZE_OPTION:
1821                         chunk_size = parse_chunk_size(optarg);
1822                         if (chunk_size == UINT32_MAX)
1823                                 goto out_err;
1824                         break;
1825                 case IMAGEX_PACK_CHUNK_SIZE_OPTION:
1826                         pack_chunk_size = parse_chunk_size(optarg);
1827                         if (pack_chunk_size == UINT32_MAX)
1828                                 goto out_err;
1829                         break;
1830                 case IMAGEX_PACK_STREAMS_OPTION:
1831                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
1832                         break;
1833                 case IMAGEX_FLAGS_OPTION:
1834                         flags_element = optarg;
1835                         break;
1836                 case IMAGEX_DEREFERENCE_OPTION:
1837                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1838                         break;
1839                 case IMAGEX_VERBOSE_OPTION:
1840                         /* No longer does anything.  */
1841                         break;
1842                 case IMAGEX_THREADS_OPTION:
1843                         num_threads = parse_num_threads(optarg);
1844                         if (num_threads == UINT_MAX)
1845                                 goto out_err;
1846                         break;
1847                 case IMAGEX_REBUILD_OPTION:
1848                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1849                         break;
1850                 case IMAGEX_UNIX_DATA_OPTION:
1851                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1852                         break;
1853                 case IMAGEX_SOURCE_LIST_OPTION:
1854                         source_list = true;
1855                         break;
1856                 case IMAGEX_NO_ACLS_OPTION:
1857                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1858                         break;
1859                 case IMAGEX_STRICT_ACLS_OPTION:
1860                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1861                         break;
1862                 case IMAGEX_RPFIX_OPTION:
1863                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1864                         break;
1865                 case IMAGEX_NORPFIX_OPTION:
1866                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1867                         break;
1868                 case IMAGEX_PIPABLE_OPTION:
1869                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1870                         break;
1871                 case IMAGEX_NOT_PIPABLE_OPTION:
1872                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
1873                         break;
1874                 case IMAGEX_UPDATE_OF_OPTION:
1875                         if (template_image_name_or_num) {
1876                                 imagex_error(T("'--update-of' can only be "
1877                                                "specified one time!"));
1878                                 goto out_err;
1879                         } else {
1880                                 tchar *colon;
1881                                 colon = tstrrchr(optarg, T(':'));
1882
1883                                 if (colon) {
1884                                         template_wimfile = optarg;
1885                                         *colon = T('\0');
1886                                         template_image_name_or_num = colon + 1;
1887                                 } else {
1888                                         template_wimfile = NULL;
1889                                         template_image_name_or_num = optarg;
1890                                 }
1891                         }
1892                         break;
1893                 case IMAGEX_DELTA_FROM_OPTION:
1894                         if (cmd != CMD_CAPTURE) {
1895                                 imagex_error(T("'--delta-from' is only "
1896                                                "valid for capture!"));
1897                                 goto out_usage;
1898                         }
1899                         ret = string_set_append(&base_wimfiles, optarg);
1900                         if (ret)
1901                                 goto out_free_base_wimfiles;
1902                         write_flags |= WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
1903                         break;
1904                 default:
1905                         goto out_usage;
1906                 }
1907         }
1908         argc -= optind;
1909         argv += optind;
1910
1911         if (argc < 2 || argc > 4)
1912                 goto out_usage;
1913
1914         source = argv[0];
1915         wimfile = argv[1];
1916
1917         /* Set default compression type and parameters.  */
1918
1919
1920         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
1921                 compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
1922
1923                 if (!compress_slow) {
1924                         struct wimlib_lzx_compressor_params params = {
1925                                 .hdr.size = sizeof(params),
1926                                 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
1927                                 .use_defaults = 1,
1928                         };
1929                         wimlib_set_default_compressor_params(WIMLIB_COMPRESSION_TYPE_LZX,
1930                                                              &params.hdr);
1931                 }
1932         }
1933
1934         if (compress_slow)
1935                 set_compress_slow();
1936
1937         if (!tstrcmp(wimfile, T("-"))) {
1938                 /* Writing captured WIM to standard output.  */
1939         #if 0
1940                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
1941                         imagex_error("Can't write a non-pipable WIM to "
1942                                      "standard output!  Specify --pipable\n"
1943                                      "       if you want to create a pipable WIM "
1944                                      "(but read the docs first).");
1945                         goto out_err;
1946                 }
1947         #else
1948                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1949         #endif
1950                 if (cmd == CMD_APPEND) {
1951                         imagex_error(T("Using standard output for append does "
1952                                        "not make sense."));
1953                         goto out_err;
1954                 }
1955                 wim_fd = STDOUT_FILENO;
1956                 wimfile = NULL;
1957                 imagex_info_file = stderr;
1958                 set_fd_to_binary_mode(wim_fd);
1959         }
1960
1961         /* If template image was specified using --update-of=IMAGE rather
1962          * than --update-of=WIMFILE:IMAGE, set the default WIMFILE.  */
1963         if (template_image_name_or_num && !template_wimfile) {
1964                 if (base_wimfiles.num_strings == 1) {
1965                         /* Capturing delta WIM based on single WIM:  default to
1966                          * base WIM.  */
1967                         template_wimfile = base_wimfiles.strings[0];
1968                 } else if (cmd == CMD_APPEND) {
1969                         /* Appending to WIM:  default to WIM being appended to.
1970                          */
1971                         template_wimfile = wimfile;
1972                 } else {
1973                         /* Capturing a normal (non-delta) WIM, so the WIM file
1974                          * *must* be explicitly specified.  */
1975                         if (base_wimfiles.num_strings > 1) {
1976                                 imagex_error(T("For capture of delta WIM "
1977                                                "based on multiple existing "
1978                                                "WIMs,\n"
1979                                                "      '--update-of' must "
1980                                                "specify WIMFILE:IMAGE!"));
1981                         } else {
1982                                 imagex_error(T("For capture of non-delta WIM, "
1983                                                "'--update-of' must specify "
1984                                                "WIMFILE:IMAGE!"));
1985                         }
1986                         goto out_usage;
1987                 }
1988         }
1989
1990         if (argc >= 3) {
1991                 name = argv[2];
1992                 name_defaulted = false;
1993         } else {
1994                 /* Set default name to SOURCE argument, omitting any directory
1995                  * prefixes and trailing slashes.  This requires making a copy
1996                  * of @source.  Leave some free characters at the end in case we
1997                  * append a number to keep the name unique. */
1998                 size_t source_name_len;
1999
2000                 source_name_len = tstrlen(source);
2001                 source_copy = alloca((source_name_len + 1 + 25) * sizeof(tchar));
2002                 name = tbasename(tstrcpy(source_copy, source));
2003                 name_defaulted = true;
2004         }
2005         /* Image description defaults to NULL if not given. */
2006         if (argc >= 4)
2007                 desc = argv[3];
2008         else
2009                 desc = NULL;
2010
2011         if (source_list) {
2012                 /* Set up capture sources in source list mode */
2013                 if (source[0] == T('-') && source[1] == T('\0')) {
2014                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
2015                 } else {
2016                         source_list_contents = file_get_text_contents(source,
2017                                                                       &source_list_nchars);
2018                 }
2019                 if (!source_list_contents)
2020                         goto out_err;
2021
2022                 capture_sources = parse_source_list(&source_list_contents,
2023                                                     source_list_nchars,
2024                                                     &num_sources);
2025                 if (!capture_sources) {
2026                         ret = -1;
2027                         goto out_free_source_list_contents;
2028                 }
2029                 capture_sources_malloced = true;
2030         } else {
2031                 /* Set up capture source in non-source-list mode.  */
2032                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
2033                 capture_sources[0].fs_source_path = source;
2034                 capture_sources[0].wim_target_path = NULL;
2035                 capture_sources[0].reserved = 0;
2036                 num_sources = 1;
2037                 capture_sources_malloced = false;
2038                 source_list_contents = NULL;
2039         }
2040
2041         if (config_file) {
2042                 /* Read and parse capture configuration file.  */
2043                 size_t config_len;
2044
2045                 config_str = file_get_text_contents(config_file, &config_len);
2046                 if (!config_str) {
2047                         ret = -1;
2048                         goto out_free_capture_sources;
2049                 }
2050
2051                 config = alloca(sizeof(*config));
2052                 ret = parse_capture_config(&config_str, config_len, config);
2053                 if (ret)
2054                         goto out_free_config;
2055         } else {
2056                 /* No capture configuration file specified; use default
2057                  * configuration for capturing Windows operating systems.  */
2058                 config = NULL;
2059                 add_image_flags |= WIMLIB_ADD_FLAG_WINCONFIG;
2060         }
2061
2062         /* Open the existing WIM, or create a new one.  */
2063         if (cmd == CMD_APPEND)
2064                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
2065                                       imagex_progress_func);
2066         else
2067                 ret = wimlib_create_new_wim(compression_type, &wim);
2068         if (ret)
2069                 goto out_free_config;
2070
2071         /* Set chunk size if non-default.  */
2072         if (chunk_size != UINT32_MAX) {
2073                 ret = wimlib_set_output_chunk_size(wim, chunk_size);
2074                 if (ret)
2075                         goto out_free_wim;
2076         }
2077         if (pack_chunk_size != UINT32_MAX) {
2078                 ret = wimlib_set_output_pack_chunk_size(wim, pack_chunk_size);
2079                 if (ret)
2080                         goto out_free_wim;
2081         }
2082
2083 #ifndef __WIN32__
2084         /* Detect if source is regular file or block device and set NTFS volume
2085          * capture mode.  */
2086         if (!source_list) {
2087                 struct stat stbuf;
2088
2089                 if (tstat(source, &stbuf) == 0) {
2090                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
2091                                 imagex_printf(T("Capturing WIM image from NTFS "
2092                                           "filesystem on \"%"TS"\"\n"), source);
2093                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
2094                         }
2095                 } else {
2096                         if (errno != ENOENT) {
2097                                 imagex_error_with_errno(T("Failed to stat "
2098                                                           "\"%"TS"\""), source);
2099                                 ret = -1;
2100                                 goto out_free_wim;
2101                         }
2102                 }
2103         }
2104 #endif
2105
2106         /* If the user did not specify an image name, and the basename of the
2107          * source already exists as an image name in the WIM file, append a
2108          * suffix to make it unique. */
2109         if (cmd == CMD_APPEND && name_defaulted) {
2110                 unsigned long conflict_idx;
2111                 tchar *name_end = tstrchr(name, T('\0'));
2112                 for (conflict_idx = 1;
2113                      wimlib_image_name_in_use(wim, name);
2114                      conflict_idx++)
2115                 {
2116                         tsprintf(name_end, T(" (%lu)"), conflict_idx);
2117                 }
2118         }
2119
2120         /* If capturing a delta WIM, reference resources from the base WIMs
2121          * before adding the new image.  */
2122         if (base_wimfiles.num_strings) {
2123                 base_wims = calloc(base_wimfiles.num_strings,
2124                                    sizeof(base_wims[0]));
2125                 if (base_wims == NULL) {
2126                         imagex_error(T("Out of memory!"));
2127                         ret = -1;
2128                         goto out_free_wim;
2129                 }
2130
2131                 for (size_t i = 0; i < base_wimfiles.num_strings; i++) {
2132                         ret = wimlib_open_wim(base_wimfiles.strings[i],
2133                                               open_flags, &base_wims[i],
2134                                               imagex_progress_func);
2135                         if (ret)
2136                                 goto out_free_base_wims;
2137
2138                 }
2139
2140                 ret = wimlib_reference_resources(wim, base_wims,
2141                                                  base_wimfiles.num_strings, 0);
2142                 if (ret)
2143                         goto out_free_base_wims;
2144
2145                 if (base_wimfiles.num_strings == 1) {
2146                         imagex_printf(T("Capturing delta WIM based on \"%"TS"\"\n"),
2147                                       base_wimfiles.strings[0]);
2148                 } else {
2149                         imagex_printf(T("Capturing delta WIM based on %u WIMs\n"),
2150                                       base_wimfiles.num_strings);
2151                 }
2152
2153         } else {
2154                 base_wims = NULL;
2155         }
2156
2157         /* If capturing or appending as an update of an existing (template) image,
2158          * open the WIM if needed and parse the image index.  */
2159         if (template_image_name_or_num) {
2160
2161
2162                 if (base_wimfiles.num_strings == 1 &&
2163                     template_wimfile == base_wimfiles.strings[0]) {
2164                         template_wim = base_wims[0];
2165                 } else if (template_wimfile == wimfile) {
2166                         template_wim = wim;
2167                 } else {
2168                         ret = wimlib_open_wim(template_wimfile, open_flags,
2169                                               &template_wim, imagex_progress_func);
2170                         if (ret)
2171                                 goto out_free_base_wims;
2172                 }
2173
2174                 template_image = wimlib_resolve_image(template_wim,
2175                                                       template_image_name_or_num);
2176
2177                 if (template_image_name_or_num[0] == T('-')) {
2178                         tchar *tmp;
2179                         unsigned long n;
2180                         struct wimlib_wim_info info;
2181
2182                         wimlib_get_wim_info(template_wim, &info);
2183                         n = tstrtoul(template_image_name_or_num + 1, &tmp, 10);
2184                         if (n >= 1 && n <= info.image_count &&
2185                             *tmp == T('\0') &&
2186                             tmp != template_image_name_or_num + 1)
2187                         {
2188                                 template_image = info.image_count - (n - 1);
2189                         }
2190                 }
2191                 ret = verify_image_exists_and_is_single(template_image,
2192                                                         template_image_name_or_num,
2193                                                         template_wimfile);
2194                 if (ret)
2195                         goto out_free_template_wim;
2196         } else {
2197                 template_wim = NULL;
2198         }
2199
2200         ret = wimlib_add_image_multisource(wim,
2201                                            capture_sources,
2202                                            num_sources,
2203                                            name,
2204                                            config,
2205                                            add_image_flags,
2206                                            imagex_progress_func);
2207         if (ret)
2208                 goto out_free_template_wim;
2209
2210         if (desc || flags_element || template_image_name_or_num) {
2211                 /* User provided <DESCRIPTION> or <FLAGS> element, or an image
2212                  * on which the added one is to be based has been specified with
2213                  * --update-of.  Get the index of the image we just
2214                  *  added, then use it to call the appropriate functions.  */
2215                 struct wimlib_wim_info info;
2216
2217                 wimlib_get_wim_info(wim, &info);
2218
2219                 if (desc) {
2220                         ret = wimlib_set_image_descripton(wim,
2221                                                           info.image_count,
2222                                                           desc);
2223                         if (ret)
2224                                 goto out_free_template_wim;
2225                 }
2226
2227                 if (flags_element) {
2228                         ret = wimlib_set_image_flags(wim, info.image_count,
2229                                                      flags_element);
2230                         if (ret)
2231                                 goto out_free_template_wim;
2232                 }
2233
2234                 /* Reference template image if the user provided one.  */
2235                 if (template_image_name_or_num) {
2236                         imagex_printf(T("Using image %d "
2237                                         "from \"%"TS"\" as template\n"),
2238                                         template_image, template_wimfile);
2239                         ret = wimlib_reference_template_image(wim,
2240                                                               info.image_count,
2241                                                               template_wim,
2242                                                               template_image,
2243                                                               0, NULL);
2244                         if (ret)
2245                                 goto out_free_template_wim;
2246                 }
2247         }
2248
2249         /* Write the new WIM or overwrite the existing WIM with the new image
2250          * appended.  */
2251         if (cmd == CMD_APPEND) {
2252                 ret = wimlib_overwrite(wim, write_flags, num_threads,
2253                                        imagex_progress_func);
2254         } else if (wimfile) {
2255                 ret = wimlib_write(wim, wimfile, WIMLIB_ALL_IMAGES,
2256                                    write_flags, num_threads,
2257                                    imagex_progress_func);
2258         } else {
2259                 ret = wimlib_write_to_fd(wim, wim_fd, WIMLIB_ALL_IMAGES,
2260                                          write_flags, num_threads,
2261                                          imagex_progress_func);
2262         }
2263 out_free_template_wim:
2264         /* template_wim may alias base_wims[0] or wim.  */
2265         if ((base_wimfiles.num_strings != 1 || template_wim != base_wims[0]) &&
2266             template_wim != wim)
2267                 wimlib_free(template_wim);
2268 out_free_base_wims:
2269         for (size_t i = 0; i < base_wimfiles.num_strings; i++)
2270                 wimlib_free(base_wims[i]);
2271         free(base_wims);
2272 out_free_wim:
2273         wimlib_free(wim);
2274 out_free_config:
2275         if (config) {
2276                 free(config->exclusion_pats.pats);
2277                 free(config->exclusion_exception_pats.pats);
2278                 free(config_str);
2279         }
2280 out_free_capture_sources:
2281         if (capture_sources_malloced)
2282                 free(capture_sources);
2283 out_free_source_list_contents:
2284         free(source_list_contents);
2285 out_free_base_wimfiles:
2286         string_set_destroy(&base_wimfiles);
2287         return ret;
2288
2289 out_usage:
2290         usage(cmd, stderr);
2291 out_err:
2292         ret = -1;
2293         goto out_free_base_wimfiles;
2294 }
2295
2296 /* Remove image(s) from a WIM. */
2297 static int
2298 imagex_delete(int argc, tchar **argv, int cmd)
2299 {
2300         int c;
2301         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
2302         int write_flags = 0;
2303         const tchar *wimfile;
2304         const tchar *image_num_or_name;
2305         WIMStruct *wim;
2306         int image;
2307         int ret;
2308
2309         for_opt(c, delete_options) {
2310                 switch (c) {
2311                 case IMAGEX_CHECK_OPTION:
2312                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2313                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2314                         break;
2315                 case IMAGEX_SOFT_OPTION:
2316                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
2317                         break;
2318                 default:
2319                         goto out_usage;
2320                 }
2321         }
2322         argc -= optind;
2323         argv += optind;
2324
2325         if (argc != 2) {
2326                 if (argc < 1)
2327                         imagex_error(T("Must specify a WIM file"));
2328                 if (argc < 2)
2329                         imagex_error(T("Must specify an image"));
2330                 goto out_usage;
2331         }
2332         wimfile = argv[0];
2333         image_num_or_name = argv[1];
2334
2335         ret = wimlib_open_wim(wimfile, open_flags, &wim,
2336                               imagex_progress_func);
2337         if (ret)
2338                 goto out;
2339
2340         image = wimlib_resolve_image(wim, image_num_or_name);
2341
2342         ret = verify_image_exists(image, image_num_or_name, wimfile);
2343         if (ret)
2344                 goto out_wimlib_free;
2345
2346         ret = wimlib_delete_image(wim, image);
2347         if (ret) {
2348                 imagex_error(T("Failed to delete image from \"%"TS"\""),
2349                              wimfile);
2350                 goto out_wimlib_free;
2351         }
2352
2353         ret = wimlib_overwrite(wim, write_flags, 0, imagex_progress_func);
2354         if (ret) {
2355                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
2356                                "deleted"), wimfile);
2357         }
2358 out_wimlib_free:
2359         wimlib_free(wim);
2360 out:
2361         return ret;
2362
2363 out_usage:
2364         usage(CMD_DELETE, stderr);
2365         ret = -1;
2366         goto out;
2367 }
2368
2369 static int
2370 print_full_path(const struct wimlib_dir_entry *wdentry, void *_ignore)
2371 {
2372         int ret = tprintf(T("%"TS"\n"), wdentry->full_path);
2373         return (ret >= 0) ? 0 : -1;
2374 }
2375
2376 /* Print the files contained in an image(s) in a WIM file. */
2377 static int
2378 imagex_dir(int argc, tchar **argv, int cmd)
2379 {
2380         const tchar *wimfile;
2381         WIMStruct *wim = NULL;
2382         int image;
2383         int ret;
2384         const tchar *path = T("");
2385         int c;
2386
2387         for_opt(c, dir_options) {
2388                 switch (c) {
2389                 case IMAGEX_PATH_OPTION:
2390                         path = optarg;
2391                         break;
2392                 default:
2393                         goto out_usage;
2394                 }
2395         }
2396         argc -= optind;
2397         argv += optind;
2398
2399         if (argc < 1) {
2400                 imagex_error(T("Must specify a WIM file"));
2401                 goto out_usage;
2402         }
2403         if (argc > 2) {
2404                 imagex_error(T("Too many arguments"));
2405                 goto out_usage;
2406         }
2407
2408         wimfile = argv[0];
2409         ret = wimlib_open_wim(wimfile, 0, &wim, imagex_progress_func);
2410         if (ret)
2411                 goto out;
2412
2413         if (argc >= 2) {
2414                 image = wimlib_resolve_image(wim, argv[1]);
2415                 ret = verify_image_exists(image, argv[1], wimfile);
2416                 if (ret)
2417                         goto out_wimlib_free;
2418         } else {
2419                 /* No image specified; default to image 1, but only if the WIM
2420                  * contains exactly one image.  */
2421
2422                 struct wimlib_wim_info info;
2423
2424                 wimlib_get_wim_info(wim, &info);
2425                 if (info.image_count != 1) {
2426                         imagex_error(T("\"%"TS"\" contains %d images; Please "
2427                                        "select one (or all)."),
2428                                      wimfile, info.image_count);
2429                         wimlib_free(wim);
2430                         goto out_usage;
2431                 }
2432                 image = 1;
2433         }
2434
2435         ret = wimlib_iterate_dir_tree(wim, image, path,
2436                                       WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE,
2437                                       print_full_path, NULL);
2438 out_wimlib_free:
2439         wimlib_free(wim);
2440 out:
2441         return ret;
2442
2443 out_usage:
2444         usage(CMD_DIR, stderr);
2445         ret = -1;
2446         goto out;
2447 }
2448
2449 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
2450  * WIM file. */
2451 static int
2452 imagex_export(int argc, tchar **argv, int cmd)
2453 {
2454         int c;
2455         int open_flags = 0;
2456         int export_flags = 0;
2457         int write_flags = 0;
2458         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
2459         const tchar *src_wimfile;
2460         const tchar *src_image_num_or_name;
2461         const tchar *dest_wimfile;
2462         int dest_wim_fd;
2463         const tchar *dest_name;
2464         const tchar *dest_desc;
2465         WIMStruct *src_wim;
2466         struct wimlib_wim_info src_info;
2467         WIMStruct *dest_wim;
2468         int ret;
2469         int image;
2470         struct stat stbuf;
2471         bool wim_is_new;
2472         STRING_SET(refglobs);
2473         unsigned num_threads = 0;
2474         uint32_t chunk_size = UINT32_MAX;
2475         uint32_t pack_chunk_size = UINT32_MAX;
2476
2477         for_opt(c, export_options) {
2478                 switch (c) {
2479                 case IMAGEX_BOOT_OPTION:
2480                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
2481                         break;
2482                 case IMAGEX_CHECK_OPTION:
2483                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2484                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2485                         break;
2486                 case IMAGEX_NOCHECK_OPTION:
2487                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2488                         break;
2489                 case IMAGEX_COMPRESS_OPTION:
2490                         compression_type = get_compression_type(optarg);
2491                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
2492                                 goto out_err;
2493                         break;
2494                 case IMAGEX_PACK_STREAMS_OPTION:
2495                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2496                         break;
2497                 case IMAGEX_CHUNK_SIZE_OPTION:
2498                         chunk_size = parse_chunk_size(optarg);
2499                         if (chunk_size == UINT32_MAX)
2500                                 goto out_err;
2501                         break;
2502                 case IMAGEX_PACK_CHUNK_SIZE_OPTION:
2503                         pack_chunk_size = parse_chunk_size(optarg);
2504                         if (pack_chunk_size == UINT32_MAX)
2505                                 goto out_err;
2506                         break;
2507                 case IMAGEX_REF_OPTION:
2508                         ret = string_set_append(&refglobs, optarg);
2509                         if (ret)
2510                                 goto out_free_refglobs;
2511                         break;
2512                 case IMAGEX_THREADS_OPTION:
2513                         num_threads = parse_num_threads(optarg);
2514                         if (num_threads == UINT_MAX)
2515                                 goto out_err;
2516                         break;
2517                 case IMAGEX_REBUILD_OPTION:
2518                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
2519                         break;
2520                 case IMAGEX_PIPABLE_OPTION:
2521                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2522                         break;
2523                 case IMAGEX_NOT_PIPABLE_OPTION:
2524                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
2525                         break;
2526                 default:
2527                         goto out_usage;
2528                 }
2529         }
2530         argc -= optind;
2531         argv += optind;
2532         if (argc < 3 || argc > 5)
2533                 goto out_usage;
2534         src_wimfile           = argv[0];
2535         src_image_num_or_name = argv[1];
2536         dest_wimfile          = argv[2];
2537         dest_name             = (argc >= 4) ? argv[3] : NULL;
2538         dest_desc             = (argc >= 5) ? argv[4] : NULL;
2539         ret = wimlib_open_wim(src_wimfile, open_flags, &src_wim,
2540                               imagex_progress_func);
2541         if (ret)
2542                 goto out_free_refglobs;
2543
2544         wimlib_get_wim_info(src_wim, &src_info);
2545
2546         /* Determine if the destination is an existing file or not.  If so, we
2547          * try to append the exported image(s) to it; otherwise, we create a new
2548          * WIM containing the exported image(s).  Furthermore, determine if we
2549          * need to write a pipable WIM directly to standard output.  */
2550
2551         if (tstrcmp(dest_wimfile, T("-")) == 0) {
2552         #if 0
2553                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2554                         imagex_error("Can't write a non-pipable WIM to "
2555                                      "standard output!  Specify --pipable\n"
2556                                      "       if you want to create a pipable WIM "
2557                                      "(but read the docs first).");
2558                         ret = -1;
2559                         goto out_free_src_wim;
2560                 }
2561         #else
2562                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2563         #endif
2564                 dest_wimfile = NULL;
2565                 dest_wim_fd = STDOUT_FILENO;
2566                 imagex_info_file = stderr;
2567                 set_fd_to_binary_mode(dest_wim_fd);
2568         }
2569         errno = ENOENT;
2570         if (dest_wimfile != NULL && tstat(dest_wimfile, &stbuf) == 0) {
2571                 wim_is_new = false;
2572                 /* Destination file exists. */
2573
2574                 if (!S_ISREG(stbuf.st_mode)) {
2575                         imagex_error(T("\"%"TS"\" is not a regular file"),
2576                                      dest_wimfile);
2577                         ret = -1;
2578                         goto out_free_src_wim;
2579                 }
2580                 ret = wimlib_open_wim(dest_wimfile,
2581                                       open_flags | WIMLIB_OPEN_FLAG_WRITE_ACCESS,
2582                                       &dest_wim, imagex_progress_func);
2583                 if (ret)
2584                         goto out_free_src_wim;
2585
2586                 if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
2587                         /* The user specified a compression type, but we're
2588                          * exporting to an existing WIM.  Make sure the
2589                          * specified compression type is the same as the
2590                          * compression type of the existing destination WIM. */
2591                         struct wimlib_wim_info dest_info;
2592
2593                         wimlib_get_wim_info(dest_wim, &dest_info);
2594                         if (compression_type != dest_info.compression_type) {
2595                                 imagex_error(T("Cannot specify a compression type that is "
2596                                                "not the same as that used in the "
2597                                                "destination WIM"));
2598                                 ret = -1;
2599                                 goto out_free_dest_wim;
2600                         }
2601                 }
2602         } else {
2603                 wim_is_new = true;
2604
2605                 if (errno != ENOENT) {
2606                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
2607                                                 dest_wimfile);
2608                         ret = -1;
2609                         goto out_free_src_wim;
2610                 }
2611
2612                 /* dest_wimfile is not an existing file, so create a new WIM. */
2613
2614                 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
2615                         /* The user did not specify a compression type; default
2616                          * to that of the source WIM.  */
2617
2618                         compression_type = src_info.compression_type;
2619                 }
2620                 ret = wimlib_create_new_wim(compression_type, &dest_wim);
2621                 if (ret)
2622                         goto out_free_src_wim;
2623
2624                 /* Use same chunk size if compression type is the same.  */
2625                 if (compression_type == src_info.compression_type &&
2626                     chunk_size == UINT32_MAX)
2627                         wimlib_set_output_chunk_size(dest_wim, src_info.chunk_size);
2628         }
2629
2630         if (chunk_size != UINT32_MAX) {
2631                 /* Set destination chunk size.  */
2632                 ret = wimlib_set_output_chunk_size(dest_wim, chunk_size);
2633                 if (ret)
2634                         goto out_free_dest_wim;
2635         }
2636         if (pack_chunk_size != UINT32_MAX) {
2637                 ret = wimlib_set_output_pack_chunk_size(dest_wim, pack_chunk_size);
2638                 if (ret)
2639                         goto out_free_dest_wim;
2640         }
2641
2642         image = wimlib_resolve_image(src_wim, src_image_num_or_name);
2643         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2644         if (ret)
2645                 goto out_free_dest_wim;
2646
2647         if (refglobs.num_strings) {
2648                 ret = wim_reference_globs(src_wim, &refglobs, open_flags);
2649                 if (ret)
2650                         goto out_free_dest_wim;
2651         }
2652
2653         if ((export_flags & WIMLIB_EXPORT_FLAG_BOOT) &&
2654             image == WIMLIB_ALL_IMAGES && src_info.boot_index == 0)
2655         {
2656                 imagex_error(T("--boot specified for all-images export, but source WIM "
2657                                "has no bootable image."));
2658                 ret = -1;
2659                 goto out_free_dest_wim;
2660         }
2661
2662         ret = wimlib_export_image(src_wim, image, dest_wim, dest_name,
2663                                   dest_desc, export_flags, imagex_progress_func);
2664         if (ret) {
2665                 if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2666                         do_resource_not_found_warning(src_wimfile,
2667                                                       &src_info, &refglobs);
2668                 }
2669                 goto out_free_dest_wim;
2670         }
2671
2672         if (!wim_is_new)
2673                 ret = wimlib_overwrite(dest_wim, write_flags, num_threads,
2674                                        imagex_progress_func);
2675         else if (dest_wimfile)
2676                 ret = wimlib_write(dest_wim, dest_wimfile, WIMLIB_ALL_IMAGES,
2677                                    write_flags, num_threads,
2678                                    imagex_progress_func);
2679         else
2680                 ret = wimlib_write_to_fd(dest_wim, dest_wim_fd,
2681                                          WIMLIB_ALL_IMAGES, write_flags,
2682                                          num_threads, imagex_progress_func);
2683 out_free_dest_wim:
2684         wimlib_free(dest_wim);
2685 out_free_src_wim:
2686         wimlib_free(src_wim);
2687 out_free_refglobs:
2688         string_set_destroy(&refglobs);
2689         return ret;
2690
2691 out_usage:
2692         usage(CMD_EXPORT, stderr);
2693 out_err:
2694         ret = -1;
2695         goto out_free_refglobs;
2696 }
2697
2698 static bool
2699 is_root_wim_path(const tchar *path)
2700 {
2701         const tchar *p;
2702         for (p = path; *p; p++)
2703                 if (*p != T('\\') && *p != T('/'))
2704                         return false;
2705         return true;
2706 }
2707
2708 static void
2709 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2710                       const tchar *dest_dir)
2711 {
2712         for (size_t i = 0; i < num_cmds; i++)
2713                 if (cmds[i].fs_dest_path != dest_dir)
2714                         free(cmds[i].fs_dest_path);
2715         free(cmds);
2716 }
2717
2718 static struct wimlib_extract_command *
2719 prepare_extract_commands(tchar **paths, unsigned num_paths,
2720                          int extract_flags, tchar *dest_dir,
2721                          size_t *num_cmds_ret)
2722 {
2723         struct wimlib_extract_command *cmds;
2724         size_t num_cmds;
2725         tchar *emptystr = T("");
2726
2727         if (num_paths == 0) {
2728                 num_paths = 1;
2729                 paths = &emptystr;
2730         }
2731         num_cmds = num_paths;
2732         cmds = calloc(num_cmds, sizeof(cmds[0]));
2733         if (!cmds) {
2734                 imagex_error(T("Out of memory!"));
2735                 return NULL;
2736         }
2737
2738         for (size_t i = 0; i < num_cmds; i++) {
2739                 cmds[i].extract_flags = extract_flags;
2740                 cmds[i].wim_source_path = paths[i];
2741                 if (is_root_wim_path(paths[i])) {
2742                         cmds[i].fs_dest_path = dest_dir;
2743                 } else {
2744                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2745                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2746                         if (!cmds[i].fs_dest_path) {
2747                                 free_extract_commands(cmds, num_cmds, dest_dir);
2748                                 return NULL;
2749                         }
2750                         tsprintf(cmds[i].fs_dest_path,
2751                                  T("%"TS""OS_PREFERRED_PATH_SEPARATOR_STRING"%"TS),
2752                                  dest_dir, tbasename(paths[i]));
2753                 }
2754         }
2755         *num_cmds_ret = num_cmds;
2756         return cmds;
2757 }
2758
2759 /* Extract files or directories from a WIM image */
2760 static int
2761 imagex_extract(int argc, tchar **argv, int cmd)
2762 {
2763         int c;
2764         int open_flags = 0;
2765         int image;
2766         WIMStruct *wim;
2767         int ret;
2768         const tchar *wimfile;
2769         const tchar *image_num_or_name;
2770         const tchar *pathlist;
2771         tchar *dest_dir = T(".");
2772         int extract_flags = WIMLIB_EXTRACT_FLAG_NORPFIX;
2773         int listfile_extract_flags = WIMLIB_EXTRACT_FLAG_GLOB_PATHS;
2774
2775         STRING_SET(refglobs);
2776
2777         struct wimlib_extract_command *cmds;
2778         size_t num_cmds;
2779
2780         for_opt(c, extract_options) {
2781                 switch (c) {
2782                 case IMAGEX_CHECK_OPTION:
2783                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2784                         break;
2785                 case IMAGEX_VERBOSE_OPTION:
2786                         /* No longer does anything.  */
2787                         break;
2788                 case IMAGEX_REF_OPTION:
2789                         ret = string_set_append(&refglobs, optarg);
2790                         if (ret)
2791                                 goto out_free_refglobs;
2792                         break;
2793                 case IMAGEX_UNIX_DATA_OPTION:
2794                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2795                         break;
2796                 case IMAGEX_NO_ACLS_OPTION:
2797                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2798                         break;
2799                 case IMAGEX_STRICT_ACLS_OPTION:
2800                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2801                         break;
2802                 case IMAGEX_DEST_DIR_OPTION:
2803                         dest_dir = optarg;
2804                         break;
2805                 case IMAGEX_TO_STDOUT_OPTION:
2806                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2807                         imagex_info_file = stderr;
2808                         imagex_be_quiet = true;
2809                         break;
2810                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
2811                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
2812                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
2813                         break;
2814                 case IMAGEX_NO_WILDCARDS_OPTION:
2815                         listfile_extract_flags &= ~WIMLIB_EXTRACT_FLAG_GLOB_PATHS;
2816                         break;
2817                 case IMAGEX_STRICT_WILDCARDS_OPTION:
2818                         listfile_extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_GLOB;
2819                         break;
2820                 default:
2821                         goto out_usage;
2822                 }
2823         }
2824         argc -= optind;
2825         argv += optind;
2826
2827         if (argc < 2)
2828                 goto out_usage;
2829
2830         wimfile = argv[0];
2831         image_num_or_name = argv[1];
2832
2833         argc -= 2;
2834         argv += 2;
2835
2836         if (argc == 1 && argv[0][0] == T('@')) {
2837                 pathlist = argv[0] + 1;
2838                 cmds = NULL;
2839                 num_cmds = 0;
2840         } else {
2841                 cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2842                                                 &num_cmds);
2843                 if (cmds == NULL)
2844                         goto out_err;
2845                 pathlist = NULL;
2846         }
2847
2848         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2849         if (ret)
2850                 goto out_free_cmds;
2851
2852         image = wimlib_resolve_image(wim, image_num_or_name);
2853         ret = verify_image_exists_and_is_single(image,
2854                                                 image_num_or_name,
2855                                                 wimfile);
2856         if (ret)
2857                 goto out_wimlib_free;
2858
2859         if (refglobs.num_strings) {
2860                 ret = wim_reference_globs(wim, &refglobs, open_flags);
2861                 if (ret)
2862                         goto out_wimlib_free;
2863         }
2864
2865         ret = 0;
2866         if (ret == 0 && cmds != NULL) {
2867                 ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2868                                            imagex_progress_func);
2869         }
2870         if (ret == 0 && pathlist != NULL) {
2871                 ret = wimlib_extract_pathlist(wim, image, dest_dir,
2872                                               pathlist,
2873                                               extract_flags | listfile_extract_flags,
2874                                               imagex_progress_func);
2875         }
2876         if (ret == 0) {
2877                 if (!imagex_be_quiet)
2878                         imagex_printf(T("Done extracting files.\n"));
2879         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2880                 tfprintf(stderr, T("Note: You can use `%"TS"' to see what "
2881                                    "files and directories\n"
2882                                    "      are in the WIM image.\n"),
2883                                 get_cmd_string(CMD_DIR, false));
2884         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2885                 struct wimlib_wim_info info;
2886
2887                 wimlib_get_wim_info(wim, &info);
2888                 do_resource_not_found_warning(wimfile, &info, &refglobs);
2889         }
2890 out_wimlib_free:
2891         wimlib_free(wim);
2892 out_free_cmds:
2893         free_extract_commands(cmds, num_cmds, dest_dir);
2894 out_free_refglobs:
2895         string_set_destroy(&refglobs);
2896         return ret;
2897
2898 out_usage:
2899         usage(CMD_EXTRACT, stderr);
2900 out_err:
2901         ret = -1;
2902         goto out_free_refglobs;
2903 }
2904
2905 static void print_byte_field(const uint8_t field[], size_t len)
2906 {
2907         while (len--)
2908                 tprintf(T("%02hhx"), *field++);
2909 }
2910
2911 static void
2912 print_wim_information(const tchar *wimfile, const struct wimlib_wim_info *info)
2913 {
2914         tputs(T("WIM Information:"));
2915         tputs(T("----------------"));
2916         tprintf(T("Path:           %"TS"\n"), wimfile);
2917         tprintf(T("GUID:           0x"));
2918         print_byte_field(info->guid, sizeof(info->guid));
2919         tputchar(T('\n'));
2920         tprintf(T("Version:        %u\n"), info->wim_version);
2921         tprintf(T("Image Count:    %d\n"), info->image_count);
2922         tprintf(T("Compression:    %"TS"\n"),
2923                 wimlib_get_compression_type_string(info->compression_type));
2924         tprintf(T("Chunk Size:     %"PRIu32" bytes\n"),
2925                 info->chunk_size);
2926         tprintf(T("Part Number:    %d/%d\n"), info->part_number, info->total_parts);
2927         tprintf(T("Boot Index:     %d\n"), info->boot_index);
2928         tprintf(T("Size:           %"PRIu64" bytes\n"), info->total_bytes);
2929         tprintf(T("Integrity Info: %"TS"\n"),
2930                 info->has_integrity_table ? T("yes") : T("no"));
2931         tprintf(T("Relative path junction: %"TS"\n"),
2932                 info->has_rpfix ? T("yes") : T("no"));
2933         tprintf(T("Pipable:        %"TS"\n"),
2934                 info->pipable ? T("yes") : T("no"));
2935         tputchar(T('\n'));
2936 }
2937
2938 static int
2939 print_resource(const struct wimlib_resource_entry *resource,
2940                void *_ignore)
2941 {
2942         tprintf(T("Uncompressed size     = %"PRIu64" bytes\n"),
2943                 resource->uncompressed_size);
2944         if (resource->packed) {
2945                 tprintf(T("Raw compressed size   = %"PRIu64" bytes\n"),
2946                         resource->raw_resource_compressed_size);
2947
2948                 tprintf(T("Raw offset in WIM     = %"PRIu64" bytes\n"),
2949                         resource->raw_resource_offset_in_wim);
2950
2951                 tprintf(T("Offset in raw         = %"PRIu64" bytes\n"),
2952                         resource->offset);
2953         } else {
2954                 tprintf(T("Compressed size       = %"PRIu64" bytes\n"),
2955                         resource->compressed_size);
2956
2957                 tprintf(T("Offset in WIM         = %"PRIu64" bytes\n"),
2958                         resource->offset);
2959         }
2960
2961         tprintf(T("Part Number           = %u\n"), resource->part_number);
2962         tprintf(T("Reference Count       = %u\n"), resource->reference_count);
2963
2964         tprintf(T("Hash                  = 0x"));
2965         print_byte_field(resource->sha1_hash, sizeof(resource->sha1_hash));
2966         tputchar(T('\n'));
2967
2968         tprintf(T("Flags                 = "));
2969         if (resource->is_compressed)
2970                 tprintf(T("WIM_RESHDR_FLAG_COMPRESSED  "));
2971         if (resource->is_metadata)
2972                 tprintf(T("WIM_RESHDR_FLAG_METADATA  "));
2973         if (resource->is_free)
2974                 tprintf(T("WIM_RESHDR_FLAG_FREE  "));
2975         if (resource->is_spanned)
2976                 tprintf(T("WIM_RESHDR_FLAG_SPANNED  "));
2977         if (resource->packed)
2978                 tprintf(T("WIM_RESHDR_FLAG_PACKED_STREAMS  "));
2979         tputchar(T('\n'));
2980         tputchar(T('\n'));
2981         return 0;
2982 }
2983
2984 static void
2985 print_lookup_table(WIMStruct *wim)
2986 {
2987         wimlib_iterate_lookup_table(wim, 0, print_resource, NULL);
2988 }
2989
2990 /* Prints information about a WIM file; also can mark an image as bootable,
2991  * change the name of an image, or change the description of an image. */
2992 static int
2993 imagex_info(int argc, tchar **argv, int cmd)
2994 {
2995         int c;
2996         bool boot         = false;
2997         bool check        = false;
2998         bool nocheck      = false;
2999         bool header       = false;
3000         bool lookup_table = false;
3001         bool xml          = false;
3002         bool metadata     = false;
3003         bool short_header = true;
3004         const tchar *xml_out_file = NULL;
3005         const tchar *wimfile;
3006         const tchar *image_num_or_name;
3007         const tchar *new_name;
3008         const tchar *new_desc;
3009         WIMStruct *wim;
3010         int image;
3011         int ret;
3012         int open_flags = 0;
3013         struct wimlib_wim_info info;
3014
3015         for_opt(c, info_options) {
3016                 switch (c) {
3017                 case IMAGEX_BOOT_OPTION:
3018                         boot = true;
3019                         break;
3020                 case IMAGEX_CHECK_OPTION:
3021                         check = true;
3022                         break;
3023                 case IMAGEX_NOCHECK_OPTION:
3024                         nocheck = true;
3025                         break;
3026                 case IMAGEX_HEADER_OPTION:
3027                         header = true;
3028                         short_header = false;
3029                         break;
3030                 case IMAGEX_LOOKUP_TABLE_OPTION:
3031                         lookup_table = true;
3032                         short_header = false;
3033                         break;
3034                 case IMAGEX_XML_OPTION:
3035                         xml = true;
3036                         short_header = false;
3037                         break;
3038                 case IMAGEX_EXTRACT_XML_OPTION:
3039                         xml_out_file = optarg;
3040                         short_header = false;
3041                         break;
3042                 case IMAGEX_METADATA_OPTION:
3043                         metadata = true;
3044                         short_header = false;
3045                         break;
3046                 default:
3047                         goto out_usage;
3048                 }
3049         }
3050
3051         argc -= optind;
3052         argv += optind;
3053         if (argc < 1 || argc > 4)
3054                 goto out_usage;
3055
3056         wimfile           = argv[0];
3057         image_num_or_name = (argc >= 2) ? argv[1] : T("all");
3058         new_name          = (argc >= 3) ? argv[2] : NULL;
3059         new_desc          = (argc >= 4) ? argv[3] : NULL;
3060
3061         if (check && nocheck) {
3062                 imagex_error(T("Can't specify both --check and --nocheck"));
3063                 goto out_err;
3064         }
3065
3066         if (check)
3067                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3068
3069         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3070         if (ret)
3071                 goto out;
3072
3073         wimlib_get_wim_info(wim, &info);
3074
3075         image = wimlib_resolve_image(wim, image_num_or_name);
3076         ret = WIMLIB_ERR_INVALID_IMAGE;
3077         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
3078                 verify_image_exists(image, image_num_or_name, wimfile);
3079                 if (boot) {
3080                         imagex_error(T("If you would like to set the boot "
3081                                        "index to 0, specify image \"0\" with "
3082                                        "the --boot flag."));
3083                 }
3084                 goto out_wimlib_free;
3085         }
3086
3087         if (boot && info.image_count == 0) {
3088                 imagex_error(T("--boot is meaningless on a WIM with no images"));
3089                 goto out_wimlib_free;
3090         }
3091
3092         if (image == WIMLIB_ALL_IMAGES && info.image_count > 1) {
3093                 if (boot) {
3094                         imagex_error(T("Cannot specify the --boot flag "
3095                                        "without specifying a specific "
3096                                        "image in a multi-image WIM"));
3097                         goto out_wimlib_free;
3098                 }
3099                 if (new_name) {
3100                         imagex_error(T("Cannot specify the NEW_NAME "
3101                                        "without specifying a specific "
3102                                        "image in a multi-image WIM"));
3103                         goto out_wimlib_free;
3104                 }
3105         }
3106
3107         /* Operations that print information are separated from operations that
3108          * recreate the WIM file. */
3109         if (!new_name && !boot) {
3110
3111                 /* Read-only operations */
3112
3113                 if (image == WIMLIB_NO_IMAGE) {
3114                         imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\""),
3115                                      image_num_or_name, wimfile);
3116                         goto out_wimlib_free;
3117                 }
3118
3119                 if (image == WIMLIB_ALL_IMAGES && short_header)
3120                         print_wim_information(wimfile, &info);
3121
3122                 if (header)
3123                         wimlib_print_header(wim);
3124
3125                 if (lookup_table) {
3126                         if (info.total_parts != 1) {
3127                                 tfprintf(stderr, T("Warning: Only showing the lookup table "
3128                                                    "for part %d of a %d-part WIM.\n"),
3129                                          info.part_number, info.total_parts);
3130                         }
3131                         print_lookup_table(wim);
3132                 }
3133
3134                 if (xml) {
3135                         ret = wimlib_extract_xml_data(wim, stdout);
3136                         if (ret)
3137                                 goto out_wimlib_free;
3138                 }
3139
3140                 if (xml_out_file) {
3141                         FILE *fp;
3142
3143                         fp = tfopen(xml_out_file, T("wb"));
3144                         if (!fp) {
3145                                 imagex_error_with_errno(T("Failed to open the "
3146                                                           "file \"%"TS"\" for "
3147                                                           "writing"),
3148                                                         xml_out_file);
3149                                 ret = -1;
3150                                 goto out_wimlib_free;
3151                         }
3152                         ret = wimlib_extract_xml_data(wim, fp);
3153                         if (fclose(fp)) {
3154                                 imagex_error(T("Failed to close the file "
3155                                                "\"%"TS"\""),
3156                                              xml_out_file);
3157                                 ret = -1;
3158                         }
3159                         if (ret)
3160                                 goto out_wimlib_free;
3161                 }
3162
3163                 if (short_header)
3164                         wimlib_print_available_images(wim, image);
3165
3166                 if (metadata) {
3167                         ret = wimlib_print_metadata(wim, image);
3168                         if (ret)
3169                                 goto out_wimlib_free;
3170                 }
3171                 ret = 0;
3172         } else {
3173
3174                 /* Modification operations */
3175
3176                 if (image == WIMLIB_ALL_IMAGES)
3177                         image = 1;
3178
3179                 if (image == WIMLIB_NO_IMAGE && new_name) {
3180                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
3181                                        "when using image 0"), new_name);
3182                         ret = -1;
3183                         goto out_wimlib_free;
3184                 }
3185
3186                 if (boot) {
3187                         if (image == info.boot_index) {
3188                                 imagex_printf(T("Image %d is already marked as "
3189                                           "bootable.\n"), image);
3190                                 boot = false;
3191                         } else {
3192                                 imagex_printf(T("Marking image %d as bootable.\n"),
3193                                         image);
3194                                 info.boot_index = image;
3195                                 ret = wimlib_set_wim_info(wim, &info,
3196                                                           WIMLIB_CHANGE_BOOT_INDEX);
3197                                 if (ret)
3198                                         goto out_wimlib_free;
3199                         }
3200                 }
3201                 if (new_name) {
3202                         if (!tstrcmp(wimlib_get_image_name(wim, image), new_name))
3203                         {
3204                                 imagex_printf(T("Image %d is already named \"%"TS"\".\n"),
3205                                         image, new_name);
3206                                 new_name = NULL;
3207                         } else {
3208                                 imagex_printf(T("Changing the name of image %d to "
3209                                           "\"%"TS"\".\n"), image, new_name);
3210                                 ret = wimlib_set_image_name(wim, image, new_name);
3211                                 if (ret)
3212                                         goto out_wimlib_free;
3213                         }
3214                 }
3215                 if (new_desc) {
3216                         const tchar *old_desc;
3217                         old_desc = wimlib_get_image_description(wim, image);
3218                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
3219                                 imagex_printf(T("The description of image %d is already "
3220                                           "\"%"TS"\".\n"), image, new_desc);
3221                                 new_desc = NULL;
3222                         } else {
3223                                 imagex_printf(T("Changing the description of image %d "
3224                                           "to \"%"TS"\".\n"), image, new_desc);
3225                                 ret = wimlib_set_image_descripton(wim, image,
3226                                                                   new_desc);
3227                                 if (ret)
3228                                         goto out_wimlib_free;
3229                         }
3230                 }
3231
3232                 /* Only call wimlib_overwrite() if something actually needs to
3233                  * be changed.  */
3234                 if (boot || new_name || new_desc ||
3235                     (check && !info.has_integrity_table) ||
3236                     (nocheck && info.has_integrity_table))
3237                 {
3238                         int write_flags = 0;
3239
3240                         if (check)
3241                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3242                         if (nocheck)
3243                                 write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3244                         ret = wimlib_overwrite(wim, write_flags, 1,
3245                                                imagex_progress_func);
3246                 } else {
3247                         imagex_printf(T("The file \"%"TS"\" was not modified "
3248                                         "because nothing needed to be done.\n"),
3249                                       wimfile);
3250                         ret = 0;
3251                 }
3252         }
3253 out_wimlib_free:
3254         wimlib_free(wim);
3255 out:
3256         return ret;
3257
3258 out_usage:
3259         usage(CMD_INFO, stderr);
3260 out_err:
3261         ret = -1;
3262         goto out;
3263 }
3264
3265 /* Join split WIMs into one part WIM */
3266 static int
3267 imagex_join(int argc, tchar **argv, int cmd)
3268 {
3269         int c;
3270         int swm_open_flags = 0;
3271         int wim_write_flags = 0;
3272         const tchar *output_path;
3273         int ret;
3274
3275         for_opt(c, join_options) {
3276                 switch (c) {
3277                 case IMAGEX_CHECK_OPTION:
3278                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3279                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3280                         break;
3281                 default:
3282                         goto out_usage;
3283                 }
3284         }
3285         argc -= optind;
3286         argv += optind;
3287
3288         if (argc < 2) {
3289                 imagex_error(T("Must specify one or more split WIM (.swm) "
3290                                "parts to join"));
3291                 goto out_usage;
3292         }
3293         output_path = argv[0];
3294         ret = wimlib_join((const tchar * const *)++argv,
3295                           --argc,
3296                           output_path,
3297                           swm_open_flags,
3298                           wim_write_flags,
3299                           imagex_progress_func);
3300 out:
3301         return ret;
3302
3303 out_usage:
3304         usage(CMD_JOIN, stderr);
3305         ret = -1;
3306         goto out;
3307 }
3308
3309 #if WIM_MOUNTING_SUPPORTED
3310
3311 /* Mounts a WIM image.  */
3312 static int
3313 imagex_mount_rw_or_ro(int argc, tchar **argv, int cmd)
3314 {
3315         int c;
3316         int mount_flags = 0;
3317         int open_flags = 0;
3318         const tchar *staging_dir = NULL;
3319         const tchar *wimfile;
3320         const tchar *dir;
3321         WIMStruct *wim;
3322         struct wimlib_wim_info info;
3323         int image;
3324         int ret;
3325
3326         STRING_SET(refglobs);
3327
3328         if (cmd == CMD_MOUNTRW) {
3329                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
3330                 open_flags |= WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3331         }
3332
3333         for_opt(c, mount_options) {
3334                 switch (c) {
3335                 case IMAGEX_ALLOW_OTHER_OPTION:
3336                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
3337                         break;
3338                 case IMAGEX_CHECK_OPTION:
3339                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3340                         break;
3341                 case IMAGEX_DEBUG_OPTION:
3342                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
3343                         break;
3344                 case IMAGEX_STREAMS_INTERFACE_OPTION:
3345                         if (!tstrcasecmp(optarg, T("none")))
3346                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
3347                         else if (!tstrcasecmp(optarg, T("xattr")))
3348                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
3349                         else if (!tstrcasecmp(optarg, T("windows")))
3350                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
3351                         else {
3352                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
3353                                              optarg);
3354                                 goto out_usage;
3355                         }
3356                         break;
3357                 case IMAGEX_REF_OPTION:
3358                         ret = string_set_append(&refglobs, optarg);
3359                         if (ret)
3360                                 goto out_free_refglobs;
3361                         break;
3362                 case IMAGEX_STAGING_DIR_OPTION:
3363                         staging_dir = optarg;
3364                         break;
3365                 case IMAGEX_UNIX_DATA_OPTION:
3366                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
3367                         break;
3368                 default:
3369                         goto out_usage;
3370                 }
3371         }
3372         argc -= optind;
3373         argv += optind;
3374         if (argc != 2 && argc != 3)
3375                 goto out_usage;
3376
3377         wimfile = argv[0];
3378
3379         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3380         if (ret)
3381                 goto out_free_refglobs;
3382
3383         wimlib_get_wim_info(wim, &info);
3384
3385         if (argc >= 3) {
3386                 /* Image explicitly specified.  */
3387                 image = wimlib_resolve_image(wim, argv[1]);
3388                 dir = argv[2];
3389                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
3390                 if (ret)
3391                         goto out_free_wim;
3392         } else {
3393                 /* No image specified; default to image 1, but only if the WIM
3394                  * contains exactly one image.  */
3395
3396                 if (info.image_count != 1) {
3397                         imagex_error(T("\"%"TS"\" contains %d images; Please "
3398                                        "select one."), wimfile, info.image_count);
3399                         wimlib_free(wim);
3400                         goto out_usage;
3401                 }
3402                 image = 1;
3403                 dir = argv[1];
3404         }
3405
3406         if (refglobs.num_strings) {
3407                 ret = wim_reference_globs(wim, &refglobs, open_flags);
3408                 if (ret)
3409                         goto out_free_wim;
3410         }
3411
3412         ret = wimlib_mount_image(wim, image, dir, mount_flags, staging_dir);
3413         if (ret) {
3414                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
3415                                "on \"%"TS"\""),
3416                              image, wimfile, dir);
3417         }
3418 out_free_wim:
3419         wimlib_free(wim);
3420 out_free_refglobs:
3421         string_set_destroy(&refglobs);
3422         return ret;
3423
3424 out_usage:
3425         usage(cmd, stderr);
3426         ret = -1;
3427         goto out_free_refglobs;
3428 }
3429 #endif /* WIM_MOUNTING_SUPPORTED */
3430
3431 /* Rebuild a WIM file */
3432 static int
3433 imagex_optimize(int argc, tchar **argv, int cmd)
3434 {
3435         int c;
3436         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3437         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
3438         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
3439         uint32_t chunk_size = UINT32_MAX;
3440         uint32_t pack_chunk_size = UINT32_MAX;
3441         int ret;
3442         WIMStruct *wim;
3443         const tchar *wimfile;
3444         off_t old_size;
3445         off_t new_size;
3446         unsigned num_threads = 0;
3447
3448         for_opt(c, optimize_options) {
3449                 switch (c) {
3450                 case IMAGEX_CHECK_OPTION:
3451                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3452                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3453                         break;
3454                 case IMAGEX_NOCHECK_OPTION:
3455                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3456                         break;
3457                 case IMAGEX_COMPRESS_OPTION:
3458                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3459                         compression_type = get_compression_type(optarg);
3460                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
3461                                 goto out_err;
3462                         break;
3463                 case IMAGEX_RECOMPRESS_OPTION:
3464                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3465                         break;
3466                 case IMAGEX_COMPRESS_SLOW_OPTION:
3467                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3468                         set_compress_slow();
3469                         break;
3470                 case IMAGEX_CHUNK_SIZE_OPTION:
3471                         chunk_size = parse_chunk_size(optarg);
3472                         if (chunk_size == UINT32_MAX)
3473                                 goto out_err;
3474                         break;
3475                 case IMAGEX_PACK_CHUNK_SIZE_OPTION:
3476                         pack_chunk_size = parse_chunk_size(optarg);
3477                         if (pack_chunk_size == UINT32_MAX)
3478                                 goto out_err;
3479                         break;
3480                 case IMAGEX_PACK_STREAMS_OPTION:
3481                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
3482                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3483                         break;
3484                 case IMAGEX_THREADS_OPTION:
3485                         num_threads = parse_num_threads(optarg);
3486                         if (num_threads == UINT_MAX)
3487                                 goto out_err;
3488                         break;
3489                 case IMAGEX_PIPABLE_OPTION:
3490                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
3491                         break;
3492                 case IMAGEX_NOT_PIPABLE_OPTION:
3493                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
3494                         break;
3495                 default:
3496                         goto out_usage;
3497                 }
3498         }
3499         argc -= optind;
3500         argv += optind;
3501
3502         if (argc != 1)
3503                 goto out_usage;
3504
3505         wimfile = argv[0];
3506
3507         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3508         if (ret)
3509                 goto out;
3510
3511         if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
3512                 /* Change compression type.  */
3513                 ret = wimlib_set_output_compression_type(wim, compression_type);
3514                 if (ret)
3515                         goto out_wimlib_free;
3516         }
3517
3518         if (chunk_size != UINT32_MAX) {
3519                 /* Change chunk size.  */
3520                 ret = wimlib_set_output_chunk_size(wim, chunk_size);
3521                 if (ret)
3522                         goto out_wimlib_free;
3523         }
3524         if (pack_chunk_size != UINT32_MAX) {
3525                 ret = wimlib_set_output_pack_chunk_size(wim, pack_chunk_size);
3526                 if (ret)
3527                         goto out_wimlib_free;
3528         }
3529
3530         old_size = file_get_size(wimfile);
3531         tprintf(T("\"%"TS"\" original size: "), wimfile);
3532         if (old_size == -1)
3533                 tputs(T("Unknown"));
3534         else
3535                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
3536
3537         ret = wimlib_overwrite(wim, write_flags, num_threads,
3538                                imagex_progress_func);
3539         if (ret) {
3540                 imagex_error(T("Optimization of \"%"TS"\" failed."), wimfile);
3541                 goto out_wimlib_free;
3542         }
3543
3544         new_size = file_get_size(wimfile);
3545         tprintf(T("\"%"TS"\" optimized size: "), wimfile);
3546         if (new_size == -1)
3547                 tputs(T("Unknown"));
3548         else
3549                 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
3550
3551         tfputs(T("Space saved: "), stdout);
3552         if (new_size != -1 && old_size != -1) {
3553                 tprintf(T("%lld KiB\n"),
3554                        ((long long)old_size - (long long)new_size) >> 10);
3555         } else {
3556                 tputs(T("Unknown"));
3557         }
3558         ret = 0;
3559 out_wimlib_free:
3560         wimlib_free(wim);
3561 out:
3562         return ret;
3563
3564 out_usage:
3565         usage(CMD_OPTIMIZE, stderr);
3566 out_err:
3567         ret = -1;
3568         goto out;
3569 }
3570
3571 /* Split a WIM into a spanned set */
3572 static int
3573 imagex_split(int argc, tchar **argv, int cmd)
3574 {
3575         int c;
3576         int open_flags = 0;
3577         int write_flags = 0;
3578         unsigned long part_size;
3579         tchar *tmp;
3580         int ret;
3581         WIMStruct *wim;
3582
3583         for_opt(c, split_options) {
3584                 switch (c) {
3585                 case IMAGEX_CHECK_OPTION:
3586                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3587                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3588                         break;
3589                 default:
3590                         goto out_usage;
3591                 }
3592         }
3593         argc -= optind;
3594         argv += optind;
3595
3596         if (argc != 3)
3597                 goto out_usage;
3598
3599         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
3600         if (tmp == argv[2] || *tmp) {
3601                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
3602                 imagex_error(T("The part size must be an integer or "
3603                                "floating-point number of megabytes."));
3604                 goto out_err;
3605         }
3606         ret = wimlib_open_wim(argv[0], open_flags, &wim, imagex_progress_func);
3607         if (ret)
3608                 goto out;
3609
3610         ret = wimlib_split(wim, argv[1], part_size, write_flags, imagex_progress_func);
3611         wimlib_free(wim);
3612 out:
3613         return ret;
3614
3615 out_usage:
3616         usage(CMD_SPLIT, stderr);
3617 out_err:
3618         ret = -1;
3619         goto out;
3620 }
3621
3622 #if WIM_MOUNTING_SUPPORTED
3623 /* Unmounts a mounted WIM image. */
3624 static int
3625 imagex_unmount(int argc, tchar **argv, int cmd)
3626 {
3627         int c;
3628         int unmount_flags = 0;
3629         int ret;
3630
3631         for_opt(c, unmount_options) {
3632                 switch (c) {
3633                 case IMAGEX_COMMIT_OPTION:
3634                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
3635                         break;
3636                 case IMAGEX_CHECK_OPTION:
3637                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
3638                         break;
3639                 case IMAGEX_REBUILD_OPTION:
3640                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
3641                         break;
3642                 case IMAGEX_LAZY_OPTION:
3643                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_LAZY;
3644                         break;
3645                 default:
3646                         goto out_usage;
3647                 }
3648         }
3649         argc -= optind;
3650         argv += optind;
3651         if (argc != 1)
3652                 goto out_usage;
3653
3654         ret = wimlib_unmount_image(argv[0], unmount_flags,
3655                                    imagex_progress_func);
3656         if (ret)
3657                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
3658 out:
3659         return ret;
3660
3661 out_usage:
3662         usage(CMD_UNMOUNT, stderr);
3663         ret = -1;
3664         goto out;
3665 }
3666 #endif /* WIM_MOUNTING_SUPPORTED */
3667
3668 /*
3669  * Add, delete, or rename files in a WIM image.
3670  */
3671 static int
3672 imagex_update(int argc, tchar **argv, int cmd)
3673 {
3674         const tchar *wimfile;
3675         int image;
3676         WIMStruct *wim;
3677         int ret;
3678         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3679         int write_flags = 0;
3680         int update_flags = WIMLIB_UPDATE_FLAG_SEND_PROGRESS;
3681         int default_add_flags = WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
3682                                 WIMLIB_ADD_FLAG_VERBOSE;
3683         int default_delete_flags = 0;
3684         unsigned num_threads = 0;
3685         int c;
3686         tchar *cmd_file_contents;
3687         size_t cmd_file_nchars;
3688         struct wimlib_update_command *cmds;
3689         size_t num_cmds;
3690         tchar *command_str = NULL;
3691
3692         const tchar *config_file = NULL;
3693         tchar *config_str;
3694         struct wimlib_capture_config *config;
3695
3696         for_opt(c, update_options) {
3697                 switch (c) {
3698                 /* Generic or write options */
3699                 case IMAGEX_THREADS_OPTION:
3700                         num_threads = parse_num_threads(optarg);
3701                         if (num_threads == UINT_MAX)
3702                                 goto out_err;
3703                         break;
3704                 case IMAGEX_CHECK_OPTION:
3705                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3706                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3707                         break;
3708                 case IMAGEX_REBUILD_OPTION:
3709                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
3710                         break;
3711                 case IMAGEX_COMMAND_OPTION:
3712                         if (command_str) {
3713                                 imagex_error(T("--command may only be specified "
3714                                                "one time.  Please provide\n"
3715                                                "       the update commands "
3716                                                "on standard input instead."));
3717                                 goto out_err;
3718                         }
3719                         command_str = tstrdup(optarg);
3720                         if (!command_str) {
3721                                 imagex_error(T("Out of memory!"));
3722                                 goto out_err;
3723                         }
3724                         break;
3725                 /* Default delete options */