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"
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"
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"
110 IMAGEX_PROGNAME" delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n"
114 IMAGEX_PROGNAME" dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n"
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"
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"
131 IMAGEX_PROGNAME" join [--check] WIMFILE SPLIT_WIM...\n"
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"
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"
147 IMAGEX_PROGNAME" optimize WIMFILE [--check] [--recompress]\n"
148 " [--threads=NUM_THREADS]\n"
152 IMAGEX_PROGNAME" split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n"
156 IMAGEX_PROGNAME" unmount DIRECTORY [--commit] [--check] [--rebuild]\n"
161 IMAGEX_ALLOW_OTHER_OPTION,
164 IMAGEX_COMMIT_OPTION,
165 IMAGEX_COMPRESS_OPTION,
166 IMAGEX_CONFIG_OPTION,
168 IMAGEX_DEREFERENCE_OPTION,
169 IMAGEX_EXTRACT_XML_OPTION,
171 IMAGEX_HARDLINK_OPTION,
172 IMAGEX_HEADER_OPTION,
173 IMAGEX_LOOKUP_TABLE_OPTION,
174 IMAGEX_METADATA_OPTION,
175 IMAGEX_NO_ACLS_OPTION,
176 IMAGEX_REBULID_OPTION,
177 IMAGEX_RECOMPRESS_OPTION,
180 IMAGEX_SOURCE_LIST_OPTION,
181 IMAGEX_STAGING_DIR_OPTION,
182 IMAGEX_STREAMS_INTERFACE_OPTION,
183 IMAGEX_STRICT_ACLS_OPTION,
184 IMAGEX_SYMLINK_OPTION,
185 IMAGEX_THREADS_OPTION,
186 IMAGEX_UNIX_DATA_OPTION,
187 IMAGEX_VERBOSE_OPTION,
191 static const struct option apply_options[] = {
192 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
193 {T("hardlink"), no_argument, NULL, IMAGEX_HARDLINK_OPTION},
194 {T("symlink"), no_argument, NULL, IMAGEX_SYMLINK_OPTION},
195 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
196 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
197 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
198 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
199 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
200 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
203 static const struct option capture_or_append_options[] = {
204 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
205 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
206 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
207 {T("config"), required_argument, NULL, IMAGEX_CONFIG_OPTION},
208 {T("dereference"), no_argument, NULL, IMAGEX_DEREFERENCE_OPTION},
209 {T("flags"), required_argument, NULL, IMAGEX_FLAGS_OPTION},
210 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
211 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
212 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
213 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
214 {T("source-list"), no_argument, NULL, IMAGEX_SOURCE_LIST_OPTION},
215 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
216 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
217 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
220 static const struct option delete_options[] = {
221 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
222 {T("soft"), no_argument, NULL, IMAGEX_SOFT_OPTION},
226 static const struct option export_options[] = {
227 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
228 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
229 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
230 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
231 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
232 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
236 static const struct option info_options[] = {
237 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
238 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
239 {T("extract-xml"), required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
240 {T("header"), no_argument, NULL, IMAGEX_HEADER_OPTION},
241 {T("lookup-table"), no_argument, NULL, IMAGEX_LOOKUP_TABLE_OPTION},
242 {T("metadata"), no_argument, NULL, IMAGEX_METADATA_OPTION},
243 {T("xml"), no_argument, NULL, IMAGEX_XML_OPTION},
247 static const struct option join_options[] = {
248 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
252 static const struct option mount_options[] = {
253 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
254 {T("debug"), no_argument, NULL, IMAGEX_DEBUG_OPTION},
255 {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
256 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
257 {T("staging-dir"), required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
258 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
259 {T("allow-other"), no_argument, NULL, IMAGEX_ALLOW_OTHER_OPTION},
263 static const struct option optimize_options[] = {
264 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
265 {T("recompress"), no_argument, NULL, IMAGEX_RECOMPRESS_OPTION},
266 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
270 static const struct option split_options[] = {
271 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
275 static const struct option unmount_options[] = {
276 {T("commit"), no_argument, NULL, IMAGEX_COMMIT_OPTION},
277 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
278 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
284 /* Print formatted error message to stderr. */
286 imagex_error(const tchar *format, ...)
289 va_start(va, format);
290 tfputs(T("ERROR: "), stderr);
291 tvfprintf(stderr, format, va);
292 tputc(T('\n'), stderr);
296 /* Print formatted error message to stderr. */
298 imagex_error_with_errno(const tchar *format, ...)
300 int errno_save = errno;
302 va_start(va, format);
303 tfputs(T("ERROR: "), stderr);
304 tvfprintf(stderr, format, va);
305 tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
310 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
312 if (image == WIMLIB_NO_IMAGE) {
313 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
314 " Please specify a 1-based image index or "
316 " You may use `"IMAGEX_PROGNAME" info' to list the images "
317 "contained in a WIM."),
318 image_name, wim_name);
325 verify_image_is_single(int image)
327 if (image == WIMLIB_ALL_IMAGES) {
328 imagex_error(T("Cannot specify all images for this action!"));
335 verify_image_exists_and_is_single(int image, const tchar *image_name,
336 const tchar *wim_name)
339 ret = verify_image_exists(image, image_name, wim_name);
341 ret = verify_image_is_single(image);
345 /* Parse the argument to --compress */
347 get_compression_type(const tchar *optarg)
349 if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
350 return WIMLIB_COMPRESSION_TYPE_LZX;
351 else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
352 return WIMLIB_COMPRESSION_TYPE_XPRESS;
353 else if (!tstrcasecmp(optarg, T("none")))
354 return WIMLIB_COMPRESSION_TYPE_NONE;
356 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
357 "\"maximum\", \"fast\", or \"none\"."), optarg);
358 return WIMLIB_COMPRESSION_TYPE_INVALID;
362 /* Returns the size of a file given its name, or -1 if the file does not exist
363 * or its size cannot be determined. */
365 file_get_size(const tchar *filename)
368 if (tstat(filename, &st) == 0)
374 tchar pat_ntfs_log[] = T("/$ntfs.log");
375 tchar pat_hiberfil_sys[] = T("/hiberfil.sys");
376 tchar pat_pagefile_sys[] = T("/pagefile.sys");
377 tchar pat_system_volume_information[] = T("/System Volume Information");
378 tchar pat_recycler[] = T("/RECYCLER");
379 tchar pat_windows_csc[] = T("/Windows/CSC");
381 tchar *default_pats[] = {
385 pat_system_volume_information,
390 static struct wimlib_capture_config default_capture_config = {
392 .num_pats = sizeof(default_pats) / sizeof(*default_pats),
393 .pats = default_pats,
398 PARSE_FILENAME_SUCCESS = 0,
399 PARSE_FILENAME_FAILURE = 1,
400 PARSE_FILENAME_NONE = 2,
404 * Parses a filename in the source list file format. (See the man page for
405 * 'wimlib-imagex capture' for details on this format and the meaning.)
406 * Accepted formats for filenames are an unquoted string (whitespace-delimited),
407 * or a double or single-quoted string.
409 * @line_p: Pointer to the pointer to the line of data. Will be updated
410 * to point past the filename iff the return value is
411 * PARSE_FILENAME_SUCCESS. If *len_p > 0, (*line_p)[*len_p - 1] must
414 * @len_p: @len_p initially stores the length of the line of data, which may
415 * be 0, and it will be updated to the number of bytes remaining in
416 * the line iff the return value is PARSE_FILENAME_SUCCESS.
418 * @fn_ret: Iff the return value is PARSE_FILENAME_SUCCESS, a pointer to the
419 * parsed filename will be returned here.
421 * Returns: PARSE_FILENAME_SUCCESS if a filename was successfully parsed; or
422 * PARSE_FILENAME_FAILURE if the data was invalid due to a missing
423 * closing quote; or PARSE_FILENAME_NONE if the line ended before the
424 * beginning of a filename was found.
427 parse_filename(tchar **line_p, size_t *len_p, tchar **fn_ret)
430 tchar *line = *line_p;
434 /* Skip leading whitespace */
437 return PARSE_FILENAME_NONE;
438 if (!istspace(*line) && *line != T('\0'))
444 if (quote_char == T('"') || quote_char == T('\'')) {
445 /* Quoted filename */
449 line = tmemchr(line, quote_char, len);
451 imagex_error(T("Missing closing quote: %"TS), fn - 1);
452 return PARSE_FILENAME_FAILURE;
455 /* Unquoted filename. Go until whitespace. Line is terminated
456 * by '\0', so no need to check 'len'. */
460 } while (!istspace(*line) && *line != T('\0'));
467 return PARSE_FILENAME_SUCCESS;
470 /* Parses a line of data (not an empty line or comment) in the source list file
471 * format. (See the man page for 'wimlib-imagex capture' for details on this
472 * format and the meaning.)
474 * @line: Line of data to be parsed. line[len - 1] must be '\0', unless
475 * len == 0. The data in @line will be modified by this function call.
477 * @len: Length of the line of data.
479 * @source: On success, the capture source and target described by the line is
480 * written into this destination. Note that it will contain pointers
481 * to data in the @line array.
483 * Returns true if the line was valid; false otherwise. */
485 parse_source_list_line(tchar *line, size_t len,
486 struct wimlib_capture_source *source)
490 ret = parse_filename(&line, &len, &source->fs_source_path);
491 if (ret != PARSE_FILENAME_SUCCESS)
493 ret = parse_filename(&line, &len, &source->wim_target_path);
494 if (ret == PARSE_FILENAME_NONE)
495 source->wim_target_path = source->fs_source_path;
496 return ret != PARSE_FILENAME_FAILURE;
499 /* Returns %true if the given line of length @len > 0 is a comment or empty line
500 * in the source list file format. */
502 is_comment_line(const tchar *line, size_t len)
507 if (!istspace(*line) && *line != T('\0'))
517 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
520 tchar *contents = *contents_p;
521 size_t nchars = *nchars_p;
524 for (i = 0; i < nchars; i++)
525 if (contents[i] == T('\n'))
528 /* Handle last line not terminated by a newline */
529 if (nchars != 0 && contents[nchars - 1] != T('\n')) {
530 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
532 imagex_error(T("Out of memory!"));
535 contents[nchars] = T('\n');
536 *contents_p = contents;
544 /* Parses a file in the source list format. (See the man page for
545 * 'wimlib-imagex capture' for details on this format and the meaning.)
547 * @source_list_contents: Contents of the source list file. Note that this
548 * buffer will be modified to save memory allocations,
549 * and cannot be freed until the returned array of
550 * wimlib_capture_source's has also been freed.
552 * @source_list_nbytes: Number of bytes of data in the @source_list_contents
555 * @nsources_ret: On success, the length of the returned array is
558 * Returns: An array of `struct wimlib_capture_source's that can be passed to
559 * the wimlib_add_image_multisource() function to specify how a WIM image is to
561 static struct wimlib_capture_source *
562 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
563 size_t *nsources_ret)
567 struct wimlib_capture_source *sources;
570 nlines = text_file_count_lines(source_list_contents_p,
571 &source_list_nchars);
575 /* Always allocate at least 1 slot, just in case the implementation of
576 * calloc() returns NULL if 0 bytes are requested. */
577 sources = calloc(nlines ?: 1, sizeof(*sources));
579 imagex_error(T("out of memory"));
582 p = *source_list_contents_p;
584 for (i = 0; i < nlines; i++) {
585 /* XXX: Could use rawmemchr() here instead, but it may not be
586 * available on all platforms. */
587 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
588 size_t len = endp - p + 1;
590 if (!is_comment_line(p, len)) {
591 if (!parse_source_list_line(p, len, &sources[j++])) {
604 enum capture_config_section {
605 CAPTURE_CONFIG_NO_SECTION,
606 CAPTURE_CONFIG_EXCLUSION_SECTION,
607 CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
608 CAPTURE_CONFIG_IGNORE_SECTION,
612 CAPTURE_CONFIG_INVALID_SECTION,
613 CAPTURE_CONFIG_CHANGED_SECTION,
614 CAPTURE_CONFIG_SAME_SECTION,
618 check_config_section(tchar *line, size_t len,
619 enum capture_config_section *cur_section)
621 while (istspace(*line))
625 return CAPTURE_CONFIG_SAME_SECTION;
628 tchar *endbrace = tstrrchr(line, T(']'));
630 return CAPTURE_CONFIG_SAME_SECTION;
632 if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
633 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
634 } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
635 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
636 } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
637 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
638 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
639 "of capture config file\n"),
641 } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
642 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
643 tfputs(T("WARNING: Ignoring [AlignmentList] section "
644 "of capture config file\n"),
647 imagex_error(T("Invalid capture config file section \"%"TS"\""),
649 return CAPTURE_CONFIG_INVALID_SECTION;
651 return CAPTURE_CONFIG_CHANGED_SECTION;
656 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
659 if (pat_list->num_pats == pat_list->num_allocated_pats) {
661 size_t num_allocated_pats = pat_list->num_pats + 8;
663 pats = realloc(pat_list->pats,
664 num_allocated_pats * sizeof(pat_list->pats[0]));
666 imagex_error(T("Out of memory!"));
669 pat_list->pats = pats;
670 pat_list->num_allocated_pats = num_allocated_pats;
672 pat_list->pats[pat_list->num_pats++] = pat;
677 parse_capture_config_line(tchar *line, size_t len,
678 enum capture_config_section *cur_section,
679 struct wimlib_capture_config *config)
684 ret = check_config_section(line, len, cur_section);
685 if (ret == CAPTURE_CONFIG_INVALID_SECTION)
687 if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
690 switch (*cur_section) {
691 case CAPTURE_CONFIG_NO_SECTION:
692 imagex_error(T("Line \"%"TS"\" is not in a section "
693 "(such as [ExclusionList]"), line);
695 case CAPTURE_CONFIG_EXCLUSION_SECTION:
696 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
698 return pattern_list_add_pattern(&config->exclusion_pats,
700 case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
701 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
703 return pattern_list_add_pattern(&config->exclusion_exception_pats,
705 case CAPTURE_CONFIG_IGNORE_SECTION:
712 parse_capture_config(tchar **contents_p, size_t nchars,
713 struct wimlib_capture_config *config)
718 enum capture_config_section cur_section;
720 memset(config, 0, sizeof(*config));
722 nlines = text_file_count_lines(contents_p, &nchars);
726 cur_section = CAPTURE_CONFIG_NO_SECTION;
728 for (i = 0; i < nlines; i++) {
729 tchar *endp = tmemchr(p, T('\n'), nchars);
730 size_t len = endp - p + 1;
732 if (!is_comment_line(p, len))
733 if (!parse_capture_config_line(p, len, &cur_section, config))
741 /* Reads the contents of a file into memory. */
743 file_get_contents(const tchar *filename, size_t *len_ret)
750 if (tstat(filename, &stbuf) != 0) {
751 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
756 fp = tfopen(filename, T("rb"));
758 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
764 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
765 "contents of file \"%"TS"\""), len, filename);
768 if (fread(buf, 1, len, fp) != len) {
769 imagex_error_with_errno(T("Failed to read %zu bytes from the "
770 "file \"%"TS"\""), len, filename);
784 /* Read standard input until EOF and return the full contents in a malloc()ed
785 * buffer and the number of bytes of data in @len_ret. Returns NULL on read
788 stdin_get_contents(size_t *len_ret)
790 /* stdin can, of course, be a pipe or other non-seekable file, so the
791 * total length of the data cannot be pre-determined */
793 size_t newlen = 1024;
797 char *p = realloc(buf, newlen);
798 size_t bytes_read, bytes_to_read;
800 imagex_error(T("out of memory while reading stdin"));
804 bytes_to_read = newlen - pos;
805 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
807 if (bytes_read != bytes_to_read) {
812 imagex_error_with_errno(T("error reading stdin"));
826 translate_text_to_tstr(char *text, size_t num_bytes,
827 size_t *num_tchars_ret)
830 /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
832 *num_tchars_ret = num_bytes;
834 #else /* !__WIN32__ */
835 /* On Windows, translate the text to UTF-16LE */
839 if (num_bytes >= 2 &&
840 ((text[0] == 0xff && text[1] == 0xfe) ||
841 (text[0] <= 0x7f && text[1] == 0x00)))
843 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
844 * with something that looks like an ASCII character encoded as
845 * a UTF-16LE code unit. Assume the file is encoded as
846 * UTF-16LE. This is not a 100% reliable check. */
847 num_wchars = num_bytes / 2;
848 text_wstr = (wchar_t*)text;
850 /* File does not look like UTF-16LE. Assume it is encoded in
851 * the current Windows code page. I think these are always
852 * ASCII-compatible, so any so-called "plain-text" (ASCII) files
853 * should work as expected. */
854 text_wstr = win32_mbs_to_wcs(text,
859 *num_tchars_ret = num_wchars;
861 #endif /* __WIN32__ */
865 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
870 contents = file_get_contents(filename, &num_bytes);
873 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
877 stdin_get_text_contents(size_t *num_tchars_ret)
882 contents = stdin_get_contents(&num_bytes);
885 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
888 /* Return 0 if a path names a file to which the current user has write access;
889 * -1 otherwise (and print an error message). */
891 file_writable(const tchar *path)
894 ret = taccess(path, W_OK);
896 imagex_error_with_errno(T("Can't modify \"%"TS"\""), path);
900 #define TO_PERCENT(numerator, denominator) \
901 (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
903 /* Given an enumerated value for WIM compression type, return a descriptive
906 get_data_type(int ctype)
909 case WIMLIB_COMPRESSION_TYPE_NONE:
910 return T("uncompressed");
911 case WIMLIB_COMPRESSION_TYPE_LZX:
912 return T("LZX-compressed");
913 case WIMLIB_COMPRESSION_TYPE_XPRESS:
914 return T("XPRESS-compressed");
919 /* Progress callback function passed to various wimlib functions. */
921 imagex_progress_func(enum wimlib_progress_msg msg,
922 const union wimlib_progress_info *info)
924 unsigned percent_done;
926 case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
927 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
928 info->write_streams.total_bytes);
929 if (info->write_streams.completed_streams == 0) {
930 const tchar *data_type;
932 data_type = get_data_type(info->write_streams.compression_type);
933 tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
934 data_type, info->write_streams.num_threads,
935 (info->write_streams.num_threads == 1) ? T("") : T("s"));
937 tprintf(T("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
938 "written (%u%% done)"),
939 info->write_streams.completed_bytes >> 20,
940 info->write_streams.total_bytes >> 20,
942 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
945 case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
946 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
947 if (*info->scan.wim_target_path) {
948 tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
949 info->scan.wim_target_path);
951 tprintf(T(" (loading as root of WIM image)...\n"));
954 case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
955 if (info->scan.excluded)
956 tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
958 tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
960 /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
962 case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
963 percent_done = TO_PERCENT(info->integrity.completed_bytes,
964 info->integrity.total_bytes);
965 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" MiB "
966 "of %"PRIu64" MiB (%u%%) done"),
967 info->integrity.filename,
968 info->integrity.completed_bytes >> 20,
969 info->integrity.total_bytes >> 20,
971 if (info->integrity.completed_bytes == info->integrity.total_bytes)
974 case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
975 percent_done = TO_PERCENT(info->integrity.completed_bytes,
976 info->integrity.total_bytes);
977 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" MiB "
978 "of %"PRIu64" MiB (%u%%) done"),
979 info->integrity.completed_bytes >> 20,
980 info->integrity.total_bytes >> 20,
982 if (info->integrity.completed_bytes == info->integrity.total_bytes)
985 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
986 tprintf(T("Applying image %d (%"TS") from \"%"TS"\" "
987 "to %"TS" \"%"TS"\"\n"),
989 info->extract.image_name,
990 info->extract.wimfile_name,
991 ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
992 T("NTFS volume") : T("directory")),
993 info->extract.target);
995 /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
996 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
997 /*info->extract.target);*/
999 case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1000 percent_done = TO_PERCENT(info->extract.completed_bytes,
1001 info->extract.total_bytes);
1002 tprintf(T("\rExtracting files: "
1003 "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done"),
1004 info->extract.completed_bytes >> 20,
1005 info->extract.total_bytes >> 20,
1007 if (info->extract.completed_bytes >= info->extract.total_bytes)
1010 case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
1011 tprintf(T("%"TS"\n"), info->extract.cur_path);
1013 case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1014 tprintf(T("Setting timestamps on all extracted files...\n"));
1016 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1017 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1018 tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1019 info->extract.target);
1022 case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
1023 percent_done = TO_PERCENT(info->join.completed_bytes,
1024 info->join.total_bytes);
1025 tprintf(T("Writing resources from part %u of %u: "
1026 "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n"),
1027 (info->join.completed_parts == info->join.total_parts) ?
1028 info->join.completed_parts : info->join.completed_parts + 1,
1029 info->join.total_parts,
1030 info->join.completed_bytes >> 20,
1031 info->join.total_bytes >> 20,
1034 case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1035 percent_done = TO_PERCENT(info->split.completed_bytes,
1036 info->split.total_bytes);
1037 tprintf(T("Writing \"%"TS"\": %"PRIu64" MiB of "
1038 "%"PRIu64" MiB (%u%%) written\n"),
1039 info->split.part_name,
1040 info->split.completed_bytes >> 20,
1041 info->split.total_bytes >> 20,
1044 case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1045 if (info->split.completed_bytes == info->split.total_bytes) {
1046 tprintf(T("Finished writing %u split WIM parts\n"),
1047 info->split.cur_part_number);
1057 /* Open all the split WIM parts that correspond to a file glob.
1059 * @first_part specifies the first part of the split WIM and it may be either
1060 * included or omitted from the glob. */
1062 open_swms_from_glob(const tchar *swm_glob,
1063 const tchar *first_part,
1065 WIMStruct ***additional_swms_ret,
1066 unsigned *num_additional_swms_ret)
1068 unsigned num_additional_swms = 0;
1069 WIMStruct **additional_swms = NULL;
1073 /* Warning: glob() is replaced in Windows native builds */
1074 ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1076 if (ret == GLOB_NOMATCH) {
1077 imagex_error(T("Found no files for glob \"%"TS"\""),
1080 imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1086 num_additional_swms = globbuf.gl_pathc;
1087 additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1088 if (!additional_swms) {
1089 imagex_error(T("Out of memory"));
1093 unsigned offset = 0;
1094 for (unsigned i = 0; i < num_additional_swms; i++) {
1095 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1099 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1100 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1101 &additional_swms[i - offset],
1102 imagex_progress_func);
1104 goto out_close_swms;
1106 *additional_swms_ret = additional_swms;
1107 *num_additional_swms_ret = num_additional_swms - offset;
1111 for (unsigned i = 0; i < num_additional_swms; i++)
1112 wimlib_free(additional_swms[i]);
1113 free(additional_swms);
1122 parse_num_threads(const tchar *optarg)
1125 unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1126 if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1127 imagex_error(T("Number of threads must be a non-negative integer!"));
1135 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1136 * one image from a WIM file to a NTFS volume. */
1138 imagex_apply(int argc, tchar **argv)
1141 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1146 const tchar *wimfile;
1147 const tchar *target;
1148 const tchar *image_num_or_name;
1149 int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1151 const tchar *swm_glob = NULL;
1152 WIMStruct **additional_swms = NULL;
1153 unsigned num_additional_swms = 0;
1155 for_opt(c, apply_options) {
1157 case IMAGEX_CHECK_OPTION:
1158 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1160 case IMAGEX_HARDLINK_OPTION:
1161 extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1163 case IMAGEX_SYMLINK_OPTION:
1164 extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1166 case IMAGEX_VERBOSE_OPTION:
1167 extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1169 case IMAGEX_REF_OPTION:
1172 case IMAGEX_UNIX_DATA_OPTION:
1173 extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1175 case IMAGEX_NO_ACLS_OPTION:
1176 extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1178 case IMAGEX_STRICT_ACLS_OPTION:
1179 extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1188 if (argc != 2 && argc != 3) {
1195 image_num_or_name = T("1");
1198 image_num_or_name = argv[1];
1202 ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1206 image = wimlib_resolve_image(w, image_num_or_name);
1207 ret = verify_image_exists(image, image_num_or_name, wimfile);
1211 num_images = wimlib_get_num_images(w);
1212 if (argc == 2 && num_images != 1) {
1213 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1214 "(or all)"), wimfile, num_images);
1221 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1223 &num_additional_swms);
1230 ret = tstat(target, &stbuf);
1232 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1233 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1235 if (errno != ENOENT) {
1236 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1244 win32_acquire_restore_privileges();
1246 ret = wimlib_extract_image(w, image, target, extract_flags,
1247 additional_swms, num_additional_swms,
1248 imagex_progress_func);
1250 tprintf(T("Done applying WIM image.\n"));
1252 win32_release_restore_privileges();
1256 if (additional_swms) {
1257 for (unsigned i = 0; i < num_additional_swms; i++)
1258 wimlib_free(additional_swms[i]);
1259 free(additional_swms);
1264 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1265 * directory trees. 'wimlib-imagex capture': create a new WIM file containing
1266 * the desired image. 'wimlib-imagex append': add a new image to an existing
1269 imagex_capture_or_append(int argc, tchar **argv)
1273 int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
1274 int write_flags = 0;
1275 int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1276 const tchar *wimfile;
1279 const tchar *flags_element = NULL;
1283 int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1284 unsigned num_threads = 0;
1287 size_t source_name_len;
1290 const tchar *config_file = NULL;
1292 struct wimlib_capture_config *config = NULL;
1294 bool source_list = false;
1295 size_t source_list_nchars;
1296 tchar *source_list_contents;
1297 bool capture_sources_malloced;
1298 struct wimlib_capture_source *capture_sources;
1301 for_opt(c, capture_or_append_options) {
1303 case IMAGEX_BOOT_OPTION:
1304 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1306 case IMAGEX_CHECK_OPTION:
1307 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1308 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1310 case IMAGEX_CONFIG_OPTION:
1311 config_file = optarg;
1313 case IMAGEX_COMPRESS_OPTION:
1314 compression_type = get_compression_type(optarg);
1315 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1318 case IMAGEX_FLAGS_OPTION:
1319 flags_element = optarg;
1321 case IMAGEX_DEREFERENCE_OPTION:
1322 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1324 case IMAGEX_VERBOSE_OPTION:
1325 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1327 case IMAGEX_THREADS_OPTION:
1328 num_threads = parse_num_threads(optarg);
1329 if (num_threads == UINT_MAX)
1332 case IMAGEX_REBULID_OPTION:
1333 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1335 case IMAGEX_UNIX_DATA_OPTION:
1336 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1338 case IMAGEX_SOURCE_LIST_OPTION:
1341 case IMAGEX_NO_ACLS_OPTION:
1342 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1344 case IMAGEX_STRICT_ACLS_OPTION:
1345 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1355 if (argc < 2 || argc > 4) {
1366 /* Set default name to SOURCE argument, omitting any directory
1367 * prefixes and trailing slashes. This requires making a copy
1369 source_name_len = tstrlen(source);
1370 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1371 name = tbasename(tstrcpy(source_copy, source));
1373 /* Image description defaults to NULL if not given. */
1374 desc = (argc >= 4) ? argv[3] : NULL;
1377 /* Set up capture sources in source list mode */
1378 if (source[0] == T('-') && source[1] == T('\0')) {
1379 source_list_contents = stdin_get_text_contents(&source_list_nchars);
1381 source_list_contents = file_get_text_contents(source,
1382 &source_list_nchars);
1384 if (!source_list_contents)
1387 capture_sources = parse_source_list(&source_list_contents,
1390 if (!capture_sources) {
1392 goto out_free_source_list_contents;
1394 capture_sources_malloced = true;
1396 /* Set up capture source in non-source-list mode (could be
1397 * either "normal" mode or "NTFS mode"--- see the man page). */
1398 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1399 capture_sources[0].fs_source_path = source;
1400 capture_sources[0].wim_target_path = NULL;
1401 capture_sources[0].reserved = 0;
1403 capture_sources_malloced = false;
1404 source_list_contents = NULL;
1410 config_str = file_get_text_contents(config_file, &config_len);
1413 goto out_free_capture_sources;
1416 config = alloca(sizeof(*config));
1417 ret = parse_capture_config(&config_str, config_len, config);
1419 goto out_free_config;
1421 config = &default_capture_config;
1425 ret = wimlib_open_wim(wimfile, open_flags, &w,
1426 imagex_progress_func);
1428 ret = wimlib_create_new_wim(compression_type, &w);
1430 goto out_free_config;
1434 ret = tstat(source, &stbuf);
1436 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1437 tprintf(T("Capturing WIM image from NTFS "
1438 "filesystem on \"%"TS"\"\n"), source);
1439 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1442 if (errno != ENOENT) {
1443 imagex_error_with_errno(T("Failed to stat "
1444 "\"%"TS"\""), source);
1446 goto out_wimlib_free;
1451 win32_acquire_capture_privileges();
1454 ret = wimlib_add_image_multisource(w,
1460 imagex_progress_func);
1462 goto out_release_privs;
1463 cur_image = wimlib_get_num_images(w);
1465 ret = wimlib_set_image_descripton(w, cur_image, desc);
1467 goto out_release_privs;
1469 if (flags_element) {
1470 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1472 goto out_release_privs;
1474 if (cmd == APPEND) {
1475 ret = wimlib_overwrite(w, write_flags, num_threads,
1476 imagex_progress_func);
1478 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1479 num_threads, imagex_progress_func);
1481 if (ret == WIMLIB_ERR_REOPEN)
1484 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1488 win32_release_capture_privileges();
1493 if (config != NULL && config != &default_capture_config) {
1494 free(config->exclusion_pats.pats);
1495 free(config->exclusion_exception_pats.pats);
1498 out_free_capture_sources:
1499 if (capture_sources_malloced)
1500 free(capture_sources);
1501 out_free_source_list_contents:
1502 free(source_list_contents);
1506 /* Remove image(s) from a WIM. */
1508 imagex_delete(int argc, tchar **argv)
1512 int write_flags = 0;
1513 const tchar *wimfile;
1514 const tchar *image_num_or_name;
1519 for_opt(c, delete_options) {
1521 case IMAGEX_CHECK_OPTION:
1522 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1523 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1525 case IMAGEX_SOFT_OPTION:
1526 write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1538 imagex_error(T("Must specify a WIM file"));
1540 imagex_error(T("Must specify an image"));
1545 image_num_or_name = argv[1];
1547 ret = file_writable(wimfile);
1551 ret = wimlib_open_wim(wimfile, open_flags, &w,
1552 imagex_progress_func);
1556 image = wimlib_resolve_image(w, image_num_or_name);
1558 ret = verify_image_exists(image, image_num_or_name, wimfile);
1562 ret = wimlib_delete_image(w, image);
1564 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1568 ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1569 if (ret == WIMLIB_ERR_REOPEN)
1572 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1573 "deleted"), wimfile);
1580 /* Print the files contained in an image(s) in a WIM file. */
1582 imagex_dir(int argc, tchar **argv)
1584 const tchar *wimfile;
1591 imagex_error(T("Must specify a WIM file"));
1596 imagex_error(T("Too many arguments"));
1602 ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1603 imagex_progress_func);
1608 image = wimlib_resolve_image(w, argv[2]);
1609 ret = verify_image_exists(image, argv[2], wimfile);
1613 /* Image was not specified. If the WIM only contains one image,
1614 * choose that one; otherwise, print an error. */
1615 num_images = wimlib_get_num_images(w);
1616 if (num_images != 1) {
1617 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
1618 "select one."), wimfile, num_images);
1626 ret = wimlib_print_files(w, image);
1632 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1635 imagex_export(int argc, tchar **argv)
1639 int export_flags = 0;
1640 int write_flags = 0;
1641 int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1642 bool compression_type_specified = false;
1643 const tchar *src_wimfile;
1644 const tchar *src_image_num_or_name;
1645 const tchar *dest_wimfile;
1646 const tchar *dest_name;
1647 const tchar *dest_desc;
1648 WIMStruct *src_w = NULL;
1649 WIMStruct *dest_w = NULL;
1654 const tchar *swm_glob = NULL;
1655 WIMStruct **additional_swms = NULL;
1656 unsigned num_additional_swms = 0;
1657 unsigned num_threads = 0;
1659 for_opt(c, export_options) {
1661 case IMAGEX_BOOT_OPTION:
1662 export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
1664 case IMAGEX_CHECK_OPTION:
1665 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1666 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1668 case IMAGEX_COMPRESS_OPTION:
1669 compression_type = get_compression_type(optarg);
1670 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1672 compression_type_specified = true;
1674 case IMAGEX_REF_OPTION:
1677 case IMAGEX_THREADS_OPTION:
1678 num_threads = parse_num_threads(optarg);
1679 if (num_threads == UINT_MAX)
1682 case IMAGEX_REBULID_OPTION:
1683 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1692 if (argc < 3 || argc > 5) {
1696 src_wimfile = argv[0];
1697 src_image_num_or_name = argv[1];
1698 dest_wimfile = argv[2];
1699 dest_name = (argc >= 4) ? argv[3] : NULL;
1700 dest_desc = (argc >= 5) ? argv[4] : NULL;
1701 ret = wimlib_open_wim(src_wimfile,
1702 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
1703 imagex_progress_func);
1707 /* Determine if the destination is an existing file or not.
1708 * If so, we try to append the exported image(s) to it; otherwise, we
1709 * create a new WIM containing the exported image(s). */
1710 if (tstat(dest_wimfile, &stbuf) == 0) {
1714 /* Destination file exists. */
1716 if (!S_ISREG(stbuf.st_mode)) {
1717 imagex_error(T("\"%"TS"\" is not a regular file"),
1722 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1723 imagex_progress_func);
1727 ret = file_writable(dest_wimfile);
1731 dest_ctype = wimlib_get_compression_type(dest_w);
1732 if (compression_type_specified
1733 && compression_type != dest_ctype)
1735 imagex_error(T("Cannot specify a compression type that is "
1736 "not the same as that used in the "
1737 "destination WIM"));
1743 /* dest_wimfile is not an existing file, so create a new WIM. */
1744 if (!compression_type_specified)
1745 compression_type = wimlib_get_compression_type(src_w);
1746 if (errno == ENOENT) {
1747 ret = wimlib_create_new_wim(compression_type, &dest_w);
1751 imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
1758 image = wimlib_resolve_image(src_w, src_image_num_or_name);
1759 ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1764 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1766 &num_additional_swms);
1771 ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1772 export_flags, additional_swms,
1773 num_additional_swms, imagex_progress_func);
1779 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1780 write_flags, num_threads,
1781 imagex_progress_func);
1783 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1784 imagex_progress_func);
1786 if (ret == WIMLIB_ERR_REOPEN)
1789 wimlib_free(dest_w);
1790 if (additional_swms) {
1791 for (unsigned i = 0; i < num_additional_swms; i++)
1792 wimlib_free(additional_swms[i]);
1793 free(additional_swms);
1798 /* Prints information about a WIM file; also can mark an image as bootable,
1799 * change the name of an image, or change the description of an image. */
1801 imagex_info(int argc, tchar **argv)
1806 bool header = false;
1807 bool lookup_table = false;
1809 bool metadata = false;
1810 bool short_header = true;
1811 const tchar *xml_out_file = NULL;
1812 const tchar *wimfile;
1813 const tchar *image_num_or_name = T("all");
1814 const tchar *new_name = NULL;
1815 const tchar *new_desc = NULL;
1820 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1825 for_opt(c, info_options) {
1827 case IMAGEX_BOOT_OPTION:
1830 case IMAGEX_CHECK_OPTION:
1833 case IMAGEX_HEADER_OPTION:
1835 short_header = false;
1837 case IMAGEX_LOOKUP_TABLE_OPTION:
1838 lookup_table = true;
1839 short_header = false;
1841 case IMAGEX_XML_OPTION:
1843 short_header = false;
1845 case IMAGEX_EXTRACT_XML_OPTION:
1846 xml_out_file = optarg;
1847 short_header = false;
1849 case IMAGEX_METADATA_OPTION:
1851 short_header = false;
1861 if (argc == 0 || argc > 4) {
1867 image_num_or_name = argv[1];
1877 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1879 ret = wimlib_open_wim(wimfile, open_flags, &w,
1880 imagex_progress_func);
1884 part_number = wimlib_get_part_number(w, &total_parts);
1886 image = wimlib_resolve_image(w, image_num_or_name);
1887 if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
1888 imagex_error(T("The image \"%"TS"\" does not exist"),
1891 imagex_error(T("If you would like to set the boot "
1892 "index to 0, specify image \"0\" with "
1893 "the --boot flag."));
1895 ret = WIMLIB_ERR_INVALID_IMAGE;
1899 num_images = wimlib_get_num_images(w);
1901 if (num_images == 0) {
1903 imagex_error(T("--boot is meaningless on a WIM with no "
1905 ret = WIMLIB_ERR_INVALID_IMAGE;
1910 if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1912 imagex_error(T("Cannot specify the --boot flag "
1913 "without specifying a specific "
1914 "image in a multi-image WIM"));
1915 ret = WIMLIB_ERR_INVALID_IMAGE;
1919 imagex_error(T("Cannot specify the NEW_NAME "
1920 "without specifying a specific "
1921 "image in a multi-image WIM"));
1922 ret = WIMLIB_ERR_INVALID_IMAGE;
1927 /* Operations that print information are separated from operations that
1928 * recreate the WIM file. */
1929 if (!new_name && !boot) {
1931 /* Read-only operations */
1933 if (image == WIMLIB_NO_IMAGE) {
1934 imagex_error(T("\"%"TS"\" is not a valid image"),
1936 ret = WIMLIB_ERR_INVALID_IMAGE;
1940 if (image == WIMLIB_ALL_IMAGES && short_header)
1941 wimlib_print_wim_information(w);
1944 wimlib_print_header(w);
1947 if (total_parts != 1) {
1948 tprintf(T("Warning: Only showing the lookup table "
1949 "for part %d of a %d-part WIM.\n"),
1950 part_number, total_parts);
1952 wimlib_print_lookup_table(w);
1956 ret = wimlib_extract_xml_data(w, stdout);
1962 fp = tfopen(xml_out_file, T("wb"));
1964 imagex_error_with_errno(T("Failed to open the "
1965 "file \"%"TS"\" for "
1971 ret = wimlib_extract_xml_data(w, fp);
1972 if (fclose(fp) != 0) {
1973 imagex_error(T("Failed to close the file "
1984 wimlib_print_available_images(w, image);
1987 ret = wimlib_print_metadata(w, image);
1993 /* Modification operations */
1994 if (total_parts != 1) {
1995 imagex_error(T("Modifying a split WIM is not supported."));
1999 if (image == WIMLIB_ALL_IMAGES)
2002 if (image == WIMLIB_NO_IMAGE && new_name) {
2003 imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2004 "when using image 0"), new_name);
2010 if (image == wimlib_get_boot_idx(w)) {
2011 tprintf(T("Image %d is already marked as "
2012 "bootable.\n"), image);
2015 tprintf(T("Marking image %d as bootable.\n"),
2017 wimlib_set_boot_idx(w, image);
2021 if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
2023 tprintf(T("Image %d is already named \"%"TS"\".\n"),
2027 tprintf(T("Changing the name of image %d to "
2028 "\"%"TS"\".\n"), image, new_name);
2029 ret = wimlib_set_image_name(w, image, new_name);
2035 const tchar *old_desc;
2036 old_desc = wimlib_get_image_description(w, image);
2037 if (old_desc && !tstrcmp(old_desc, new_desc)) {
2038 tprintf(T("The description of image %d is already "
2039 "\"%"TS"\".\n"), image, new_desc);
2042 tprintf(T("Changing the description of image %d "
2043 "to \"%"TS"\".\n"), image, new_desc);
2044 ret = wimlib_set_image_descripton(w, image,
2051 /* Only call wimlib_overwrite() if something actually needs to
2053 if (boot || new_name || new_desc ||
2054 (check && !wimlib_has_integrity_table(w)))
2058 ret = file_writable(wimfile);
2063 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2067 ret = wimlib_overwrite(w, write_flags, 1,
2068 imagex_progress_func);
2069 if (ret == WIMLIB_ERR_REOPEN)
2072 tprintf(T("The file \"%"TS"\" was not modified because nothing "
2073 "needed to be done.\n"), wimfile);
2082 /* Join split WIMs into one part WIM */
2084 imagex_join(int argc, tchar **argv)
2087 int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2088 int wim_write_flags = 0;
2089 const tchar *output_path;
2091 for_opt(c, join_options) {
2093 case IMAGEX_CHECK_OPTION:
2094 swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2095 wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2105 imagex_error(T("Must specify one or more split WIM (.swm) "
2109 output_path = argv[0];
2110 return wimlib_join((const tchar * const *)++argv,
2115 imagex_progress_func);
2121 /* Mounts an image using a FUSE mount. */
2123 imagex_mount_rw_or_ro(int argc, tchar **argv)
2126 int mount_flags = 0;
2127 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2128 const tchar *wimfile;
2134 const tchar *swm_glob = NULL;
2135 WIMStruct **additional_swms = NULL;
2136 unsigned num_additional_swms = 0;
2137 const tchar *staging_dir = NULL;
2139 if (!tstrcmp(argv[0], T("mountrw")))
2140 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2142 for_opt(c, mount_options) {
2144 case IMAGEX_ALLOW_OTHER_OPTION:
2145 mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2147 case IMAGEX_CHECK_OPTION:
2148 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2150 case IMAGEX_DEBUG_OPTION:
2151 mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2153 case IMAGEX_STREAMS_INTERFACE_OPTION:
2154 if (!tstrcasecmp(optarg, T("none")))
2155 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2156 else if (!tstrcasecmp(optarg, T("xattr")))
2157 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2158 else if (!tstrcasecmp(optarg, T("windows")))
2159 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2161 imagex_error(T("Unknown stream interface \"%"TS"\""),
2166 case IMAGEX_REF_OPTION:
2169 case IMAGEX_STAGING_DIR_OPTION:
2170 staging_dir = optarg;
2172 case IMAGEX_UNIX_DATA_OPTION:
2173 mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2181 if (argc != 2 && argc != 3)
2186 ret = wimlib_open_wim(wimfile, open_flags, &w,
2187 imagex_progress_func);
2192 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2194 &num_additional_swms);
2201 num_images = wimlib_get_num_images(w);
2202 if (num_images != 1) {
2203 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
2204 "select one."), wimfile, num_images);
2205 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2212 image = wimlib_resolve_image(w, argv[1]);
2214 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2219 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2220 ret = file_writable(wimfile);
2225 ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2226 num_additional_swms, staging_dir);
2228 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2230 image, wimfile, dir);
2235 if (additional_swms) {
2236 for (unsigned i = 0; i < num_additional_swms; i++)
2237 wimlib_free(additional_swms[i]);
2238 free(additional_swms);
2242 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2247 /* Rebuild a WIM file */
2249 imagex_optimize(int argc, tchar **argv)
2253 int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2256 const tchar *wimfile;
2259 unsigned num_threads = 0;
2261 for_opt(c, optimize_options) {
2263 case IMAGEX_CHECK_OPTION:
2264 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2265 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2267 case IMAGEX_RECOMPRESS_OPTION:
2268 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2270 case IMAGEX_THREADS_OPTION:
2271 num_threads = parse_num_threads(optarg);
2272 if (num_threads == UINT_MAX)
2290 ret = wimlib_open_wim(wimfile, open_flags, &w,
2291 imagex_progress_func);
2295 old_size = file_get_size(argv[0]);
2296 tprintf(T("\"%"TS"\" original size: "), wimfile);
2298 tfputs(T("Unknown\n"), stdout);
2300 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2302 ret = wimlib_overwrite(w, write_flags, num_threads,
2303 imagex_progress_func);
2306 new_size = file_get_size(argv[0]);
2307 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2309 tfputs(T("Unknown\n"), stdout);
2311 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2313 tfputs(T("Space saved: "), stdout);
2314 if (new_size != -1 && old_size != -1) {
2315 tprintf(T("%lld KiB\n"),
2316 ((long long)old_size - (long long)new_size) >> 10);
2318 tfputs(T("Unknown\n"), stdout);
2326 /* Split a WIM into a spanned set */
2328 imagex_split(int argc, tchar **argv)
2331 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2332 int write_flags = 0;
2333 unsigned long part_size;
2338 for_opt(c, split_options) {
2340 case IMAGEX_CHECK_OPTION:
2341 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2342 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2356 part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2357 if (tmp == argv[2] || *tmp) {
2358 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2359 imagex_error(T("The part size must be an integer or "
2360 "floating-point number of megabytes."));
2363 ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2366 ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2371 /* Unmounts a mounted WIM image. */
2373 imagex_unmount(int argc, tchar **argv)
2376 int unmount_flags = 0;
2379 for_opt(c, unmount_options) {
2381 case IMAGEX_COMMIT_OPTION:
2382 unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2384 case IMAGEX_CHECK_OPTION:
2385 unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2387 case IMAGEX_REBULID_OPTION:
2388 unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2402 ret = wimlib_unmount_image(argv[0], unmount_flags,
2403 imagex_progress_func);
2405 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2409 struct imagex_command {
2411 int (*func)(int , tchar **);
2416 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
2417 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
2419 static const struct imagex_command imagex_commands[] = {
2420 {T("append"), imagex_capture_or_append, APPEND},
2421 {T("apply"), imagex_apply, APPLY},
2422 {T("capture"), imagex_capture_or_append, CAPTURE},
2423 {T("delete"), imagex_delete, DELETE},
2424 {T("dir"), imagex_dir, DIR},
2425 {T("export"), imagex_export, EXPORT},
2426 {T("info"), imagex_info, INFO},
2427 {T("join"), imagex_join, JOIN},
2428 {T("mount"), imagex_mount_rw_or_ro, MOUNT},
2429 {T("mountrw"), imagex_mount_rw_or_ro, MOUNTRW},
2430 {T("optimize"),imagex_optimize, OPTIMIZE},
2431 {T("split"), imagex_split, SPLIT},
2432 {T("unmount"), imagex_unmount, UNMOUNT},
2438 static const tchar *s =
2440 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
2441 "Copyright (C) 2012, 2013 Eric Biggers\n"
2442 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
2443 "This is free software: you are free to change and redistribute it.\n"
2444 "There is NO WARRANTY, to the extent permitted by law.\n"
2446 "Report bugs to "PACKAGE_BUGREPORT".\n"
2453 help_or_version(int argc, tchar **argv)
2457 const struct imagex_command *cmd;
2459 for (i = 1; i < argc; i++) {
2467 if (!tstrcmp(p, T("help"))) {
2468 for_imagex_command(cmd) {
2469 if (!tstrcmp(cmd->name, argv[1])) {
2477 if (!tstrcmp(p, T("version"))) {
2488 const struct imagex_command *cmd;
2489 tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
2490 for_imagex_command(cmd) {
2491 if (cmd->cmd == cmd_type) {
2492 tprintf(T("\nTry `man "IMAGEX_PROGNAME"-%"TS"' "
2493 "for more details.\n"), cmd->name);
2501 tfputs(T("Usage:\n"), stdout);
2502 for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
2503 tprintf(T(" %"TS), usage_strings[i]);
2504 static const tchar *extra =
2506 " "IMAGEX_PROGNAME" --help\n"
2507 " "IMAGEX_PROGNAME" --version\n"
2509 " The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
2511 " Try `man "IMAGEX_PROGNAME"' for more information.\n"
2513 tfputs(extra, stdout);
2516 /* Entry point for wimlib's ImageX implementation. On UNIX the command
2517 * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
2518 * something else), while an Windows the command arguments will be UTF-16LE
2519 * encoded 'wchar_t' strings. */
2522 wmain(int argc, wchar_t **argv, wchar_t **envp)
2524 main(int argc, char **argv)
2527 const struct imagex_command *cmd;
2532 if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
2533 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
2537 setlocale(LC_ALL, "");
2538 codeset = nl_langinfo(CODESET);
2539 if (!strstr(codeset, "UTF-8") &&
2540 !strstr(codeset, "UTF8") &&
2541 !strstr(codeset, "utf-8") &&
2542 !strstr(codeset, "utf8"))
2545 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
2546 " Maybe try: `export LANG=en_US.UTF-8'?\n"
2547 " Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
2548 " to any value to force wimlib to use UTF-8.\n",
2553 #endif /* !__WIN32__ */
2556 imagex_error(T("No command specified"));
2562 /* Handle --help and --version for all commands. Note that this will
2563 * not return if either of these arguments are present. */
2564 help_or_version(argc, argv);
2568 /* The user may like to see more informative error messages. */
2569 wimlib_set_print_errors(true);
2571 /* Do any initializations that the library needs */
2572 ret = wimlib_global_init(init_flags);
2574 goto out_check_status;
2576 /* Search for the function to handle the ImageX subcommand. */
2577 for_imagex_command(cmd) {
2578 if (!tstrcmp(cmd->name, *argv)) {
2579 ret = cmd->func(argc, argv);
2580 goto out_check_write_error;
2584 imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
2588 out_check_write_error:
2589 /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
2590 * standard output is part of the program's actual behavior and not just
2591 * for informational purposes, so we should set a failure exit status if
2592 * there was a write error. */
2593 if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
2594 if (ferror(stdout) || fclose(stdout)) {
2595 imagex_error_with_errno(T("error writing to standard output"));
2601 /* Exit status (ret): -1 indicates an error found by 'wimlib-imagex'
2602 * outside of the wimlib library code. 0 indicates success. > 0
2603 * indicates a wimlib error code from which an error message can be
2606 imagex_error(T("Exiting with error code %d:\n"
2608 wimlib_get_error_string(ret));
2609 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
2610 imagex_error_with_errno(T("errno"));
2613 /* Make the library free any resources it's holding (not strictly
2614 * necessary because the process is ending anyway). */
2615 wimlib_global_cleanup();