4 * Use wimlib to create, modify, extract, mount, unmount, or display information
9 * Copyright (C) 2012, 2013 Eric Biggers
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.
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.
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/>.
27 #include "wimlib_tchar.h"
47 # include "imagex-win32.h"
48 # define tbasename win32_wbasename
49 # define tglob win32_wglob
53 # include <langinfo.h>
54 # define tbasename basename
59 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
61 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
80 static void usage(int cmd_type);
81 static void usage_all();
84 static const tchar *usage_strings[] = {
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 " [--rpfix] [--norpfix]\n"
96 IMAGEX_PROGNAME" apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all]\n"
97 " (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
98 " [--symlink] [--verbose] [--ref=\"GLOB\"] [--unix-data]\n"
99 " [--no-acls] [--strict-acls] [--rpfix] [--norpfix]\n"
103 IMAGEX_PROGNAME" capture (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
104 " [DESCRIPTION] [--boot] [--check] [--compress=TYPE]\n"
105 " [--flags EDITION_ID] [--verbose] [--dereference]\n"
106 " [--config=FILE] [--threads=NUM_THREADS] [--unix-data]\n"
107 " [--source-list] [--no-acls] [--strict-acls]\n"
108 " [--rpfix] [--norpfix]\n"
112 IMAGEX_PROGNAME" delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n"
116 IMAGEX_PROGNAME" dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n"
120 IMAGEX_PROGNAME" export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
121 " DEST_WIMFILE [DEST_IMAGE_NAME] [DEST_IMAGE_DESCRIPTION]\n"
122 " [--boot] [--check] [--compress=TYPE] [--ref=\"GLOB\"]\n"
123 " [--threads=NUM_THREADS] [--rebuild]\n"
127 IMAGEX_PROGNAME" info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
128 " [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
129 " [--xml] [--extract-xml FILE] [--metadata]\n"
133 IMAGEX_PROGNAME" join [--check] WIMFILE SPLIT_WIM...\n"
137 IMAGEX_PROGNAME" mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
138 " [--check] [--debug] [--streams-interface=INTERFACE]\n"
139 " [--ref=\"GLOB\"] [--unix-data] [--allow-other]\n"
143 IMAGEX_PROGNAME" mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
144 " [--check] [--debug] [--streams-interface=INTERFACE]\n"
145 " [--staging-dir=DIR] [--unix-data] [--allow-other]\n"
149 IMAGEX_PROGNAME" optimize WIMFILE [--check] [--recompress]\n"
150 " [--threads=NUM_THREADS]\n"
154 IMAGEX_PROGNAME" split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n"
158 IMAGEX_PROGNAME" unmount DIRECTORY [--commit] [--check] [--rebuild]\n"
163 IMAGEX_ALLOW_OTHER_OPTION,
166 IMAGEX_COMMIT_OPTION,
167 IMAGEX_COMPRESS_OPTION,
168 IMAGEX_CONFIG_OPTION,
170 IMAGEX_DEREFERENCE_OPTION,
171 IMAGEX_EXTRACT_XML_OPTION,
173 IMAGEX_HARDLINK_OPTION,
174 IMAGEX_HEADER_OPTION,
175 IMAGEX_LOOKUP_TABLE_OPTION,
176 IMAGEX_METADATA_OPTION,
177 IMAGEX_NO_ACLS_OPTION,
178 IMAGEX_NORPFIX_OPTION,
179 IMAGEX_REBULID_OPTION,
180 IMAGEX_RECOMPRESS_OPTION,
184 IMAGEX_SOURCE_LIST_OPTION,
185 IMAGEX_STAGING_DIR_OPTION,
186 IMAGEX_STREAMS_INTERFACE_OPTION,
187 IMAGEX_STRICT_ACLS_OPTION,
188 IMAGEX_SYMLINK_OPTION,
189 IMAGEX_THREADS_OPTION,
190 IMAGEX_UNIX_DATA_OPTION,
191 IMAGEX_VERBOSE_OPTION,
195 static const struct option apply_options[] = {
196 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
197 {T("hardlink"), no_argument, NULL, IMAGEX_HARDLINK_OPTION},
198 {T("symlink"), no_argument, NULL, IMAGEX_SYMLINK_OPTION},
199 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
200 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
201 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
202 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
203 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
204 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
205 {T("rpfix"), no_argument, NULL, IMAGEX_RPFIX_OPTION},
206 {T("norpfix"), no_argument, NULL, IMAGEX_NORPFIX_OPTION},
209 static const struct option capture_or_append_options[] = {
210 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
211 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
212 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
213 {T("config"), required_argument, NULL, IMAGEX_CONFIG_OPTION},
214 {T("dereference"), no_argument, NULL, IMAGEX_DEREFERENCE_OPTION},
215 {T("flags"), required_argument, NULL, IMAGEX_FLAGS_OPTION},
216 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
217 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
218 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
219 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
220 {T("source-list"), no_argument, NULL, IMAGEX_SOURCE_LIST_OPTION},
221 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
222 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
223 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
224 {T("rpfix"), no_argument, NULL, IMAGEX_RPFIX_OPTION},
225 {T("norpfix"), no_argument, NULL, IMAGEX_NORPFIX_OPTION},
228 static const struct option delete_options[] = {
229 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
230 {T("soft"), no_argument, NULL, IMAGEX_SOFT_OPTION},
234 static const struct option export_options[] = {
235 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
236 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
237 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
238 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
239 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
240 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
244 static const struct option info_options[] = {
245 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
246 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
247 {T("extract-xml"), required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
248 {T("header"), no_argument, NULL, IMAGEX_HEADER_OPTION},
249 {T("lookup-table"), no_argument, NULL, IMAGEX_LOOKUP_TABLE_OPTION},
250 {T("metadata"), no_argument, NULL, IMAGEX_METADATA_OPTION},
251 {T("xml"), no_argument, NULL, IMAGEX_XML_OPTION},
255 static const struct option join_options[] = {
256 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
260 static const struct option mount_options[] = {
261 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
262 {T("debug"), no_argument, NULL, IMAGEX_DEBUG_OPTION},
263 {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
264 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
265 {T("staging-dir"), required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
266 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
267 {T("allow-other"), no_argument, NULL, IMAGEX_ALLOW_OTHER_OPTION},
271 static const struct option optimize_options[] = {
272 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
273 {T("recompress"), no_argument, NULL, IMAGEX_RECOMPRESS_OPTION},
274 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
278 static const struct option split_options[] = {
279 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
283 static const struct option unmount_options[] = {
284 {T("commit"), no_argument, NULL, IMAGEX_COMMIT_OPTION},
285 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
286 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
292 /* Print formatted error message to stderr. */
294 imagex_error(const tchar *format, ...)
297 va_start(va, format);
298 tfputs(T("ERROR: "), stderr);
299 tvfprintf(stderr, format, va);
300 tputc(T('\n'), stderr);
304 /* Print formatted error message to stderr. */
306 imagex_error_with_errno(const tchar *format, ...)
308 int errno_save = errno;
310 va_start(va, format);
311 tfputs(T("ERROR: "), stderr);
312 tvfprintf(stderr, format, va);
313 tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
318 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
320 if (image == WIMLIB_NO_IMAGE) {
321 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
322 " Please specify a 1-based image index or "
324 " You may use `"IMAGEX_PROGNAME" info' to list the images "
325 "contained in a WIM."),
326 image_name, wim_name);
333 verify_image_is_single(int image)
335 if (image == WIMLIB_ALL_IMAGES) {
336 imagex_error(T("Cannot specify all images for this action!"));
343 verify_image_exists_and_is_single(int image, const tchar *image_name,
344 const tchar *wim_name)
347 ret = verify_image_exists(image, image_name, wim_name);
349 ret = verify_image_is_single(image);
353 /* Parse the argument to --compress */
355 get_compression_type(const tchar *optarg)
357 if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
358 return WIMLIB_COMPRESSION_TYPE_LZX;
359 else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
360 return WIMLIB_COMPRESSION_TYPE_XPRESS;
361 else if (!tstrcasecmp(optarg, T("none")))
362 return WIMLIB_COMPRESSION_TYPE_NONE;
364 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
365 "\"maximum\", \"fast\", or \"none\"."), optarg);
366 return WIMLIB_COMPRESSION_TYPE_INVALID;
370 /* Returns the size of a file given its name, or -1 if the file does not exist
371 * or its size cannot be determined. */
373 file_get_size(const tchar *filename)
376 if (tstat(filename, &st) == 0)
382 tchar pat_ntfs_log[] = T("/$ntfs.log");
383 tchar pat_hiberfil_sys[] = T("/hiberfil.sys");
384 tchar pat_pagefile_sys[] = T("/pagefile.sys");
385 tchar pat_system_volume_information[] = T("/System Volume Information");
386 tchar pat_recycler[] = T("/RECYCLER");
387 tchar pat_windows_csc[] = T("/Windows/CSC");
389 tchar *default_pats[] = {
393 pat_system_volume_information,
398 static struct wimlib_capture_config default_capture_config = {
400 .num_pats = sizeof(default_pats) / sizeof(*default_pats),
401 .pats = default_pats,
406 PARSE_FILENAME_SUCCESS = 0,
407 PARSE_FILENAME_FAILURE = 1,
408 PARSE_FILENAME_NONE = 2,
412 * Parses a filename in the source list file format. (See the man page for
413 * 'wimlib-imagex capture' for details on this format and the meaning.)
414 * Accepted formats for filenames are an unquoted string (whitespace-delimited),
415 * or a double or single-quoted string.
417 * @line_p: Pointer to the pointer to the line of data. Will be updated
418 * to point past the filename iff the return value is
419 * PARSE_FILENAME_SUCCESS. If *len_p > 0, (*line_p)[*len_p - 1] must
422 * @len_p: @len_p initially stores the length of the line of data, which may
423 * be 0, and it will be updated to the number of bytes remaining in
424 * the line iff the return value is PARSE_FILENAME_SUCCESS.
426 * @fn_ret: Iff the return value is PARSE_FILENAME_SUCCESS, a pointer to the
427 * parsed filename will be returned here.
429 * Returns: PARSE_FILENAME_SUCCESS if a filename was successfully parsed; or
430 * PARSE_FILENAME_FAILURE if the data was invalid due to a missing
431 * closing quote; or PARSE_FILENAME_NONE if the line ended before the
432 * beginning of a filename was found.
435 parse_filename(tchar **line_p, size_t *len_p, tchar **fn_ret)
438 tchar *line = *line_p;
442 /* Skip leading whitespace */
445 return PARSE_FILENAME_NONE;
446 if (!istspace(*line) && *line != T('\0'))
452 if (quote_char == T('"') || quote_char == T('\'')) {
453 /* Quoted filename */
457 line = tmemchr(line, quote_char, len);
459 imagex_error(T("Missing closing quote: %"TS), fn - 1);
460 return PARSE_FILENAME_FAILURE;
463 /* Unquoted filename. Go until whitespace. Line is terminated
464 * by '\0', so no need to check 'len'. */
468 } while (!istspace(*line) && *line != T('\0'));
475 return PARSE_FILENAME_SUCCESS;
478 /* Parses a line of data (not an empty line or comment) in the source list file
479 * format. (See the man page for 'wimlib-imagex capture' for details on this
480 * format and the meaning.)
482 * @line: Line of data to be parsed. line[len - 1] must be '\0', unless
483 * len == 0. The data in @line will be modified by this function call.
485 * @len: Length of the line of data.
487 * @source: On success, the capture source and target described by the line is
488 * written into this destination. Note that it will contain pointers
489 * to data in the @line array.
491 * Returns true if the line was valid; false otherwise. */
493 parse_source_list_line(tchar *line, size_t len,
494 struct wimlib_capture_source *source)
498 ret = parse_filename(&line, &len, &source->fs_source_path);
499 if (ret != PARSE_FILENAME_SUCCESS)
501 ret = parse_filename(&line, &len, &source->wim_target_path);
502 if (ret == PARSE_FILENAME_NONE)
503 source->wim_target_path = source->fs_source_path;
504 return ret != PARSE_FILENAME_FAILURE;
507 /* Returns %true if the given line of length @len > 0 is a comment or empty line
508 * in the source list file format. */
510 is_comment_line(const tchar *line, size_t len)
515 if (!istspace(*line) && *line != T('\0'))
525 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
528 tchar *contents = *contents_p;
529 size_t nchars = *nchars_p;
532 for (i = 0; i < nchars; i++)
533 if (contents[i] == T('\n'))
536 /* Handle last line not terminated by a newline */
537 if (nchars != 0 && contents[nchars - 1] != T('\n')) {
538 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
540 imagex_error(T("Out of memory!"));
543 contents[nchars] = T('\n');
544 *contents_p = contents;
552 /* Parses a file in the source list format. (See the man page for
553 * 'wimlib-imagex capture' for details on this format and the meaning.)
555 * @source_list_contents: Contents of the source list file. Note that this
556 * buffer will be modified to save memory allocations,
557 * and cannot be freed until the returned array of
558 * wimlib_capture_source's has also been freed.
560 * @source_list_nbytes: Number of bytes of data in the @source_list_contents
563 * @nsources_ret: On success, the length of the returned array is
566 * Returns: An array of `struct wimlib_capture_source's that can be passed to
567 * the wimlib_add_image_multisource() function to specify how a WIM image is to
569 static struct wimlib_capture_source *
570 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
571 size_t *nsources_ret)
575 struct wimlib_capture_source *sources;
578 nlines = text_file_count_lines(source_list_contents_p,
579 &source_list_nchars);
583 /* Always allocate at least 1 slot, just in case the implementation of
584 * calloc() returns NULL if 0 bytes are requested. */
585 sources = calloc(nlines ?: 1, sizeof(*sources));
587 imagex_error(T("out of memory"));
590 p = *source_list_contents_p;
592 for (i = 0; i < nlines; i++) {
593 /* XXX: Could use rawmemchr() here instead, but it may not be
594 * available on all platforms. */
595 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
596 size_t len = endp - p + 1;
598 if (!is_comment_line(p, len)) {
599 if (!parse_source_list_line(p, len, &sources[j++])) {
612 enum capture_config_section {
613 CAPTURE_CONFIG_NO_SECTION,
614 CAPTURE_CONFIG_EXCLUSION_SECTION,
615 CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
616 CAPTURE_CONFIG_IGNORE_SECTION,
620 CAPTURE_CONFIG_INVALID_SECTION,
621 CAPTURE_CONFIG_CHANGED_SECTION,
622 CAPTURE_CONFIG_SAME_SECTION,
626 check_config_section(tchar *line, size_t len,
627 enum capture_config_section *cur_section)
629 while (istspace(*line))
633 return CAPTURE_CONFIG_SAME_SECTION;
636 tchar *endbrace = tstrrchr(line, T(']'));
638 return CAPTURE_CONFIG_SAME_SECTION;
640 if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
641 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
642 } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
643 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
644 } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
645 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
646 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
647 "of capture config file\n"),
649 } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
650 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
651 tfputs(T("WARNING: Ignoring [AlignmentList] section "
652 "of capture config file\n"),
655 imagex_error(T("Invalid capture config file section \"%"TS"\""),
657 return CAPTURE_CONFIG_INVALID_SECTION;
659 return CAPTURE_CONFIG_CHANGED_SECTION;
664 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
667 if (pat_list->num_pats == pat_list->num_allocated_pats) {
669 size_t num_allocated_pats = pat_list->num_pats + 8;
671 pats = realloc(pat_list->pats,
672 num_allocated_pats * sizeof(pat_list->pats[0]));
674 imagex_error(T("Out of memory!"));
677 pat_list->pats = pats;
678 pat_list->num_allocated_pats = num_allocated_pats;
680 pat_list->pats[pat_list->num_pats++] = pat;
685 parse_capture_config_line(tchar *line, size_t len,
686 enum capture_config_section *cur_section,
687 struct wimlib_capture_config *config)
692 ret = check_config_section(line, len, cur_section);
693 if (ret == CAPTURE_CONFIG_INVALID_SECTION)
695 if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
698 switch (*cur_section) {
699 case CAPTURE_CONFIG_NO_SECTION:
700 imagex_error(T("Line \"%"TS"\" is not in a section "
701 "(such as [ExclusionList]"), line);
703 case CAPTURE_CONFIG_EXCLUSION_SECTION:
704 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
706 return pattern_list_add_pattern(&config->exclusion_pats,
708 case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
709 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
711 return pattern_list_add_pattern(&config->exclusion_exception_pats,
713 case CAPTURE_CONFIG_IGNORE_SECTION:
720 parse_capture_config(tchar **contents_p, size_t nchars,
721 struct wimlib_capture_config *config)
726 enum capture_config_section cur_section;
728 memset(config, 0, sizeof(*config));
730 nlines = text_file_count_lines(contents_p, &nchars);
734 cur_section = CAPTURE_CONFIG_NO_SECTION;
736 for (i = 0; i < nlines; i++) {
737 tchar *endp = tmemchr(p, T('\n'), nchars);
738 size_t len = endp - p + 1;
740 if (!is_comment_line(p, len))
741 if (!parse_capture_config_line(p, len, &cur_section, config))
749 /* Reads the contents of a file into memory. */
751 file_get_contents(const tchar *filename, size_t *len_ret)
758 if (tstat(filename, &stbuf) != 0) {
759 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
764 fp = tfopen(filename, T("rb"));
766 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
772 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
773 "contents of file \"%"TS"\""), len, filename);
776 if (fread(buf, 1, len, fp) != len) {
777 imagex_error_with_errno(T("Failed to read %zu bytes from the "
778 "file \"%"TS"\""), len, filename);
792 /* Read standard input until EOF and return the full contents in a malloc()ed
793 * buffer and the number of bytes of data in @len_ret. Returns NULL on read
796 stdin_get_contents(size_t *len_ret)
798 /* stdin can, of course, be a pipe or other non-seekable file, so the
799 * total length of the data cannot be pre-determined */
801 size_t newlen = 1024;
805 char *p = realloc(buf, newlen);
806 size_t bytes_read, bytes_to_read;
808 imagex_error(T("out of memory while reading stdin"));
812 bytes_to_read = newlen - pos;
813 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
815 if (bytes_read != bytes_to_read) {
820 imagex_error_with_errno(T("error reading stdin"));
834 translate_text_to_tstr(char *text, size_t num_bytes,
835 size_t *num_tchars_ret)
838 /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
840 *num_tchars_ret = num_bytes;
842 #else /* !__WIN32__ */
843 /* On Windows, translate the text to UTF-16LE */
847 if (num_bytes >= 2 &&
848 ((text[0] == 0xff && text[1] == 0xfe) ||
849 (text[0] <= 0x7f && text[1] == 0x00)))
851 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
852 * with something that looks like an ASCII character encoded as
853 * a UTF-16LE code unit. Assume the file is encoded as
854 * UTF-16LE. This is not a 100% reliable check. */
855 num_wchars = num_bytes / 2;
856 text_wstr = (wchar_t*)text;
858 /* File does not look like UTF-16LE. Assume it is encoded in
859 * the current Windows code page. I think these are always
860 * ASCII-compatible, so any so-called "plain-text" (ASCII) files
861 * should work as expected. */
862 text_wstr = win32_mbs_to_wcs(text,
867 *num_tchars_ret = num_wchars;
869 #endif /* __WIN32__ */
873 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
878 contents = file_get_contents(filename, &num_bytes);
881 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
885 stdin_get_text_contents(size_t *num_tchars_ret)
890 contents = stdin_get_contents(&num_bytes);
893 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
896 /* Return 0 if a path names a file to which the current user has write access;
897 * -1 otherwise (and print an error message). */
899 file_writable(const tchar *path)
902 ret = taccess(path, W_OK);
904 imagex_error_with_errno(T("Can't modify \"%"TS"\""), path);
908 #define TO_PERCENT(numerator, denominator) \
909 (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
911 /* Given an enumerated value for WIM compression type, return a descriptive
914 get_data_type(int ctype)
917 case WIMLIB_COMPRESSION_TYPE_NONE:
918 return T("uncompressed");
919 case WIMLIB_COMPRESSION_TYPE_LZX:
920 return T("LZX-compressed");
921 case WIMLIB_COMPRESSION_TYPE_XPRESS:
922 return T("XPRESS-compressed");
927 /* Progress callback function passed to various wimlib functions. */
929 imagex_progress_func(enum wimlib_progress_msg msg,
930 const union wimlib_progress_info *info)
932 unsigned percent_done;
934 case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
935 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
936 info->write_streams.total_bytes);
937 if (info->write_streams.completed_streams == 0) {
938 const tchar *data_type;
940 data_type = get_data_type(info->write_streams.compression_type);
941 tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
942 data_type, info->write_streams.num_threads,
943 (info->write_streams.num_threads == 1) ? T("") : T("s"));
945 tprintf(T("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
946 "written (%u%% done)"),
947 info->write_streams.completed_bytes >> 20,
948 info->write_streams.total_bytes >> 20,
950 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
953 case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
954 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
955 if (*info->scan.wim_target_path) {
956 tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
957 info->scan.wim_target_path);
959 tprintf(T(" (loading as root of WIM image)...\n"));
962 case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
963 if (info->scan.excluded)
964 tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
966 tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
968 /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
970 case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
971 percent_done = TO_PERCENT(info->integrity.completed_bytes,
972 info->integrity.total_bytes);
973 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" MiB "
974 "of %"PRIu64" MiB (%u%%) done"),
975 info->integrity.filename,
976 info->integrity.completed_bytes >> 20,
977 info->integrity.total_bytes >> 20,
979 if (info->integrity.completed_bytes == info->integrity.total_bytes)
982 case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
983 percent_done = TO_PERCENT(info->integrity.completed_bytes,
984 info->integrity.total_bytes);
985 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" MiB "
986 "of %"PRIu64" MiB (%u%%) done"),
987 info->integrity.completed_bytes >> 20,
988 info->integrity.total_bytes >> 20,
990 if (info->integrity.completed_bytes == info->integrity.total_bytes)
993 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
994 tprintf(T("Applying image %d (%"TS") from \"%"TS"\" "
995 "to %"TS" \"%"TS"\"\n"),
997 info->extract.image_name,
998 info->extract.wimfile_name,
999 ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
1000 T("NTFS volume") : T("directory")),
1001 info->extract.target);
1003 /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
1004 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
1005 /*info->extract.target);*/
1007 case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1008 percent_done = TO_PERCENT(info->extract.completed_bytes,
1009 info->extract.total_bytes);
1010 tprintf(T("\rExtracting files: "
1011 "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done"),
1012 info->extract.completed_bytes >> 20,
1013 info->extract.total_bytes >> 20,
1015 if (info->extract.completed_bytes >= info->extract.total_bytes)
1018 case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
1019 tprintf(T("%"TS"\n"), info->extract.cur_path);
1021 case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1022 tprintf(T("Setting timestamps on all extracted files...\n"));
1024 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1025 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1026 tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1027 info->extract.target);
1030 case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
1031 percent_done = TO_PERCENT(info->join.completed_bytes,
1032 info->join.total_bytes);
1033 tprintf(T("Writing resources from part %u of %u: "
1034 "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n"),
1035 (info->join.completed_parts == info->join.total_parts) ?
1036 info->join.completed_parts : info->join.completed_parts + 1,
1037 info->join.total_parts,
1038 info->join.completed_bytes >> 20,
1039 info->join.total_bytes >> 20,
1042 case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1043 percent_done = TO_PERCENT(info->split.completed_bytes,
1044 info->split.total_bytes);
1045 tprintf(T("Writing \"%"TS"\": %"PRIu64" MiB of "
1046 "%"PRIu64" MiB (%u%%) written\n"),
1047 info->split.part_name,
1048 info->split.completed_bytes >> 20,
1049 info->split.total_bytes >> 20,
1052 case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1053 if (info->split.completed_bytes == info->split.total_bytes) {
1054 tprintf(T("Finished writing %u split WIM parts\n"),
1055 info->split.cur_part_number);
1065 /* Open all the split WIM parts that correspond to a file glob.
1067 * @first_part specifies the first part of the split WIM and it may be either
1068 * included or omitted from the glob. */
1070 open_swms_from_glob(const tchar *swm_glob,
1071 const tchar *first_part,
1073 WIMStruct ***additional_swms_ret,
1074 unsigned *num_additional_swms_ret)
1076 unsigned num_additional_swms = 0;
1077 WIMStruct **additional_swms = NULL;
1081 /* Warning: glob() is replaced in Windows native builds */
1082 ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1084 if (ret == GLOB_NOMATCH) {
1085 imagex_error(T("Found no files for glob \"%"TS"\""),
1088 imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1094 num_additional_swms = globbuf.gl_pathc;
1095 additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1096 if (!additional_swms) {
1097 imagex_error(T("Out of memory"));
1101 unsigned offset = 0;
1102 for (unsigned i = 0; i < num_additional_swms; i++) {
1103 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1107 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1108 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1109 &additional_swms[i - offset],
1110 imagex_progress_func);
1112 goto out_close_swms;
1114 *additional_swms_ret = additional_swms;
1115 *num_additional_swms_ret = num_additional_swms - offset;
1119 for (unsigned i = 0; i < num_additional_swms; i++)
1120 wimlib_free(additional_swms[i]);
1121 free(additional_swms);
1130 parse_num_threads(const tchar *optarg)
1133 unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1134 if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1135 imagex_error(T("Number of threads must be a non-negative integer!"));
1143 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1144 * one image from a WIM file to a NTFS volume. */
1146 imagex_apply(int argc, tchar **argv)
1149 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1154 const tchar *wimfile;
1155 const tchar *target;
1156 const tchar *image_num_or_name;
1157 int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1159 const tchar *swm_glob = NULL;
1160 WIMStruct **additional_swms = NULL;
1161 unsigned num_additional_swms = 0;
1163 for_opt(c, apply_options) {
1165 case IMAGEX_CHECK_OPTION:
1166 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1168 case IMAGEX_HARDLINK_OPTION:
1169 extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1171 case IMAGEX_SYMLINK_OPTION:
1172 extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1174 case IMAGEX_VERBOSE_OPTION:
1175 extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1177 case IMAGEX_REF_OPTION:
1180 case IMAGEX_UNIX_DATA_OPTION:
1181 extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1183 case IMAGEX_NO_ACLS_OPTION:
1184 extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1186 case IMAGEX_STRICT_ACLS_OPTION:
1187 extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1189 case IMAGEX_NORPFIX_OPTION:
1190 extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1192 case IMAGEX_RPFIX_OPTION:
1193 extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1202 if (argc != 2 && argc != 3) {
1209 image_num_or_name = T("1");
1212 image_num_or_name = argv[1];
1216 ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1220 image = wimlib_resolve_image(w, image_num_or_name);
1221 ret = verify_image_exists(image, image_num_or_name, wimfile);
1225 num_images = wimlib_get_num_images(w);
1226 if (argc == 2 && num_images != 1) {
1227 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1228 "(or all)"), wimfile, num_images);
1235 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1237 &num_additional_swms);
1244 ret = tstat(target, &stbuf);
1246 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1247 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1249 if (errno != ENOENT) {
1250 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1258 win32_acquire_restore_privileges();
1260 ret = wimlib_extract_image(w, image, target, extract_flags,
1261 additional_swms, num_additional_swms,
1262 imagex_progress_func);
1264 tprintf(T("Done applying WIM image.\n"));
1266 win32_release_restore_privileges();
1270 if (additional_swms) {
1271 for (unsigned i = 0; i < num_additional_swms; i++)
1272 wimlib_free(additional_swms[i]);
1273 free(additional_swms);
1278 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1279 * directory trees. 'wimlib-imagex capture': create a new WIM file containing
1280 * the desired image. 'wimlib-imagex append': add a new image to an existing
1283 imagex_capture_or_append(int argc, tchar **argv)
1287 int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
1288 int write_flags = 0;
1289 int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1290 const tchar *wimfile;
1293 const tchar *flags_element = NULL;
1297 int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1298 unsigned num_threads = 0;
1301 size_t source_name_len;
1304 const tchar *config_file = NULL;
1306 struct wimlib_capture_config *config = NULL;
1308 bool source_list = false;
1309 size_t source_list_nchars;
1310 tchar *source_list_contents;
1311 bool capture_sources_malloced;
1312 struct wimlib_capture_source *capture_sources;
1315 for_opt(c, capture_or_append_options) {
1317 case IMAGEX_BOOT_OPTION:
1318 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1320 case IMAGEX_CHECK_OPTION:
1321 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1322 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1324 case IMAGEX_CONFIG_OPTION:
1325 config_file = optarg;
1327 case IMAGEX_COMPRESS_OPTION:
1328 compression_type = get_compression_type(optarg);
1329 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1332 case IMAGEX_FLAGS_OPTION:
1333 flags_element = optarg;
1335 case IMAGEX_DEREFERENCE_OPTION:
1336 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1338 case IMAGEX_VERBOSE_OPTION:
1339 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1341 case IMAGEX_THREADS_OPTION:
1342 num_threads = parse_num_threads(optarg);
1343 if (num_threads == UINT_MAX)
1346 case IMAGEX_REBULID_OPTION:
1347 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1349 case IMAGEX_UNIX_DATA_OPTION:
1350 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1352 case IMAGEX_SOURCE_LIST_OPTION:
1355 case IMAGEX_NO_ACLS_OPTION:
1356 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1358 case IMAGEX_STRICT_ACLS_OPTION:
1359 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1361 case IMAGEX_RPFIX_OPTION:
1362 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1364 case IMAGEX_NORPFIX_OPTION:
1365 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1375 if (argc < 2 || argc > 4) {
1386 /* Set default name to SOURCE argument, omitting any directory
1387 * prefixes and trailing slashes. This requires making a copy
1389 source_name_len = tstrlen(source);
1390 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1391 name = tbasename(tstrcpy(source_copy, source));
1393 /* Image description defaults to NULL if not given. */
1394 desc = (argc >= 4) ? argv[3] : NULL;
1397 /* Set up capture sources in source list mode */
1398 if (source[0] == T('-') && source[1] == T('\0')) {
1399 source_list_contents = stdin_get_text_contents(&source_list_nchars);
1401 source_list_contents = file_get_text_contents(source,
1402 &source_list_nchars);
1404 if (!source_list_contents)
1407 capture_sources = parse_source_list(&source_list_contents,
1410 if (!capture_sources) {
1412 goto out_free_source_list_contents;
1414 capture_sources_malloced = true;
1416 /* Set up capture source in non-source-list mode (could be
1417 * either "normal" mode or "NTFS mode"--- see the man page). */
1418 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1419 capture_sources[0].fs_source_path = source;
1420 capture_sources[0].wim_target_path = NULL;
1421 capture_sources[0].reserved = 0;
1423 capture_sources_malloced = false;
1424 source_list_contents = NULL;
1430 config_str = file_get_text_contents(config_file, &config_len);
1433 goto out_free_capture_sources;
1436 config = alloca(sizeof(*config));
1437 ret = parse_capture_config(&config_str, config_len, config);
1439 goto out_free_config;
1441 config = &default_capture_config;
1445 ret = wimlib_open_wim(wimfile, open_flags, &w,
1446 imagex_progress_func);
1448 ret = wimlib_create_new_wim(compression_type, &w);
1450 goto out_free_config;
1454 ret = tstat(source, &stbuf);
1456 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1457 tprintf(T("Capturing WIM image from NTFS "
1458 "filesystem on \"%"TS"\"\n"), source);
1459 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1462 if (errno != ENOENT) {
1463 imagex_error_with_errno(T("Failed to stat "
1464 "\"%"TS"\""), source);
1466 goto out_wimlib_free;
1471 win32_acquire_capture_privileges();
1474 ret = wimlib_add_image_multisource(w,
1480 imagex_progress_func);
1482 goto out_release_privs;
1483 cur_image = wimlib_get_num_images(w);
1485 ret = wimlib_set_image_descripton(w, cur_image, desc);
1487 goto out_release_privs;
1489 if (flags_element) {
1490 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1492 goto out_release_privs;
1494 if (cmd == APPEND) {
1495 ret = wimlib_overwrite(w, write_flags, num_threads,
1496 imagex_progress_func);
1498 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1499 num_threads, imagex_progress_func);
1501 if (ret == WIMLIB_ERR_REOPEN)
1504 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1508 win32_release_capture_privileges();
1513 if (config != NULL && config != &default_capture_config) {
1514 free(config->exclusion_pats.pats);
1515 free(config->exclusion_exception_pats.pats);
1518 out_free_capture_sources:
1519 if (capture_sources_malloced)
1520 free(capture_sources);
1521 out_free_source_list_contents:
1522 free(source_list_contents);
1526 /* Remove image(s) from a WIM. */
1528 imagex_delete(int argc, tchar **argv)
1532 int write_flags = 0;
1533 const tchar *wimfile;
1534 const tchar *image_num_or_name;
1539 for_opt(c, delete_options) {
1541 case IMAGEX_CHECK_OPTION:
1542 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1543 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1545 case IMAGEX_SOFT_OPTION:
1546 write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1558 imagex_error(T("Must specify a WIM file"));
1560 imagex_error(T("Must specify an image"));
1565 image_num_or_name = argv[1];
1567 ret = file_writable(wimfile);
1571 ret = wimlib_open_wim(wimfile, open_flags, &w,
1572 imagex_progress_func);
1576 image = wimlib_resolve_image(w, image_num_or_name);
1578 ret = verify_image_exists(image, image_num_or_name, wimfile);
1582 ret = wimlib_delete_image(w, image);
1584 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1588 ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1589 if (ret == WIMLIB_ERR_REOPEN)
1592 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1593 "deleted"), wimfile);
1600 /* Print the files contained in an image(s) in a WIM file. */
1602 imagex_dir(int argc, tchar **argv)
1604 const tchar *wimfile;
1611 imagex_error(T("Must specify a WIM file"));
1616 imagex_error(T("Too many arguments"));
1622 ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1623 imagex_progress_func);
1628 image = wimlib_resolve_image(w, argv[2]);
1629 ret = verify_image_exists(image, argv[2], wimfile);
1633 /* Image was not specified. If the WIM only contains one image,
1634 * choose that one; otherwise, print an error. */
1635 num_images = wimlib_get_num_images(w);
1636 if (num_images != 1) {
1637 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
1638 "select one."), wimfile, num_images);
1646 ret = wimlib_print_files(w, image);
1652 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1655 imagex_export(int argc, tchar **argv)
1659 int export_flags = 0;
1660 int write_flags = 0;
1661 int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1662 bool compression_type_specified = false;
1663 const tchar *src_wimfile;
1664 const tchar *src_image_num_or_name;
1665 const tchar *dest_wimfile;
1666 const tchar *dest_name;
1667 const tchar *dest_desc;
1668 WIMStruct *src_w = NULL;
1669 WIMStruct *dest_w = NULL;
1674 const tchar *swm_glob = NULL;
1675 WIMStruct **additional_swms = NULL;
1676 unsigned num_additional_swms = 0;
1677 unsigned num_threads = 0;
1679 for_opt(c, export_options) {
1681 case IMAGEX_BOOT_OPTION:
1682 export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
1684 case IMAGEX_CHECK_OPTION:
1685 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1686 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1688 case IMAGEX_COMPRESS_OPTION:
1689 compression_type = get_compression_type(optarg);
1690 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1692 compression_type_specified = true;
1694 case IMAGEX_REF_OPTION:
1697 case IMAGEX_THREADS_OPTION:
1698 num_threads = parse_num_threads(optarg);
1699 if (num_threads == UINT_MAX)
1702 case IMAGEX_REBULID_OPTION:
1703 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1712 if (argc < 3 || argc > 5) {
1716 src_wimfile = argv[0];
1717 src_image_num_or_name = argv[1];
1718 dest_wimfile = argv[2];
1719 dest_name = (argc >= 4) ? argv[3] : NULL;
1720 dest_desc = (argc >= 5) ? argv[4] : NULL;
1721 ret = wimlib_open_wim(src_wimfile,
1722 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
1723 imagex_progress_func);
1727 /* Determine if the destination is an existing file or not.
1728 * If so, we try to append the exported image(s) to it; otherwise, we
1729 * create a new WIM containing the exported image(s). */
1730 if (tstat(dest_wimfile, &stbuf) == 0) {
1734 /* Destination file exists. */
1736 if (!S_ISREG(stbuf.st_mode)) {
1737 imagex_error(T("\"%"TS"\" is not a regular file"),
1742 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1743 imagex_progress_func);
1747 ret = file_writable(dest_wimfile);
1751 dest_ctype = wimlib_get_compression_type(dest_w);
1752 if (compression_type_specified
1753 && compression_type != dest_ctype)
1755 imagex_error(T("Cannot specify a compression type that is "
1756 "not the same as that used in the "
1757 "destination WIM"));
1763 /* dest_wimfile is not an existing file, so create a new WIM. */
1764 if (!compression_type_specified)
1765 compression_type = wimlib_get_compression_type(src_w);
1766 if (errno == ENOENT) {
1767 ret = wimlib_create_new_wim(compression_type, &dest_w);
1771 imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
1778 image = wimlib_resolve_image(src_w, src_image_num_or_name);
1779 ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1784 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1786 &num_additional_swms);
1791 ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1792 export_flags, additional_swms,
1793 num_additional_swms, imagex_progress_func);
1799 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1800 write_flags, num_threads,
1801 imagex_progress_func);
1803 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1804 imagex_progress_func);
1806 if (ret == WIMLIB_ERR_REOPEN)
1809 wimlib_free(dest_w);
1810 if (additional_swms) {
1811 for (unsigned i = 0; i < num_additional_swms; i++)
1812 wimlib_free(additional_swms[i]);
1813 free(additional_swms);
1818 /* Prints information about a WIM file; also can mark an image as bootable,
1819 * change the name of an image, or change the description of an image. */
1821 imagex_info(int argc, tchar **argv)
1826 bool header = false;
1827 bool lookup_table = false;
1829 bool metadata = false;
1830 bool short_header = true;
1831 const tchar *xml_out_file = NULL;
1832 const tchar *wimfile;
1833 const tchar *image_num_or_name = T("all");
1834 const tchar *new_name = NULL;
1835 const tchar *new_desc = NULL;
1840 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1845 for_opt(c, info_options) {
1847 case IMAGEX_BOOT_OPTION:
1850 case IMAGEX_CHECK_OPTION:
1853 case IMAGEX_HEADER_OPTION:
1855 short_header = false;
1857 case IMAGEX_LOOKUP_TABLE_OPTION:
1858 lookup_table = true;
1859 short_header = false;
1861 case IMAGEX_XML_OPTION:
1863 short_header = false;
1865 case IMAGEX_EXTRACT_XML_OPTION:
1866 xml_out_file = optarg;
1867 short_header = false;
1869 case IMAGEX_METADATA_OPTION:
1871 short_header = false;
1881 if (argc == 0 || argc > 4) {
1887 image_num_or_name = argv[1];
1897 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1899 ret = wimlib_open_wim(wimfile, open_flags, &w,
1900 imagex_progress_func);
1904 part_number = wimlib_get_part_number(w, &total_parts);
1906 image = wimlib_resolve_image(w, image_num_or_name);
1907 if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
1908 imagex_error(T("The image \"%"TS"\" does not exist"),
1911 imagex_error(T("If you would like to set the boot "
1912 "index to 0, specify image \"0\" with "
1913 "the --boot flag."));
1915 ret = WIMLIB_ERR_INVALID_IMAGE;
1919 num_images = wimlib_get_num_images(w);
1921 if (num_images == 0) {
1923 imagex_error(T("--boot is meaningless on a WIM with no "
1925 ret = WIMLIB_ERR_INVALID_IMAGE;
1930 if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1932 imagex_error(T("Cannot specify the --boot flag "
1933 "without specifying a specific "
1934 "image in a multi-image WIM"));
1935 ret = WIMLIB_ERR_INVALID_IMAGE;
1939 imagex_error(T("Cannot specify the NEW_NAME "
1940 "without specifying a specific "
1941 "image in a multi-image WIM"));
1942 ret = WIMLIB_ERR_INVALID_IMAGE;
1947 /* Operations that print information are separated from operations that
1948 * recreate the WIM file. */
1949 if (!new_name && !boot) {
1951 /* Read-only operations */
1953 if (image == WIMLIB_NO_IMAGE) {
1954 imagex_error(T("\"%"TS"\" is not a valid image"),
1956 ret = WIMLIB_ERR_INVALID_IMAGE;
1960 if (image == WIMLIB_ALL_IMAGES && short_header)
1961 wimlib_print_wim_information(w);
1964 wimlib_print_header(w);
1967 if (total_parts != 1) {
1968 tprintf(T("Warning: Only showing the lookup table "
1969 "for part %d of a %d-part WIM.\n"),
1970 part_number, total_parts);
1972 wimlib_print_lookup_table(w);
1976 ret = wimlib_extract_xml_data(w, stdout);
1982 fp = tfopen(xml_out_file, T("wb"));
1984 imagex_error_with_errno(T("Failed to open the "
1985 "file \"%"TS"\" for "
1991 ret = wimlib_extract_xml_data(w, fp);
1992 if (fclose(fp) != 0) {
1993 imagex_error(T("Failed to close the file "
2004 wimlib_print_available_images(w, image);
2007 ret = wimlib_print_metadata(w, image);
2013 /* Modification operations */
2014 if (total_parts != 1) {
2015 imagex_error(T("Modifying a split WIM is not supported."));
2019 if (image == WIMLIB_ALL_IMAGES)
2022 if (image == WIMLIB_NO_IMAGE && new_name) {
2023 imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2024 "when using image 0"), new_name);
2030 if (image == wimlib_get_boot_idx(w)) {
2031 tprintf(T("Image %d is already marked as "
2032 "bootable.\n"), image);
2035 tprintf(T("Marking image %d as bootable.\n"),
2037 wimlib_set_boot_idx(w, image);
2041 if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
2043 tprintf(T("Image %d is already named \"%"TS"\".\n"),
2047 tprintf(T("Changing the name of image %d to "
2048 "\"%"TS"\".\n"), image, new_name);
2049 ret = wimlib_set_image_name(w, image, new_name);
2055 const tchar *old_desc;
2056 old_desc = wimlib_get_image_description(w, image);
2057 if (old_desc && !tstrcmp(old_desc, new_desc)) {
2058 tprintf(T("The description of image %d is already "
2059 "\"%"TS"\".\n"), image, new_desc);
2062 tprintf(T("Changing the description of image %d "
2063 "to \"%"TS"\".\n"), image, new_desc);
2064 ret = wimlib_set_image_descripton(w, image,
2071 /* Only call wimlib_overwrite() if something actually needs to
2073 if (boot || new_name || new_desc ||
2074 (check && !wimlib_has_integrity_table(w)))
2078 ret = file_writable(wimfile);
2083 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2087 ret = wimlib_overwrite(w, write_flags, 1,
2088 imagex_progress_func);
2089 if (ret == WIMLIB_ERR_REOPEN)
2092 tprintf(T("The file \"%"TS"\" was not modified because nothing "
2093 "needed to be done.\n"), wimfile);
2102 /* Join split WIMs into one part WIM */
2104 imagex_join(int argc, tchar **argv)
2107 int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2108 int wim_write_flags = 0;
2109 const tchar *output_path;
2111 for_opt(c, join_options) {
2113 case IMAGEX_CHECK_OPTION:
2114 swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2115 wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2125 imagex_error(T("Must specify one or more split WIM (.swm) "
2129 output_path = argv[0];
2130 return wimlib_join((const tchar * const *)++argv,
2135 imagex_progress_func);
2141 /* Mounts an image using a FUSE mount. */
2143 imagex_mount_rw_or_ro(int argc, tchar **argv)
2146 int mount_flags = 0;
2147 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2148 const tchar *wimfile;
2154 const tchar *swm_glob = NULL;
2155 WIMStruct **additional_swms = NULL;
2156 unsigned num_additional_swms = 0;
2157 const tchar *staging_dir = NULL;
2159 if (!tstrcmp(argv[0], T("mountrw")))
2160 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2162 for_opt(c, mount_options) {
2164 case IMAGEX_ALLOW_OTHER_OPTION:
2165 mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2167 case IMAGEX_CHECK_OPTION:
2168 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2170 case IMAGEX_DEBUG_OPTION:
2171 mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2173 case IMAGEX_STREAMS_INTERFACE_OPTION:
2174 if (!tstrcasecmp(optarg, T("none")))
2175 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2176 else if (!tstrcasecmp(optarg, T("xattr")))
2177 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2178 else if (!tstrcasecmp(optarg, T("windows")))
2179 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2181 imagex_error(T("Unknown stream interface \"%"TS"\""),
2186 case IMAGEX_REF_OPTION:
2189 case IMAGEX_STAGING_DIR_OPTION:
2190 staging_dir = optarg;
2192 case IMAGEX_UNIX_DATA_OPTION:
2193 mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2201 if (argc != 2 && argc != 3)
2206 ret = wimlib_open_wim(wimfile, open_flags, &w,
2207 imagex_progress_func);
2212 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2214 &num_additional_swms);
2221 num_images = wimlib_get_num_images(w);
2222 if (num_images != 1) {
2223 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
2224 "select one."), wimfile, num_images);
2225 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2232 image = wimlib_resolve_image(w, argv[1]);
2234 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2239 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2240 ret = file_writable(wimfile);
2245 ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2246 num_additional_swms, staging_dir);
2248 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2250 image, wimfile, dir);
2255 if (additional_swms) {
2256 for (unsigned i = 0; i < num_additional_swms; i++)
2257 wimlib_free(additional_swms[i]);
2258 free(additional_swms);
2262 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2267 /* Rebuild a WIM file */
2269 imagex_optimize(int argc, tchar **argv)
2273 int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2276 const tchar *wimfile;
2279 unsigned num_threads = 0;
2281 for_opt(c, optimize_options) {
2283 case IMAGEX_CHECK_OPTION:
2284 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2285 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2287 case IMAGEX_RECOMPRESS_OPTION:
2288 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2290 case IMAGEX_THREADS_OPTION:
2291 num_threads = parse_num_threads(optarg);
2292 if (num_threads == UINT_MAX)
2310 ret = wimlib_open_wim(wimfile, open_flags, &w,
2311 imagex_progress_func);
2315 old_size = file_get_size(argv[0]);
2316 tprintf(T("\"%"TS"\" original size: "), wimfile);
2318 tfputs(T("Unknown\n"), stdout);
2320 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2322 ret = wimlib_overwrite(w, write_flags, num_threads,
2323 imagex_progress_func);
2326 new_size = file_get_size(argv[0]);
2327 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2329 tfputs(T("Unknown\n"), stdout);
2331 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2333 tfputs(T("Space saved: "), stdout);
2334 if (new_size != -1 && old_size != -1) {
2335 tprintf(T("%lld KiB\n"),
2336 ((long long)old_size - (long long)new_size) >> 10);
2338 tfputs(T("Unknown\n"), stdout);
2346 /* Split a WIM into a spanned set */
2348 imagex_split(int argc, tchar **argv)
2351 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2352 int write_flags = 0;
2353 unsigned long part_size;
2358 for_opt(c, split_options) {
2360 case IMAGEX_CHECK_OPTION:
2361 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2362 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2376 part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2377 if (tmp == argv[2] || *tmp) {
2378 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2379 imagex_error(T("The part size must be an integer or "
2380 "floating-point number of megabytes."));
2383 ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2386 ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2391 /* Unmounts a mounted WIM image. */
2393 imagex_unmount(int argc, tchar **argv)
2396 int unmount_flags = 0;
2399 for_opt(c, unmount_options) {
2401 case IMAGEX_COMMIT_OPTION:
2402 unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2404 case IMAGEX_CHECK_OPTION:
2405 unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2407 case IMAGEX_REBULID_OPTION:
2408 unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2422 ret = wimlib_unmount_image(argv[0], unmount_flags,
2423 imagex_progress_func);
2425 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2429 struct imagex_command {
2431 int (*func)(int , tchar **);
2436 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
2437 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
2439 static const struct imagex_command imagex_commands[] = {
2440 {T("append"), imagex_capture_or_append, APPEND},
2441 {T("apply"), imagex_apply, APPLY},
2442 {T("capture"), imagex_capture_or_append, CAPTURE},
2443 {T("delete"), imagex_delete, DELETE},
2444 {T("dir"), imagex_dir, DIR},
2445 {T("export"), imagex_export, EXPORT},
2446 {T("info"), imagex_info, INFO},
2447 {T("join"), imagex_join, JOIN},
2448 {T("mount"), imagex_mount_rw_or_ro, MOUNT},
2449 {T("mountrw"), imagex_mount_rw_or_ro, MOUNTRW},
2450 {T("optimize"),imagex_optimize, OPTIMIZE},
2451 {T("split"), imagex_split, SPLIT},
2452 {T("unmount"), imagex_unmount, UNMOUNT},
2458 static const tchar *s =
2460 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
2461 "Copyright (C) 2012, 2013 Eric Biggers\n"
2462 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
2463 "This is free software: you are free to change and redistribute it.\n"
2464 "There is NO WARRANTY, to the extent permitted by law.\n"
2466 "Report bugs to "PACKAGE_BUGREPORT".\n"
2473 help_or_version(int argc, tchar **argv)
2477 const struct imagex_command *cmd;
2479 for (i = 1; i < argc; i++) {
2487 if (!tstrcmp(p, T("help"))) {
2488 for_imagex_command(cmd) {
2489 if (!tstrcmp(cmd->name, argv[1])) {
2497 if (!tstrcmp(p, T("version"))) {
2508 const struct imagex_command *cmd;
2509 tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
2510 for_imagex_command(cmd) {
2511 if (cmd->cmd == cmd_type) {
2512 tprintf(T("\nTry `man "IMAGEX_PROGNAME"-%"TS"' "
2513 "for more details.\n"), cmd->name);
2521 tfputs(T("Usage:\n"), stdout);
2522 for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
2523 tprintf(T(" %"TS), usage_strings[i]);
2524 static const tchar *extra =
2526 " "IMAGEX_PROGNAME" --help\n"
2527 " "IMAGEX_PROGNAME" --version\n"
2529 " The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
2531 " Try `man "IMAGEX_PROGNAME"' for more information.\n"
2533 tfputs(extra, stdout);
2536 /* Entry point for wimlib's ImageX implementation. On UNIX the command
2537 * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
2538 * something else), while an Windows the command arguments will be UTF-16LE
2539 * encoded 'wchar_t' strings. */
2542 wmain(int argc, wchar_t **argv, wchar_t **envp)
2544 main(int argc, char **argv)
2547 const struct imagex_command *cmd;
2552 if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
2553 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
2557 setlocale(LC_ALL, "");
2558 codeset = nl_langinfo(CODESET);
2559 if (!strstr(codeset, "UTF-8") &&
2560 !strstr(codeset, "UTF8") &&
2561 !strstr(codeset, "utf-8") &&
2562 !strstr(codeset, "utf8"))
2565 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
2566 " Maybe try: `export LANG=en_US.UTF-8'?\n"
2567 " Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
2568 " to any value to force wimlib to use UTF-8.\n",
2573 #endif /* !__WIN32__ */
2576 imagex_error(T("No command specified"));
2582 /* Handle --help and --version for all commands. Note that this will
2583 * not return if either of these arguments are present. */
2584 help_or_version(argc, argv);
2588 /* The user may like to see more informative error messages. */
2589 wimlib_set_print_errors(true);
2591 /* Do any initializations that the library needs */
2592 ret = wimlib_global_init(init_flags);
2594 goto out_check_status;
2596 /* Search for the function to handle the ImageX subcommand. */
2597 for_imagex_command(cmd) {
2598 if (!tstrcmp(cmd->name, *argv)) {
2599 ret = cmd->func(argc, argv);
2600 goto out_check_write_error;
2604 imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
2608 out_check_write_error:
2609 /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
2610 * standard output is part of the program's actual behavior and not just
2611 * for informational purposes, so we should set a failure exit status if
2612 * there was a write error. */
2613 if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
2614 if (ferror(stdout) || fclose(stdout)) {
2615 imagex_error_with_errno(T("error writing to standard output"));
2621 /* Exit status (ret): -1 indicates an error found by 'wimlib-imagex'
2622 * outside of the wimlib library code. 0 indicates success. > 0
2623 * indicates a wimlib error code from which an error message can be
2626 imagex_error(T("Exiting with error code %d:\n"
2628 wimlib_get_error_string(ret));
2629 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
2630 imagex_error_with_errno(T("errno"));
2633 /* Make the library free any resources it's holding (not strictly
2634 * necessary because the process is ending anyway). */
2635 wimlib_global_cleanup();