Debian Codegraph @

src/find_tools.rs

raw symbols SCIP
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! An internal use crate to looking for windows-specific tools:
12 //! 1. On Windows host, probe the Windows Registry if needed;
13 //! 2. On non-Windows host, check specified environment variables.
14
15 #![allow(clippy::upper_case_acronyms)]
16
17 use std::{
18 env,
19 ffi::{OsStr, OsString},
20 ops::Deref,
21 path::{Path, PathBuf},
22 process::Command,
23 sync::Arc,
24 };
25
26 use crate::Tool;
27
28 /// The target provided by the user.
29 #[derive(Copy, Clone, PartialEq, Eq)]
30 enum TargetArch {
31 X86,
32 X64,
33 Arm,
34 Arm64,
35 Arm64ec,
36 }
37 impl TargetArch {
38 /// Parse the `TargetArch` from a str. Returns `None` if the arch is unrecognized.
39 fn new(arch: &str) -> Option<Self> {
40 // NOTE: Keep up to date with docs in [`find`].
41 match arch {
42 "x64" | "x86_64" => Some(Self::X64),
43 "arm64" | "aarch64" => Some(Self::Arm64),
44 "arm64ec" => Some(Self::Arm64ec),
45 "x86" | "i686" | "i586" => Some(Self::X86),
46 "arm" | "thumbv7a" => Some(Self::Arm),
47 _ => None,
48 }
49 }
50
51 #[cfg(windows)]
52 /// Gets the Visual Studio name for the architecture.
53 fn as_vs_arch(&self) -> &'static str {
54 match self {
55 Self::X64 => "x64",
56 Self::Arm64 | Self::Arm64ec => "arm64",
57 Self::X86 => "x86",
58 Self::Arm => "arm",
59 }
60 }
61 }
62
63 #[derive(Debug, Clone)]
64 #[non_exhaustive]
65 pub enum Env {
66 Owned(OsString),
67 Arced(Arc<OsStr>),
68 }
69
70 impl AsRef<OsStr> for Env {
71 fn as_ref(&self) -> &OsStr {
72 self.deref()
73 }
74 }
75
76 impl Deref for Env {
77 type Target = OsStr;
78
79 fn deref(&self) -> &Self::Target {
80 match self {
81 Env::Owned(os_str) => os_str,
82 Env::Arced(os_str) => os_str,
83 }
84 }
85 }
86
87 impl From<Env> for PathBuf {
88 fn from(env: Env) -> Self {
89 match env {
90 Env::Owned(os_str) => PathBuf::from(os_str),
91 Env::Arced(os_str) => PathBuf::from(os_str.deref()),
92 }
93 }
94 }
95
96 pub trait EnvGetter {
97 fn get_env(&self, name: &'static str) -> Option<Env>;
98 }
99
100 struct StdEnvGetter;
101
102 impl EnvGetter for StdEnvGetter {
103 #[allow(clippy::disallowed_methods)]
104 fn get_env(&self, name: &'static str) -> Option<Env> {
105 env::var_os(name).map(Env::Owned)
106 }
107 }
108
109 /// Attempts to find a tool within an MSVC installation using the Windows
110 /// registry as a point to search from.
111 ///
112 /// The `arch_or_target` argument is the architecture or the Rust target name
113 /// that the tool should work for (e.g. compile or link for). The supported
114 /// architecture names are:
115 /// - `"x64"` or `"x86_64"`
116 /// - `"arm64"` or `"aarch64"`
117 /// - `"arm64ec"`
118 /// - `"x86"`, `"i586"` or `"i686"`
119 /// - `"arm"` or `"thumbv7a"`
120 ///
121 /// The `tool` argument is the tool to find. Supported tools include:
122 /// - MSVC tools: `cl.exe`, `link.exe`, `lib.exe`, etc.
123 /// - `MSBuild`: `msbuild.exe`
124 /// - Visual Studio IDE: `devenv.exe`
125 /// - Clang/LLVM tools: `clang.exe`, `clang++.exe`, `clang-*.exe`, `llvm-*.exe`, `lld.exe`, etc.
126 ///
127 /// This function will return `None` if the tool could not be found, or it will
128 /// return `Some(cmd)` which represents a command that's ready to execute the
129 /// tool with the appropriate environment variables set.
130 ///
131 /// To find MSVC tools, this function will first attempt to detect if we are
132 /// running in the context of a developer command prompt, and then use the tools
133 /// as found in the current `PATH`. If that fails, it will attempt to locate
134 /// the newest MSVC toolset in the newest installed version of Visual Studio.
135 /// To limit the search to a specific version of the MSVC toolset, set the
136 /// VCToolsVersion environment variable to the desired version (e.g. "14.44.35207").
137 ///
138 /// Note that this function always returns `None` for non-MSVC targets (if a
139 /// full target name was specified).
140 pub fn find(arch_or_target: &str, tool: &str) -> Option<Command> {
141 find_tool(arch_or_target, tool).map(|c| c.to_command())
142 }
143
144 /// Similar to the `find` function above, this function will attempt the same
145 /// operation (finding a MSVC tool in a local install) but instead returns a
146 /// `Tool` which may be introspected.
147 pub fn find_tool(arch_or_target: &str, tool: &str) -> Option<Tool> {
148 let full_arch = if let Some((full_arch, rest)) = arch_or_target.split_once("-") {
149 // The logic is all tailored for MSVC, if the target is not that then
150 // bail out early.
151 if !rest.contains("msvc") {
152 return None;
153 }
154 full_arch
155 } else {
156 arch_or_target
157 };
158 find_tool_with_env(full_arch, tool, &StdEnvGetter)
159 }
160
161 pub fn find_tool_with_env(full_arch: &str, tool: &str, env_getter: &dyn EnvGetter) -> Option<Tool> {
162 // We only need the arch.
163 let target = TargetArch::new(full_arch)?;
164
165 // Looks like msbuild isn't located in the same location as other tools like
166 // cl.exe and lib.exe.
167 if tool.contains("msbuild") {
168 return impl_::find_msbuild(target, env_getter);
169 }
170
171 // Looks like devenv isn't located in the same location as other tools like
172 // cl.exe and lib.exe.
173 if tool.contains("devenv") {
174 return impl_::find_devenv(target, env_getter);
175 }
176
177 // Clang/LLVM isn't located in the same location as other tools like
178 // cl.exe and lib.exe.
179 if ["clang", "lldb", "llvm", "ld", "lld"]
180 .iter()
181 .any(|&t| tool.contains(t))
182 {
183 return impl_::find_llvm_tool(tool, target, env_getter);
184 }
185
186 // Ok, if we're here, now comes the fun part of the probing. Default shells
187 // or shells like MSYS aren't really configured to execute `cl.exe` and the
188 // various compiler tools shipped as part of Visual Studio. Here we try to
189 // first find the relevant tool, then we also have to be sure to fill in
190 // environment variables like `LIB`, `INCLUDE`, and `PATH` to ensure that
191 // the tool is actually usable.
192
193 impl_::find_msvc_environment(tool, target, env_getter)
194 .or_else(|| impl_::find_msvc_15plus(tool, target, env_getter))
195 .or_else(|| impl_::find_msvc_14(tool, target, env_getter))
196 }
197
198 /// An SDK found by [`find_windows_sdk`]
199 #[derive(Default)]
200 pub struct Sdk {
201 libs: Vec<PathBuf>,
202 path: Vec<PathBuf>,
203 include: Vec<PathBuf>,
204 version: String,
205 }
206
207 impl Sdk {
208 /// Directories containing static libraries (e.g. `.lib` files).
209 pub fn libs(&self) -> impl Iterator<Item = &Path> {
210 self.libs.iter().map(PathBuf::as_path)
211 }
212
213 /// Directories containing binaries (`.exe` and `.dll` files).
214 pub fn path(&self) -> impl Iterator<Item = &Path> {
215 self.path.iter().map(PathBuf::as_path)
216 }
217
218 /// Directories containing source headers (e.g. `.h` files)
219 pub fn include(&self) -> impl Iterator<Item = &Path> {
220 self.include.iter().map(PathBuf::as_path)
221 }
222
223 /// The Windows SDK version that was found.
224 pub fn sdk_version(&self) -> &str {
225 &self.version
226 }
227 }
228
229 /// Find the directories of the latest installed Windows SDK.
230 ///
231 /// It's not necessary to call this if using [`find`] or [`find_tool`] as they will populate the relvant
232 /// environment variables with the SDK directories.
233 pub fn find_windows_sdk(full_arch: &str) -> Option<Sdk> {
234 let target = TargetArch::new(full_arch)?;
235 impl_::get_sdks(target, &StdEnvGetter)
236 }
237
238 /// A version of Visual Studio
239 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
240 #[non_exhaustive]
241 pub enum VsVers {
242 /// Visual Studio 12 (2013)
243 #[deprecated(
244 note = "Visual Studio 12 is no longer supported. cc will never return this value."
245 )]
246 Vs12,
247 /// Visual Studio 14 (2015)
248 Vs14,
249 /// Visual Studio 15 (2017)
250 Vs15,
251 /// Visual Studio 16 (2019)
252 Vs16,
253 /// Visual Studio 17 (2022)
254 Vs17,
255 /// Visual Studio 18 (2026)
256 Vs18,
257 }
258
259 /// Find the most recent installed version of Visual Studio
260 ///
261 /// This is used by the cmake crate to figure out the correct
262 /// generator.
263 #[allow(clippy::disallowed_methods)]
264 pub fn find_vs_version() -> Result<VsVers, String> {
265 fn has_msbuild_version(version: &str) -> bool {
266 impl_::has_msbuild_version(version, &StdEnvGetter)
267 }
268
269 match std::env::var("VisualStudioVersion") {
270 Ok(version) => match &version[..] {
271 "18.0" => Ok(VsVers::Vs18),
272 "17.0" => Ok(VsVers::Vs17),
273 "16.0" => Ok(VsVers::Vs16),
274 "15.0" => Ok(VsVers::Vs15),
275 "14.0" => Ok(VsVers::Vs14),
276 vers => Err(format!(
277 "\n\n\
278 unsupported or unknown VisualStudio version: {vers}\n\
279 if another version is installed consider running \
280 the appropriate vcvars script before building this \
281 crate\n\
282 "
283 )),
284 },
285 _ => {
286 // Check for the presence of a specific registry key
287 // that indicates visual studio is installed.
288 if has_msbuild_version("18.0") {
289 Ok(VsVers::Vs18)
290 } else if has_msbuild_version("17.0") {
291 Ok(VsVers::Vs17)
292 } else if has_msbuild_version("16.0") {
293 Ok(VsVers::Vs16)
294 } else if has_msbuild_version("15.0") {
295 Ok(VsVers::Vs15)
296 } else if has_msbuild_version("14.0") {
297 Ok(VsVers::Vs14)
298 } else {
299 Err("\n\n\
300 couldn't determine visual studio generator\n\
301 if VisualStudio is installed, however, consider \
302 running the appropriate vcvars script before building \
303 this crate\n\
304 "
305 .to_string())
306 }
307 }
308 }
309 }
310
311 /// To find the Universal CRT we look in a specific registry key for where
312 /// all the Universal CRTs are located and then sort them asciibetically to
313 /// find the newest version. While this sort of sorting isn't ideal, it is
314 /// what vcvars does so that's good enough for us.
315 ///
316 /// Returns a pair of (root, version) for the ucrt dir if found
317 pub fn get_ucrt_dir() -> Option<(PathBuf, String)> {
318 impl_::get_ucrt_dir()
319 }
320
321 /// Windows Implementation.
322 #[cfg(windows)]
323 mod impl_ {
324 use crate::com;
325 use crate::registry::{RegistryKey, LOCAL_MACHINE};
326 use crate::setup_config::SetupConfiguration;
327 use crate::vs_instances::{VsInstances, VswhereInstance};
328 use crate::windows_sys::{
329 GetMachineTypeAttributes, GetProcAddress, LoadLibraryA, UserEnabled, HMODULE,
330 IMAGE_FILE_MACHINE_AMD64, MACHINE_ATTRIBUTES, S_OK,
331 };
332 use std::convert::TryFrom;
333 use std::env;
334 use std::ffi::OsString;
335 use std::fs::File;
336 use std::io::Read;
337 use std::iter;
338 use std::mem;
339 use std::path::{Path, PathBuf};
340 use std::process::Command;
341 use std::str::FromStr;
342 use std::sync::atomic::{AtomicBool, Ordering};
343 use std::sync::Once;
344
345 use super::{EnvGetter, Sdk, TargetArch};
346 use crate::Tool;
347
348 struct MsvcTool {
349 tool: PathBuf,
350 libs: Vec<PathBuf>,
351 path: Vec<PathBuf>,
352 include: Vec<PathBuf>,
353 }
354
355 struct LibraryHandle(HMODULE);
356
357 impl LibraryHandle {
358 fn new(name: &[u8]) -> Option<Self> {
359 let handle = unsafe { LoadLibraryA(name.as_ptr() as _) };
360 (!handle.is_null()).then_some(Self(handle))
361 }
362
363 /// Get a function pointer to a function in the library.
364 /// # SAFETY
365 ///
366 /// The caller must ensure that the function signature matches the actual function.
367 /// The easiest way to do this is to add an entry to `windows_sys_no_link.list` and use the
368 /// generated function for `func_signature`.
369 ///
370 /// The function returned cannot be used after the handle is dropped.
371 unsafe fn get_proc_address<F>(&self, name: &[u8]) -> Option<F> {
372 let symbol = GetProcAddress(self.0, name.as_ptr() as _);
373 symbol.map(|symbol| mem::transmute_copy(&symbol))
374 }
375 }
376
377 type GetMachineTypeAttributesFuncType =
378 unsafe extern "system" fn(u16, *mut MACHINE_ATTRIBUTES) -> i32;
379 const _: () = {
380 // Ensure that our hand-written signature matches the actual function signature.
381 // We can't use `GetMachineTypeAttributes` outside of a const scope otherwise we'll end up statically linking to
382 // it, which will fail to load on older versions of Windows.
383 let _: GetMachineTypeAttributesFuncType = GetMachineTypeAttributes;
384 };
385
386 fn is_amd64_emulation_supported_inner() -> Option<bool> {
387 // GetMachineTypeAttributes is only available on Win11 22000+, so dynamically load it.
388 let kernel32 = LibraryHandle::new(b"kernel32.dll\0")?;
389 // SAFETY: GetMachineTypeAttributesFuncType is checked to match the real function signature.
390 let get_machine_type_attributes = unsafe {
391 kernel32
392 .get_proc_address::<GetMachineTypeAttributesFuncType>(b"GetMachineTypeAttributes\0")
393 }?;
394 let mut attributes = Default::default();
395 if unsafe { get_machine_type_attributes(IMAGE_FILE_MACHINE_AMD64, &mut attributes) } == S_OK
396 {
397 Some((attributes & UserEnabled) != 0)
398 } else {
399 Some(false)
400 }
401 }
402
403 fn is_amd64_emulation_supported() -> bool {
404 // TODO: Replace with a OnceLock once MSRV is 1.70.
405 static LOAD_VALUE: Once = Once::new();
406 static IS_SUPPORTED: AtomicBool = AtomicBool::new(false);
407
408 // Using Relaxed ordering since the Once is providing synchronization.
409 LOAD_VALUE.call_once(|| {
410 IS_SUPPORTED.store(
411 is_amd64_emulation_supported_inner().unwrap_or(false),
412 Ordering::Relaxed,
413 );
414 });
415 IS_SUPPORTED.load(Ordering::Relaxed)
416 }
417
418 impl MsvcTool {
419 fn new(tool: PathBuf) -> MsvcTool {
420 MsvcTool {
421 tool,
422 libs: Vec::new(),
423 path: Vec::new(),
424 include: Vec::new(),
425 }
426 }
427
428 fn add_sdk(&mut self, sdk_info: Sdk) {
429 self.libs.extend(sdk_info.libs);
430 self.path.extend(sdk_info.path);
431 self.include.extend(sdk_info.include);
432 }
433
434 fn into_tool(self, env_getter: &dyn EnvGetter) -> Tool {
435 let MsvcTool {
436 tool,
437 libs,
438 path,
439 include,
440 } = self;
441 let mut tool = Tool {
442 tool,
443 is_clang_cl: false,
444 env: Vec::new(),
445 };
446 add_env(&mut tool, "LIB", libs, env_getter);
447 add_env(&mut tool, "PATH", path, env_getter);
448 add_env(&mut tool, "INCLUDE", include, env_getter);
449 tool
450 }
451 }
452
453 impl Sdk {
454 fn find_tool(&self, tool: &str) -> Option<PathBuf> {
455 self.path.iter().map(|p| p.join(tool)).find_map(|mut p| {
456 (p.exists() || (p.set_extension(env::consts::EXE_SUFFIX) && p.exists()))
457 .then_some(p)
458 })
459 }
460 }
461
462 /// Checks to see if the target's arch matches the VS environment. Returns `None` if the
463 /// environment is unknown.
464 fn is_vscmd_target(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<bool> {
465 is_vscmd_target_env(target, env_getter).or_else(|| is_vscmd_target_cl(target, env_getter))
466 }
467
468 /// Checks to see if the `VSCMD_ARG_TGT_ARCH` environment variable matches the
469 /// given target's arch. Returns `None` if the variable does not exist.
470 fn is_vscmd_target_env(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<bool> {
471 let vscmd_arch = env_getter.get_env("VSCMD_ARG_TGT_ARCH")?;
472 Some(target.as_vs_arch() == vscmd_arch.as_ref())
473 }
474
475 /// Checks if the cl.exe target matches the given target's arch. Returns `None` if anything
476 /// fails.
477 fn is_vscmd_target_cl(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<bool> {
478 let cmd_target = vscmd_target_cl(env_getter)?;
479 Some(target.as_vs_arch() == cmd_target)
480 }
481
482 /// Detect the target architecture of `cl.exe` in the current path, and return `None` if this
483 /// fails for any reason.
484 fn vscmd_target_cl(env_getter: &dyn EnvGetter) -> Option<&'static str> {
485 let cl_exe = env_getter.get_env("PATH").and_then(|path| {
486 env::split_paths(&path)
487 .map(|p| p.join("cl.exe"))
488 .find(|p| p.exists())
489 })?;
490 let mut cl = Command::new(cl_exe);
491 cl.stderr(std::process::Stdio::piped())
492 .stdout(std::process::Stdio::null());
493
494 let out = cl.output().ok()?;
495 let cl_arch = out
496 .stderr
497 .split(|&b| b == b'\n' || b == b'\r')
498 .next()?
499 .rsplit(|&b| b == b' ')
500 .next()?;
501
502 match cl_arch {
503 b"x64" => Some("x64"),
504 b"x86" => Some("x86"),
505 b"ARM64" => Some("arm64"),
506 b"ARM" => Some("arm"),
507 _ => None,
508 }
509 }
510
511 /// Attempt to find the tool using environment variables set by vcvars.
512 pub(super) fn find_msvc_environment(
513 tool: &str,
514 target: TargetArch,
515 env_getter: &dyn EnvGetter,
516 ) -> Option<Tool> {
517 // Early return if the environment isn't one that is known to have compiler toolsets in PATH
518 // `VCINSTALLDIR` is set from vcvarsall.bat (developer command prompt)
519 // `VSTEL_MSBuildProjectFullPath` is set by msbuild when invoking custom build steps
520 // NOTE: `VisualStudioDir` used to be used but this isn't set when invoking msbuild from the commandline
521 if env_getter.get_env("VCINSTALLDIR").is_none()
522 && env_getter.get_env("VSTEL_MSBuildProjectFullPath").is_none()
523 {
524 return None;
525 }
526
527 // If the vscmd target differs from the requested target then
528 // attempt to get the tool using the VS install directory.
529 if is_vscmd_target(target, env_getter) == Some(false) {
530 // We will only get here with versions 15+.
531 let vs_install_dir: PathBuf = env_getter.get_env("VSINSTALLDIR")?.into();
532 tool_from_vs15plus_instance(tool, target, &vs_install_dir, env_getter)
533 } else {
534 // Fallback to simply using the current environment.
535 env_getter
536 .get_env("PATH")
537 .and_then(|path| {
538 env::split_paths(&path)
539 .map(|p| p.join(tool))
540 .find(|p| p.exists())
541 })
542 .map(|path| Tool {
543 tool: path,
544 is_clang_cl: false,
545 env: Vec::new(),
546 })
547 }
548 }
549
550 fn find_msbuild_vs18(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
551 find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "18", env_getter)
552 }
553
554 fn find_msbuild_vs17(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
555 find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "17", env_getter)
556 }
557
558 #[allow(bare_trait_objects)]
559 fn vs16plus_instances(
560 target: TargetArch,
561 version: &'static str,
562 env_getter: &dyn EnvGetter,
563 ) -> Box<Iterator<Item = PathBuf>> {
564 let instances = if let Some(instances) = vs15plus_instances(target, env_getter) {
565 instances
566 } else {
567 return Box::new(iter::empty());
568 };
569 Box::new(instances.into_iter().filter_map(move |instance| {
570 let installation_name = instance.installation_name()?;
571 if installation_name.starts_with(&format!("VisualStudio/{}.", version))
572 || installation_name.starts_with(&format!("VisualStudioPreview/{}.", version))
573 {
574 Some(instance.installation_path()?)
575 } else {
576 None
577 }
578 }))
579 }
580
581 fn find_tool_in_vs16plus_path(
582 tool: &str,
583 target: TargetArch,
584 version: &'static str,
585 env_getter: &dyn EnvGetter,
586 ) -> Option<Tool> {
587 vs16plus_instances(target, version, env_getter)
588 .filter_map(|path| {
589 let path = path.join(tool);
590 if !path.is_file() {
591 return None;
592 }
593 let mut tool = Tool {
594 tool: path,
595 is_clang_cl: false,
596 env: Vec::new(),
597 };
598 if target == TargetArch::X64 {
599 tool.env.push(("Platform".into(), "X64".into()));
600 }
601 if matches!(target, TargetArch::Arm64 | TargetArch::Arm64ec) {
602 tool.env.push(("Platform".into(), "ARM64".into()));
603 }
604 Some(tool)
605 })
606 .next()
607 }
608
609 fn find_msbuild_vs16(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
610 find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "16", env_getter)
611 }
612
613 pub(super) fn find_llvm_tool(
614 tool: &str,
615 target: TargetArch,
616 env_getter: &dyn EnvGetter,
617 ) -> Option<Tool> {
618 find_llvm_tool_vs17plus(tool, target, env_getter, "18")
619 .or_else(|| find_llvm_tool_vs17plus(tool, target, env_getter, "17"))
620 }
621
622 fn find_llvm_tool_vs17plus(
623 tool: &str,
624 target: TargetArch,
625 env_getter: &dyn EnvGetter,
626 version: &'static str,
627 ) -> Option<Tool> {
628 vs16plus_instances(target, version, env_getter)
629 .filter_map(|mut base_path| {
630 base_path.push(r"VC\Tools\LLVM");
631 let host_folder = match host_arch() {
632 // The default LLVM bin folder is x86, and there's separate subfolders
633 // for the x64 and ARM64 host tools.
634 X86 => "",
635 X86_64 => "x64",
636 AARCH64 => "ARM64",
637 _ => return None,
638 };
639 if host_folder != "" {
640 // E.g. C:\...\VC\Tools\LLVM\x64
641 base_path.push(host_folder);
642 }
643 // E.g. C:\...\VC\Tools\LLVM\x64\bin\clang.exe
644 base_path.push("bin");
645 base_path.push(tool);
646 let is_clang_cl = tool.contains("clang-cl");
647 base_path.is_file().then(|| Tool {
648 tool: base_path,
649 is_clang_cl,
650 env: Vec::new(),
651 })
652 })
653 .next()
654 }
655
656 // In MSVC 15 (2017) MS once again changed the scheme for locating
657 // the tooling. Now we must go through some COM interfaces, which
658 // is super fun for Rust.
659 //
660 // Note that much of this logic can be found [online] wrt paths, COM, etc.
661 //
662 // [online]: https://blogs.msdn.microsoft.com/vcblog/2017/03/06/finding-the-visual-c-compiler-tools-in-visual-studio-2017/
663 //
664 // Returns MSVC 15+ instances (15, 16 right now), the order should be consider undefined.
665 //
666 // However, on ARM64 this method doesn't work because VS Installer fails to register COM component on ARM64.
667 // Hence, as the last resort we try to use vswhere.exe to list available instances.
668 fn vs15plus_instances(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<VsInstances> {
669 vs15plus_instances_using_com()
670 .or_else(|| vs15plus_instances_using_vswhere(target, env_getter))
671 }
672
673 fn vs15plus_instances_using_com() -> Option<VsInstances> {
674 com::initialize().ok()?;
675
676 let config = SetupConfiguration::new().ok()?;
677 let enum_setup_instances = config.enum_all_instances().ok()?;
678
679 Some(VsInstances::ComBased(enum_setup_instances))
680 }
681
682 fn vs15plus_instances_using_vswhere(
683 target: TargetArch,
684 env_getter: &dyn EnvGetter,
685 ) -> Option<VsInstances> {
686 let program_files_path = env_getter
687 .get_env("ProgramFiles(x86)")
688 .or_else(|| env_getter.get_env("ProgramFiles"))?;
689
690 let program_files_path = Path::new(program_files_path.as_ref());
691
692 let vswhere_path =
693 program_files_path.join(r"Microsoft Visual Studio\Installer\vswhere.exe");
694
695 if !vswhere_path.exists() {
696 return None;
697 }
698
699 let tools_arch = match target {
700 TargetArch::X86 | TargetArch::X64 => Some("x86.x64"),
701 TargetArch::Arm => Some("ARM"),
702 TargetArch::Arm64 | TargetArch::Arm64ec => Some("ARM64"),
703 };
704
705 let vswhere_output = Command::new(vswhere_path)
706 .args([
707 "-latest",
708 "-products",
709 "*",
710 "-requires",
711 &format!("Microsoft.VisualStudio.Component.VC.Tools.{}", tools_arch?),
712 "-format",
713 "text",
714 "-nologo",
715 ])
716 .stderr(std::process::Stdio::inherit())
717 .output()
718 .ok()?;
719
720 let vs_instances =
721 VsInstances::VswhereBased(VswhereInstance::try_from(&vswhere_output.stdout).ok()?);
722
723 Some(vs_instances)
724 }
725
726 // Inspired from official microsoft/vswhere ParseVersionString
727 // i.e. at most four u16 numbers separated by '.'
728 fn parse_version(version: &str) -> Option<[u16; 4]> {
729 let mut iter = version.split('.').map(u16::from_str).fuse();
730 let mut get_next_number = move || match iter.next() {
731 Some(Ok(version_part)) => Some(version_part),
732 Some(Err(_)) => None,
733 None => Some(0),
734 };
735 Some([
736 get_next_number()?,
737 get_next_number()?,
738 get_next_number()?,
739 get_next_number()?,
740 ])
741 }
742
743 pub(super) fn find_msvc_15plus(
744 tool: &str,
745 target: TargetArch,
746 env_getter: &dyn EnvGetter,
747 ) -> Option<Tool> {
748 let iter = vs15plus_instances(target, env_getter)?;
749 iter.into_iter()
750 .filter_map(|instance| {
751 let version = parse_version(&instance.installation_version()?)?;
752 let instance_path = instance.installation_path()?;
753 let tool = tool_from_vs15plus_instance(tool, target, &instance_path, env_getter)?;
754 Some((version, tool))
755 })
756 .max_by(|(a_version, _), (b_version, _)| a_version.cmp(b_version))
757 .map(|(_version, tool)| tool)
758 }
759
760 // While the paths to Visual Studio 2017's devenv and MSBuild could
761 // potentially be retrieved from the registry, finding them via
762 // SetupConfiguration has shown to be [more reliable], and is preferred
763 // according to Microsoft. To help head off potential regressions though,
764 // we keep the registry method as a fallback option.
765 //
766 // [more reliable]: https://github.com/rust-lang/cc-rs/pull/331
767 fn find_tool_in_vs15_path(
768 tool: &str,
769 target: TargetArch,
770 env_getter: &dyn EnvGetter,
771 ) -> Option<Tool> {
772 let mut path = match vs15plus_instances(target, env_getter) {
773 Some(instances) => instances
774 .into_iter()
775 .filter_map(|instance| instance.installation_path())
776 .map(|path| path.join(tool))
777 .find(|path| path.is_file()),
778 None => None,
779 };
780
781 if path.is_none() {
782 let key = r"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7";
783 path = LOCAL_MACHINE
784 .open(key.as_ref())
785 .ok()
786 .and_then(|key| key.query_str("15.0").ok())
787 .map(|path| PathBuf::from(path).join(tool))
788 .and_then(|path| if path.is_file() { Some(path) } else { None });
789 }
790
791 path.map(|path| {
792 let mut tool = Tool {
793 tool: path,
794 is_clang_cl: false,
795 env: Vec::new(),
796 };
797 if target == TargetArch::X64 {
798 tool.env.push(("Platform".into(), "X64".into()));
799 } else if matches!(target, TargetArch::Arm64 | TargetArch::Arm64ec) {
800 tool.env.push(("Platform".into(), "ARM64".into()));
801 }
802 tool
803 })
804 }
805
806 fn tool_from_vs15plus_instance(
807 tool: &str,
808 target: TargetArch,
809 instance_path: &Path,
810 env_getter: &dyn EnvGetter,
811 ) -> Option<Tool> {
812 let (root_path, bin_path, host_dylib_path, lib_path, alt_lib_path, include_path) =
813 vs15plus_vc_paths(target, instance_path, env_getter)?;
814 let sdk_info = get_sdks(target, env_getter)?;
815 let mut tool_path = bin_path.join(tool);
816 if !tool_path.exists() {
817 tool_path = sdk_info.find_tool(tool)?;
818 };
819
820 let mut tool = MsvcTool::new(tool_path);
821 tool.path.push(bin_path.clone());
822 tool.path.push(host_dylib_path);
823 if let Some(alt_lib_path) = alt_lib_path {
824 tool.libs.push(alt_lib_path);
825 }
826 tool.libs.push(lib_path);
827 tool.include.push(include_path);
828
829 if let Some((atl_lib_path, atl_include_path)) = atl_paths(target, &root_path) {
830 tool.libs.push(atl_lib_path);
831 tool.include.push(atl_include_path);
832 }
833
834 tool.add_sdk(sdk_info);
835
836 Some(tool.into_tool(env_getter))
837 }
838
839 fn vs15plus_vc_paths(
840 target_arch: TargetArch,
841 instance_path: &Path,
842 env_getter: &dyn EnvGetter,
843 ) -> Option<(PathBuf, PathBuf, PathBuf, PathBuf, Option<PathBuf>, PathBuf)> {
844 let version = vs15plus_vc_read_version(instance_path, env_getter)?;
845
846 let hosts = match host_arch() {
847 X86 => &["X86"],
848 X86_64 => &["X64"],
849 // Starting with VS 17.4, there is a natively hosted compiler on ARM64:
850 // https://devblogs.microsoft.com/visualstudio/arm64-visual-studio-is-officially-here/
851 // On older versions of VS, we use x64 if running under emulation is supported,
852 // otherwise use x86.
853 AARCH64 => {
854 if is_amd64_emulation_supported() {
855 &["ARM64", "X64", "X86"][..]
856 } else {
857 &["ARM64", "X86"]
858 }
859 }
860 _ => return None,
861 };
862 let target_dir = target_arch.as_vs_arch();
863 // The directory layout here is MSVC/bin/Host$host/$target/
864 let path = instance_path.join(r"VC\Tools\MSVC").join(version);
865 // We use the first available host architecture that can build for the target
866 let (host_path, host) = hosts.iter().find_map(|&x| {
867 let candidate = path.join("bin").join(format!("Host{}", x));
868 if candidate.join(target_dir).exists() {
869 Some((candidate, x))
870 } else {
871 None
872 }
873 })?;
874 // This is the path to the toolchain for a particular target, running
875 // on a given host
876 let bin_path = host_path.join(target_dir);
877 // But! we also need PATH to contain the target directory for the host
878 // architecture, because it contains dlls like mspdb140.dll compiled for
879 // the host architecture.
880 let host_dylib_path = host_path.join(host.to_lowercase());
881 let lib_fragment = if use_spectre_mitigated_libs(env_getter) {
882 r"lib\spectre"
883 } else {
884 "lib"
885 };
886 let lib_path = path.join(lib_fragment).join(target_dir);
887 let alt_lib_path =
888 (target_arch == TargetArch::Arm64ec).then(|| path.join(lib_fragment).join("arm64ec"));
889 let include_path = path.join("include");
890 Some((
891 path,
892 bin_path,
893 host_dylib_path,
894 lib_path,
895 alt_lib_path,
896 include_path,
897 ))
898 }
899
900 fn vs15plus_vc_read_version(dir: &Path, env_getter: &dyn EnvGetter) -> Option<String> {
901 if let Some(version) = env_getter.get_env("VCToolsVersion") {
902 // Restrict the search to a specific msvc version; if it doesn't exist then
903 // our caller will fail to find the tool for this instance and move on.
904 return version.to_str().map(ToString::to_string);
905 }
906
907 // Try to open the default version file.
908 let mut version_path: PathBuf =
909 dir.join(r"VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt");
910 let mut version_file = if let Ok(f) = File::open(&version_path) {
911 f
912 } else {
913 // If the default doesn't exist, search for other version files.
914 // These are in the form Microsoft.VCToolsVersion.v143.default.txt
915 // where `143` is any three decimal digit version number.
916 // This sorts versions by lexical order and selects the highest version.
917 let mut version_file = String::new();
918 version_path.pop();
919 for file in version_path.read_dir().ok()? {
920 let name = file.ok()?.file_name();
921 let name = name.to_str()?;
922 if name.starts_with("Microsoft.VCToolsVersion.v")
923 && name.ends_with(".default.txt")
924 && name > &version_file
925 {
926 version_file.replace_range(.., name);
927 }
928 }
929 if version_file.is_empty() {
930 // If all else fails, manually search for bin directories.
931 let tools_dir: PathBuf = dir.join(r"VC\Tools\MSVC");
932 return tools_dir
933 .read_dir()
934 .ok()?
935 .filter_map(|file| {
936 let file = file.ok()?;
937 let name = file.file_name().into_string().ok()?;
938
939 file.path().join("bin").exists().then(|| {
940 let version = parse_version(&name);
941 (name, version)
942 })
943 })
944 .max_by(|(_, a), (_, b)| a.cmp(b))
945 .map(|(version, _)| version);
946 }
947 version_path.push(version_file);
948 File::open(version_path).ok()?
949 };
950
951 // Get the version string from the file we found.
952 let mut version = String::new();
953 version_file.read_to_string(&mut version).ok()?;
954 version.truncate(version.trim_end().len());
955 Some(version)
956 }
957
958 fn use_spectre_mitigated_libs(env_getter: &dyn EnvGetter) -> bool {
959 env_getter
960 .get_env("VSCMD_ARG_VCVARS_SPECTRE")
961 .map(|env| env.as_ref() == "spectre")
962 .unwrap_or_default()
963 }
964
965 fn atl_paths(target: TargetArch, path: &Path) -> Option<(PathBuf, PathBuf)> {
966 let atl_path = path.join("atlmfc");
967 let sub = target.as_vs_arch();
968 if atl_path.exists() {
969 Some((atl_path.join("lib").join(sub), atl_path.join("include")))
970 } else {
971 None
972 }
973 }
974
975 // For MSVC 14 we need to find the Universal CRT as well as either
976 // the Windows 10 SDK or Windows 8.1 SDK.
977 pub(super) fn find_msvc_14(
978 tool: &str,
979 target: TargetArch,
980 env_getter: &dyn EnvGetter,
981 ) -> Option<Tool> {
982 if env_getter.get_env("VCToolsVersion").is_some() {
983 // VCToolsVersion is not set/supported for MSVC 14
984 return None;
985 }
986
987 let vcdir = get_vc_dir("14.0")?;
988 let sdk_info = get_sdks(target, env_getter)?;
989 let mut tool = get_tool(tool, &vcdir, target, &sdk_info)?;
990 tool.add_sdk(sdk_info);
991 Some(tool.into_tool(env_getter))
992 }
993
994 pub(super) fn get_sdks(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Sdk> {
995 let sub = target.as_vs_arch();
996 let (ucrt, ucrt_version) = get_ucrt_dir()?;
997
998 let host = match host_arch() {
999 X86 => "x86",
1000 X86_64 => "x64",
1001 AARCH64 => "arm64",
1002 _ => return None,
1003 };
1004
1005 let mut info = Sdk::default();
1006
1007 info.path
1008 .push(ucrt.join("bin").join(&ucrt_version).join(host));
1009
1010 let ucrt_include = ucrt.join("include").join(&ucrt_version);
1011 info.include.push(ucrt_include.join("ucrt"));
1012
1013 let ucrt_lib = ucrt.join("lib").join(&ucrt_version);
1014 info.libs.push(ucrt_lib.join("ucrt").join(sub));
1015
1016 if let Some((sdk, version)) = get_sdk10_dir(env_getter) {
1017 info.path.push(sdk.join("bin").join(host));
1018 let sdk_lib = sdk.join("lib").join(&version);
1019 info.libs.push(sdk_lib.join("um").join(sub));
1020 let sdk_include = sdk.join("include").join(&version);
1021 info.include.push(sdk_include.join("um"));
1022 info.include.push(sdk_include.join("cppwinrt"));
1023 info.include.push(sdk_include.join("winrt"));
1024 info.include.push(sdk_include.join("shared"));
1025 info.version = version;
1026 } else if let Some(sdk) = get_sdk81_dir() {
1027 info.path.push(sdk.join("bin").join(host));
1028 let sdk_lib = sdk.join("lib").join("winv6.3");
1029 info.libs.push(sdk_lib.join("um").join(sub));
1030 let sdk_include = sdk.join("include");
1031 info.include.push(sdk_include.join("um"));
1032 info.include.push(sdk_include.join("winrt"));
1033 info.include.push(sdk_include.join("shared"));
1034 info.version = "8.1".into();
1035 }
1036
1037 Some(info)
1038 }
1039
1040 fn add_env(
1041 tool: &mut Tool,
1042 env: &'static str,
1043 paths: Vec<PathBuf>,
1044 env_getter: &dyn EnvGetter,
1045 ) {
1046 let prev = env_getter.get_env(env);
1047 let prev = prev.as_ref().map(AsRef::as_ref).unwrap_or_default();
1048 let prev = env::split_paths(&prev);
1049 let new = paths.into_iter().chain(prev);
1050 tool.env
1051 .push((env.to_string().into(), env::join_paths(new).unwrap()));
1052 }
1053
1054 // Given a possible MSVC installation directory, we look for the linker and
1055 // then add the MSVC library path.
1056 fn get_tool(tool: &str, path: &Path, target: TargetArch, sdk_info: &Sdk) -> Option<MsvcTool> {
1057 bin_subdir(target)
1058 .into_iter()
1059 .map(|(sub, host)| {
1060 (
1061 path.join("bin").join(sub).join(tool),
1062 Some(path.join("bin").join(host)),
1063 )
1064 })
1065 .filter(|(path, _)| path.is_file())
1066 .chain(iter::once_with(|| Some((sdk_info.find_tool(tool)?, None))).flatten())
1067 .map(|(tool_path, host)| {
1068 let mut tool = MsvcTool::new(tool_path);
1069 tool.path.extend(host);
1070 let sub = vc_lib_subdir(target);
1071 tool.libs.push(path.join("lib").join(sub));
1072 tool.include.push(path.join("include"));
1073 let atlmfc_path = path.join("atlmfc");
1074 if atlmfc_path.exists() {
1075 tool.libs.push(atlmfc_path.join("lib").join(sub));
1076 tool.include.push(atlmfc_path.join("include"));
1077 }
1078 tool
1079 })
1080 .next()
1081 }
1082
1083 // To find MSVC we look in a specific registry key for the version we are
1084 // trying to find.
1085 fn get_vc_dir(ver: &str) -> Option<PathBuf> {
1086 let key = r"SOFTWARE\Microsoft\VisualStudio\SxS\VC7";
1087 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
1088 let path = key.query_str(ver).ok()?;
1089 Some(path.into())
1090 }
1091
1092 // To find the Universal CRT we look in a specific registry key for where
1093 // all the Universal CRTs are located and then sort them asciibetically to
1094 // find the newest version. While this sort of sorting isn't ideal, it is
1095 // what vcvars does so that's good enough for us.
1096 //
1097 // Returns a pair of (root, version) for the ucrt dir if found
1098 pub(super) fn get_ucrt_dir() -> Option<(PathBuf, String)> {
1099 let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots";
1100 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
1101 let root = key.query_str("KitsRoot10").ok()?;
1102 let readdir = Path::new(&root).join("lib").read_dir().ok()?;
1103 let max_libdir = readdir
1104 .filter_map(|dir| dir.ok())
1105 .map(|dir| dir.path())
1106 .filter(|dir| {
1107 dir.components()
1108 .last()
1109 .and_then(|c| c.as_os_str().to_str())
1110 .map(|c| c.starts_with("10.") && dir.join("ucrt").is_dir())
1111 .unwrap_or(false)
1112 })
1113 .max()?;
1114 let version = max_libdir.components().last().unwrap();
1115 let version = version.as_os_str().to_str().unwrap().to_string();
1116 Some((root.into(), version))
1117 }
1118
1119 // Vcvars finds the correct version of the Windows 10 SDK by looking
1120 // for the include `um\Windows.h` because sometimes a given version will
1121 // only have UCRT bits without the rest of the SDK. Since we only care about
1122 // libraries and not includes, we instead look for `um\x64\kernel32.lib`.
1123 // Since the 32-bit and 64-bit libraries are always installed together we
1124 // only need to bother checking x64, making this code a tiny bit simpler.
1125 // Like we do for the Universal CRT, we sort the possibilities
1126 // asciibetically to find the newest one as that is what vcvars does.
1127 // Before doing that, we check the "WindowsSdkDir" and "WindowsSDKVersion"
1128 // environment variables set by vcvars to use the environment sdk version
1129 // if one is already configured.
1130 fn get_sdk10_dir(env_getter: &dyn EnvGetter) -> Option<(PathBuf, String)> {
1131 if let (Some(root), Some(version)) = (
1132 env_getter.get_env("WindowsSdkDir"),
1133 env_getter
1134 .get_env("WindowsSDKVersion")
1135 .as_ref()
1136 .and_then(|version| version.as_ref().to_str()),
1137 ) {
1138 return Some((
1139 PathBuf::from(root),
1140 version.trim_end_matches('\\').to_string(),
1141 ));
1142 }
1143
1144 let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0";
1145 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
1146 let root = key.query_str("InstallationFolder").ok()?;
1147 let readdir = Path::new(&root).join("lib").read_dir().ok()?;
1148 let mut dirs = readdir
1149 .filter_map(|dir| dir.ok())
1150 .map(|dir| dir.path())
1151 .collect::<Vec<_>>();
1152 dirs.sort();
1153 let dir = dirs
1154 .into_iter()
1155 .rev()
1156 .find(|dir| dir.join("um").join("x64").join("kernel32.lib").is_file())?;
1157 let version = dir.components().last().unwrap();
1158 let version = version.as_os_str().to_str().unwrap().to_string();
1159 Some((root.into(), version))
1160 }
1161
1162 // Interestingly there are several subdirectories, `win7` `win8` and
1163 // `winv6.3`. Vcvars seems to only care about `winv6.3` though, so the same
1164 // applies to us. Note that if we were targeting kernel mode drivers
1165 // instead of user mode applications, we would care.
1166 fn get_sdk81_dir() -> Option<PathBuf> {
1167 let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1";
1168 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
1169 let root = key.query_str("InstallationFolder").ok()?;
1170 Some(root.into())
1171 }
1172
1173 const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0;
1174 const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
1175 const PROCESSOR_ARCHITECTURE_ARM64: u16 = 12;
1176 const X86: u16 = PROCESSOR_ARCHITECTURE_INTEL;
1177 const X86_64: u16 = PROCESSOR_ARCHITECTURE_AMD64;
1178 const AARCH64: u16 = PROCESSOR_ARCHITECTURE_ARM64;
1179
1180 // When choosing the tool to use, we have to choose the one which matches
1181 // the target architecture. Otherwise we end up in situations where someone
1182 // on 32-bit Windows is trying to cross compile to 64-bit and it tries to
1183 // invoke the native 64-bit compiler which won't work.
1184 //
1185 // For the return value of this function, the first member of the tuple is
1186 // the folder of the tool we will be invoking, while the second member is
1187 // the folder of the host toolchain for that tool which is essential when
1188 // using a cross linker. We return a Vec since on x64 there are often two
1189 // linkers that can target the architecture we desire. The 64-bit host
1190 // linker is preferred, and hence first, due to 64-bit allowing it more
1191 // address space to work with and potentially being faster.
1192 fn bin_subdir(target: TargetArch) -> Vec<(&'static str, &'static str)> {
1193 match (target, host_arch()) {
1194 (TargetArch::X86, X86) => vec![("", "")],
1195 (TargetArch::X86, X86_64) => vec![("amd64_x86", "amd64"), ("", "")],
1196 (TargetArch::X64, X86) => vec![("x86_amd64", "")],
1197 (TargetArch::X64, X86_64) => vec![("amd64", "amd64"), ("x86_amd64", "")],
1198 (TargetArch::Arm, X86) => vec![("x86_arm", "")],
1199 (TargetArch::Arm, X86_64) => vec![("amd64_arm", "amd64"), ("x86_arm", "")],
1200 _ => vec![],
1201 }
1202 }
1203
1204 // MSVC's x86 libraries are not in a subfolder
1205 fn vc_lib_subdir(target: TargetArch) -> &'static str {
1206 match target {
1207 TargetArch::X86 => "",
1208 TargetArch::X64 => "amd64",
1209 TargetArch::Arm => "arm",
1210 TargetArch::Arm64 | TargetArch::Arm64ec => "arm64",
1211 }
1212 }
1213
1214 #[allow(bad_style)]
1215 fn host_arch() -> u16 {
1216 type DWORD = u32;
1217 type WORD = u16;
1218 type LPVOID = *mut u8;
1219 type DWORD_PTR = usize;
1220
1221 #[repr(C)]
1222 struct SYSTEM_INFO {
1223 wProcessorArchitecture: WORD,
1224 _wReserved: WORD,
1225 _dwPageSize: DWORD,
1226 _lpMinimumApplicationAddress: LPVOID,
1227 _lpMaximumApplicationAddress: LPVOID,
1228 _dwActiveProcessorMask: DWORD_PTR,
1229 _dwNumberOfProcessors: DWORD,
1230 _dwProcessorType: DWORD,
1231 _dwAllocationGranularity: DWORD,
1232 _wProcessorLevel: WORD,
1233 _wProcessorRevision: WORD,
1234 }
1235
1236 extern "system" {
1237 fn GetNativeSystemInfo(lpSystemInfo: *mut SYSTEM_INFO);
1238 }
1239
1240 unsafe {
1241 let mut info = mem::zeroed();
1242 GetNativeSystemInfo(&mut info);
1243 info.wProcessorArchitecture
1244 }
1245 }
1246
1247 #[cfg(test)]
1248 mod tests {
1249 use super::*;
1250 use std::path::Path;
1251 // Import the find function from the module level
1252 use crate::find_tools::find;
1253
1254 fn host_arch_to_string(host_arch_value: u16) -> &'static str {
1255 match host_arch_value {
1256 X86 => "x86",
1257 X86_64 => "x64",
1258 AARCH64 => "arm64",
1259 _ => panic!("Unsupported host architecture: {}", host_arch_value),
1260 }
1261 }
1262
1263 #[test]
1264 fn test_find_cl_exe() {
1265 // Test that we can find cl.exe for common target architectures
1266 // and validate the correct host-target combination paths
1267 // This should pass on Windows CI with Visual Studio installed
1268
1269 let target_architectures = ["x64", "x86", "arm64"];
1270 let mut found_any = false;
1271
1272 // Determine the host architecture
1273 let host_arch_value = host_arch();
1274 let host_name = host_arch_to_string(host_arch_value);
1275
1276 for &target_arch in &target_architectures {
1277 if let Some(cmd) = find(target_arch, "cl.exe") {
1278 // Verify the command looks valid
1279 assert!(
1280 !cmd.get_program().is_empty(),
1281 "cl.exe program path should not be empty"
1282 );
1283 assert!(
1284 Path::new(cmd.get_program()).exists(),
1285 "cl.exe should exist at: {:?}",
1286 cmd.get_program()
1287 );
1288
1289 // Verify the path contains the correct host-target combination
1290 // Use case-insensitive comparison since VS IDE uses "Hostx64" while Build Tools use "HostX64"
1291 let path_str = cmd.get_program().to_string_lossy();
1292 let path_str_lower = path_str.to_lowercase();
1293 let expected_host_target_path =
1294 format!("\\bin\\host{host_name}\\{target_arch}");
1295 let expected_host_target_path_unix =
1296 expected_host_target_path.replace("\\", "/");
1297
1298 assert!(
1299 path_str_lower.contains(&expected_host_target_path) || path_str_lower.contains(&expected_host_target_path_unix),
1300 "cl.exe path should contain host-target combination (case-insensitive) '{}' for {} host targeting {}, but found: {}",
1301 expected_host_target_path,
1302 host_name,
1303 target_arch,
1304 path_str
1305 );
1306
1307 found_any = true;
1308 }
1309 }
1310
1311 assert!(found_any, "Expected to find cl.exe for at least one target architecture (x64, x86, or arm64) on Windows CI with Visual Studio installed");
1312 }
1313
1314 #[test]
1315 #[cfg(not(disable_clang_cl_tests))]
1316 fn test_find_llvm_tools() {
1317 // Import StdEnvGetter from the parent module
1318 use crate::find_tools::StdEnvGetter;
1319
1320 // Test the actual find_llvm_tool function with various LLVM tools
1321 // This test assumes CI environment has Visual Studio + Clang installed
1322 // We test against x64 target since clang can cross-compile to any target
1323 let target_arch = TargetArch::new("x64").expect("Should support x64 architecture");
1324 let llvm_tools = ["clang.exe", "clang++.exe", "lld.exe", "llvm-ar.exe"];
1325
1326 // Determine expected host-specific path based on host architecture
1327 let host_arch_value = host_arch();
1328 let expected_host_path = match host_arch_value {
1329 X86 => "LLVM\\bin", // x86 host
1330 X86_64 => "LLVM\\x64\\bin", // x64 host
1331 AARCH64 => "LLVM\\ARM64\\bin", // arm64 host
1332 _ => panic!("Unsupported host architecture: {}", host_arch_value),
1333 };
1334
1335 let host_name = host_arch_to_string(host_arch_value);
1336
1337 let mut found_tools_count = 0;
1338
1339 for &tool in &llvm_tools {
1340 // Test finding LLVM tools using the standard environment getter
1341 let env_getter = StdEnvGetter;
1342 let result = find_llvm_tool(tool, target_arch, &env_getter);
1343
1344 match result {
1345 Some(found_tool) => {
1346 found_tools_count += 1;
1347
1348 // Verify the found tool has a valid, non-empty path
1349 assert!(
1350 !found_tool.path().as_os_str().is_empty(),
1351 "Found LLVM tool '{}' should have a non-empty path",
1352 tool
1353 );
1354
1355 // Verify the tool path actually exists on filesystem
1356 assert!(
1357 found_tool.path().exists(),
1358 "LLVM tool '{}' path should exist: {:?}",
1359 tool,
1360 found_tool.path()
1361 );
1362
1363 // Verify the tool path contains the expected tool name
1364 let path_str = found_tool.path().to_string_lossy();
1365 assert!(
1366 path_str.contains(tool.trim_end_matches(".exe")),
1367 "Tool path '{}' should contain tool name '{}'",
1368 path_str,
1369 tool
1370 );
1371
1372 // Verify it's in the correct host-specific VS LLVM directory
1373 assert!(
1374 path_str.contains(expected_host_path) || path_str.contains(&expected_host_path.replace("\\", "/")),
1375 "LLVM tool should be in host-specific VS LLVM directory '{}' for {} host, but found: {}",
1376 expected_host_path,
1377 host_name,
1378 path_str
1379 );
1380 }
1381 None => {}
1382 }
1383 }
1384
1385 // On CI with VS + Clang installed, we should find at least some LLVM tools
1386 assert!(
1387 found_tools_count > 0,
1388 "Expected to find at least one LLVM tool on CI with Visual Studio + Clang installed for {} host. Found: {}",
1389 host_name,
1390 found_tools_count
1391 );
1392 }
1393 }
1394
1395 // Given a registry key, look at all the sub keys and find the one which has
1396 // the maximal numeric value.
1397 //
1398 // Returns the name of the maximal key as well as the opened maximal key.
1399 fn max_version(key: &RegistryKey) -> Option<(OsString, RegistryKey)> {
1400 let mut max_vers = 0;
1401 let mut max_key = None;
1402 for subkey in key.iter().filter_map(|k| k.ok()) {
1403 let val = subkey
1404 .to_str()
1405 .and_then(|s| s.trim_start_matches('v').replace('.', "").parse().ok());
1406 let val = match val {
1407 Some(s) => s,
1408 None => continue,
1409 };
1410 if val > max_vers {
1411 if let Ok(k) = key.open(&subkey) {
1412 max_vers = val;
1413 max_key = Some((subkey, k));
1414 }
1415 }
1416 }
1417 max_key
1418 }
1419
1420 #[inline(always)]
1421 pub(super) fn has_msbuild_version(version: &str, env_getter: &dyn EnvGetter) -> bool {
1422 match version {
1423 "18.0" => {
1424 find_msbuild_vs18(TargetArch::X64, env_getter).is_some()
1425 || find_msbuild_vs18(TargetArch::X86, env_getter).is_some()
1426 || find_msbuild_vs18(TargetArch::Arm64, env_getter).is_some()
1427 }
1428 "17.0" => {
1429 find_msbuild_vs17(TargetArch::X64, env_getter).is_some()
1430 || find_msbuild_vs17(TargetArch::X86, env_getter).is_some()
1431 || find_msbuild_vs17(TargetArch::Arm64, env_getter).is_some()
1432 }
1433 "16.0" => {
1434 find_msbuild_vs16(TargetArch::X64, env_getter).is_some()
1435 || find_msbuild_vs16(TargetArch::X86, env_getter).is_some()
1436 || find_msbuild_vs16(TargetArch::Arm64, env_getter).is_some()
1437 }
1438 "15.0" => {
1439 find_msbuild_vs15(TargetArch::X64, env_getter).is_some()
1440 || find_msbuild_vs15(TargetArch::X86, env_getter).is_some()
1441 || find_msbuild_vs15(TargetArch::Arm64, env_getter).is_some()
1442 }
1443 "14.0" => LOCAL_MACHINE
1444 .open(&OsString::from(format!(
1445 "SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{}",
1446 version
1447 )))
1448 .is_ok(),
1449 _ => false,
1450 }
1451 }
1452
1453 pub(super) fn find_devenv(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
1454 find_devenv_vs15(target, env_getter)
1455 }
1456
1457 fn find_devenv_vs15(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
1458 find_tool_in_vs15_path(r"Common7\IDE\devenv.exe", target, env_getter)
1459 }
1460
1461 // see http://stackoverflow.com/questions/328017/path-to-msbuild
1462 pub(super) fn find_msbuild(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
1463 // VS 15 (2017) changed how to locate msbuild
1464 if let Some(r) = find_msbuild_vs18(target, env_getter) {
1465 Some(r)
1466 } else if let Some(r) = find_msbuild_vs17(target, env_getter) {
1467 Some(r)
1468 } else if let Some(r) = find_msbuild_vs16(target, env_getter) {
1469 return Some(r);
1470 } else if let Some(r) = find_msbuild_vs15(target, env_getter) {
1471 return Some(r);
1472 } else {
1473 find_old_msbuild(target)
1474 }
1475 }
1476
1477 fn find_msbuild_vs15(target: TargetArch, env_getter: &dyn EnvGetter) -> Option<Tool> {
1478 find_tool_in_vs15_path(r"MSBuild\15.0\Bin\MSBuild.exe", target, env_getter)
1479 }
1480
1481 fn find_old_msbuild(target: TargetArch) -> Option<Tool> {
1482 let key = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions";
1483 LOCAL_MACHINE
1484 .open(key.as_ref())
1485 .ok()
1486 .and_then(|key| {
1487 max_version(&key).and_then(|(_vers, key)| key.query_str("MSBuildToolsPath").ok())
1488 })
1489 .map(|path| {
1490 let mut path = PathBuf::from(path);
1491 path.push("MSBuild.exe");
1492 let mut tool = Tool {
1493 tool: path,
1494 is_clang_cl: false,
1495 env: Vec::new(),
1496 };
1497 if target == TargetArch::X64 {
1498 tool.env.push(("Platform".into(), "X64".into()));
1499 }
1500 tool
1501 })
1502 }
1503 }
1504
1505 /// Non-Windows Implementation.
1506 #[cfg(not(windows))]
1507 mod impl_ {
1508 use std::{env, ffi::OsStr, path::PathBuf};
1509
1510 use super::{EnvGetter, Sdk, TargetArch};
1511 use crate::Tool;
1512
1513 /// Finding msbuild.exe tool under unix system is not currently supported.
1514 /// Maybe can check it using an environment variable looks like `MSBUILD_BIN`.
1515 #[inline(always)]
1516 pub(super) fn find_msbuild(_target: TargetArch, _: &dyn EnvGetter) -> Option<Tool> {
1517 None
1518 }
1519
1520 // Finding devenv.exe tool under unix system is not currently supported.
1521 // Maybe can check it using an environment variable looks like `DEVENV_BIN`.
1522 #[inline(always)]
1523 pub(super) fn find_devenv(_target: TargetArch, _: &dyn EnvGetter) -> Option<Tool> {
1524 None
1525 }
1526
1527 // Finding Clang/LLVM-related tools on unix systems is not currently supported.
1528 #[inline(always)]
1529 pub(super) fn find_llvm_tool(
1530 _tool: &str,
1531 _target: TargetArch,
1532 _: &dyn EnvGetter,
1533 ) -> Option<Tool> {
1534 None
1535 }
1536
1537 /// Attempt to find the tool using environment variables set by vcvars.
1538 pub(super) fn find_msvc_environment(
1539 tool: &str,
1540 _target: TargetArch,
1541 env_getter: &dyn EnvGetter,
1542 ) -> Option<Tool> {
1543 // Early return if the environment doesn't contain a VC install.
1544 let vc_install_dir = env_getter.get_env("VCINSTALLDIR")?;
1545 let vs_install_dir = env_getter.get_env("VSINSTALLDIR")?;
1546
1547 let get_tool = |install_dir: &OsStr| {
1548 env::split_paths(install_dir)
1549 .map(|p| p.join(tool))
1550 .find(|p| p.exists())
1551 .map(|path| Tool {
1552 tool: path,
1553 is_clang_cl: false,
1554 env: Vec::new(),
1555 })
1556 };
1557
1558 // Take the path of tool for the vc install directory.
1559 get_tool(vc_install_dir.as_ref())
1560 // Take the path of tool for the vs install directory.
1561 .or_else(|| get_tool(vs_install_dir.as_ref()))
1562 // Take the path of tool for the current path environment.
1563 .or_else(|| {
1564 env_getter
1565 .get_env("PATH")
1566 .as_ref()
1567 .map(|path| path.as_ref())
1568 .and_then(get_tool)
1569 })
1570 }
1571
1572 #[inline(always)]
1573 pub(super) fn find_msvc_15plus(
1574 _tool: &str,
1575 _target: TargetArch,
1576 _: &dyn EnvGetter,
1577 ) -> Option<Tool> {
1578 None
1579 }
1580
1581 // For MSVC 14 we need to find the Universal CRT as well as either
1582 // the Windows 10 SDK or Windows 8.1 SDK.
1583 #[inline(always)]
1584 pub(super) fn find_msvc_14(
1585 _tool: &str,
1586 _target: TargetArch,
1587 _: &dyn EnvGetter,
1588 ) -> Option<Tool> {
1589 None
1590 }
1591
1592 #[inline(always)]
1593 pub(super) fn has_msbuild_version(_version: &str, _: &dyn EnvGetter) -> bool {
1594 false
1595 }
1596
1597 #[inline(always)]
1598 pub(super) fn get_ucrt_dir() -> Option<(PathBuf, String)> {
1599 None
1600 }
1601
1602 #[inline(always)]
1603 pub(super) fn get_sdks(_target: TargetArch, _env_getter: &dyn EnvGetter) -> Option<Sdk> {
1604 None
1605 }
1606 }