2 * win32_apply.c - Windows-specific code for applying files from a WIM image.
6 * Copyright (C) 2013-2016 Eric Biggers
8 * This file is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU Lesser General Public License as published by the Free
10 * Software Foundation; either version 3 of the License, or (at your option) any
13 * This file is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this file; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib/win32_common.h"
30 #include "wimlib/apply.h"
31 #include "wimlib/assert.h"
32 #include "wimlib/blob_table.h"
33 #include "wimlib/dentry.h"
34 #include "wimlib/encoding.h"
35 #include "wimlib/error.h"
36 #include "wimlib/metadata.h"
37 #include "wimlib/object_id.h"
38 #include "wimlib/paths.h"
39 #include "wimlib/pattern.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/scan.h" /* for mangle_pat() and match_pattern_list() */
42 #include "wimlib/textfile.h"
43 #include "wimlib/xml.h"
44 #include "wimlib/wimboot.h"
45 #include "wimlib/wof.h"
47 struct win32_apply_ctx {
49 /* Extract flags, the pointer to the WIMStruct, etc. */
50 struct apply_ctx common;
52 /* WIMBoot information, only filled in if WIMLIB_EXTRACT_FLAG_WIMBOOT
55 /* This array contains the WIM files registered with WOF on the
56 * target volume for this extraction operation. All WIMStructs
57 * in this array are distinct and have ->filename != NULL. */
61 u8 blob_table_hash[SHA1_HASH_SIZE];
65 bool have_wrong_version_wims;
66 bool have_uncompressed_wims;
67 bool have_unsupported_compressed_resources;
68 bool have_huge_resources;
71 /* External backing information */
72 struct string_list *prepopulate_pats;
73 void *mem_prepopulate_pats;
74 bool tried_to_load_prepopulate_list;
76 /* Open handle to the target directory */
79 /* NT namespace path to the target directory (buffer allocated) */
80 UNICODE_STRING target_ntpath;
82 /* Temporary buffer for building paths (buffer allocated) */
83 UNICODE_STRING pathbuf;
85 /* Object attributes to reuse for opening files in the target directory.
86 * (attr.ObjectName == &pathbuf) and (attr.RootDirectory == h_target).
88 OBJECT_ATTRIBUTES attr;
90 /* Temporary I/O status block for system calls */
93 /* Allocated buffer for creating "printable" paths from our
94 * target-relative NT paths */
95 wchar_t *print_buffer;
97 /* Allocated buffer for reading blob data when it cannot be extracted
101 /* Pointer to the next byte in @data_buffer to fill */
104 /* Size allocated in @data_buffer */
105 size_t data_buffer_size;
107 /* Current offset in the raw encrypted file being written */
108 size_t encrypted_offset;
110 /* Current size of the raw encrypted file being written */
111 size_t encrypted_size;
113 /* Temporary buffer for reparse data */
114 struct reparse_buffer_disk rpbuf;
116 /* Temporary buffer for reparse data of "fixed" absolute symbolic links
118 struct reparse_buffer_disk rpfixbuf;
120 /* Array of open handles to filesystem streams currently being written
122 HANDLE open_handles[MAX_OPEN_FILES];
124 /* Number of handles in @open_handles currently open (filled in from the
125 * beginning of the array) */
126 unsigned num_open_handles;
128 /* List of dentries, joined by @d_tmp_list, that need to have reparse
129 * data extracted as soon as the whole blob has been read into
131 struct list_head reparse_dentries;
133 /* List of dentries, joined by @d_tmp_list, that need to have raw
134 * encrypted data extracted as soon as the whole blob has been read into
136 struct list_head encrypted_dentries;
138 /* Number of files for which we didn't have permission to set the full
139 * security descriptor. */
140 unsigned long partial_security_descriptors;
142 /* Number of files for which we didn't have permission to set any part
143 * of the security descriptor. */
144 unsigned long no_security_descriptors;
146 /* Number of files for which we couldn't set the short name. */
147 unsigned long num_set_short_name_failures;
149 /* Number of files for which we couldn't remove the short name. */
150 unsigned long num_remove_short_name_failures;
152 /* Number of files on which we couldn't set System Compression. */
153 unsigned long num_system_compression_failures;
155 /* The number of files which, for compatibility with the Windows
156 * bootloader, were not compressed using the requested system
157 * compression format. This includes matches with the hardcoded pattern
158 * list only; it does not include matches with patterns in
159 * [PrepopulateList]. */
160 unsigned long num_system_compression_exclusions;
162 /* Number of files for which we couldn't set the object ID. */
163 unsigned long num_object_id_failures;
165 /* The Windows build number of the image being applied, or 0 if unknown.
167 u64 windows_build_number;
169 /* Have we tried to enable short name support on the target volume yet?
171 bool tried_to_enable_short_names;
174 /* Get the drive letter from a Windows path, or return the null character if the
175 * path is relative. */
177 get_drive_letter(const wchar_t *path)
179 /* Skip \\?\ prefix */
180 if (!wcsncmp(path, L"\\\\?\\", 4))
183 /* Return drive letter if valid */
184 if (((path[0] >= L'a' && path[0] <= L'z') ||
185 (path[0] >= L'A' && path[0] <= L'Z')) && path[1] == L':')
192 get_vol_flags(const wchar_t *target, DWORD *vol_flags_ret,
193 bool *short_names_supported_ret)
195 wchar_t filesystem_name[MAX_PATH + 1];
197 wchar_t *volume = NULL;
200 *short_names_supported_ret = false;
202 drive[0] = get_drive_letter(target);
210 if (!GetVolumeInformation(volume, NULL, 0, NULL, NULL,
211 vol_flags_ret, filesystem_name,
212 ARRAY_LEN(filesystem_name)))
214 win32_warning(GetLastError(),
215 L"Failed to get volume information for \"%ls\"",
220 if (wcsstr(filesystem_name, L"NTFS")) {
221 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and
222 * later. Force it on anyway if filesystem is NTFS. */
223 *vol_flags_ret |= FILE_SUPPORTS_HARD_LINKS;
225 /* There's no volume flag for short names, but according to the
226 * MS documentation they are only user-settable on NTFS. */
227 *short_names_supported_ret = true;
231 /* Is the image being extracted an OS image for Windows 10 or later? */
233 is_image_windows_10_or_later(struct win32_apply_ctx *ctx)
235 /* Note: if no build number is available, this returns false. */
236 return ctx->windows_build_number >= 10240;
239 static const wchar_t *
240 current_path(struct win32_apply_ctx *ctx);
243 build_extraction_path(const struct wim_dentry *dentry,
244 struct win32_apply_ctx *ctx);
247 report_dentry_apply_error(const struct wim_dentry *dentry,
248 struct win32_apply_ctx *ctx, int ret)
250 build_extraction_path(dentry, ctx);
251 return report_apply_error(&ctx->common, ret, current_path(ctx));
255 check_apply_error(const struct wim_dentry *dentry,
256 struct win32_apply_ctx *ctx, int ret)
259 ret = report_dentry_apply_error(dentry, ctx, ret);
264 win32_get_supported_features(const wchar_t *target,
265 struct wim_features *supported_features)
268 bool short_names_supported;
270 /* Query the features of the target volume. */
272 get_vol_flags(target, &vol_flags, &short_names_supported);
274 supported_features->readonly_files = 1;
275 supported_features->hidden_files = 1;
276 supported_features->system_files = 1;
277 supported_features->archive_files = 1;
279 if (vol_flags & FILE_FILE_COMPRESSION)
280 supported_features->compressed_files = 1;
282 if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
283 supported_features->encrypted_files = 1;
284 supported_features->encrypted_directories = 1;
287 supported_features->not_context_indexed_files = 1;
289 /* Don't do anything with FILE_SUPPORTS_SPARSE_FILES. */
291 if (vol_flags & FILE_NAMED_STREAMS)
292 supported_features->named_data_streams = 1;
294 if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
295 supported_features->hard_links = 1;
297 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS)
298 supported_features->reparse_points = 1;
300 if (vol_flags & FILE_PERSISTENT_ACLS)
301 supported_features->security_descriptors = 1;
303 if (short_names_supported)
304 supported_features->short_names = 1;
306 if (vol_flags & FILE_SUPPORTS_OBJECT_IDS)
307 supported_features->object_ids = 1;
309 supported_features->timestamps = 1;
311 /* Note: Windows does not support case sensitive filenames! At least
312 * not without changing the registry and rebooting... */
317 #define COMPACT_FLAGS (WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K | \
318 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K | \
319 WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K | \
320 WIMLIB_EXTRACT_FLAG_COMPACT_LZX)
325 * If not done already, load the patterns from the [PrepopulateList] section of
326 * WimBootCompress.ini in the WIM image being extracted.
328 * Note: WimBootCompress.ini applies to both types of "external backing":
330 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
331 * - File backing ("System Compression" - Windows 10 and later)
334 load_prepopulate_pats(struct win32_apply_ctx *ctx)
336 const wchar_t *path = L"\\Windows\\System32\\WimBootCompress.ini";
337 struct wim_dentry *dentry;
338 const struct blob_descriptor *blob;
341 struct string_list *strings;
343 struct text_file_section sec;
345 if (ctx->tried_to_load_prepopulate_list)
348 ctx->tried_to_load_prepopulate_list = true;
350 dentry = get_dentry(ctx->common.wim, path, WIMLIB_CASE_INSENSITIVE);
352 (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
353 FILE_ATTRIBUTE_REPARSE_POINT |
354 FILE_ATTRIBUTE_ENCRYPTED)) ||
355 !(blob = inode_get_blob_for_unnamed_data_stream(dentry->d_inode,
356 ctx->common.wim->blob_table)))
358 WARNING("%ls does not exist in the WIM image.\n"
359 " The default configuration will be used instead; it assumes that all\n"
360 " files are valid for external backing regardless of path, equivalent\n"
361 " to an empty [PrepopulateList] section.", path);
362 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
365 ret = read_blob_into_alloc_buf(blob, &buf);
369 strings = CALLOC(1, sizeof(struct string_list));
372 return WIMLIB_ERR_NOMEM;
375 sec.name = T("PrepopulateList");
376 sec.strings = strings;
378 ret = do_load_text_file(path, buf, blob->size, &mem, &sec, 1,
379 LOAD_TEXT_FILE_REMOVE_QUOTES |
380 LOAD_TEXT_FILE_NO_WARNINGS,
382 STATIC_ASSERT(OS_PREFERRED_PATH_SEPARATOR == WIM_PATH_SEPARATOR);
388 ctx->prepopulate_pats = strings;
389 ctx->mem_prepopulate_pats = mem;
393 /* Returns %true if the specified absolute path to a file in the WIM image can
394 * be subject to external backing when extracted. Otherwise returns %false. */
396 can_externally_back_path(const wchar_t *path, const struct win32_apply_ctx *ctx)
398 /* Does the path match a pattern given in the [PrepopulateList] section
399 * of WimBootCompress.ini? */
400 if (ctx->prepopulate_pats && match_pattern_list(path, ctx->prepopulate_pats))
403 /* Since we attempt to modify the SYSTEM registry after it's extracted
404 * (see end_wimboot_extraction()), it can't be extracted as externally
405 * backed. This extends to associated files such as SYSTEM.LOG that
406 * also must be writable in order to write to the registry. Normally,
407 * SYSTEM is in [PrepopulateList], and the SYSTEM.* files match patterns
408 * in [ExclusionList] and therefore are not captured in the WIM at all.
409 * However, a WIM that wasn't specifically captured in "WIMBoot mode"
410 * may contain SYSTEM.* files. So to make things "just work", hard-code
412 if (match_path(path, L"\\Windows\\System32\\config\\SYSTEM*", false))
418 /* Can the specified WIM resource be used as the source of an external backing
419 * for the wof.sys WIM provider? */
421 is_resource_valid_for_external_backing(const struct wim_resource_descriptor *rdesc,
422 struct win32_apply_ctx *ctx)
424 /* Must be the original WIM file format. This check excludes pipable
425 * resources and solid resources. It also excludes other resources
426 * contained in such files even if they would be otherwise compatible.
428 if (rdesc->wim->hdr.magic != WIM_MAGIC ||
429 rdesc->wim->hdr.wim_version != WIM_VERSION_DEFAULT)
431 ctx->wimboot.have_wrong_version_wims = true;
436 * Whitelist of compression types and chunk sizes supported by
437 * Microsoft's WOF driver.
440 * - Uncompressed WIMs result in BSOD. However, this only applies to
441 * the WIM file itself, not to uncompressed resources in a WIM file
442 * that is otherwise compressed.
443 * - XPRESS 64K sometimes appears to work, but sometimes it causes
444 * reads to fail with STATUS_UNSUCCESSFUL.
446 switch (rdesc->compression_type) {
447 case WIMLIB_COMPRESSION_TYPE_NONE:
448 if (rdesc->wim->compression_type == WIMLIB_COMPRESSION_TYPE_NONE) {
449 ctx->wimboot.have_uncompressed_wims = true;
453 case WIMLIB_COMPRESSION_TYPE_XPRESS:
454 switch (rdesc->chunk_size) {
461 ctx->wimboot.have_unsupported_compressed_resources = true;
465 case WIMLIB_COMPRESSION_TYPE_LZX:
466 switch (rdesc->chunk_size) {
470 ctx->wimboot.have_unsupported_compressed_resources = true;
475 ctx->wimboot.have_unsupported_compressed_resources = true;
479 /* Microsoft's WoF driver errors out if it tries to satisfy a read with
480 * ending offset >= 4 GiB from an externally backed file. */
481 if (rdesc->uncompressed_size > 4200000000) {
482 ctx->wimboot.have_huge_resources = true;
489 #define EXTERNAL_BACKING_NOT_ENABLED -1
490 #define EXTERNAL_BACKING_NOT_POSSIBLE -2
491 #define EXTERNAL_BACKING_EXCLUDED -3
494 * Determines whether the specified file will be externally backed. Returns a
495 * negative status code if no, 0 if yes, or a positive wimlib error code on
496 * error. If the file is excluded from external backing based on its path, then
497 * *excluded_dentry_ret is set to the dentry for the path that matched the
500 * Note that this logic applies to both types of "external backing":
502 * - WIM backing ("WIMBoot" - Windows 8.1 and later)
503 * - File backing ("System Compression" - Windows 10 and later)
505 * However, in the case of WIM backing we also need to validate that the WIM
506 * resource that would be the source of the backing is supported by the wof.sys
510 will_externally_back_inode(struct wim_inode *inode, struct win32_apply_ctx *ctx,
511 const struct wim_dentry **excluded_dentry_ret,
514 struct wim_dentry *dentry;
515 struct blob_descriptor *blob;
518 if (load_prepopulate_pats(ctx) == WIMLIB_ERR_NOMEM)
519 return WIMLIB_ERR_NOMEM;
521 if (inode->i_can_externally_back)
524 /* This may do redundant checks because the cached value
525 * i_can_externally_back is 2-state (as opposed to 3-state:
526 * unknown/no/yes). But most files can be externally backed, so this
529 if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
530 FILE_ATTRIBUTE_REPARSE_POINT |
531 FILE_ATTRIBUTE_ENCRYPTED))
532 return EXTERNAL_BACKING_NOT_POSSIBLE;
534 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
537 return EXTERNAL_BACKING_NOT_POSSIBLE;
540 (blob->blob_location != BLOB_IN_WIM ||
541 !is_resource_valid_for_external_backing(blob->rdesc, ctx)))
542 return EXTERNAL_BACKING_NOT_POSSIBLE;
545 * We need to check the patterns in [PrepopulateList] against every name
546 * of the inode, in case any of them match.
549 inode_for_each_extraction_alias(dentry, inode) {
551 ret = calculate_dentry_full_path(dentry);
555 if (!can_externally_back_path(dentry->d_full_path, ctx)) {
556 if (excluded_dentry_ret)
557 *excluded_dentry_ret = dentry;
558 return EXTERNAL_BACKING_EXCLUDED;
562 inode->i_can_externally_back = 1;
567 * Determines if the unnamed data stream of a file will be created as a WIM
568 * external backing (a "WIMBoot pointer file"), as opposed to a standard
572 win32_will_back_from_wim(struct wim_dentry *dentry, struct apply_ctx *_ctx)
574 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
576 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
577 return EXTERNAL_BACKING_NOT_ENABLED;
579 return will_externally_back_inode(dentry->d_inode, ctx, NULL, true);
582 /* Find the WOF registration information for the specified WIM file. */
583 static struct wimboot_wim *
584 find_wimboot_wim(WIMStruct *wim_to_find, struct win32_apply_ctx *ctx)
586 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
587 if (wim_to_find == ctx->wimboot.wims[i].wim)
588 return &ctx->wimboot.wims[i];
595 set_backed_from_wim(HANDLE h, struct wim_inode *inode, struct win32_apply_ctx *ctx)
598 const struct wim_dentry *excluded_dentry;
599 const struct blob_descriptor *blob;
600 const struct wimboot_wim *wimboot_wim;
602 ret = will_externally_back_inode(inode, ctx, &excluded_dentry, true);
603 if (ret > 0) /* Error. */
606 if (ret < 0 && ret != EXTERNAL_BACKING_EXCLUDED)
607 return 0; /* Not externally backing, other than due to exclusion. */
609 if (unlikely(ret == EXTERNAL_BACKING_EXCLUDED)) {
610 /* Not externally backing due to exclusion. */
611 union wimlib_progress_info info;
613 build_extraction_path(excluded_dentry, ctx);
615 info.wimboot_exclude.path_in_wim = excluded_dentry->d_full_path;
616 info.wimboot_exclude.extraction_path = current_path(ctx);
618 return call_progress(ctx->common.progfunc,
619 WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
620 &info, ctx->common.progctx);
623 /* Externally backing. */
625 blob = inode_get_blob_for_unnamed_data_stream_resolved(inode);
626 wimboot_wim = find_wimboot_wim(blob->rdesc->wim, ctx);
628 if (unlikely(!wimboot_set_pointer(h,
630 wimboot_wim->data_source_id,
631 wimboot_wim->blob_table_hash,
632 ctx->wimboot.wof_running)))
634 const DWORD err = GetLastError();
636 build_extraction_path(inode_first_extraction_dentry(inode), ctx);
637 win32_error(err, L"\"%ls\": Couldn't set WIMBoot pointer data",
639 return WIMLIB_ERR_WIMBOOT;
644 /* Calculates the SHA-1 message digest of the WIM's blob table. */
646 hash_blob_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
648 return wim_reshdr_to_hash(&wim->hdr.blob_table_reshdr, wim, hash);
652 register_wim_with_wof(WIMStruct *wim, struct win32_apply_ctx *ctx)
654 struct wimboot_wim *p;
657 /* Check if already registered */
658 for (size_t i = 0; i < ctx->wimboot.num_wims; i++)
659 if (wim == ctx->wimboot.wims[i].wim)
662 /* Not yet registered */
664 p = REALLOC(ctx->wimboot.wims,
665 (ctx->wimboot.num_wims + 1) * sizeof(ctx->wimboot.wims[0]));
667 return WIMLIB_ERR_NOMEM;
668 ctx->wimboot.wims = p;
670 ctx->wimboot.wims[ctx->wimboot.num_wims].wim = wim;
672 ret = hash_blob_table(wim, ctx->wimboot.wims[ctx->wimboot.num_wims].blob_table_hash);
676 ret = wimboot_alloc_data_source_id(wim->filename,
678 ctx->common.wim->current_image,
680 &ctx->wimboot.wims[ctx->wimboot.num_wims].data_source_id,
681 &ctx->wimboot.wof_running);
685 ctx->wimboot.num_wims++;
689 /* Prepare for doing a "WIMBoot" extraction by registering each source WIM file
690 * with WOF on the target volume. */
692 start_wimboot_extraction(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
695 struct wim_dentry *dentry;
697 if (!xml_get_wimboot(ctx->common.wim->xml_info,
698 ctx->common.wim->current_image))
699 WARNING("The WIM image is not marked as WIMBoot compatible. This usually\n"
700 " means it is not intended to be used to back a Windows operating\n"
701 " system. Proceeding anyway.");
703 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
704 struct blob_descriptor *blob;
706 ret = win32_will_back_from_wim(dentry, &ctx->common);
707 if (ret > 0) /* Error */
709 if (ret < 0) /* Won't externally back */
712 blob = inode_get_blob_for_unnamed_data_stream_resolved(dentry->d_inode);
713 ret = register_wim_with_wof(blob->rdesc->wim, ctx);
718 if (ctx->wimboot.have_wrong_version_wims) {
719 WARNING("At least one of the source WIM files uses a version of the WIM\n"
720 " file format that not supported by Microsoft's wof.sys driver.\n"
721 " Files whose data is contained in one of these WIM files will be\n"
722 " extracted as full files rather than externally backed.");
725 if (ctx->wimboot.have_uncompressed_wims) {
726 WARNING("At least one of the source WIM files is uncompressed. Files whose\n"
727 " data is contained in an uncompressed WIM file will be extracted as\n"
728 " full files rather than externally backed, since uncompressed WIM\n"
729 " files are not supported by Microsoft's wof.sys driver.");
732 if (ctx->wimboot.have_unsupported_compressed_resources) {
733 WARNING("At least one of the source WIM files uses a compression format that\n"
734 " is not supported by Microsoft's wof.sys driver. Files whose data is\n"
735 " contained in a compressed resource in one of these WIM files will be\n"
736 " extracted as full files rather than externally backed. (The\n"
737 " compression formats supported by wof.sys are: XPRESS 4K, XPRESS 8K,\n"
738 " XPRESS 16K, XPRESS 32K, and LZX 32K.)");
741 if (ctx->wimboot.have_huge_resources) {
742 WARNING("Some files exceeded 4.2 GB in size. Such files will be extracted\n"
743 " as full files rather than externally backed, since very large files\n"
744 " are not supported by Microsoft's wof.sys driver.");
751 build_win32_extraction_path(const struct wim_dentry *dentry,
752 struct win32_apply_ctx *ctx);
754 /* Sets WimBoot=1 in the extracted SYSTEM registry hive.
756 * WIMGAPI does this, and it's possible that it's important.
757 * But I don't know exactly what this value means to Windows. */
759 end_wimboot_extraction(struct win32_apply_ctx *ctx)
761 struct wim_dentry *dentry;
762 wchar_t subkeyname[32];
768 dentry = get_dentry(ctx->common.wim, L"\\Windows\\System32\\config\\SYSTEM",
769 WIMLIB_CASE_INSENSITIVE);
771 if (!dentry || !will_extract_dentry(dentry))
774 if (!will_extract_dentry(wim_get_current_root_dentry(ctx->common.wim)))
777 /* Not bothering to use the native routines (e.g. NtLoadKey()) for this.
778 * If this doesn't work, you probably also have many other problems. */
780 build_win32_extraction_path(dentry, ctx);
782 randomize_char_array_with_alnum(subkeyname, 20);
783 subkeyname[20] = L'\0';
785 res = RegLoadKey(HKEY_LOCAL_MACHINE, subkeyname, ctx->pathbuf.Buffer);
789 wcscpy(&subkeyname[20], L"\\Setup");
791 res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subkeyname, 0, NULL,
792 REG_OPTION_BACKUP_RESTORE, 0, NULL, &key, NULL);
798 res = RegSetValueEx(key, L"WimBoot", 0, REG_DWORD,
799 (const BYTE *)&value, sizeof(DWORD));
803 res = RegFlushKey(key);
806 res2 = RegCloseKey(key);
810 subkeyname[20] = L'\0';
811 RegUnLoadKey(HKEY_LOCAL_MACHINE, subkeyname);
815 win32_warning(res, L"Failed to set \\Setup: dword \"WimBoot\"=1 "
816 "value in registry hive \"%ls\"",
817 ctx->pathbuf.Buffer);
823 /* Returns the number of wide characters needed to represent the path to the
824 * specified @dentry, relative to the target directory, when extracted.
826 * Does not include null terminator (not needed for NtCreateFile). */
828 dentry_extraction_path_length(const struct wim_dentry *dentry)
831 const struct wim_dentry *d;
835 len += d->d_extraction_name_nchars + 1;
837 } while (!dentry_is_root(d) && will_extract_dentry(d));
839 return --len; /* No leading slash */
842 /* Returns the length of the longest string that might need to be appended to
843 * the path to an alias of an inode to open or create a named data stream.
845 * If the inode has no named data streams, this will be 0. Otherwise, this will
846 * be 1 plus the length of the longest-named data stream, since the data stream
847 * name must be separated from the path by the ':' character. */
849 inode_longest_named_data_stream_spec(const struct wim_inode *inode)
852 for (unsigned i = 0; i < inode->i_num_streams; i++) {
853 const struct wim_inode_stream *strm = &inode->i_streams[i];
854 if (!stream_is_named_data_stream(strm))
856 size_t len = utf16le_len_chars(strm->stream_name);
865 /* Find the length, in wide characters, of the longest path needed for
866 * extraction of any file in @dentry_list relative to the target directory.
868 * Accounts for named data streams, but does not include null terminator (not
869 * needed for NtCreateFile). */
871 compute_path_max(struct list_head *dentry_list)
874 const struct wim_dentry *dentry;
876 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
879 len = dentry_extraction_path_length(dentry);
881 /* Account for named data streams */
882 len += inode_longest_named_data_stream_spec(dentry->d_inode);
891 /* Build the path at which to extract the @dentry, relative to the target
894 * The path is saved in ctx->pathbuf. */
896 build_extraction_path(const struct wim_dentry *dentry,
897 struct win32_apply_ctx *ctx)
901 const struct wim_dentry *d;
903 len = dentry_extraction_path_length(dentry);
905 ctx->pathbuf.Length = len * sizeof(wchar_t);
906 p = ctx->pathbuf.Buffer + len;
908 !dentry_is_root(d->d_parent) && will_extract_dentry(d->d_parent);
911 p -= d->d_extraction_name_nchars;
912 if (d->d_extraction_name_nchars)
913 wmemcpy(p, d->d_extraction_name,
914 d->d_extraction_name_nchars);
917 /* No leading slash */
918 p -= d->d_extraction_name_nchars;
919 wmemcpy(p, d->d_extraction_name, d->d_extraction_name_nchars);
922 /* Build the path at which to extract the @dentry, relative to the target
923 * directory, adding the suffix for a named data stream.
925 * The path is saved in ctx->pathbuf. */
927 build_extraction_path_with_ads(const struct wim_dentry *dentry,
928 struct win32_apply_ctx *ctx,
929 const wchar_t *stream_name,
930 size_t stream_name_nchars)
934 build_extraction_path(dentry, ctx);
936 /* Add :NAME for named data stream */
937 p = ctx->pathbuf.Buffer + (ctx->pathbuf.Length / sizeof(wchar_t));
939 wmemcpy(p, stream_name, stream_name_nchars);
940 ctx->pathbuf.Length += (1 + stream_name_nchars) * sizeof(wchar_t);
943 /* Build the Win32 namespace path to the specified @dentry when extracted.
945 * The path is saved in ctx->pathbuf and will be null terminated.
947 * XXX: We could get rid of this if it wasn't needed for the file encryption
948 * APIs, and the registry manipulation in WIMBoot mode. */
950 build_win32_extraction_path(const struct wim_dentry *dentry,
951 struct win32_apply_ctx *ctx)
953 build_extraction_path(dentry, ctx);
955 /* Prepend target_ntpath to our relative path, then change \??\ into \\?\ */
957 memmove(ctx->pathbuf.Buffer +
958 (ctx->target_ntpath.Length / sizeof(wchar_t)) + 1,
959 ctx->pathbuf.Buffer, ctx->pathbuf.Length);
960 memcpy(ctx->pathbuf.Buffer, ctx->target_ntpath.Buffer,
961 ctx->target_ntpath.Length);
962 ctx->pathbuf.Buffer[ctx->target_ntpath.Length / sizeof(wchar_t)] = L'\\';
963 ctx->pathbuf.Length += ctx->target_ntpath.Length + sizeof(wchar_t);
964 ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)] = L'\0';
966 wimlib_assert(ctx->pathbuf.Length >= 4 * sizeof(wchar_t) &&
967 !wmemcmp(ctx->pathbuf.Buffer, L"\\??\\", 4));
969 ctx->pathbuf.Buffer[1] = L'\\';
973 /* Returns a "printable" representation of the last relative NT path that was
974 * constructed with build_extraction_path() or build_extraction_path_with_ads().
976 * This will be overwritten by the next call to this function. */
977 static const wchar_t *
978 current_path(struct win32_apply_ctx *ctx)
980 wchar_t *p = ctx->print_buffer;
982 p = wmempcpy(p, ctx->common.target, ctx->common.target_nchars);
984 p = wmempcpy(p, ctx->pathbuf.Buffer, ctx->pathbuf.Length / sizeof(wchar_t));
986 return ctx->print_buffer;
989 /* Open handle to the target directory if it is not already open. If the target
990 * directory does not exist, this creates it. */
992 open_target_directory(struct win32_apply_ctx *ctx)
999 ctx->attr.Length = sizeof(ctx->attr);
1000 ctx->attr.RootDirectory = NULL;
1001 ctx->attr.ObjectName = &ctx->target_ntpath;
1003 /* Don't use FILE_OPEN_REPARSE_POINT here; we want the extraction to
1004 * happen at the directory "pointed to" by the reparse point. */
1005 status = NtCreateFile(&ctx->h_target,
1011 FILE_SHARE_VALID_FLAGS,
1013 FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT,
1016 if (!NT_SUCCESS(status)) {
1017 winnt_error(status, L"Can't open or create directory \"%ls\"",
1018 ctx->common.target);
1019 return WIMLIB_ERR_OPENDIR;
1021 ctx->attr.RootDirectory = ctx->h_target;
1022 ctx->attr.ObjectName = &ctx->pathbuf;
1027 close_target_directory(struct win32_apply_ctx *ctx)
1029 if (ctx->h_target) {
1030 NtClose(ctx->h_target);
1031 ctx->h_target = NULL;
1032 ctx->attr.RootDirectory = NULL;
1037 * Ensures the target directory exists and opens a handle to it, in preparation
1038 * of using paths relative to it.
1041 prepare_target(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1046 ret = win32_path_to_nt_path(ctx->common.target, &ctx->target_ntpath);
1050 ret = open_target_directory(ctx);
1054 path_max = compute_path_max(dentry_list);
1055 /* Add some extra for building Win32 paths for the file encryption APIs,
1056 * and ensure we have at least enough to potentially use a 8.3 name for
1057 * the last component. */
1058 path_max += max(2 + (ctx->target_ntpath.Length / sizeof(wchar_t)),
1061 ctx->pathbuf.MaximumLength = path_max * sizeof(wchar_t);
1062 ctx->pathbuf.Buffer = MALLOC(ctx->pathbuf.MaximumLength);
1063 if (!ctx->pathbuf.Buffer)
1064 return WIMLIB_ERR_NOMEM;
1066 ctx->print_buffer = MALLOC((ctx->common.target_nchars + 1 + path_max + 1) *
1068 if (!ctx->print_buffer)
1069 return WIMLIB_ERR_NOMEM;
1074 /* When creating an inode that will have a short (DOS) name, we create it using
1075 * the long name associated with the short name. This ensures that the short
1076 * name gets associated with the correct long name. */
1077 static struct wim_dentry *
1078 first_extraction_alias(const struct wim_inode *inode)
1080 struct wim_dentry *dentry;
1082 inode_for_each_extraction_alias(dentry, inode)
1083 if (dentry_has_short_name(dentry))
1085 return inode_first_extraction_dentry(inode);
1089 * Set or clear FILE_ATTRIBUTE_COMPRESSED if the inherited value is different
1090 * from the desired value.
1092 * Note that you can NOT override the inherited value of
1093 * FILE_ATTRIBUTE_COMPRESSED directly with NtCreateFile().
1096 adjust_compression_attribute(HANDLE h, const struct wim_dentry *dentry,
1097 struct win32_apply_ctx *ctx)
1099 const bool compressed = (dentry->d_inode->i_attributes &
1100 FILE_ATTRIBUTE_COMPRESSED);
1101 FILE_BASIC_INFORMATION info;
1102 USHORT compression_state;
1105 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)
1108 if (!ctx->common.supported_features.compressed_files)
1112 /* Get current attributes */
1113 status = NtQueryInformationFile(h, &ctx->iosb, &info, sizeof(info),
1114 FileBasicInformation);
1115 if (NT_SUCCESS(status) &&
1116 compressed == !!(info.FileAttributes & FILE_ATTRIBUTE_COMPRESSED))
1118 /* Nothing needs to be done. */
1122 /* Set the new compression state */
1125 compression_state = COMPRESSION_FORMAT_DEFAULT;
1127 compression_state = COMPRESSION_FORMAT_NONE;
1129 status = winnt_fsctl(h, FSCTL_SET_COMPRESSION,
1130 &compression_state, sizeof(USHORT), NULL, 0, NULL);
1131 if (NT_SUCCESS(status))
1134 winnt_error(status, L"Can't %s compression attribute on \"%ls\"",
1135 (compressed ? "set" : "clear"), current_path(ctx));
1136 return WIMLIB_ERR_SET_ATTRIBUTES;
1139 /* Try to enable short name support on the target volume. If successful, return
1140 * true. If unsuccessful, issue a warning and return false. */
1142 try_to_enable_short_names(const wchar_t *volume)
1145 FILE_FS_PERSISTENT_VOLUME_INFORMATION info;
1147 DWORD bytesReturned;
1149 h = CreateFile(volume, GENERIC_WRITE,
1150 FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
1151 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1152 if (h == INVALID_HANDLE_VALUE)
1155 info.VolumeFlags = 0;
1156 info.FlagMask = PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED;
1160 bret = DeviceIoControl(h, FSCTL_SET_PERSISTENT_VOLUME_STATE,
1161 &info, sizeof(info), NULL, 0,
1162 &bytesReturned, NULL);
1171 win32_warning(GetLastError(),
1172 L"Failed to enable short name support on %ls",
1178 remove_conflicting_short_name(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1184 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1185 (13 * sizeof(wchar_t));
1186 u8 buf[bufsize] _aligned_attribute(8);
1187 bool retried = false;
1188 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1190 memset(buf, 0, bufsize);
1192 /* Build the path with the short name. */
1193 name = &ctx->pathbuf.Buffer[ctx->pathbuf.Length / sizeof(wchar_t)];
1194 while (name != ctx->pathbuf.Buffer && *(name - 1) != L'\\')
1196 end = mempcpy(name, dentry->d_short_name, dentry->d_short_name_nbytes);
1197 ctx->pathbuf.Length = ((u8 *)end - (u8 *)ctx->pathbuf.Buffer);
1199 /* Open the conflicting file (by short name). */
1200 status = NtOpenFile(&h, GENERIC_WRITE | DELETE,
1201 &ctx->attr, &ctx->iosb,
1202 FILE_SHARE_VALID_FLAGS,
1203 FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT);
1204 if (!NT_SUCCESS(status)) {
1205 winnt_warning(status, L"Can't open \"%ls\"", current_path(ctx));
1210 WARNING("Overriding conflicting short name; path=\"%ls\"",
1214 /* Try to remove the short name on the conflicting file. */
1217 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1218 FileShortNameInformation);
1220 if (status == STATUS_INVALID_PARAMETER && !retried) {
1222 /* Microsoft forgot to make it possible to remove short names
1223 * until Windows 7. Oops. Use a random short name instead. */
1225 info->FileNameLength = 12 * sizeof(wchar_t);
1226 for (int i = 0; i < 8; i++)
1227 info->FileName[i] = 'A' + (rand() % 26);
1228 info->FileName[8] = L'.';
1229 info->FileName[9] = L'W';
1230 info->FileName[10] = L'L';
1231 info->FileName[11] = L'B';
1232 info->FileName[12] = L'\0';
1238 build_extraction_path(dentry, ctx);
1242 /* Set the short name on the open file @h which has been created at the location
1243 * indicated by @dentry.
1245 * Note that this may add, change, or remove the short name.
1247 * @h must be opened with DELETE access.
1249 * Returns 0 or WIMLIB_ERR_SET_SHORT_NAME. The latter only happens in
1250 * STRICT_SHORT_NAMES mode.
1253 set_short_name(HANDLE h, const struct wim_dentry *dentry,
1254 struct win32_apply_ctx *ctx)
1257 if (!ctx->common.supported_features.short_names)
1261 * Note: The size of the FILE_NAME_INFORMATION buffer must be such that
1262 * FileName contains at least 2 wide characters (4 bytes). Otherwise,
1263 * NtSetInformationFile() will return STATUS_INFO_LENGTH_MISMATCH. This
1264 * is despite the fact that FileNameLength can validly be 0 or 2 bytes,
1265 * with the former case being removing the existing short name if
1266 * present, rather than setting one.
1268 * The null terminator is seemingly optional, but to be safe we include
1269 * space for it and zero all unused space.
1272 size_t bufsize = offsetof(FILE_NAME_INFORMATION, FileName) +
1273 max(dentry->d_short_name_nbytes, sizeof(wchar_t)) +
1275 u8 buf[bufsize] _aligned_attribute(8);
1276 FILE_NAME_INFORMATION *info = (FILE_NAME_INFORMATION *)buf;
1278 bool tried_to_remove_existing = false;
1280 memset(buf, 0, bufsize);
1282 info->FileNameLength = dentry->d_short_name_nbytes;
1283 memcpy(info->FileName, dentry->d_short_name, dentry->d_short_name_nbytes);
1286 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1287 FileShortNameInformation);
1288 if (NT_SUCCESS(status))
1291 if (status == STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME) {
1292 if (dentry->d_short_name_nbytes == 0)
1294 if (!ctx->tried_to_enable_short_names) {
1298 ctx->tried_to_enable_short_names = true;
1300 ret = win32_get_drive_path(ctx->common.target,
1304 if (try_to_enable_short_names(volume))
1310 * Short names can conflict in several cases:
1312 * - a file being extracted has a short name conflicting with an
1315 * - a file being extracted has a short name conflicting with another
1316 * file being extracted (possible, but shouldn't happen)
1318 * - a file being extracted has a short name that conflicts with the
1319 * automatically generated short name of a file we previously
1320 * extracted, but failed to set the short name for. Sounds unlikely,
1321 * but this actually does happen fairly often on versions of Windows
1322 * prior to Windows 7 because they do not support removing short names
1325 if (unlikely(status == STATUS_OBJECT_NAME_COLLISION) &&
1326 dentry->d_short_name_nbytes && !tried_to_remove_existing)
1328 tried_to_remove_existing = true;
1329 status = remove_conflicting_short_name(dentry, ctx);
1330 if (NT_SUCCESS(status))
1334 /* By default, failure to set short names is not an error (since short
1335 * names aren't too important anymore...). */
1336 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SHORT_NAMES)) {
1337 if (dentry->d_short_name_nbytes)
1338 ctx->num_set_short_name_failures++;
1340 ctx->num_remove_short_name_failures++;
1344 winnt_error(status, L"Can't set short name on \"%ls\"", current_path(ctx));
1345 return WIMLIB_ERR_SET_SHORT_NAME;
1349 * A wrapper around NtCreateFile() to make it slightly more usable...
1350 * This uses the path currently constructed in ctx->pathbuf.
1352 * Also, we always specify SYNCHRONIZE access, FILE_OPEN_FOR_BACKUP_INTENT, and
1353 * FILE_OPEN_REPARSE_POINT.
1356 do_create_file(PHANDLE FileHandle,
1357 ACCESS_MASK DesiredAccess,
1358 PLARGE_INTEGER AllocationSize,
1359 ULONG FileAttributes,
1360 ULONG CreateDisposition,
1361 ULONG CreateOptions,
1362 struct win32_apply_ctx *ctx)
1364 return NtCreateFile(FileHandle,
1365 DesiredAccess | SYNCHRONIZE,
1370 FILE_SHARE_VALID_FLAGS,
1373 FILE_OPEN_FOR_BACKUP_INTENT |
1374 FILE_OPEN_REPARSE_POINT,
1379 /* Like do_create_file(), but builds the extraction path of the @dentry first.
1382 create_file(PHANDLE FileHandle,
1383 ACCESS_MASK DesiredAccess,
1384 PLARGE_INTEGER AllocationSize,
1385 ULONG FileAttributes,
1386 ULONG CreateDisposition,
1387 ULONG CreateOptions,
1388 const struct wim_dentry *dentry,
1389 struct win32_apply_ctx *ctx)
1391 build_extraction_path(dentry, ctx);
1392 return do_create_file(FileHandle,
1402 delete_file_or_stream(struct win32_apply_ctx *ctx)
1406 ULONG perms = DELETE;
1407 ULONG flags = FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE;
1409 /* First try opening the file with FILE_DELETE_ON_CLOSE. In most cases,
1410 * all we have to do is that plus close the file handle. */
1412 status = do_create_file(&h, perms, NULL, 0, FILE_OPEN, flags, ctx);
1414 if (unlikely(status == STATUS_CANNOT_DELETE)) {
1415 /* This error occurs for files with FILE_ATTRIBUTE_READONLY set.
1416 * Try an alternate approach: first open the file without
1417 * FILE_DELETE_ON_CLOSE, then reset the file attributes, then
1418 * set the "delete" disposition on the handle. */
1419 if (flags & FILE_DELETE_ON_CLOSE) {
1420 flags &= ~FILE_DELETE_ON_CLOSE;
1421 perms |= FILE_WRITE_ATTRIBUTES;
1426 if (unlikely(!NT_SUCCESS(status))) {
1427 winnt_error(status, L"Can't open \"%ls\" for deletion "
1428 "(perms=%x, flags=%x)",
1429 current_path(ctx), perms, flags);
1430 return WIMLIB_ERR_OPEN;
1433 if (unlikely(!(flags & FILE_DELETE_ON_CLOSE))) {
1435 FILE_BASIC_INFORMATION basic_info =
1436 { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1437 status = NtSetInformationFile(h, &ctx->iosb, &basic_info,
1439 FileBasicInformation);
1441 if (!NT_SUCCESS(status)) {
1442 winnt_error(status, L"Can't reset attributes of \"%ls\" "
1443 "to prepare for deletion", current_path(ctx));
1445 return WIMLIB_ERR_SET_ATTRIBUTES;
1448 FILE_DISPOSITION_INFORMATION disp_info =
1449 { .DoDeleteFile = TRUE };
1450 status = NtSetInformationFile(h, &ctx->iosb, &disp_info,
1452 FileDispositionInformation);
1453 if (!NT_SUCCESS(status)) {
1454 winnt_error(status, L"Can't set delete-on-close "
1455 "disposition on \"%ls\"", current_path(ctx));
1457 return WIMLIB_ERR_SET_ATTRIBUTES;
1461 status = NtClose(h);
1462 if (unlikely(!NT_SUCCESS(status))) {
1463 winnt_error(status, L"Error closing \"%ls\" after setting "
1464 "delete-on-close disposition", current_path(ctx));
1465 return WIMLIB_ERR_OPEN;
1472 * Create a nondirectory file or named data stream at the current path,
1473 * superseding any that already exists at that path. If successful, return an
1474 * open handle to the file or named data stream with the requested permissions.
1477 supersede_file_or_stream(struct win32_apply_ctx *ctx, DWORD perms,
1481 bool retried = false;
1483 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1484 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1486 status = do_create_file(h_ret,
1489 FILE_ATTRIBUTE_SYSTEM,
1491 FILE_NON_DIRECTORY_FILE,
1493 if (likely(NT_SUCCESS(status)))
1496 /* STATUS_OBJECT_NAME_COLLISION means that the file or stream already
1497 * exists. Delete the existing file or stream, then try again.
1499 * Note: we don't use FILE_OVERWRITE_IF or FILE_SUPERSEDE because of
1500 * problems with certain file attributes, especially
1501 * FILE_ATTRIBUTE_ENCRYPTED. FILE_SUPERSEDE is also broken in the
1502 * Windows PE ramdisk. */
1503 if (status == STATUS_OBJECT_NAME_COLLISION && !retried) {
1504 int ret = delete_file_or_stream(ctx);
1510 winnt_error(status, L"Can't create \"%ls\"", current_path(ctx));
1511 return WIMLIB_ERR_OPEN;
1514 /* Set the reparse point @rpbuf of length @rpbuflen on the extracted file
1515 * corresponding to the WIM dentry @dentry. */
1517 do_set_reparse_point(const struct wim_dentry *dentry,
1518 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
1519 struct win32_apply_ctx *ctx)
1524 status = create_file(&h, GENERIC_WRITE, NULL,
1525 0, FILE_OPEN, 0, dentry, ctx);
1526 if (!NT_SUCCESS(status))
1529 status = winnt_fsctl(h, FSCTL_SET_REPARSE_POINT,
1530 rpbuf, rpbuflen, NULL, 0, NULL);
1533 if (NT_SUCCESS(status))
1536 /* On Windows, by default only the Administrator can create symbolic
1537 * links for some reason. By default we just issue a warning if this
1538 * appears to be the problem. Use WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS
1539 * to get a hard error. */
1540 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_SYMLINKS)
1541 && (status == STATUS_PRIVILEGE_NOT_HELD ||
1542 status == STATUS_ACCESS_DENIED)
1543 && (dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1544 dentry->d_inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1546 WARNING("Can't create symbolic link \"%ls\"! \n"
1547 " (Need Administrator rights, or at least "
1549 " SeCreateSymbolicLink privilege.)",
1555 winnt_error(status, L"Can't set reparse data on \"%ls\"",
1557 return WIMLIB_ERR_SET_REPARSE_DATA;
1561 * Create empty named data streams and potentially a reparse point for the
1562 * specified file, if any.
1564 * Since these won't have blob descriptors, they won't show up in the call to
1565 * extract_blob_list(). Hence the need for the special case.
1568 create_empty_streams(const struct wim_dentry *dentry,
1569 struct win32_apply_ctx *ctx)
1571 const struct wim_inode *inode = dentry->d_inode;
1574 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1575 const struct wim_inode_stream *strm = &inode->i_streams[i];
1577 if (stream_blob_resolved(strm) != NULL)
1580 if (strm->stream_type == STREAM_TYPE_REPARSE_POINT &&
1581 ctx->common.supported_features.reparse_points)
1583 u8 buf[REPARSE_DATA_OFFSET] _aligned_attribute(8);
1584 struct reparse_buffer_disk *rpbuf =
1585 (struct reparse_buffer_disk *)buf;
1586 complete_reparse_point(rpbuf, inode, 0);
1587 ret = do_set_reparse_point(dentry, rpbuf,
1588 REPARSE_DATA_OFFSET, ctx);
1591 } else if (stream_is_named_data_stream(strm) &&
1592 ctx->common.supported_features.named_data_streams)
1596 build_extraction_path_with_ads(dentry, ctx,
1598 utf16le_len_chars(strm->stream_name));
1600 * Note: do not request any permissions on the handle.
1601 * Otherwise, we may encounter a Windows bug where the
1602 * parent directory DACL denies read access to the new
1603 * named data stream, even when using backup semantics!
1605 ret = supersede_file_or_stream(ctx, 0, &h);
1607 build_extraction_path(dentry, ctx);
1619 * Creates the directory named by @dentry, or uses an existing directory at that
1620 * location. If necessary, sets the short name and/or fixes compression and
1621 * encryption attributes.
1623 * Returns 0, WIMLIB_ERR_MKDIR, or WIMLIB_ERR_SET_SHORT_NAME.
1626 create_directory(const struct wim_dentry *dentry, struct win32_apply_ctx *ctx)
1633 /* DELETE is needed for set_short_name(); GENERIC_READ and GENERIC_WRITE
1634 * are needed for adjust_compression_attribute(); WRITE_DAC is needed to
1635 * remove the directory's DACL if the directory already existed */
1636 perms = GENERIC_READ | GENERIC_WRITE | WRITE_DAC;
1637 if (!dentry_is_root(dentry))
1640 /* FILE_ATTRIBUTE_SYSTEM is needed to ensure that
1641 * FILE_ATTRIBUTE_ENCRYPTED doesn't get set before we want it to be. */
1643 status = create_file(&h, perms, NULL, FILE_ATTRIBUTE_SYSTEM,
1644 FILE_OPEN_IF, FILE_DIRECTORY_FILE, dentry, ctx);
1645 if (unlikely(!NT_SUCCESS(status))) {
1646 if (status == STATUS_ACCESS_DENIED) {
1647 if (perms & WRITE_DAC) {
1648 perms &= ~WRITE_DAC;
1651 if (perms & DELETE) {
1656 const wchar_t *path = current_path(ctx);
1657 winnt_error(status, L"Can't create directory \"%ls\"", path);
1659 /* Check for known issue with WindowsApps directory. */
1660 if (status == STATUS_ACCESS_DENIED &&
1661 (wcsstr(path, L"\\WindowsApps\\") ||
1662 wcsstr(path, L"\\InfusedApps\\"))) {
1664 "You seem to be trying to extract files to the WindowsApps directory.\n"
1665 " Windows 8.1 and later use new file permissions in this directory that\n"
1666 " cannot be overridden, even by backup/restore programs. To extract your\n"
1667 " files anyway, you need to choose a different target directory, delete\n"
1668 " the WindowsApps directory entirely, reformat the volume, do the\n"
1669 " extraction from a non-broken operating system such as Windows 7 or\n"
1670 " Linux, or wait for Microsoft to fix the design flaw in their operating\n"
1671 " system. This is *not* a bug in wimlib. See this thread for more\n"
1672 " information: https://wimlib.net/forums/viewtopic.php?f=1&t=261");
1674 return WIMLIB_ERR_MKDIR;
1677 if (ctx->iosb.Information == FILE_OPENED) {
1678 /* If we opened an existing directory, try to clear its file
1679 * attributes. As far as I know, this only actually makes a
1680 * difference in the case where a FILE_ATTRIBUTE_READONLY
1681 * directory has a named data stream which needs to be
1682 * extracted. You cannot create a named data stream of such a
1683 * directory, even though this contradicts Microsoft's
1684 * documentation for FILE_ATTRIBUTE_READONLY which states it is
1685 * not honored for directories! */
1686 if (!(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
1687 FILE_BASIC_INFORMATION basic_info =
1688 { .FileAttributes = FILE_ATTRIBUTE_NORMAL };
1689 NtSetInformationFile(h, &ctx->iosb, &basic_info,
1691 FileBasicInformation);
1695 if (!dentry_is_root(dentry)) {
1696 ret = set_short_name(h, dentry, ctx);
1701 ret = adjust_compression_attribute(h, dentry, ctx);
1708 * Create all the directories being extracted, other than the target directory
1711 * Note: we don't honor directory hard links. However, we don't allow them to
1712 * exist in WIM images anyway (see inode_fixup.c).
1715 create_directories(struct list_head *dentry_list,
1716 struct win32_apply_ctx *ctx)
1718 const struct wim_dentry *dentry;
1721 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1723 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
1726 /* Note: Here we include files with
1727 * FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT, but we
1728 * wait until later to actually set the reparse data. */
1730 ret = create_directory(dentry, ctx);
1733 ret = create_empty_streams(dentry, ctx);
1735 ret = check_apply_error(dentry, ctx, ret);
1739 ret = report_file_created(&ctx->common);
1747 * Creates the nondirectory file named by @dentry.
1749 * On success, returns an open handle to the file in @h_ret, with GENERIC_READ,
1750 * GENERIC_WRITE, and DELETE access. Also, the path to the file will be saved
1751 * in ctx->pathbuf. On failure, returns an error code.
1754 create_nondirectory_inode(HANDLE *h_ret, const struct wim_dentry *dentry,
1755 struct win32_apply_ctx *ctx)
1760 build_extraction_path(dentry, ctx);
1762 ret = supersede_file_or_stream(ctx,
1763 GENERIC_READ | GENERIC_WRITE | DELETE,
1768 ret = adjust_compression_attribute(h, dentry, ctx);
1772 ret = create_empty_streams(dentry, ctx);
1785 /* Creates a hard link at the location named by @dentry to the file represented
1786 * by the open handle @h. Or, if the target volume does not support hard links,
1787 * create a separate file instead. */
1789 create_link(HANDLE h, const struct wim_dentry *dentry,
1790 struct win32_apply_ctx *ctx)
1792 if (ctx->common.supported_features.hard_links) {
1794 build_extraction_path(dentry, ctx);
1796 size_t bufsize = offsetof(FILE_LINK_INFORMATION, FileName) +
1797 ctx->pathbuf.Length + sizeof(wchar_t);
1798 u8 buf[bufsize] _aligned_attribute(8);
1799 FILE_LINK_INFORMATION *info = (FILE_LINK_INFORMATION *)buf;
1802 info->ReplaceIfExists = TRUE;
1803 info->RootDirectory = ctx->attr.RootDirectory;
1804 info->FileNameLength = ctx->pathbuf.Length;
1805 memcpy(info->FileName, ctx->pathbuf.Buffer, ctx->pathbuf.Length);
1806 info->FileName[info->FileNameLength / 2] = L'\0';
1808 /* Note: the null terminator isn't actually necessary,
1809 * but if you don't add the extra character, you get
1810 * STATUS_INFO_LENGTH_MISMATCH when FileNameLength
1811 * happens to be 2 */
1813 status = NtSetInformationFile(h, &ctx->iosb, info, bufsize,
1814 FileLinkInformation);
1815 if (NT_SUCCESS(status))
1817 winnt_error(status, L"Failed to create link \"%ls\"",
1819 return WIMLIB_ERR_LINK;
1824 ret = create_nondirectory_inode(&h2, dentry, ctx);
1833 /* Given an inode (represented by the open handle @h) for which one link has
1834 * been created (named by @first_dentry), create the other links.
1836 * Or, if the target volume does not support hard links, create separate files.
1838 * Note: This uses ctx->pathbuf and does not reset it.
1841 create_links(HANDLE h, const struct wim_dentry *first_dentry,
1842 struct win32_apply_ctx *ctx)
1844 const struct wim_inode *inode = first_dentry->d_inode;
1845 const struct wim_dentry *dentry;
1848 inode_for_each_extraction_alias(dentry, inode) {
1849 if (dentry != first_dentry) {
1850 ret = create_link(h, dentry, ctx);
1858 /* Create a nondirectory file, including all links. */
1860 create_nondirectory(struct wim_inode *inode, struct win32_apply_ctx *ctx)
1862 struct wim_dentry *first_dentry;
1866 first_dentry = first_extraction_alias(inode);
1868 /* Create first link. */
1869 ret = create_nondirectory_inode(&h, first_dentry, ctx);
1873 /* Set short name. */
1874 ret = set_short_name(h, first_dentry, ctx);
1876 /* Create additional links, OR if hard links are not supported just
1877 * create more files. */
1879 ret = create_links(h, first_dentry, ctx);
1881 /* "WIMBoot" extraction: set external backing by the WIM file if needed. */
1882 if (!ret && unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT))
1883 ret = set_backed_from_wim(h, inode, ctx);
1889 /* Create all the nondirectory files being extracted, including all aliases
1892 create_nondirectories(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
1894 struct wim_dentry *dentry;
1895 struct wim_inode *inode;
1898 list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
1899 inode = dentry->d_inode;
1900 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
1902 /* Call create_nondirectory() only once per inode */
1903 if (dentry == inode_first_extraction_dentry(inode)) {
1904 ret = create_nondirectory(inode, ctx);
1905 ret = check_apply_error(dentry, ctx, ret);
1909 ret = report_file_created(&ctx->common);
1917 close_handles(struct win32_apply_ctx *ctx)
1919 for (unsigned i = 0; i < ctx->num_open_handles; i++)
1920 NtClose(ctx->open_handles[i]);
1923 /* Prepare to read the next blob, which has size @blob_size, into an in-memory
1926 prepare_data_buffer(struct win32_apply_ctx *ctx, u64 blob_size)
1928 if (blob_size > ctx->data_buffer_size) {
1929 /* Larger buffer needed. */
1931 if ((size_t)blob_size != blob_size)
1933 new_buffer = REALLOC(ctx->data_buffer, blob_size);
1936 ctx->data_buffer = new_buffer;
1937 ctx->data_buffer_size = blob_size;
1939 /* On the first call this changes data_buffer_ptr from NULL, which tells
1940 * extract_chunk() that the data buffer needs to be filled while reading
1941 * the stream data. */
1942 ctx->data_buffer_ptr = ctx->data_buffer;
1947 begin_extract_blob_instance(const struct blob_descriptor *blob,
1948 struct wim_dentry *dentry,
1949 const struct wim_inode_stream *strm,
1950 struct win32_apply_ctx *ctx)
1952 FILE_ALLOCATION_INFORMATION alloc_info;
1956 if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
1957 /* We can't write the reparse point stream directly; we must set
1958 * it with FSCTL_SET_REPARSE_POINT, which requires that all the
1959 * data be available. So, stage the data in a buffer. */
1960 if (!prepare_data_buffer(ctx, blob->size))
1961 return WIMLIB_ERR_NOMEM;
1962 list_add_tail(&dentry->d_tmp_list, &ctx->reparse_dentries);
1966 if (unlikely(strm->stream_type == STREAM_TYPE_EFSRPC_RAW_DATA)) {
1967 /* We can't write encrypted files directly; we must use
1968 * WriteEncryptedFileRaw(), which requires providing the data
1969 * through a callback function. This can't easily be combined
1970 * with our own callback-based approach.
1972 * The current workaround is to simply read the blob into memory
1973 * and write the encrypted file from that.
1975 * TODO: This isn't sufficient for extremely large encrypted
1976 * files. Perhaps we should create an extra thread to write
1978 if (!prepare_data_buffer(ctx, blob->size))
1979 return WIMLIB_ERR_NOMEM;
1980 list_add_tail(&dentry->d_tmp_list, &ctx->encrypted_dentries);
1984 /* It's a data stream (may be unnamed or named). */
1985 wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
1987 if (ctx->num_open_handles == MAX_OPEN_FILES) {
1988 /* XXX: Fix this. But because of the checks in
1989 * extract_blob_list(), this can now only happen on a filesystem
1990 * that does not support hard links. */
1991 ERROR("Can't extract data: too many open files!");
1992 return WIMLIB_ERR_UNSUPPORTED;
1996 if (unlikely(stream_is_named(strm))) {
1997 build_extraction_path_with_ads(dentry, ctx,
1999 utf16le_len_chars(strm->stream_name));
2001 build_extraction_path(dentry, ctx);
2005 /* Open a new handle */
2006 status = do_create_file(&h,
2007 FILE_WRITE_DATA | SYNCHRONIZE,
2008 NULL, 0, FILE_OPEN_IF,
2009 FILE_SEQUENTIAL_ONLY |
2010 FILE_SYNCHRONOUS_IO_NONALERT,
2012 if (!NT_SUCCESS(status)) {
2013 winnt_error(status, L"Can't open \"%ls\" for writing",
2015 return WIMLIB_ERR_OPEN;
2018 ctx->open_handles[ctx->num_open_handles++] = h;
2020 /* Allocate space for the data. */
2021 alloc_info.AllocationSize.QuadPart = blob->size;
2022 NtSetInformationFile(h, &ctx->iosb, &alloc_info, sizeof(alloc_info),
2023 FileAllocationInformation);
2027 /* Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2028 * pointer to the suffix of the path that begins with the device directly, such
2029 * as e:\Windows\System32. */
2030 static const wchar_t *
2031 skip_nt_toplevel_component(const wchar_t *path, size_t path_nchars)
2033 static const wchar_t * const dirs[] = {
2038 const wchar_t * const end = path + path_nchars;
2040 for (size_t i = 0; i < ARRAY_LEN(dirs); i++) {
2041 size_t len = wcslen(dirs[i]);
2042 if (len <= (end - path) && !wmemcmp(path, dirs[i], len)) {
2044 while (path != end && *path == L'\\')
2053 * Given a Windows NT namespace path, such as \??\e:\Windows\System32, return a
2054 * pointer to the suffix of the path that is device-relative but possibly with
2055 * leading slashes, such as \Windows\System32.
2057 * The path has an explicit length and is not necessarily null terminated.
2059 static const wchar_t *
2060 get_device_relative_path(const wchar_t *path, size_t path_nchars)
2062 const wchar_t * const orig_path = path;
2063 const wchar_t * const end = path + path_nchars;
2065 path = skip_nt_toplevel_component(path, path_nchars);
2066 if (path == orig_path)
2069 while (path != end && *path != L'\\')
2076 * Given a reparse point buffer for an inode for which the absolute link target
2077 * was relativized when it was archived, de-relative the link target to be
2078 * consistent with the actual extraction location.
2081 try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
2082 struct win32_apply_ctx *ctx)
2084 struct link_reparse_point link;
2085 size_t orig_subst_name_nchars;
2086 const wchar_t *relpath;
2087 size_t relpath_nchars;
2088 size_t target_ntpath_nchars;
2089 size_t fixed_subst_name_nchars;
2090 const wchar_t *fixed_print_name;
2091 size_t fixed_print_name_nchars;
2093 /* Do nothing if the reparse data is invalid. */
2094 if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link))
2097 /* Do nothing if the reparse point is a relative symbolic link. */
2098 if (link_is_relative_symlink(&link))
2101 /* Build the new substitute name from the NT namespace path to the
2102 * target directory, then a path separator, then the "device relative"
2103 * part of the old substitute name. */
2105 orig_subst_name_nchars = link.substitute_name_nbytes / sizeof(wchar_t);
2107 relpath = get_device_relative_path(link.substitute_name,
2108 orig_subst_name_nchars);
2109 relpath_nchars = orig_subst_name_nchars -
2110 (relpath - link.substitute_name);
2112 target_ntpath_nchars = ctx->target_ntpath.Length / sizeof(wchar_t);
2114 /* If the target directory is a filesystem root, such as \??\C:\, then
2115 * it already will have a trailing slash. Don't include this slash if
2116 * we are already adding slashes via 'relpath'. This prevents an extra
2117 * slash from being generated each time the link is extracted. And
2118 * unlike on UNIX, the number of slashes in paths on Windows can be
2119 * significant; Windows won't understand the link target if it contains
2120 * too many slashes. */
2121 if (target_ntpath_nchars > 0 && relpath_nchars > 0 &&
2122 ctx->target_ntpath.Buffer[target_ntpath_nchars - 1] == L'\\')
2123 target_ntpath_nchars--;
2125 /* Also remove extra slashes from the beginning of 'relpath'. Normally
2126 * this isn't needed, but this is here to make the extra slash(es) added
2127 * by wimlib pre-v1.9.1 get removed automatically. */
2128 while (relpath_nchars >= 2 &&
2129 relpath[0] == L'\\' && relpath[1] == L'\\') {
2134 fixed_subst_name_nchars = target_ntpath_nchars + relpath_nchars;
2136 wchar_t fixed_subst_name[fixed_subst_name_nchars];
2138 wmemcpy(fixed_subst_name, ctx->target_ntpath.Buffer, target_ntpath_nchars);
2139 wmemcpy(&fixed_subst_name[target_ntpath_nchars], relpath, relpath_nchars);
2140 /* Doesn't need to be null-terminated. */
2142 /* Print name should be Win32, but not all NT names can even be
2143 * translated to Win32 names. But we can at least delete the top-level
2144 * directory, such as \??\, and this will have the expected result in
2145 * the usual case. */
2146 fixed_print_name = skip_nt_toplevel_component(fixed_subst_name,
2147 fixed_subst_name_nchars);
2148 fixed_print_name_nchars = fixed_subst_name_nchars - (fixed_print_name -
2151 link.substitute_name = fixed_subst_name;
2152 link.substitute_name_nbytes = fixed_subst_name_nchars * sizeof(wchar_t);
2153 link.print_name = (wchar_t *)fixed_print_name;
2154 link.print_name_nbytes = fixed_print_name_nchars * sizeof(wchar_t);
2155 make_link_reparse_point(&link, rpbuf, rpbuflen_p);
2158 /* Sets the reparse point on the specified file. This handles "fixing" the
2159 * targets of absolute symbolic links and junctions if WIMLIB_EXTRACT_FLAG_RPFIX
2162 set_reparse_point(const struct wim_dentry *dentry,
2163 const struct reparse_buffer_disk *rpbuf, u16 rpbuflen,
2164 struct win32_apply_ctx *ctx)
2166 if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
2167 && !(dentry->d_inode->i_rp_flags & WIM_RP_FLAG_NOT_FIXED))
2169 memcpy(&ctx->rpfixbuf, rpbuf, rpbuflen);
2170 try_rpfix(&ctx->rpfixbuf, &rpbuflen, ctx);
2171 rpbuf = &ctx->rpfixbuf;
2173 return do_set_reparse_point(dentry, rpbuf, rpbuflen, ctx);
2177 /* Import the next block of raw encrypted data */
2179 import_encrypted_data(PBYTE pbData, PVOID pvCallbackContext, PULONG Length)
2181 struct win32_apply_ctx *ctx = pvCallbackContext;
2184 copy_len = min(ctx->encrypted_size - ctx->encrypted_offset, *Length);
2185 memcpy(pbData, &ctx->data_buffer[ctx->encrypted_offset], copy_len);
2186 ctx->encrypted_offset += copy_len;
2188 return ERROR_SUCCESS;
2192 * Write the raw encrypted data to the already-created file (or directory)
2193 * corresponding to @dentry.
2195 * The raw encrypted data is provided in ctx->data_buffer, and its size is
2196 * ctx->encrypted_size.
2198 * This function may close the target directory, in which case the caller needs
2199 * to re-open it if needed.
2202 extract_encrypted_file(const struct wim_dentry *dentry,
2203 struct win32_apply_ctx *ctx)
2210 /* Temporarily build a Win32 path for OpenEncryptedFileRaw() */
2211 build_win32_extraction_path(dentry, ctx);
2213 flags = CREATE_FOR_IMPORT | OVERWRITE_HIDDEN;
2214 if (dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
2215 flags |= CREATE_FOR_DIR;
2219 err = OpenEncryptedFileRaw(ctx->pathbuf.Buffer, flags, &rawctx);
2220 if (err == ERROR_SHARING_VIOLATION && !retried) {
2221 /* This can be caused by the handle we have open to the target
2222 * directory. Try closing it temporarily. */
2223 close_target_directory(ctx);
2228 /* Restore the NT namespace path */
2229 build_extraction_path(dentry, ctx);
2231 if (err != ERROR_SUCCESS) {
2232 win32_error(err, L"Can't open \"%ls\" for encrypted import",
2234 return WIMLIB_ERR_OPEN;
2237 ctx->encrypted_offset = 0;
2239 err = WriteEncryptedFileRaw(import_encrypted_data, ctx, rawctx);
2241 CloseEncryptedFileRaw(rawctx);
2243 if (err != ERROR_SUCCESS) {
2244 win32_error(err, L"Can't import encrypted file \"%ls\"",
2246 return WIMLIB_ERR_WRITE;
2252 /* Called when starting to read a blob for extraction on Windows */
2254 begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
2256 struct win32_apply_ctx *ctx = _ctx;
2257 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2260 ctx->num_open_handles = 0;
2261 ctx->data_buffer_ptr = NULL;
2262 INIT_LIST_HEAD(&ctx->reparse_dentries);
2263 INIT_LIST_HEAD(&ctx->encrypted_dentries);
2265 for (u32 i = 0; i < blob->out_refcnt; i++) {
2266 const struct wim_inode *inode = targets[i].inode;
2267 const struct wim_inode_stream *strm = targets[i].stream;
2268 struct wim_dentry *dentry;
2270 /* A copy of the blob needs to be extracted to @inode. */
2272 if (ctx->common.supported_features.hard_links) {
2273 dentry = inode_first_extraction_dentry(inode);
2274 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2275 ret = check_apply_error(dentry, ctx, ret);
2279 /* Hard links not supported. Extract the blob
2280 * separately to each alias of the inode. */
2281 inode_for_each_extraction_alias(dentry, inode) {
2282 ret = begin_extract_blob_instance(blob, dentry, strm, ctx);
2283 ret = check_apply_error(dentry, ctx, ret);
2297 /* Called when the next chunk of a blob has been read for extraction on Windows
2300 extract_chunk(const void *chunk, size_t size, void *_ctx)
2302 struct win32_apply_ctx *ctx = _ctx;
2304 /* Write the data chunk to each open handle */
2305 for (unsigned i = 0; i < ctx->num_open_handles; i++) {
2306 u8 *bufptr = (u8 *)chunk;
2307 size_t bytes_remaining = size;
2309 while (bytes_remaining) {
2310 ULONG count = min(0xFFFFFFFF, bytes_remaining);
2312 status = NtWriteFile(ctx->open_handles[i],
2314 &ctx->iosb, bufptr, count,
2316 if (!NT_SUCCESS(status)) {
2317 winnt_error(status, L"Error writing data to target volume");
2318 return WIMLIB_ERR_WRITE;
2320 bufptr += ctx->iosb.Information;
2321 bytes_remaining -= ctx->iosb.Information;
2325 /* Copy the data chunk into the buffer (if needed) */
2326 if (ctx->data_buffer_ptr)
2327 ctx->data_buffer_ptr = mempcpy(ctx->data_buffer_ptr,
2333 get_system_compression_format(int extract_flags)
2335 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS4K)
2336 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2338 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS8K)
2339 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K;
2341 if (extract_flags & WIMLIB_EXTRACT_FLAG_COMPACT_XPRESS16K)
2342 return FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K;
2344 return FILE_PROVIDER_COMPRESSION_FORMAT_LZX;
2348 static const wchar_t *
2349 get_system_compression_format_string(int format)
2352 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K:
2354 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS8K:
2356 case FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS16K:
2357 return L"XPRESS16K";
2364 set_system_compression(HANDLE h, int format)
2368 struct wof_external_info wof_info;
2369 struct file_provider_external_info file_info;
2372 .version = WOF_CURRENT_VERSION,
2373 .provider = WOF_PROVIDER_FILE,
2376 .version = FILE_PROVIDER_CURRENT_VERSION,
2377 .compression_format = format,
2381 /* We intentionally use NtFsControlFile() rather than DeviceIoControl()
2382 * here because the "compressing this object would not save space"
2383 * status code does not map to a valid Win32 error code on older
2384 * versions of Windows (before Windows 10?). This can be a problem if
2385 * the WOFADK driver is being used rather than the regular WOF, since
2386 * WOFADK can be used on older versions of Windows. */
2387 status = winnt_fsctl(h, FSCTL_SET_EXTERNAL_BACKING,
2388 &in, sizeof(in), NULL, 0, NULL);
2390 if (status == 0xC000046F) /* "Compressing this object would not save space." */
2391 return STATUS_SUCCESS;
2396 /* Hard-coded list of files which the Windows bootloader may need to access
2397 * before the WOF driver has been loaded. */
2398 static wchar_t *bootloader_pattern_strings[] = {
2401 L"\\Windows\\AppPatch\\drvmain.sdb",
2402 L"\\Windows\\Boot\\DVD\\*",
2403 L"\\Windows\\Boot\\EFI\\*",
2404 L"\\Windows\\bootstat.dat",
2405 L"\\Windows\\Fonts\\vgaoem.fon",
2406 L"\\Windows\\Fonts\\vgasys.fon",
2407 L"\\Windows\\INF\\errata.inf",
2408 L"\\Windows\\System32\\config\\*",
2409 L"\\Windows\\System32\\ntkrnlpa.exe",
2410 L"\\Windows\\System32\\ntoskrnl.exe",
2411 L"\\Windows\\System32\\bootvid.dll",
2412 L"\\Windows\\System32\\ci.dll",
2413 L"\\Windows\\System32\\hal*.dll",
2414 L"\\Windows\\System32\\mcupdate_AuthenticAMD.dll",
2415 L"\\Windows\\System32\\mcupdate_GenuineIntel.dll",
2416 L"\\Windows\\System32\\pshed.dll",
2417 L"\\Windows\\System32\\apisetschema.dll",
2418 L"\\Windows\\System32\\api-ms-win*.dll",
2419 L"\\Windows\\System32\\ext-ms-win*.dll",
2420 L"\\Windows\\System32\\KernelBase.dll",
2421 L"\\Windows\\System32\\drivers\\*.sys",
2422 L"\\Windows\\System32\\*.nls",
2423 L"\\Windows\\System32\\kbd*.dll",
2424 L"\\Windows\\System32\\kd*.dll",
2425 L"\\Windows\\System32\\clfs.sys",
2426 L"\\Windows\\System32\\CodeIntegrity\\driver.stl",
2429 static const struct string_list bootloader_patterns = {
2430 .strings = bootloader_pattern_strings,
2431 .num_strings = ARRAY_LEN(bootloader_pattern_strings),
2435 set_system_compression_on_inode(struct wim_inode *inode, int format,
2436 struct win32_apply_ctx *ctx)
2438 bool retried = false;
2442 /* If it may be needed for compatibility with the Windows bootloader,
2443 * force this file to XPRESS4K or uncompressed format. The bootloader
2444 * of Windows 10 supports XPRESS4K only; older versions don't support
2445 * system compression at all. */
2446 if (!is_image_windows_10_or_later(ctx) ||
2447 format != FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K)
2449 /* We need to check the patterns against every name of the
2450 * inode, in case any of them match. */
2451 struct wim_dentry *dentry;
2452 inode_for_each_extraction_alias(dentry, inode) {
2456 if (calculate_dentry_full_path(dentry)) {
2457 ERROR("Unable to compute file path!");
2458 return STATUS_NO_MEMORY;
2461 incompatible = match_pattern_list(dentry->d_full_path,
2462 &bootloader_patterns);
2463 FREE(dentry->d_full_path);
2464 dentry->d_full_path = NULL;
2469 warned = (ctx->num_system_compression_exclusions++ > 0);
2471 if (is_image_windows_10_or_later(ctx)) {
2472 /* Force to XPRESS4K */
2474 WARNING("For compatibility with the "
2475 "Windows bootloader, some "
2478 "using the XPRESS4K format "
2479 "instead of the %"TS" format\n"
2481 get_system_compression_format_string(format));
2483 format = FILE_PROVIDER_COMPRESSION_FORMAT_XPRESS4K;
2486 /* Force to uncompressed */
2488 WARNING("For compatibility with the "
2489 "Windows bootloader, some "
2491 " be compressed with"
2492 " system compression "
2493 "(\"compacted\").");
2495 return STATUS_SUCCESS;
2501 /* Open the extracted file. */
2502 status = create_file(&h, GENERIC_READ | GENERIC_WRITE, NULL,
2504 inode_first_extraction_dentry(inode), ctx);
2506 if (!NT_SUCCESS(status))
2509 /* Compress the file. If the attempt fails with "invalid device
2510 * request", then attach wof.sys (or wofadk.sys) and retry. */
2511 status = set_system_compression(h, format);
2512 if (unlikely(status == STATUS_INVALID_DEVICE_REQUEST && !retried)) {
2513 wchar_t drive_path[7];
2514 if (!win32_get_drive_path(ctx->common.target, drive_path) &&
2515 win32_try_to_attach_wof(drive_path + 4)) {
2526 * This function is called when doing a "compact-mode" extraction and we just
2527 * finished extracting a blob to one or more locations. For each location that
2528 * was the unnamed data stream of a file, this function compresses the
2529 * corresponding file using System Compression, if allowed.
2531 * Note: we're doing the compression immediately after extracting the data
2532 * rather than during a separate compression pass. This way should be faster
2533 * since the operating system should still have the file's data cached.
2535 * Note: we're having the operating system do the compression, which is not
2536 * ideal because wimlib could create the compressed data faster and more
2537 * efficiently (the compressed data format is identical to a WIM resource). But
2538 * we seemingly don't have a choice because WOF prevents applications from
2539 * creating its reparse points.
2542 handle_system_compression(struct blob_descriptor *blob, struct win32_apply_ctx *ctx)
2544 const struct blob_extraction_target *targets = blob_extraction_targets(blob);
2546 const int format = get_system_compression_format(ctx->common.extract_flags);
2548 for (u32 i = 0; i < blob->out_refcnt; i++) {
2549 struct wim_inode *inode = targets[i].inode;
2550 struct wim_inode_stream *strm = targets[i].stream;
2553 if (!stream_is_unnamed_data_stream(strm))
2556 if (will_externally_back_inode(inode, ctx, NULL, false) != 0)
2559 status = set_system_compression_on_inode(inode, format, ctx);
2560 if (likely(NT_SUCCESS(status)))
2563 if (status == STATUS_INVALID_DEVICE_REQUEST) {
2565 "The request to compress the extracted files using System Compression\n"
2566 " will not be honored because the operating system or target volume\n"
2567 " does not support it. System Compression is only supported on\n"
2568 " Windows 10 and later, and only on NTFS volumes.");
2569 ctx->common.extract_flags &= ~COMPACT_FLAGS;
2573 ctx->num_system_compression_failures++;
2574 if (ctx->num_system_compression_failures < 10) {
2575 winnt_warning(status, L"\"%ls\": Failed to compress "
2576 "extracted file using System Compression",
2578 } else if (ctx->num_system_compression_failures == 10) {
2579 WARNING("Suppressing further warnings about "
2580 "System Compression failures.");
2585 /* Called when a blob has been fully read for extraction on Windows */
2587 end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
2589 struct win32_apply_ctx *ctx = _ctx;
2591 const struct wim_dentry *dentry;
2598 if (unlikely(ctx->common.extract_flags & COMPACT_FLAGS))
2599 handle_system_compression(blob, ctx);
2601 if (likely(!ctx->data_buffer_ptr))
2604 if (!list_empty(&ctx->reparse_dentries)) {
2605 if (blob->size > REPARSE_DATA_MAX_SIZE) {
2606 dentry = list_first_entry(&ctx->reparse_dentries,
2607 struct wim_dentry, d_tmp_list);
2608 build_extraction_path(dentry, ctx);
2609 ERROR("Reparse data of \"%ls\" has size "
2610 "%"PRIu64" bytes (exceeds %u bytes)",
2611 current_path(ctx), blob->size,
2612 REPARSE_DATA_MAX_SIZE);
2613 ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
2614 return check_apply_error(dentry, ctx, ret);
2617 memcpy(ctx->rpbuf.rpdata, ctx->data_buffer, blob->size);
2619 list_for_each_entry(dentry, &ctx->reparse_dentries, d_tmp_list) {
2621 /* Reparse point header */
2622 complete_reparse_point(&ctx->rpbuf, dentry->d_inode,
2625 ret = set_reparse_point(dentry, &ctx->rpbuf,
2626 REPARSE_DATA_OFFSET + blob->size,
2628 ret = check_apply_error(dentry, ctx, ret);
2634 if (!list_empty(&ctx->encrypted_dentries)) {
2635 ctx->encrypted_size = blob->size;
2636 list_for_each_entry(dentry, &ctx->encrypted_dentries, d_tmp_list) {
2637 ret = extract_encrypted_file(dentry, ctx);
2638 ret = check_apply_error(dentry, ctx, ret);
2641 /* Re-open the target directory if needed. */
2642 ret = open_target_directory(ctx);
2651 /* Attributes that can't be set directly */
2652 #define SPECIAL_ATTRIBUTES \
2653 (FILE_ATTRIBUTE_REPARSE_POINT | \
2654 FILE_ATTRIBUTE_DIRECTORY | \
2655 FILE_ATTRIBUTE_ENCRYPTED | \
2656 FILE_ATTRIBUTE_SPARSE_FILE | \
2657 FILE_ATTRIBUTE_COMPRESSED)
2660 set_object_id(HANDLE h, const struct wim_inode *inode,
2661 struct win32_apply_ctx *ctx)
2663 const void *object_id;
2667 if (!ctx->common.supported_features.object_ids)
2670 object_id = inode_get_object_id(inode, &len);
2671 if (likely(object_id == NULL)) /* No object ID? */
2674 status = winnt_fsctl(h, FSCTL_SET_OBJECT_ID,
2675 object_id, len, NULL, 0, NULL);
2676 if (NT_SUCCESS(status))
2679 /* Object IDs must be unique within the filesystem. A duplicate might
2680 * occur if an image containing object IDs is applied twice to the same
2681 * filesystem. Arguably, the user should be warned in this case; but
2682 * the reality seems to be that nothing important cares about object IDs
2683 * except the Distributed Link Tracking Service... so for now these
2684 * failures are just ignored. */
2685 if (status == STATUS_DUPLICATE_NAME ||
2686 status == STATUS_OBJECT_NAME_COLLISION)
2689 ctx->num_object_id_failures++;
2690 if (ctx->num_object_id_failures < 10) {
2691 winnt_warning(status, L"Can't set object ID on \"%ls\"",
2693 } else if (ctx->num_object_id_failures == 10) {
2694 WARNING("Suppressing further warnings about failure to set "
2699 /* Set the security descriptor @desc, of @desc_size bytes, on the file with open
2702 set_security_descriptor(HANDLE h, const void *_desc,
2703 size_t desc_size, struct win32_apply_ctx *ctx)
2705 SECURITY_INFORMATION info;
2707 SECURITY_DESCRIPTOR_RELATIVE *desc;
2710 * Ideally, we would just pass in the security descriptor buffer as-is.
2711 * But it turns out that Windows can mess up the security descriptor
2712 * even when using the low-level NtSetSecurityObject() function:
2714 * - Windows will clear SE_DACL_AUTO_INHERITED if it is set in the
2715 * passed buffer. To actually get Windows to set
2716 * SE_DACL_AUTO_INHERITED, the application must set the non-persistent
2717 * flag SE_DACL_AUTO_INHERIT_REQ. As usual, Microsoft didn't bother
2718 * to properly document either of these flags. It's unclear how
2719 * important SE_DACL_AUTO_INHERITED actually is, but to be safe we use
2720 * the SE_DACL_AUTO_INHERIT_REQ workaround to set it if needed.
2722 * - The above also applies to the equivalent SACL flags,
2723 * SE_SACL_AUTO_INHERITED and SE_SACL_AUTO_INHERIT_REQ.
2725 * - If the application says that it's setting
2726 * DACL_SECURITY_INFORMATION, then Windows sets SE_DACL_PRESENT in the
2727 * resulting security descriptor, even if the security descriptor the
2728 * application provided did not have a DACL. This seems to be
2729 * unavoidable, since omitting DACL_SECURITY_INFORMATION would cause a
2730 * default DACL to remain. Fortunately, this behavior seems harmless,
2731 * since the resulting DACL will still be "null" --- but it will be
2732 * "the other representation of null".
2734 * - The above also applies to SACL_SECURITY_INFORMATION and
2735 * SE_SACL_PRESENT. Again, it's seemingly unavoidable but "harmless"
2736 * that Windows changes the representation of a "null SACL".
2738 if (likely(desc_size <= STACK_MAX)) {
2739 desc = alloca(desc_size);
2741 desc = MALLOC(desc_size);
2743 return STATUS_NO_MEMORY;
2746 memcpy(desc, _desc, desc_size);
2748 if (likely(desc_size >= 4)) {
2750 if (desc->Control & SE_DACL_AUTO_INHERITED)
2751 desc->Control |= SE_DACL_AUTO_INHERIT_REQ;
2753 if (desc->Control & SE_SACL_AUTO_INHERITED)
2754 desc->Control |= SE_SACL_AUTO_INHERIT_REQ;
2758 * More API insanity. We want to set the entire security descriptor
2759 * as-is. But all available APIs require specifying the specific parts
2760 * of the security descriptor being set. Especially annoying is that
2761 * mandatory integrity labels are part of the SACL, but they aren't set
2762 * with SACL_SECURITY_INFORMATION. Instead, applications must also
2763 * specify LABEL_SECURITY_INFORMATION (Windows Vista, Windows 7) or
2764 * BACKUP_SECURITY_INFORMATION (Windows 8). But at least older versions
2765 * of Windows don't error out if you provide these newer flags...
2767 * Also, if the process isn't running as Administrator, then it probably
2768 * doesn't have SE_RESTORE_PRIVILEGE. In this case, it will always get
2769 * the STATUS_PRIVILEGE_NOT_HELD error by trying to set the SACL, even
2770 * if the security descriptor it provided did not have a SACL. By
2771 * default, in this case we try to recover and set as much of the
2772 * security descriptor as possible --- potentially excluding the DACL, and
2773 * even the owner, as well as the SACL.
2776 info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
2777 DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION |
2778 LABEL_SECURITY_INFORMATION | BACKUP_SECURITY_INFORMATION;
2782 * It's also worth noting that SetFileSecurity() is unusable because it
2783 * doesn't request "backup semantics" when it opens the file internally.
2784 * NtSetSecurityObject() seems to be the best function to use in backup
2785 * applications. (SetSecurityInfo() should also work, but it's harder
2786 * to use and must call NtSetSecurityObject() internally anyway.
2787 * BackupWrite() is theoretically usable as well, but it's inflexible
2788 * and poorly documented.)
2792 status = NtSetSecurityObject(h, info, desc);
2793 if (NT_SUCCESS(status))
2794 goto out_maybe_free_desc;
2796 /* Failed to set the requested parts of the security descriptor. If the
2797 * error was permissions-related, try to set fewer parts of the security
2798 * descriptor, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled. */
2799 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
2800 status == STATUS_ACCESS_DENIED) &&
2801 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2803 if (info & SACL_SECURITY_INFORMATION) {
2804 info &= ~(SACL_SECURITY_INFORMATION |
2805 LABEL_SECURITY_INFORMATION |
2806 BACKUP_SECURITY_INFORMATION);
2807 ctx->partial_security_descriptors++;
2810 if (info & DACL_SECURITY_INFORMATION) {
2811 info &= ~DACL_SECURITY_INFORMATION;
2814 if (info & OWNER_SECURITY_INFORMATION) {
2815 info &= ~OWNER_SECURITY_INFORMATION;
2818 /* Nothing left except GROUP, and if we removed it we
2819 * wouldn't have anything at all. */
2822 /* No part of the security descriptor could be set, or
2823 * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full security
2824 * descriptor could not be set. */
2825 if (!(info & SACL_SECURITY_INFORMATION))
2826 ctx->partial_security_descriptors--;
2827 ctx->no_security_descriptors++;
2829 out_maybe_free_desc:
2830 if (unlikely(desc_size > STACK_MAX))
2835 /* Set metadata on the open file @h from the WIM inode @inode. */
2837 do_apply_metadata_to_file(HANDLE h, const struct wim_inode *inode,
2838 struct win32_apply_ctx *ctx)
2840 FILE_BASIC_INFORMATION info;
2843 /* Set the file's object ID if present and object IDs are supported by
2844 * the filesystem. */
2845 set_object_id(h, inode, ctx);
2847 /* Set the file's security descriptor if present and we're not in
2849 if (inode_has_security_descriptor(inode) &&
2850 !(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
2852 const struct wim_security_data *sd;
2856 sd = wim_get_current_security_data(ctx->common.wim);
2857 desc = sd->descriptors[inode->i_security_id];
2858 desc_size = sd->sizes[inode->i_security_id];
2860 status = set_security_descriptor(h, desc, desc_size, ctx);
2861 if (!NT_SUCCESS(status) &&
2862 (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
2865 L"Can't set security descriptor on \"%ls\"",
2867 return WIMLIB_ERR_SET_SECURITY;
2871 /* Set attributes and timestamps */
2872 info.CreationTime.QuadPart = inode->i_creation_time;
2873 info.LastAccessTime.QuadPart = inode->i_last_access_time;
2874 info.LastWriteTime.QuadPart = inode->i_last_write_time;
2875 info.ChangeTime.QuadPart = 0;
2876 if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES) {
2877 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2879 info.FileAttributes = inode->i_attributes & ~SPECIAL_ATTRIBUTES;
2880 if (info.FileAttributes == 0)
2881 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2884 status = NtSetInformationFile(h, &ctx->iosb, &info, sizeof(info),
2885 FileBasicInformation);
2886 /* On FAT volumes we get STATUS_INVALID_PARAMETER if we try to set
2887 * attributes on the root directory. (Apparently because FAT doesn't
2888 * actually have a place to store those attributes!) */
2889 if (!NT_SUCCESS(status)
2890 && !(status == STATUS_INVALID_PARAMETER &&
2891 dentry_is_root(inode_first_extraction_dentry(inode))))
2893 winnt_error(status, L"Can't set basic metadata on \"%ls\"",
2895 return WIMLIB_ERR_SET_ATTRIBUTES;
2902 apply_metadata_to_file(const struct wim_dentry *dentry,
2903 struct win32_apply_ctx *ctx)
2905 const struct wim_inode *inode = dentry->d_inode;
2911 perms = FILE_WRITE_ATTRIBUTES | WRITE_DAC |
2912 WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
2914 build_extraction_path(dentry, ctx);
2916 /* Open a handle with as many relevant permissions as possible. */
2917 while (!NT_SUCCESS(status = do_create_file(&h, perms, NULL,
2918 0, FILE_OPEN, 0, ctx)))
2920 if (status == STATUS_PRIVILEGE_NOT_HELD ||
2921 status == STATUS_ACCESS_DENIED)
2923 if (perms & ACCESS_SYSTEM_SECURITY) {
2924 perms &= ~ACCESS_SYSTEM_SECURITY;
2927 if (perms & WRITE_DAC) {
2928 perms &= ~WRITE_DAC;
2931 if (perms & WRITE_OWNER) {
2932 perms &= ~WRITE_OWNER;
2936 winnt_error(status, L"Can't open \"%ls\" to set metadata",
2938 return WIMLIB_ERR_OPEN;
2941 ret = do_apply_metadata_to_file(h, inode, ctx);
2949 apply_metadata(struct list_head *dentry_list, struct win32_apply_ctx *ctx)
2951 const struct wim_dentry *dentry;
2954 /* We go in reverse so that metadata is set on all a directory's
2955 * children before the directory itself. This avoids any potential
2956 * problems with attributes, timestamps, or security descriptors. */
2957 list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node)
2959 ret = apply_metadata_to_file(dentry, ctx);
2960 ret = check_apply_error(dentry, ctx, ret);
2963 ret = report_file_metadata_applied(&ctx->common);
2970 /* Issue warnings about problems during the extraction for which warnings were
2971 * not already issued (due to the high number of potential warnings if we issued
2972 * them per-file). */
2974 do_warnings(const struct win32_apply_ctx *ctx)
2976 if (ctx->partial_security_descriptors == 0
2977 && ctx->no_security_descriptors == 0
2978 && ctx->num_set_short_name_failures == 0
2980 && ctx->num_remove_short_name_failures == 0
2985 WARNING("Extraction to \"%ls\" complete, but with one or more warnings:",
2986 ctx->common.target);
2987 if (ctx->num_set_short_name_failures) {
2988 WARNING("- Could not set short names on %lu files or directories",
2989 ctx->num_set_short_name_failures);
2992 if (ctx->num_remove_short_name_failures) {
2993 WARNING("- Could not remove short names on %lu files or directories"
2994 " (This is expected on Vista and earlier)",
2995 ctx->num_remove_short_name_failures);
2998 if (ctx->partial_security_descriptors) {
2999 WARNING("- Could only partially set the security descriptor\n"
3000 " on %lu files or directories.",
3001 ctx->partial_security_descriptors);
3003 if (ctx->no_security_descriptors) {
3004 WARNING("- Could not set security descriptor at all\n"
3005 " on %lu files or directories.",
3006 ctx->no_security_descriptors);
3008 if (ctx->partial_security_descriptors || ctx->no_security_descriptors) {
3009 WARNING("To fully restore all security descriptors, run the program\n"
3010 " with Administrator rights.");
3015 count_dentries(const struct list_head *dentry_list)
3017 const struct list_head *cur;
3020 list_for_each(cur, dentry_list)
3026 /* Extract files from a WIM image to a directory on Windows */
3028 win32_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
3031 struct win32_apply_ctx *ctx = (struct win32_apply_ctx *)_ctx;
3034 ret = prepare_target(dentry_list, ctx);
3038 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
3039 ret = start_wimboot_extraction(dentry_list, ctx);
3044 ctx->windows_build_number = xml_get_windows_build_number(ctx->common.wim->xml_info,
3045 ctx->common.wim->current_image);
3047 dentry_count = count_dentries(dentry_list);
3049 ret = start_file_structure_phase(&ctx->common, dentry_count);
3053 ret = create_directories(dentry_list, ctx);
3057 ret = create_nondirectories(dentry_list, ctx);
3061 ret = end_file_structure_phase(&ctx->common);
3065 struct read_blob_callbacks cbs = {
3066 .begin_blob = begin_extract_blob,
3067 .consume_chunk = extract_chunk,
3068 .end_blob = end_extract_blob,
3071 ret = extract_blob_list(&ctx->common, &cbs);
3075 ret = start_file_metadata_phase(&ctx->common, dentry_count);
3079 ret = apply_metadata(dentry_list, ctx);
3083 ret = end_file_metadata_phase(&ctx->common);
3087 if (unlikely(ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT)) {
3088 ret = end_wimboot_extraction(ctx);
3095 close_target_directory(ctx);
3096 if (ctx->target_ntpath.Buffer)
3097 HeapFree(GetProcessHeap(), 0, ctx->target_ntpath.Buffer);
3098 FREE(ctx->pathbuf.Buffer);
3099 FREE(ctx->print_buffer);
3100 FREE(ctx->wimboot.wims);
3101 if (ctx->prepopulate_pats) {
3102 FREE(ctx->prepopulate_pats->strings);
3103 FREE(ctx->prepopulate_pats);
3105 FREE(ctx->mem_prepopulate_pats);
3106 FREE(ctx->data_buffer);
3110 const struct apply_operations win32_apply_ops = {
3112 .get_supported_features = win32_get_supported_features,
3113 .extract = win32_extract,
3114 .will_back_from_wim = win32_will_back_from_wim,
3115 .context_size = sizeof(struct win32_apply_ctx),
3118 #endif /* __WIN32__ */