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