4 * Use wimlib to create, modify, extract, mount, unmount, or display information
9 * Copyright (C) 2012, 2013 Eric Biggers
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "wimlib_tchar.h"
47 # include "imagex-win32.h"
48 # define tbasename win32_wbasename
49 # define tglob win32_wglob
53 # include <langinfo.h>
54 # define tbasename basename
59 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
61 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
80 static void usage(int cmd_type);
81 static void usage_all();
84 static const tchar *usage_strings[] = {
87 IMAGEX_PROGNAME" append (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
88 " [DESCRIPTION] [--boot] [--check] [--flags EDITION_ID]\n"
89 " [--verbose] [--dereference] [--config=FILE]\n"
90 " [--threads=NUM_THREADS] [--rebuild] [--unix-data]\n"
91 " [--source-list] [--no-acls] [--strict-acls]\n"
92 " [--rpfix] [--norpfix]\n"
96 IMAGEX_PROGNAME" apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all]\n"
97 " (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
98 " [--symlink] [--verbose] [--ref=\"GLOB\"] [--unix-data]\n"
99 " [--no-acls] [--strict-acls]\n"
103 IMAGEX_PROGNAME" capture (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
104 " [DESCRIPTION] [--boot] [--check] [--compress=TYPE]\n"
105 " [--flags EDITION_ID] [--verbose] [--dereference]\n"
106 " [--config=FILE] [--threads=NUM_THREADS] [--unix-data]\n"
107 " [--source-list] [--no-acls] [--strict-acls]\n"
108 " [--rpfix] [--norpfix]\n"
112 IMAGEX_PROGNAME" delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n"
116 IMAGEX_PROGNAME" dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n"
120 IMAGEX_PROGNAME" export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
121 " DEST_WIMFILE [DEST_IMAGE_NAME] [DEST_IMAGE_DESCRIPTION]\n"
122 " [--boot] [--check] [--compress=TYPE] [--ref=\"GLOB\"]\n"
123 " [--threads=NUM_THREADS] [--rebuild]\n"
127 IMAGEX_PROGNAME" info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
128 " [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
129 " [--xml] [--extract-xml FILE] [--metadata]\n"
133 IMAGEX_PROGNAME" join [--check] WIMFILE SPLIT_WIM...\n"
137 IMAGEX_PROGNAME" mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
138 " [--check] [--debug] [--streams-interface=INTERFACE]\n"
139 " [--ref=\"GLOB\"] [--unix-data] [--allow-other]\n"
143 IMAGEX_PROGNAME" mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
144 " [--check] [--debug] [--streams-interface=INTERFACE]\n"
145 " [--staging-dir=DIR] [--unix-data] [--allow-other]\n"
149 IMAGEX_PROGNAME" optimize WIMFILE [--check] [--recompress]\n"
150 " [--threads=NUM_THREADS]\n"
154 IMAGEX_PROGNAME" split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n"
158 IMAGEX_PROGNAME" unmount DIRECTORY [--commit] [--check] [--rebuild]\n"
163 IMAGEX_ALLOW_OTHER_OPTION,
166 IMAGEX_COMMIT_OPTION,
167 IMAGEX_COMPRESS_OPTION,
168 IMAGEX_CONFIG_OPTION,
170 IMAGEX_DEREFERENCE_OPTION,
171 IMAGEX_EXTRACT_XML_OPTION,
173 IMAGEX_HARDLINK_OPTION,
174 IMAGEX_HEADER_OPTION,
175 IMAGEX_LOOKUP_TABLE_OPTION,
176 IMAGEX_METADATA_OPTION,
177 IMAGEX_NO_ACLS_OPTION,
178 IMAGEX_NORPFIX_OPTION,
179 IMAGEX_REBULID_OPTION,
180 IMAGEX_RECOMPRESS_OPTION,
184 IMAGEX_SOURCE_LIST_OPTION,
185 IMAGEX_STAGING_DIR_OPTION,
186 IMAGEX_STREAMS_INTERFACE_OPTION,
187 IMAGEX_STRICT_ACLS_OPTION,
188 IMAGEX_SYMLINK_OPTION,
189 IMAGEX_THREADS_OPTION,
190 IMAGEX_UNIX_DATA_OPTION,
191 IMAGEX_VERBOSE_OPTION,
195 static const struct option apply_options[] = {
196 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
197 {T("hardlink"), no_argument, NULL, IMAGEX_HARDLINK_OPTION},
198 {T("symlink"), no_argument, NULL, IMAGEX_SYMLINK_OPTION},
199 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
200 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
201 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
202 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
203 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
204 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
207 static const struct option capture_or_append_options[] = {
208 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
209 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
210 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
211 {T("config"), required_argument, NULL, IMAGEX_CONFIG_OPTION},
212 {T("dereference"), no_argument, NULL, IMAGEX_DEREFERENCE_OPTION},
213 {T("flags"), required_argument, NULL, IMAGEX_FLAGS_OPTION},
214 {T("verbose"), no_argument, NULL, IMAGEX_VERBOSE_OPTION},
215 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
216 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
217 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
218 {T("source-list"), no_argument, NULL, IMAGEX_SOURCE_LIST_OPTION},
219 {T("noacls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
220 {T("no-acls"), no_argument, NULL, IMAGEX_NO_ACLS_OPTION},
221 {T("strict-acls"), no_argument, NULL, IMAGEX_STRICT_ACLS_OPTION},
222 {T("rpfix"), no_argument, NULL, IMAGEX_RPFIX_OPTION},
223 {T("norpfix"), no_argument, NULL, IMAGEX_NORPFIX_OPTION},
226 static const struct option delete_options[] = {
227 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
228 {T("soft"), no_argument, NULL, IMAGEX_SOFT_OPTION},
232 static const struct option export_options[] = {
233 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
234 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
235 {T("compress"), required_argument, NULL, IMAGEX_COMPRESS_OPTION},
236 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
237 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
238 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
242 static const struct option info_options[] = {
243 {T("boot"), no_argument, NULL, IMAGEX_BOOT_OPTION},
244 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
245 {T("extract-xml"), required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
246 {T("header"), no_argument, NULL, IMAGEX_HEADER_OPTION},
247 {T("lookup-table"), no_argument, NULL, IMAGEX_LOOKUP_TABLE_OPTION},
248 {T("metadata"), no_argument, NULL, IMAGEX_METADATA_OPTION},
249 {T("xml"), no_argument, NULL, IMAGEX_XML_OPTION},
253 static const struct option join_options[] = {
254 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
258 static const struct option mount_options[] = {
259 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
260 {T("debug"), no_argument, NULL, IMAGEX_DEBUG_OPTION},
261 {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
262 {T("ref"), required_argument, NULL, IMAGEX_REF_OPTION},
263 {T("staging-dir"), required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
264 {T("unix-data"), no_argument, NULL, IMAGEX_UNIX_DATA_OPTION},
265 {T("allow-other"), no_argument, NULL, IMAGEX_ALLOW_OTHER_OPTION},
269 static const struct option optimize_options[] = {
270 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
271 {T("recompress"), no_argument, NULL, IMAGEX_RECOMPRESS_OPTION},
272 {T("threads"), required_argument, NULL, IMAGEX_THREADS_OPTION},
276 static const struct option split_options[] = {
277 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
281 static const struct option unmount_options[] = {
282 {T("commit"), no_argument, NULL, IMAGEX_COMMIT_OPTION},
283 {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
284 {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
290 /* Print formatted error message to stderr. */
292 imagex_error(const tchar *format, ...)
295 va_start(va, format);
296 tfputs(T("ERROR: "), stderr);
297 tvfprintf(stderr, format, va);
298 tputc(T('\n'), stderr);
302 /* Print formatted error message to stderr. */
304 imagex_error_with_errno(const tchar *format, ...)
306 int errno_save = errno;
308 va_start(va, format);
309 tfputs(T("ERROR: "), stderr);
310 tvfprintf(stderr, format, va);
311 tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
316 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
318 if (image == WIMLIB_NO_IMAGE) {
319 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
320 " Please specify a 1-based image index or "
322 " You may use `"IMAGEX_PROGNAME" info' to list the images "
323 "contained in a WIM."),
324 image_name, wim_name);
331 verify_image_is_single(int image)
333 if (image == WIMLIB_ALL_IMAGES) {
334 imagex_error(T("Cannot specify all images for this action!"));
341 verify_image_exists_and_is_single(int image, const tchar *image_name,
342 const tchar *wim_name)
345 ret = verify_image_exists(image, image_name, wim_name);
347 ret = verify_image_is_single(image);
351 /* Parse the argument to --compress */
353 get_compression_type(const tchar *optarg)
355 if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
356 return WIMLIB_COMPRESSION_TYPE_LZX;
357 else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
358 return WIMLIB_COMPRESSION_TYPE_XPRESS;
359 else if (!tstrcasecmp(optarg, T("none")))
360 return WIMLIB_COMPRESSION_TYPE_NONE;
362 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
363 "\"maximum\", \"fast\", or \"none\"."), optarg);
364 return WIMLIB_COMPRESSION_TYPE_INVALID;
368 /* Returns the size of a file given its name, or -1 if the file does not exist
369 * or its size cannot be determined. */
371 file_get_size(const tchar *filename)
374 if (tstat(filename, &st) == 0)
380 tchar pat_ntfs_log[] = T("/$ntfs.log");
381 tchar pat_hiberfil_sys[] = T("/hiberfil.sys");
382 tchar pat_pagefile_sys[] = T("/pagefile.sys");
383 tchar pat_system_volume_information[] = T("/System Volume Information");
384 tchar pat_recycler[] = T("/RECYCLER");
385 tchar pat_windows_csc[] = T("/Windows/CSC");
387 tchar *default_pats[] = {
391 pat_system_volume_information,
396 static struct wimlib_capture_config default_capture_config = {
398 .num_pats = sizeof(default_pats) / sizeof(*default_pats),
399 .pats = default_pats,
404 PARSE_FILENAME_SUCCESS = 0,
405 PARSE_FILENAME_FAILURE = 1,
406 PARSE_FILENAME_NONE = 2,
410 * Parses a filename in the source list file format. (See the man page for
411 * 'wimlib-imagex capture' for details on this format and the meaning.)
412 * Accepted formats for filenames are an unquoted string (whitespace-delimited),
413 * or a double or single-quoted string.
415 * @line_p: Pointer to the pointer to the line of data. Will be updated
416 * to point past the filename iff the return value is
417 * PARSE_FILENAME_SUCCESS. If *len_p > 0, (*line_p)[*len_p - 1] must
420 * @len_p: @len_p initially stores the length of the line of data, which may
421 * be 0, and it will be updated to the number of bytes remaining in
422 * the line iff the return value is PARSE_FILENAME_SUCCESS.
424 * @fn_ret: Iff the return value is PARSE_FILENAME_SUCCESS, a pointer to the
425 * parsed filename will be returned here.
427 * Returns: PARSE_FILENAME_SUCCESS if a filename was successfully parsed; or
428 * PARSE_FILENAME_FAILURE if the data was invalid due to a missing
429 * closing quote; or PARSE_FILENAME_NONE if the line ended before the
430 * beginning of a filename was found.
433 parse_filename(tchar **line_p, size_t *len_p, tchar **fn_ret)
436 tchar *line = *line_p;
440 /* Skip leading whitespace */
443 return PARSE_FILENAME_NONE;
444 if (!istspace(*line) && *line != T('\0'))
450 if (quote_char == T('"') || quote_char == T('\'')) {
451 /* Quoted filename */
455 line = tmemchr(line, quote_char, len);
457 imagex_error(T("Missing closing quote: %"TS), fn - 1);
458 return PARSE_FILENAME_FAILURE;
461 /* Unquoted filename. Go until whitespace. Line is terminated
462 * by '\0', so no need to check 'len'. */
466 } while (!istspace(*line) && *line != T('\0'));
473 return PARSE_FILENAME_SUCCESS;
476 /* Parses a line of data (not an empty line or comment) in the source list file
477 * format. (See the man page for 'wimlib-imagex capture' for details on this
478 * format and the meaning.)
480 * @line: Line of data to be parsed. line[len - 1] must be '\0', unless
481 * len == 0. The data in @line will be modified by this function call.
483 * @len: Length of the line of data.
485 * @source: On success, the capture source and target described by the line is
486 * written into this destination. Note that it will contain pointers
487 * to data in the @line array.
489 * Returns true if the line was valid; false otherwise. */
491 parse_source_list_line(tchar *line, size_t len,
492 struct wimlib_capture_source *source)
496 ret = parse_filename(&line, &len, &source->fs_source_path);
497 if (ret != PARSE_FILENAME_SUCCESS)
499 ret = parse_filename(&line, &len, &source->wim_target_path);
500 if (ret == PARSE_FILENAME_NONE)
501 source->wim_target_path = source->fs_source_path;
502 return ret != PARSE_FILENAME_FAILURE;
505 /* Returns %true if the given line of length @len > 0 is a comment or empty line
506 * in the source list file format. */
508 is_comment_line(const tchar *line, size_t len)
513 if (!istspace(*line) && *line != T('\0'))
523 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
526 tchar *contents = *contents_p;
527 size_t nchars = *nchars_p;
530 for (i = 0; i < nchars; i++)
531 if (contents[i] == T('\n'))
534 /* Handle last line not terminated by a newline */
535 if (nchars != 0 && contents[nchars - 1] != T('\n')) {
536 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
538 imagex_error(T("Out of memory!"));
541 contents[nchars] = T('\n');
542 *contents_p = contents;
550 /* Parses a file in the source list format. (See the man page for
551 * 'wimlib-imagex capture' for details on this format and the meaning.)
553 * @source_list_contents: Contents of the source list file. Note that this
554 * buffer will be modified to save memory allocations,
555 * and cannot be freed until the returned array of
556 * wimlib_capture_source's has also been freed.
558 * @source_list_nbytes: Number of bytes of data in the @source_list_contents
561 * @nsources_ret: On success, the length of the returned array is
564 * Returns: An array of `struct wimlib_capture_source's that can be passed to
565 * the wimlib_add_image_multisource() function to specify how a WIM image is to
567 static struct wimlib_capture_source *
568 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
569 size_t *nsources_ret)
573 struct wimlib_capture_source *sources;
576 nlines = text_file_count_lines(source_list_contents_p,
577 &source_list_nchars);
581 /* Always allocate at least 1 slot, just in case the implementation of
582 * calloc() returns NULL if 0 bytes are requested. */
583 sources = calloc(nlines ?: 1, sizeof(*sources));
585 imagex_error(T("out of memory"));
588 p = *source_list_contents_p;
590 for (i = 0; i < nlines; i++) {
591 /* XXX: Could use rawmemchr() here instead, but it may not be
592 * available on all platforms. */
593 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
594 size_t len = endp - p + 1;
596 if (!is_comment_line(p, len)) {
597 if (!parse_source_list_line(p, len, &sources[j++])) {
610 enum capture_config_section {
611 CAPTURE_CONFIG_NO_SECTION,
612 CAPTURE_CONFIG_EXCLUSION_SECTION,
613 CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
614 CAPTURE_CONFIG_IGNORE_SECTION,
618 CAPTURE_CONFIG_INVALID_SECTION,
619 CAPTURE_CONFIG_CHANGED_SECTION,
620 CAPTURE_CONFIG_SAME_SECTION,
624 check_config_section(tchar *line, size_t len,
625 enum capture_config_section *cur_section)
627 while (istspace(*line))
631 return CAPTURE_CONFIG_SAME_SECTION;
634 tchar *endbrace = tstrrchr(line, T(']'));
636 return CAPTURE_CONFIG_SAME_SECTION;
638 if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
639 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
640 } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
641 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
642 } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
643 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
644 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
645 "of capture config file\n"),
647 } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
648 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
649 tfputs(T("WARNING: Ignoring [AlignmentList] section "
650 "of capture config file\n"),
653 imagex_error(T("Invalid capture config file section \"%"TS"\""),
655 return CAPTURE_CONFIG_INVALID_SECTION;
657 return CAPTURE_CONFIG_CHANGED_SECTION;
662 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
665 if (pat_list->num_pats == pat_list->num_allocated_pats) {
667 size_t num_allocated_pats = pat_list->num_pats + 8;
669 pats = realloc(pat_list->pats,
670 num_allocated_pats * sizeof(pat_list->pats[0]));
672 imagex_error(T("Out of memory!"));
675 pat_list->pats = pats;
676 pat_list->num_allocated_pats = num_allocated_pats;
678 pat_list->pats[pat_list->num_pats++] = pat;
683 parse_capture_config_line(tchar *line, size_t len,
684 enum capture_config_section *cur_section,
685 struct wimlib_capture_config *config)
690 ret = check_config_section(line, len, cur_section);
691 if (ret == CAPTURE_CONFIG_INVALID_SECTION)
693 if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
696 switch (*cur_section) {
697 case CAPTURE_CONFIG_NO_SECTION:
698 imagex_error(T("Line \"%"TS"\" is not in a section "
699 "(such as [ExclusionList]"), line);
701 case CAPTURE_CONFIG_EXCLUSION_SECTION:
702 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
704 return pattern_list_add_pattern(&config->exclusion_pats,
706 case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
707 if (parse_filename(&line, &len, &filename) != PARSE_FILENAME_SUCCESS)
709 return pattern_list_add_pattern(&config->exclusion_exception_pats,
711 case CAPTURE_CONFIG_IGNORE_SECTION:
718 parse_capture_config(tchar **contents_p, size_t nchars,
719 struct wimlib_capture_config *config)
724 enum capture_config_section cur_section;
726 memset(config, 0, sizeof(*config));
728 nlines = text_file_count_lines(contents_p, &nchars);
732 cur_section = CAPTURE_CONFIG_NO_SECTION;
734 for (i = 0; i < nlines; i++) {
735 tchar *endp = tmemchr(p, T('\n'), nchars);
736 size_t len = endp - p + 1;
738 if (!is_comment_line(p, len))
739 if (!parse_capture_config_line(p, len, &cur_section, config))
747 /* Reads the contents of a file into memory. */
749 file_get_contents(const tchar *filename, size_t *len_ret)
756 if (tstat(filename, &stbuf) != 0) {
757 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
762 fp = tfopen(filename, T("rb"));
764 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
770 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
771 "contents of file \"%"TS"\""), len, filename);
774 if (fread(buf, 1, len, fp) != len) {
775 imagex_error_with_errno(T("Failed to read %zu bytes from the "
776 "file \"%"TS"\""), len, filename);
790 /* Read standard input until EOF and return the full contents in a malloc()ed
791 * buffer and the number of bytes of data in @len_ret. Returns NULL on read
794 stdin_get_contents(size_t *len_ret)
796 /* stdin can, of course, be a pipe or other non-seekable file, so the
797 * total length of the data cannot be pre-determined */
799 size_t newlen = 1024;
803 char *p = realloc(buf, newlen);
804 size_t bytes_read, bytes_to_read;
806 imagex_error(T("out of memory while reading stdin"));
810 bytes_to_read = newlen - pos;
811 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
813 if (bytes_read != bytes_to_read) {
818 imagex_error_with_errno(T("error reading stdin"));
832 translate_text_to_tstr(char *text, size_t num_bytes,
833 size_t *num_tchars_ret)
836 /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
838 *num_tchars_ret = num_bytes;
840 #else /* !__WIN32__ */
841 /* On Windows, translate the text to UTF-16LE */
845 if (num_bytes >= 2 &&
846 ((text[0] == 0xff && text[1] == 0xfe) ||
847 (text[0] <= 0x7f && text[1] == 0x00)))
849 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
850 * with something that looks like an ASCII character encoded as
851 * a UTF-16LE code unit. Assume the file is encoded as
852 * UTF-16LE. This is not a 100% reliable check. */
853 num_wchars = num_bytes / 2;
854 text_wstr = (wchar_t*)text;
856 /* File does not look like UTF-16LE. Assume it is encoded in
857 * the current Windows code page. I think these are always
858 * ASCII-compatible, so any so-called "plain-text" (ASCII) files
859 * should work as expected. */
860 text_wstr = win32_mbs_to_wcs(text,
865 *num_tchars_ret = num_wchars;
867 #endif /* __WIN32__ */
871 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
876 contents = file_get_contents(filename, &num_bytes);
879 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
883 stdin_get_text_contents(size_t *num_tchars_ret)
888 contents = stdin_get_contents(&num_bytes);
891 return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
894 /* Return 0 if a path names a file to which the current user has write access;
895 * -1 otherwise (and print an error message). */
897 file_writable(const tchar *path)
900 ret = taccess(path, W_OK);
902 imagex_error_with_errno(T("Can't modify \"%"TS"\""), path);
906 #define TO_PERCENT(numerator, denominator) \
907 (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
909 /* Given an enumerated value for WIM compression type, return a descriptive
912 get_data_type(int ctype)
915 case WIMLIB_COMPRESSION_TYPE_NONE:
916 return T("uncompressed");
917 case WIMLIB_COMPRESSION_TYPE_LZX:
918 return T("LZX-compressed");
919 case WIMLIB_COMPRESSION_TYPE_XPRESS:
920 return T("XPRESS-compressed");
925 /* Progress callback function passed to various wimlib functions. */
927 imagex_progress_func(enum wimlib_progress_msg msg,
928 const union wimlib_progress_info *info)
930 unsigned percent_done;
932 case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
933 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
934 info->write_streams.total_bytes);
935 if (info->write_streams.completed_streams == 0) {
936 const tchar *data_type;
938 data_type = get_data_type(info->write_streams.compression_type);
939 tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
940 data_type, info->write_streams.num_threads,
941 (info->write_streams.num_threads == 1) ? T("") : T("s"));
943 tprintf(T("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
944 "written (%u%% done)"),
945 info->write_streams.completed_bytes >> 20,
946 info->write_streams.total_bytes >> 20,
948 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
951 case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
952 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
953 if (*info->scan.wim_target_path) {
954 tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
955 info->scan.wim_target_path);
957 tprintf(T(" (loading as root of WIM image)...\n"));
960 case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
961 if (info->scan.excluded)
962 tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
964 tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
966 /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
968 case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
969 percent_done = TO_PERCENT(info->integrity.completed_bytes,
970 info->integrity.total_bytes);
971 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" MiB "
972 "of %"PRIu64" MiB (%u%%) done"),
973 info->integrity.filename,
974 info->integrity.completed_bytes >> 20,
975 info->integrity.total_bytes >> 20,
977 if (info->integrity.completed_bytes == info->integrity.total_bytes)
980 case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
981 percent_done = TO_PERCENT(info->integrity.completed_bytes,
982 info->integrity.total_bytes);
983 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" MiB "
984 "of %"PRIu64" MiB (%u%%) done"),
985 info->integrity.completed_bytes >> 20,
986 info->integrity.total_bytes >> 20,
988 if (info->integrity.completed_bytes == info->integrity.total_bytes)
991 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
992 tprintf(T("Applying image %d (%"TS") from \"%"TS"\" "
993 "to %"TS" \"%"TS"\"\n"),
995 info->extract.image_name,
996 info->extract.wimfile_name,
997 ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
998 T("NTFS volume") : T("directory")),
999 info->extract.target);
1001 /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
1002 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
1003 /*info->extract.target);*/
1005 case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1006 percent_done = TO_PERCENT(info->extract.completed_bytes,
1007 info->extract.total_bytes);
1008 tprintf(T("\rExtracting files: "
1009 "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done"),
1010 info->extract.completed_bytes >> 20,
1011 info->extract.total_bytes >> 20,
1013 if (info->extract.completed_bytes >= info->extract.total_bytes)
1016 case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
1017 tprintf(T("%"TS"\n"), info->extract.cur_path);
1019 case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1020 tprintf(T("Setting timestamps on all extracted files...\n"));
1022 case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1023 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1024 tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1025 info->extract.target);
1028 case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
1029 percent_done = TO_PERCENT(info->join.completed_bytes,
1030 info->join.total_bytes);
1031 tprintf(T("Writing resources from part %u of %u: "
1032 "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n"),
1033 (info->join.completed_parts == info->join.total_parts) ?
1034 info->join.completed_parts : info->join.completed_parts + 1,
1035 info->join.total_parts,
1036 info->join.completed_bytes >> 20,
1037 info->join.total_bytes >> 20,
1040 case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1041 percent_done = TO_PERCENT(info->split.completed_bytes,
1042 info->split.total_bytes);
1043 tprintf(T("Writing \"%"TS"\": %"PRIu64" MiB of "
1044 "%"PRIu64" MiB (%u%%) written\n"),
1045 info->split.part_name,
1046 info->split.completed_bytes >> 20,
1047 info->split.total_bytes >> 20,
1050 case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1051 if (info->split.completed_bytes == info->split.total_bytes) {
1052 tprintf(T("Finished writing %u split WIM parts\n"),
1053 info->split.cur_part_number);
1063 /* Open all the split WIM parts that correspond to a file glob.
1065 * @first_part specifies the first part of the split WIM and it may be either
1066 * included or omitted from the glob. */
1068 open_swms_from_glob(const tchar *swm_glob,
1069 const tchar *first_part,
1071 WIMStruct ***additional_swms_ret,
1072 unsigned *num_additional_swms_ret)
1074 unsigned num_additional_swms = 0;
1075 WIMStruct **additional_swms = NULL;
1079 /* Warning: glob() is replaced in Windows native builds */
1080 ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1082 if (ret == GLOB_NOMATCH) {
1083 imagex_error(T("Found no files for glob \"%"TS"\""),
1086 imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1092 num_additional_swms = globbuf.gl_pathc;
1093 additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1094 if (!additional_swms) {
1095 imagex_error(T("Out of memory"));
1099 unsigned offset = 0;
1100 for (unsigned i = 0; i < num_additional_swms; i++) {
1101 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1105 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1106 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1107 &additional_swms[i - offset],
1108 imagex_progress_func);
1110 goto out_close_swms;
1112 *additional_swms_ret = additional_swms;
1113 *num_additional_swms_ret = num_additional_swms - offset;
1117 for (unsigned i = 0; i < num_additional_swms; i++)
1118 wimlib_free(additional_swms[i]);
1119 free(additional_swms);
1128 parse_num_threads(const tchar *optarg)
1131 unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1132 if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1133 imagex_error(T("Number of threads must be a non-negative integer!"));
1141 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1142 * one image from a WIM file to a NTFS volume. */
1144 imagex_apply(int argc, tchar **argv)
1147 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1152 const tchar *wimfile;
1153 const tchar *target;
1154 const tchar *image_num_or_name;
1155 int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1157 const tchar *swm_glob = NULL;
1158 WIMStruct **additional_swms = NULL;
1159 unsigned num_additional_swms = 0;
1161 for_opt(c, apply_options) {
1163 case IMAGEX_CHECK_OPTION:
1164 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1166 case IMAGEX_HARDLINK_OPTION:
1167 extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1169 case IMAGEX_SYMLINK_OPTION:
1170 extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1172 case IMAGEX_VERBOSE_OPTION:
1173 extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1175 case IMAGEX_REF_OPTION:
1178 case IMAGEX_UNIX_DATA_OPTION:
1179 extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1181 case IMAGEX_NO_ACLS_OPTION:
1182 extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1184 case IMAGEX_STRICT_ACLS_OPTION:
1185 extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1194 if (argc != 2 && argc != 3) {
1201 image_num_or_name = T("1");
1204 image_num_or_name = argv[1];
1208 ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1212 image = wimlib_resolve_image(w, image_num_or_name);
1213 ret = verify_image_exists(image, image_num_or_name, wimfile);
1217 num_images = wimlib_get_num_images(w);
1218 if (argc == 2 && num_images != 1) {
1219 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1220 "(or all)"), wimfile, num_images);
1227 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1229 &num_additional_swms);
1236 ret = tstat(target, &stbuf);
1238 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1239 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1241 if (errno != ENOENT) {
1242 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1250 win32_acquire_restore_privileges();
1252 ret = wimlib_extract_image(w, image, target, extract_flags,
1253 additional_swms, num_additional_swms,
1254 imagex_progress_func);
1256 tprintf(T("Done applying WIM image.\n"));
1258 win32_release_restore_privileges();
1262 if (additional_swms) {
1263 for (unsigned i = 0; i < num_additional_swms; i++)
1264 wimlib_free(additional_swms[i]);
1265 free(additional_swms);
1270 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1271 * directory trees. 'wimlib-imagex capture': create a new WIM file containing
1272 * the desired image. 'wimlib-imagex append': add a new image to an existing
1275 imagex_capture_or_append(int argc, tchar **argv)
1279 int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
1280 int write_flags = 0;
1281 int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1282 const tchar *wimfile;
1285 const tchar *flags_element = NULL;
1289 int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1290 unsigned num_threads = 0;
1293 size_t source_name_len;
1296 const tchar *config_file = NULL;
1298 struct wimlib_capture_config *config = NULL;
1300 bool source_list = false;
1301 size_t source_list_nchars;
1302 tchar *source_list_contents;
1303 bool capture_sources_malloced;
1304 struct wimlib_capture_source *capture_sources;
1307 for_opt(c, capture_or_append_options) {
1309 case IMAGEX_BOOT_OPTION:
1310 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1312 case IMAGEX_CHECK_OPTION:
1313 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1314 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1316 case IMAGEX_CONFIG_OPTION:
1317 config_file = optarg;
1319 case IMAGEX_COMPRESS_OPTION:
1320 compression_type = get_compression_type(optarg);
1321 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1324 case IMAGEX_FLAGS_OPTION:
1325 flags_element = optarg;
1327 case IMAGEX_DEREFERENCE_OPTION:
1328 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1330 case IMAGEX_VERBOSE_OPTION:
1331 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1333 case IMAGEX_THREADS_OPTION:
1334 num_threads = parse_num_threads(optarg);
1335 if (num_threads == UINT_MAX)
1338 case IMAGEX_REBULID_OPTION:
1339 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1341 case IMAGEX_UNIX_DATA_OPTION:
1342 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1344 case IMAGEX_SOURCE_LIST_OPTION:
1347 case IMAGEX_NO_ACLS_OPTION:
1348 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1350 case IMAGEX_STRICT_ACLS_OPTION:
1351 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1353 case IMAGEX_RPFIX_OPTION:
1354 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1356 case IMAGEX_NORPFIX_OPTION:
1357 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1367 if (argc < 2 || argc > 4) {
1378 /* Set default name to SOURCE argument, omitting any directory
1379 * prefixes and trailing slashes. This requires making a copy
1381 source_name_len = tstrlen(source);
1382 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1383 name = tbasename(tstrcpy(source_copy, source));
1385 /* Image description defaults to NULL if not given. */
1386 desc = (argc >= 4) ? argv[3] : NULL;
1389 /* Set up capture sources in source list mode */
1390 if (source[0] == T('-') && source[1] == T('\0')) {
1391 source_list_contents = stdin_get_text_contents(&source_list_nchars);
1393 source_list_contents = file_get_text_contents(source,
1394 &source_list_nchars);
1396 if (!source_list_contents)
1399 capture_sources = parse_source_list(&source_list_contents,
1402 if (!capture_sources) {
1404 goto out_free_source_list_contents;
1406 capture_sources_malloced = true;
1408 /* Set up capture source in non-source-list mode (could be
1409 * either "normal" mode or "NTFS mode"--- see the man page). */
1410 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1411 capture_sources[0].fs_source_path = source;
1412 capture_sources[0].wim_target_path = NULL;
1413 capture_sources[0].reserved = 0;
1415 capture_sources_malloced = false;
1416 source_list_contents = NULL;
1422 config_str = file_get_text_contents(config_file, &config_len);
1425 goto out_free_capture_sources;
1428 config = alloca(sizeof(*config));
1429 ret = parse_capture_config(&config_str, config_len, config);
1431 goto out_free_config;
1433 config = &default_capture_config;
1437 ret = wimlib_open_wim(wimfile, open_flags, &w,
1438 imagex_progress_func);
1440 ret = wimlib_create_new_wim(compression_type, &w);
1442 goto out_free_config;
1446 ret = tstat(source, &stbuf);
1448 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1449 tprintf(T("Capturing WIM image from NTFS "
1450 "filesystem on \"%"TS"\"\n"), source);
1451 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1454 if (errno != ENOENT) {
1455 imagex_error_with_errno(T("Failed to stat "
1456 "\"%"TS"\""), source);
1458 goto out_wimlib_free;
1463 win32_acquire_capture_privileges();
1466 ret = wimlib_add_image_multisource(w,
1472 imagex_progress_func);
1474 goto out_release_privs;
1475 cur_image = wimlib_get_num_images(w);
1477 ret = wimlib_set_image_descripton(w, cur_image, desc);
1479 goto out_release_privs;
1481 if (flags_element) {
1482 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1484 goto out_release_privs;
1486 if (cmd == APPEND) {
1487 ret = wimlib_overwrite(w, write_flags, num_threads,
1488 imagex_progress_func);
1490 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1491 num_threads, imagex_progress_func);
1493 if (ret == WIMLIB_ERR_REOPEN)
1496 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1500 win32_release_capture_privileges();
1505 if (config != NULL && config != &default_capture_config) {
1506 free(config->exclusion_pats.pats);
1507 free(config->exclusion_exception_pats.pats);
1510 out_free_capture_sources:
1511 if (capture_sources_malloced)
1512 free(capture_sources);
1513 out_free_source_list_contents:
1514 free(source_list_contents);
1518 /* Remove image(s) from a WIM. */
1520 imagex_delete(int argc, tchar **argv)
1524 int write_flags = 0;
1525 const tchar *wimfile;
1526 const tchar *image_num_or_name;
1531 for_opt(c, delete_options) {
1533 case IMAGEX_CHECK_OPTION:
1534 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1535 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1537 case IMAGEX_SOFT_OPTION:
1538 write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1550 imagex_error(T("Must specify a WIM file"));
1552 imagex_error(T("Must specify an image"));
1557 image_num_or_name = argv[1];
1559 ret = file_writable(wimfile);
1563 ret = wimlib_open_wim(wimfile, open_flags, &w,
1564 imagex_progress_func);
1568 image = wimlib_resolve_image(w, image_num_or_name);
1570 ret = verify_image_exists(image, image_num_or_name, wimfile);
1574 ret = wimlib_delete_image(w, image);
1576 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1580 ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1581 if (ret == WIMLIB_ERR_REOPEN)
1584 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1585 "deleted"), wimfile);
1592 /* Print the files contained in an image(s) in a WIM file. */
1594 imagex_dir(int argc, tchar **argv)
1596 const tchar *wimfile;
1603 imagex_error(T("Must specify a WIM file"));
1608 imagex_error(T("Too many arguments"));
1614 ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1615 imagex_progress_func);
1620 image = wimlib_resolve_image(w, argv[2]);
1621 ret = verify_image_exists(image, argv[2], wimfile);
1625 /* Image was not specified. If the WIM only contains one image,
1626 * choose that one; otherwise, print an error. */
1627 num_images = wimlib_get_num_images(w);
1628 if (num_images != 1) {
1629 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
1630 "select one."), wimfile, num_images);
1638 ret = wimlib_print_files(w, image);
1644 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1647 imagex_export(int argc, tchar **argv)
1651 int export_flags = 0;
1652 int write_flags = 0;
1653 int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1654 bool compression_type_specified = false;
1655 const tchar *src_wimfile;
1656 const tchar *src_image_num_or_name;
1657 const tchar *dest_wimfile;
1658 const tchar *dest_name;
1659 const tchar *dest_desc;
1660 WIMStruct *src_w = NULL;
1661 WIMStruct *dest_w = NULL;
1666 const tchar *swm_glob = NULL;
1667 WIMStruct **additional_swms = NULL;
1668 unsigned num_additional_swms = 0;
1669 unsigned num_threads = 0;
1671 for_opt(c, export_options) {
1673 case IMAGEX_BOOT_OPTION:
1674 export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
1676 case IMAGEX_CHECK_OPTION:
1677 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1678 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1680 case IMAGEX_COMPRESS_OPTION:
1681 compression_type = get_compression_type(optarg);
1682 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1684 compression_type_specified = true;
1686 case IMAGEX_REF_OPTION:
1689 case IMAGEX_THREADS_OPTION:
1690 num_threads = parse_num_threads(optarg);
1691 if (num_threads == UINT_MAX)
1694 case IMAGEX_REBULID_OPTION:
1695 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1704 if (argc < 3 || argc > 5) {
1708 src_wimfile = argv[0];
1709 src_image_num_or_name = argv[1];
1710 dest_wimfile = argv[2];
1711 dest_name = (argc >= 4) ? argv[3] : NULL;
1712 dest_desc = (argc >= 5) ? argv[4] : NULL;
1713 ret = wimlib_open_wim(src_wimfile,
1714 open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
1715 imagex_progress_func);
1719 /* Determine if the destination is an existing file or not.
1720 * If so, we try to append the exported image(s) to it; otherwise, we
1721 * create a new WIM containing the exported image(s). */
1722 if (tstat(dest_wimfile, &stbuf) == 0) {
1726 /* Destination file exists. */
1728 if (!S_ISREG(stbuf.st_mode)) {
1729 imagex_error(T("\"%"TS"\" is not a regular file"),
1734 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1735 imagex_progress_func);
1739 ret = file_writable(dest_wimfile);
1743 dest_ctype = wimlib_get_compression_type(dest_w);
1744 if (compression_type_specified
1745 && compression_type != dest_ctype)
1747 imagex_error(T("Cannot specify a compression type that is "
1748 "not the same as that used in the "
1749 "destination WIM"));
1755 /* dest_wimfile is not an existing file, so create a new WIM. */
1756 if (!compression_type_specified)
1757 compression_type = wimlib_get_compression_type(src_w);
1758 if (errno == ENOENT) {
1759 ret = wimlib_create_new_wim(compression_type, &dest_w);
1763 imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
1770 image = wimlib_resolve_image(src_w, src_image_num_or_name);
1771 ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1776 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1778 &num_additional_swms);
1783 ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1784 export_flags, additional_swms,
1785 num_additional_swms, imagex_progress_func);
1791 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1792 write_flags, num_threads,
1793 imagex_progress_func);
1795 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1796 imagex_progress_func);
1798 if (ret == WIMLIB_ERR_REOPEN)
1801 wimlib_free(dest_w);
1802 if (additional_swms) {
1803 for (unsigned i = 0; i < num_additional_swms; i++)
1804 wimlib_free(additional_swms[i]);
1805 free(additional_swms);
1810 /* Prints information about a WIM file; also can mark an image as bootable,
1811 * change the name of an image, or change the description of an image. */
1813 imagex_info(int argc, tchar **argv)
1818 bool header = false;
1819 bool lookup_table = false;
1821 bool metadata = false;
1822 bool short_header = true;
1823 const tchar *xml_out_file = NULL;
1824 const tchar *wimfile;
1825 const tchar *image_num_or_name = T("all");
1826 const tchar *new_name = NULL;
1827 const tchar *new_desc = NULL;
1832 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1837 for_opt(c, info_options) {
1839 case IMAGEX_BOOT_OPTION:
1842 case IMAGEX_CHECK_OPTION:
1845 case IMAGEX_HEADER_OPTION:
1847 short_header = false;
1849 case IMAGEX_LOOKUP_TABLE_OPTION:
1850 lookup_table = true;
1851 short_header = false;
1853 case IMAGEX_XML_OPTION:
1855 short_header = false;
1857 case IMAGEX_EXTRACT_XML_OPTION:
1858 xml_out_file = optarg;
1859 short_header = false;
1861 case IMAGEX_METADATA_OPTION:
1863 short_header = false;
1873 if (argc == 0 || argc > 4) {
1879 image_num_or_name = argv[1];
1889 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1891 ret = wimlib_open_wim(wimfile, open_flags, &w,
1892 imagex_progress_func);
1896 part_number = wimlib_get_part_number(w, &total_parts);
1898 image = wimlib_resolve_image(w, image_num_or_name);
1899 if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
1900 imagex_error(T("The image \"%"TS"\" does not exist"),
1903 imagex_error(T("If you would like to set the boot "
1904 "index to 0, specify image \"0\" with "
1905 "the --boot flag."));
1907 ret = WIMLIB_ERR_INVALID_IMAGE;
1911 num_images = wimlib_get_num_images(w);
1913 if (num_images == 0) {
1915 imagex_error(T("--boot is meaningless on a WIM with no "
1917 ret = WIMLIB_ERR_INVALID_IMAGE;
1922 if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1924 imagex_error(T("Cannot specify the --boot flag "
1925 "without specifying a specific "
1926 "image in a multi-image WIM"));
1927 ret = WIMLIB_ERR_INVALID_IMAGE;
1931 imagex_error(T("Cannot specify the NEW_NAME "
1932 "without specifying a specific "
1933 "image in a multi-image WIM"));
1934 ret = WIMLIB_ERR_INVALID_IMAGE;
1939 /* Operations that print information are separated from operations that
1940 * recreate the WIM file. */
1941 if (!new_name && !boot) {
1943 /* Read-only operations */
1945 if (image == WIMLIB_NO_IMAGE) {
1946 imagex_error(T("\"%"TS"\" is not a valid image"),
1948 ret = WIMLIB_ERR_INVALID_IMAGE;
1952 if (image == WIMLIB_ALL_IMAGES && short_header)
1953 wimlib_print_wim_information(w);
1956 wimlib_print_header(w);
1959 if (total_parts != 1) {
1960 tprintf(T("Warning: Only showing the lookup table "
1961 "for part %d of a %d-part WIM.\n"),
1962 part_number, total_parts);
1964 wimlib_print_lookup_table(w);
1968 ret = wimlib_extract_xml_data(w, stdout);
1974 fp = tfopen(xml_out_file, T("wb"));
1976 imagex_error_with_errno(T("Failed to open the "
1977 "file \"%"TS"\" for "
1983 ret = wimlib_extract_xml_data(w, fp);
1984 if (fclose(fp) != 0) {
1985 imagex_error(T("Failed to close the file "
1996 wimlib_print_available_images(w, image);
1999 ret = wimlib_print_metadata(w, image);
2005 /* Modification operations */
2006 if (total_parts != 1) {
2007 imagex_error(T("Modifying a split WIM is not supported."));
2011 if (image == WIMLIB_ALL_IMAGES)
2014 if (image == WIMLIB_NO_IMAGE && new_name) {
2015 imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2016 "when using image 0"), new_name);
2022 if (image == wimlib_get_boot_idx(w)) {
2023 tprintf(T("Image %d is already marked as "
2024 "bootable.\n"), image);
2027 tprintf(T("Marking image %d as bootable.\n"),
2029 wimlib_set_boot_idx(w, image);
2033 if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
2035 tprintf(T("Image %d is already named \"%"TS"\".\n"),
2039 tprintf(T("Changing the name of image %d to "
2040 "\"%"TS"\".\n"), image, new_name);
2041 ret = wimlib_set_image_name(w, image, new_name);
2047 const tchar *old_desc;
2048 old_desc = wimlib_get_image_description(w, image);
2049 if (old_desc && !tstrcmp(old_desc, new_desc)) {
2050 tprintf(T("The description of image %d is already "
2051 "\"%"TS"\".\n"), image, new_desc);
2054 tprintf(T("Changing the description of image %d "
2055 "to \"%"TS"\".\n"), image, new_desc);
2056 ret = wimlib_set_image_descripton(w, image,
2063 /* Only call wimlib_overwrite() if something actually needs to
2065 if (boot || new_name || new_desc ||
2066 (check && !wimlib_has_integrity_table(w)))
2070 ret = file_writable(wimfile);
2075 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2079 ret = wimlib_overwrite(w, write_flags, 1,
2080 imagex_progress_func);
2081 if (ret == WIMLIB_ERR_REOPEN)
2084 tprintf(T("The file \"%"TS"\" was not modified because nothing "
2085 "needed to be done.\n"), wimfile);
2094 /* Join split WIMs into one part WIM */
2096 imagex_join(int argc, tchar **argv)
2099 int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2100 int wim_write_flags = 0;
2101 const tchar *output_path;
2103 for_opt(c, join_options) {
2105 case IMAGEX_CHECK_OPTION:
2106 swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2107 wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2117 imagex_error(T("Must specify one or more split WIM (.swm) "
2121 output_path = argv[0];
2122 return wimlib_join((const tchar * const *)++argv,
2127 imagex_progress_func);
2133 /* Mounts an image using a FUSE mount. */
2135 imagex_mount_rw_or_ro(int argc, tchar **argv)
2138 int mount_flags = 0;
2139 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2140 const tchar *wimfile;
2146 const tchar *swm_glob = NULL;
2147 WIMStruct **additional_swms = NULL;
2148 unsigned num_additional_swms = 0;
2149 const tchar *staging_dir = NULL;
2151 if (!tstrcmp(argv[0], T("mountrw")))
2152 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2154 for_opt(c, mount_options) {
2156 case IMAGEX_ALLOW_OTHER_OPTION:
2157 mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2159 case IMAGEX_CHECK_OPTION:
2160 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2162 case IMAGEX_DEBUG_OPTION:
2163 mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2165 case IMAGEX_STREAMS_INTERFACE_OPTION:
2166 if (!tstrcasecmp(optarg, T("none")))
2167 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2168 else if (!tstrcasecmp(optarg, T("xattr")))
2169 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2170 else if (!tstrcasecmp(optarg, T("windows")))
2171 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2173 imagex_error(T("Unknown stream interface \"%"TS"\""),
2178 case IMAGEX_REF_OPTION:
2181 case IMAGEX_STAGING_DIR_OPTION:
2182 staging_dir = optarg;
2184 case IMAGEX_UNIX_DATA_OPTION:
2185 mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2193 if (argc != 2 && argc != 3)
2198 ret = wimlib_open_wim(wimfile, open_flags, &w,
2199 imagex_progress_func);
2204 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2206 &num_additional_swms);
2213 num_images = wimlib_get_num_images(w);
2214 if (num_images != 1) {
2215 imagex_error(T("The file \"%"TS"\" contains %d images; Please "
2216 "select one."), wimfile, num_images);
2217 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2224 image = wimlib_resolve_image(w, argv[1]);
2226 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2231 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2232 ret = file_writable(wimfile);
2237 ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2238 num_additional_swms, staging_dir);
2240 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2242 image, wimfile, dir);
2247 if (additional_swms) {
2248 for (unsigned i = 0; i < num_additional_swms; i++)
2249 wimlib_free(additional_swms[i]);
2250 free(additional_swms);
2254 usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2259 /* Rebuild a WIM file */
2261 imagex_optimize(int argc, tchar **argv)
2265 int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2268 const tchar *wimfile;
2271 unsigned num_threads = 0;
2273 for_opt(c, optimize_options) {
2275 case IMAGEX_CHECK_OPTION:
2276 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2277 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2279 case IMAGEX_RECOMPRESS_OPTION:
2280 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2282 case IMAGEX_THREADS_OPTION:
2283 num_threads = parse_num_threads(optarg);
2284 if (num_threads == UINT_MAX)
2302 ret = wimlib_open_wim(wimfile, open_flags, &w,
2303 imagex_progress_func);
2307 old_size = file_get_size(argv[0]);
2308 tprintf(T("\"%"TS"\" original size: "), wimfile);
2310 tfputs(T("Unknown\n"), stdout);
2312 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2314 ret = wimlib_overwrite(w, write_flags, num_threads,
2315 imagex_progress_func);
2318 new_size = file_get_size(argv[0]);
2319 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2321 tfputs(T("Unknown\n"), stdout);
2323 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2325 tfputs(T("Space saved: "), stdout);
2326 if (new_size != -1 && old_size != -1) {
2327 tprintf(T("%lld KiB\n"),
2328 ((long long)old_size - (long long)new_size) >> 10);
2330 tfputs(T("Unknown\n"), stdout);
2338 /* Split a WIM into a spanned set */
2340 imagex_split(int argc, tchar **argv)
2343 int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2344 int write_flags = 0;
2345 unsigned long part_size;
2350 for_opt(c, split_options) {
2352 case IMAGEX_CHECK_OPTION:
2353 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2354 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2368 part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2369 if (tmp == argv[2] || *tmp) {
2370 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2371 imagex_error(T("The part size must be an integer or "
2372 "floating-point number of megabytes."));
2375 ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2378 ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2383 /* Unmounts a mounted WIM image. */
2385 imagex_unmount(int argc, tchar **argv)
2388 int unmount_flags = 0;
2391 for_opt(c, unmount_options) {
2393 case IMAGEX_COMMIT_OPTION:
2394 unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2396 case IMAGEX_CHECK_OPTION:
2397 unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2399 case IMAGEX_REBULID_OPTION:
2400 unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2414 ret = wimlib_unmount_image(argv[0], unmount_flags,
2415 imagex_progress_func);
2417 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2421 struct imagex_command {
2423 int (*func)(int , tchar **);
2428 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
2429 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
2431 static const struct imagex_command imagex_commands[] = {
2432 {T("append"), imagex_capture_or_append, APPEND},
2433 {T("apply"), imagex_apply, APPLY},
2434 {T("capture"), imagex_capture_or_append, CAPTURE},
2435 {T("delete"), imagex_delete, DELETE},
2436 {T("dir"), imagex_dir, DIR},
2437 {T("export"), imagex_export, EXPORT},
2438 {T("info"), imagex_info, INFO},
2439 {T("join"), imagex_join, JOIN},
2440 {T("mount"), imagex_mount_rw_or_ro, MOUNT},
2441 {T("mountrw"), imagex_mount_rw_or_ro, MOUNTRW},
2442 {T("optimize"),imagex_optimize, OPTIMIZE},
2443 {T("split"), imagex_split, SPLIT},
2444 {T("unmount"), imagex_unmount, UNMOUNT},
2450 static const tchar *s =
2452 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
2453 "Copyright (C) 2012, 2013 Eric Biggers\n"
2454 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
2455 "This is free software: you are free to change and redistribute it.\n"
2456 "There is NO WARRANTY, to the extent permitted by law.\n"
2458 "Report bugs to "PACKAGE_BUGREPORT".\n"
2465 help_or_version(int argc, tchar **argv)
2469 const struct imagex_command *cmd;
2471 for (i = 1; i < argc; i++) {
2479 if (!tstrcmp(p, T("help"))) {
2480 for_imagex_command(cmd) {
2481 if (!tstrcmp(cmd->name, argv[1])) {
2489 if (!tstrcmp(p, T("version"))) {
2500 const struct imagex_command *cmd;
2501 tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
2502 for_imagex_command(cmd) {
2503 if (cmd->cmd == cmd_type) {
2504 tprintf(T("\nTry `man "IMAGEX_PROGNAME"-%"TS"' "
2505 "for more details.\n"), cmd->name);
2513 tfputs(T("Usage:\n"), stdout);
2514 for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
2515 tprintf(T(" %"TS), usage_strings[i]);
2516 static const tchar *extra =
2518 " "IMAGEX_PROGNAME" --help\n"
2519 " "IMAGEX_PROGNAME" --version\n"
2521 " The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
2523 " Try `man "IMAGEX_PROGNAME"' for more information.\n"
2525 tfputs(extra, stdout);
2528 /* Entry point for wimlib's ImageX implementation. On UNIX the command
2529 * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
2530 * something else), while an Windows the command arguments will be UTF-16LE
2531 * encoded 'wchar_t' strings. */
2534 wmain(int argc, wchar_t **argv, wchar_t **envp)
2536 main(int argc, char **argv)
2539 const struct imagex_command *cmd;
2544 if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
2545 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
2549 setlocale(LC_ALL, "");
2550 codeset = nl_langinfo(CODESET);
2551 if (!strstr(codeset, "UTF-8") &&
2552 !strstr(codeset, "UTF8") &&
2553 !strstr(codeset, "utf-8") &&
2554 !strstr(codeset, "utf8"))
2557 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
2558 " Maybe try: `export LANG=en_US.UTF-8'?\n"
2559 " Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
2560 " to any value to force wimlib to use UTF-8.\n",
2565 #endif /* !__WIN32__ */
2568 imagex_error(T("No command specified"));
2574 /* Handle --help and --version for all commands. Note that this will
2575 * not return if either of these arguments are present. */
2576 help_or_version(argc, argv);
2580 /* The user may like to see more informative error messages. */
2581 wimlib_set_print_errors(true);
2583 /* Do any initializations that the library needs */
2584 ret = wimlib_global_init(init_flags);
2586 goto out_check_status;
2588 /* Search for the function to handle the ImageX subcommand. */
2589 for_imagex_command(cmd) {
2590 if (!tstrcmp(cmd->name, *argv)) {
2591 ret = cmd->func(argc, argv);
2592 goto out_check_write_error;
2596 imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
2600 out_check_write_error:
2601 /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
2602 * standard output is part of the program's actual behavior and not just
2603 * for informational purposes, so we should set a failure exit status if
2604 * there was a write error. */
2605 if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
2606 if (ferror(stdout) || fclose(stdout)) {
2607 imagex_error_with_errno(T("error writing to standard output"));
2613 /* Exit status (ret): -1 indicates an error found by 'wimlib-imagex'
2614 * outside of the wimlib library code. 0 indicates success. > 0
2615 * indicates a wimlib error code from which an error message can be
2618 imagex_error(T("Exiting with error code %d:\n"
2620 wimlib_get_error_string(ret));
2621 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
2622 imagex_error_with_errno(T("errno"));
2625 /* Make the library free any resources it's holding (not strictly
2626 * necessary because the process is ending anyway). */
2627 wimlib_global_cleanup();