Debian Codegraph @

debian/rust-vendor/cc/src/target/parser.rs

raw
1 use std::mem;
2
3 use crate::{
4 target::TargetInfo,
5 utilities::{cargo_env_var, OnceLock},
6 Error, ErrorKind,
7 };
8
9 #[derive(Debug)]
10 struct TargetInfoParserInner {
11 full_arch: Box<str>,
12 arch: Box<str>,
13 vendor: Box<str>,
14 os: Box<str>,
15 env: Box<str>,
16 abi: Box<str>,
17 }
18
19 impl TargetInfoParserInner {
20 fn from_cargo_environment_variables() -> Result<Self, Error> {
21 // `TARGET` must be present.
22 let target_name = cargo_env_var("TARGET")?;
23
24 // Parse the full architecture name from the target name.
25 let (full_arch, _rest) = target_name.split_once('-').ok_or(Error::new(
26 ErrorKind::InvalidTarget,
27 format!("target `{target_name}` only had a single component (at least two required)"),
28 ))?;
29
30 let cargo_env = |key, fallback: Option<&str>| match cargo_env_var(key) {
31 Ok(var) => Ok(var.into_boxed_str()),
32 Err(err) => match fallback {
33 Some(fallback) => Ok(fallback.into()),
34 None => Err(Error::new(
35 ErrorKind::EnvVarNotFound,
36 format!(
37 "did not find fallback information for target `{target_name}`: {}",
38 err.message
39 ),
40 )),
41 },
42 };
43
44 // Prefer to use `CARGO_ENV_*` if set, since these contain the most
45 // correct information relative to the current `rustc`, and makes it
46 // possible to support custom target JSON specs unknown to `rustc`.
47 //
48 // NOTE: If the user is using an older `rustc`, that data may be older
49 // than our pre-generated data, but we still prefer Cargo's view of
50 // the world, since at least `cc` won't differ from `rustc` in that
51 // case.
52 //
53 // These may not be set in case the user depended on being able to
54 // just set `TARGET` outside of build scripts; in those cases, fall
55 // back back to data from the known set of target names instead.
56 //
57 // See discussion in #1225 for further details.
58 let fallback_target = TargetInfo::from_rustc_target(&target_name).ok();
59 let ft = fallback_target.as_ref();
60 let arch = cargo_env("CARGO_CFG_TARGET_ARCH", ft.map(|t| t.arch))?;
61 let vendor = cargo_env("CARGO_CFG_TARGET_VENDOR", ft.map(|t| t.vendor))?;
62 let os = cargo_env("CARGO_CFG_TARGET_OS", ft.map(|t| t.os))?;
63 let mut env = cargo_env("CARGO_CFG_TARGET_ENV", ft.map(|t| t.env))?;
64 // `target_abi` was stabilized in Rust 1.78, which is higher than our
65 // MSRV, so it may not always be available; In that case, fall back to
66 // `""`, which is _probably_ correct for unknown target names.
67 let mut abi = cargo_env("CARGO_CFG_TARGET_ABI", ft.map(|t| t.abi))
68 .unwrap_or_else(|_| String::default().into_boxed_str());
69
70 // Remove `macabi` and `sim` from `target_abi` (if present), it's been moved to `target_env`.
71 // TODO: Remove once MSRV is bumped to 1.91 and `rustc` removes these from `target_abi`.
72 if matches!(&*abi, "macabi" | "sim") {
73 debug_assert!(
74 matches!(&*env, "" | "macabi" | "sim"),
75 "env/abi mismatch: {:?}, {:?}",
76 env,
77 abi,
78 );
79 env = mem::replace(&mut abi, String::default().into_boxed_str());
80 }
81
82 Ok(Self {
83 full_arch: full_arch.to_string().into_boxed_str(),
84 arch,
85 vendor,
86 os,
87 env,
88 abi,
89 })
90 }
91 }
92
93 /// Parser for [`TargetInfo`], contains cached information.
94 #[derive(Default, Debug)]
95 pub(crate) struct TargetInfoParser(OnceLock<Result<TargetInfoParserInner, Error>>);
96
97 impl TargetInfoParser {
98 pub fn parse_from_cargo_environment_variables(&self) -> Result<TargetInfo<'_>, Error> {
99 match self
100 .0
101 .get_or_init(TargetInfoParserInner::from_cargo_environment_variables)
102 {
103 Ok(TargetInfoParserInner {
104 full_arch,
105 arch,
106 vendor,
107 os,
108 env,
109 abi,
110 }) => Ok(TargetInfo {
111 full_arch,
112 arch,
113 vendor,
114 os,
115 env,
116 abi,
117 }),
118 Err(e) => Err(e.clone()),
119 }
120 }
121 }
122
123 /// Parse the full architecture in the target name into the simpler
124 /// `cfg(target_arch = "...")` that `rustc` exposes.
125 fn parse_arch(full_arch: &str) -> Option<&str> {
126 // NOTE: Some of these don't necessarily match an existing target in
127 // `rustc`. They're parsed anyhow to be as forward-compatible as possible,
128 // while still being correct.
129 //
130 // See also:
131 // https://docs.rs/cfg-expr/0.18.0/cfg_expr/targets/index.html
132 // https://docs.rs/target-lexicon/0.13.2/target_lexicon/enum.Architecture.html
133 // https://gcc.gnu.org/onlinedocs/gcc/Submodel-Options.html
134 // `clang -print-targets`
135 Some(match full_arch {
136 arch if arch.starts_with("mipsisa32r6") => "mips32r6", // mipsisa32r6 | mipsisa32r6el
137 arch if arch.starts_with("mipsisa64r6") => "mips64r6", // mipsisa64r6 | mipsisa64r6el
138
139 arch if arch.starts_with("mips64") => "mips64", // mips64 | mips64el
140 arch if arch.starts_with("mips") => "mips", // mips | mipsel
141
142 arch if arch.starts_with("loongarch64") => "loongarch64",
143 arch if arch.starts_with("loongarch32") => "loongarch32",
144
145 arch if arch.starts_with("powerpc64") => "powerpc64", // powerpc64 | powerpc64le
146 arch if arch.starts_with("powerpc") => "powerpc",
147 arch if arch.starts_with("ppc64") => "powerpc64",
148 arch if arch.starts_with("ppc") => "powerpc",
149
150 arch if arch.starts_with("x86_64") => "x86_64", // x86_64 | x86_64h
151 arch if arch.starts_with("i") && arch.ends_with("86") => "x86", // i386 | i586 | i686
152
153 "arm64ec" => "arm64ec", // https://github.com/rust-lang/rust/issues/131172
154 arch if arch.starts_with("aarch64") => "aarch64", // arm64e | arm64_32
155 arch if arch.starts_with("arm64") => "aarch64", // aarch64 | aarch64_be
156
157 arch if arch.starts_with("arm") => "arm", // arm | armv7s | armeb | ...
158 arch if arch.starts_with("thumb") => "arm", // thumbv4t | thumbv7a | thumbv8m | ...
159
160 arch if arch.starts_with("riscv64") => "riscv64",
161 arch if arch.starts_with("riscv32") => "riscv32",
162
163 arch if arch.starts_with("wasm64") => "wasm64",
164 arch if arch.starts_with("wasm32") => "wasm32", // wasm32 | wasm32v1
165 "asmjs" => "wasm32",
166
167 arch if arch.starts_with("nvptx64") => "nvptx64",
168 arch if arch.starts_with("nvptx") => "nvptx",
169
170 arch if arch.starts_with("bpf") => "bpf", // bpfeb | bpfel
171 arch if arch.starts_with("sh4") => "sh4", // sh4 | sh4-unknown-linux-gnu | sh4-unknown-redox
172
173 // https://github.com/bytecodealliance/wasmtime/tree/v30.0.1/pulley
174 arch if arch.starts_with("pulley64") => "pulley64",
175 arch if arch.starts_with("pulley32") => "pulley32",
176
177 // https://github.com/Clever-ISA/Clever-ISA
178 arch if arch.starts_with("clever") => "clever",
179
180 "sparc" | "sparcv7" | "sparcv8" => "sparc",
181 "sparc64" | "sparcv9" => "sparc64",
182
183 "amdgcn" => "amdgpu",
184 "avr" => "avr",
185 "csky" => "csky",
186 "hexagon" => "hexagon",
187 "m68k" => "m68k",
188 "msp430" => "msp430",
189 "r600" => "r600",
190 "s390x" => "s390x",
191 "xtensa" => "xtensa",
192
193 // Arches supported by gcc, but not LLVM.
194 arch if arch.starts_with("alpha") => "alpha", // DEC Alpha
195 "hppa" => "hppa", // https://en.wikipedia.org/wiki/PA-RISC, also known as HPPA
196 arch if arch.starts_with("sh") => "sh", // SuperH
197 _ => return None,
198 })
199 }
200
201 /// Parse environment and ABI from the last component of the target name.
202 fn parse_envabi(last_component: &str) -> Option<(&str, &str)> {
203 let (env, abi) = match last_component {
204 // Combined environment and ABI
205
206 // gnullvm | gnueabi | gnueabihf | gnuabiv2 | gnuabi64 | gnuspe | gnux32 | gnu_ilp32
207 env_and_abi if env_and_abi.starts_with("gnu") => {
208 let abi = env_and_abi.strip_prefix("gnu").unwrap();
209 let abi = abi.strip_prefix("_").unwrap_or(abi);
210 ("gnu", abi)
211 }
212 // musl | musleabi | musleabihf | muslabi64 | muslspe
213 env_and_abi if env_and_abi.starts_with("musl") => {
214 ("musl", env_and_abi.strip_prefix("musl").unwrap())
215 }
216 // uclibc | uclibceabi | uclibceabihf
217 env_and_abi if env_and_abi.starts_with("uclibc") => {
218 ("uclibc", env_and_abi.strip_prefix("uclibc").unwrap())
219 }
220 // newlib | newlibeabihf
221 env_and_abi if env_and_abi.starts_with("newlib") => {
222 ("newlib", env_and_abi.strip_prefix("newlib").unwrap())
223 }
224
225 // target that enables arm's pointer authentication
226 "pauthtest" => ("musl", "pauthtest"),
227
228 // Environments
229 "msvc" => ("msvc", ""),
230 "ohos" => ("ohos", ""),
231 "qnx700" => ("nto70", ""),
232 "qnx710_iosock" => ("nto71_iosock", ""),
233 "qnx710" => ("nto71", ""),
234 "sgx" => ("sgx", ""),
235 "threads" => ("threads", ""),
236 "mlibc" => ("mlibc", ""),
237 "relibc" => ("relibc", ""),
238
239 // ABIs
240 "abi64" => ("", "abi64"),
241 "abiv2" => ("", "spe"),
242 "eabi" => ("", "eabi"),
243 "eabihf" => ("", "eabihf"),
244 "macabi" => ("macabi", ""),
245 "sim" => ("sim", ""),
246 "softfloat" => ("", "softfloat"),
247 "spe" => ("", "spe"),
248 "x32" => ("", "x32"),
249
250 // Badly named targets, ELF is already known from target OS.
251 // Probably too late to fix now though.
252 "elf" => ("", ""),
253 // Undesirable to expose to user code (yet):
254 // https://github.com/rust-lang/rust/pull/131166#issuecomment-2389541917
255 "freestanding" => ("", ""),
256
257 _ => return None,
258 };
259 Some((env, abi))
260 }
261
262 impl<'a> TargetInfo<'a> {
263 pub(crate) fn from_rustc_target(target: &'a str) -> Result<Self, Error> {
264 // FIXME(madsmtm): This target should be renamed, cannot be parsed
265 // with the means we do below (since `none` must not be interpreted
266 // as an env/ABI).
267 if target == "x86_64-unknown-linux-none" {
268 return Ok(Self {
269 full_arch: "x86_64",
270 arch: "x86_64",
271 vendor: "unknown",
272 os: "linux",
273 env: "",
274 abi: "",
275 });
276 }
277
278 let mut components = target.split('-');
279
280 // Insist that the target name contains at least a valid architecture.
281 let full_arch = components.next().ok_or(Error::new(
282 ErrorKind::InvalidTarget,
283 "target was empty".to_string(),
284 ))?;
285
286 if target == "armv7a-vex-v5" || target == "thumbv7a-vex-v5" {
287 return Ok(Self {
288 full_arch,
289 arch: "arm",
290 vendor: "vex",
291 os: "vexos",
292 env: "v5",
293 abi: "eabihf",
294 });
295 }
296
297 let arch = parse_arch(full_arch).ok_or_else(|| {
298 Error::new(
299 ErrorKind::UnknownTarget,
300 format!("target `{target}` had an unknown architecture"),
301 )
302 })?;
303
304 // Newer target names have begun omitting the vendor, so the only
305 // component we know must be there is the OS name.
306 let components: Vec<_> = components.collect();
307 let (vendor, os, mut env, mut abi) = match &*components {
308 [] => {
309 return Err(Error::new(
310 ErrorKind::InvalidTarget,
311 format!("target `{target}` must have at least two components"),
312 ))
313 }
314 // Two components; format is `arch-os`.
315 [os] => ("unknown", *os, "", ""),
316 // The three-component case is a bit tricky to handle, it could
317 // either have the format `arch-vendor-os` or `arch-os-env+abi`.
318 [vendor_or_os, os_or_envabi] => {
319 // We differentiate between these by checking if the last
320 // component is an env/ABI; if it isn't, then it's probably
321 // an OS instead.
322 if let Some((env, abi)) = parse_envabi(os_or_envabi) {
323 ("unknown", *vendor_or_os, env, abi)
324 } else {
325 (*vendor_or_os, *os_or_envabi, "", "")
326 }
327 }
328 // Four components; format is `arch-vendor-os-env+abi`.
329 [vendor, os, envabi] => {
330 let (env, abi) = parse_envabi(envabi).ok_or_else(|| {
331 Error::new(
332 ErrorKind::UnknownTarget,
333 format!("unknown environment/ABI `{envabi}` in target `{target}`"),
334 )
335 })?;
336 (*vendor, *os, env, abi)
337 }
338 _ => {
339 return Err(Error::new(
340 ErrorKind::InvalidTarget,
341 format!("too many components in target `{target}`"),
342 ))
343 }
344 };
345
346 // Part of the architecture name is carried over into the ABI.
347 match full_arch {
348 // https://github.com/rust-lang/compiler-team/issues/830
349 arch if arch.starts_with("riscv32e") => {
350 abi = "ilp32e";
351 }
352 _ => {}
353 }
354
355 // Various environment/ABIs are determined based on OS name.
356 match os {
357 "3ds" | "rtems" | "espidf" => env = "newlib",
358 "vxworks" => env = "gnu",
359 "redox" => env = "relibc",
360 "aix" => abi = "vec-extabi",
361 _ => {}
362 }
363
364 // Extra overrides for badly named targets.
365 match target {
366 // Actually simulator targets.
367 "i386-apple-ios" | "x86_64-apple-ios" | "x86_64-apple-tvos" => {
368 env = "sim";
369 }
370 // Name should've contained `muslabi64`.
371 "mips64-openwrt-linux-musl" => {
372 abi = "abi64";
373 }
374 // Specifies abi even though not in name.
375 "armv6-unknown-freebsd" | "armv6k-nintendo-3ds" | "armv7-unknown-freebsd" => {
376 abi = "eabihf";
377 }
378 // Specifies abi even though not in name.
379 "armv7-unknown-linux-ohos" | "armv7-unknown-trusty" => {
380 abi = "eabi";
381 }
382 _ => {}
383 }
384
385 let os = match os {
386 // Horizon is the common/internal OS name for 3DS and the Switch.
387 "3ds" | "switch" => "horizon",
388 // FIXME(madsmtm): macOS targets are badly named.
389 "darwin" => "macos",
390
391 // WASI targets contain the preview version in them too. Should've
392 // been `wasi-p1`/`wasi-p2`, but that's probably too late now.
393 os if os.starts_with("wasi") => {
394 env = os.strip_prefix("wasi").unwrap();
395 "wasi"
396 }
397 // FIXME(madsmtm): Badly named targets `*-linux-androideabi`,
398 // should be `*-android-eabi`.
399 "androideabi" => {
400 abi = "eabi";
401 "android"
402 }
403
404 os => os,
405 };
406
407 let vendor = match vendor {
408 // esp, esp32, esp32s2 etc.
409 vendor if vendor.starts_with("esp") => "espressif",
410 // FIXME(madsmtm): Badly named targets `*-linux-android*`,
411 // "linux" makes no sense as the vendor name.
412 "linux" if os == "android" || os == "androideabi" => "unknown",
413 // FIXME(madsmtm): Fix in `rustc` after
414 // https://github.com/rust-lang/compiler-team/issues/850.
415 "wali" => "unknown",
416 "lynx" => "unknown",
417 "oe" => "unknown",
418 // Some Linux distributions set their name as the target vendor,
419 // so we have to assume that it can be an arbitary string.
420 vendor => vendor,
421 };
422
423 // Intentionally also marked as an ABI:
424 // https://github.com/rust-lang/rust/pull/86922
425 if vendor == "fortanix" {
426 abi = "fortanix";
427 }
428 if vendor == "uwp" {
429 abi = "uwp";
430 }
431 if ["powerpc64-unknown-linux-gnu", "powerpc64-wrs-vxworks"].contains(&target) {
432 abi = "elfv1";
433 }
434 if [
435 "powerpc64-unknown-freebsd",
436 "powerpc64-unknown-linux-musl",
437 "powerpc64-unknown-openbsd",
438 "powerpc64le-unknown-freebsd",
439 "powerpc64le-unknown-linux-gnu",
440 "powerpc64le-unknown-linux-musl",
441 ]
442 .contains(&target)
443 {
444 abi = "elfv2";
445 }
446
447 if ["asan", "msan", "tsan"].contains(&abi) {
448 abi = "";
449 }
450
451 Ok(Self {
452 full_arch,
453 arch,
454 vendor,
455 os,
456 env,
457 abi,
458 })
459 }
460 }
461
462 #[cfg(test)]
463 #[allow(unexpected_cfgs)]
464 #[allow(clippy::disallowed_methods)]
465 mod tests {
466 use std::process::Command;
467
468 use super::TargetInfo;
469 use crate::ErrorKind;
470
471 // Test tier 1 targets.
472 #[test]
473 fn tier1() {
474 let targets = [
475 "aarch64-unknown-linux-gnu",
476 "aarch64-apple-darwin",
477 "i686-pc-windows-gnu",
478 "i686-pc-windows-msvc",
479 "i686-unknown-linux-gnu",
480 "x86_64-apple-darwin",
481 "x86_64-pc-windows-gnu",
482 "x86_64-pc-windows-msvc",
483 "x86_64-unknown-linux-gnu",
484 ];
485
486 for target in targets {
487 // Check that they parse.
488 let _ = TargetInfo::from_rustc_target(target).unwrap();
489 }
490 }
491
492 // Various custom target names not (or no longer) known by `rustc`.
493 #[test]
494 fn parse_extra() {
495 let targets = [
496 "aarch64-unknown-none-gnu",
497 "aarch64-uwp-windows-gnu",
498 "arm-frc-linux-gnueabi",
499 "arm-unknown-netbsd-eabi",
500 "armv7neon-unknown-linux-gnueabihf",
501 "armv7neon-unknown-linux-musleabihf",
502 "thumbv7-unknown-linux-gnueabihf",
503 "thumbv7-unknown-linux-musleabihf",
504 "armv7-apple-ios",
505 "wasm32-wasi",
506 "x86_64-rumprun-netbsd",
507 "x86_64-unknown-linux",
508 "x86_64-alpine-linux-musl",
509 "x86_64-chimera-linux-musl",
510 "x86_64-foxkit-linux-musl",
511 "arm-poky-linux-gnueabi",
512 "x86_64-unknown-moturus",
513 "x86_64-unknown-managarm-mlibc",
514 ];
515
516 for target in targets {
517 // Check that they parse.
518 let _ = TargetInfo::from_rustc_target(target).unwrap();
519 }
520 }
521
522 fn target_from_rustc_cfgs<'a>(target: &'a str, cfgs: &'a str) -> TargetInfo<'a> {
523 // Cannot determine full architecture from cfgs.
524 let (full_arch, _rest) = target.split_once('-').expect("target to have arch");
525
526 let mut target = TargetInfo {
527 full_arch,
528 arch: "invalid-none-set",
529 vendor: "invalid-none-set",
530 os: "invalid-none-set",
531 env: "invalid-none-set",
532 // Not set in older Rust versions
533 abi: "",
534 };
535
536 for cfg in cfgs.lines() {
537 if let Some((name, value)) = cfg.split_once('=') {
538 // Remove whitespace, if `rustc` decided to insert any.
539 let name = name.trim();
540 let value = value.trim();
541
542 // Remove quotes around value.
543 let value = value.strip_prefix('"').unwrap_or(value);
544 let value = value.strip_suffix('"').unwrap_or(value);
545
546 match name {
547 "target_arch" => target.arch = value,
548 "target_vendor" => target.vendor = value,
549 "target_os" => target.os = value,
550 "target_env" => target.env = value,
551 "target_abi" => target.abi = value,
552 _ => {}
553 }
554 } else {
555 // Skip cfgs like `debug_assertions` and `unix`.
556 }
557 }
558
559 if matches!(target.abi, "macabi" | "sim") {
560 assert_eq!(target.env, target.abi);
561 target.abi = "";
562 }
563
564 target
565 }
566
567 #[test]
568 fn unknown_env_determined_as_unknown() {
569 let err = TargetInfo::from_rustc_target("aarch64-unknown-linux-bogus").unwrap_err();
570 assert!(matches!(err.kind, ErrorKind::UnknownTarget));
571 }
572
573 // Used in .github/workflows/test-rustc-targets.yml
574 #[test]
575 #[cfg_attr(
576 not(rustc_target_test),
577 ignore = "must enable explicitly with --cfg=rustc_target_test"
578 )]
579 fn parse_rustc_targets() {
580 #[allow(clippy::disallowed_methods)]
581 let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
582
583 let target_list = Command::new(&rustc)
584 .arg("--print=target-list")
585 .output()
586 .unwrap()
587 .stdout;
588 let target_list = String::from_utf8(target_list).unwrap();
589
590 let mut has_failure = false;
591 for target in target_list.lines() {
592 let cfgs = Command::new(&rustc)
593 .arg("--target")
594 .arg(target)
595 .arg("--print=cfg")
596 .output()
597 .unwrap()
598 .stdout;
599 let cfgs = String::from_utf8(cfgs).unwrap();
600
601 let expected = target_from_rustc_cfgs(target, &cfgs);
602 let actual = TargetInfo::from_rustc_target(target);
603
604 if Some(&expected) != actual.as_ref().ok() {
605 eprintln!("failed comparing {target}:");
606 eprintln!(" expected: Ok({expected:?})");
607 eprintln!(" actual: {actual:?}");
608 eprintln!();
609 has_failure = true;
610 }
611 }
612
613 if has_failure {
614 panic!("failed comparing targets");
615 }
616 }
617
618 #[test]
619 fn parses_apple_envs_correctly() {
620 assert_eq!(
621 TargetInfo::from_rustc_target("aarch64-apple-ios-macabi").unwrap(),
622 TargetInfo {
623 full_arch: "aarch64",
624 arch: "aarch64",
625 vendor: "apple",
626 os: "ios",
627 env: "macabi",
628 abi: "",
629 }
630 );
631 assert_eq!(
632 TargetInfo::from_rustc_target("aarch64-apple-ios-sim").unwrap(),
633 TargetInfo {
634 full_arch: "aarch64",
635 arch: "aarch64",
636 vendor: "apple",
637 os: "ios",
638 env: "sim",
639 abi: "",
640 }
641 );
642 }
643 }