rucc_driver/library.rs
1//! Where the library's headers are.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.4.
4//!
5//! A hosted implementation is two halves and `rucc_session::runtime` is one of them. The
6//! other is the library's, and finding it is the compiler's job because nothing else can do
7//! it. A compiler that has to be told `-isystem /usr/include` on every command line is a
8//! compiler nobody can run `make` with.
9//!
10//! gcc settles this at configure time, which it can do because a gcc is built for the machine
11//! it will run on and the directories are baked into the binary. This compiler is one binary
12//! that runs wherever it is copied, so it has to ask the machine instead, and the shape of
13//! the answer is a list of candidates per platform of which the ones that exist are taken.
14//!
15//! Cross compiling to another operating system produces nothing here on purpose. The host's
16//! `/usr/include` describes the host's library and handing it to a program being built for
17//! somewhere else is worse than handing it nothing, because the failure moves from the
18//! `#include` that could not be resolved to a declaration that is quietly wrong.
19//!
20//! What a cross build gets instead is the target's own headers, out of the sysroot for that
21//! target, and [`header_dirs`] is where the two cases meet. It is the header half of what
22//! [`crate::link`] does for the libraries, it decides nothing itself, and the rule it asks is
23//! `rucc_sysroot::search`, which is section 8.5 written once.
24
25use std::path::{Path, PathBuf};
26use std::process::Command;
27use std::sync::OnceLock;
28
29use rucc_sysroot::{Kernel, Options, Sysroot, Wall, include_paths};
30use rucc_target::{Env, Os, Triple};
31
32/// What the machine says about itself, and what the command line said over the top of it.
33///
34/// Separated from the lookup so that the lookup is a function of its arguments and can be
35/// tested for a platform the test is not running on. Everything here is read once, in
36/// [`system_dirs`], which is the only place that talks to the environment.
37#[derive(Debug, Default, Clone, PartialEq, Eq)]
38pub struct Machine {
39 /// The triple of the machine the compiler is running on, when it is one we know.
40 pub host: Option<Triple>,
41 /// `--sysroot`, which prefixes the configured directories, or `-isysroot`, which is the
42 /// spelling Apple's tools use and which means the same thing to us.
43 pub sysroot: Option<PathBuf>,
44 /// The SDK to compile against on an Apple platform, once it has been found.
45 pub sdk: Option<PathBuf>,
46 /// The Windows SDK to compile against, as an `INCLUDE` spells one, once it has been found.
47 ///
48 /// `INCLUDE` itself when the environment has it, which is what `vcvarsall.bat` sets and what
49 /// every build on that platform already reads, and otherwise the same list assembled from the
50 /// Visual Studio installation this machine has. The entries are separated by `;`, which is a
51 /// path separator there and a legal character in a file name nowhere.
52 pub include: Option<String>,
53}
54
55/// The directories the library's headers might be in, in search order.
56///
57/// Every candidate, whether or not it is there. [`system_dirs`] is what filters them, and the
58/// split is so that this half can be read as the platform knowledge it is.
59#[must_use]
60pub fn candidates(target: Triple, machine: &Machine) -> Vec<PathBuf> {
61 // A target that is not this machine has no directories on this machine. There are two
62 // exceptions and they are the same exception twice: a sysroot and an SDK are both somebody
63 // saying that the headers for that target are over there, and `INCLUDE` is a third somebody
64 // saying it in the words that platform uses. The SDK case is how `SDKROOT` reaches an Apple
65 // target from a machine that is not a mac, which is the path
66 // `spec/cross-compile/08-sysroots.md` section 8.6 leaves open when it says a user supplies one.
67 if machine.sysroot.is_none()
68 && machine.sdk.is_none()
69 && machine.include.is_none()
70 && machine.host.is_some_and(|host| host.os != target.os)
71 {
72 return Vec::new();
73 }
74 let root = machine.sysroot.as_deref();
75 match target.os {
76 Os::Linux => linux(target, root),
77 Os::Darwin => darwin(machine.sdk.as_deref().or(root)),
78 Os::Windows => windows(root, machine.include.as_deref()),
79 // Freestanding. There is no library, so there are no headers of one, and the nine the
80 // compiler ships are the whole of what a program may include.
81 Os::None => Vec::new(),
82 }
83}
84
85/// gcc's order on a glibc system, which is what every Linux distribution lays out.
86///
87/// `/usr/local/include` first because that is where a locally built library installs and the
88/// point of installing one there is that it wins. The multiarch directory before
89/// `/usr/include` because that is where Debian and its derivatives put the headers that
90/// differ between two architectures of the same machine, and a distribution that does not use
91/// multiarch simply does not have the directory.
92fn linux(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
93 let libc = match target.env {
94 Env::Musl => "musl",
95 // Not `Env::as_str`, which answers `none` for a target written without an environment.
96 // A bare `x86_64-linux` on a Linux box means the machine's own libc, and on every
97 // machine that lays its headers out per architecture that libc is glibc.
98 Env::None | Env::Gnu | Env::Msvc => "gnu",
99 };
100 let multiarch = format!("{}-linux-{libc}", target.arch.as_str());
101 ["/usr/local/include".into(), format!("/usr/include/{multiarch}"), "/usr/include".into()]
102 .into_iter()
103 .map(|dir| under(sysroot, &dir))
104 .collect()
105}
106
107/// The SDK, which on an Apple platform is the whole of it.
108///
109/// There is no `/usr/include` on a Mac since the command line tools stopped installing one,
110/// and the headers live inside the SDK that Xcode or the command line tools brought with
111/// them. Nothing is offered when there is no SDK, because a guess at a path that is not there
112/// only makes the diagnostic longer, and the diagnostic is `rucc_sysroot::Wall::no_headers`,
113/// which the driver leaves on the search path: an Apple target with no SDK anywhere is Apple's
114/// licence wall rather than a missing directory, and the include that failed is where it is said.
115fn darwin(sdk: Option<&Path>) -> Vec<PathBuf> {
116 sdk.map(|sdk| vec![sdk.join("usr/include")]).unwrap_or_default()
117}
118
119/// A tree somebody named, or whatever `INCLUDE` says, in the order it says it.
120///
121/// Windows has no fixed place for the headers. The MSVC ones move with the toolchain version
122/// and the SDK ones move with the SDK version, and the way both are found is the environment
123/// that `vcvarsall.bat` sets, which is what every compiler on that platform reads and what
124/// every build there already has. So `INCLUDE` is a list of directories rather than a root,
125/// and it is taken as it stands.
126///
127/// A named tree is the other way in, and it is the one a cross compile uses, because nothing on
128/// a Linux box ran `vcvarsall.bat`. The layout is the one `xwin` writes and `cargo-xwin` builds
129/// against, which is the only relocatable shape an MSVC tree has: the CRT's headers under
130/// `crt/include` and the Windows SDK's under `sdk/include`, lowercase, with the version
131/// directories already resolved away. A copied Visual Studio installation is reached by setting
132/// `INCLUDE` instead, which is that platform's own spelling for it.
133fn windows(sysroot: Option<&Path>, include: Option<&str>) -> Vec<PathBuf> {
134 if let Some(root) = sysroot {
135 return ["crt/include", "sdk/include/ucrt", "sdk/include/shared", "sdk/include/um"]
136 .into_iter()
137 .chain(["sdk/include/winrt", "sdk/include/cppwinrt"])
138 .map(|dir| root.join(dir))
139 .collect();
140 }
141 include
142 .unwrap_or_default()
143 .split(';')
144 .map(str::trim)
145 .filter(|dir| !dir.is_empty())
146 .map(PathBuf::from)
147 .collect()
148}
149
150/// The header directories of a Visual Studio installation, in the order `vcvarsall.bat` puts them
151/// in `INCLUDE`.
152///
153/// `vc` is the versioned directory under `VC/Tools/MSVC` and `kit` is the versioned directory under
154/// the Windows Kit's `Include`, because the two halves are versioned separately and installed by
155/// different things: one comes with the compiler and holds the CRT, and the other is the platform
156/// and holds `windows.h` and the universal CRT. A machine can have several of each.
157///
158/// The five kit directories rather than the one, because they are five search roots and not a
159/// hierarchy. `ucrt` is the C library, `um` is the Win32 API, `shared` is what those two have in
160/// common, and the last two are for a language this compiler does not compile, so they are here for
161/// the same reason `vcvarsall.bat` puts them there: a header in one of them includes one of the
162/// others by its bare name.
163fn msvc_dirs(vc: &Path, kit: &Path) -> Vec<PathBuf> {
164 let mut dirs = vec![vc.join("include")];
165 for dir in ["ucrt", "shared", "um", "winrt", "cppwinrt"] {
166 dirs.push(kit.join(dir));
167 }
168 dirs
169}
170
171/// A version directory's name as numbers, for comparing two of them.
172///
173/// Text comparison is wrong here and quietly so. `10.0.9.0` sorts after `10.0.22621.0` as text and
174/// before it as a version, and the Windows Kit's directories are exactly that shape, so a compiler
175/// that picked the larger string would compile against an SDK from several years before the one the
176/// machine has. [`None`] for a name that is not a version at all, which is how a `Catalogs` or a
177/// `Source` directory beside the versioned ones is passed over.
178fn version_key(name: &str) -> Option<Vec<u64>> {
179 let parts: Vec<u64> = name.split('.').map(|part| part.parse().ok()).collect::<Option<_>>()?;
180 (!parts.is_empty()).then_some(parts)
181}
182
183/// The newest version directory under `dir`, which is the one to compile against.
184///
185/// The newest rather than a configured one, because there is nothing to configure it with and a
186/// person who installed a second SDK installed a newer one. A named `--sysroot` is how somebody
187/// says which tree they meant, and `INCLUDE` is how they say it in that platform's own words.
188fn newest(dir: &Path) -> Option<PathBuf> {
189 let mut best: Option<(Vec<u64>, PathBuf)> = None;
190 for entry in std::fs::read_dir(dir).ok()?.flatten() {
191 let name = entry.file_name();
192 let Some(key) = name.to_str().and_then(version_key) else { continue };
193 if !entry.path().is_dir() {
194 continue;
195 }
196 if best.as_ref().is_none_or(|(found, _)| key > *found) {
197 best = Some((key, entry.path()));
198 }
199 }
200 best.map(|(_, path)| path)
201}
202
203/// What this machine's own Visual Studio installation says, as an `INCLUDE` would say it.
204///
205/// Asked at most once per process, for the reason [`xcrun`] is: it costs two subprocesses and the
206/// answer does not change inside one compile. Joined with `;` rather than kept as a list so that
207/// there is one parser for both ways in, which is lossless because `;` is a path separator on that
208/// platform and a legal character in a file name nowhere.
209///
210/// This is the Windows half of what `xcrun` is on a mac, and it exists for the same reason: the
211/// headers of a platform whose SDK is not ours to ship are on the machine or they are nowhere, and
212/// the only way to be told where is to ask the thing that installed them. `vswhere.exe` is at a
213/// fixed path on every machine with Visual Studio 2017 or later, which is what makes it askable at
214/// all, and the kit is in the registry because that is where its installer puts it.
215fn installed_msvc() -> Option<String> {
216 static ANSWER: OnceLock<Option<String>> = OnceLock::new();
217 ANSWER
218 .get_or_init(|| {
219 let vc = newest(&visual_studio()?.join("VC").join("Tools").join("MSVC"))?;
220 let kit = newest(&windows_kit()?.join("Include"))?;
221 let dirs: Vec<String> =
222 msvc_dirs(&vc, &kit).iter().map(|dir| dir.display().to_string()).collect();
223 Some(dirs.join(";"))
224 })
225 .clone()
226}
227
228/// Where Visual Studio is, according to the installer that put it there.
229///
230/// `-products *` because the C++ build tools are a product of their own and a machine with those and
231/// no Visual Studio is the ordinary shape of a build server. `-latest` because the alternative is to
232/// read a list and pick, which is [`newest`]'s job one level down.
233fn visual_studio() -> Option<PathBuf> {
234 let program_files = std::env::var_os("ProgramFiles(x86)")?;
235 let vswhere = PathBuf::from(program_files)
236 .join("Microsoft Visual Studio")
237 .join("Installer")
238 .join("vswhere.exe");
239 if !vswhere.is_file() {
240 return None;
241 }
242 let out = Command::new(vswhere)
243 .args(["-latest", "-products", "*", "-property", "installationPath"])
244 .output()
245 .ok()?;
246 if !out.status.success() {
247 return None;
248 }
249 let path = PathBuf::from(String::from_utf8(out.stdout).ok()?.lines().next()?.trim());
250 path.is_dir().then_some(path)
251}
252
253/// Where the Windows Kit is, which is the Windows SDK and the universal CRT.
254///
255/// The registry first and the default location second, rather than the default location only,
256/// because the installer lets somebody move it and writes down where it went. `reg.exe` is how a
257/// program with no dependencies reads a key, and the value is the rest of the line after the type
258/// because a path there has spaces in it and `Program Files (x86)` has two.
259fn windows_kit() -> Option<PathBuf> {
260 const KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows Kits\Installed Roots";
261 if let Ok(out) = Command::new("reg.exe").args(["query", KEY, "/v", "KitsRoot10"]).output() {
262 if let Ok(text) = String::from_utf8(out.stdout) {
263 for line in text.lines() {
264 let Some((name, value)) = line.trim().split_once("REG_SZ") else { continue };
265 if name.trim() != "KitsRoot10" {
266 continue;
267 }
268 let root = PathBuf::from(value.trim());
269 if root.is_dir() {
270 return Some(root);
271 }
272 }
273 }
274 }
275 let default = PathBuf::from(std::env::var_os("ProgramFiles(x86)")?).join("Windows Kits/10");
276 default.is_dir().then_some(default)
277}
278
279/// A path under the sysroot, when there is one.
280fn under(sysroot: Option<&Path>, dir: &str) -> PathBuf {
281 match sysroot {
282 // `strip_prefix` because joining an absolute path replaces the root rather than
283 // extending it, which would make every entry the unprefixed one.
284 Some(root) => root.join(dir.strip_prefix('/').unwrap_or(dir)),
285 None => PathBuf::from(dir),
286 }
287}
288
289/// The directories the library's headers are actually in, in search order.
290///
291/// This is the one function here that talks to the machine: it reads the environment, asks
292/// `xcrun` where the SDK is when it has to, and keeps the candidates that exist.
293#[must_use]
294pub fn system_dirs(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
295 let machine = Machine {
296 host: Triple::host(),
297 sysroot: sysroot.map(Path::to_path_buf),
298 // Asked for only on the platforms that have one, since finding either can mean running a
299 // program and a compile for Linux should not wait on Xcode or on the Visual Studio
300 // installer. The MSVC environment and not every Windows target, because a mingw-w64 target's
301 // headers are ours and are in the cache, and handing it Microsoft's would be giving a
302 // program the declarations of a C library it is not being linked against.
303 sdk: if target.os == Os::Darwin { sdk(sysroot) } else { None },
304 include: if target.os == Os::Windows && target.env == Env::Msvc {
305 msvc(sysroot)
306 } else {
307 None
308 },
309 };
310 candidates(target, &machine).into_iter().filter(|dir| dir.is_dir()).collect()
311}
312
313/// The system header directories for this compile, which is step 3 of section 8.5.
314///
315/// Design: `spec/cross-compile/08-sysroots.md` section 8.5.
316///
317/// Three sources and the first that has anything wins: a tree the user named with `--sysroot` or
318/// `-isysroot`, then the sysroot for this target, then this machine's own directories and only when
319/// the target is this machine. `bundled` is [`crate::link::cross_sysroot`], which is the one place
320/// the two kinds of compile are told apart, so the headers a file is compiled against and the
321/// libraries it is linked against cannot disagree about which kind it is.
322///
323/// The ordering between the three is not decided here. It is `rucc_sysroot::search::include_paths`,
324/// which is section 8.5 as a function, and the condition that a host directory is legal only when
325/// the target is the host lives there and nowhere else. What this adds is the part that has to talk
326/// to the machine, which is [`system_dirs`] above.
327///
328/// Steps 1 and 2 are the driver's own. `-I` and its relatives are in [`rucc_session`]'s search path
329/// already, in the order the command line gave them, and the compiler's own headers are not a
330/// directory at all but the `<builtin>` entry the caller pushes before this.
331///
332/// A sysroot that is not on the disk yet is still named. The list is not filtered for existence the
333/// way [`system_dirs`] filters the machine's, because the answer to `rucc --target=... -v` on a
334/// machine where the tree has not been built should be the path it would be at rather than silence.
335///
336/// `kernel` is [`crate::link::cross_kernel`], and on a Linux target it adds two more directories
337/// after the libc's. They are the kernel's `asm/` for the architecture and its shared `linux/` and
338/// `asm-generic/`, they are not under any sysroot because every target sharing an architecture reads
339/// the same files, and they come last for the reason section 8.5 gives: both trees have a `sys/` and
340/// the libc's is the one a program means.
341#[must_use]
342pub fn header_dirs(
343 target: Triple,
344 sysroot: Option<&Path>,
345 bundled: Option<&Sysroot>,
346 kernel: Option<&Kernel>,
347) -> Vec<PathBuf> {
348 // Once, because asking can mean running `xcrun` or the Visual Studio installer. The answer goes
349 // to whichever of the three fields it belongs in, and which one that is decides how step 3 treats
350 // it rather than being a detail of how it was found. With a `--sysroot` these are the directories
351 // under the tree the user named. Without one, on a target behind a licence wall, they are an SDK
352 // this machine has, which is the target's own headers for every architecture of that platform and
353 // not this machine's library, so one Xcode serves `x86_64-macos` on an arm64 mac and one Windows
354 // Kit serves `aarch64-windows-msvc` on an x86_64 box, which is how the platform's own tools use
355 // them. Otherwise they are the machine's own directories and step 3 will only take them when the
356 // target is the host.
357 let dirs = system_dirs(target, sysroot);
358 // `Wall` rather than a second list of the two operating systems, because the targets whose
359 // headers are found as an SDK are exactly the targets whose headers are not ours to ship, and a
360 // copy of that rule here is a copy that can disagree with the one the diagnostic reads.
361 let walled = Wall::of(target.tuple()).is_some();
362 let (named, sdk, host) = match (sysroot.is_some(), walled) {
363 (true, _) => (dirs, Vec::new(), Vec::new()),
364 (false, true) => (Vec::new(), dirs, Vec::new()),
365 (false, false) => (Vec::new(), Vec::new(), dirs),
366 };
367 let options = Options {
368 sysroot: &named,
369 sdk: &sdk,
370 bundled,
371 kernel,
372 host_include: &host,
373 ..Options::default()
374 };
375 include_paths(target.tuple(), Triple::host().map(Triple::tuple), &options)
376 .into_iter()
377 .map(|entry| entry.path)
378 .collect()
379}
380
381/// The SDK to compile against, in the order the platform's own tools look.
382///
383/// `-isysroot` beats `SDKROOT` beats `xcrun` beats the place the command line tools put it.
384/// `xcrun` is a program rather than a path because the answer moves with the Xcode that is
385/// selected and asking is the only way to be told which one that is, and it is third rather
386/// than first because it costs a process and the two before it are free.
387fn sdk(sysroot: Option<&Path>) -> Option<PathBuf> {
388 if let Some(root) = sysroot {
389 return Some(root.to_path_buf());
390 }
391 if let Some(root) = std::env::var_os("SDKROOT") {
392 let root = PathBuf::from(root);
393 if root.is_dir() {
394 return Some(root);
395 }
396 }
397 if let Some(root) = xcrun() {
398 return Some(root);
399 }
400 let tools = PathBuf::from("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk");
401 tools.is_dir().then_some(tools)
402}
403
404/// The Windows SDK to compile against, in the order somebody would expect to be obeyed.
405///
406/// A tree somebody named beats `INCLUDE` beats the installation this machine has, which is the order
407/// [`sdk`] uses on the Apple side and for the same reasons: the cheap answers are the ones somebody
408/// gave us, and the one that costs a process is last. A named tree answers nothing here because it is
409/// not a list of directories, and [`windows`] is handed the root itself.
410fn msvc(sysroot: Option<&Path>) -> Option<String> {
411 if sysroot.is_some() {
412 return None;
413 }
414 match std::env::var("INCLUDE") {
415 Ok(include) if !include.trim().is_empty() => Some(include),
416 _ => installed_msvc(),
417 }
418}
419
420/// What `xcrun` said, asked at most once in a process.
421///
422/// A compiler that ran it for the header search and again for the diagnostic that explains an empty
423/// one would pay for a process twice to be told the same path. The answer cannot change underneath us
424/// in a way that matters either: a run of the compiler compiles against one SDK.
425fn xcrun() -> Option<PathBuf> {
426 static ANSWER: OnceLock<Option<PathBuf>> = OnceLock::new();
427 ANSWER.get_or_init(ask_xcrun).clone()
428}
429
430/// Asks `xcrun` for the SDK path, and says nothing if it is not there to ask.
431fn ask_xcrun() -> Option<PathBuf> {
432 let out = Command::new("/usr/bin/xcrun").args(["--show-sdk-path"]).output().ok()?;
433 if !out.status.success() {
434 return None;
435 }
436 let path = PathBuf::from(String::from_utf8(out.stdout).ok()?.trim());
437 (path.is_absolute() && path.is_dir()).then_some(path)
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443 use rucc_target::Arch;
444
445 fn triple(os: Os, env: Env) -> Triple {
446 Triple::new(Arch::X86_64, os, env)
447 }
448
449 fn on(host: Os) -> Machine {
450 Machine { host: Some(triple(host, Env::Gnu)), ..Machine::default() }
451 }
452
453 #[test]
454 fn the_local_directory_comes_before_the_distributions_and_the_specific_before_the_general() {
455 let dirs = candidates(triple(Os::Linux, Env::Gnu), &on(Os::Linux));
456 let dirs: Vec<String> = dirs.iter().map(|d| d.display().to_string()).collect();
457 assert_eq!(dirs, ["/usr/local/include", "/usr/include/x86_64-linux-gnu", "/usr/include"]);
458 }
459
460 #[test]
461 fn the_directory_headers_are_kept_apart_in_is_named_after_the_targets_own_library() {
462 let of = |env| candidates(triple(Os::Linux, env), &on(Os::Linux))[1].display().to_string();
463 assert_eq!(of(Env::Musl), "/usr/include/x86_64-linux-musl");
464 assert_eq!(of(Env::Gnu), "/usr/include/x86_64-linux-gnu");
465 // A triple written without an environment is the machine's own, and a machine that
466 // sorts its headers by architecture at all is one running glibc.
467 assert_eq!(of(Env::None), "/usr/include/x86_64-linux-gnu");
468 }
469
470 #[test]
471 fn a_sysroot_is_in_front_of_every_one_of_them_rather_than_replacing_the_root() {
472 let machine = Machine { sysroot: Some("/opt/cross".into()), ..on(Os::Linux) };
473 let dirs = candidates(triple(Os::Linux, Env::Gnu), &machine);
474 // Joined rather than spelled out, because a path prints with the separator the host
475 // uses and this test runs on a host where that is a backslash.
476 let under = |dir| PathBuf::from("/opt/cross").join(dir);
477 assert_eq!(
478 dirs,
479 [
480 under("usr/local/include"),
481 under("usr/include/x86_64-linux-gnu"),
482 under("usr/include")
483 ]
484 );
485 }
486
487 #[test]
488 fn this_machines_headers_are_not_offered_to_a_program_being_built_for_another_system() {
489 assert!(candidates(triple(Os::Windows, Env::Msvc), &on(Os::Linux)).is_empty());
490 assert!(candidates(triple(Os::Linux, Env::Gnu), &on(Os::Darwin)).is_empty());
491 // With a sysroot they are, because that is what naming one says.
492 let machine = Machine { sysroot: Some("/opt/cross".into()), ..on(Os::Darwin) };
493 assert!(!candidates(triple(Os::Linux, Env::Gnu), &machine).is_empty());
494 }
495
496 #[test]
497 fn an_unknown_host_offers_the_targets_own_directories_rather_than_none() {
498 // `Triple::host` answers nothing on a machine this compiler has no target for, and a
499 // native compile there is still a native compile.
500 let machine = Machine { host: None, ..Machine::default() };
501 assert_eq!(candidates(triple(Os::Linux, Env::Gnu), &machine).len(), 3);
502 }
503
504 #[test]
505 fn an_apple_target_is_the_sdk_and_nothing_else_and_nothing_without_one() {
506 let machine = Machine { sdk: Some("/S.sdk".into()), ..on(Os::Darwin) };
507 let dirs = candidates(triple(Os::Darwin, Env::None), &machine);
508 assert_eq!(dirs, [PathBuf::from("/S.sdk/usr/include")]);
509 assert!(candidates(triple(Os::Darwin, Env::None), &on(Os::Darwin)).is_empty());
510 }
511
512 #[test]
513 fn an_sdk_reaches_an_apple_target_from_a_host_that_is_not_a_mac() {
514 // A Linux box with `SDKROOT` pointing at an SDK somebody downloaded under their own licence,
515 // which is the path section 8.6 leaves open on every host that is not a mac. It is the same
516 // exception a `--sysroot` gets and for the same reason: somebody said where the headers are.
517 let machine = Machine { sdk: Some("/S.sdk".into()), ..on(Os::Linux) };
518 let dirs = candidates(triple(Os::Darwin, Env::None), &machine);
519 assert_eq!(dirs, [PathBuf::from("/S.sdk/usr/include")]);
520 // And with no SDK there is nothing, which is what the licence wall's message is about.
521 assert!(candidates(triple(Os::Darwin, Env::None), &on(Os::Linux)).is_empty());
522 }
523
524 #[test]
525 fn windows_is_told_where_its_headers_are_and_is_not_guessed_at() {
526 let machine =
527 Machine { include: Some(r"C:\vc\include;C:\sdk\ucrt ;".to_owned()), ..on(Os::Windows) };
528 let dirs = candidates(triple(Os::Windows, Env::Msvc), &machine);
529 assert_eq!(dirs, [PathBuf::from(r"C:\vc\include"), PathBuf::from(r"C:\sdk\ucrt")]);
530 assert!(candidates(triple(Os::Windows, Env::Msvc), &on(Os::Windows)).is_empty());
531 }
532
533 #[test]
534 fn an_sdk_reaches_an_msvc_target_from_a_host_that_is_not_windows() {
535 // The same exception the Apple side gets, and the case it is for is a Linux build machine
536 // with a tree `xwin` assembled on it under a licence its owner accepted.
537 let machine = Machine { include: Some(r"C:\sdk\um".to_owned()), ..on(Os::Linux) };
538 let dirs = candidates(triple(Os::Windows, Env::Msvc), &machine);
539 assert_eq!(dirs, [PathBuf::from(r"C:\sdk\um")]);
540 }
541
542 #[test]
543 fn a_named_tree_for_an_msvc_target_is_the_layout_a_relocatable_one_has() {
544 let machine = Machine { sysroot: Some("/opt/xwin".into()), ..on(Os::Linux) };
545 let dirs = candidates(triple(Os::Windows, Env::Msvc), &machine);
546 let under = |dir| PathBuf::from("/opt/xwin").join(dir);
547 assert_eq!(
548 dirs,
549 [
550 under("crt/include"),
551 under("sdk/include/ucrt"),
552 under("sdk/include/shared"),
553 under("sdk/include/um"),
554 under("sdk/include/winrt"),
555 under("sdk/include/cppwinrt"),
556 ]
557 );
558 }
559
560 #[test]
561 fn the_mingw_target_is_not_offered_microsofts_headers() {
562 // Its headers are ours, they are in the cache, and Microsoft's are the declarations of a
563 // library it is not linked against. `system_dirs` is what decides this, by asking for an
564 // `INCLUDE` only in the MSVC environment, so a `Machine` with one set is the test.
565 let machine = Machine { include: Some(r"C:\sdk\um".to_owned()), ..on(Os::Windows) };
566 assert!(system_dirs(triple(Os::Windows, Env::Gnu), None).is_empty());
567 // And the field itself is still obeyed when it is set, which is what keeps this test honest
568 // about where the decision is rather than asserting it twice.
569 assert!(!candidates(triple(Os::Windows, Env::Gnu), &machine).is_empty());
570 }
571
572 #[test]
573 fn the_headers_of_an_installation_are_in_the_order_the_developer_prompt_puts_them() {
574 // Joined rather than spelled out, because this test runs on hosts whose separator is not
575 // the one a path like this is written with.
576 let vc = PathBuf::from(r"C:\BuildTools\VC\Tools\MSVC\14.44.35207");
577 let dirs = msvc_dirs(&vc, Path::new("/k"));
578 assert_eq!(dirs[0], vc.join("include"));
579 let rest: Vec<String> =
580 dirs[1..].iter().map(|dir| dir.file_name().unwrap().to_string_lossy().into()).collect();
581 assert_eq!(rest, ["ucrt", "shared", "um", "winrt", "cppwinrt"]);
582 }
583
584 #[test]
585 fn a_version_directory_is_compared_as_numbers_and_not_as_text() {
586 // The case that makes this matter. As text the first of these is the larger.
587 assert!(version_key("10.0.9.0") < version_key("10.0.22621.0"));
588 assert!(version_key("10.0.22621.0") < version_key("10.0.26100.0"));
589 assert!(version_key("14.44.35207") > version_key("14.39.33519"));
590 // And the directories that sit beside the versioned ones in a Windows Kit.
591 assert_eq!(version_key("Catalogs"), None);
592 assert_eq!(version_key("wdf"), None);
593 assert_eq!(version_key(""), None);
594 }
595
596 #[test]
597 fn a_freestanding_target_has_no_library_to_find_the_headers_of() {
598 let machine = Machine { sysroot: Some("/opt/cross".into()), ..Machine::default() };
599 assert!(candidates(triple(Os::None, Env::None), &machine).is_empty());
600 }
601
602 #[test]
603 fn what_is_offered_on_this_machine_is_there_because_it_was_checked_for() {
604 for dir in system_dirs(Triple::host().unwrap_or(triple(Os::Linux, Env::Gnu)), None) {
605 assert!(dir.is_dir(), "{}", dir.display());
606 }
607 }
608}