Skip to main content

cuno_toolchain/msvc/
environment.rs

1//! The environment MSVC, clang and clang-cl need on Windows, built from a
2//! toolset and the Windows SDK rather than by running `vcvars64.bat`. See
3//! `docs/en/specs/toolchain.md`, "Environment resolution on Windows".
4
5use std::ffi::OsString;
6use std::path::{Path, PathBuf};
7
8use cuno_core::Env;
9
10use super::MsvcToolset;
11use crate::ToolchainError;
12
13/// Where the Windows SDK installer records its location.
14const KITS_KEY: &str = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots";
15const KITS_VALUE: &str = "KitsRoot10";
16
17/// The machine's registry, as far as finding the Windows SDK needs it: a
18/// value, so tests can stand in for it.
19pub trait Registry {
20    /// A string value under `HKEY_LOCAL_MACHINE`, if it exists.
21    fn local_machine_string(&self, key: &str, value: &str) -> Option<OsString>;
22}
23
24/// The real registry. Elsewhere than on Windows there is none.
25pub struct SystemRegistry;
26
27impl Registry for SystemRegistry {
28    #[cfg(windows)]
29    fn local_machine_string(&self, key: &str, value: &str) -> Option<OsString> {
30        let hklm = winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE);
31        hklm.open_subkey(key)
32            .ok()?
33            .get_value::<OsString, _>(value)
34            .ok()
35    }
36
37    #[cfg(not(windows))]
38    fn local_machine_string(&self, _key: &str, _value: &str) -> Option<OsString> {
39        None
40    }
41}
42
43/// One Windows SDK version.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct WindowsSdk {
46    /// The SDK directory (`...\Windows Kits\10`).
47    pub dir: PathBuf,
48    /// The version directory name (`10.0.28000.0`).
49    pub version: String,
50}
51
52/// The Windows SDK to build with: the newest complete version in the first
53/// place that has one, of the registered SDK directory and
54/// `%ProgramFiles(x86)%\Windows Kits\10`.
55pub fn find_windows_sdk(env: &Env, registry: &dyn Registry) -> Result<WindowsSdk, ToolchainError> {
56    let roots = sdk_roots(env, registry);
57    for dir in &roots {
58        if let Some(version) = newest_complete_version(dir) {
59            return Ok(WindowsSdk {
60                dir: dir.clone(),
61                version,
62            });
63        }
64    }
65    let looked_in = if roots.is_empty() {
66        vec![
67            Path::new("%ProgramFiles(x86)%")
68                .join("Windows Kits")
69                .join("10"),
70        ]
71    } else {
72        roots
73    };
74    Err(ToolchainError::NoWindowsSdk { looked_in })
75}
76
77/// Where the SDK may be, in order: the registered directory, then the one
78/// under `%ProgramFiles(x86)%`, taking only absolute ones. An empty or
79/// relative directory would be read from cuno's working directory (often the
80/// project).
81fn sdk_roots(env: &Env, registry: &dyn Registry) -> Vec<PathBuf> {
82    let registered = registry
83        .local_machine_string(KITS_KEY, KITS_VALUE)
84        .map(PathBuf::from);
85    let program_files = env
86        .get("ProgramFiles(x86)")
87        .map(|pf| Path::new(pf).join("Windows Kits").join("10"));
88    let mut roots: Vec<PathBuf> = Vec::new();
89    for dir in [registered, program_files].into_iter().flatten() {
90        if dir.is_absolute() && !roots.contains(&dir) {
91            roots.push(dir);
92        }
93    }
94    roots
95}
96
97/// The newest version under `dir` that is complete, compared as numbers.
98fn newest_complete_version(dir: &Path) -> Option<String> {
99    let mut versions: Vec<(Vec<u32>, String)> = std::fs::read_dir(dir.join("Include"))
100        .into_iter()
101        .flatten()
102        .flatten()
103        .filter_map(|entry| entry.file_name().into_string().ok())
104        .filter(|version| complete(dir, version))
105        .filter_map(|version| Some((numeric(&version)?, version)))
106        .collect();
107    versions.sort();
108    versions.pop().map(|(_, version)| version)
109}
110
111/// Whether `version` has the x64 headers and libraries of both the Windows
112/// API (`um`) and the C runtime (`ucrt`): an SDK can leave part of a version
113/// behind when only part of it is installed or removed.
114fn complete(dir: &Path, version: &str) -> bool {
115    let include = dir.join("Include").join(version);
116    let lib = dir.join("Lib").join(version);
117    include.join("um").join("windows.h").is_file()
118        && include.join("ucrt").join("stdio.h").is_file()
119        && lib.join("um").join("x64").is_dir()
120        && lib.join("ucrt").join("x64").is_dir()
121}
122
123/// `10.0.28000.0` as numbers, so that `10.0.9` is older than `10.0.10`.
124fn numeric(version: &str) -> Option<Vec<u32>> {
125    version.split('.').map(|part| part.parse().ok()).collect()
126}
127
128/// What a compile needs on top of the user's environment.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct MsvcEnvironment {
131    /// `INCLUDE`.
132    pub include: Vec<PathBuf>,
133    /// `LIB`.
134    pub lib: Vec<PathBuf>,
135    /// `LIBPATH`.
136    pub libpath: Vec<PathBuf>,
137    /// Put in front of `PATH`.
138    pub path: Vec<PathBuf>,
139}
140
141/// The environment for `toolset` with `sdk`, for MSVC, clang and clang-cl
142/// alike.
143pub fn resolve(toolset: &MsvcToolset, sdk: &WindowsSdk) -> MsvcEnvironment {
144    let msvc = &toolset.dir;
145    let include = sdk.dir.join("Include").join(&sdk.version);
146    let lib = sdk.dir.join("Lib").join(&sdk.version);
147    // `<VS>\VC\Auxiliary\VS\include` (`CppCoreCheck\warnings.h`), next to the
148    // toolset's `VC\Tools\MSVC\<version>`, when this Visual Studio has it.
149    let auxiliary = msvc
150        .ancestors()
151        .nth(3)
152        .map(|vc| vc.join("Auxiliary").join("VS").join("include"))
153        .filter(|dir| dir.is_dir());
154    MsvcEnvironment {
155        include: [msvc.join("include")]
156            .into_iter()
157            .chain(auxiliary)
158            .chain(
159                ["ucrt", "um", "shared", "winrt", "cppwinrt"]
160                    .iter()
161                    .map(|part| include.join(part)),
162            )
163            .collect(),
164        lib: vec![
165            msvc.join("lib").join("x64"),
166            lib.join("ucrt").join("x64"),
167            lib.join("um").join("x64"),
168        ],
169        libpath: vec![msvc.join("lib").join("x64")],
170        path: vec![
171            msvc.join("bin").join("Hostx64").join("x64"),
172            sdk.dir.join("bin").join(&sdk.version).join("x64"),
173        ],
174    }
175}
176
177impl MsvcEnvironment {
178    /// `base` with `INCLUDE`, `LIB` and `LIBPATH` replaced, `PATH` prefixed
179    /// and the Developer Command Prompt's variables removed, for running a
180    /// compiler or linker.
181    pub fn apply(&self, base: &Env) -> Env {
182        let base = &base.without(DEVELOPER_PROMPT_VARIABLES);
183        let path = self
184            .path
185            .iter()
186            .cloned()
187            .chain(base.get("PATH").into_iter().flat_map(std::env::split_paths));
188        [
189            ("INCLUDE", join(self.include.iter().cloned())),
190            ("LIB", join(self.lib.iter().cloned())),
191            ("LIBPATH", join(self.libpath.iter().cloned())),
192            ("PATH", join(path)),
193        ]
194        .into_iter()
195        .fold(base.clone(), |env, (name, value)| env.with(name, value))
196    }
197}
198
199/// What a Developer Command Prompt sets that clang and clang-cl read to find
200/// a toolset and a linker: left in place, a prompt for another Visual Studio
201/// would win over the toolset cuno chose. See `docs/en/specs/toolchain.md`,
202/// "How it is resolved".
203const DEVELOPER_PROMPT_VARIABLES: &[&str] = &[
204    "VSINSTALLDIR",
205    "VCINSTALLDIR",
206    "VCToolsInstallDir",
207    "EXTERNAL_INCLUDE",
208    "WindowsSdkDir",
209    "WindowsSDKVersion",
210    "UniversalCRTSdkDir",
211    "UCRTVersion",
212];
213
214/// Directories as one `PATH`-style value. On Windows joining fails only for
215/// a `"` in a name, which Windows does not allow in file names.
216fn join(dirs: impl Iterator<Item = PathBuf>) -> OsString {
217    std::env::join_paths(dirs).unwrap_or_default()
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::Version;
224    use cuno_core::NameCase;
225
226    struct Kits(Option<PathBuf>);
227    impl Registry for Kits {
228        fn local_machine_string(&self, key: &str, value: &str) -> Option<OsString> {
229            assert_eq!((key, value), (KITS_KEY, KITS_VALUE));
230            self.0.clone().map(Into::into)
231        }
232    }
233
234    /// What a version directory holds.
235    #[derive(Clone, Copy)]
236    enum Part {
237        Complete,
238        NoWindowsH,
239        NoUcrtHeader,
240        NoUmLib,
241        NoUcrtLib,
242    }
243
244    /// An SDK tree under `dir` with `versions`.
245    fn sdk_tree(dir: &Path, versions: &[(&str, Part)]) {
246        for (version, part) in versions {
247            let include = dir.join("Include").join(version);
248            let lib = dir.join("Lib").join(version);
249            for sub in ["um", "ucrt"] {
250                std::fs::create_dir_all(include.join(sub)).unwrap();
251            }
252            if !matches!(part, Part::NoWindowsH) {
253                std::fs::write(include.join("um").join("windows.h"), "").unwrap();
254            }
255            if !matches!(part, Part::NoUcrtHeader) {
256                std::fs::write(include.join("ucrt").join("stdio.h"), "").unwrap();
257            }
258            if !matches!(part, Part::NoUmLib) {
259                std::fs::create_dir_all(lib.join("um").join("x64")).unwrap();
260            }
261            if !matches!(part, Part::NoUcrtLib) {
262                std::fs::create_dir_all(lib.join("ucrt").join("x64")).unwrap();
263            }
264        }
265    }
266
267    fn env(pairs: &[(&str, &Path)]) -> Env {
268        Env::from_pairs(
269            pairs
270                .iter()
271                .map(|(k, v)| ((*k).into(), v.as_os_str().into())),
272            NameCase::Insensitive,
273        )
274    }
275
276    /// Mutation: compare versions as strings, take a name that is not a
277    /// number as a version, or drop any of the four checks of a complete
278    /// version; this test fails.
279    #[test]
280    fn the_newest_complete_version_is_taken() {
281        let root = tempfile::tempdir().unwrap();
282        let kits = root.path().join("Kits");
283        sdk_tree(
284            &kits,
285            &[
286                ("10.0.9.0", Part::Complete),
287                ("10.0.10.0", Part::Complete),
288                ("10.0.11.0", Part::NoWindowsH),
289                ("10.0.12.0", Part::NoUcrtHeader),
290                ("10.0.13.0", Part::NoUmLib),
291                ("10.0.14.0", Part::NoUcrtLib),
292                ("wdf", Part::Complete),
293                ("10.0.x.0", Part::Complete),
294            ],
295        );
296        let sdk = find_windows_sdk(&env(&[]), &Kits(Some(kits.clone()))).unwrap();
297        assert_eq!(
298            sdk,
299            WindowsSdk {
300                dir: kits,
301                version: "10.0.10.0".into()
302            }
303        );
304    }
305
306    /// Mutation: read `%ProgramFiles(x86)%` from the process instead of
307    /// `env`, look there before the registry, or stop at a registered
308    /// directory with no SDK left in it; this test fails. The directory name
309    /// is not ASCII, as on a machine with a Japanese user name: paths stay
310    /// paths end to end.
311    #[test]
312    fn the_registry_comes_first_and_program_files_second() {
313        let root = tempfile::tempdir().unwrap();
314        let pf = root.path().join("プログラム");
315        let installed = pf.join("Windows Kits").join("10");
316        sdk_tree(&installed, &[("10.0.1.0", Part::Complete)]);
317        let registered = root.path().join("Registered");
318        let stale = root.path().join("Stale");
319        std::fs::create_dir_all(&stale).unwrap();
320        sdk_tree(&registered, &[("10.0.1.0", Part::Complete)]);
321        let env = env(&[("ProgramFiles(x86)", &pf)]);
322        let found = |registry| find_windows_sdk(&env, &registry).unwrap().dir;
323        assert_eq!(found(Kits(Some(registered.clone()))), registered);
324        assert_eq!(found(Kits(Some(stale))), installed);
325        assert_eq!(found(Kits(None)), installed);
326    }
327
328    /// Mutation: report only one of the places looked in, take a directory
329    /// whose name is not a number as a version, or name no place
330    /// when there is none to look in; this test fails.
331    #[test]
332    fn no_complete_version_is_an_error_naming_where_it_looked() {
333        let root = tempfile::tempdir().unwrap();
334        let pf = root.path().join("pf");
335        let installed = pf.join("Windows Kits").join("10");
336        sdk_tree(
337            root.path(),
338            &[("10.0.1.0", Part::NoWindowsH), ("wdf", Part::Complete)],
339        );
340        let err = find_windows_sdk(
341            &env(&[("ProgramFiles(x86)", &pf)]),
342            &Kits(Some(root.path().into())),
343        )
344        .unwrap_err();
345        assert!(
346            matches!(&err, ToolchainError::NoWindowsSdk { looked_in } if *looked_in == [root.path().to_owned(), installed]),
347            "{err:?}"
348        );
349        let err = find_windows_sdk(&env(&[]), &Kits(None)).unwrap_err();
350        assert!(err.to_string().contains("%ProgramFiles(x86)%"), "{err}");
351    }
352
353    /// Mutation: take an empty or relative directory from the registry or
354    /// `%ProgramFiles(x86)%` instead of passing over it; this test fails.
355    #[test]
356    fn only_absolute_sdk_directories_are_searched() {
357        let pf = std::env::temp_dir();
358        let absolute = env(&[("ProgramFiles(x86)", &pf)]);
359        let relative = env(&[("ProgramFiles(x86)", Path::new("pf"))]);
360        let expected = vec![pf.join("Windows Kits").join("10")];
361        assert_eq!(sdk_roots(&absolute, &Kits(Some("".into()))), expected);
362        assert_eq!(sdk_roots(&absolute, &Kits(Some("Kits".into()))), expected);
363        assert!(sdk_roots(&relative, &Kits(None)).is_empty());
364        assert!(sdk_roots(&env(&[]), &Kits(None)).is_empty());
365    }
366
367    fn toolset(dir: impl Into<PathBuf>) -> MsvcToolset {
368        MsvcToolset {
369            dir: dir.into(),
370            cl_version: Version {
371                major: 19,
372                minor: 52,
373                patch: 1,
374            },
375        }
376    }
377
378    /// Mutation: drop `um` from `INCLUDE`, `ucrt` from `LIB`, prepend `PATH`
379    /// after the user's instead of before, or keep a Developer Command Prompt
380    /// variable; this test fails.
381    #[test]
382    fn the_environment_has_the_toolset_and_sdk_directories_in_order() {
383        let sdk = WindowsSdk {
384            dir: "K".into(),
385            version: "10.0.1.0".into(),
386        };
387        let resolved = resolve(&toolset("T"), &sdk);
388        let base = Env::from_pairs(
389            [
390                ("Path".into(), "U".into()),
391                ("INCLUDE".into(), "stale".into()),
392            ]
393            .into_iter()
394            .chain(
395                DEVELOPER_PROMPT_VARIABLES
396                    .iter()
397                    .map(|name| (name.to_ascii_lowercase().into(), "stale".into())),
398            ),
399            NameCase::Insensitive,
400        );
401        let env = resolved.apply(&base);
402        for name in DEVELOPER_PROMPT_VARIABLES {
403            assert_eq!(env.get(name), None, "{name}");
404        }
405        let list = |name: &str| -> Vec<PathBuf> {
406            std::env::split_paths(env.get(name).unwrap()).collect()
407        };
408        let p = |s: &str| PathBuf::from(s.replace('/', std::path::MAIN_SEPARATOR_STR));
409        assert_eq!(
410            list("INCLUDE"),
411            [
412                p("T/include"),
413                p("K/Include/10.0.1.0/ucrt"),
414                p("K/Include/10.0.1.0/um"),
415                p("K/Include/10.0.1.0/shared"),
416                p("K/Include/10.0.1.0/winrt"),
417                p("K/Include/10.0.1.0/cppwinrt"),
418            ]
419        );
420        assert_eq!(
421            list("LIB"),
422            [
423                p("T/lib/x64"),
424                p("K/Lib/10.0.1.0/ucrt/x64"),
425                p("K/Lib/10.0.1.0/um/x64")
426            ]
427        );
428        assert_eq!(list("LIBPATH"), [p("T/lib/x64")]);
429        assert_eq!(
430            list("PATH"),
431            [p("T/bin/Hostx64/x64"), p("K/bin/10.0.1.0/x64"), p("U")]
432        );
433    }
434
435    /// Mutation: leave out `VC\Auxiliary\VS\include`, or add it when this
436    /// Visual Studio does not have it; this test fails.
437    #[test]
438    fn the_auxiliary_include_directory_is_used_when_present() {
439        let root = tempfile::tempdir().unwrap();
440        let vc = root.path().join("VS").join("VC");
441        let msvc = vc.join("Tools").join("MSVC").join("14.52.1");
442        let sdk = WindowsSdk {
443            dir: "K".into(),
444            version: "10.0.1.0".into(),
445        };
446        let auxiliary = vc.join("Auxiliary").join("VS").join("include");
447        assert!(
448            !resolve(&toolset(msvc.clone()), &sdk)
449                .include
450                .contains(&auxiliary)
451        );
452        std::fs::create_dir_all(&auxiliary).unwrap();
453        assert_eq!(resolve(&toolset(msvc.clone()), &sdk).include[1], auxiliary);
454    }
455}