372e115b64509d8b6a85ba72061038160c353aef
[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 #include "config.h"
26 #include "wimlib.h"
27 #include "wimlib_tchar.h"
28
29 #include <ctype.h>
30 #include <errno.h>
31
32 #include <inttypes.h>
33 #include <libgen.h>
34 #include <limits.h>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #include <locale.h>
41
42 #ifdef HAVE_ALLOCA_H
43 #include <alloca.h>
44 #endif
45
46 #ifdef __WIN32__
47 #  include "imagex-win32.h"
48 #  define tbasename     win32_wbasename
49 #  define tglob         win32_wglob
50 #else /* __WIN32__ */
51 #  include <glob.h>
52 #  include <getopt.h>
53 #  include <langinfo.h>
54 #  define tbasename     basename
55 #  define tglob         glob
56 #endif /* !__WIN32 */
57
58
59 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
60
61 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
62                                 opts, NULL)) != -1)
63
64 enum imagex_op_type {
65         APPEND = 0,
66         APPLY,
67         CAPTURE,
68         DELETE,
69         DIR,
70         EXPORT,
71         INFO,
72         JOIN,
73         MOUNT,
74         MOUNTRW,
75         OPTIMIZE,
76         SPLIT,
77         UNMOUNT,
78 };
79
80 static void usage(int cmd_type);
81 static void usage_all();
82
83
84 static const tchar *usage_strings[] = {
85 [APPEND] =
86 T(
87 IMAGEX_PROGNAME" append (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
88 "                     [DESCRIPTION] [--boot] [--check] [--flags EDITION_ID]\n"
89 "                     [--verbose] [--dereference] [--config=FILE]\n"
90 "                     [--threads=NUM_THREADS] [--rebuild] [--unix-data]\n"
91 "                     [--source-list] [--no-acls] [--strict-acls]\n"
92 ),
93 [APPLY] =
94 T(
95 IMAGEX_PROGNAME" apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all]\n"
96 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
97 "                    [--symlink] [--verbose] [--ref=\"GLOB\"] [--unix-data]\n"
98 "                    [--no-acls] [--strict-acls]\n"
99 ),
100 [CAPTURE] =
101 T(
102 IMAGEX_PROGNAME" capture (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
103 "                      [DESCRIPTION] [--boot] [--check] [--compress=TYPE]\n"
104 "                      [--flags EDITION_ID] [--verbose] [--dereference]\n"
105 "                      [--config=FILE] [--threads=NUM_THREADS] [--unix-data]\n"
106 "                      [--source-list] [--no-acls] [--strict-acls]\n"
107 ),
108 [DELETE] =
109 T(
110 IMAGEX_PROGNAME" delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n"
111 ),
112 [DIR] =
113 T(
114 IMAGEX_PROGNAME" dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n"
115 ),
116 [EXPORT] =
117 T(
118 IMAGEX_PROGNAME" export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
119 "              DEST_WIMFILE [DEST_IMAGE_NAME] [DEST_IMAGE_DESCRIPTION]\n"
120 "              [--boot] [--check] [--compress=TYPE] [--ref=\"GLOB\"]\n"
121 "              [--threads=NUM_THREADS] [--rebuild]\n"
122 ),
123 [INFO] =
124 T(
125 IMAGEX_PROGNAME" info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
126 "                   [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
127 "                   [--xml] [--extract-xml FILE] [--metadata]\n"
128 ),
129 [JOIN] =
130 T(
131 IMAGEX_PROGNAME" join [--check] WIMFILE SPLIT_WIM...\n"
132 ),
133 [MOUNT] =
134 T(
135 IMAGEX_PROGNAME" mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
136 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
137 "                    [--ref=\"GLOB\"] [--unix-data] [--allow-other]\n"
138 ),
139 [MOUNTRW] =
140 T(
141 IMAGEX_PROGNAME" mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
142 "                      [--check] [--debug] [--streams-interface=INTERFACE]\n"
143 "                      [--staging-dir=DIR] [--unix-data] [--allow-other]\n"
144 ),
145 [OPTIMIZE] =
146 T(
147 IMAGEX_PROGNAME" optimize WIMFILE [--check] [--recompress]\n"
148 "                      [--threads=NUM_THREADS]\n"
149 ),
150 [SPLIT] =
151 T(
152 IMAGEX_PROGNAME" split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n"
153 ),
154 [UNMOUNT] =
155 T(
156 IMAGEX_PROGNAME" unmount DIRECTORY [--commit] [--check] [--rebuild]\n"
157 ),
158 };
159
160 enum {
161         IMAGEX_ALLOW_OTHER_OPTION,
162         IMAGEX_BOOT_OPTION,
163         IMAGEX_CHECK_OPTION,
164         IMAGEX_COMMIT_OPTION,
165         IMAGEX_COMPRESS_OPTION,
166         IMAGEX_CONFIG_OPTION,
167         IMAGEX_DEBUG_OPTION,
168         IMAGEX_DEREFERENCE_OPTION,
169         IMAGEX_EXTRACT_XML_OPTION,
170         IMAGEX_FLAGS_OPTION,
171         IMAGEX_HARDLINK_OPTION,
172         IMAGEX_HEADER_OPTION,
173         IMAGEX_LOOKUP_TABLE_OPTION,
174         IMAGEX_METADATA_OPTION,
175         IMAGEX_NO_ACLS_OPTION,
176         IMAGEX_REBULID_OPTION,
177         IMAGEX_RECOMPRESS_OPTION,
178         IMAGEX_REF_OPTION,
179         IMAGEX_SOFT_OPTION,
180         IMAGEX_SOURCE_LIST_OPTION,
181         IMAGEX_STAGING_DIR_OPTION,
182         IMAGEX_STREAMS_INTERFACE_OPTION,
183         IMAGEX_STRICT_ACLS_OPTION,
184         IMAGEX_SYMLINK_OPTION,
185         IMAGEX_THREADS_OPTION,
186         IMAGEX_UNIX_DATA_OPTION,
187         IMAGEX_VERBOSE_OPTION,
188         IMAGEX_XML_OPTION,
189 };
190
191 static const struct option apply_options[] = {
192         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
193         {T("hardlink"),    no_argument,       NULL, IMAGEX_HARDLINK_OPTION},
194         {T("symlink"),     no_argument,       NULL, IMAGEX_SYMLINK_OPTION},
195         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
196         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
197         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
198         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
199         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
200         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
201         {NULL, 0, NULL, 0},
202 };
203 static const struct option capture_or_append_options[] = {
204         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
205         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
206         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
207         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
208         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
209         {T("flags"),       required_argument, NULL, IMAGEX_FLAGS_OPTION},
210         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
211         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
212         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBULID_OPTION},
213         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
214         {T("source-list"), no_argument,       NULL, IMAGEX_SOURCE_LIST_OPTION},
215         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
216         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
217         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
218         {NULL, 0, NULL, 0},
219 };
220 static const struct option delete_options[] = {
221         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
222         {T("soft"),  no_argument, NULL, IMAGEX_SOFT_OPTION},
223         {NULL, 0, NULL, 0},
224 };
225
226 static const struct option export_options[] = {
227         {T("boot"),       no_argument,       NULL, IMAGEX_BOOT_OPTION},
228         {T("check"),      no_argument,       NULL, IMAGEX_CHECK_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_REBULID_OPTION},
233         {NULL, 0, NULL, 0},
234 };
235
236 static const struct option info_options[] = {
237         {T("boot"),         no_argument,       NULL, IMAGEX_BOOT_OPTION},
238         {T("check"),        no_argument,       NULL, IMAGEX_CHECK_OPTION},
239         {T("extract-xml"),  required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
240         {T("header"),       no_argument,       NULL, IMAGEX_HEADER_OPTION},
241         {T("lookup-table"), no_argument,       NULL, IMAGEX_LOOKUP_TABLE_OPTION},
242         {T("metadata"),     no_argument,       NULL, IMAGEX_METADATA_OPTION},
243         {T("xml"),          no_argument,       NULL, IMAGEX_XML_OPTION},
244         {NULL, 0, NULL, 0},
245 };
246
247 static const struct option join_options[] = {
248         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
249         {NULL, 0, NULL, 0},
250 };
251
252 static const struct option mount_options[] = {
253         {T("check"),             no_argument,       NULL, IMAGEX_CHECK_OPTION},
254         {T("debug"),             no_argument,       NULL, IMAGEX_DEBUG_OPTION},
255         {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
256         {T("ref"),               required_argument, NULL, IMAGEX_REF_OPTION},
257         {T("staging-dir"),       required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
258         {T("unix-data"),         no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
259         {T("allow-other"),       no_argument,       NULL, IMAGEX_ALLOW_OTHER_OPTION},
260         {NULL, 0, NULL, 0},
261 };
262
263 static const struct option optimize_options[] = {
264         {T("check"),      no_argument, NULL, IMAGEX_CHECK_OPTION},
265         {T("recompress"), no_argument, NULL, IMAGEX_RECOMPRESS_OPTION},
266         {T("threads"),    required_argument, NULL, IMAGEX_THREADS_OPTION},
267         {NULL, 0, NULL, 0},
268 };
269
270 static const struct option split_options[] = {
271         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
272         {NULL, 0, NULL, 0},
273 };
274
275 static const struct option unmount_options[] = {
276         {T("commit"),  no_argument, NULL, IMAGEX_COMMIT_OPTION},
277         {T("check"),   no_argument, NULL, IMAGEX_CHECK_OPTION},
278         {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
279         {NULL, 0, NULL, 0},
280 };
281
282
283
284 /* Print formatted error message to stderr. */
285 static void
286 imagex_error(const tchar *format, ...)
287 {
288         va_list va;
289         va_start(va, format);
290         tfputs(T("ERROR: "), stderr);
291         tvfprintf(stderr, format, va);
292         tputc(T('\n'), stderr);
293         va_end(va);
294 }
295
296 /* Print formatted error message to stderr. */
297 static void
298 imagex_error_with_errno(const tchar *format, ...)
299 {
300         int errno_save = errno;
301         va_list va;
302         va_start(va, format);
303         tfputs(T("ERROR: "), stderr);
304         tvfprintf(stderr, format, va);
305         tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
306         va_end(va);
307 }
308
309 static int
310 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
311 {
312         if (image == WIMLIB_NO_IMAGE) {
313                 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
314                              "       Please specify a 1-based image index or "
315                              "image name.\n"
316                              "       You may use `"IMAGEX_PROGNAME" info' to list the images "
317                              "contained in a WIM."),
318                              image_name, wim_name);
319                 return -1;
320         }
321         return 0;
322 }
323
324 static int
325 verify_image_is_single(int image)
326 {
327         if (image == WIMLIB_ALL_IMAGES) {
328                 imagex_error(T("Cannot specify all images for this action!"));
329                 return -1;
330         }
331         return 0;
332 }
333
334 static int
335 verify_image_exists_and_is_single(int image, const tchar *image_name,
336                                   const tchar *wim_name)
337 {
338         int ret;
339         ret = verify_image_exists(image, image_name, wim_name);
340         if (ret == 0)
341                 ret = verify_image_is_single(image);
342         return ret;
343 }
344
345 /* Parse the argument to --compress */
346 static int
347 get_compression_type(const tchar *optarg)
348 {
349         if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
350                 return WIMLIB_COMPRESSION_TYPE_LZX;
351         else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
352                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
353         else if (!tstrcasecmp(optarg, T("none")))
354                 return WIMLIB_COMPRESSION_TYPE_NONE;
355         else {
356                 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
357                              "\"maximum\", \"fast\", or \"none\"."), optarg);
358                 return WIMLIB_COMPRESSION_TYPE_INVALID;
359         }
360 }
361
362 /* Returns the size of a file given its name, or -1 if the file does not exist
363  * or its size cannot be determined.  */
364 static off_t
365 file_get_size(const tchar *filename)
366 {
367         struct stat st;
368         if (tstat(filename, &st) == 0)
369                 return st.st_size;
370         else
371                 return (off_t)-1;
372 }
373
374 tchar pat_ntfs_log[]                  = T("/$ntfs.log");
375 tchar pat_hiberfil_sys[]              = T("/hiberfil.sys");
376 tchar pat_pagefile_sys[]              = T("/pagefile.sys");
377 tchar pat_system_volume_information[] = T("/System Volume Information");
378 tchar pat_recycler[]                  = T("/RECYCLER");
379 tchar pat_windows_csc[]               = T("/Windows/CSC");
380
381 tchar *default_pats[] = {
382         pat_ntfs_log,
383         pat_hiberfil_sys,
384         pat_pagefile_sys,
385         pat_system_volume_information,
386         pat_recycler,
387         pat_windows_csc,
388 };
389
390 static struct wimlib_capture_config default_capture_config = {
391         .exclusion_pats = {
392                 .num_pats = sizeof(default_pats) / sizeof(*default_pats),
393                 .pats = default_pats,
394         },
395 };
396
397 enum {
398         PARSE_FILENAME_SUCCESS = 0,
399         PARSE_FILENAME_FAILURE = 1,
400         PARSE_FILENAME_NONE = 2,
401 };
402
403 /*
404  * Parses a filename in the source list file format.  (See the man page for
405  * 'wimlib-imagex capture' for details on this format and the meaning.)
406  * Accepted formats for filenames are an unquoted string (whitespace-delimited),
407  * or a double or single-quoted string.
408  *
409  * @line_p:  Pointer to the pointer to the line of data.  Will be updated
410  *           to point past the filename iff the return value is
411  *           PARSE_FILENAME_SUCCESS.  If *len_p > 0, (*line_p)[*len_p - 1] must
412  *           be '\0'.
413  *
414  * @len_p:   @len_p initially stores the length of the line of data, which may
415  *           be 0, and it will be updated to the number of bytes remaining in
416  *           the line iff the return value is PARSE_FILENAME_SUCCESS.
417  *
418  * @fn_ret:  Iff the return value is PARSE_FILENAME_SUCCESS, a pointer to the
419  *           parsed filename will be returned here.
420  *
421  * Returns: PARSE_FILENAME_SUCCESS if a filename was successfully parsed; or
422  *          PARSE_FILENAME_FAILURE if the data was invalid due to a missing
423  *          closing quote; or PARSE_FILENAME_NONE if the line ended before the
424  *          beginning of a filename was found.
425  */
426 static int
427 parse_filename(tchar **line_p, size_t *len_p, tchar **fn_ret)
428 {
429         size_t len = *len_p;
430         tchar *line = *line_p;
431         tchar *fn;
432         tchar quote_char;
433
434         /* Skip leading whitespace */
435         for (;;) {
436                 if (len == 0)
437                         return PARSE_FILENAME_NONE;
438                 if (!istspace(*line) && *line != T('\0'))
439                         break;
440                 line++;
441                 len--;
442         }
443         quote_char = *line;
444         if (quote_char == T('"') || quote_char == T('\'')) {
445                 /* Quoted filename */
446                 line++;
447                 len--;
448                 fn = line;
449                 line = tmemchr(line, quote_char, len);
450                 if (!line) {
451                         imagex_error(T("Missing closing quote: %"TS), fn - 1);
452                         return PARSE_FILENAME_FAILURE;
453                 }
454         } else {
455                 /* Unquoted filename.  Go until whitespace.  Line is terminated
456                  * by '\0', so no need to check 'len'. */
457                 fn = line;
458                 do {
459                         line++;
460                 } while (!istspace(*line) && *line != T('\0'));
461         }
462         *line = T('\0');
463         len -= line - fn;
464         *len_p = len;
465         *line_p = line;
466         *fn_ret = fn;
467         return PARSE_FILENAME_SUCCESS;
468 }
469
470 /* Parses a line of data (not an empty line or comment) in the source list file
471  * format.  (See the man page for 'wimlib-imagex capture' for details on this
472  * format and the meaning.)
473  *
474  * @line:  Line of data to be parsed.  line[len - 1] must be '\0', unless
475  *         len == 0.  The data in @line will be modified by this function call.
476  *
477  * @len:   Length of the line of data.
478  *
479  * @source:  On success, the capture source and target described by the line is
480  *           written into this destination.  Note that it will contain pointers
481  *           to data in the @line array.
482  *
483  * Returns true if the line was valid; false otherwise.  */
484 static bool
485 parse_source_list_line(tchar *line, size_t len,
486                        struct wimlib_capture_source *source)
487 {
488         /* SOURCE [DEST] */
489         int ret;
490         ret = parse_filename(&line, &len, &source->fs_source_path);
491         if (ret != PARSE_FILENAME_SUCCESS)
492                 return false;
493         ret = parse_filename(&line, &len, &source->wim_target_path);
494         if (ret == PARSE_FILENAME_NONE)
495                 source->wim_target_path = source->fs_source_path;
496         return ret != PARSE_FILENAME_FAILURE;
497 }
498
499 /* Returns %true if the given line of length @len > 0 is a comment or empty line
500  * in the source list file format. */
501 static bool
502 is_comment_line(const tchar *line, size_t len)
503 {
504         for (;;) {
505                 if (*line == T('#'))
506                         return true;
507                 if (!istspace(*line) && *line != T('\0'))
508                         return false;
509                 ++line;
510                 --len;
511                 if (len == 0)
512                         return true;
513         }
514 }
515
516 static ssize_t
517 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
518 {
519         ssize_t nlines = 0;
520         tchar *contents = *contents_p;
521         size_t nchars = *nchars_p;
522         size_t i;
523
524         for (i = 0; i < nchars; i++)
525                 if (contents[i] == T('\n'))
526                         nlines++;
527
528         /* Handle last line not terminated by a newline */
529         if (nchars != 0 && contents[nchars - 1] != T('\n')) {
530                 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
531                 if (!contents) {
532                         imagex_error(T("Out of memory!"));
533                         return -1;
534                 }
535                 contents[nchars] = T('\n');
536                 *contents_p = contents;
537                 nchars++;
538                 nlines++;
539         }
540         *nchars_p = nchars;
541         return nlines;
542 }
543
544 /* Parses a file in the source list format.  (See the man page for
545  * 'wimlib-imagex capture' for details on this format and the meaning.)
546  *
547  * @source_list_contents:  Contents of the source list file.  Note that this
548  *                         buffer will be modified to save memory allocations,
549  *                         and cannot be freed until the returned array of
550  *                         wimlib_capture_source's has also been freed.
551  *
552  * @source_list_nbytes:    Number of bytes of data in the @source_list_contents
553  *                         buffer.
554  *
555  * @nsources_ret:          On success, the length of the returned array is
556  *                         returned here.
557  *
558  * Returns:   An array of `struct wimlib_capture_source's that can be passed to
559  * the wimlib_add_image_multisource() function to specify how a WIM image is to
560  * be created.  */
561 static struct wimlib_capture_source *
562 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
563                   size_t *nsources_ret)
564 {
565         ssize_t nlines;
566         tchar *p;
567         struct wimlib_capture_source *sources;
568         size_t i, j;
569
570         nlines = text_file_count_lines(source_list_contents_p,
571                                        &source_list_nchars);
572         if (nlines < 0)
573                 return NULL;
574
575         /* Always allocate at least 1 slot, just in case the implementation of
576          * calloc() returns NULL if 0 bytes are requested. */
577         sources = calloc(nlines ?: 1, sizeof(*sources));
578         if (!sources) {
579                 imagex_error(T("out of memory"));
580                 return NULL;
581         }
582         p = *source_list_contents_p;
583         j = 0;
584         for (i = 0; i < nlines; i++) {
585                 /* XXX: Could use rawmemchr() here instead, but it may not be
586                  * available on all platforms. */
587                 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
588                 size_t len = endp - p + 1;
589                 *endp = T('\0');
590                 if (!is_comment_line(p, len)) {
591                         if (!parse_source_list_line(p, len, &sources[j++])) {
592                                 free(sources);
593                                 return NULL;
594                         }
595                 }
596                 p = endp + 1;
597
598         }
599         *nsources_ret = j;
600         return sources;
601 }
602
603
604 enum capture_config_section {
605         CAPTURE_CONFIG_NO_SECTION,
606         CAPTURE_CONFIG_EXCLUSION_SECTION,
607         CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
608         CAPTURE_CONFIG_IGNORE_SECTION,
609 };
610
611 enum {
612         CAPTURE_CONFIG_INVALID_SECTION,
613         CAPTURE_CONFIG_CHANGED_SECTION,
614         CAPTURE_CONFIG_SAME_SECTION,
615 };
616
617 static int
618 check_config_section(tchar *line, size_t len,
619                      enum capture_config_section *cur_section)
620 {
621         while (istspace(*line))
622                 line++;
623
624         if (*line != T('['))
625                 return CAPTURE_CONFIG_SAME_SECTION;
626
627         line++;
628         tchar *endbrace = tstrrchr(line, T(']'));
629         if (!endbrace)
630                 return CAPTURE_CONFIG_SAME_SECTION;
631
632         if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
633                 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
634         } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
635                 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
636         } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
637                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
638                 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
639                          "of capture config file\n"),
640                        stderr);
641         } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
642                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
643                 tfputs(T("WARNING: Ignoring [AlignmentList] section "
644                          "of capture config file\n"),
645                        stderr);
646         } else {
647                 imagex_error(T("Invalid capture config file section \"%"TS"\""),
648                              line - 1);
649                 return CAPTURE_CONFIG_INVALID_SECTION;
650         }
651         return CAPTURE_CONFIG_CHANGED_SECTION;
652 }
653
654
655 static bool
656 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
657                          tchar *pat)
658 {
659         if (pat_list->num_pats == pat_list->num_allocated_pats) {
660                 tchar **pats;
661                 size_t num_allocated_pats = pat_list->num_pats + 8;
662
663                 pats = realloc(pat_list->pats,
664                                num_allocated_pats * sizeof(pat_list->pats[0]));
665                 if (!pats) {
666                         imagex_error(T("Out of memory!"));
667                         return false;
668                 }
669                 pat_list->pats = pats;
670                 pat_list->num_allocated_pats = num_allocated_pats;
671         }
672         pat_list->pats[pat_list->num_pats++] = pat;
673         return true;
674 }
675
676 static bool
677 parse_capture_config_line(tchar *line, size_t len,
678                           enum capture_config_section *cur_section,
679                           struct wimlib_capture_config *config)
680 {
681         tchar *filename;
682         int ret;
683
684         ret = check_config_section(line, len, cur_section);
685         if (ret == CAPTURE_CONFIG_INVALID_SECTION)
686                 return false;
687         if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
688                 return true;
689
690         switch (*cur_section) {
691         case CAPTURE_CONFIG_NO_SECTION:
692                 imagex_error(T("Line \"%"TS"\" is not in a section "
693                                "(such as [ExclusionList]"), line);
694                 return false;
695         case CAPTURE_CONFIG_EXCLUSION_SECTION:
696                 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
697                         return false;
698                 return pattern_list_add_pattern(&config->exclusion_pats,
699                                                 filename);
700         case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
701                 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
702                         return false;
703                 return pattern_list_add_pattern(&config->exclusion_exception_pats,
704                                                 filename);
705         case CAPTURE_CONFIG_IGNORE_SECTION:
706                 return true;
707         }
708         return false;
709 }
710
711 static int
712 parse_capture_config(tchar **contents_p, size_t nchars,
713                      struct wimlib_capture_config *config)
714 {
715         ssize_t nlines;
716         tchar *p;
717         size_t i;
718         enum capture_config_section cur_section;
719
720         memset(config, 0, sizeof(*config));
721
722         nlines = text_file_count_lines(contents_p, &nchars);
723         if (nlines < 0)
724                 return -1;
725
726         cur_section = CAPTURE_CONFIG_NO_SECTION;
727         p = *contents_p;
728         for (i = 0; i < nlines; i++) {
729                 tchar *endp = tmemchr(p, T('\n'), nchars);
730                 size_t len = endp - p + 1;
731                 *endp = T('\0');
732                 if (!is_comment_line(p, len))
733                         if (!parse_capture_config_line(p, len, &cur_section, config))
734                                 return -1;
735                 p = endp + 1;
736
737         }
738         return 0;
739 }
740
741 /* Reads the contents of a file into memory. */
742 static char *
743 file_get_contents(const tchar *filename, size_t *len_ret)
744 {
745         struct stat stbuf;
746         void *buf = NULL;
747         size_t len;
748         FILE *fp;
749
750         if (tstat(filename, &stbuf) != 0) {
751                 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
752                 goto out;
753         }
754         len = stbuf.st_size;
755
756         fp = tfopen(filename, T("rb"));
757         if (!fp) {
758                 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
759                 goto out;
760         }
761
762         buf = malloc(len);
763         if (!buf) {
764                 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
765                                "contents of file \"%"TS"\""), len, filename);
766                 goto out_fclose;
767         }
768         if (fread(buf, 1, len, fp) != len) {
769                 imagex_error_with_errno(T("Failed to read %zu bytes from the "
770                                           "file \"%"TS"\""), len, filename);
771                 goto out_free_buf;
772         }
773         *len_ret = len;
774         goto out_fclose;
775 out_free_buf:
776         free(buf);
777         buf = NULL;
778 out_fclose:
779         fclose(fp);
780 out:
781         return buf;
782 }
783
784 /* Read standard input until EOF and return the full contents in a malloc()ed
785  * buffer and the number of bytes of data in @len_ret.  Returns NULL on read
786  * error. */
787 static char *
788 stdin_get_contents(size_t *len_ret)
789 {
790         /* stdin can, of course, be a pipe or other non-seekable file, so the
791          * total length of the data cannot be pre-determined */
792         char *buf = NULL;
793         size_t newlen = 1024;
794         size_t pos = 0;
795         size_t inc = 1024;
796         for (;;) {
797                 char *p = realloc(buf, newlen);
798                 size_t bytes_read, bytes_to_read;
799                 if (!p) {
800                         imagex_error(T("out of memory while reading stdin"));
801                         break;
802                 }
803                 buf = p;
804                 bytes_to_read = newlen - pos;
805                 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
806                 pos += bytes_read;
807                 if (bytes_read != bytes_to_read) {
808                         if (feof(stdin)) {
809                                 *len_ret = pos;
810                                 return buf;
811                         } else {
812                                 imagex_error_with_errno(T("error reading stdin"));
813                                 break;
814                         }
815                 }
816                 newlen += inc;
817                 inc *= 3;
818                 inc /= 2;
819         }
820         free(buf);
821         return NULL;
822 }
823
824
825 static tchar *
826 translate_text_to_tstr(char *text, size_t num_bytes,
827                        size_t *num_tchars_ret)
828 {
829 #ifndef __WIN32__
830         /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
831          * */
832         *num_tchars_ret = num_bytes;
833         return text;
834 #else /* !__WIN32__ */
835         /* On Windows, translate the text to UTF-16LE */
836         wchar_t *text_wstr;
837         size_t num_wchars;
838
839         if (num_bytes >= 2 &&
840             ((text[0] == 0xff && text[1] == 0xfe) ||
841              (text[0] <= 0x7f && text[1] == 0x00)))
842         {
843                 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
844                  * with something that looks like an ASCII character encoded as
845                  * a UTF-16LE code unit.  Assume the file is encoded as
846                  * UTF-16LE.  This is not a 100% reliable check. */
847                 num_wchars = num_bytes / 2;
848                 text_wstr = (wchar_t*)text;
849         } else {
850                 /* File does not look like UTF-16LE.  Assume it is encoded in
851                  * the current Windows code page.  I think these are always
852                  * ASCII-compatible, so any so-called "plain-text" (ASCII) files
853                  * should work as expected. */
854                 text_wstr = win32_mbs_to_wcs(text,
855                                              num_bytes,
856                                              &num_wchars);
857                 free(text);
858         }
859         *num_tchars_ret = num_wchars;
860         return text_wstr;
861 #endif /* __WIN32__ */
862 }
863
864 static tchar *
865 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
866 {
867         char *contents;
868         size_t num_bytes;
869
870         contents = file_get_contents(filename, &num_bytes);
871         if (!contents)
872                 return NULL;
873         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
874 }
875
876 static tchar *
877 stdin_get_text_contents(size_t *num_tchars_ret)
878 {
879         char *contents;
880         size_t num_bytes;
881
882         contents = stdin_get_contents(&num_bytes);
883         if (!contents)
884                 return NULL;
885         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
886 }
887
888 /* Return 0 if a path names a file to which the current user has write access;
889  * -1 otherwise (and print an error message). */
890 static int
891 file_writable(const tchar *path)
892 {
893         int ret;
894         ret = taccess(path, W_OK);
895         if (ret != 0)
896                 imagex_error_with_errno(T("Can't modify \"%"TS"\""), path);
897         return ret;
898 }
899
900 #define TO_PERCENT(numerator, denominator) \
901         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
902
903 /* Given an enumerated value for WIM compression type, return a descriptive
904  * string. */
905 static const tchar *
906 get_data_type(int ctype)
907 {
908         switch (ctype) {
909         case WIMLIB_COMPRESSION_TYPE_NONE:
910                 return T("uncompressed");
911         case WIMLIB_COMPRESSION_TYPE_LZX:
912                 return T("LZX-compressed");
913         case WIMLIB_COMPRESSION_TYPE_XPRESS:
914                 return T("XPRESS-compressed");
915         }
916         return NULL;
917 }
918
919 /* Progress callback function passed to various wimlib functions. */
920 static int
921 imagex_progress_func(enum wimlib_progress_msg msg,
922                      const union wimlib_progress_info *info)
923 {
924         unsigned percent_done;
925         switch (msg) {
926         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
927                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
928                                           info->write_streams.total_bytes);
929                 if (info->write_streams.completed_streams == 0) {
930                         const tchar *data_type;
931
932                         data_type = get_data_type(info->write_streams.compression_type);
933                         tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
934                                 data_type, info->write_streams.num_threads,
935                                 (info->write_streams.num_threads == 1) ? T("") : T("s"));
936                 }
937                 tprintf(T("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
938                         "written (%u%% done)"),
939                         info->write_streams.completed_bytes >> 20,
940                         info->write_streams.total_bytes >> 20,
941                         percent_done);
942                 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
943                         tputchar(T('\n'));
944                 break;
945         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
946                 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
947                 if (*info->scan.wim_target_path) {
948                         tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
949                                info->scan.wim_target_path);
950                 } else {
951                         tprintf(T(" (loading as root of WIM image)...\n"));
952                 }
953                 break;
954         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
955                 if (info->scan.excluded)
956                         tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
957                 else
958                         tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
959                 break;
960         /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
961                 /*break;*/
962         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
963                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
964                                           info->integrity.total_bytes);
965                 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" MiB "
966                         "of %"PRIu64" MiB (%u%%) done"),
967                         info->integrity.filename,
968                         info->integrity.completed_bytes >> 20,
969                         info->integrity.total_bytes >> 20,
970                         percent_done);
971                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
972                         tputchar(T('\n'));
973                 break;
974         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
975                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
976                                           info->integrity.total_bytes);
977                 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" MiB "
978                           "of %"PRIu64" MiB (%u%%) done"),
979                         info->integrity.completed_bytes >> 20,
980                         info->integrity.total_bytes >> 20,
981                         percent_done);
982                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
983                         tputchar(T('\n'));
984                 break;
985         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
986                 tprintf(T("Applying image %d (%"TS") from \"%"TS"\" "
987                           "to %"TS" \"%"TS"\"\n"),
988                         info->extract.image,
989                         info->extract.image_name,
990                         info->extract.wimfile_name,
991                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
992                          T("NTFS volume") : T("directory")),
993                         info->extract.target);
994                 break;
995         /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
996                 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
997                         /*info->extract.target);*/
998                 /*break;*/
999         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1000                 percent_done = TO_PERCENT(info->extract.completed_bytes,
1001                                           info->extract.total_bytes);
1002                 tprintf(T("\rExtracting files: "
1003                           "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done"),
1004                         info->extract.completed_bytes >> 20,
1005                         info->extract.total_bytes >> 20,
1006                         percent_done);
1007                 if (info->extract.completed_bytes >= info->extract.total_bytes)
1008                         tputchar(T('\n'));
1009                 break;
1010         case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
1011                 tprintf(T("%"TS"\n"), info->extract.cur_path);
1012                 break;
1013         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1014                 tprintf(T("Setting timestamps on all extracted files...\n"));
1015                 break;
1016         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1017                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1018                         tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1019                                 info->extract.target);
1020                 }
1021                 break;
1022         case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
1023                 percent_done = TO_PERCENT(info->join.completed_bytes,
1024                                           info->join.total_bytes);
1025                 tprintf(T("Writing resources from part %u of %u: "
1026                           "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n"),
1027                         (info->join.completed_parts == info->join.total_parts) ?
1028                         info->join.completed_parts : info->join.completed_parts + 1,
1029                         info->join.total_parts,
1030                         info->join.completed_bytes >> 20,
1031                         info->join.total_bytes >> 20,
1032                         percent_done);
1033                 break;
1034         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1035                 percent_done = TO_PERCENT(info->split.completed_bytes,
1036                                           info->split.total_bytes);
1037                 tprintf(T("Writing \"%"TS"\": %"PRIu64" MiB of "
1038                           "%"PRIu64" MiB (%u%%) written\n"),
1039                         info->split.part_name,
1040                         info->split.completed_bytes >> 20,
1041                         info->split.total_bytes >> 20,
1042                         percent_done);
1043                 break;
1044         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1045                 if (info->split.completed_bytes == info->split.total_bytes) {
1046                         tprintf(T("Finished writing %u split WIM parts\n"),
1047                                 info->split.cur_part_number);
1048                 }
1049                 break;
1050         default:
1051                 break;
1052         }
1053         fflush(stdout);
1054         return 0;
1055 }
1056
1057 /* Open all the split WIM parts that correspond to a file glob.
1058  *
1059  * @first_part specifies the first part of the split WIM and it may be either
1060  * included or omitted from the glob. */
1061 static int
1062 open_swms_from_glob(const tchar *swm_glob,
1063                     const tchar *first_part,
1064                     int open_flags,
1065                     WIMStruct ***additional_swms_ret,
1066                     unsigned *num_additional_swms_ret)
1067 {
1068         unsigned num_additional_swms = 0;
1069         WIMStruct **additional_swms = NULL;
1070         glob_t globbuf;
1071         int ret;
1072
1073         /* Warning: glob() is replaced in Windows native builds */
1074         ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1075         if (ret != 0) {
1076                 if (ret == GLOB_NOMATCH) {
1077                         imagex_error(T("Found no files for glob \"%"TS"\""),
1078                                      swm_glob);
1079                 } else {
1080                         imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1081                                                 swm_glob);
1082                 }
1083                 ret = -1;
1084                 goto out;
1085         }
1086         num_additional_swms = globbuf.gl_pathc;
1087         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1088         if (!additional_swms) {
1089                 imagex_error(T("Out of memory"));
1090                 ret = -1;
1091                 goto out_globfree;
1092         }
1093         unsigned offset = 0;
1094         for (unsigned i = 0; i < num_additional_swms; i++) {
1095                 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1096                         offset++;
1097                         continue;
1098                 }
1099                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1100                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1101                                       &additional_swms[i - offset],
1102                                       imagex_progress_func);
1103                 if (ret != 0)
1104                         goto out_close_swms;
1105         }
1106         *additional_swms_ret = additional_swms;
1107         *num_additional_swms_ret = num_additional_swms - offset;
1108         ret = 0;
1109         goto out_globfree;
1110 out_close_swms:
1111         for (unsigned i = 0; i < num_additional_swms; i++)
1112                 wimlib_free(additional_swms[i]);
1113         free(additional_swms);
1114 out_globfree:
1115         globfree(&globbuf);
1116 out:
1117         return ret;
1118 }
1119
1120
1121 static unsigned
1122 parse_num_threads(const tchar *optarg)
1123 {
1124         tchar *tmp;
1125         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1126         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1127                 imagex_error(T("Number of threads must be a non-negative integer!"));
1128                 return UINT_MAX;
1129         } else {
1130                 return ul_nthreads;
1131         }
1132 }
1133
1134
1135 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1136  * one image from a WIM file to a NTFS volume. */
1137 static int
1138 imagex_apply(int argc, tchar **argv)
1139 {
1140         int c;
1141         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1142         int image;
1143         int num_images;
1144         WIMStruct *w;
1145         int ret;
1146         const tchar *wimfile;
1147         const tchar *target;
1148         const tchar *image_num_or_name;
1149         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1150
1151         const tchar *swm_glob = NULL;
1152         WIMStruct **additional_swms = NULL;
1153         unsigned num_additional_swms = 0;
1154
1155         for_opt(c, apply_options) {
1156                 switch (c) {
1157                 case IMAGEX_CHECK_OPTION:
1158                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1159                         break;
1160                 case IMAGEX_HARDLINK_OPTION:
1161                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1162                         break;
1163                 case IMAGEX_SYMLINK_OPTION:
1164                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1165                         break;
1166                 case IMAGEX_VERBOSE_OPTION:
1167                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1168                         break;
1169                 case IMAGEX_REF_OPTION:
1170                         swm_glob = optarg;
1171                         break;
1172                 case IMAGEX_UNIX_DATA_OPTION:
1173                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1174                         break;
1175                 case IMAGEX_NO_ACLS_OPTION:
1176                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1177                         break;
1178                 case IMAGEX_STRICT_ACLS_OPTION:
1179                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1180                         break;
1181                 default:
1182                         usage(APPLY);
1183                         return -1;
1184                 }
1185         }
1186         argc -= optind;
1187         argv += optind;
1188         if (argc != 2 && argc != 3) {
1189                 usage(APPLY);
1190                 return -1;
1191         }
1192
1193         wimfile = argv[0];
1194         if (argc == 2) {
1195                 image_num_or_name = T("1");
1196                 target = argv[1];
1197         } else {
1198                 image_num_or_name = argv[1];
1199                 target = argv[2];
1200         }
1201
1202         ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1203         if (ret != 0)
1204                 return ret;
1205
1206         image = wimlib_resolve_image(w, image_num_or_name);
1207         ret = verify_image_exists(image, image_num_or_name, wimfile);
1208         if (ret != 0)
1209                 goto out;
1210
1211         num_images = wimlib_get_num_images(w);
1212         if (argc == 2 && num_images != 1) {
1213                 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1214                                "(or all)"), wimfile, num_images);
1215                 usage(APPLY);
1216                 ret = -1;
1217                 goto out;
1218         }
1219
1220         if (swm_glob) {
1221                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1222                                           &additional_swms,
1223                                           &num_additional_swms);
1224                 if (ret != 0)
1225                         goto out;
1226         }
1227
1228         struct stat stbuf;
1229
1230         ret = tstat(target, &stbuf);
1231         if (ret == 0) {
1232                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1233                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1234         } else {
1235                 if (errno != ENOENT) {
1236                         imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1237                                                 target);
1238                         ret = -1;
1239                         goto out;
1240                 }
1241         }
1242
1243 #ifdef __WIN32__
1244         win32_acquire_restore_privileges();
1245 #endif
1246         ret = wimlib_extract_image(w, image, target, extract_flags,
1247                                    additional_swms, num_additional_swms,
1248                                    imagex_progress_func);
1249         if (ret == 0)
1250                 tprintf(T("Done applying WIM image.\n"));
1251 #ifdef __WIN32__
1252         win32_release_restore_privileges();
1253 #endif
1254 out:
1255         wimlib_free(w);
1256         if (additional_swms) {
1257                 for (unsigned i = 0; i < num_additional_swms; i++)
1258                         wimlib_free(additional_swms[i]);
1259                 free(additional_swms);
1260         }
1261         return ret;
1262 }
1263
1264 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1265  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1266  * the desired image.  'wimlib-imagex append': add a new image to an existing
1267  * WIM file. */
1268 static int
1269 imagex_capture_or_append(int argc, tchar **argv)
1270 {
1271         int c;
1272         int open_flags = 0;
1273         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
1274         int write_flags = 0;
1275         int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1276         const tchar *wimfile;
1277         const tchar *name;
1278         const tchar *desc;
1279         const tchar *flags_element = NULL;
1280         WIMStruct *w;
1281         int ret;
1282         int cur_image;
1283         int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1284         unsigned num_threads = 0;
1285
1286         tchar *source;
1287         size_t source_name_len;
1288         tchar *source_copy;
1289
1290         const tchar *config_file = NULL;
1291         tchar *config_str;
1292         struct wimlib_capture_config *config = NULL;
1293
1294         bool source_list = false;
1295         size_t source_list_nchars;
1296         tchar *source_list_contents;
1297         bool capture_sources_malloced;
1298         struct wimlib_capture_source *capture_sources;
1299         size_t num_sources;
1300
1301         for_opt(c, capture_or_append_options) {
1302                 switch (c) {
1303                 case IMAGEX_BOOT_OPTION:
1304                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1305                         break;
1306                 case IMAGEX_CHECK_OPTION:
1307                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1308                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1309                         break;
1310                 case IMAGEX_CONFIG_OPTION:
1311                         config_file = optarg;
1312                         break;
1313                 case IMAGEX_COMPRESS_OPTION:
1314                         compression_type = get_compression_type(optarg);
1315                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1316                                 return -1;
1317                         break;
1318                 case IMAGEX_FLAGS_OPTION:
1319                         flags_element = optarg;
1320                         break;
1321                 case IMAGEX_DEREFERENCE_OPTION:
1322                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1323                         break;
1324                 case IMAGEX_VERBOSE_OPTION:
1325                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1326                         break;
1327                 case IMAGEX_THREADS_OPTION:
1328                         num_threads = parse_num_threads(optarg);
1329                         if (num_threads == UINT_MAX)
1330                                 return -1;
1331                         break;
1332                 case IMAGEX_REBULID_OPTION:
1333                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1334                         break;
1335                 case IMAGEX_UNIX_DATA_OPTION:
1336                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1337                         break;
1338                 case IMAGEX_SOURCE_LIST_OPTION:
1339                         source_list = true;
1340                         break;
1341                 case IMAGEX_NO_ACLS_OPTION:
1342                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1343                         break;
1344                 case IMAGEX_STRICT_ACLS_OPTION:
1345                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1346                         break;
1347                 default:
1348                         usage(cmd);
1349                         return -1;
1350                 }
1351         }
1352         argc -= optind;
1353         argv += optind;
1354
1355         if (argc < 2 || argc > 4) {
1356                 usage(cmd);
1357                 return -1;
1358         }
1359
1360         source = argv[0];
1361         wimfile = argv[1];
1362
1363         if (argc >= 3) {
1364                 name = argv[2];
1365         } else {
1366                 /* Set default name to SOURCE argument, omitting any directory
1367                  * prefixes and trailing slashes.  This requires making a copy
1368                  * of @source. */
1369                 source_name_len = tstrlen(source);
1370                 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1371                 name = tbasename(tstrcpy(source_copy, source));
1372         }
1373         /* Image description defaults to NULL if not given. */
1374         desc = (argc >= 4) ? argv[3] : NULL;
1375
1376         if (source_list) {
1377                 /* Set up capture sources in source list mode */
1378                 if (source[0] == T('-') && source[1] == T('\0')) {
1379                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1380                 } else {
1381                         source_list_contents = file_get_text_contents(source,
1382                                                                       &source_list_nchars);
1383                 }
1384                 if (!source_list_contents)
1385                         return -1;
1386
1387                 capture_sources = parse_source_list(&source_list_contents,
1388                                                     source_list_nchars,
1389                                                     &num_sources);
1390                 if (!capture_sources) {
1391                         ret = -1;
1392                         goto out_free_source_list_contents;
1393                 }
1394                 capture_sources_malloced = true;
1395         } else {
1396                 /* Set up capture source in non-source-list mode (could be
1397                  * either "normal" mode or "NTFS mode"--- see the man page). */
1398                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1399                 capture_sources[0].fs_source_path = source;
1400                 capture_sources[0].wim_target_path = NULL;
1401                 capture_sources[0].reserved = 0;
1402                 num_sources = 1;
1403                 capture_sources_malloced = false;
1404                 source_list_contents = NULL;
1405         }
1406
1407         if (config_file) {
1408                 size_t config_len;
1409
1410                 config_str = file_get_text_contents(config_file, &config_len);
1411                 if (!config_str) {
1412                         ret = -1;
1413                         goto out_free_capture_sources;
1414                 }
1415
1416                 config = alloca(sizeof(*config));
1417                 ret = parse_capture_config(&config_str, config_len, config);
1418                 if (ret)
1419                         goto out_free_config;
1420         } else {
1421                 config = &default_capture_config;
1422         }
1423
1424         if (cmd == APPEND)
1425                 ret = wimlib_open_wim(wimfile, open_flags, &w,
1426                                       imagex_progress_func);
1427         else
1428                 ret = wimlib_create_new_wim(compression_type, &w);
1429         if (ret)
1430                 goto out_free_config;
1431
1432         if (!source_list) {
1433                 struct stat stbuf;
1434                 ret = tstat(source, &stbuf);
1435                 if (ret == 0) {
1436                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1437                                 tprintf(T("Capturing WIM image from NTFS "
1438                                           "filesystem on \"%"TS"\"\n"), source);
1439                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1440                         }
1441                 } else {
1442                         if (errno != ENOENT) {
1443                                 imagex_error_with_errno(T("Failed to stat "
1444                                                           "\"%"TS"\""), source);
1445                                 ret = -1;
1446                                 goto out_wimlib_free;
1447                         }
1448                 }
1449         }
1450 #ifdef __WIN32__
1451         win32_acquire_capture_privileges();
1452 #endif
1453
1454         ret = wimlib_add_image_multisource(w,
1455                                            capture_sources,
1456                                            num_sources,
1457                                            name,
1458                                            config,
1459                                            add_image_flags,
1460                                            imagex_progress_func);
1461         if (ret != 0)
1462                 goto out_release_privs;
1463         cur_image = wimlib_get_num_images(w);
1464         if (desc) {
1465                 ret = wimlib_set_image_descripton(w, cur_image, desc);
1466                 if (ret != 0)
1467                         goto out_release_privs;
1468         }
1469         if (flags_element) {
1470                 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1471                 if (ret != 0)
1472                         goto out_release_privs;
1473         }
1474         if (cmd == APPEND) {
1475                 ret = wimlib_overwrite(w, write_flags, num_threads,
1476                                        imagex_progress_func);
1477         } else {
1478                 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1479                                    num_threads, imagex_progress_func);
1480         }
1481         if (ret == WIMLIB_ERR_REOPEN)
1482                 ret = 0;
1483         if (ret != 0)
1484                 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1485                              wimfile);
1486 out_release_privs:
1487 #ifdef __WIN32__
1488         win32_release_capture_privileges();
1489 #endif
1490 out_wimlib_free:
1491         wimlib_free(w);
1492 out_free_config:
1493         if (config != NULL && config != &default_capture_config) {
1494                 free(config->exclusion_pats.pats);
1495                 free(config->exclusion_exception_pats.pats);
1496                 free(config_str);
1497         }
1498 out_free_capture_sources:
1499         if (capture_sources_malloced)
1500                 free(capture_sources);
1501 out_free_source_list_contents:
1502         free(source_list_contents);
1503         return ret;
1504 }
1505
1506 /* Remove image(s) from a WIM. */
1507 static int
1508 imagex_delete(int argc, tchar **argv)
1509 {
1510         int c;
1511         int open_flags = 0;
1512         int write_flags = 0;
1513         const tchar *wimfile;
1514         const tchar *image_num_or_name;
1515         WIMStruct *w;
1516         int image;
1517         int ret;
1518
1519         for_opt(c, delete_options) {
1520                 switch (c) {
1521                 case IMAGEX_CHECK_OPTION:
1522                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1523                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1524                         break;
1525                 case IMAGEX_SOFT_OPTION:
1526                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1527                         break;
1528                 default:
1529                         usage(DELETE);
1530                         return -1;
1531                 }
1532         }
1533         argc -= optind;
1534         argv += optind;
1535
1536         if (argc != 2) {
1537                 if (argc < 1)
1538                         imagex_error(T("Must specify a WIM file"));
1539                 if (argc < 2)
1540                         imagex_error(T("Must specify an image"));
1541                 usage(DELETE);
1542                 return -1;
1543         }
1544         wimfile = argv[0];
1545         image_num_or_name = argv[1];
1546
1547         ret = file_writable(wimfile);
1548         if (ret != 0)
1549                 return ret;
1550
1551         ret = wimlib_open_wim(wimfile, open_flags, &w,
1552                               imagex_progress_func);
1553         if (ret != 0)
1554                 return ret;
1555
1556         image = wimlib_resolve_image(w, image_num_or_name);
1557
1558         ret = verify_image_exists(image, image_num_or_name, wimfile);
1559         if (ret != 0)
1560                 goto out;
1561
1562         ret = wimlib_delete_image(w, image);
1563         if (ret != 0) {
1564                 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1565                 goto out;
1566         }
1567
1568         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1569         if (ret == WIMLIB_ERR_REOPEN)
1570                 ret = 0;
1571         if (ret != 0) {
1572                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1573                                "deleted"), wimfile);
1574         }
1575 out:
1576         wimlib_free(w);
1577         return ret;
1578 }
1579
1580 /* Print the files contained in an image(s) in a WIM file. */
1581 static int
1582 imagex_dir(int argc, tchar **argv)
1583 {
1584         const tchar *wimfile;
1585         WIMStruct *w;
1586         int image;
1587         int ret;
1588         int num_images;
1589
1590         if (argc < 2) {
1591                 imagex_error(T("Must specify a WIM file"));
1592                 usage(DIR);
1593                 return -1;
1594         }
1595         if (argc > 3) {
1596                 imagex_error(T("Too many arguments"));
1597                 usage(DIR);
1598                 return -1;
1599         }
1600
1601         wimfile = argv[1];
1602         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1603                               imagex_progress_func);
1604         if (ret != 0)
1605                 return ret;
1606
1607         if (argc == 3) {
1608                 image = wimlib_resolve_image(w, argv[2]);
1609                 ret = verify_image_exists(image, argv[2], wimfile);
1610                 if (ret != 0)
1611                         goto out;
1612         } else {
1613                 /* Image was not specified.  If the WIM only contains one image,
1614                  * choose that one; otherwise, print an error. */
1615                 num_images = wimlib_get_num_images(w);
1616                 if (num_images != 1) {
1617                         imagex_error(T("The file \"%"TS"\" contains %d images; Please "
1618                                        "select one."), wimfile, num_images);
1619                         usage(DIR);
1620                         ret = -1;
1621                         goto out;
1622                 }
1623                 image = 1;
1624         }
1625
1626         ret = wimlib_print_files(w, image);
1627 out:
1628         wimlib_free(w);
1629         return ret;
1630 }
1631
1632 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1633  * WIM file. */
1634 static int
1635 imagex_export(int argc, tchar **argv)
1636 {
1637         int c;
1638         int open_flags = 0;
1639         int export_flags = 0;
1640         int write_flags = 0;
1641         int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1642         bool compression_type_specified = false;
1643         const tchar *src_wimfile;
1644         const tchar *src_image_num_or_name;
1645         const tchar *dest_wimfile;
1646         const tchar *dest_name;
1647         const tchar *dest_desc;
1648         WIMStruct *src_w = NULL;
1649         WIMStruct *dest_w = NULL;
1650         int ret;
1651         int image;
1652         struct stat stbuf;
1653         bool wim_is_new;
1654         const tchar *swm_glob = NULL;
1655         WIMStruct **additional_swms = NULL;
1656         unsigned num_additional_swms = 0;
1657         unsigned num_threads = 0;
1658
1659         for_opt(c, export_options) {
1660                 switch (c) {
1661                 case IMAGEX_BOOT_OPTION:
1662                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
1663                         break;
1664                 case IMAGEX_CHECK_OPTION:
1665                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1666                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1667                         break;
1668                 case IMAGEX_COMPRESS_OPTION:
1669                         compression_type = get_compression_type(optarg);
1670                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1671                                 return -1;
1672                         compression_type_specified = true;
1673                         break;
1674                 case IMAGEX_REF_OPTION:
1675                         swm_glob = optarg;
1676                         break;
1677                 case IMAGEX_THREADS_OPTION:
1678                         num_threads = parse_num_threads(optarg);
1679                         if (num_threads == UINT_MAX)
1680                                 return -1;
1681                         break;
1682                 case IMAGEX_REBULID_OPTION:
1683                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1684                         break;
1685                 default:
1686                         usage(EXPORT);
1687                         return -1;
1688                 }
1689         }
1690         argc -= optind;
1691         argv += optind;
1692         if (argc < 3 || argc > 5) {
1693                 usage(EXPORT);
1694                 return -1;
1695         }
1696         src_wimfile           = argv[0];
1697         src_image_num_or_name = argv[1];
1698         dest_wimfile          = argv[2];
1699         dest_name             = (argc >= 4) ? argv[3] : NULL;
1700         dest_desc             = (argc >= 5) ? argv[4] : NULL;
1701         ret = wimlib_open_wim(src_wimfile,
1702                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
1703                               imagex_progress_func);
1704         if (ret != 0)
1705                 return ret;
1706
1707         /* Determine if the destination is an existing file or not.
1708          * If so, we try to append the exported image(s) to it; otherwise, we
1709          * create a new WIM containing the exported image(s). */
1710         if (tstat(dest_wimfile, &stbuf) == 0) {
1711                 int dest_ctype;
1712
1713                 wim_is_new = false;
1714                 /* Destination file exists. */
1715
1716                 if (!S_ISREG(stbuf.st_mode)) {
1717                         imagex_error(T("\"%"TS"\" is not a regular file"),
1718                                      dest_wimfile);
1719                         ret = -1;
1720                         goto out;
1721                 }
1722                 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1723                                       imagex_progress_func);
1724                 if (ret != 0)
1725                         goto out;
1726
1727                 ret = file_writable(dest_wimfile);
1728                 if (ret != 0)
1729                         goto out;
1730
1731                 dest_ctype = wimlib_get_compression_type(dest_w);
1732                 if (compression_type_specified
1733                     && compression_type != dest_ctype)
1734                 {
1735                         imagex_error(T("Cannot specify a compression type that is "
1736                                        "not the same as that used in the "
1737                                        "destination WIM"));
1738                         ret = -1;
1739                         goto out;
1740                 }
1741         } else {
1742                 wim_is_new = true;
1743                 /* dest_wimfile is not an existing file, so create a new WIM. */
1744                 if (!compression_type_specified)
1745                         compression_type = wimlib_get_compression_type(src_w);
1746                 if (errno == ENOENT) {
1747                         ret = wimlib_create_new_wim(compression_type, &dest_w);
1748                         if (ret != 0)
1749                                 goto out;
1750                 } else {
1751                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
1752                                                 dest_wimfile);
1753                         ret = -1;
1754                         goto out;
1755                 }
1756         }
1757
1758         image = wimlib_resolve_image(src_w, src_image_num_or_name);
1759         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1760         if (ret != 0)
1761                 goto out;
1762
1763         if (swm_glob) {
1764                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1765                                           &additional_swms,
1766                                           &num_additional_swms);
1767                 if (ret != 0)
1768                         goto out;
1769         }
1770
1771         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1772                                   export_flags, additional_swms,
1773                                   num_additional_swms, imagex_progress_func);
1774         if (ret != 0)
1775                 goto out;
1776
1777
1778         if (wim_is_new)
1779                 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1780                                    write_flags, num_threads,
1781                                    imagex_progress_func);
1782         else
1783                 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1784                                        imagex_progress_func);
1785 out:
1786         if (ret == WIMLIB_ERR_REOPEN)
1787                 ret = 0;
1788         wimlib_free(src_w);
1789         wimlib_free(dest_w);
1790         if (additional_swms) {
1791                 for (unsigned i = 0; i < num_additional_swms; i++)
1792                         wimlib_free(additional_swms[i]);
1793                 free(additional_swms);
1794         }
1795         return ret;
1796 }
1797
1798 /* Prints information about a WIM file; also can mark an image as bootable,
1799  * change the name of an image, or change the description of an image. */
1800 static int
1801 imagex_info(int argc, tchar **argv)
1802 {
1803         int c;
1804         bool boot         = false;
1805         bool check        = false;
1806         bool header       = false;
1807         bool lookup_table = false;
1808         bool xml          = false;
1809         bool metadata     = false;
1810         bool short_header = true;
1811         const tchar *xml_out_file = NULL;
1812         const tchar *wimfile;
1813         const tchar *image_num_or_name = T("all");
1814         const tchar *new_name = NULL;
1815         const tchar *new_desc = NULL;
1816         WIMStruct *w;
1817         FILE *fp;
1818         int image;
1819         int ret;
1820         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1821         int part_number;
1822         int total_parts;
1823         int num_images;
1824
1825         for_opt(c, info_options) {
1826                 switch (c) {
1827                 case IMAGEX_BOOT_OPTION:
1828                         boot = true;
1829                         break;
1830                 case IMAGEX_CHECK_OPTION:
1831                         check = true;
1832                         break;
1833                 case IMAGEX_HEADER_OPTION:
1834                         header = true;
1835                         short_header = false;
1836                         break;
1837                 case IMAGEX_LOOKUP_TABLE_OPTION:
1838                         lookup_table = true;
1839                         short_header = false;
1840                         break;
1841                 case IMAGEX_XML_OPTION:
1842                         xml = true;
1843                         short_header = false;
1844                         break;
1845                 case IMAGEX_EXTRACT_XML_OPTION:
1846                         xml_out_file = optarg;
1847                         short_header = false;
1848                         break;
1849                 case IMAGEX_METADATA_OPTION:
1850                         metadata = true;
1851                         short_header = false;
1852                         break;
1853                 default:
1854                         usage(INFO);
1855                         return -1;
1856                 }
1857         }
1858
1859         argc -= optind;
1860         argv += optind;
1861         if (argc == 0 || argc > 4) {
1862                 usage(INFO);
1863                 return -1;
1864         }
1865         wimfile = argv[0];
1866         if (argc > 1) {
1867                 image_num_or_name = argv[1];
1868                 if (argc > 2) {
1869                         new_name = argv[2];
1870                         if (argc > 3) {
1871                                 new_desc = argv[3];
1872                         }
1873                 }
1874         }
1875
1876         if (check)
1877                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1878
1879         ret = wimlib_open_wim(wimfile, open_flags, &w,
1880                               imagex_progress_func);
1881         if (ret != 0)
1882                 return ret;
1883
1884         part_number = wimlib_get_part_number(w, &total_parts);
1885
1886         image = wimlib_resolve_image(w, image_num_or_name);
1887         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
1888                 imagex_error(T("The image \"%"TS"\" does not exist"),
1889                              image_num_or_name);
1890                 if (boot) {
1891                         imagex_error(T("If you would like to set the boot "
1892                                        "index to 0, specify image \"0\" with "
1893                                        "the --boot flag."));
1894                 }
1895                 ret = WIMLIB_ERR_INVALID_IMAGE;
1896                 goto out;
1897         }
1898
1899         num_images = wimlib_get_num_images(w);
1900
1901         if (num_images == 0) {
1902                 if (boot) {
1903                         imagex_error(T("--boot is meaningless on a WIM with no "
1904                                        "images"));
1905                         ret = WIMLIB_ERR_INVALID_IMAGE;
1906                         goto out;
1907                 }
1908         }
1909
1910         if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1911                 if (boot) {
1912                         imagex_error(T("Cannot specify the --boot flag "
1913                                        "without specifying a specific "
1914                                        "image in a multi-image WIM"));
1915                         ret = WIMLIB_ERR_INVALID_IMAGE;
1916                         goto out;
1917                 }
1918                 if (new_name) {
1919                         imagex_error(T("Cannot specify the NEW_NAME "
1920                                        "without specifying a specific "
1921                                        "image in a multi-image WIM"));
1922                         ret = WIMLIB_ERR_INVALID_IMAGE;
1923                         goto out;
1924                 }
1925         }
1926
1927         /* Operations that print information are separated from operations that
1928          * recreate the WIM file. */
1929         if (!new_name && !boot) {
1930
1931                 /* Read-only operations */
1932
1933                 if (image == WIMLIB_NO_IMAGE) {
1934                         imagex_error(T("\"%"TS"\" is not a valid image"),
1935                                      image_num_or_name);
1936                         ret = WIMLIB_ERR_INVALID_IMAGE;
1937                         goto out;
1938                 }
1939
1940                 if (image == WIMLIB_ALL_IMAGES && short_header)
1941                         wimlib_print_wim_information(w);
1942
1943                 if (header)
1944                         wimlib_print_header(w);
1945
1946                 if (lookup_table) {
1947                         if (total_parts != 1) {
1948                                 tprintf(T("Warning: Only showing the lookup table "
1949                                           "for part %d of a %d-part WIM.\n"),
1950                                         part_number, total_parts);
1951                         }
1952                         wimlib_print_lookup_table(w);
1953                 }
1954
1955                 if (xml) {
1956                         ret = wimlib_extract_xml_data(w, stdout);
1957                         if (ret != 0)
1958                                 goto out;
1959                 }
1960
1961                 if (xml_out_file) {
1962                         fp = tfopen(xml_out_file, T("wb"));
1963                         if (!fp) {
1964                                 imagex_error_with_errno(T("Failed to open the "
1965                                                           "file \"%"TS"\" for "
1966                                                           "writing "),
1967                                                         xml_out_file);
1968                                 ret = -1;
1969                                 goto out;
1970                         }
1971                         ret = wimlib_extract_xml_data(w, fp);
1972                         if (fclose(fp) != 0) {
1973                                 imagex_error(T("Failed to close the file "
1974                                                "\"%"TS"\""),
1975                                              xml_out_file);
1976                                 ret = -1;
1977                         }
1978
1979                         if (ret != 0)
1980                                 goto out;
1981                 }
1982
1983                 if (short_header)
1984                         wimlib_print_available_images(w, image);
1985
1986                 if (metadata) {
1987                         ret = wimlib_print_metadata(w, image);
1988                         if (ret != 0)
1989                                 goto out;
1990                 }
1991         } else {
1992
1993                 /* Modification operations */
1994                 if (total_parts != 1) {
1995                         imagex_error(T("Modifying a split WIM is not supported."));
1996                         ret = -1;
1997                         goto out;
1998                 }
1999                 if (image == WIMLIB_ALL_IMAGES)
2000                         image = 1;
2001
2002                 if (image == WIMLIB_NO_IMAGE && new_name) {
2003                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2004                                        "when using image 0"), new_name);
2005                         ret = -1;
2006                         goto out;
2007                 }
2008
2009                 if (boot) {
2010                         if (image == wimlib_get_boot_idx(w)) {
2011                                 tprintf(T("Image %d is already marked as "
2012                                           "bootable.\n"), image);
2013                                 boot = false;
2014                         } else {
2015                                 tprintf(T("Marking image %d as bootable.\n"),
2016                                         image);
2017                                 wimlib_set_boot_idx(w, image);
2018                         }
2019                 }
2020                 if (new_name) {
2021                         if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
2022                         {
2023                                 tprintf(T("Image %d is already named \"%"TS"\".\n"),
2024                                         image, new_name);
2025                                 new_name = NULL;
2026                         } else {
2027                                 tprintf(T("Changing the name of image %d to "
2028                                           "\"%"TS"\".\n"), image, new_name);
2029                                 ret = wimlib_set_image_name(w, image, new_name);
2030                                 if (ret != 0)
2031                                         goto out;
2032                         }
2033                 }
2034                 if (new_desc) {
2035                         const tchar *old_desc;
2036                         old_desc = wimlib_get_image_description(w, image);
2037                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
2038                                 tprintf(T("The description of image %d is already "
2039                                           "\"%"TS"\".\n"), image, new_desc);
2040                                 new_desc = NULL;
2041                         } else {
2042                                 tprintf(T("Changing the description of image %d "
2043                                           "to \"%"TS"\".\n"), image, new_desc);
2044                                 ret = wimlib_set_image_descripton(w, image,
2045                                                                   new_desc);
2046                                 if (ret != 0)
2047                                         goto out;
2048                         }
2049                 }
2050
2051                 /* Only call wimlib_overwrite() if something actually needs to
2052                  * be changed. */
2053                 if (boot || new_name || new_desc ||
2054                     (check && !wimlib_has_integrity_table(w)))
2055                 {
2056                         int write_flags;
2057
2058                         ret = file_writable(wimfile);
2059                         if (ret != 0)
2060                                 return ret;
2061
2062                         if (check)
2063                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2064                         else
2065                                 write_flags = 0;
2066
2067                         ret = wimlib_overwrite(w, write_flags, 1,
2068                                                imagex_progress_func);
2069                         if (ret == WIMLIB_ERR_REOPEN)
2070                                 ret = 0;
2071                 } else {
2072                         tprintf(T("The file \"%"TS"\" was not modified because nothing "
2073                                   "needed to be done.\n"), wimfile);
2074                         ret = 0;
2075                 }
2076         }
2077 out:
2078         wimlib_free(w);
2079         return ret;
2080 }
2081
2082 /* Join split WIMs into one part WIM */
2083 static int
2084 imagex_join(int argc, tchar **argv)
2085 {
2086         int c;
2087         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2088         int wim_write_flags = 0;
2089         const tchar *output_path;
2090
2091         for_opt(c, join_options) {
2092                 switch (c) {
2093                 case IMAGEX_CHECK_OPTION:
2094                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2095                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2096                         break;
2097                 default:
2098                         goto err;
2099                 }
2100         }
2101         argc -= optind;
2102         argv += optind;
2103
2104         if (argc < 2) {
2105                 imagex_error(T("Must specify one or more split WIM (.swm) "
2106                                "parts to join"));
2107                 goto err;
2108         }
2109         output_path = argv[0];
2110         return wimlib_join((const tchar * const *)++argv,
2111                            --argc,
2112                            output_path,
2113                            swm_open_flags,
2114                            wim_write_flags,
2115                            imagex_progress_func);
2116 err:
2117         usage(JOIN);
2118         return -1;
2119 }
2120
2121 /* Mounts an image using a FUSE mount. */
2122 static int
2123 imagex_mount_rw_or_ro(int argc, tchar **argv)
2124 {
2125         int c;
2126         int mount_flags = 0;
2127         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2128         const tchar *wimfile;
2129         const tchar *dir;
2130         WIMStruct *w;
2131         int image;
2132         int num_images;
2133         int ret;
2134         const tchar *swm_glob = NULL;
2135         WIMStruct **additional_swms = NULL;
2136         unsigned num_additional_swms = 0;
2137         const tchar *staging_dir = NULL;
2138
2139         if (!tstrcmp(argv[0], T("mountrw")))
2140                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2141
2142         for_opt(c, mount_options) {
2143                 switch (c) {
2144                 case IMAGEX_ALLOW_OTHER_OPTION:
2145                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2146                         break;
2147                 case IMAGEX_CHECK_OPTION:
2148                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2149                         break;
2150                 case IMAGEX_DEBUG_OPTION:
2151                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2152                         break;
2153                 case IMAGEX_STREAMS_INTERFACE_OPTION:
2154                         if (!tstrcasecmp(optarg, T("none")))
2155                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2156                         else if (!tstrcasecmp(optarg, T("xattr")))
2157                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2158                         else if (!tstrcasecmp(optarg, T("windows")))
2159                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2160                         else {
2161                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
2162                                              optarg);
2163                                 goto mount_usage;
2164                         }
2165                         break;
2166                 case IMAGEX_REF_OPTION:
2167                         swm_glob = optarg;
2168                         break;
2169                 case IMAGEX_STAGING_DIR_OPTION:
2170                         staging_dir = optarg;
2171                         break;
2172                 case IMAGEX_UNIX_DATA_OPTION:
2173                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2174                         break;
2175                 default:
2176                         goto mount_usage;
2177                 }
2178         }
2179         argc -= optind;
2180         argv += optind;
2181         if (argc != 2 && argc != 3)
2182                 goto mount_usage;
2183
2184         wimfile = argv[0];
2185
2186         ret = wimlib_open_wim(wimfile, open_flags, &w,
2187                               imagex_progress_func);
2188         if (ret != 0)
2189                 return ret;
2190
2191         if (swm_glob) {
2192                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2193                                           &additional_swms,
2194                                           &num_additional_swms);
2195                 if (ret != 0)
2196                         goto out;
2197         }
2198
2199         if (argc == 2) {
2200                 image = 1;
2201                 num_images = wimlib_get_num_images(w);
2202                 if (num_images != 1) {
2203                         imagex_error(T("The file \"%"TS"\" contains %d images; Please "
2204                                        "select one."), wimfile, num_images);
2205                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2206                                         ? MOUNTRW : MOUNT);
2207                         ret = -1;
2208                         goto out;
2209                 }
2210                 dir = argv[1];
2211         } else {
2212                 image = wimlib_resolve_image(w, argv[1]);
2213                 dir = argv[2];
2214                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2215                 if (ret != 0)
2216                         goto out;
2217         }
2218
2219         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2220                 ret = file_writable(wimfile);
2221                 if (ret != 0)
2222                         goto out;
2223         }
2224
2225         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2226                                  num_additional_swms, staging_dir);
2227         if (ret != 0) {
2228                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2229                                "on \"%"TS"\""),
2230                              image, wimfile, dir);
2231
2232         }
2233 out:
2234         wimlib_free(w);
2235         if (additional_swms) {
2236                 for (unsigned i = 0; i < num_additional_swms; i++)
2237                         wimlib_free(additional_swms[i]);
2238                 free(additional_swms);
2239         }
2240         return ret;
2241 mount_usage:
2242         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2243                         ? MOUNTRW : MOUNT);
2244         return -1;
2245 }
2246
2247 /* Rebuild a WIM file */
2248 static int
2249 imagex_optimize(int argc, tchar **argv)
2250 {
2251         int c;
2252         int open_flags = 0;
2253         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2254         int ret;
2255         WIMStruct *w;
2256         const tchar *wimfile;
2257         off_t old_size;
2258         off_t new_size;
2259         unsigned num_threads = 0;
2260
2261         for_opt(c, optimize_options) {
2262                 switch (c) {
2263                 case IMAGEX_CHECK_OPTION:
2264                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2265                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2266                         break;
2267                 case IMAGEX_RECOMPRESS_OPTION:
2268                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2269                         break;
2270                 case IMAGEX_THREADS_OPTION:
2271                         num_threads = parse_num_threads(optarg);
2272                         if (num_threads == UINT_MAX)
2273                                 return -1;
2274                         break;
2275                 default:
2276                         usage(OPTIMIZE);
2277                         return -1;
2278                 }
2279         }
2280         argc -= optind;
2281         argv += optind;
2282
2283         if (argc != 1) {
2284                 usage(OPTIMIZE);
2285                 return -1;
2286         }
2287
2288         wimfile = argv[0];
2289
2290         ret = wimlib_open_wim(wimfile, open_flags, &w,
2291                               imagex_progress_func);
2292         if (ret != 0)
2293                 return ret;
2294
2295         old_size = file_get_size(argv[0]);
2296         tprintf(T("\"%"TS"\" original size: "), wimfile);
2297         if (old_size == -1)
2298                 tfputs(T("Unknown\n"), stdout);
2299         else
2300                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2301
2302         ret = wimlib_overwrite(w, write_flags, num_threads,
2303                                imagex_progress_func);
2304
2305         if (ret == 0) {
2306                 new_size = file_get_size(argv[0]);
2307                 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2308                 if (new_size == -1)
2309                         tfputs(T("Unknown\n"), stdout);
2310                 else
2311                         tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2312
2313                 tfputs(T("Space saved: "), stdout);
2314                 if (new_size != -1 && old_size != -1) {
2315                         tprintf(T("%lld KiB\n"),
2316                                ((long long)old_size - (long long)new_size) >> 10);
2317                 } else {
2318                         tfputs(T("Unknown\n"), stdout);
2319                 }
2320         }
2321
2322         wimlib_free(w);
2323         return ret;
2324 }
2325
2326 /* Split a WIM into a spanned set */
2327 static int
2328 imagex_split(int argc, tchar **argv)
2329 {
2330         int c;
2331         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2332         int write_flags = 0;
2333         unsigned long part_size;
2334         tchar *tmp;
2335         int ret;
2336         WIMStruct *w;
2337
2338         for_opt(c, split_options) {
2339                 switch (c) {
2340                 case IMAGEX_CHECK_OPTION:
2341                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2342                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2343                         break;
2344                 default:
2345                         usage(SPLIT);
2346                         return -1;
2347                 }
2348         }
2349         argc -= optind;
2350         argv += optind;
2351
2352         if (argc != 3) {
2353                 usage(SPLIT);
2354                 return -1;
2355         }
2356         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2357         if (tmp == argv[2] || *tmp) {
2358                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2359                 imagex_error(T("The part size must be an integer or "
2360                                "floating-point number of megabytes."));
2361                 return -1;
2362         }
2363         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2364         if (ret != 0)
2365                 return ret;
2366         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2367         wimlib_free(w);
2368         return ret;
2369 }
2370
2371 /* Unmounts a mounted WIM image. */
2372 static int
2373 imagex_unmount(int argc, tchar **argv)
2374 {
2375         int c;
2376         int unmount_flags = 0;
2377         int ret;
2378
2379         for_opt(c, unmount_options) {
2380                 switch (c) {
2381                 case IMAGEX_COMMIT_OPTION:
2382                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2383                         break;
2384                 case IMAGEX_CHECK_OPTION:
2385                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2386                         break;
2387                 case IMAGEX_REBULID_OPTION:
2388                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2389                         break;
2390                 default:
2391                         usage(UNMOUNT);
2392                         return -1;
2393                 }
2394         }
2395         argc -= optind;
2396         argv += optind;
2397         if (argc != 1) {
2398                 usage(UNMOUNT);
2399                 return -1;
2400         }
2401
2402         ret = wimlib_unmount_image(argv[0], unmount_flags,
2403                                    imagex_progress_func);
2404         if (ret != 0)
2405                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2406         return ret;
2407 }
2408
2409 struct imagex_command {
2410         const tchar *name;
2411         int (*func)(int , tchar **);
2412         int cmd;
2413 };
2414
2415
2416 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
2417                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
2418
2419 static const struct imagex_command imagex_commands[] = {
2420         {T("append"),  imagex_capture_or_append, APPEND},
2421         {T("apply"),   imagex_apply,             APPLY},
2422         {T("capture"), imagex_capture_or_append, CAPTURE},
2423         {T("delete"),  imagex_delete,            DELETE},
2424         {T("dir"),     imagex_dir,               DIR},
2425         {T("export"),  imagex_export,            EXPORT},
2426         {T("info"),    imagex_info,              INFO},
2427         {T("join"),    imagex_join,              JOIN},
2428         {T("mount"),   imagex_mount_rw_or_ro,    MOUNT},
2429         {T("mountrw"), imagex_mount_rw_or_ro,    MOUNTRW},
2430         {T("optimize"),imagex_optimize,          OPTIMIZE},
2431         {T("split"),   imagex_split,             SPLIT},
2432         {T("unmount"), imagex_unmount,           UNMOUNT},
2433 };
2434
2435 static void
2436 version()
2437 {
2438         static const tchar *s =
2439         T(
2440 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
2441 "Copyright (C) 2012, 2013 Eric Biggers\n"
2442 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
2443 "This is free software: you are free to change and redistribute it.\n"
2444 "There is NO WARRANTY, to the extent permitted by law.\n"
2445 "\n"
2446 "Report bugs to "PACKAGE_BUGREPORT".\n"
2447         );
2448         tfputs(s, stdout);
2449 }
2450
2451
2452 static void
2453 help_or_version(int argc, tchar **argv)
2454 {
2455         int i;
2456         const tchar *p;
2457         const struct imagex_command *cmd;
2458
2459         for (i = 1; i < argc; i++) {
2460                 p = argv[i];
2461                 if (*p == T('-'))
2462                         p++;
2463                 else
2464                         continue;
2465                 if (*p == T('-'))
2466                         p++;
2467                 if (!tstrcmp(p, T("help"))) {
2468                         for_imagex_command(cmd) {
2469                                 if (!tstrcmp(cmd->name, argv[1])) {
2470                                         usage(cmd->cmd);
2471                                         exit(0);
2472                                 }
2473                         }
2474                         usage_all();
2475                         exit(0);
2476                 }
2477                 if (!tstrcmp(p, T("version"))) {
2478                         version();
2479                         exit(0);
2480                 }
2481         }
2482 }
2483
2484
2485 static void
2486 usage(int cmd_type)
2487 {
2488         const struct imagex_command *cmd;
2489         tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
2490         for_imagex_command(cmd) {
2491                 if (cmd->cmd == cmd_type) {
2492                         tprintf(T("\nTry `man "IMAGEX_PROGNAME"-%"TS"' "
2493                                   "for more details.\n"), cmd->name);
2494                 }
2495         }
2496 }
2497
2498 static void
2499 usage_all()
2500 {
2501         tfputs(T("Usage:\n"), stdout);
2502         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
2503                 tprintf(T("    %"TS), usage_strings[i]);
2504         static const tchar *extra =
2505         T(
2506 "    "IMAGEX_PROGNAME" --help\n"
2507 "    "IMAGEX_PROGNAME" --version\n"
2508 "\n"
2509 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
2510 "\n"
2511 "    Try `man "IMAGEX_PROGNAME"' for more information.\n"
2512         );
2513         tfputs(extra, stdout);
2514 }
2515
2516 /* Entry point for wimlib's ImageX implementation.  On UNIX the command
2517  * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
2518  * something else), while an Windows the command arguments will be UTF-16LE
2519  * encoded 'wchar_t' strings. */
2520 int
2521 #ifdef __WIN32__
2522 wmain(int argc, wchar_t **argv, wchar_t **envp)
2523 #else
2524 main(int argc, char **argv)
2525 #endif
2526 {
2527         const struct imagex_command *cmd;
2528         int ret;
2529
2530 #ifndef __WIN32__
2531         setlocale(LC_ALL, "");
2532         {
2533                 char *codeset = nl_langinfo(CODESET);
2534                 if (!strstr(codeset, "UTF-8") &&
2535                     !strstr(codeset, "UTF8") &&
2536                     !strstr(codeset, "utf-8") &&
2537                     !strstr(codeset, "utf8"))
2538                 {
2539                         fputs(
2540 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
2541 "         (Maybe try: `export LANG=en_US.UTF-8'?\n", stderr);
2542
2543                 }
2544         }
2545 #endif /* !__WIN32__ */
2546
2547         if (argc < 2) {
2548                 imagex_error(T("No command specified"));
2549                 usage_all();
2550                 ret = 2;
2551                 goto out;
2552         }
2553
2554         /* Handle --help and --version for all commands.  Note that this will
2555          * not return if either of these arguments are present. */
2556         help_or_version(argc, argv);
2557         argc--;
2558         argv++;
2559
2560         /* The user may like to see more informative error messages. */
2561         wimlib_set_print_errors(true);
2562
2563         /* Do any initializations that the library needs */
2564         ret = wimlib_global_init();
2565         if (ret)
2566                 goto out_check_status;
2567
2568         /* Search for the function to handle the ImageX subcommand. */
2569         for_imagex_command(cmd) {
2570                 if (!tstrcmp(cmd->name, *argv)) {
2571                         ret = cmd->func(argc, argv);
2572                         goto out_check_write_error;
2573                 }
2574         }
2575
2576         imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
2577         usage_all();
2578         ret = 2;
2579         goto out_cleanup;
2580 out_check_write_error:
2581         /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
2582          * standard output is part of the program's actual behavior and not just
2583          * for informational purposes, so we should set a failure exit status if
2584          * there was a write error. */
2585         if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
2586                 if (ferror(stdout) || fclose(stdout)) {
2587                         imagex_error_with_errno(T("error writing to standard output"));
2588                         if (ret == 0)
2589                                 ret = -1;
2590                 }
2591         }
2592 out_check_status:
2593         /* Exit status (ret):  -1 indicates an error found by 'wimlib-imagex'
2594          * outside of the wimlib library code.  0 indicates success.  > 0
2595          * indicates a wimlib error code from which an error message can be
2596          * printed. */
2597         if (ret > 0) {
2598                 imagex_error(T("Exiting with error code %d:\n"
2599                                "       %"TS"."), ret,
2600                              wimlib_get_error_string(ret));
2601                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
2602                         imagex_error_with_errno(T("errno"));
2603         }
2604 out_cleanup:
2605         /* Make the library free any resources it's holding (not strictly
2606          * necessary because the process is ending anyway). */
2607         wimlib_global_cleanup();
2608 out:
2609         return ret;
2610 }