字段
std.zig.WindowsSdk.Allocator
别名
别名目标 std.mem.Allocator
std.zig.WindowsSdk.builtin
常量
std.zig.WindowsSdk.Dir
别名
别名目标 std.Io.Dir
std.zig.WindowsSdk.Environ
别名
别名目标 std.process.Environ
std.zig.WindowsSdk.find
函数
查找 Windows 10 SDK、Windows 8.1 SDK 的路径和版本,以及 MSVC 的 lib/ 目录路径。
调用者拥有结果各字段的所有权。
返回由 gpa 分配的内存。
pub fn find( gpa: Allocator, io: Io, arch: std.Target.Cpu.Arch, environ_map: *const Environ.Map, ) error{ OutOfMemory, NotFound, PathTooLong }!WindowsSdk
参数
错误
- NotFound
- OutOfMemory
- PathTooLong
std.zig.WindowsSdk.free
函数
pub fn free(sdk: WindowsSdk, gpa: Allocator) void
参数
sdk: WindowsSdk
gpa: Allocator
std.zig.WindowsSdk.Installation
容器
字段
path: []const u8
version: []const u8
std.zig.WindowsSdk.Installation.find
函数
查找 Windows SDK 的路径和版本。 调用方拥有结果中各字段的所有权。
fn find( gpa: Allocator, io: Io, registry: *Registry, roots_key: Registry.Key, roots_subkey: []const u16, prefix: []const u8, version_key_name: []const u16, ) error{ OutOfMemory, InstallationNotFound, PathTooLong, VersionTooLong }!Installation
参数
gpa: Allocator
io: Io
registry: *Registry
roots_key: Registry.Key
roots_subkey: []const u16
prefix: []const u8
version_key_name: []const u16
错误
- InstallationNotFound
- OutOfMemory
- PathTooLong
- VersionTooLong
std.zig.WindowsSdk.Installation.findFromInstallationFolder
函数
fn findFromInstallationFolder( gpa: Allocator, registry: *Registry, version_key_name: []const u16, ) error{ OutOfMemory, InstallationNotFound, PathTooLong, VersionTooLong }!Installation
参数
错误
- InstallationNotFound
- OutOfMemory
- PathTooLong
- VersionTooLong
std.zig.WindowsSdk.Installation.findFromRoot
函数
fn findFromRoot( gpa: Allocator, io: Io, roots_key: Registry.Key, roots_subkey: []const u16, prefix: []const u8, ) error{ OutOfMemory, InstallationNotFound, PathTooLong, VersionTooLong }!Installation
参数
错误
- InstallationNotFound
- OutOfMemory
- PathTooLong
- VersionTooLong
std.zig.WindowsSdk.Installation.free
函数
fn free(install: Installation, gpa: Allocator) void
参数
install: Installation
gpa: Allocator
std.zig.WindowsSdk.Installation.isValidVersion
函数
检查注册表中是否列出了此版本。
fn isValidVersion(installation: Installation, roots_key: Registry.Key) bool
参数
installation: Installation
roots_key: Registry.Key
std.zig.WindowsSdk.Io
别名
别名目标 std.Io
std.zig.WindowsSdk.is_32_bit
常量
std.zig.WindowsSdk.iterateAndFilterByVersion
函数
通过 iterator 遍历,收集名称以 strip_prefix 和版本开头的全部目录。
返回按降序排列的版本字符串切片。
结果的所有权归调用者。
fn iterateAndFilterByVersion( iterator: *Dir.Iterator, gpa: Allocator, io: Io, prefix: []const u8, ) error{OutOfMemory}![][]const u8
参数
错误
- OutOfMemory
std.zig.WindowsSdk.iterateAndFilterByVersion.lessThan
函数
pub fn lessThan(context: @This(), lhs: usize, rhs: usize) bool
参数
context: @This()
lhs: usize
rhs: usize
std.zig.WindowsSdk.iterateAndFilterByVersion.order
函数
fn order(lhs: @This(), rhs: @This()) std.math.Order
参数
lhs: @This()
rhs: @This()
std.zig.WindowsSdk.iterateAndFilterByVersion.parseNum
函数
fn parseNum(num: []const u8) ?u32
参数
num: []const u8
std.zig.WindowsSdk.iterateAndFilterByVersion.swap
函数
pub fn swap(context: @This(), lhs: usize, rhs: usize) void
参数
context: @This()
lhs: usize
rhs: usize
std.zig.WindowsSdk.L
别名
std.zig.WindowsSdk.MsvcLibDir
命名空间
std.zig.WindowsSdk.MsvcLibDir.find
函数
查找 MSVC 的 lib/ 目录路径。
调用方拥有返回结果的所有权。
pub fn find( gpa: Allocator, io: Io, registry: *Registry, arch: std.Target.Cpu.Arch, environ_map: *const Environ.Map, ) error{ OutOfMemory, MsvcLibDirNotFound }![]const u8
参数
错误
- MsvcLibDirNotFound
- OutOfMemory
std.zig.WindowsSdk.MsvcLibDir.findInstancesDir
函数
fn findInstancesDir( gpa: Allocator, io: Io, registry: *Registry, environ_map: *const Environ.Map, ) error{ OutOfMemory, PathNotFound }!Dir
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.findInstancesDirViaCLSID
函数
fn findInstancesDirViaCLSID(gpa: Allocator, io: Io, registry: *Registry) error{ OutOfMemory, PathNotFound }!Dir
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.findInstancesDirViaSetup
函数
fn findInstancesDirViaSetup(gpa: Allocator, io: Io, registry: *Registry) error{ OutOfMemory, PathNotFound }!Dir
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.findViaCOM
函数
旨在等价于 ISetupConfiguration.EnumInstances: https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.setup.configuration 但不使用 COM,以避免依赖 ole32.dll。
通过 Procmon 验证,此函数中的逻辑旨在匹配 ISetupConfiguration 的底层实现。
fn findViaCOM( gpa: Allocator, io: Io, registry: *Registry, arch: std.Target.Cpu.Arch, environ_map: *const Environ.Map, ) error{ OutOfMemory, PathNotFound }![]const u8
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.findViaRegistry
函数
fn findViaRegistry( gpa: Allocator, io: Io, arch: std.Target.Cpu.Arch, environ_map: *const Environ.Map, ) error{ OutOfMemory, PathNotFound }![]const u8
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.findViaVs7Key
函数
fn findViaVs7Key( gpa: Allocator, io: Io, registry: *Registry, arch: std.Target.Cpu.Arch, environ_map: *const Environ.Map, ) error{ OutOfMemory, PathNotFound }![]const u8
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.libDirFromInstallationPath
函数
fn libDirFromInstallationPath( gpa: Allocator, io: Io, installation_path: []const u8, arch: std.Target.Cpu.Arch, ) error{ OutOfMemory, PathNotFound }![]const u8
参数
错误
- OutOfMemory
- PathNotFound
std.zig.WindowsSdk.MsvcLibDir.parseVersionQuad
函数
旨在等价于 ISetupHelper.ParseVersion
示例:17.4.33205.214 -> 0x0011000481b500d6
fn parseVersionQuad(version: []const u8) error{InvalidVersion}!u64
参数
version: []const u8
错误
- InvalidVersion
std.zig.WindowsSdk.MsvcLibDir.verifyLibDir
函数
fn verifyLibDir(io: Io, lib_dir_path: []const u8) bool
参数
io: Io
lib_dir_path: []const u8
std.zig.WindowsSdk.product_version_max_length
常量
std.zig.WindowsSdk.Registry
容器
这不是基于 ntdll 的通用注册表接口实现,只支持查找 SDK/MSVC 安装路径所必需的特定调用。
传入 HKEY_LOCAL_MACHINE(HKLM)和 HKEY_CURRENT_USER(HKCU)时,advapi32 接口在内部打开并缓存 \Registry\Machine 和当前用户键,还会在适当时重写键路径,使其经过 WOW6432Node。
例如,设置 WOW64_32KEY 选项后,相对于 HKEY_LOCAL_MACHINE 打开 Software\Foo,最终会调用 NtLoadKeyEx,相对于缓存的 \REGISTRY\Machine 键使用重写后的 Software\WOW6432Node\Foo 路径。
这里实际只关心 Software 键的四种潜在形式:
- 相对于 HKLM,不通过 WOW6432Node 重定向
- 相对于 HKLM,通过 WOW6432Node 重定向
- 相对于 HKCU,不通过 WOW6432Node 重定向
- 相对于 HKCU,通过 WOW6432Node 重定向
也就是说,所需值都位于其中某个
Software键下。
因此,缓存这些 Software 键的变体,而非 HKLM/HKCU,并将它们视为用户可指定的“根”键。这样既使全部输入路径无须关心 WOW6432Node,也避免内部路径重写,还能在 32 位目标上直接正确运行。
例如,advapi32 相对于 HKEY_LOCAL_MACHINE 打开 Software\Foo 的调用可能被重写为 Software\WOW6432Node\Foo;现在的等价操作则是相对于某个 Software 键变体打开 Foo。
字段
cache: Cache = .{}
std.zig.WindowsSdk.Registry.Cache
容器
字段
hklm_software_foreign: if (is_32_bit) void else ?windows.HANDLE = if (is_32_bit) {} else null
hkcu_software_foreign: if (is_32_bit) void else ?windows.HANDLE = if (is_32_bit) {} else null
hklm_software_native: ?windows.HANDLE = null
hkcu_software_native: ?windows.HANDLE = null
hkcu: ?windows.HANDLE = null
std.zig.WindowsSdk.Registry.Cache.getSoftware
函数
fn getSoftware(cache: *const Cache, variant: Software) ?windows.HANDLE
参数
std.zig.WindowsSdk.Registry.deinit
函数
pub fn deinit(self: Registry) void
参数
self: Registry
std.zig.WindowsSdk.Registry.Key
容器
字段
std.zig.WindowsSdk.Registry.Key.close
函数
fn close(self: Key) void
参数
self: Key
std.zig.WindowsSdk.Registry.Key.getDword
函数
fn getDword(key: Key, entry: ValueEntry) error{ ValueNameNotFound, NotADword, DwordNotFound }!windows.DWORD
参数
key: Key
entry: ValueEntry
错误
- DwordNotFound
- NotADword
- ValueNameNotFound
std.zig.WindowsSdk.Registry.Key.getString
函数
fn getString( key: Key, gpa: Allocator, entry: ValueEntry, comptime result_encoding: enum { wtf16, wtf8 }, ) error{ OutOfMemory, ValueNameNotFound, NotAString, StringNotFound }!(switch (result_encoding) { .wtf8 => []u8, .wtf16 => []u16, })
参数
错误
- NotAString
- OutOfMemory
- StringNotFound
- ValueNameNotFound
std.zig.WindowsSdk.Registry.Key.open
函数
fn open(self: Key, sub_path: []const u16) error{KeyNotFound}!Key
参数
self: Key
sub_path: []const u16
错误
- KeyNotFound
std.zig.WindowsSdk.Registry.Key.ValueEntry
容器
字段
default: void
name: []const u16
std.zig.WindowsSdk.Registry.openSoftwareKey
函数
fn openSoftwareKey(registry: *Registry, software: Software, sub_path: []const u16) error{KeyNotFound}!Key
参数
错误
- KeyNotFound
std.zig.WindowsSdk.Registry.Software
容器
字段
std.zig.WindowsSdk.Registry.Software.getOrOpenKey
函数
fn getOrOpenKey(self: Software, registry: *Registry) !Key
参数
std.zig.WindowsSdk.Registry.Software.Root
容器
字段
local_machine
current_user
std.zig.WindowsSdk.Registry.tryOpenSoftwareKeyWithPrecedence
函数
fn tryOpenSoftwareKeyWithPrecedence(registry: *Registry, variants: []const Software, sub_path: []const u16) error{KeyNotFound}!Key
参数
错误
- KeyNotFound
std.zig.WindowsSdk.Registry.Wow64
容器
在 64 位操作系统上运行的 32 位程序中,WOW64 版本的 ntdll.dll 会在调用真正的 ntdll.dll 前 处理 WOW6432Node 重定向,因此无需特殊处理, 此设置在该情况下无关紧要。
字段
native在 64 位目标上使用 64 位注册表,在 32 位目标上使用 32 位注册表。
wow64_32若适用,在 32 位和 64 位目标上均经由 WOW6432Node; 32 位操作系统上执行的 32 位程序忽略此项。
std.zig.WindowsSdk.std
别名
别名目标 std
std.zig.WindowsSdk.version_major_minor_max_length
常量
std.zig.WindowsSdk.windows
别名
别名目标 std.os.windows
std.zig.WindowsSdk.windows_kits_reg_key
常量
std.zig.WindowsSdk.WindowsSdk
别名
别名目标 std.zig.WindowsSdk
std.zig.WindowsSdk.Writer
别名
别名目标 std.Io.Writer
源码
std/zig/WindowsSdk.zig
const WindowsSdk = @This();
const builtin = @import("builtin");
const std = @import("std");
const Io = std.Io;
const Dir = std.Io.Dir;
const Writer = std.Io.Writer;
const Allocator = std.mem.Allocator;
const Environ = std.process.Environ;
const L = std.unicode.wtf8ToWtf16LeStringLiteral;
const is_32_bit = @bitSizeOf(usize) == 32;
windows10sdk: ?Installation,
windows81sdk: ?Installation,
msvc_lib_dir: ?[]const u8,
const windows = std.os.windows;
const windows_kits_reg_key = "Microsoft\\Windows Kits\\Installed Roots";
// https://learn.microsoft.com/en-us/windows/win32/msi/productversion
const version_major_minor_max_length = "255.255".len;
// 注册表中的 ProductVersion(由 Visual Studio 安装程序创建)很可能也遵循此规则
const product_version_max_length = version_major_minor_max_length + ".65535".len;
/// 查找 Windows 10 SDK、Windows 8.1 SDK 的路径和版本,以及 MSVC 的 `lib/` 目录路径。
/// 调用者拥有结果各字段的所有权。
/// 返回由 `gpa` 分配的内存。
pub fn find(
gpa: Allocator,
io: Io,
arch: std.Target.Cpu.Arch,
environ_map: *const Environ.Map,
) error{ OutOfMemory, NotFound, PathTooLong }!WindowsSdk {
if (builtin.os.tag != .windows) return error.NotFound;
var registry: Registry = .{};
defer registry.deinit();
// 若此键不存在,则既未安装 Win 8 SDK,也未安装 Win 10 SDK
const roots_key = registry.openSoftwareKey(.{ .root = .local_machine, .wow64 = .wow64_32 }, L(windows_kits_reg_key)) catch |err| switch (err) {
error.KeyNotFound => return error.NotFound,
};
defer roots_key.close();
const windows10sdk = Installation.find(gpa, io, ®istry, roots_key, L("KitsRoot10"), "", L("v10.0")) catch |err| switch (err) {
error.InstallationNotFound => null,
error.PathTooLong => null,
error.VersionTooLong => null,
error.OutOfMemory => |e| return e,
};
errdefer if (windows10sdk) |*w| w.free(gpa);
const windows81sdk = Installation.find(gpa, io, ®istry, roots_key, L("KitsRoot81"), "winver", L("v8.1")) catch |err| switch (err) {
error.InstallationNotFound => null,
error.PathTooLong => null,
error.VersionTooLong => null,
error.OutOfMemory => |e| return e,
};
errdefer if (windows81sdk) |*w| w.free(gpa);
const msvc_lib_dir: ?[]const u8 = MsvcLibDir.find(gpa, io, ®istry, arch, environ_map) catch |err| switch (err) {
error.MsvcLibDirNotFound => null,
error.OutOfMemory => |e| return e,
};
errdefer gpa.free(msvc_lib_dir);
return .{
.windows10sdk = windows10sdk,
.windows81sdk = windows81sdk,
.msvc_lib_dir = msvc_lib_dir,
};
}
pub fn free(sdk: WindowsSdk, gpa: Allocator) void {
if (sdk.windows10sdk) |*w10sdk| {
w10sdk.free(gpa);
}
if (sdk.windows81sdk) |*w81sdk| {
w81sdk.free(gpa);
}
if (sdk.msvc_lib_dir) |msvc_lib_dir| {
gpa.free(msvc_lib_dir);
}
}
/// 通过 `iterator` 遍历,收集名称以 `strip_prefix` 和版本开头的全部目录。
/// 返回按降序排列的版本字符串切片。
/// 结果的所有权归调用者。
fn iterateAndFilterByVersion(
iterator: *Dir.Iterator,
gpa: Allocator,
io: Io,
prefix: []const u8,
) error{OutOfMemory}![][]const u8 {
const Version = struct {
nums: [4]u32,
build: []const u8,
fn parseNum(num: []const u8) ?u32 {
if (num[0] == '0' and num.len > 1) return null;
return std.fmt.parseInt(u32, num, 10) catch null;
}
fn order(lhs: @This(), rhs: @This()) std.math.Order {
return std.mem.order(u32, &lhs.nums, &rhs.nums).differ() orelse
std.mem.order(u8, lhs.build, rhs.build);
}
};
var versions = std.array_list.Managed(Version).init(gpa);
var dirs = std.array_list.Managed([]const u8).init(gpa);
defer {
versions.deinit();
for (dirs.items) |filtered_dir| gpa.free(filtered_dir);
dirs.deinit();
}
iterate: while (iterator.next(io) catch null) |entry| {
if (entry.kind != .directory) continue;
if (!std.mem.startsWith(u8, entry.name, prefix)) continue;
var version: Version = .{
.nums = @splat(0),
.build = "",
};
const suffix = entry.name[prefix.len..];
const underscore = std.mem.findScalar(u8, entry.name, '_');
var num_it = std.mem.splitScalar(u8, suffix[0 .. underscore orelse suffix.len], '.');
version.nums[0] = Version.parseNum(num_it.first()) orelse continue;
for (version.nums[1..]) |*num|
num.* = Version.parseNum(num_it.next() orelse break) orelse continue :iterate
else if (num_it.next()) |_| continue;
const name = try gpa.dupe(u8, suffix);
errdefer gpa.free(name);
if (underscore) |pos| version.build = name[pos + 1 ..];
try versions.append(version);
try dirs.append(name);
}
std.mem.sortUnstableContext(0, dirs.items.len, struct {
versions: []Version,
dirs: [][]const u8,
pub fn lessThan(context: @This(), lhs: usize, rhs: usize) bool {
return context.versions[lhs].order(context.versions[rhs]).compare(.gt);
}
pub fn swap(context: @This(), lhs: usize, rhs: usize) void {
std.mem.swap(Version, &context.versions[lhs], &context.versions[rhs]);
std.mem.swap([]const u8, &context.dirs[lhs], &context.dirs[rhs]);
}
}{ .versions = versions.items, .dirs = dirs.items });
return dirs.toOwnedSlice();
}
/// 这不是基于 ntdll 的通用注册表接口实现,只支持查找 SDK/MSVC 安装路径所必需的特定调用。
///
/// 传入 HKEY_LOCAL_MACHINE(HKLM)和 HKEY_CURRENT_USER(HKCU)时,advapi32 接口在内部打开并缓存 `\Registry\Machine` 和当前用户键,还会在适当时重写键路径,使其经过 WOW6432Node。
///
/// 例如,设置 WOW64_32KEY 选项后,相对于 `HKEY_LOCAL_MACHINE` 打开 `Software\Foo`,最终会调用 NtLoadKeyEx,相对于缓存的 `\REGISTRY\Machine` 键使用重写后的 `Software\WOW6432Node\Foo` 路径。
///
/// 这里实际只关心 `Software` 键的四种潜在形式:
/// - 相对于 HKLM,不通过 WOW6432Node 重定向
/// - 相对于 HKLM,通过 WOW6432Node 重定向
/// - 相对于 HKCU,不通过 WOW6432Node 重定向
/// - 相对于 HKCU,通过 WOW6432Node 重定向
/// 也就是说,所需值都位于其中某个 `Software` 键下。
///
/// 因此,缓存这些 Software 键的变体,而非 HKLM/HKCU,并将它们视为用户可指定的“根”键。这样既使全部输入路径无须关心 WOW6432Node,也避免内部路径重写,还能在 32 位目标上直接正确运行。
///
/// 例如,advapi32 相对于 `HKEY_LOCAL_MACHINE` 打开 `Software\Foo` 的调用可能被重写为 `Software\WOW6432Node\Foo`;现在的等价操作则是相对于某个 Software 键变体打开 `Foo`。
///
///
///
///
///
///
///
///
///
///
///
///
const Registry = struct {
cache: Cache = .{},
pub fn deinit(self: Registry) void {
if (!is_32_bit) {
if (self.cache.hklm_software_foreign) |key| windows.CloseHandle(key);
if (self.cache.hkcu_software_foreign) |key| windows.CloseHandle(key);
}
if (self.cache.hklm_software_native) |key| windows.CloseHandle(key);
if (self.cache.hkcu_software_native) |key| windows.CloseHandle(key);
if (self.cache.hkcu) |key| windows.CloseHandle(key);
}
const Cache = struct {
hklm_software_foreign: if (is_32_bit) void else ?windows.HANDLE = if (is_32_bit) {} else null,
hkcu_software_foreign: if (is_32_bit) void else ?windows.HANDLE = if (is_32_bit) {} else null,
hklm_software_native: ?windows.HANDLE = null,
hkcu_software_native: ?windows.HANDLE = null,
hkcu: ?windows.HANDLE = null,
fn getSoftware(cache: *const Cache, variant: Software) ?windows.HANDLE {
if (!is_32_bit and variant.wow64 == .wow64_32) {
return switch (variant.root) {
.local_machine => cache.hklm_software_foreign,
.current_user => cache.hkcu_software_foreign,
};
}
return switch (variant.root) {
.local_machine => cache.hklm_software_native,
.current_user => cache.hkcu_software_native,
};
}
};
// 此值不对应 HKEY_LOCAL_MACHINE/HKEY_CURRENT_USER,
// 因为 WOW64 重定向适用于例如 `HKLM\Software`,而非
// 直接适用于 HKLM/HKCU。由于我们只关心
// `Software` 键,将 `Software` 视为“根”更合理,
// 这样就可以完全使用不受 WOW6432Node 重定向
// 影响的相对路径。
const Software = struct {
root: Root,
wow64: Wow64 = .native,
const Root = enum {
local_machine,
current_user,
};
fn getOrOpenKey(self: Software, registry: *Registry) !Key {
if (registry.cache.getSoftware(self)) |handle| {
return .{ .handle = handle };
}
const is_foreign = !is_32_bit and self.wow64 == .wow64_32;
switch (self.root) {
.local_machine => {
const path = if (is_foreign) L("\\Registry\\Machine\\Software\\WOW6432Node") else L("\\Registry\\Machine\\Software");
var key: Key = undefined;
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = null,
.Attributes = .{},
.ObjectName = @constCast(&windows.UNICODE_STRING.init(path)),
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
const status = windows.ntdll.NtOpenKeyEx(
&key.handle,
.{ .MAXIMUM_ALLOWED = true },
&attr,
.{},
);
switch (status) {
.SUCCESS => {},
else => return error.KeyNotFound,
}
if (is_foreign) {
registry.cache.hklm_software_foreign = key.handle;
} else {
registry.cache.hklm_software_native = key.handle;
}
return key;
},
.current_user => {
const cu_handle: windows.HANDLE = registry.cache.hkcu orelse hkcu: {
var cu_handle: windows.HANDLE = undefined;
const status = windows.ntdll.RtlOpenCurrentUser(
.{ .MAXIMUM_ALLOWED = true },
&cu_handle,
);
switch (status) {
.SUCCESS => {},
else => return error.KeyNotFound,
}
registry.cache.hkcu = cu_handle;
break :hkcu cu_handle;
};
const cu_key: Registry.Key = .{ .handle = cu_handle };
const path = if (is_foreign) L("Software\\WOW6432Node") else L("Software");
const key = try cu_key.open(path);
if (is_foreign) {
registry.cache.hkcu_software_foreign = key.handle;
} else {
registry.cache.hkcu_software_native = key.handle;
}
return key;
},
}
}
};
/// 在 64 位操作系统上运行的 32 位程序中,WOW64
/// 版本的 ntdll.dll 会在调用真正的 ntdll.dll 前
/// 处理 WOW6432Node 重定向,因此无需特殊处理,
/// 此设置在该情况下无关紧要。
const Wow64 = enum {
/// 在 64 位目标上使用 64 位注册表,在 32 位目标上使用 32 位注册表。
///
native,
/// 若适用,在 32 位和 64 位目标上均经由 WOW6432Node;
/// 32 位操作系统上执行的 32 位程序忽略此项。
///
wow64_32,
};
fn tryOpenSoftwareKeyWithPrecedence(registry: *Registry, variants: []const Software, sub_path: []const u16) error{KeyNotFound}!Key {
for (variants) |variant| {
return registry.openSoftwareKey(variant, sub_path) catch continue;
}
return error.KeyNotFound;
}
fn openSoftwareKey(registry: *Registry, software: Software, sub_path: []const u16) error{KeyNotFound}!Key {
const software_key = try software.getOrOpenKey(registry);
return software_key.open(sub_path);
}
const Key = struct {
handle: windows.HANDLE,
fn close(self: Key) void {
windows.CloseHandle(self.handle);
}
fn open(self: Key, sub_path: []const u16) error{KeyNotFound}!Key {
var key: Key = undefined;
const attr: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = self.handle,
.Attributes = .{},
.ObjectName = @constCast(&windows.UNICODE_STRING.init(sub_path)),
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
const status = windows.ntdll.NtOpenKeyEx(
&key.handle,
.{ .SPECIFIC = .{
.KEY = .{
.QUERY_VALUE = true,
.ENUMERATE_SUB_KEYS = true,
},
} },
&attr,
.{},
);
switch (status) {
.SUCCESS => return key,
else => return error.KeyNotFound,
}
}
const ValueEntry = union(enum) {
default: void,
name: []const u16,
};
fn getString(
key: Key,
gpa: Allocator,
entry: ValueEntry,
comptime result_encoding: enum { wtf16, wtf8 },
) error{ OutOfMemory, ValueNameNotFound, NotAString, StringNotFound }!(switch (result_encoding) {
.wtf8 => []u8,
.wtf16 => []u16,
}) {
const num_data_bytes = windows.MAX_PATH * 2;
const stack_buf_len = @sizeOf(windows.KEY.VALUE.PARTIAL_INFORMATION) + num_data_bytes;
var stack_info_buf: [stack_buf_len]u8 align(@alignOf(windows.KEY.VALUE.PARTIAL_INFORMATION)) = undefined;
var result_len: windows.ULONG = undefined;
const rc = windows.ntdll.NtQueryValueKey(
key.handle,
switch (entry) {
.name => |name| @constCast(&windows.UNICODE_STRING.init(name)),
.default => @constCast(&windows.UNICODE_STRING.empty),
},
.Partial,
&stack_info_buf,
stack_buf_len,
&result_len,
);
var heap_info_buf: ?[]align(@alignOf(windows.KEY.VALUE.PARTIAL_INFORMATION)) u8 = null;
defer if (heap_info_buf) |buf| gpa.free(buf);
const info: *const windows.KEY.VALUE.PARTIAL_INFORMATION = switch (rc) {
.SUCCESS => @ptrCast(&stack_info_buf),
.BUFFER_OVERFLOW, .BUFFER_TOO_SMALL => heap_info: {
heap_info_buf = try gpa.alignedAlloc(u8, .of(windows.KEY.VALUE.PARTIAL_INFORMATION), result_len);
const heap_rc = windows.ntdll.NtQueryValueKey(
key.handle,
switch (entry) {
.name => |name| @constCast(&windows.UNICODE_STRING.init(name)),
.default => @constCast(&windows.UNICODE_STRING.empty),
},
.Partial,
heap_info_buf.?.ptr,
@intCast(heap_info_buf.?.len),
&result_len,
);
switch (heap_rc) {
.SUCCESS => break :heap_info @ptrCast(heap_info_buf.?.ptr),
.OBJECT_NAME_NOT_FOUND => return error.ValueNameNotFound,
else => return error.StringNotFound,
}
},
.OBJECT_NAME_NOT_FOUND => return error.ValueNameNotFound,
else => return error.StringNotFound,
};
switch (info.Type) {
.SZ => {},
else => return error.NotAString,
}
const data_wtf16_with_nul = @as([*]const u16, @ptrCast(@alignCast(info.data())))[0..@divExact(info.DataLength, 2)];
const data_wtf16 = std.mem.trimEnd(u16, data_wtf16_with_nul, L("\x00"));
switch (result_encoding) {
.wtf16 => return gpa.dupe(u16, data_wtf16),
.wtf8 => return std.unicode.wtf16LeToWtf8Alloc(gpa, data_wtf16),
}
}
fn getDword(key: Key, entry: ValueEntry) error{ ValueNameNotFound, NotADword, DwordNotFound }!windows.DWORD {
const num_data_bytes = @sizeOf(windows.DWORD);
const buf_len = @sizeOf(windows.KEY.VALUE.PARTIAL_INFORMATION) + num_data_bytes;
var info_buf: [buf_len]u8 align(@alignOf(windows.KEY.VALUE.PARTIAL_INFORMATION)) = undefined;
var result_len: windows.ULONG = undefined;
const rc = windows.ntdll.NtQueryValueKey(
key.handle,
switch (entry) {
.name => |name| @constCast(&windows.UNICODE_STRING.init(name)),
.default => @constCast(&windows.UNICODE_STRING.empty),
},
.Partial,
&info_buf,
buf_len,
&result_len,
);
switch (rc) {
.SUCCESS => {},
.OBJECT_NAME_NOT_FOUND => return error.ValueNameNotFound,
else => return error.DwordNotFound,
}
const info: *const windows.KEY.VALUE.PARTIAL_INFORMATION = @ptrCast(&info_buf);
switch (info.Type) {
.DWORD => {},
else => return error.NotADword,
}
return std.mem.bytesToValue(windows.DWORD, info.data());
}
};
};
pub const Installation = struct {
path: []const u8,
version: []const u8,
/// 查找 Windows SDK 的路径和版本。
/// 调用方拥有结果中各字段的所有权。
fn find(
gpa: Allocator,
io: Io,
registry: *Registry,
roots_key: Registry.Key,
roots_subkey: []const u16,
prefix: []const u8,
version_key_name: []const u16,
) error{ OutOfMemory, InstallationNotFound, PathTooLong, VersionTooLong }!Installation {
roots: {
const installation = findFromRoot(gpa, io, roots_key, roots_subkey, prefix) catch
break :roots;
if (installation.isValidVersion(roots_key)) return installation;
installation.free(gpa);
}
{
const installation = try findFromInstallationFolder(gpa, registry, version_key_name);
if (installation.isValidVersion(roots_key)) return installation;
installation.free(gpa);
}
return error.InstallationNotFound;
}
fn findFromRoot(
gpa: Allocator,
io: Io,
roots_key: Registry.Key,
roots_subkey: []const u16,
prefix: []const u8,
) error{ OutOfMemory, InstallationNotFound, PathTooLong, VersionTooLong }!Installation {
const path = path: {
const path_w_maybe_with_trailing_slash = roots_key.getString(gpa, .{ .name = roots_subkey }, .wtf16) catch |err| switch (err) {
error.NotAString,
error.ValueNameNotFound,
error.StringNotFound,
=> return error.InstallationNotFound,
error.OutOfMemory => |e| return e,
};
defer gpa.free(path_w_maybe_with_trailing_slash);
if (!std.fs.path.isAbsoluteWindowsWtf16(path_w_maybe_with_trailing_slash)) {
return error.InstallationNotFound;
}
const path_w = std.mem.trimEnd(u16, path_w_maybe_with_trailing_slash, L("\\/"));
break :path try std.unicode.wtf16LeToWtf8Alloc(gpa, path_w);
};
errdefer gpa.free(path);
const version = version: {
var buf: [Dir.max_path_bytes]u8 = undefined;
const sdk_lib_dir_path = std.mem.print(buf[0..], "{s}\\Lib\\", .{path}) catch |err| switch (err) {
error.NoSpaceLeft => return error.PathTooLong,
};
if (!Dir.path.isAbsolute(sdk_lib_dir_path)) return error.InstallationNotFound;
// 枚举 SDK 路径中的文件,查找最新版本。
var sdk_lib_dir = Dir.openDirAbsolute(io, sdk_lib_dir_path, .{
.iterate = true,
}) catch |err| switch (err) {
error.NameTooLong => return error.PathTooLong,
else => return error.InstallationNotFound,
};
defer sdk_lib_dir.close(io);
var iterator = sdk_lib_dir.iterate();
const versions = try iterateAndFilterByVersion(&iterator, gpa, io, prefix);
if (versions.len == 0) return error.InstallationNotFound;
defer {
for (versions[1..]) |version| gpa.free(version);
gpa.free(versions);
}
break :version versions[0];
};
errdefer gpa.free(version);
return .{ .path = path, .version = version };
}
fn findFromInstallationFolder(
gpa: Allocator,
registry: *Registry,
version_key_name: []const u16,
) error{ OutOfMemory, InstallationNotFound, PathTooLong, VersionTooLong }!Installation {
const key_name = try std.mem.concat(gpa, u16, &.{ L("Microsoft\\Microsoft SDKs\\Windows\\"), version_key_name });
defer gpa.free(key_name);
const key = registry.tryOpenSoftwareKeyWithPrecedence(switch (is_32_bit) {
true => &.{
.{ .root = .local_machine },
.{ .root = .current_user },
},
false => &.{
.{ .root = .local_machine, .wow64 = .wow64_32 },
.{ .root = .current_user, .wow64 = .wow64_32 },
.{ .root = .local_machine, .wow64 = .native },
.{ .root = .current_user, .wow64 = .native },
},
}, key_name) catch {
return error.InstallationNotFound;
};
defer key.close();
const path: []const u8 = path: {
const path_w_maybe_with_trailing_slash = key.getString(gpa, .{ .name = L("InstallationFolder") }, .wtf16) catch |err| switch (err) {
error.NotAString,
error.ValueNameNotFound,
error.StringNotFound,
=> return error.InstallationNotFound,
error.OutOfMemory => |e| return e,
};
defer gpa.free(path_w_maybe_with_trailing_slash);
if (!std.fs.path.isAbsoluteWindowsWtf16(path_w_maybe_with_trailing_slash)) {
return error.InstallationNotFound;
}
const path_w = std.mem.trimEnd(u16, path_w_maybe_with_trailing_slash, L("\\/"));
break :path try std.unicode.wtf16LeToWtf8Alloc(gpa, path_w);
};
errdefer gpa.free(path);
const version: []const u8 = version: {
// Microsoft 的 ProductVersion 键不包含 .0
const version_without_0 = key.getString(gpa, .{ .name = L("ProductVersion") }, .wtf16) catch |err| switch (err) {
error.NotAString,
error.ValueNameNotFound,
error.StringNotFound,
=> return error.InstallationNotFound,
error.OutOfMemory => |e| return e,
};
defer gpa.free(version_without_0);
if (version_without_0.len + ".0".len > product_version_max_length) {
return error.VersionTooLong;
}
var version: std.array_list.Managed(u8) = try .initCapacity(gpa, version_without_0.len + 2);
errdefer version.deinit();
try std.unicode.wtf16LeToWtf8ArrayList(&version, version_without_0);
try version.appendSlice(".0");
break :version try version.toOwnedSlice();
};
errdefer gpa.free(version);
return .{ .path = path, .version = version };
}
/// 检查注册表中是否列出了此版本。
fn isValidVersion(installation: Installation, roots_key: Registry.Key) bool {
var version_buf: [product_version_max_length]u16 = undefined;
const version_len = std.unicode.wtf8ToWtf16Le(&version_buf, installation.version) catch return false;
const version = version_buf[0..version_len];
const options_key_name = "Installed Options";
const buf_len = product_version_max_length + options_key_name.len + 2;
var buf: [buf_len]u16 = undefined;
var query: std.ArrayList(u16) = .initBuffer(&buf);
query.appendSliceAssumeCapacity(version);
query.appendAssumeCapacity('\\');
query.appendSliceAssumeCapacity(L(options_key_name));
const options_key = roots_key.open(query.items) catch |err| switch (err) {
error.KeyNotFound => return false,
};
defer options_key.close();
const option_name = comptime switch (builtin.target.cpu.arch) {
.thumb => "OptionId.DesktopCPParm",
.aarch64 => "OptionId.DesktopCPParm64",
.x86 => "OptionId.DesktopCPPx86",
.x86_64 => "OptionId.DesktopCPPx64",
else => |tag| @compileError("Windows SDK cannot be detected on architecture " ++ tag),
};
const reg_value = options_key.getDword(.{ .name = L(option_name) }) catch return false;
return (reg_value == 1);
}
fn free(install: Installation, gpa: Allocator) void {
gpa.free(install.path);
gpa.free(install.version);
}
};
const MsvcLibDir = struct {
fn findInstancesDirViaSetup(gpa: Allocator, io: Io, registry: *Registry) error{ OutOfMemory, PathNotFound }!Dir {
const vs_setup_key_path = L("Microsoft\\VisualStudio\\Setup");
const vs_setup_key = registry.openSoftwareKey(.{ .root = .local_machine }, vs_setup_key_path) catch |err| switch (err) {
error.KeyNotFound => return error.PathNotFound,
};
defer vs_setup_key.close();
const packages_path = vs_setup_key.getString(gpa, .{ .name = L("CachePath") }, .wtf8) catch |err| switch (err) {
error.NotAString,
error.ValueNameNotFound,
error.StringNotFound,
=> return error.PathNotFound,
error.OutOfMemory => |e| return e,
};
defer gpa.free(packages_path);
if (!std.fs.path.isAbsolute(packages_path)) return error.PathNotFound;
const instances_path = try std.fs.path.join(gpa, &.{ packages_path, "_Instances" });
defer gpa.free(instances_path);
return Dir.openDirAbsolute(io, instances_path, .{ .iterate = true }) catch return error.PathNotFound;
}
fn findInstancesDirViaCLSID(gpa: Allocator, io: Io, registry: *Registry) error{ OutOfMemory, PathNotFound }!Dir {
const setup_configuration_clsid = "{177f0c4a-1cd3-4de7-a32c-71dbbb9fa36d}";
// HKEY_CLASSES_ROOT 并非单一键,而是 HKCU\Software\Classes 与 HKLM\Software\Classes 的组合,其中 HKCU 优先
// https://learn.microsoft.com/en-us/windows/win32/sysinfo/hkey-classes-root-key
//
// 我们不采用 CLASSES_ROOT 抽象,而是通过更通用的抽象模拟其行为。这也意味着路径中必须包含 `Classes`,因为我们从 `Software` 键开始,而不是从“classes root”开始。
//
// 使用 `HKEY_CLASSES_ROOT` 的 advapi32 API 会访问 `\REGISTRY\USER\<SID>_Classes`,而不是 `\REGISTRY\USER\<SID>\Software\Classes`;但我们使用后者,因为这样可以利用 `RtlOpenCurrentUser`,无需实现获取当前用户注册表路径的逻辑,而且这两个键看起来在效果上等价。不过,进一步研究这两个键之间的关系可能会有帮助。
//
//
//
//
//
//
//
//
const setup_config_key = registry.tryOpenSoftwareKeyWithPrecedence(&.{
.{ .root = .current_user },
.{ .root = .local_machine },
}, L("Classes\\CLSID\\" ++ setup_configuration_clsid)) catch |err| switch (err) {
error.KeyNotFound => return error.PathNotFound,
};
defer setup_config_key.close();
const inproc_server = setup_config_key.open(L("InprocServer32")) catch return error.PathNotFound;
const dll_path = inproc_server.getString(gpa, .default, .wtf8) catch |err| switch (err) {
error.NotAString,
error.ValueNameNotFound,
error.StringNotFound,
=> return error.PathNotFound,
error.OutOfMemory => |e| return e,
};
defer gpa.free(dll_path);
if (!std.fs.path.isAbsolute(dll_path)) return error.PathNotFound;
var path_it = std.fs.path.componentIterator(dll_path);
// .dll 文件名
_ = path_it.last();
const root_path = while (path_it.previous()) |dir_component| {
if (std.ascii.eqlIgnoreCase(dir_component.name, "VisualStudio")) {
break dir_component.path;
}
} else {
return error.PathNotFound;
};
const instances_path = try std.fs.path.join(gpa, &.{ root_path, "Packages", "_Instances" });
defer gpa.free(instances_path);
return Dir.openDirAbsolute(io, instances_path, .{ .iterate = true }) catch return error.PathNotFound;
}
fn findInstancesDir(
gpa: Allocator,
io: Io,
registry: *Registry,
environ_map: *const Environ.Map,
) error{ OutOfMemory, PathNotFound }!Dir {
// 首先尝试从注册表获取包缓存路径。
// 似乎只有路径不同于默认值时才存在该项。
method1: {
return findInstancesDirViaSetup(gpa, io, registry) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.PathNotFound => break :method1,
};
}
// 否则,尝试从原本会通过 COM 为 SetupConfiguration
// 加载的 .dll 中获取路径。
method2: {
return findInstancesDirViaCLSID(gpa, io, registry) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.PathNotFound => break :method2,
};
}
// 若找不到,则回退为手动将 `Microsoft\VisualStudio\Packages\_Instances` 追加到 %PROGRAMDATA%
//
method3: {
const program_data = std.zig.EnvVar.PROGRAMDATA.get(environ_map) orelse break :method3;
if (!std.fs.path.isAbsolute(program_data)) break :method3;
const instances_path = try Dir.path.join(gpa, &.{
program_data, "Microsoft", "VisualStudio", "Packages", "_Instances",
});
defer gpa.free(instances_path);
return Dir.openDirAbsolute(io, instances_path, .{ .iterate = true }) catch break :method3;
}
return error.PathNotFound;
}
/// 旨在等价于 `ISetupHelper.ParseVersion`
/// 示例:17.4.33205.214 -> 0x0011000481b500d6
fn parseVersionQuad(version: []const u8) error{InvalidVersion}!u64 {
var it = std.mem.splitScalar(u8, version, '.');
const a = it.first();
const b = it.next() orelse return error.InvalidVersion;
const c = it.next() orelse return error.InvalidVersion;
const d = it.next() orelse return error.InvalidVersion;
if (it.next()) |_| return error.InvalidVersion;
var result: u64 = undefined;
var result_bytes = std.mem.asBytes(&result);
std.mem.writeInt(
u16,
result_bytes[0..2],
std.fmt.parseUnsigned(u16, d, 10) catch return error.InvalidVersion,
.little,
);
std.mem.writeInt(
u16,
result_bytes[2..4],
std.fmt.parseUnsigned(u16, c, 10) catch return error.InvalidVersion,
.little,
);
std.mem.writeInt(
u16,
result_bytes[4..6],
std.fmt.parseUnsigned(u16, b, 10) catch return error.InvalidVersion,
.little,
);
std.mem.writeInt(
u16,
result_bytes[6..8],
std.fmt.parseUnsigned(u16, a, 10) catch return error.InvalidVersion,
.little,
);
return result;
}
/// 旨在等价于 ISetupConfiguration.EnumInstances:
/// https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.setup.configuration
/// 但不使用 COM,以避免依赖 ole32.dll。
///
/// 通过 Procmon 验证,此函数中的逻辑旨在匹配 ISetupConfiguration 的底层实现。
///
fn findViaCOM(
gpa: Allocator,
io: Io,
registry: *Registry,
arch: std.Target.Cpu.Arch,
environ_map: *const Environ.Map,
) error{ OutOfMemory, PathNotFound }![]const u8 {
// 通常为 `%PROGRAMDATA%\Microsoft\VisualStudio\Packages\_Instances`。
// 其中包含名称为实例标识(如 80a758ca)的目录,
// 目录中有 `state.json` 文件,提供版本和
// 安装目录。
var instances_dir = try findInstancesDir(gpa, io, registry, environ_map);
defer instances_dir.close(io);
var state_subpath_buf: [Dir.max_name_bytes + 32]u8 = undefined;
var latest_version_lib_dir: std.ArrayList(u8) = .empty;
errdefer latest_version_lib_dir.deinit(gpa);
var latest_version: u64 = 0;
var instances_dir_it = instances_dir.iterateAssumeFirstIteration();
while (instances_dir_it.next(io) catch return error.PathNotFound) |entry| {
if (entry.kind != .directory) continue;
var writer: Writer = .fixed(&state_subpath_buf);
writer.writeAll(entry.name) catch unreachable;
writer.writeByte(Dir.path.sep) catch unreachable;
writer.writeAll("state.json") catch unreachable;
const json_contents = instances_dir.readFileAlloc(io, writer.buffered(), gpa, .limited(std.math.maxInt(usize))) catch continue;
defer gpa.free(json_contents);
var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_contents, .{}) catch continue;
defer parsed.deinit();
if (parsed.value != .object) continue;
const catalog_info = parsed.value.object.get("catalogInfo") orelse continue;
if (catalog_info != .object) continue;
const product_version_value = catalog_info.object.get("buildVersion") orelse continue;
if (product_version_value != .string) continue;
const product_version_text = product_version_value.string;
const parsed_version = parseVersionQuad(product_version_text) catch continue;
// 最终应安装可用的最新版本
if (parsed_version <= latest_version) continue;
const installation_path = parsed.value.object.get("installationPath") orelse continue;
if (installation_path != .string) continue;
const lib_dir_path = libDirFromInstallationPath(gpa, io, installation_path.string, arch) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.PathNotFound => continue,
};
defer gpa.free(lib_dir_path);
latest_version_lib_dir.clearRetainingCapacity();
try latest_version_lib_dir.appendSlice(gpa, lib_dir_path);
latest_version = parsed_version;
}
if (latest_version_lib_dir.items.len == 0) return error.PathNotFound;
return latest_version_lib_dir.toOwnedSlice(gpa);
}
fn libDirFromInstallationPath(
gpa: Allocator,
io: Io,
installation_path: []const u8,
arch: std.Target.Cpu.Arch,
) error{ OutOfMemory, PathNotFound }![]const u8 {
var lib_dir_buf = try std.array_list.Managed(u8).initCapacity(gpa, installation_path.len + 64);
errdefer lib_dir_buf.deinit();
lib_dir_buf.appendSliceAssumeCapacity(installation_path);
if (!Dir.path.isSep(lib_dir_buf.last().?)) {
try lib_dir_buf.append('\\');
}
const installation_path_with_trailing_sep_len = lib_dir_buf.items.len;
try lib_dir_buf.appendSlice("VC\\Auxiliary\\Build\\Microsoft.VCToolsVersion.default.txt");
var default_tools_version_buf: [512]u8 = undefined;
const default_tools_version_contents = Dir.cwd().readFile(io, lib_dir_buf.items, &default_tools_version_buf) catch {
return error.PathNotFound;
};
var tokenizer = std.mem.tokenizeAny(u8, default_tools_version_contents, " \r\n");
const default_tools_version = tokenizer.next() orelse return error.PathNotFound;
lib_dir_buf.shrinkRetainingCapacity(installation_path_with_trailing_sep_len);
try lib_dir_buf.appendSlice("VC\\Tools\\MSVC\\");
try lib_dir_buf.appendSlice(default_tools_version);
try lib_dir_buf.appendSlice("\\Lib\\");
try lib_dir_buf.appendSlice(switch (arch) {
.thumb => "arm",
.aarch64 => "arm64",
.x86 => "x86",
.x86_64 => "x64",
else => unreachable,
});
if (!verifyLibDir(io, lib_dir_buf.items)) {
return error.PathNotFound;
}
return lib_dir_buf.toOwnedSlice();
}
// https://learn.microsoft.com/en-us/visualstudio/install/tools-for-managing-visual-studio-instances?view=vs-2022#editing-the-registry-for-a-visual-studio-instance
fn findViaRegistry(
gpa: Allocator,
io: Io,
arch: std.Target.Cpu.Arch,
environ_map: *const Environ.Map,
) error{ OutOfMemory, PathNotFound }![]const u8 {
// %localappdata%\Microsoft\VisualStudio\
// %appdata%\Local\Microsoft\VisualStudio\
const local_app_data_path = std.zig.EnvVar.LOCALAPPDATA.get(environ_map) orelse return error.PathNotFound;
const visualstudio_folder_path = try Dir.path.join(gpa, &.{
local_app_data_path, "Microsoft\\VisualStudio\\",
});
defer gpa.free(visualstudio_folder_path);
if (!Dir.path.isAbsolute(visualstudio_folder_path)) return error.PathNotFound;
// 为便于后续操作,此处打开 VisualStudio 目录,
// 这样即可将相对路径传给 NtLoadKeyEx,避免处理
// 向 NT 命名空间路径的转换。
var visualstudio_folder = Dir.openDirAbsolute(io, visualstudio_folder_path, .{
.iterate = true,
}) catch return error.PathNotFound;
defer visualstudio_folder.close(io);
const vs_versions: []const []const u8 = vs_versions: {
// 枚举包含 `privateregistry.bin` 的文件夹,查找所有版本
// 例如 %localappdata%\Microsoft\VisualStudio\17.0_9e9cbb98\
var iterator = visualstudio_folder.iterate();
break :vs_versions try iterateAndFilterByVersion(&iterator, gpa, io, "");
};
defer {
for (vs_versions) |vs_version| gpa.free(vs_version);
gpa.free(vs_versions);
}
var key_path_buf: [windows.NAME_MAX * 2]u16 = undefined;
var sub_path_buf: [windows.NAME_MAX * 2]u16 = undefined;
const source_directories: []const u8 = source_directories: for (vs_versions) |vs_version| {
const sub_path = blk: {
var buf: std.ArrayList(u16) = .initBuffer(&sub_path_buf);
buf.items.len += std.unicode.wtf8ToWtf16Le(buf.unusedCapacitySlice(), vs_version) catch unreachable;
buf.appendSliceAssumeCapacity(L("\\privateregistry.bin"));
break :blk buf.items;
};
// 目标是直接调用 NtLoadKeyEx,模拟 advapi32.RegLoadAppKeyW。
//
// RegLoadAppKeyW 将配置单元加载到如下格式的注册表键中:
// \REGISTRY\A\{fdb2baa5-8ca8-ef03-78d0-3b1f868fd2a9}
// 其中 `\REGISTRY\A` 是用于应用专属配置单元的特殊位置,无法枚举;GUID 随机生成,测试时每次运行程序都不同。
//
// 当某个键的全部句柄关闭后,操作系统负责清理 `\REGISTRY\A`,因此这里无需额外处理。
//
//
//
//
//
const temp_key_path = blk: {
var guid: windows.GUID = undefined;
io.random(std.mem.asBytes(&guid));
var guid_buf: [38]u8 = undefined;
const guid_str = std.mem.print(&guid_buf, "{f}", .{guid}) catch unreachable;
var buf: std.ArrayList(u16) = .initBuffer(&key_path_buf);
buf.appendSliceAssumeCapacity(L("\\REGISTRY\\A\\"));
buf.items.len += std.unicode.wtf8ToWtf16Le(buf.unusedCapacitySlice(), guid_str) catch unreachable;
break :blk buf.items;
};
const target_key: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = null,
.Attributes = .{},
.ObjectName = @constCast(&windows.UNICODE_STRING.init(temp_key_path)),
.SecurityDescriptor = null,
};
const source_file: windows.OBJECT.ATTRIBUTES = .{
.RootDirectory = visualstudio_folder.handle,
.Attributes = .{},
.ObjectName = @constCast(&windows.UNICODE_STRING.init(sub_path)),
.SecurityDescriptor = null,
};
var root_key: Registry.Key = undefined;
const rc = windows.ntdll.NtLoadKeyEx(
&target_key,
&source_file,
.{
.APP_HIVE = true,
// RegLoadAppKeyW 未设置此项,但似乎相关,
// 因为不打算修改该配置单元。
.OPEN_READ_ONLY = true,
},
null,
null,
.{ .SPECIFIC = .{
.KEY = .{
.QUERY_VALUE = true,
.ENUMERATE_SUB_KEYS = true,
},
} },
&root_key.handle,
null,
);
switch (rc) {
.SUCCESS => {},
else => continue,
}
defer root_key.close();
const config_path = blk: {
var buf: std.ArrayList(u16) = .initBuffer(&key_path_buf);
buf.appendSliceAssumeCapacity(L("Software\\Microsoft\\VisualStudio\\"));
buf.items.len += std.unicode.wtf8ToWtf16Le(buf.unusedCapacitySlice(), vs_version) catch unreachable;
buf.appendSliceAssumeCapacity(L("_Config"));
break :blk buf.items;
};
const config_key = root_key.open(config_path) catch continue;
const source_directories_value = config_key.getString(gpa, .{ .name = L("Source Directories") }, .wtf8) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
else => continue,
};
break :source_directories source_directories_value;
} else return error.PathNotFound;
defer gpa.free(source_directories);
var source_directories_split = std.mem.splitScalar(u8, source_directories, ';');
const msvc_dir: []const u8 = msvc_dir: {
const msvc_include_dir_maybe_with_trailing_slash = try gpa.dupe(u8, source_directories_split.first());
if (msvc_include_dir_maybe_with_trailing_slash.len > Dir.max_path_bytes or !Dir.path.isAbsolute(msvc_include_dir_maybe_with_trailing_slash)) {
gpa.free(msvc_include_dir_maybe_with_trailing_slash);
return error.PathNotFound;
}
var msvc_dir = std.array_list.Managed(u8).fromOwnedSlice(gpa, msvc_include_dir_maybe_with_trailing_slash);
errdefer msvc_dir.deinit();
// 字符串可能含有末尾斜杠,因此在此处裁剪
if (msvc_dir.items.len > "C:\\".len and msvc_dir.last().? == '\\') _ = msvc_dir.pop();
// 移除路径末尾的 `\include`
if (std.mem.endsWith(u8, msvc_dir.items, "\\include")) {
msvc_dir.shrinkRetainingCapacity(msvc_dir.items.len - "\\include".len);
}
try msvc_dir.appendSlice("\\Lib\\");
try msvc_dir.appendSlice(switch (arch) {
.thumb => "arm",
.aarch64 => "arm64",
.x86 => "x86",
.x86_64 => "x64",
else => unreachable,
});
const msvc_dir_with_arch = try msvc_dir.toOwnedSlice();
break :msvc_dir msvc_dir_with_arch;
};
errdefer gpa.free(msvc_dir);
if (!verifyLibDir(io, msvc_dir)) {
return error.PathNotFound;
}
return msvc_dir;
}
fn findViaVs7Key(
gpa: Allocator,
io: Io,
registry: *Registry,
arch: std.Target.Cpu.Arch,
environ_map: *const Environ.Map,
) error{ OutOfMemory, PathNotFound }![]const u8 {
var base_path: std.array_list.Managed(u8) = base_path: {
try_env: {
if (environ_map.get("VS140COMNTOOLS")) |VS140COMNTOOLS| {
if (VS140COMNTOOLS.len < "C:\\Common7\\Tools".len) break :try_env;
if (!Dir.path.isAbsolute(VS140COMNTOOLS)) break :try_env;
var list = std.array_list.Managed(u8).init(gpa);
errdefer list.deinit();
try list.appendSlice(VS140COMNTOOLS); // C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools
// 字符串末尾可能带斜杠,因此在此去除
if (list.items.len > "C:\\".len and list.last().? == '\\') _ = list.pop();
list.shrinkRetainingCapacity(list.items.len - "\\Common7\\Tools".len); // C:\Program Files (x86)\Microsoft Visual Studio 14.0
break :base_path list;
}
}
const vs7_key = registry.openSoftwareKey(.{ .root = .local_machine, .wow64 = .wow64_32 }, L("Microsoft\\VisualStudio\\SxS\\VS7")) catch return error.PathNotFound;
defer vs7_key.close();
try_vs7_key: {
const path_maybe_with_trailing_slash = vs7_key.getString(gpa, .{ .name = L("14.0") }, .wtf8) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
else => break :try_vs7_key,
};
if (path_maybe_with_trailing_slash.len > Dir.max_path_bytes or !Dir.path.isAbsolute(path_maybe_with_trailing_slash)) {
gpa.free(path_maybe_with_trailing_slash);
break :try_vs7_key;
}
var path = std.array_list.Managed(u8).fromOwnedSlice(gpa, path_maybe_with_trailing_slash);
errdefer path.deinit();
// 字符串可能含有末尾斜杠,因此在此处裁剪
if (path.items.len > "C:\\".len and path.last().? == '\\') _ = path.pop();
break :base_path path;
}
return error.PathNotFound;
};
errdefer base_path.deinit();
try base_path.appendSlice("\\VC\\lib\\");
try base_path.appendSlice(switch (arch) {
.thumb => "arm",
.aarch64 => "arm64",
.x86 => "", // x86 位于 Lib 文件夹根目录
.x86_64 => "amd64",
else => unreachable,
});
if (!verifyLibDir(io, base_path.items)) {
return error.PathNotFound;
}
const full_path = try base_path.toOwnedSlice();
return full_path;
}
fn verifyLibDir(io: Io, lib_dir_path: []const u8) bool {
std.debug.assert(Dir.path.isAbsolute(lib_dir_path)); // 应已在 `findVia*` 中处理
var dir = Dir.openDirAbsolute(io, lib_dir_path, .{}) catch return false;
defer dir.close(io);
const stat = dir.statFile(io, "vcruntime.lib", .{}) catch return false;
if (stat.kind != .file)
return false;
return true;
}
/// 查找 MSVC 的 `lib/` 目录路径。
/// 调用方拥有返回结果的所有权。
pub fn find(
gpa: Allocator,
io: Io,
registry: *Registry,
arch: std.Target.Cpu.Arch,
environ_map: *const Environ.Map,
) error{ OutOfMemory, MsvcLibDirNotFound }![]const u8 {
const full_path = MsvcLibDir.findViaCOM(gpa, io, registry, arch, environ_map) catch |err1| switch (err1) {
error.OutOfMemory => |e| return e,
error.PathNotFound => MsvcLibDir.findViaRegistry(gpa, io, arch, environ_map) catch |err2| switch (err2) {
error.OutOfMemory => |e| return e,
error.PathNotFound => MsvcLibDir.findViaVs7Key(gpa, io, registry, arch, environ_map) catch |err3| switch (err3) {
error.OutOfMemory => |e| return e,
error.PathNotFound => return error.MsvcLibDirNotFound,
},
},
};
errdefer gpa.free(full_path);
return full_path;
}
};