Debian Codegraph @

src/briefcase/integrations/windows_sdk.py

raw
1 from __future__ import annotations
2
3 import subprocess
4 from collections.abc import Collection, Iterator
5 from pathlib import Path
6
7 # winreg can only be imported on Windows
8 try:
9 import winreg
10 except ImportError: # pragma: no-cover-if-is-windows
11 winreg = None
12
13 from briefcase.exceptions import BriefcaseCommandError
14 from briefcase.integrations.base import Tool, ToolCache
15
16
17 class WindowsSDK(Tool):
18 name = "windows_sdk"
19 full_name = "Windows SDK"
20 supported_host_os: Collection[str] = {"Windows"}
21
22 SDK_VERSION = "10.0"
23 # Oldest supported SDK version is 10.0.15063.0
24 SDK_MIN_VERSION = 15063
25 # Registry path to keys with details of the installed Windows SDKs
26 SDK_KEY = rf"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v{SDK_VERSION}"
27 # Subkey containing the installation directory for the SDK
28 SDK_DIR_KEY = "InstallationFolder"
29 # Subkey for "latest" installed SDK version
30 SDK_VERSION_KEY = "ProductVersion"
31 # As a fallback, possible default locations for SDK
32 DEFAULT_SDK_DIRS: Collection[Path] = [
33 Path(rf"C:\Program Files (x86)\Windows Kits\{SDK_VERSION.split('.')[0]}")
34 ]
35 # Installing parts of the SDK for UWP apps is not inherently required; however,
36 # it is the minimum selection that ensures the signing tool has the libraries
37 # necessary to run. Executables from older versions of the SDK may not be
38 # compatible with the version of Windows that's installed.
39 SDK_REQUIRED_COMPONENTS = """
40 * Windows SDK Signing Tools for Desktop Apps
41 * Windows SDK for UWP Managed Apps
42 """
43
44 def __init__(self, tools: ToolCache, root_path: Path, version: str, arch: str):
45 """Create a wrapper around the Windows SDK.
46
47 :param tools: ToolCache of available tools
48 :param root_path: Base path for sdk, e.g. C:/Program Files (x86)/Windows
49 Kits/10/
50 :param version: Full SDK version, e.g. 10.0.22621.0
51 :param arch: Host architecture for SDK, e.g. x64, arm64, etc
52 """
53 super().__init__(tools=tools)
54 self.root_path = root_path
55 self.version = version
56 self.arch = arch
57
58 @property
59 def bin_path(self) -> Path:
60 return self.root_path / "bin" / self.version / self.arch
61
62 @property
63 def signtool_exe(self) -> Path:
64 return self.bin_path / "signtool.exe"
65
66 @classmethod
67 def _sdk_versions_from_bin(cls, sdk_dir: Path) -> list[str]:
68 """Returns list of SDK versions from the install location bin directory."""
69 bin_dir = sdk_dir / "bin"
70 # prioritize newer versions of the SDK
71 version_dirs = sorted(bin_dir.glob(f"{cls.SDK_VERSION}.*.0/"), reverse=True)
72 return [d.name for d in version_dirs]
73
74 @classmethod
75 def _windows_sdks(cls, tools: ToolCache) -> Iterator[tuple[Path, str]]:
76 """Generator of (path, version) for instances of Windows SDK.
77
78 All instances of Windows SDK should reside in the same base directory; this is
79 enforced by the SDK installer. Certain subdirectories, such as `include` and
80 `bin`, will contain subdirectories for versions that may be installed.
81 """
82 tools.console.debug("Finding Suitable Installation...", prefix=cls.full_name)
83
84 # Return user-specified SDK
85 if (environ_sdk_dir := tools.os.environ.get("WindowsSDKDir")) and (
86 environ_sdk_version := tools.os.environ.get("WindowsSDKVersion")
87 ):
88 yield Path(environ_sdk_dir), environ_sdk_version
89 raise BriefcaseCommandError(
90 f"""\
91 The 'WindowsSDKDir' and 'WindowsSDKVersion' environment variables do not point
92 to a valid install of the Windows SDK v{cls.SDK_VERSION}:
93
94 WindowsSDKDir: {environ_sdk_dir}
95 WindowsSDKVersion: {environ_sdk_version}
96 """
97 )
98
99 # To support the varied bitness of processes and installations within Windows,
100 # the registry is split among different views to avoid a process naively and
101 # likely unintentionally referencing incompatible software/settings. This is
102 # accomplished with subkeys under the primary trees, for example:
103 # HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node
104 # A 32-bit version of the registry tree is effectively mirrored under this
105 # subkey for a 64-bit Windows installation.
106 access_right_precedence = [
107 # 32-bit process sees 32-bit registry; 64-bit process sees 64-bit registry
108 winreg.KEY_READ,
109 # 32-bit process sees 32-bit registry; 64-bit process sees 32-bit registry
110 winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
111 # 32-bit process sees 64-bit registry; 64-bit process sees 64-bit registry
112 winreg.KEY_READ | winreg.KEY_WOW64_64KEY,
113 ]
114
115 registry_tree_order = (
116 (hkey, access)
117 for hkey in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]
118 for access in access_right_precedence
119 )
120
121 for hkey, access in registry_tree_order:
122 try:
123 with winreg.OpenKeyEx(hkey, cls.SDK_KEY, access=access) as key:
124 if not (sdk_dir := winreg.QueryValueEx(key, cls.SDK_DIR_KEY)[0]):
125 continue
126 if not (sdk_dir := Path(tools.os.fsdecode(sdk_dir))).is_dir():
127 continue
128
129 # Return the "latest" installed SDK first
130 if reg_version := winreg.QueryValueEx(key, cls.SDK_VERSION_KEY)[0]:
131 # Append missing "servicing" revision to registry version
132 reg_version = f"{reg_version}.0"
133 tools.console.debug(
134 f"Evaluating Registry SDK version '{reg_version}' "
135 f"at {sdk_dir}"
136 )
137 yield sdk_dir, reg_version
138
139 # Return other versions of the SDK installed in sdk_dir
140 for sdk_version in cls._sdk_versions_from_bin(sdk_dir):
141 if sdk_version != reg_version:
142 tools.console.debug(
143 f"Evaluating Registry SDK Bin version '{sdk_version}' "
144 f"at {sdk_dir}"
145 )
146 yield sdk_dir, sdk_version
147 except FileNotFoundError:
148 pass # ignore missing registry keys
149
150 for sdk_dir in cls.DEFAULT_SDK_DIRS:
151 if sdk_dir.is_dir():
152 for sdk_version in cls._sdk_versions_from_bin(sdk_dir):
153 tools.console.debug(
154 f"Evaluating Default Bin SDK version '{sdk_version}' "
155 f"at {sdk_dir}"
156 )
157 yield sdk_dir, sdk_version
158
159 @classmethod
160 def _is_supported_version(cls, sdk: WindowsSDK) -> bool:
161 """Returns whether the version of the SDK install is supported."""
162 try:
163 version_split = sdk.version.split(".")
164 if not sdk.version.startswith(cls.SDK_VERSION):
165 return False
166 if int(version_split[2]) < cls.SDK_MIN_VERSION:
167 return False
168 except (AttributeError, ValueError, IndexError):
169 return False
170
171 return True
172
173 @classmethod
174 def _verify_signtool(cls, sdk: WindowsSDK) -> bool:
175 """Returns SDK if signtool exists and can successfully run."""
176 if not sdk.signtool_exe.is_file():
177 return False
178
179 try:
180 sdk.tools.subprocess.check_output([sdk.signtool_exe, "-?"])
181 except (OSError, subprocess.CalledProcessError):
182 # Windows can raise OSError when it cannot run signtool.
183 # This can happen when an old version of the SDK is installed
184 # and only signtool is installed.
185 return False
186
187 return True
188
189 @classmethod
190 def verify_install(cls, tools: ToolCache, **kwargs) -> WindowsSDK:
191 """Verify the Windows SDK is installed with needed components.
192
193 :param tools: ToolCache of available tools
194 """
195 # short circuit since already verified and available
196 if hasattr(tools, "windows_sdk"):
197 return tools.windows_sdk
198
199 arch = {"AMD64": "x64", "ARM64": "arm64"}.get(tools.host_arch, tools.host_arch)
200
201 sdk = None
202 for sdk_dir, sdk_version in cls._windows_sdks(tools=tools):
203 sdk = WindowsSDK(
204 tools=tools,
205 root_path=sdk_dir,
206 version=sdk_version,
207 arch=arch,
208 )
209
210 if not cls._is_supported_version(sdk):
211 sdk = None
212 continue
213
214 if not cls._verify_signtool(sdk):
215 sdk = None
216 continue
217
218 break
219
220 if sdk is None:
221 raise BriefcaseCommandError(
222 f"""\
223 Unable to locate a suitable Windows SDK v{cls.SDK_VERSION} installation.
224
225 Ensure at least v{cls.SDK_VERSION}.{cls.SDK_MIN_VERSION}.0 is installed
226 and the components below are included:
227 {cls.SDK_REQUIRED_COMPONENTS}
228 See https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/
229 to install the SDK.
230 """
231 )
232
233 tools.console.debug(f"Using Windows SDK v{sdk.version} at {sdk.root_path}")
234 tools.windows_sdk = sdk
235 return sdk