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"
151 IMAGEX_PROGNAME" split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n"
155 IMAGEX_PROGNAME" unmount DIRECTORY [--commit] [--check] [--rebuild]\n"
160 IMAGEX_ALLOW_OTHER_OPTION,
163 IMAGEX_COMMIT_OPTION,
164 IMAGEX_COMPRESS_OPTION,
165 IMAGEX_CONFIG_OPTION,
167 IMAGEX_DEREFERENCE_OPTION,
168 IMAGEX_EXTRACT_XML_OPTION,
170 IMAGEX_HARDLINK_OPTION,
171 IMAGEX_HEADER_OPTION,
172 IMAGEX_LOOKUP_TABLE_OPTION,
173 IMAGEX_METADATA_OPTION,
174 IMAGEX_NO_ACLS_OPTION,
175 IMAGEX_REBULID_OPTION,
176 IMAGEX_RECOMPRESS_OPTION,
179 IMAGEX_SOURCE_LIST_OPTION,
180 IMAGEX_STAGING_DIR_OPTION,
181 IMAGEX_STREAMS_INTERFACE_OPTION,
182 IMAGEX_STRICT_ACLS_OPTION,
183 IMAGEX_SYMLINK_OPTION,
184 IMAGEX_THREADS_OPTION,
185 IMAGEX_UNIX_DATA_OPTION,
186 IMAGEX_VERBOSE_OPTION,
190 static const struct option apply_options[] = {
191 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
192 {T("hardlink"), no_argument, NULL, IMAGEX_HARDLINK_OPTION},
193 {T("symlink"), no_argument, NULL, IMAGEX_SYMLINK_OPTION},
194 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
195 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
196 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
197 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
198 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
199 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
202 static const struct option capture_or_append_options[] = {
203 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
204 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
205 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
206 {T("config"), required_argument, NULL, IMAGEX_CONFIG_OPTION},
207 {T("dereference"), no_argument, NULL, IMAGEX_DEREFERENCE_OPTION},
208 {T("flags"), required_argument, NULL, IMAGEX_FLAGS_OPTION},
209 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
210 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
211 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
212 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
213 {T("source-list"), no_argument, NULL, IMAGEX_SOURCE_LIST_OPTION},
214 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
215 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
216 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
219 static const struct option delete_options[] = {
220 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
221 {T("soft"), no_argument, NULL, IMAGEX_SOFT_OPTION},
225 static const struct option export_options[] = {
226 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
227 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
228 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
229 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
230 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
231 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
235 static const struct option info_options[] = {
236 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
237 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
238 {T("extract-xml"), required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
239 {T("header"), no_argument, NULL, IMAGEX_HEADER_OPTION},
240 {T("lookup-table"), no_argument, NULL, IMAGEX_LOOKUP_TABLE_OPTION},
241 {T("metadata"), no_argument, NULL, IMAGEX_METADATA_OPTION},
242 {T("xml"), no_argument, NULL, IMAGEX_XML_OPTION},
246 static const struct option join_options[] = {
247 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
251 static const struct option mount_options[] = {
252 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
253 {T("debug"), no_argument, NULL, IMAGEX_DEBUG_OPTION},
254 {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
255 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
256 {T("staging-dir"), required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
257 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
258 {T("allow-other"), no_argument, NULL, IMAGEX_ALLOW_OTHER_OPTION},
262 static const struct option optimize_options[] = {
263 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
264 {T("recompress"), no_argument, NULL, IMAGEX_RECOMPRESS_OPTION},
268 static const struct option split_options[] = {
269 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
273 static const struct option unmount_options[] = {
274 {T("commit"), no_argument, NULL, IMAGEX_COMMIT_OPTION},
275 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
276 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
282 /* Print formatted error message to stderr. */
284 imagex_error(const tchar *format, ...)
287 va_start(va, format);
288 tfputs(T("ERROR: "), stderr);
289 tvfprintf(stderr, format, va);
290 tputc(T('\n'), stderr);
294 /* Print formatted error message to stderr. */
296 imagex_error_with_errno(const tchar *format, ...)
298 int errno_save = errno;
300 va_start(va, format);
301 tfputs(T("ERROR: "), stderr);
302 tvfprintf(stderr, format, va);
303 tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
308 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
310 if (image == WIMLIB_NO_IMAGE) {
311 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
312 " Please specify a 1-based image index or "
314 " You may use `"IMAGEX_PROGNAME" info' to list the images "
315 "contained in a WIM."),
316 image_name, wim_name);
323 verify_image_is_single(int image)
325 if (image == WIMLIB_ALL_IMAGES) {
326 imagex_error(T("Cannot specify all images for this action!"));
333 verify_image_exists_and_is_single(int image, const tchar *image_name,
334 const tchar *wim_name)
337 ret = verify_image_exists(image, image_name, wim_name);
339 ret = verify_image_is_single(image);
343 /* Parse the argument to --compress */
345 get_compression_type(const tchar *optarg)
347 if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
348 return WIMLIB_COMPRESSION_TYPE_LZX;
349 else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
350 return WIMLIB_COMPRESSION_TYPE_XPRESS;
351 else if (!tstrcasecmp(optarg, T("none")))
352 return WIMLIB_COMPRESSION_TYPE_NONE;
354 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
355 "\"maximum\", \"fast\", or \"none\"."), optarg);
356 return WIMLIB_COMPRESSION_TYPE_INVALID;
360 /* Returns the size of a file given its name, or -1 if the file does not exist
361 * or its size cannot be determined. */
363 file_get_size(const tchar *filename)
366 if (tstat(filename, &st) == 0)
372 tchar pat_ntfs_log[] = T("/$ntfs.log");
373 tchar pat_hiberfil_sys[] = T("/hiberfil.sys");
374 tchar pat_pagefile_sys[] = T("/pagefile.sys");
375 tchar pat_system_volume_information[] = T("/System Volume Information");
376 tchar pat_recycler[] = T("/RECYCLER");
377 tchar pat_windows_csc[] = T("/Windows/CSC");
379 tchar *default_pats[] = {
383 pat_system_volume_information,
388 static struct wimlib_capture_config default_capture_config = {
390 .num_pats = sizeof(default_pats) / sizeof(*default_pats),
391 .pats = default_pats,
396 PARSE_FILENAME_SUCCESS = 0,
397 PARSE_FILENAME_FAILURE = 1,
398 PARSE_FILENAME_NONE = 2,
402 * Parses a filename in the source list file format. (See the man page for
403 * 'wimlib-imagex capture' for details on this format and the meaning.)
404 * Accepted formats for filenames are an unquoted string (whitespace-delimited),
405 * or a double or single-quoted string.
407 * @line_p: Pointer to the pointer to the line of data. Will be updated
408 * to point past the filename iff the return value is
409 * PARSE_FILENAME_SUCCESS. If *len_p > 0, (*line_p)[*len_p - 1] must
412 * @len_p: @len_p initially stores the length of the line of data, which may
413 * be 0, and it will be updated to the number of bytes remaining in
414 * the line iff the return value is PARSE_FILENAME_SUCCESS.
416 * @fn_ret: Iff the return value is PARSE_FILENAME_SUCCESS, a pointer to the
417 * parsed filename will be returned here.
419 * Returns: PARSE_FILENAME_SUCCESS if a filename was successfully parsed; or
420 * PARSE_FILENAME_FAILURE if the data was invalid due to a missing
421 * closing quote; or PARSE_FILENAME_NONE if the line ended before the
422 * beginning of a filename was found.
425 parse_filename(tchar **line_p, size_t *len_p, tchar **fn_ret)
428 tchar *line = *line_p;
432 /* Skip leading whitespace */
435 return PARSE_FILENAME_NONE;
436 if (!istspace(*line) && *line != T('\0'))
442 if (quote_char == T('"') || quote_char == T('\'')) {
443 /* Quoted filename */
447 line = tmemchr(line, quote_char, len);
449 imagex_error(T("Missing closing quote: %"TS), fn - 1);
450 return PARSE_FILENAME_FAILURE;
453 /* Unquoted filename. Go until whitespace. Line is terminated
454 * by '\0', so no need to check 'len'. */
458 } while (!istspace(*line) && *line != T('\0'));
465 return PARSE_FILENAME_SUCCESS;
468 /* Parses a line of data (not an empty line or comment) in the source list file
469 * format. (See the man page for 'wimlib-imagex capture' for details on this
470 * format and the meaning.)
472 * @line: Line of data to be parsed. line[len - 1] must be '\0', unless
473 * len == 0. The data in @line will be modified by this function call.
475 * @len: Length of the line of data.
477 * @source: On success, the capture source and target described by the line is
478 * written into this destination. Note that it will contain pointers
479 * to data in the @line array.
481 * Returns true if the line was valid; false otherwise. */
483 parse_source_list_line(tchar *line, size_t len,
484 struct wimlib_capture_source *source)
488 ret = parse_filename(&line, &len, &source->fs_source_path);
489 if (ret != PARSE_FILENAME_SUCCESS)
491 ret = parse_filename(&line, &len, &source->wim_target_path);
492 if (ret == PARSE_FILENAME_NONE)
493 source->wim_target_path = source->fs_source_path;
494 return ret != PARSE_FILENAME_FAILURE;
497 /* Returns %true if the given line of length @len > 0 is a comment or empty line
498 * in the source list file format. */
500 is_comment_line(const tchar *line, size_t len)
505 if (!istspace(*line) && *line != T('\0'))
515 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
518 tchar *contents = *contents_p;
519 size_t nchars = *nchars_p;
522 for (i = 0; i < nchars; i++)
523 if (contents[i] == T('\n'))
526 /* Handle last line not terminated by a newline */
527 if (nchars != 0 && contents[nchars - 1] != T('\n')) {
528 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
530 imagex_error(T("Out of memory!"));
533 contents[nchars] = T('\n');
534 *contents_p = contents;
542 /* Parses a file in the source list format. (See the man page for
543 * 'wimlib-imagex capture' for details on this format and the meaning.)
545 * @source_list_contents: Contents of the source list file. Note that this
546 * buffer will be modified to save memory allocations,
547 * and cannot be freed until the returned array of
548 * wimlib_capture_source's has also been freed.
550 * @source_list_nbytes: Number of bytes of data in the @source_list_contents
553 * @nsources_ret: On success, the length of the returned array is
556 * Returns: An array of `struct wimlib_capture_source's that can be passed to
557 * the wimlib_add_image_multisource() function to specify how a WIM image is to
559 static struct wimlib_capture_source *
560 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
561 size_t *nsources_ret)
565 struct wimlib_capture_source *sources;
568 nlines = text_file_count_lines(source_list_contents_p,
569 &source_list_nchars);
573 /* Always allocate at least 1 slot, just in case the implementation of
574 * calloc() returns NULL if 0 bytes are requested. */
575 sources = calloc(nlines ?: 1, sizeof(*sources));
577 imagex_error(T("out of memory"));
580 p = *source_list_contents_p;
582 for (i = 0; i < nlines; i++) {
583 /* XXX: Could use rawmemchr() here instead, but it may not be
584 * available on all platforms. */
585 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
586 size_t len = endp - p + 1;
588 if (!is_comment_line(p, len)) {
589 if (!parse_source_list_line(p, len, &sources[j++])) {
602 enum capture_config_section {
603 CAPTURE_CONFIG_NO_SECTION,
604 CAPTURE_CONFIG_EXCLUSION_SECTION,
605 CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
606 CAPTURE_CONFIG_IGNORE_SECTION,
610 CAPTURE_CONFIG_INVALID_SECTION,
611 CAPTURE_CONFIG_CHANGED_SECTION,
612 CAPTURE_CONFIG_SAME_SECTION,
616 check_config_section(tchar *line, size_t len,
617 enum capture_config_section *cur_section)
619 while (istspace(*line))
623 return CAPTURE_CONFIG_SAME_SECTION;
626 tchar *endbrace = tstrrchr(line, T(']'));
628 return CAPTURE_CONFIG_SAME_SECTION;
630 if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
631 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
632 } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
633 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
634 } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
635 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
636 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
637 "of capture config file\n"),
639 } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
640 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
641 tfputs(T("WARNING: Ignoring [AlignmentList] section "
642 "of capture config file\n"),
645 imagex_error(T("Invalid capture config file section \"%"TS"\""),
647 return CAPTURE_CONFIG_INVALID_SECTION;
649 return CAPTURE_CONFIG_CHANGED_SECTION;
654 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
657 if (pat_list->num_pats == pat_list->num_allocated_pats) {
659 size_t num_allocated_pats = pat_list->num_pats + 8;
661 pats = realloc(pat_list->pats,
662 num_allocated_pats * sizeof(pat_list->pats[0]));
664 imagex_error(T("Out of memory!"));
667 pat_list->pats = pats;
668 pat_list->num_allocated_pats = num_allocated_pats;
670 pat_list->pats[pat_list->num_pats++] = pat;
675 parse_capture_config_line(tchar *line, size_t len,
676 enum capture_config_section *cur_section,
677 struct wimlib_capture_config *config)
682 ret = check_config_section(line, len, cur_section);
683 if (ret == CAPTURE_CONFIG_INVALID_SECTION)
685 if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
688 switch (*cur_section) {
689 case CAPTURE_CONFIG_NO_SECTION:
690 imagex_error(T("Line \"%"TS"\" is not in a section "
691 "(such as [ExclusionList]"), line);
693 case CAPTURE_CONFIG_EXCLUSION_SECTION:
694 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
696 return pattern_list_add_pattern(&config->exclusion_pats,
698 case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
699 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
701 return pattern_list_add_pattern(&config->exclusion_exception_pats,
703 case CAPTURE_CONFIG_IGNORE_SECTION:
710 parse_capture_config(tchar **contents_p, size_t nchars,
711 struct wimlib_capture_config *config)
716 enum capture_config_section cur_section;
718 memset(config, 0, sizeof(*config));
720 nlines = text_file_count_lines(contents_p, &nchars);
724 cur_section = CAPTURE_CONFIG_NO_SECTION;
726 for (i = 0; i < nlines; i++) {
727 tchar *endp = tmemchr(p, T('\n'), nchars);
728 size_t len = endp - p + 1;
730 if (!is_comment_line(p, len))
731 if (!parse_capture_config_line(p, len, &cur_section, config))
739 /* Reads the contents of a file into memory. */
741 file_get_contents(const tchar *filename, size_t *len_ret)
748 if (tstat(filename, &stbuf) != 0) {
749 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
754 fp = tfopen(filename, T("rb"));
756 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
762 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
763 "contents of file \"%"TS"\""), len, filename);
766 if (fread(buf, 1, len, fp) != len) {
767 imagex_error_with_errno(T("Failed to read %zu bytes from the "
768 "file \"%"TS"\""), len, filename);
782 /* Read standard input until EOF and return the full contents in a malloc()ed
783 * buffer and the number of bytes of data in @len_ret. Returns NULL on read
786 stdin_get_contents(size_t *len_ret)
788 /* stdin can, of course, be a pipe or other non-seekable file, so the
789 * total length of the data cannot be pre-determined */
791 size_t newlen = 1024;
795 char *p = realloc(buf, newlen);
796 size_t bytes_read, bytes_to_read;
798 imagex_error(T("out of memory while reading stdin"));
802 bytes_to_read = newlen - pos;
803 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
805 if (bytes_read != bytes_to_read) {
810 imagex_error_with_errno(T("error reading stdin"));
824 translate_text_to_tstr(char *text, size_t num_bytes,
825 size_t *num_tchars_ret)
828 /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
830 *num_tchars_ret = num_bytes;
832 #else /* !__WIN32__ */
833 /* On Windows, translate the text to UTF-16LE */
837 if (num_bytes >= 2 &&
838 ((text[0] == 0xff && text[1] == 0xfe) ||
839 (text[0] <= 0x7f && text[1] == 0x00)))
841 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
842 * with something that looks like an ASCII character encoded as
843 * a UTF-16LE code unit. Assume the file is encoded as
844 * UTF-16LE. This is not a 100% reliable check. */
845 num_wchars = num_bytes / 2;
846 text_wstr = (wchar_t*)text;
848 /* File does not look like UTF-16LE. Assume it is encoded in
849 * the current Windows code page. I think these are always
850 * ASCII-compatible, so any so-called "plain-text" (ASCII) files
851 * should work as expected. */
852 text_wstr = win32_mbs_to_wcs(text,
857 *num_tchars_ret = num_wchars;
859 #endif /* __WIN32__ */
863 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
868 contents = file_get_contents(filename, &num_bytes);
871 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
875 stdin_get_text_contents(size_t *num_tchars_ret)
880 contents = stdin_get_contents(&num_bytes);
883 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
886 /* Return 0 if a path names a file to which the current user has write access;
887 * -1 otherwise (and print an error message). */
889 file_writable(const tchar *path)
892 ret = taccess(path, W_OK);
894 imagex_error_with_errno(T("Can't modify \"%"TS"\""), path);
898 #define TO_PERCENT(numerator, denominator) \
899 (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
901 /* Given an enumerated value for WIM compression type, return a descriptive
904 get_data_type(int ctype)
907 case WIMLIB_COMPRESSION_TYPE_NONE:
908 return T("uncompressed");
909 case WIMLIB_COMPRESSION_TYPE_LZX:
910 return T("LZX-compressed");
911 case WIMLIB_COMPRESSION_TYPE_XPRESS:
912 return T("XPRESS-compressed");
917 /* Progress callback function passed to various wimlib functions. */
919 imagex_progress_func(enum wimlib_progress_msg msg,
920 const union wimlib_progress_info *info)
922 unsigned percent_done;
924 case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
925 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
926 info->write_streams.total_bytes);
927 if (info->write_streams.completed_streams == 0) {
928 const tchar *data_type;
930 data_type = get_data_type(info->write_streams.compression_type);
931 tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
932 data_type, info->write_streams.num_threads,
933 (info->write_streams.num_threads == 1) ? T("") : T("s"));
935 tprintf(T("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
936 "written (%u%% done)"),
937 info->write_streams.completed_bytes >> 20,
938 info->write_streams.total_bytes >> 20,
940 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
943 case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
944 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
945 if (*info->scan.wim_target_path) {
946 tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
947 info->scan.wim_target_path);
949 tprintf(T(" (loading as root of WIM image)...\n"));
952 case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
953 if (info->scan.excluded)
954 tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
956 tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
958 /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
960 case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
961 percent_done = TO_PERCENT(info->integrity.completed_bytes,
962 info->integrity.total_bytes);
963 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" MiB "
964 "of %"PRIu64" MiB (%u%%) done"),
965 info->integrity.filename,
966 info->integrity.completed_bytes >> 20,
967 info->integrity.total_bytes >> 20,
969 if (info->integrity.completed_bytes == info->integrity.total_bytes)
972 case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
973 percent_done = TO_PERCENT(info->integrity.completed_bytes,
974 info->integrity.total_bytes);
975 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" MiB "
976 "of %"PRIu64" MiB (%u%%) done"),
977 info->integrity.completed_bytes >> 20,
978 info->integrity.total_bytes >> 20,
980 if (info->integrity.completed_bytes == info->integrity.total_bytes)
983 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
984 tprintf(T("Applying image %d (%"TS") from \"%"TS"\" "
985 "to %"TS" \"%"TS"\"\n"),
987 info->extract.image_name,
988 info->extract.wimfile_name,
989 ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
990 T("NTFS volume") : T("directory")),
991 info->extract.target);
993 /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
994 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
995 /*info->extract.target);*/
997 case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
998 percent_done = TO_PERCENT(info->extract.completed_bytes,
999 info->extract.total_bytes);
1000 tprintf(T("\rExtracting files: "
1001 "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done"),
1002 info->extract.completed_bytes >> 20,
1003 info->extract.total_bytes >> 20,
1005 if (info->extract.completed_bytes >= info->extract.total_bytes)
1008 case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
1009 tprintf(T("%"TS"\n"), info->extract.cur_path);
1011 case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1012 tprintf(T("Setting timestamps on all extracted files...\n"));
1014 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1015 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1016 tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1017 info->extract.target);
1020 case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
1021 percent_done = TO_PERCENT(info->join.completed_bytes,
1022 info->join.total_bytes);
1023 tprintf(T("Writing resources from part %u of %u: "
1024 "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n"),
1025 (info->join.completed_parts == info->join.total_parts) ?
1026 info->join.completed_parts : info->join.completed_parts + 1,
1027 info->join.total_parts,
1028 info->join.completed_bytes >> 20,
1029 info->join.total_bytes >> 20,
1032 case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1033 percent_done = TO_PERCENT(info->split.completed_bytes,
1034 info->split.total_bytes);
1035 tprintf(T("Writing \"%"TS"\": %"PRIu64" MiB of "
1036 "%"PRIu64" MiB (%u%%) written\n"),
1037 info->split.part_name,
1038 info->split.completed_bytes >> 20,
1039 info->split.total_bytes >> 20,
1042 case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1043 if (info->split.completed_bytes == info->split.total_bytes) {
1044 tprintf(T("Finished writing %u split WIM parts\n"),
1045 info->split.cur_part_number);
1055 /* Open all the split WIM parts that correspond to a file glob.
1057 * @first_part specifies the first part of the split WIM and it may be either
1058 * included or omitted from the glob. */
1060 open_swms_from_glob(const tchar *swm_glob,
1061 const tchar *first_part,
1063 WIMStruct ***additional_swms_ret,
1064 unsigned *num_additional_swms_ret)
1066 unsigned num_additional_swms = 0;
1067 WIMStruct **additional_swms = NULL;
1071 /* Warning: glob() is replaced in Windows native builds */
1072 ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1074 if (ret == GLOB_NOMATCH) {
1075 imagex_error(T("Found no files for glob \"%"TS"\""),
1078 imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1084 num_additional_swms = globbuf.gl_pathc;
1085 additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1086 if (!additional_swms) {
1087 imagex_error(T("Out of memory"));
1091 unsigned offset = 0;
1092 for (unsigned i = 0; i < num_additional_swms; i++) {
1093 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1097 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1098 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1099 &additional_swms[i - offset],
1100 imagex_progress_func);
1102 goto out_close_swms;
1104 *additional_swms_ret = additional_swms;
1105 *num_additional_swms_ret = num_additional_swms - offset;
1109 for (unsigned i = 0; i < num_additional_swms; i++)
1110 wimlib_free(additional_swms[i]);
1111 free(additional_swms);
1120 parse_num_threads(const tchar *optarg)
1123 unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1124 if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1125 imagex_error(T("Number of threads must be a non-negative integer!"));
1133 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1134 * one image from a WIM file to a NTFS volume. */
1136 imagex_apply(int argc, tchar **argv)
1139 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1144 const tchar *wimfile;
1145 const tchar *target;
1146 const tchar *image_num_or_name;
1147 int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1149 const tchar *swm_glob = NULL;
1150 WIMStruct **additional_swms = NULL;
1151 unsigned num_additional_swms = 0;
1153 for_opt(c, apply_options) {
1155 case IMAGEX_CHECK_OPTION:
1156 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1158 case IMAGEX_HARDLINK_OPTION:
1159 extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1161 case IMAGEX_SYMLINK_OPTION:
1162 extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1164 case IMAGEX_VERBOSE_OPTION:
1165 extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1167 case IMAGEX_REF_OPTION:
1170 case IMAGEX_UNIX_DATA_OPTION:
1171 extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1173 case IMAGEX_NO_ACLS_OPTION:
1174 extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1176 case IMAGEX_STRICT_ACLS_OPTION:
1177 extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1186 if (argc != 2 && argc != 3) {
1193 image_num_or_name = T("1");
1196 image_num_or_name = argv[1];
1200 ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1204 image = wimlib_resolve_image(w, image_num_or_name);
1205 ret = verify_image_exists(image, image_num_or_name, wimfile);
1209 num_images = wimlib_get_num_images(w);
1210 if (argc == 2 && num_images != 1) {
1211 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1212 "(or all)"), wimfile, num_images);
1219 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1221 &num_additional_swms);
1228 ret = tstat(target, &stbuf);
1230 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1231 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1233 if (errno != ENOENT) {
1234 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1242 win32_acquire_restore_privileges();
1244 ret = wimlib_extract_image(w, image, target, extract_flags,
1245 additional_swms, num_additional_swms,
1246 imagex_progress_func);
1248 tprintf(T("Done applying WIM image.\n"));
1250 win32_release_restore_privileges();
1254 if (additional_swms) {
1255 for (unsigned i = 0; i < num_additional_swms; i++)
1256 wimlib_free(additional_swms[i]);
1257 free(additional_swms);
1262 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1263 * directory trees. 'wimlib-imagex capture': create a new WIM file containing
1264 * the desired image. 'wimlib-imagex append': add a new image to an existing
1267 imagex_capture_or_append(int argc, tchar **argv)
1271 int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
1272 int write_flags = 0;
1273 int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1274 const tchar *wimfile;
1277 const tchar *flags_element = NULL;
1281 int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1282 unsigned num_threads = 0;
1285 size_t source_name_len;
1288 const tchar *config_file = NULL;
1290 struct wimlib_capture_config *config = NULL;
1292 bool source_list = false;
1293 size_t source_list_nchars;
1294 tchar *source_list_contents;
1295 bool capture_sources_malloced;
1296 struct wimlib_capture_source *capture_sources;
1299 for_opt(c, capture_or_append_options) {
1301 case IMAGEX_BOOT_OPTION:
1302 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1304 case IMAGEX_CHECK_OPTION:
1305 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1306 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1308 case IMAGEX_CONFIG_OPTION:
1309 config_file = optarg;
1311 case IMAGEX_COMPRESS_OPTION:
1312 compression_type = get_compression_type(optarg);
1313 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1316 case IMAGEX_FLAGS_OPTION:
1317 flags_element = optarg;
1319 case IMAGEX_DEREFERENCE_OPTION:
1320 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1322 case IMAGEX_VERBOSE_OPTION:
1323 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1325 case IMAGEX_THREADS_OPTION:
1326 num_threads = parse_num_threads(optarg);
1327 if (num_threads == UINT_MAX)
1330 case IMAGEX_REBULID_OPTION:
1331 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1333 case IMAGEX_UNIX_DATA_OPTION:
1334 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1336 case IMAGEX_SOURCE_LIST_OPTION:
1339 case IMAGEX_NO_ACLS_OPTION:
1340 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1342 case IMAGEX_STRICT_ACLS_OPTION:
1343 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1353 if (argc < 2 || argc > 4) {
1364 /* Set default name to SOURCE argument, omitting any directory
1365 * prefixes and trailing slashes. This requires making a copy
1367 source_name_len = tstrlen(source);
1368 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1369 name = tbasename(tstrcpy(source_copy, source));
1371 /* Image description defaults to NULL if not given. */
1372 desc = (argc >= 4) ? argv[3] : NULL;
1375 /* Set up capture sources in source list mode */
1376 if (source[0] == T('-') && source[1] == T('\0')) {
1377 source_list_contents = stdin_get_text_contents(&source_list_nchars);
1379 source_list_contents = file_get_text_contents(source,
1380 &source_list_nchars);
1382 if (!source_list_contents)
1385 capture_sources = parse_source_list(&source_list_contents,
1388 if (!capture_sources) {
1390 goto out_free_source_list_contents;
1392 capture_sources_malloced = true;
1394 /* Set up capture source in non-source-list mode (could be
1395 * either "normal" mode or "NTFS mode"--- see the man page). */
1396 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1397 capture_sources[0].fs_source_path = source;
1398 capture_sources[0].wim_target_path = NULL;
1399 capture_sources[0].reserved = 0;
1401 capture_sources_malloced = false;
1402 source_list_contents = NULL;
1408 config_str = file_get_text_contents(config_file, &config_len);
1411 goto out_free_capture_sources;
1414 config = alloca(sizeof(*config));
1415 ret = parse_capture_config(&config_str, config_len, config);
1417 goto out_free_config;
1419 config = &default_capture_config;
1423 ret = wimlib_open_wim(wimfile, open_flags, &w,
1424 imagex_progress_func);
1426 ret = wimlib_create_new_wim(compression_type, &w);
1428 goto out_free_config;
1432 ret = tstat(source, &stbuf);
1434 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1435 tprintf(T("Capturing WIM image from NTFS "
1436 "filesystem on \"%"TS"\"\n"), source);
1437 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1440 if (errno != ENOENT) {
1441 imagex_error_with_errno(T("Failed to stat "
1442 "\"%"TS"\""), source);
1444 goto out_wimlib_free;
1449 win32_acquire_capture_privileges();
1452 ret = wimlib_add_image_multisource(w,
1458 imagex_progress_func);
1460 goto out_release_privs;
1461 cur_image = wimlib_get_num_images(w);
1463 ret = wimlib_set_image_descripton(w, cur_image, desc);
1465 goto out_release_privs;
1467 if (flags_element) {
1468 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1470 goto out_release_privs;
1472 if (cmd == APPEND) {
1473 ret = wimlib_overwrite(w, write_flags, num_threads,
1474 imagex_progress_func);
1476 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1477 num_threads, imagex_progress_func);
1479 if (ret == WIMLIB_ERR_REOPEN)
1482 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1486 win32_release_capture_privileges();
1491 if (config != NULL && config != &default_capture_config) {
1492 free(config->exclusion_pats.pats);
1493 free(config->exclusion_exception_pats.pats);
1496 out_free_capture_sources:
1497 if (capture_sources_malloced)
1498 free(capture_sources);
1499 out_free_source_list_contents:
1500 free(source_list_contents);
1504 /* Remove image(s) from a WIM. */
1506 imagex_delete(int argc, tchar **argv)
1510 int write_flags = 0;
1511 const tchar *wimfile;
1512 const tchar *image_num_or_name;
1517 for_opt(c, delete_options) {
1519 case IMAGEX_CHECK_OPTION:
1520 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1521 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1523 case IMAGEX_SOFT_OPTION:
1524 write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1536 imagex_error(T("Must specify a WIM file"));
1538 imagex_error(T("Must specify an image"));
1543 image_num_or_name = argv[1];
1545 ret = file_writable(wimfile);
1549 ret = wimlib_open_wim(wimfile, open_flags, &w,
1550 imagex_progress_func);
1554 image = wimlib_resolve_image(w, image_num_or_name);
1556 ret = verify_image_exists(image, image_num_or_name, wimfile);
1560 ret = wimlib_delete_image(w, image);
1562 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1566 ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1567 if (ret == WIMLIB_ERR_REOPEN)
1570 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1571 "deleted"), wimfile);
1578 /* Print the files contained in an image(s) in a WIM file. */
1580 imagex_dir(int argc, tchar **argv)
1582 const tchar *wimfile;
1589 imagex_error(T("Must specify a WIM file"));
1594 imagex_error(T("Too many arguments"));
1600 ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1601 imagex_progress_func);
1606 image = wimlib_resolve_image(w, argv[2]);
1607 ret = verify_image_exists(image, argv[2], wimfile);
1611 /* Image was not specified. If the WIM only contains one image,
1612 * choose that one; otherwise, print an error. */
1613 num_images = wimlib_get_num_images(w);
1614 if (num_images != 1) {
1615 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
1616 "select one."), wimfile, num_images);
1624 ret = wimlib_print_files(w, image);
1630 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1633 imagex_export(int argc, tchar **argv)
1637 int export_flags = 0;
1638 int write_flags = 0;
1639 int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1640 bool compression_type_specified = false;
1641 const tchar *src_wimfile;
1642 const tchar *src_image_num_or_name;
1643 const tchar *dest_wimfile;
1644 const tchar *dest_name;
1645 const tchar *dest_desc;
1646 WIMStruct *src_w = NULL;
1647 WIMStruct *dest_w = NULL;
1652 const tchar *swm_glob = NULL;
1653 WIMStruct **additional_swms = NULL;
1654 unsigned num_additional_swms = 0;
1655 unsigned num_threads = 0;
1657 for_opt(c, export_options) {
1659 case IMAGEX_BOOT_OPTION:
1660 export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
1662 case IMAGEX_CHECK_OPTION:
1663 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1664 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1666 case IMAGEX_COMPRESS_OPTION:
1667 compression_type = get_compression_type(optarg);
1668 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1670 compression_type_specified = true;
1672 case IMAGEX_REF_OPTION:
1675 case IMAGEX_THREADS_OPTION:
1676 num_threads = parse_num_threads(optarg);
1677 if (num_threads == UINT_MAX)
1680 case IMAGEX_REBULID_OPTION:
1681 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1690 if (argc < 3 || argc > 5) {
1694 src_wimfile = argv[0];
1695 src_image_num_or_name = argv[1];
1696 dest_wimfile = argv[2];
1697 dest_name = (argc >= 4) ? argv[3] : NULL;
1698 dest_desc = (argc >= 5) ? argv[4] : NULL;
1699 ret = wimlib_open_wim(src_wimfile,
1700 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
1701 imagex_progress_func);
1705 /* Determine if the destination is an existing file or not.
1706 * If so, we try to append the exported image(s) to it; otherwise, we
1707 * create a new WIM containing the exported image(s). */
1708 if (tstat(dest_wimfile, &stbuf) == 0) {
1712 /* Destination file exists. */
1714 if (!S_ISREG(stbuf.st_mode)) {
1715 imagex_error(T("\"%"TS"\" is not a regular file"),
1720 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1721 imagex_progress_func);
1725 ret = file_writable(dest_wimfile);
1729 dest_ctype = wimlib_get_compression_type(dest_w);
1730 if (compression_type_specified
1731 && compression_type != dest_ctype)
1733 imagex_error(T("Cannot specify a compression type that is "
1734 "not the same as that used in the "
1735 "destination WIM"));
1741 /* dest_wimfile is not an existing file, so create a new WIM. */
1742 if (!compression_type_specified)
1743 compression_type = wimlib_get_compression_type(src_w);
1744 if (errno == ENOENT) {
1745 ret = wimlib_create_new_wim(compression_type, &dest_w);
1749 imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
1756 image = wimlib_resolve_image(src_w, src_image_num_or_name);
1757 ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1762 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1764 &num_additional_swms);
1769 ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1770 export_flags, additional_swms,
1771 num_additional_swms, imagex_progress_func);
1777 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1778 write_flags, num_threads,
1779 imagex_progress_func);
1781 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1782 imagex_progress_func);
1784 if (ret == WIMLIB_ERR_REOPEN)
1787 wimlib_free(dest_w);
1788 if (additional_swms) {
1789 for (unsigned i = 0; i < num_additional_swms; i++)
1790 wimlib_free(additional_swms[i]);
1791 free(additional_swms);
1796 /* Prints information about a WIM file; also can mark an image as bootable,
1797 * change the name of an image, or change the description of an image. */
1799 imagex_info(int argc, tchar **argv)
1804 bool header = false;
1805 bool lookup_table = false;
1807 bool metadata = false;
1808 bool short_header = true;
1809 const tchar *xml_out_file = NULL;
1810 const tchar *wimfile;
1811 const tchar *image_num_or_name = T("all");
1812 const tchar *new_name = NULL;
1813 const tchar *new_desc = NULL;
1818 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1823 for_opt(c, info_options) {
1825 case IMAGEX_BOOT_OPTION:
1828 case IMAGEX_CHECK_OPTION:
1831 case IMAGEX_HEADER_OPTION:
1833 short_header = false;
1835 case IMAGEX_LOOKUP_TABLE_OPTION:
1836 lookup_table = true;
1837 short_header = false;
1839 case IMAGEX_XML_OPTION:
1841 short_header = false;
1843 case IMAGEX_EXTRACT_XML_OPTION:
1844 xml_out_file = optarg;
1845 short_header = false;
1847 case IMAGEX_METADATA_OPTION:
1849 short_header = false;
1859 if (argc == 0 || argc > 4) {
1865 image_num_or_name = argv[1];
1875 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1877 ret = wimlib_open_wim(wimfile, open_flags, &w,
1878 imagex_progress_func);
1882 part_number = wimlib_get_part_number(w, &total_parts);
1884 image = wimlib_resolve_image(w, image_num_or_name);
1885 if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
1886 imagex_error(T("The image \"%"TS"\" does not exist"),
1889 imagex_error(T("If you would like to set the boot "
1890 "index to 0, specify image \"0\" with "
1891 "the --boot flag."));
1893 ret = WIMLIB_ERR_INVALID_IMAGE;
1897 num_images = wimlib_get_num_images(w);
1899 if (num_images == 0) {
1901 imagex_error(T("--boot is meaningless on a WIM with no "
1903 ret = WIMLIB_ERR_INVALID_IMAGE;
1908 if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1910 imagex_error(T("Cannot specify the --boot flag "
1911 "without specifying a specific "
1912 "image in a multi-image WIM"));
1913 ret = WIMLIB_ERR_INVALID_IMAGE;
1917 imagex_error(T("Cannot specify the NEW_NAME "
1918 "without specifying a specific "
1919 "image in a multi-image WIM"));
1920 ret = WIMLIB_ERR_INVALID_IMAGE;
1925 /* Operations that print information are separated from operations that
1926 * recreate the WIM file. */
1927 if (!new_name && !boot) {
1929 /* Read-only operations */
1931 if (image == WIMLIB_NO_IMAGE) {
1932 imagex_error(T("\"%"TS"\" is not a valid image"),
1934 ret = WIMLIB_ERR_INVALID_IMAGE;
1938 if (image == WIMLIB_ALL_IMAGES && short_header)
1939 wimlib_print_wim_information(w);
1942 wimlib_print_header(w);
1945 if (total_parts != 1) {
1946 tprintf(T("Warning: Only showing the lookup table "
1947 "for part %d of a %d-part WIM.\n"),
1948 part_number, total_parts);
1950 wimlib_print_lookup_table(w);
1954 ret = wimlib_extract_xml_data(w, stdout);
1960 fp = tfopen(xml_out_file, T("wb"));
1962 imagex_error_with_errno(T("Failed to open the "
1963 "file \"%"TS"\" for "
1969 ret = wimlib_extract_xml_data(w, fp);
1970 if (fclose(fp) != 0) {
1971 imagex_error(T("Failed to close the file "
1982 wimlib_print_available_images(w, image);
1985 ret = wimlib_print_metadata(w, image);
1991 /* Modification operations */
1992 if (total_parts != 1) {
1993 imagex_error(T("Modifying a split WIM is not supported."));
1997 if (image == WIMLIB_ALL_IMAGES)
2000 if (image == WIMLIB_NO_IMAGE && new_name) {
2001 imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2002 "when using image 0"), new_name);
2008 if (image == wimlib_get_boot_idx(w)) {
2009 tprintf(T("Image %d is already marked as "
2010 "bootable.\n"), image);
2013 tprintf(T("Marking image %d as bootable.\n"),
2015 wimlib_set_boot_idx(w, image);
2019 if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
2021 tprintf(T("Image %d is already named \"%"TS"\".\n"),
2025 tprintf(T("Changing the name of image %d to "
2026 "\"%"TS"\".\n"), image, new_name);
2027 ret = wimlib_set_image_name(w, image, new_name);
2033 const tchar *old_desc;
2034 old_desc = wimlib_get_image_description(w, image);
2035 if (old_desc && !tstrcmp(old_desc, new_desc)) {
2036 tprintf(T("The description of image %d is already "
2037 "\"%"TS"\".\n"), image, new_desc);
2040 tprintf(T("Changing the description of image %d "
2041 "to \"%"TS"\".\n"), image, new_desc);
2042 ret = wimlib_set_image_descripton(w, image,
2049 /* Only call wimlib_overwrite() if something actually needs to
2051 if (boot || new_name || new_desc ||
2052 (check && !wimlib_has_integrity_table(w)))
2056 ret = file_writable(wimfile);
2061 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2065 ret = wimlib_overwrite(w, write_flags, 1,
2066 imagex_progress_func);
2067 if (ret == WIMLIB_ERR_REOPEN)
2070 tprintf(T("The file \"%"TS"\" was not modified because nothing "
2071 "needed to be done.\n"), wimfile);
2080 /* Join split WIMs into one part WIM */
2082 imagex_join(int argc, tchar **argv)
2085 int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2086 int wim_write_flags = 0;
2087 const tchar *output_path;
2089 for_opt(c, join_options) {
2091 case IMAGEX_CHECK_OPTION:
2092 swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2093 wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2103 imagex_error(T("Must specify one or more split WIM (.swm) "
2107 output_path = argv[0];
2108 return wimlib_join((const tchar * const *)++argv,
2113 imagex_progress_func);
2119 /* Mounts an image using a FUSE mount. */
2121 imagex_mount_rw_or_ro(int argc, tchar **argv)
2124 int mount_flags = 0;
2125 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2126 const tchar *wimfile;
2132 const tchar *swm_glob = NULL;
2133 WIMStruct **additional_swms = NULL;
2134 unsigned num_additional_swms = 0;
2135 const tchar *staging_dir = NULL;
2137 if (!tstrcmp(argv[0], T("mountrw")))
2138 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2140 for_opt(c, mount_options) {
2142 case IMAGEX_ALLOW_OTHER_OPTION:
2143 mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2145 case IMAGEX_CHECK_OPTION:
2146 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2148 case IMAGEX_DEBUG_OPTION:
2149 mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2151 case IMAGEX_STREAMS_INTERFACE_OPTION:
2152 if (!tstrcasecmp(optarg, T("none")))
2153 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2154 else if (!tstrcasecmp(optarg, T("xattr")))
2155 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2156 else if (!tstrcasecmp(optarg, T("windows")))
2157 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2159 imagex_error(T("Unknown stream interface \"%"TS"\""),
2164 case IMAGEX_REF_OPTION:
2167 case IMAGEX_STAGING_DIR_OPTION:
2168 staging_dir = optarg;
2170 case IMAGEX_UNIX_DATA_OPTION:
2171 mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2179 if (argc != 2 && argc != 3)
2184 ret = wimlib_open_wim(wimfile, open_flags, &w,
2185 imagex_progress_func);
2190 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2192 &num_additional_swms);
2199 num_images = wimlib_get_num_images(w);
2200 if (num_images != 1) {
2201 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
2202 "select one."), wimfile, num_images);
2203 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2210 image = wimlib_resolve_image(w, argv[1]);
2212 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2217 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2218 ret = file_writable(wimfile);
2223 ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2224 num_additional_swms, staging_dir);
2226 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2228 image, wimfile, dir);
2233 if (additional_swms) {
2234 for (unsigned i = 0; i < num_additional_swms; i++)
2235 wimlib_free(additional_swms[i]);
2236 free(additional_swms);
2240 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2245 /* Rebuild a WIM file */
2247 imagex_optimize(int argc, tchar **argv)
2251 int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2254 const tchar *wimfile;
2258 for_opt(c, optimize_options) {
2260 case IMAGEX_CHECK_OPTION:
2261 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2262 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2264 case IMAGEX_RECOMPRESS_OPTION:
2265 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2282 ret = wimlib_open_wim(wimfile, open_flags, &w,
2283 imagex_progress_func);
2287 old_size = file_get_size(argv[0]);
2288 tprintf(T("\"%"TS"\" original size: "), wimfile);
2290 tfputs(T("Unknown\n"), stdout);
2292 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2294 ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
2297 new_size = file_get_size(argv[0]);
2298 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2300 tfputs(T("Unknown\n"), stdout);
2302 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2304 tfputs(T("Space saved: "), stdout);
2305 if (new_size != -1 && old_size != -1) {
2306 tprintf(T("%lld KiB\n"),
2307 ((long long)old_size - (long long)new_size) >> 10);
2309 tfputs(T("Unknown\n"), stdout);
2317 /* Split a WIM into a spanned set */
2319 imagex_split(int argc, tchar **argv)
2322 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2323 int write_flags = 0;
2324 unsigned long part_size;
2329 for_opt(c, split_options) {
2331 case IMAGEX_CHECK_OPTION:
2332 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2333 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2347 part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2348 if (tmp == argv[2] || *tmp) {
2349 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2350 imagex_error(T("The part size must be an integer or "
2351 "floating-point number of megabytes."));
2354 ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2357 ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2362 /* Unmounts a mounted WIM image. */
2364 imagex_unmount(int argc, tchar **argv)
2367 int unmount_flags = 0;
2370 for_opt(c, unmount_options) {
2372 case IMAGEX_COMMIT_OPTION:
2373 unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2375 case IMAGEX_CHECK_OPTION:
2376 unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2378 case IMAGEX_REBULID_OPTION:
2379 unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2393 ret = wimlib_unmount_image(argv[0], unmount_flags,
2394 imagex_progress_func);
2396 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2400 struct imagex_command {
2402 int (*func)(int , tchar **);
2407 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
2408 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
2410 static const struct imagex_command imagex_commands[] = {
2411 {T("append"), imagex_capture_or_append, APPEND},
2412 {T("apply"), imagex_apply, APPLY},
2413 {T("capture"), imagex_capture_or_append, CAPTURE},
2414 {T("delete"), imagex_delete, DELETE},
2415 {T("dir"), imagex_dir, DIR},
2416 {T("export"), imagex_export, EXPORT},
2417 {T("info"), imagex_info, INFO},
2418 {T("join"), imagex_join, JOIN},
2419 {T("mount"), imagex_mount_rw_or_ro, MOUNT},
2420 {T("mountrw"), imagex_mount_rw_or_ro, MOUNTRW},
2421 {T("optimize"),imagex_optimize, OPTIMIZE},
2422 {T("split"), imagex_split, SPLIT},
2423 {T("unmount"), imagex_unmount, UNMOUNT},
2429 static const tchar *s =
2431 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
2432 "Copyright (C) 2012, 2013 Eric Biggers\n"
2433 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
2434 "This is free software: you are free to change and redistribute it.\n"
2435 "There is NO WARRANTY, to the extent permitted by law.\n"
2437 "Report bugs to "PACKAGE_BUGREPORT".\n"
2444 help_or_version(int argc, tchar **argv)
2448 const struct imagex_command *cmd;
2450 for (i = 1; i < argc; i++) {
2458 if (!tstrcmp(p, T("help"))) {
2459 for_imagex_command(cmd) {
2460 if (!tstrcmp(cmd->name, argv[1])) {
2468 if (!tstrcmp(p, T("version"))) {
2479 const struct imagex_command *cmd;
2480 tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
2481 for_imagex_command(cmd) {
2482 if (cmd->cmd == cmd_type) {
2483 tprintf(T("\nTry `man "IMAGEX_PROGNAME"-%"TS"' "
2484 "for more details.\n"), cmd->name);
2492 tfputs(T("Usage:\n"), stdout);
2493 for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
2494 tprintf(T(" %"TS), usage_strings[i]);
2495 static const tchar *extra =
2497 " "IMAGEX_PROGNAME" --help\n"
2498 " "IMAGEX_PROGNAME" --version\n"
2500 " The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
2502 " Try `man "IMAGEX_PROGNAME"' for more information.\n"
2504 tfputs(extra, stdout);
2507 /* Entry point for wimlib's ImageX implementation. On UNIX the command
2508 * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
2509 * something else), while an Windows the command arguments will be UTF-16LE
2510 * encoded 'wchar_t' strings. */
2513 wmain(int argc, wchar_t **argv, wchar_t **envp)
2515 main(int argc, char **argv)
2518 const struct imagex_command *cmd;
2522 setlocale(LC_ALL, "");
2524 char *codeset = nl_langinfo(CODESET);
2525 if (!strstr(codeset, "UTF-8") &&
2526 !strstr(codeset, "UTF8") &&
2527 !strstr(codeset, "utf-8") &&
2528 !strstr(codeset, "utf8"))
2531 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
2532 " (Maybe try: `export LANG=en_US.UTF-8'?\n", stderr);
2536 #endif /* !__WIN32__ */
2539 imagex_error(T("No command specified"));
2545 /* Handle --help and --version for all commands. Note that this will
2546 * not return if either of these arguments are present. */
2547 help_or_version(argc, argv);
2551 /* The user may like to see more informative error messages. */
2552 wimlib_set_print_errors(true);
2554 /* Do any initializations that the library needs */
2555 ret = wimlib_global_init();
2557 goto out_check_status;
2559 /* Search for the function to handle the ImageX subcommand. */
2560 for_imagex_command(cmd) {
2561 if (!tstrcmp(cmd->name, *argv)) {
2562 ret = cmd->func(argc, argv);
2563 goto out_check_write_error;
2567 imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
2571 out_check_write_error:
2572 /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
2573 * standard output is part of the program's actual behavior and not just
2574 * for informational purposes, so we should set a failure exit status if
2575 * there was a write error. */
2576 if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
2577 if (ferror(stdout) || fclose(stdout)) {
2578 imagex_error_with_errno(T("error writing to standard output"));
2584 /* Exit status (ret): -1 indicates an error found by 'wimlib-imagex'
2585 * outside of the wimlib library code. 0 indicates success. > 0
2586 * indicates a wimlib error code from which an error message can be
2589 imagex_error(T("Exiting with error code %d:\n"
2591 wimlib_get_error_string(ret));
2592 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
2593 imagex_error_with_errno(T("errno"));
2596 /* Make the library free any resources it's holding (not strictly
2597 * necessary because the process is ending anyway). */
2598 wimlib_global_cleanup();