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