Debian Codegraph @

.cargo/vendor/cc/src/windows/find_tools.rs

raw
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 //! A helper module 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::process::Command;
18
19 use crate::Tool;
20 use crate::ToolFamily;
21
22 const MSVC_FAMILY: ToolFamily = ToolFamily::Msvc { clang_cl: false };
23
24 #[derive(Copy, Clone)]
25 struct TargetArch<'a>(pub &'a str);
26
27 impl PartialEq<&str> for TargetArch<'_> {
28 fn eq(&self, other: &&str) -> bool {
29 self.0 == *other
30 }
31 }
32
33 impl<'a> From<TargetArch<'a>> for &'a str {
34 fn from(target: TargetArch<'a>) -> Self {
35 target.0
36 }
37 }
38
39 /// Attempts to find a tool within an MSVC installation using the Windows
40 /// registry as a point to search from.
41 ///
42 /// The `target` argument is the target that the tool should work for (e.g.
43 /// compile or link for) and the `tool` argument is the tool to find (e.g.
44 /// `cl.exe` or `link.exe`).
45 ///
46 /// This function will return `None` if the tool could not be found, or it will
47 /// return `Some(cmd)` which represents a command that's ready to execute the
48 /// tool with the appropriate environment variables set.
49 ///
50 /// Note that this function always returns `None` for non-MSVC targets.
51 pub fn find(target: &str, tool: &str) -> Option<Command> {
52 find_tool(target, tool).map(|c| c.to_command())
53 }
54
55 /// Similar to the `find` function above, this function will attempt the same
56 /// operation (finding a MSVC tool in a local install) but instead returns a
57 /// `Tool` which may be introspected.
58 pub fn find_tool(target: &str, tool: &str) -> Option<Tool> {
59 // This logic is all tailored for MSVC, if we're not that then bail out
60 // early.
61 if !target.contains("msvc") {
62 return None;
63 }
64
65 // Split the target to get the arch.
66 let target = TargetArch(target.split_once('-')?.0);
67
68 // Looks like msbuild isn't located in the same location as other tools like
69 // cl.exe and lib.exe.
70 if tool.contains("msbuild") {
71 return impl_::find_msbuild(target);
72 }
73
74 // Looks like devenv isn't located in the same location as other tools like
75 // cl.exe and lib.exe.
76 if tool.contains("devenv") {
77 return impl_::find_devenv(target);
78 }
79
80 // Ok, if we're here, now comes the fun part of the probing. Default shells
81 // or shells like MSYS aren't really configured to execute `cl.exe` and the
82 // various compiler tools shipped as part of Visual Studio. Here we try to
83 // first find the relevant tool, then we also have to be sure to fill in
84 // environment variables like `LIB`, `INCLUDE`, and `PATH` to ensure that
85 // the tool is actually usable.
86
87 impl_::find_msvc_environment(tool, target)
88 .or_else(|| impl_::find_msvc_15plus(tool, target))
89 .or_else(|| impl_::find_msvc_14(tool, target))
90 .or_else(|| impl_::find_msvc_12(tool, target))
91 }
92
93 /// A version of Visual Studio
94 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
95 #[non_exhaustive]
96 pub enum VsVers {
97 /// Visual Studio 12 (2013)
98 Vs12,
99 /// Visual Studio 14 (2015)
100 Vs14,
101 /// Visual Studio 15 (2017)
102 Vs15,
103 /// Visual Studio 16 (2019)
104 Vs16,
105 /// Visual Studio 17 (2022)
106 Vs17,
107 }
108
109 /// Find the most recent installed version of Visual Studio
110 ///
111 /// This is used by the cmake crate to figure out the correct
112 /// generator.
113 pub fn find_vs_version() -> Result<VsVers, String> {
114 match std::env::var("VisualStudioVersion") {
115 Ok(version) => match &version[..] {
116 "17.0" => Ok(VsVers::Vs17),
117 "16.0" => Ok(VsVers::Vs16),
118 "15.0" => Ok(VsVers::Vs15),
119 "14.0" => Ok(VsVers::Vs14),
120 "12.0" => Ok(VsVers::Vs12),
121 vers => Err(format!(
122 "\n\n\
123 unsupported or unknown VisualStudio version: {}\n\
124 if another version is installed consider running \
125 the appropriate vcvars script before building this \
126 crate\n\
127 ",
128 vers
129 )),
130 },
131 _ => {
132 // Check for the presence of a specific registry key
133 // that indicates visual studio is installed.
134 if impl_::has_msbuild_version("17.0") {
135 Ok(VsVers::Vs17)
136 } else if impl_::has_msbuild_version("16.0") {
137 Ok(VsVers::Vs16)
138 } else if impl_::has_msbuild_version("15.0") {
139 Ok(VsVers::Vs15)
140 } else if impl_::has_msbuild_version("14.0") {
141 Ok(VsVers::Vs14)
142 } else if impl_::has_msbuild_version("12.0") {
143 Ok(VsVers::Vs12)
144 } else {
145 Err(format!(
146 "\n\n\
147 couldn't determine visual studio generator\n\
148 if VisualStudio is installed, however, consider \
149 running the appropriate vcvars script before building \
150 this crate\n\
151 "
152 ))
153 }
154 }
155 }
156 }
157
158 /// Windows Implementation.
159 #[cfg(windows)]
160 mod impl_ {
161 use crate::windows::com;
162 use crate::windows::registry::{RegistryKey, LOCAL_MACHINE};
163 use crate::windows::setup_config::SetupConfiguration;
164 use crate::windows::vs_instances::{VsInstances, VswhereInstance};
165 use crate::windows::windows_sys::{
166 FreeLibrary, GetMachineTypeAttributes, GetProcAddress, LoadLibraryA, UserEnabled, HMODULE,
167 IMAGE_FILE_MACHINE_AMD64, MACHINE_ATTRIBUTES, S_OK,
168 };
169 use std::convert::TryFrom;
170 use std::env;
171 use std::ffi::OsString;
172 use std::fs::File;
173 use std::io::Read;
174 use std::iter;
175 use std::mem;
176 use std::path::{Path, PathBuf};
177 use std::process::Command;
178 use std::str::FromStr;
179 use std::sync::atomic::{AtomicBool, Ordering};
180 use std::sync::Once;
181
182 use super::{TargetArch, MSVC_FAMILY};
183 use crate::Tool;
184
185 struct MsvcTool {
186 tool: PathBuf,
187 libs: Vec<PathBuf>,
188 path: Vec<PathBuf>,
189 include: Vec<PathBuf>,
190 }
191
192 struct LibraryHandle(HMODULE);
193
194 impl LibraryHandle {
195 fn new(name: &[u8]) -> Option<Self> {
196 let handle = unsafe { LoadLibraryA(name.as_ptr() as _) };
197 (!handle.is_null()).then(|| Self(handle))
198 }
199
200 /// Get a function pointer to a function in the library.
201 /// # SAFETY
202 ///
203 /// The caller must ensure that the function signature matches the actual function.
204 /// The easiest way to do this is to add an entry to windows_sys_no_link.list and use the
205 /// generated function for `func_signature`.
206 ///
207 /// The function returned cannot be used after the handle is dropped.
208 unsafe fn get_proc_address<F>(&self, name: &[u8]) -> Option<F> {
209 let symbol = unsafe { GetProcAddress(self.0, name.as_ptr() as _) };
210 symbol.map(|symbol| unsafe { mem::transmute_copy(&symbol) })
211 }
212 }
213
214 impl Drop for LibraryHandle {
215 fn drop(&mut self) {
216 unsafe { FreeLibrary(self.0) };
217 }
218 }
219
220 type GetMachineTypeAttributesFuncType =
221 unsafe extern "system" fn(u16, *mut MACHINE_ATTRIBUTES) -> i32;
222 const _: () = {
223 // Ensure that our hand-written signature matches the actual function signature.
224 // We can't use `GetMachineTypeAttributes` outside of a const scope otherwise we'll end up statically linking to
225 // it, which will fail to load on older versions of Windows.
226 let _: GetMachineTypeAttributesFuncType = GetMachineTypeAttributes;
227 };
228
229 fn is_amd64_emulation_supported_inner() -> Option<bool> {
230 // GetMachineTypeAttributes is only available on Win11 22000+, so dynamically load it.
231 let kernel32 = LibraryHandle::new(b"kernel32.dll\0")?;
232 // SAFETY: GetMachineTypeAttributesFuncType is checked to match the real function signature.
233 let get_machine_type_attributes = unsafe {
234 kernel32
235 .get_proc_address::<GetMachineTypeAttributesFuncType>(b"GetMachineTypeAttributes\0")
236 }?;
237 let mut attributes = Default::default();
238 if unsafe { get_machine_type_attributes(IMAGE_FILE_MACHINE_AMD64, &mut attributes) } == S_OK
239 {
240 Some((attributes & UserEnabled) != 0)
241 } else {
242 Some(false)
243 }
244 }
245
246 fn is_amd64_emulation_supported() -> bool {
247 // TODO: Replace with a OnceLock once MSRV is 1.70.
248 static LOAD_VALUE: Once = Once::new();
249 static IS_SUPPORTED: AtomicBool = AtomicBool::new(false);
250
251 // Using Relaxed ordering since the Once is providing synchronization.
252 LOAD_VALUE.call_once(|| {
253 IS_SUPPORTED.store(
254 is_amd64_emulation_supported_inner().unwrap_or(false),
255 Ordering::Relaxed,
256 );
257 });
258 IS_SUPPORTED.load(Ordering::Relaxed)
259 }
260
261 impl MsvcTool {
262 fn new(tool: PathBuf) -> MsvcTool {
263 MsvcTool {
264 tool,
265 libs: Vec::new(),
266 path: Vec::new(),
267 include: Vec::new(),
268 }
269 }
270
271 fn into_tool(self) -> Tool {
272 let MsvcTool {
273 tool,
274 libs,
275 path,
276 include,
277 } = self;
278 let mut tool = Tool::with_family(tool, MSVC_FAMILY);
279 add_env(&mut tool, "LIB", libs);
280 add_env(&mut tool, "PATH", path);
281 add_env(&mut tool, "INCLUDE", include);
282 tool
283 }
284 }
285
286 /// Checks to see if the `VSCMD_ARG_TGT_ARCH` environment variable matches the
287 /// given target's arch. Returns `None` if the variable does not exist.
288 fn is_vscmd_target(target: TargetArch<'_>) -> Option<bool> {
289 let vscmd_arch = env::var("VSCMD_ARG_TGT_ARCH").ok()?;
290 // Convert the Rust target arch to its VS arch equivalent.
291 let arch = match target.into() {
292 "x86_64" => "x64",
293 "aarch64" | "arm64ec" => "arm64",
294 "i686" | "i586" => "x86",
295 "thumbv7a" => "arm",
296 // An unrecognized arch.
297 _ => return Some(false),
298 };
299 Some(vscmd_arch == arch)
300 }
301
302 /// Attempt to find the tool using environment variables set by vcvars.
303 pub(super) fn find_msvc_environment(tool: &str, target: TargetArch<'_>) -> Option<Tool> {
304 // Early return if the environment doesn't contain a VC install.
305 if env::var_os("VCINSTALLDIR").is_none() {
306 return None;
307 }
308 let vs_install_dir = env::var_os("VSINSTALLDIR")?.into();
309
310 // If the vscmd target differs from the requested target then
311 // attempt to get the tool using the VS install directory.
312 if is_vscmd_target(target) == Some(false) {
313 // We will only get here with versions 15+.
314 tool_from_vs15plus_instance(tool, target, &vs_install_dir)
315 } else {
316 // Fallback to simply using the current environment.
317 env::var_os("PATH")
318 .and_then(|path| {
319 env::split_paths(&path)
320 .map(|p| p.join(tool))
321 .find(|p| p.exists())
322 })
323 .map(|path| Tool::with_family(path, MSVC_FAMILY))
324 }
325 }
326
327 fn find_msbuild_vs17(target: TargetArch<'_>) -> Option<Tool> {
328 find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "17")
329 }
330
331 #[allow(bare_trait_objects)]
332 fn vs16plus_instances(
333 target: TargetArch<'_>,
334 version: &'static str,
335 ) -> Box<Iterator<Item = PathBuf>> {
336 let instances = if let Some(instances) = vs15plus_instances(target) {
337 instances
338 } else {
339 return Box::new(iter::empty());
340 };
341 Box::new(instances.into_iter().filter_map(move |instance| {
342 let installation_name = instance.installation_name()?;
343 if installation_name.starts_with(&format!("VisualStudio/{}.", version)) {
344 Some(instance.installation_path()?)
345 } else if installation_name.starts_with(&format!("VisualStudioPreview/{}.", version)) {
346 Some(instance.installation_path()?)
347 } else {
348 None
349 }
350 }))
351 }
352
353 fn find_tool_in_vs16plus_path(
354 tool: &str,
355 target: TargetArch<'_>,
356 version: &'static str,
357 ) -> Option<Tool> {
358 vs16plus_instances(target, version)
359 .filter_map(|path| {
360 let path = path.join(tool);
361 if !path.is_file() {
362 return None;
363 }
364 let mut tool = Tool::with_family(path, MSVC_FAMILY);
365 if target == "x86_64" {
366 tool.env.push(("Platform".into(), "X64".into()));
367 }
368 if target == "aarch64" || target == "arm64ec" {
369 tool.env.push(("Platform".into(), "ARM64".into()));
370 }
371 Some(tool)
372 })
373 .next()
374 }
375
376 fn find_msbuild_vs16(target: TargetArch<'_>) -> Option<Tool> {
377 find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "16")
378 }
379
380 // In MSVC 15 (2017) MS once again changed the scheme for locating
381 // the tooling. Now we must go through some COM interfaces, which
382 // is super fun for Rust.
383 //
384 // Note that much of this logic can be found [online] wrt paths, COM, etc.
385 //
386 // [online]: https://blogs.msdn.microsoft.com/vcblog/2017/03/06/finding-the-visual-c-compiler-tools-in-visual-studio-2017/
387 //
388 // Returns MSVC 15+ instances (15, 16 right now), the order should be consider undefined.
389 //
390 // However, on ARM64 this method doesn't work because VS Installer fails to register COM component on ARM64.
391 // Hence, as the last resort we try to use vswhere.exe to list available instances.
392 fn vs15plus_instances(target: TargetArch<'_>) -> Option<VsInstances> {
393 vs15plus_instances_using_com().or_else(|| vs15plus_instances_using_vswhere(target))
394 }
395
396 fn vs15plus_instances_using_com() -> Option<VsInstances> {
397 com::initialize().ok()?;
398
399 let config = SetupConfiguration::new().ok()?;
400 let enum_setup_instances = config.enum_all_instances().ok()?;
401
402 Some(VsInstances::ComBased(enum_setup_instances))
403 }
404
405 fn vs15plus_instances_using_vswhere(target: TargetArch<'_>) -> Option<VsInstances> {
406 let program_files_path: PathBuf = env::var("ProgramFiles(x86)")
407 .or_else(|_| env::var("ProgramFiles"))
408 .ok()?
409 .into();
410
411 let vswhere_path =
412 program_files_path.join(r"Microsoft Visual Studio\Installer\vswhere.exe");
413
414 if !vswhere_path.exists() {
415 return None;
416 }
417
418 let tools_arch = match target.into() {
419 "i586" | "i686" | "x86_64" => Some("x86.x64"),
420 "arm" | "thumbv7a" => Some("ARM"),
421 "aarch64" | "arm64ec" => Some("ARM64"),
422 _ => None,
423 };
424
425 let vswhere_output = Command::new(vswhere_path)
426 .args(&[
427 "-latest",
428 "-products",
429 "*",
430 "-requires",
431 &format!("Microsoft.VisualStudio.Component.VC.Tools.{}", tools_arch?),
432 "-format",
433 "text",
434 "-nologo",
435 ])
436 .stderr(std::process::Stdio::inherit())
437 .output()
438 .ok()?;
439
440 let vs_instances =
441 VsInstances::VswhereBased(VswhereInstance::try_from(&vswhere_output.stdout).ok()?);
442
443 Some(vs_instances)
444 }
445
446 // Inspired from official microsoft/vswhere ParseVersionString
447 // i.e. at most four u16 numbers separated by '.'
448 fn parse_version(version: &str) -> Option<Vec<u16>> {
449 version
450 .split('.')
451 .map(|chunk| u16::from_str(chunk).ok())
452 .collect()
453 }
454
455 pub(super) fn find_msvc_15plus(tool: &str, target: TargetArch<'_>) -> Option<Tool> {
456 let iter = vs15plus_instances(target)?;
457 iter.into_iter()
458 .filter_map(|instance| {
459 let version = parse_version(&instance.installation_version()?)?;
460 let instance_path = instance.installation_path()?;
461 let tool = tool_from_vs15plus_instance(tool, target, &instance_path)?;
462 Some((version, tool))
463 })
464 .max_by(|(a_version, _), (b_version, _)| a_version.cmp(b_version))
465 .map(|(_version, tool)| tool)
466 }
467
468 // While the paths to Visual Studio 2017's devenv and MSBuild could
469 // potentially be retrieved from the registry, finding them via
470 // SetupConfiguration has shown to be [more reliable], and is preferred
471 // according to Microsoft. To help head off potential regressions though,
472 // we keep the registry method as a fallback option.
473 //
474 // [more reliable]: https://github.com/rust-lang/cc-rs/pull/331
475 fn find_tool_in_vs15_path(tool: &str, target: TargetArch<'_>) -> Option<Tool> {
476 let mut path = match vs15plus_instances(target) {
477 Some(instances) => instances
478 .into_iter()
479 .filter_map(|instance| instance.installation_path())
480 .map(|path| path.join(tool))
481 .find(|path| path.is_file()),
482 None => None,
483 };
484
485 if path.is_none() {
486 let key = r"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7";
487 path = LOCAL_MACHINE
488 .open(key.as_ref())
489 .ok()
490 .and_then(|key| key.query_str("15.0").ok())
491 .map(|path| PathBuf::from(path).join(tool))
492 .and_then(|path| if path.is_file() { Some(path) } else { None });
493 }
494
495 path.map(|path| {
496 let mut tool = Tool::with_family(path, MSVC_FAMILY);
497 if target == "x86_64" {
498 tool.env.push(("Platform".into(), "X64".into()));
499 } else if target == "aarch64" {
500 tool.env.push(("Platform".into(), "ARM64".into()));
501 }
502 tool
503 })
504 }
505
506 fn tool_from_vs15plus_instance(
507 tool: &str,
508 target: TargetArch<'_>,
509 instance_path: &PathBuf,
510 ) -> Option<Tool> {
511 let (root_path, bin_path, host_dylib_path, lib_path, alt_lib_path, include_path) =
512 vs15plus_vc_paths(target, instance_path)?;
513 let tool_path = bin_path.join(tool);
514 if !tool_path.exists() {
515 return None;
516 };
517
518 let mut tool = MsvcTool::new(tool_path);
519 tool.path.push(bin_path.clone());
520 tool.path.push(host_dylib_path);
521 if let Some(alt_lib_path) = alt_lib_path {
522 tool.libs.push(alt_lib_path);
523 }
524 tool.libs.push(lib_path);
525 tool.include.push(include_path);
526
527 if let Some((atl_lib_path, atl_include_path)) = atl_paths(target, &root_path) {
528 tool.libs.push(atl_lib_path);
529 tool.include.push(atl_include_path);
530 }
531
532 add_sdks(&mut tool, target)?;
533
534 Some(tool.into_tool())
535 }
536
537 fn vs15plus_vc_paths(
538 target: TargetArch<'_>,
539 instance_path: &Path,
540 ) -> Option<(PathBuf, PathBuf, PathBuf, PathBuf, Option<PathBuf>, PathBuf)> {
541 let version = vs15plus_vc_read_version(instance_path)?;
542
543 let hosts = match host_arch() {
544 X86 => &["X86"],
545 X86_64 => &["X64"],
546 // Starting with VS 17.4, there is a natively hosted compiler on ARM64:
547 // https://devblogs.microsoft.com/visualstudio/arm64-visual-studio-is-officially-here/
548 // On older versions of VS, we use x64 if running under emulation is supported,
549 // otherwise use x86.
550 AARCH64 => {
551 if is_amd64_emulation_supported() {
552 &["ARM64", "X64", "X86"][..]
553 } else {
554 &["ARM64", "X86"]
555 }
556 }
557 _ => return None,
558 };
559 let target = lib_subdir(target)?;
560 // The directory layout here is MSVC/bin/Host$host/$target/
561 let path = instance_path.join(r"VC\Tools\MSVC").join(version);
562 // We use the first available host architecture that can build for the target
563 let (host_path, host) = hosts.iter().find_map(|&x| {
564 let candidate = path.join("bin").join(format!("Host{}", x));
565 if candidate.join(target).exists() {
566 Some((candidate, x))
567 } else {
568 None
569 }
570 })?;
571 // This is the path to the toolchain for a particular target, running
572 // on a given host
573 let bin_path = host_path.join(target);
574 // But! we also need PATH to contain the target directory for the host
575 // architecture, because it contains dlls like mspdb140.dll compiled for
576 // the host architecture.
577 let host_dylib_path = host_path.join(host.to_lowercase());
578 let lib_fragment = if use_spectre_mitigated_libs() {
579 r"lib\spectre"
580 } else {
581 "lib"
582 };
583 let lib_path = path.join(lib_fragment).join(target);
584 let alt_lib_path = (target == "arm64ec").then(|| path.join(lib_fragment).join("arm64ec"));
585 let include_path = path.join("include");
586 Some((
587 path,
588 bin_path,
589 host_dylib_path,
590 lib_path,
591 alt_lib_path,
592 include_path,
593 ))
594 }
595
596 fn vs15plus_vc_read_version(dir: &Path) -> Option<String> {
597 // Try to open the default version file.
598 let mut version_path: PathBuf =
599 dir.join(r"VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt");
600 let mut version_file = if let Ok(f) = File::open(&version_path) {
601 f
602 } else {
603 // If the default doesn't exist, search for other version files.
604 // These are in the form Microsoft.VCToolsVersion.v143.default.txt
605 // where `143` is any three decimal digit version number.
606 // This sorts versions by lexical order and selects the highest version.
607 let mut version_file = String::new();
608 version_path.pop();
609 for file in version_path.read_dir().ok()? {
610 let name = file.ok()?.file_name();
611 let name = name.to_str()?;
612 if name.starts_with("Microsoft.VCToolsVersion.v")
613 && name.ends_with(".default.txt")
614 && name > &version_file
615 {
616 version_file.replace_range(.., name);
617 }
618 }
619 if version_file.is_empty() {
620 return None;
621 }
622 version_path.push(version_file);
623 File::open(version_path).ok()?
624 };
625
626 // Get the version string from the file we found.
627 let mut version = String::new();
628 version_file.read_to_string(&mut version).ok()?;
629 version.truncate(version.trim_end().len());
630 Some(version)
631 }
632
633 fn use_spectre_mitigated_libs() -> bool {
634 env::var("VSCMD_ARG_VCVARS_SPECTRE").as_deref() == Ok("spectre")
635 }
636
637 fn atl_paths(target: TargetArch<'_>, path: &Path) -> Option<(PathBuf, PathBuf)> {
638 let atl_path = path.join("atlmfc");
639 let sub = lib_subdir(target)?;
640 if atl_path.exists() {
641 Some((atl_path.join("lib").join(sub), atl_path.join("include")))
642 } else {
643 None
644 }
645 }
646
647 // For MSVC 14 we need to find the Universal CRT as well as either
648 // the Windows 10 SDK or Windows 8.1 SDK.
649 pub(super) fn find_msvc_14(tool: &str, target: TargetArch<'_>) -> Option<Tool> {
650 let vcdir = get_vc_dir("14.0")?;
651 let mut tool = get_tool(tool, &vcdir, target)?;
652 add_sdks(&mut tool, target)?;
653 Some(tool.into_tool())
654 }
655
656 fn add_sdks(tool: &mut MsvcTool, target: TargetArch<'_>) -> Option<()> {
657 let sub = lib_subdir(target)?;
658 let (ucrt, ucrt_version) = get_ucrt_dir()?;
659
660 let host = match host_arch() {
661 X86 => "x86",
662 X86_64 => "x64",
663 AARCH64 => "arm64",
664 _ => return None,
665 };
666
667 tool.path
668 .push(ucrt.join("bin").join(&ucrt_version).join(host));
669
670 let ucrt_include = ucrt.join("include").join(&ucrt_version);
671 tool.include.push(ucrt_include.join("ucrt"));
672
673 let ucrt_lib = ucrt.join("lib").join(&ucrt_version);
674 tool.libs.push(ucrt_lib.join("ucrt").join(sub));
675
676 if let Some((sdk, version)) = get_sdk10_dir() {
677 tool.path.push(sdk.join("bin").join(host));
678 let sdk_lib = sdk.join("lib").join(&version);
679 tool.libs.push(sdk_lib.join("um").join(sub));
680 let sdk_include = sdk.join("include").join(&version);
681 tool.include.push(sdk_include.join("um"));
682 tool.include.push(sdk_include.join("cppwinrt"));
683 tool.include.push(sdk_include.join("winrt"));
684 tool.include.push(sdk_include.join("shared"));
685 } else if let Some(sdk) = get_sdk81_dir() {
686 tool.path.push(sdk.join("bin").join(host));
687 let sdk_lib = sdk.join("lib").join("winv6.3");
688 tool.libs.push(sdk_lib.join("um").join(sub));
689 let sdk_include = sdk.join("include");
690 tool.include.push(sdk_include.join("um"));
691 tool.include.push(sdk_include.join("winrt"));
692 tool.include.push(sdk_include.join("shared"));
693 }
694
695 Some(())
696 }
697
698 // For MSVC 12 we need to find the Windows 8.1 SDK.
699 pub(super) fn find_msvc_12(tool: &str, target: TargetArch<'_>) -> Option<Tool> {
700 let vcdir = get_vc_dir("12.0")?;
701 let mut tool = get_tool(tool, &vcdir, target)?;
702 let sub = lib_subdir(target)?;
703 let sdk81 = get_sdk81_dir()?;
704 tool.path.push(sdk81.join("bin").join(sub));
705 let sdk_lib = sdk81.join("lib").join("winv6.3");
706 tool.libs.push(sdk_lib.join("um").join(sub));
707 let sdk_include = sdk81.join("include");
708 tool.include.push(sdk_include.join("shared"));
709 tool.include.push(sdk_include.join("um"));
710 tool.include.push(sdk_include.join("winrt"));
711 Some(tool.into_tool())
712 }
713
714 fn add_env(tool: &mut Tool, env: &str, paths: Vec<PathBuf>) {
715 let prev = env::var_os(env).unwrap_or(OsString::new());
716 let prev = env::split_paths(&prev);
717 let new = paths.into_iter().chain(prev);
718 tool.env
719 .push((env.to_string().into(), env::join_paths(new).unwrap()));
720 }
721
722 // Given a possible MSVC installation directory, we look for the linker and
723 // then add the MSVC library path.
724 fn get_tool(tool: &str, path: &Path, target: TargetArch<'_>) -> Option<MsvcTool> {
725 bin_subdir(target)
726 .into_iter()
727 .map(|(sub, host)| {
728 (
729 path.join("bin").join(sub).join(tool),
730 path.join("bin").join(host),
731 )
732 })
733 .filter(|(path, _)| path.is_file())
734 .map(|(path, host)| {
735 let mut tool = MsvcTool::new(path);
736 tool.path.push(host);
737 tool
738 })
739 .filter_map(|mut tool| {
740 let sub = vc_lib_subdir(target)?;
741 tool.libs.push(path.join("lib").join(sub));
742 tool.include.push(path.join("include"));
743 let atlmfc_path = path.join("atlmfc");
744 if atlmfc_path.exists() {
745 tool.libs.push(atlmfc_path.join("lib").join(sub));
746 tool.include.push(atlmfc_path.join("include"));
747 }
748 Some(tool)
749 })
750 .next()
751 }
752
753 // To find MSVC we look in a specific registry key for the version we are
754 // trying to find.
755 fn get_vc_dir(ver: &str) -> Option<PathBuf> {
756 let key = r"SOFTWARE\Microsoft\VisualStudio\SxS\VC7";
757 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
758 let path = key.query_str(ver).ok()?;
759 Some(path.into())
760 }
761
762 // To find the Universal CRT we look in a specific registry key for where
763 // all the Universal CRTs are located and then sort them asciibetically to
764 // find the newest version. While this sort of sorting isn't ideal, it is
765 // what vcvars does so that's good enough for us.
766 //
767 // Returns a pair of (root, version) for the ucrt dir if found
768 fn get_ucrt_dir() -> Option<(PathBuf, String)> {
769 let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots";
770 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
771 let root = key.query_str("KitsRoot10").ok()?;
772 let readdir = Path::new(&root).join("lib").read_dir().ok()?;
773 let max_libdir = readdir
774 .filter_map(|dir| dir.ok())
775 .map(|dir| dir.path())
776 .filter(|dir| {
777 dir.components()
778 .last()
779 .and_then(|c| c.as_os_str().to_str())
780 .map(|c| c.starts_with("10.") && dir.join("ucrt").is_dir())
781 .unwrap_or(false)
782 })
783 .max()?;
784 let version = max_libdir.components().last().unwrap();
785 let version = version.as_os_str().to_str().unwrap().to_string();
786 Some((root.into(), version))
787 }
788
789 // Vcvars finds the correct version of the Windows 10 SDK by looking
790 // for the include `um\Windows.h` because sometimes a given version will
791 // only have UCRT bits without the rest of the SDK. Since we only care about
792 // libraries and not includes, we instead look for `um\x64\kernel32.lib`.
793 // Since the 32-bit and 64-bit libraries are always installed together we
794 // only need to bother checking x64, making this code a tiny bit simpler.
795 // Like we do for the Universal CRT, we sort the possibilities
796 // asciibetically to find the newest one as that is what vcvars does.
797 // Before doing that, we check the "WindowsSdkDir" and "WindowsSDKVersion"
798 // environment variables set by vcvars to use the environment sdk version
799 // if one is already configured.
800 fn get_sdk10_dir() -> Option<(PathBuf, String)> {
801 if let (Ok(root), Ok(version)) = (env::var("WindowsSdkDir"), env::var("WindowsSDKVersion"))
802 {
803 return Some((root.into(), version.trim_end_matches('\\').to_string()));
804 }
805
806 let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0";
807 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
808 let root = key.query_str("InstallationFolder").ok()?;
809 let readdir = Path::new(&root).join("lib").read_dir().ok()?;
810 let mut dirs = readdir
811 .filter_map(|dir| dir.ok())
812 .map(|dir| dir.path())
813 .collect::<Vec<_>>();
814 dirs.sort();
815 let dir = dirs
816 .into_iter()
817 .rev()
818 .filter(|dir| dir.join("um").join("x64").join("kernel32.lib").is_file())
819 .next()?;
820 let version = dir.components().last().unwrap();
821 let version = version.as_os_str().to_str().unwrap().to_string();
822 Some((root.into(), version))
823 }
824
825 // Interestingly there are several subdirectories, `win7` `win8` and
826 // `winv6.3`. Vcvars seems to only care about `winv6.3` though, so the same
827 // applies to us. Note that if we were targeting kernel mode drivers
828 // instead of user mode applications, we would care.
829 fn get_sdk81_dir() -> Option<PathBuf> {
830 let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1";
831 let key = LOCAL_MACHINE.open(key.as_ref()).ok()?;
832 let root = key.query_str("InstallationFolder").ok()?;
833 Some(root.into())
834 }
835
836 const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0;
837 const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
838 const PROCESSOR_ARCHITECTURE_ARM64: u16 = 12;
839 const X86: u16 = PROCESSOR_ARCHITECTURE_INTEL;
840 const X86_64: u16 = PROCESSOR_ARCHITECTURE_AMD64;
841 const AARCH64: u16 = PROCESSOR_ARCHITECTURE_ARM64;
842
843 // When choosing the tool to use, we have to choose the one which matches
844 // the target architecture. Otherwise we end up in situations where someone
845 // on 32-bit Windows is trying to cross compile to 64-bit and it tries to
846 // invoke the native 64-bit compiler which won't work.
847 //
848 // For the return value of this function, the first member of the tuple is
849 // the folder of the tool we will be invoking, while the second member is
850 // the folder of the host toolchain for that tool which is essential when
851 // using a cross linker. We return a Vec since on x64 there are often two
852 // linkers that can target the architecture we desire. The 64-bit host
853 // linker is preferred, and hence first, due to 64-bit allowing it more
854 // address space to work with and potentially being faster.
855 fn bin_subdir(target: TargetArch<'_>) -> Vec<(&'static str, &'static str)> {
856 match (target.into(), host_arch()) {
857 ("i586", X86) | ("i686", X86) => vec![("", "")],
858 ("i586", X86_64) | ("i686", X86_64) => vec![("amd64_x86", "amd64"), ("", "")],
859 ("x86_64", X86) => vec![("x86_amd64", "")],
860 ("x86_64", X86_64) => vec![("amd64", "amd64"), ("x86_amd64", "")],
861 ("arm", X86) | ("thumbv7a", X86) => vec![("x86_arm", "")],
862 ("arm", X86_64) | ("thumbv7a", X86_64) => vec![("amd64_arm", "amd64"), ("x86_arm", "")],
863 _ => vec![],
864 }
865 }
866
867 fn lib_subdir(target: TargetArch<'_>) -> Option<&'static str> {
868 match target.into() {
869 "i586" | "i686" => Some("x86"),
870 "x86_64" => Some("x64"),
871 "arm" | "thumbv7a" => Some("arm"),
872 "aarch64" | "arm64ec" => Some("arm64"),
873 _ => None,
874 }
875 }
876
877 // MSVC's x86 libraries are not in a subfolder
878 fn vc_lib_subdir(target: TargetArch<'_>) -> Option<&'static str> {
879 match target.into() {
880 "i586" | "i686" => Some(""),
881 "x86_64" => Some("amd64"),
882 "arm" | "thumbv7a" => Some("arm"),
883 "aarch64" => Some("arm64"),
884 _ => None,
885 }
886 }
887
888 #[allow(bad_style)]
889 fn host_arch() -> u16 {
890 type DWORD = u32;
891 type WORD = u16;
892 type LPVOID = *mut u8;
893 type DWORD_PTR = usize;
894
895 #[repr(C)]
896 struct SYSTEM_INFO {
897 wProcessorArchitecture: WORD,
898 _wReserved: WORD,
899 _dwPageSize: DWORD,
900 _lpMinimumApplicationAddress: LPVOID,
901 _lpMaximumApplicationAddress: LPVOID,
902 _dwActiveProcessorMask: DWORD_PTR,
903 _dwNumberOfProcessors: DWORD,
904 _dwProcessorType: DWORD,
905 _dwAllocationGranularity: DWORD,
906 _wProcessorLevel: WORD,
907 _wProcessorRevision: WORD,
908 }
909
910 extern "system" {
911 fn GetNativeSystemInfo(lpSystemInfo: *mut SYSTEM_INFO);
912 }
913
914 unsafe {
915 let mut info = mem::zeroed();
916 GetNativeSystemInfo(&mut info);
917 info.wProcessorArchitecture
918 }
919 }
920
921 // Given a registry key, look at all the sub keys and find the one which has
922 // the maximal numeric value.
923 //
924 // Returns the name of the maximal key as well as the opened maximal key.
925 fn max_version(key: &RegistryKey) -> Option<(OsString, RegistryKey)> {
926 let mut max_vers = 0;
927 let mut max_key = None;
928 for subkey in key.iter().filter_map(|k| k.ok()) {
929 let val = subkey
930 .to_str()
931 .and_then(|s| s.trim_left_matches("v").replace('.', "").parse().ok());
932 let val = match val {
933 Some(s) => s,
934 None => continue,
935 };
936 if val > max_vers {
937 if let Ok(k) = key.open(&subkey) {
938 max_vers = val;
939 max_key = Some((subkey, k));
940 }
941 }
942 }
943 max_key
944 }
945
946 pub(super) fn has_msbuild_version(version: &str) -> bool {
947 match version {
948 "17.0" => {
949 find_msbuild_vs17(TargetArch("x86_64")).is_some()
950 || find_msbuild_vs17(TargetArch("i686")).is_some()
951 || find_msbuild_vs17(TargetArch("aarch64")).is_some()
952 }
953 "16.0" => {
954 find_msbuild_vs16(TargetArch("x86_64")).is_some()
955 || find_msbuild_vs16(TargetArch("i686")).is_some()
956 || find_msbuild_vs16(TargetArch("aarch64")).is_some()
957 }
958 "15.0" => {
959 find_msbuild_vs15(TargetArch("x86_64")).is_some()
960 || find_msbuild_vs15(TargetArch("i686")).is_some()
961 || find_msbuild_vs15(TargetArch("aarch64")).is_some()
962 }
963 "12.0" | "14.0" => LOCAL_MACHINE
964 .open(&OsString::from(format!(
965 "SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{}",
966 version
967 )))
968 .is_ok(),
969 _ => false,
970 }
971 }
972
973 pub(super) fn find_devenv(target: TargetArch<'_>) -> Option<Tool> {
974 find_devenv_vs15(target)
975 }
976
977 fn find_devenv_vs15(target: TargetArch<'_>) -> Option<Tool> {
978 find_tool_in_vs15_path(r"Common7\IDE\devenv.exe", target)
979 }
980
981 // see http://stackoverflow.com/questions/328017/path-to-msbuild
982 pub(super) fn find_msbuild(target: TargetArch<'_>) -> Option<Tool> {
983 // VS 15 (2017) changed how to locate msbuild
984 if let Some(r) = find_msbuild_vs17(target) {
985 Some(r)
986 } else if let Some(r) = find_msbuild_vs16(target) {
987 return Some(r);
988 } else if let Some(r) = find_msbuild_vs15(target) {
989 return Some(r);
990 } else {
991 find_old_msbuild(target)
992 }
993 }
994
995 fn find_msbuild_vs15(target: TargetArch<'_>) -> Option<Tool> {
996 find_tool_in_vs15_path(r"MSBuild\15.0\Bin\MSBuild.exe", target)
997 }
998
999 fn find_old_msbuild(target: TargetArch<'_>) -> Option<Tool> {
1000 let key = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions";
1001 LOCAL_MACHINE
1002 .open(key.as_ref())
1003 .ok()
1004 .and_then(|key| {
1005 max_version(&key).and_then(|(_vers, key)| key.query_str("MSBuildToolsPath").ok())
1006 })
1007 .map(|path| {
1008 let mut path = PathBuf::from(path);
1009 path.push("MSBuild.exe");
1010 let mut tool = Tool::with_family(path, MSVC_FAMILY);
1011 if target == "x86_64" {
1012 tool.env.push(("Platform".into(), "X64".into()));
1013 }
1014 tool
1015 })
1016 }
1017 }
1018
1019 /// Non-Windows Implementation.
1020 #[cfg(not(windows))]
1021 mod impl_ {
1022 use std::{env, ffi::OsString};
1023
1024 use super::{TargetArch, MSVC_FAMILY};
1025 use crate::Tool;
1026
1027 /// Finding msbuild.exe tool under unix system is not currently supported.
1028 /// Maybe can check it using an environment variable looks like `MSBUILD_BIN`.
1029 pub(super) fn find_msbuild(_target: TargetArch<'_>) -> Option<Tool> {
1030 None
1031 }
1032
1033 // Finding devenv.exe tool under unix system is not currently supported.
1034 // Maybe can check it using an environment variable looks like `DEVENV_BIN`.
1035 pub(super) fn find_devenv(_target: TargetArch<'_>) -> Option<Tool> {
1036 None
1037 }
1038
1039 /// Attempt to find the tool using environment variables set by vcvars.
1040 pub(super) fn find_msvc_environment(tool: &str, _target: TargetArch<'_>) -> Option<Tool> {
1041 // Early return if the environment doesn't contain a VC install.
1042 let vc_install_dir = env::var_os("VCINSTALLDIR")?;
1043 let vs_install_dir = env::var_os("VSINSTALLDIR")?;
1044
1045 let get_tool = |install_dir: OsString| {
1046 env::split_paths(&install_dir)
1047 .map(|p| p.join(tool))
1048 .find(|p| p.exists())
1049 .map(|path| Tool::with_family(path.into(), MSVC_FAMILY))
1050 };
1051
1052 // Take the path of tool for the vc install directory.
1053 get_tool(vc_install_dir)
1054 // Take the path of tool for the vs install directory.
1055 .or_else(|| get_tool(vs_install_dir))
1056 // Take the path of tool for the current path environment.
1057 .or_else(|| env::var_os("PATH").and_then(|path| get_tool(path)))
1058 }
1059
1060 pub(super) fn find_msvc_15plus(_tool: &str, _target: TargetArch<'_>) -> Option<Tool> {
1061 None
1062 }
1063
1064 // For MSVC 14 we need to find the Universal CRT as well as either
1065 // the Windows 10 SDK or Windows 8.1 SDK.
1066 pub(super) fn find_msvc_14(_tool: &str, _target: TargetArch<'_>) -> Option<Tool> {
1067 None
1068 }
1069
1070 // For MSVC 12 we need to find the Windows 8.1 SDK.
1071 pub(super) fn find_msvc_12(_tool: &str, _target: TargetArch<'_>) -> Option<Tool> {
1072 None
1073 }
1074
1075 pub(super) fn has_msbuild_version(version: &str) -> bool {
1076 match version {
1077 "17.0" => false,
1078 "16.0" => false,
1079 "15.0" => false,
1080 "12.0" | "14.0" => false,
1081 _ => false,
1082 }
1083 }
1084 }