1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
9 //! # Using custom targets
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
26 //! # Defining a new target
28 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
37 use crate::abi::Endian;
38 use crate::spec::abi::{lookup as lookup_abi, Abi};
39 use crate::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
40 use rustc_serialize::json::{Json, ToJson};
41 use rustc_span::symbol::{sym, Symbol};
42 use std::collections::BTreeMap;
43 use std::convert::TryFrom;
44 use std::ops::{Deref, DerefMut};
45 use std::path::{Path, PathBuf};
46 use std::str::FromStr;
49 use rustc_macros::HashStable_Generic;
64 mod hermit_kernel_base;
69 mod linux_kernel_base;
71 mod linux_uclibc_base;
83 mod windows_msvc_base;
84 mod windows_uwp_gnu_base;
85 mod windows_uwp_msvc_base;
87 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
88 pub enum LinkerFlavor {
97 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
106 fn from_str(s: &str) -> Option<Self> {
108 "darwin" => LldFlavor::Ld64,
109 "gnu" => LldFlavor::Ld,
110 "link" => LldFlavor::Link,
111 "wasm" => LldFlavor::Wasm,
117 impl ToJson for LldFlavor {
118 fn to_json(&self) -> Json {
120 LldFlavor::Ld64 => "darwin",
121 LldFlavor::Ld => "gnu",
122 LldFlavor::Link => "link",
123 LldFlavor::Wasm => "wasm",
129 impl ToJson for LinkerFlavor {
130 fn to_json(&self) -> Json {
131 self.desc().to_json()
134 macro_rules! flavor_mappings {
135 ($((($($flavor:tt)*), $string:expr),)*) => (
137 pub const fn one_of() -> &'static str {
138 concat!("one of: ", $($string, " ",)*)
141 pub fn from_str(s: &str) -> Option<Self> {
143 $($string => $($flavor)*,)*
148 pub fn desc(&self) -> &str {
150 $($($flavor)* => $string,)*
158 ((LinkerFlavor::Em), "em"),
159 ((LinkerFlavor::Gcc), "gcc"),
160 ((LinkerFlavor::Ld), "ld"),
161 ((LinkerFlavor::Msvc), "msvc"),
162 ((LinkerFlavor::PtxLinker), "ptx-linker"),
163 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
164 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
165 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
166 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
169 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
170 pub enum PanicStrategy {
176 pub fn desc(&self) -> &str {
178 PanicStrategy::Unwind => "unwind",
179 PanicStrategy::Abort => "abort",
183 pub fn desc_symbol(&self) -> Symbol {
185 PanicStrategy::Unwind => sym::unwind,
186 PanicStrategy::Abort => sym::abort,
191 impl ToJson for PanicStrategy {
192 fn to_json(&self) -> Json {
194 PanicStrategy::Abort => "abort".to_json(),
195 PanicStrategy::Unwind => "unwind".to_json(),
200 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
201 pub enum RelroLevel {
209 pub fn desc(&self) -> &str {
211 RelroLevel::Full => "full",
212 RelroLevel::Partial => "partial",
213 RelroLevel::Off => "off",
214 RelroLevel::None => "none",
219 impl FromStr for RelroLevel {
222 fn from_str(s: &str) -> Result<RelroLevel, ()> {
224 "full" => Ok(RelroLevel::Full),
225 "partial" => Ok(RelroLevel::Partial),
226 "off" => Ok(RelroLevel::Off),
227 "none" => Ok(RelroLevel::None),
233 impl ToJson for RelroLevel {
234 fn to_json(&self) -> Json {
236 RelroLevel::Full => "full".to_json(),
237 RelroLevel::Partial => "partial".to_json(),
238 RelroLevel::Off => "off".to_json(),
239 RelroLevel::None => "None".to_json(),
244 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
245 pub enum MergeFunctions {
251 impl MergeFunctions {
252 pub fn desc(&self) -> &str {
254 MergeFunctions::Disabled => "disabled",
255 MergeFunctions::Trampolines => "trampolines",
256 MergeFunctions::Aliases => "aliases",
261 impl FromStr for MergeFunctions {
264 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
266 "disabled" => Ok(MergeFunctions::Disabled),
267 "trampolines" => Ok(MergeFunctions::Trampolines),
268 "aliases" => Ok(MergeFunctions::Aliases),
274 impl ToJson for MergeFunctions {
275 fn to_json(&self) -> Json {
277 MergeFunctions::Disabled => "disabled".to_json(),
278 MergeFunctions::Trampolines => "trampolines".to_json(),
279 MergeFunctions::Aliases => "aliases".to_json(),
284 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
285 pub enum RelocModel {
294 impl FromStr for RelocModel {
297 fn from_str(s: &str) -> Result<RelocModel, ()> {
299 "static" => RelocModel::Static,
300 "pic" => RelocModel::Pic,
301 "dynamic-no-pic" => RelocModel::DynamicNoPic,
302 "ropi" => RelocModel::Ropi,
303 "rwpi" => RelocModel::Rwpi,
304 "ropi-rwpi" => RelocModel::RopiRwpi,
310 impl ToJson for RelocModel {
311 fn to_json(&self) -> Json {
313 RelocModel::Static => "static",
314 RelocModel::Pic => "pic",
315 RelocModel::DynamicNoPic => "dynamic-no-pic",
316 RelocModel::Ropi => "ropi",
317 RelocModel::Rwpi => "rwpi",
318 RelocModel::RopiRwpi => "ropi-rwpi",
324 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
333 impl FromStr for CodeModel {
336 fn from_str(s: &str) -> Result<CodeModel, ()> {
338 "tiny" => CodeModel::Tiny,
339 "small" => CodeModel::Small,
340 "kernel" => CodeModel::Kernel,
341 "medium" => CodeModel::Medium,
342 "large" => CodeModel::Large,
348 impl ToJson for CodeModel {
349 fn to_json(&self) -> Json {
351 CodeModel::Tiny => "tiny",
352 CodeModel::Small => "small",
353 CodeModel::Kernel => "kernel",
354 CodeModel::Medium => "medium",
355 CodeModel::Large => "large",
361 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
369 impl FromStr for TlsModel {
372 fn from_str(s: &str) -> Result<TlsModel, ()> {
374 // Note the difference "general" vs "global" difference. The model name is "general",
375 // but the user-facing option name is "global" for consistency with other compilers.
376 "global-dynamic" => TlsModel::GeneralDynamic,
377 "local-dynamic" => TlsModel::LocalDynamic,
378 "initial-exec" => TlsModel::InitialExec,
379 "local-exec" => TlsModel::LocalExec,
385 impl ToJson for TlsModel {
386 fn to_json(&self) -> Json {
388 TlsModel::GeneralDynamic => "global-dynamic",
389 TlsModel::LocalDynamic => "local-dynamic",
390 TlsModel::InitialExec => "initial-exec",
391 TlsModel::LocalExec => "local-exec",
397 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
398 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
399 pub enum LinkOutputKind {
400 /// Dynamically linked non position-independent executable.
402 /// Dynamically linked position-independent executable.
404 /// Statically linked non position-independent executable.
406 /// Statically linked position-independent executable.
408 /// Regular dynamic library ("dynamically linked").
410 /// Dynamic library with bundled libc ("statically linked").
412 /// WASI module with a lifetime past the _initialize entry point
416 impl LinkOutputKind {
417 fn as_str(&self) -> &'static str {
419 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
420 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
421 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
422 LinkOutputKind::StaticPicExe => "static-pic-exe",
423 LinkOutputKind::DynamicDylib => "dynamic-dylib",
424 LinkOutputKind::StaticDylib => "static-dylib",
425 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
429 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
431 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
432 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
433 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
434 "static-pic-exe" => LinkOutputKind::StaticPicExe,
435 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
436 "static-dylib" => LinkOutputKind::StaticDylib,
437 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
443 impl fmt::Display for LinkOutputKind {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 f.write_str(self.as_str())
449 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
451 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
452 pub enum SplitDebuginfo {
453 /// Split debug-information is disabled, meaning that on supported platforms
454 /// you can find all debug information in the executable itself. This is
455 /// only supported for ELF effectively.
457 /// * Windows - not supported
458 /// * macOS - don't run `dsymutil`
459 /// * ELF - `.dwarf_*` sections
462 /// Split debug-information can be found in a "packed" location separate
463 /// from the final artifact. This is supported on all platforms.
465 /// * Windows - `*.pdb`
466 /// * macOS - `*.dSYM` (run `dsymutil`)
467 /// * ELF - `*.dwp` (run `rust-llvm-dwp`)
470 /// Split debug-information can be found in individual object files on the
471 /// filesystem. The main executable may point to the object files.
473 /// * Windows - not supported
474 /// * macOS - supported, scattered object files
475 /// * ELF - supported, scattered `*.dwo` files
479 impl SplitDebuginfo {
480 fn as_str(&self) -> &'static str {
482 SplitDebuginfo::Off => "off",
483 SplitDebuginfo::Packed => "packed",
484 SplitDebuginfo::Unpacked => "unpacked",
489 impl FromStr for SplitDebuginfo {
492 fn from_str(s: &str) -> Result<SplitDebuginfo, ()> {
494 "off" => SplitDebuginfo::Off,
495 "unpacked" => SplitDebuginfo::Unpacked,
496 "packed" => SplitDebuginfo::Packed,
502 impl ToJson for SplitDebuginfo {
503 fn to_json(&self) -> Json {
504 self.as_str().to_json()
508 impl fmt::Display for SplitDebuginfo {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 f.write_str(self.as_str())
514 macro_rules! supported_targets {
515 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
518 /// List of supported targets
519 pub const TARGETS: &[&str] = &[$($($triple),+),+];
521 fn load_builtin(target: &str) -> Option<Target> {
522 let mut t = match target {
523 $( $($triple)|+ => $module::target(), )+
527 debug!("got builtin target: {:?}", t);
535 // Cannot put this into a separate file without duplication, make an exception.
539 tests_impl::test_target(super::$module::target());
546 #[derive(Clone, Debug, PartialEq, Eq)]
547 pub enum StackProbeType {
548 /// Don't emit any stack probes.
550 /// It is harmless to use this option even on targets that do not have backend support for
551 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
554 /// Call `__rust_probestack` whenever stack needs to be probed.
556 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
557 /// and call `__rust_probestack` otherwise.
558 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
561 impl StackProbeType {
562 fn from_json(json: &Json) -> Result<Self, String> {
563 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
566 .and_then(|o| o.as_string())
567 .ok_or_else(|| "expected `kind` to be a string")?;
569 "none" => Ok(StackProbeType::None),
570 "inline" => Ok(StackProbeType::Inline),
571 "call" => Ok(StackProbeType::Call),
572 "inline-or-call" => {
573 let min_version = object
574 .get("min-llvm-version-for-inline")
575 .and_then(|o| o.as_array())
576 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
577 let mut iter = min_version.into_iter().map(|v| {
578 let int = v.as_u64().ok_or_else(
579 || "expected `min-llvm-version-for-inline` values to be integers",
582 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
584 let min_llvm_version_for_inline = (
585 iter.next().unwrap_or(Ok(11))?,
586 iter.next().unwrap_or(Ok(0))?,
587 iter.next().unwrap_or(Ok(0))?,
589 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
591 _ => Err(String::from(
592 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
598 impl ToJson for StackProbeType {
599 fn to_json(&self) -> Json {
600 Json::Object(match self {
601 StackProbeType::None => {
602 vec![(String::from("kind"), "none".to_json())].into_iter().collect()
604 StackProbeType::Inline => {
605 vec![(String::from("kind"), "inline".to_json())].into_iter().collect()
607 StackProbeType::Call => {
608 vec![(String::from("kind"), "call".to_json())].into_iter().collect()
610 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => vec![
611 (String::from("kind"), "inline-or-call".to_json()),
613 String::from("min-llvm-version-for-inline"),
614 min_llvm_version_for_inline.to_json(),
624 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
625 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
626 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
627 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
628 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
629 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
630 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
631 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
632 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
633 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
634 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
635 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
636 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
637 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
638 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
639 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
640 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
641 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
642 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
643 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
644 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
645 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
646 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
647 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
648 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
649 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
650 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
651 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
652 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
653 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
654 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
655 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
656 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
657 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
658 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
659 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
660 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
661 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
662 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
663 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
664 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
665 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
666 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
667 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
668 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
669 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
670 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
672 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
673 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
675 ("i686-linux-android", i686_linux_android),
676 ("x86_64-linux-android", x86_64_linux_android),
677 ("arm-linux-androideabi", arm_linux_androideabi),
678 ("armv7-linux-androideabi", armv7_linux_androideabi),
679 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
680 ("aarch64-linux-android", aarch64_linux_android),
682 ("x86_64-linux-kernel", x86_64_linux_kernel),
684 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
685 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
686 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
687 ("i686-unknown-freebsd", i686_unknown_freebsd),
688 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
689 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
691 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
693 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
694 ("i686-unknown-openbsd", i686_unknown_openbsd),
695 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
696 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
698 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
699 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
700 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
701 ("i686-unknown-netbsd", i686_unknown_netbsd),
702 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
703 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
704 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
705 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
707 ("i686-unknown-haiku", i686_unknown_haiku),
708 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
710 ("aarch64-apple-darwin", aarch64_apple_darwin),
711 ("x86_64-apple-darwin", x86_64_apple_darwin),
712 ("i686-apple-darwin", i686_apple_darwin),
714 ("aarch64-fuchsia", aarch64_fuchsia),
715 ("x86_64-fuchsia", x86_64_fuchsia),
717 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
719 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
721 ("aarch64-unknown-redox", aarch64_unknown_redox),
722 ("x86_64-unknown-redox", x86_64_unknown_redox),
724 ("i386-apple-ios", i386_apple_ios),
725 ("x86_64-apple-ios", x86_64_apple_ios),
726 ("aarch64-apple-ios", aarch64_apple_ios),
727 ("armv7-apple-ios", armv7_apple_ios),
728 ("armv7s-apple-ios", armv7s_apple_ios),
729 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
730 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
731 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
732 ("aarch64-apple-tvos", aarch64_apple_tvos),
733 ("x86_64-apple-tvos", x86_64_apple_tvos),
735 ("armebv7r-none-eabi", armebv7r_none_eabi),
736 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
737 ("armv7r-none-eabi", armv7r_none_eabi),
738 ("armv7r-none-eabihf", armv7r_none_eabihf),
740 // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
741 // (See <https://github.com/rust-lang/rust/issues/40531>.)
742 ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris),
743 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
745 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
747 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
748 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
749 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
750 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
752 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
753 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
754 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
755 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
756 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
757 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
758 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
759 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
760 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
762 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
763 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
764 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
765 ("wasm32-wasi", wasm32_wasi),
767 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
768 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
769 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
770 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
771 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
772 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
773 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
775 ("armv7a-none-eabi", armv7a_none_eabi),
776 ("armv7a-none-eabihf", armv7a_none_eabihf),
778 ("msp430-none-elf", msp430_none_elf),
780 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
781 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
782 ("x86_64-unknown-hermit-kernel", x86_64_unknown_hermit_kernel),
784 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
785 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
786 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
787 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
788 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
789 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
790 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
791 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
792 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
794 ("aarch64-unknown-none", aarch64_unknown_none),
795 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
797 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
799 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
800 ("i686-unknown-uefi", i686_unknown_uefi),
802 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
804 ("i686-wrs-vxworks", i686_wrs_vxworks),
805 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
806 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
807 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
808 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
809 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
810 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
812 ("mipsel-sony-psp", mipsel_sony_psp),
813 ("mipsel-unknown-none", mipsel_unknown_none),
814 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
816 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
817 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
818 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
821 /// Everything `rustc` knows about how to compile for a specific target.
823 /// Every field here must be specified, and has no default value.
824 #[derive(PartialEq, Clone, Debug)]
826 /// Target triple to pass to LLVM.
827 pub llvm_target: String,
828 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
829 pub pointer_width: u32,
830 /// Architecture to use for ABI considerations. Valid options include: "x86",
831 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
833 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
834 pub data_layout: String,
835 /// Optional settings with defaults.
836 pub options: TargetOptions,
839 pub trait HasTargetSpec {
840 fn target_spec(&self) -> &Target;
843 impl HasTargetSpec for Target {
844 fn target_spec(&self) -> &Target {
849 /// Optional aspects of a target specification.
851 /// This has an implementation of `Default`, see each field for what the default is. In general,
852 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
854 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
855 /// construction, all its fields logically belong to `Target` and available from `Target`
856 /// through `Deref` impls.
857 #[derive(PartialEq, Clone, Debug)]
858 pub struct TargetOptions {
859 /// Whether the target is built-in or loaded from a custom target specification.
860 pub is_builtin: bool,
862 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
864 /// Width of c_int type. Defaults to "32".
865 pub c_int_width: String,
866 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
867 /// "none" implies a bare metal target without `std` library.
868 /// A couple of targets having `std` also use "unknown" as an `os` value,
869 /// but they are exceptions.
871 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
873 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
875 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
876 /// on the command line. Defaults to `LinkerFlavor::Gcc`.
877 pub linker_flavor: LinkerFlavor,
880 pub linker: Option<String>,
882 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
883 /// without clarifying its flavor in any way.
884 pub lld_flavor: LldFlavor,
886 /// Linker arguments that are passed *before* any user-defined libraries.
887 pub pre_link_args: LinkArgs,
888 /// Objects to link before and after all other object code.
889 pub pre_link_objects: CrtObjects,
890 pub post_link_objects: CrtObjects,
891 /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
892 /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
893 /// See `crt_objects.rs` for some more detailed documentation.
894 pub pre_link_objects_fallback: CrtObjects,
895 pub post_link_objects_fallback: CrtObjects,
896 /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
897 pub crt_objects_fallback: Option<CrtObjectsFallback>,
899 /// Linker arguments that are unconditionally passed after any
900 /// user-defined but before post-link objects. Standard platform
901 /// libraries that should be always be linked to, usually go here.
902 pub late_link_args: LinkArgs,
903 /// Linker arguments used in addition to `late_link_args` if at least one
904 /// Rust dependency is dynamically linked.
905 pub late_link_args_dynamic: LinkArgs,
906 /// Linker arguments used in addition to `late_link_args` if aall Rust
907 /// dependencies are statically linked.
908 pub late_link_args_static: LinkArgs,
909 /// Linker arguments that are unconditionally passed *after* any
910 /// user-defined libraries.
911 pub post_link_args: LinkArgs,
912 /// Optional link script applied to `dylib` and `executable` crate types.
913 /// This is a string containing the script, not a path. Can only be applied
914 /// to linkers where `linker_is_gnu` is true.
915 pub link_script: Option<String>,
917 /// Environment variables to be set for the linker invocation.
918 pub link_env: Vec<(String, String)>,
919 /// Environment variables to be removed for the linker invocation.
920 pub link_env_remove: Vec<String>,
922 /// Extra arguments to pass to the external assembler (when used)
923 pub asm_args: Vec<String>,
925 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
928 /// Default target features to pass to LLVM. These features will *always* be
929 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
930 /// -mattr=$features`.
931 pub features: String,
932 /// Whether dynamic linking is available on this target. Defaults to false.
933 pub dynamic_linking: bool,
934 /// If dynamic linking is available, whether only cdylibs are supported.
935 pub only_cdylib: bool,
936 /// Whether executables are available on this target. iOS, for example, only allows static
937 /// libraries. Defaults to false.
938 pub executables: bool,
939 /// Relocation model to use in object file. Corresponds to `llc
940 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
941 pub relocation_model: RelocModel,
942 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
943 /// Defaults to `None` which means "inherited from the base LLVM target".
944 pub code_model: Option<CodeModel>,
945 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
946 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
947 pub tls_model: TlsModel,
948 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
949 pub disable_redzone: bool,
950 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
951 pub eliminate_frame_pointer: bool,
952 /// Emit each function in its own section. Defaults to true.
953 pub function_sections: bool,
954 /// String to prepend to the name of every dynamic library. Defaults to "lib".
955 pub dll_prefix: String,
956 /// String to append to the name of every dynamic library. Defaults to ".so".
957 pub dll_suffix: String,
958 /// String to append to the name of every executable.
959 pub exe_suffix: String,
960 /// String to prepend to the name of every static library. Defaults to "lib".
961 pub staticlib_prefix: String,
962 /// String to append to the name of every static library. Defaults to ".a".
963 pub staticlib_suffix: String,
964 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
965 pub os_family: Option<String>,
966 /// Whether the target toolchain's ABI supports returning small structs as an integer.
967 pub abi_return_struct_as_int: bool,
968 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
969 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
970 pub is_like_osx: bool,
971 /// Whether the target toolchain is like Solaris's.
972 /// Only useful for compiling against Illumos/Solaris,
973 /// as they have a different set of linker flags. Defaults to false.
974 pub is_like_solaris: bool,
975 /// Whether the target is like Windows.
976 /// This is a combination of several more specific properties represented as a single flag:
977 /// - The target uses a Windows ABI,
978 /// - uses PE/COFF as a format for object code,
979 /// - uses Windows-style dllexport/dllimport for shared libraries,
980 /// - uses import libraries and .def files for symbol exports,
981 /// - executables support setting a subsystem.
982 pub is_like_windows: bool,
983 /// Whether the target is like MSVC.
984 /// This is a combination of several more specific properties represented as a single flag:
985 /// - The target has all the properties from `is_like_windows`
986 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
987 /// - has some MSVC-specific Windows ABI properties,
988 /// - uses a link.exe-like linker,
989 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
990 /// - uses SEH-based unwinding,
991 /// - supports control flow guard mechanism.
992 pub is_like_msvc: bool,
993 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
994 /// Emscripten toolchain.
995 /// Defaults to false.
996 pub is_like_emscripten: bool,
997 /// Whether the target toolchain is like Fuchsia's.
998 pub is_like_fuchsia: bool,
999 /// Version of DWARF to use if not using the default.
1000 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1001 pub dwarf_version: Option<u32>,
1002 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
1003 pub linker_is_gnu: bool,
1004 /// The MinGW toolchain has a known issue that prevents it from correctly
1005 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1006 /// symbol needs its own COMDAT section, weak linkage implies a large
1007 /// number sections that easily exceeds the given limit for larger
1008 /// codebases. Consequently we want a way to disallow weak linkage on some
1010 pub allows_weak_linkage: bool,
1011 /// Whether the linker support rpaths or not. Defaults to false.
1012 pub has_rpath: bool,
1013 /// Whether to disable linking to the default libraries, typically corresponds
1014 /// to `-nodefaultlibs`. Defaults to true.
1015 pub no_default_libraries: bool,
1016 /// Dynamically linked executables can be compiled as position independent
1017 /// if the default relocation model of position independent code is not
1018 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1019 /// the functions in the executable are not randomized and can be used
1020 /// during an exploit of a vulnerability in any code.
1021 pub position_independent_executables: bool,
1022 /// Executables that are both statically linked and position-independent are supported.
1023 pub static_position_independent_executables: bool,
1024 /// Determines if the target always requires using the PLT for indirect
1025 /// library calls or not. This controls the default value of the `-Z plt` flag.
1026 pub needs_plt: bool,
1027 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1028 /// resolve all symbols at startup and marks the GOT read-only before
1029 /// starting the program, preventing overwriting the GOT.
1030 pub relro_level: RelroLevel,
1031 /// Format that archives should be emitted in. This affects whether we use
1032 /// LLVM to assemble an archive or fall back to the system linker, and
1033 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1034 /// the system linker to be used.
1035 pub archive_format: String,
1036 /// Is asm!() allowed? Defaults to true.
1037 pub allow_asm: bool,
1038 /// Whether the runtime startup code requires the `main` function be passed
1039 /// `argc` and `argv` values.
1040 pub main_needs_argc_argv: bool,
1042 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
1044 pub has_elf_tls: bool,
1045 // This is mainly for easy compatibility with emscripten.
1046 // If we give emcc .o files that are actually .bc files it
1047 // will 'just work'.
1048 pub obj_is_bitcode: bool,
1049 /// Whether the target requires that emitted object code includes bitcode.
1050 pub forces_embed_bitcode: bool,
1051 /// Content of the LLVM cmdline section associated with embedded bitcode.
1052 pub bitcode_llvm_cmdline: String,
1054 /// Don't use this field; instead use the `.min_atomic_width()` method.
1055 pub min_atomic_width: Option<u64>,
1057 /// Don't use this field; instead use the `.max_atomic_width()` method.
1058 pub max_atomic_width: Option<u64>,
1060 /// Whether the target supports atomic CAS operations natively
1061 pub atomic_cas: bool,
1063 /// Panic strategy: "unwind" or "abort"
1064 pub panic_strategy: PanicStrategy,
1066 /// A list of ABIs unsupported by the current target. Note that generic ABIs
1067 /// are considered to be supported on all platforms and cannot be marked
1069 pub unsupported_abis: Vec<Abi>,
1071 /// Whether or not linking dylibs to a static CRT is allowed.
1072 pub crt_static_allows_dylibs: bool,
1073 /// Whether or not the CRT is statically linked by default.
1074 pub crt_static_default: bool,
1075 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1076 pub crt_static_respected: bool,
1078 /// The implementation of stack probes to use.
1079 pub stack_probes: StackProbeType,
1081 /// The minimum alignment for global symbols.
1082 pub min_global_align: Option<u64>,
1084 /// Default number of codegen units to use in debug mode
1085 pub default_codegen_units: Option<u64>,
1087 /// Whether to generate trap instructions in places where optimization would
1088 /// otherwise produce control flow that falls through into unrelated memory.
1089 pub trap_unreachable: bool,
1091 /// This target requires everything to be compiled with LTO to emit a final
1092 /// executable, aka there is no native linker for this target.
1093 pub requires_lto: bool,
1095 /// This target has no support for threads.
1096 pub singlethread: bool,
1098 /// Whether library functions call lowering/optimization is disabled in LLVM
1099 /// for this target unconditionally.
1100 pub no_builtins: bool,
1102 /// The default visibility for symbols in this target should be "hidden"
1103 /// rather than "default"
1104 pub default_hidden_visibility: bool,
1106 /// Whether a .debug_gdb_scripts section will be added to the output object file
1107 pub emit_debug_gdb_scripts: bool,
1109 /// Whether or not to unconditionally `uwtable` attributes on functions,
1110 /// typically because the platform needs to unwind for things like stack
1112 pub requires_uwtable: bool,
1114 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1115 /// typically required if a target can be compiled with a mixed set of
1116 /// target features. This is `true` by default, and `false` for targets like
1117 /// wasm32 where the whole program either has simd or not.
1118 pub simd_types_indirect: bool,
1120 /// Pass a list of symbol which should be exported in the dylib to the linker.
1121 pub limit_rdylib_exports: bool,
1123 /// If set, have the linker export exactly these symbols, instead of using
1124 /// the usual logic to figure this out from the crate itself.
1125 pub override_export_symbols: Option<Vec<String>>,
1127 /// Determines how or whether the MergeFunctions LLVM pass should run for
1128 /// this target. Either "disabled", "trampolines", or "aliases".
1129 /// The MergeFunctions pass is generally useful, but some targets may need
1130 /// to opt out. The default is "aliases".
1132 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1133 pub merge_functions: MergeFunctions,
1135 /// Use platform dependent mcount function
1138 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1139 pub llvm_abiname: String,
1141 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1142 pub relax_elf_relocations: bool,
1144 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1145 pub llvm_args: Vec<String>,
1147 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1148 /// to false (uses .init_array).
1149 pub use_ctors_section: bool,
1151 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1152 /// used to locate unwinding information is passed
1153 /// (only has effect if the linker is `ld`-like).
1154 pub eh_frame_header: bool,
1156 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1157 /// thumb and arm interworking.
1158 pub has_thumb_interworking: bool,
1160 /// How to handle split debug information, if at all. Specifying `None` has
1161 /// target-specific meaning.
1162 pub split_debuginfo: SplitDebuginfo,
1165 impl Default for TargetOptions {
1166 /// Creates a set of "sane defaults" for any target. This is still
1167 /// incomplete, and if used for compilation, will certainly not work.
1168 fn default() -> TargetOptions {
1171 endian: Endian::Little,
1172 c_int_width: "32".to_string(),
1173 os: "none".to_string(),
1175 vendor: "unknown".to_string(),
1176 linker_flavor: LinkerFlavor::Gcc,
1177 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1178 lld_flavor: LldFlavor::Ld,
1179 pre_link_args: LinkArgs::new(),
1180 post_link_args: LinkArgs::new(),
1182 asm_args: Vec::new(),
1183 cpu: "generic".to_string(),
1184 features: String::new(),
1185 dynamic_linking: false,
1188 relocation_model: RelocModel::Pic,
1190 tls_model: TlsModel::GeneralDynamic,
1191 disable_redzone: false,
1192 eliminate_frame_pointer: true,
1193 function_sections: true,
1194 dll_prefix: "lib".to_string(),
1195 dll_suffix: ".so".to_string(),
1196 exe_suffix: String::new(),
1197 staticlib_prefix: "lib".to_string(),
1198 staticlib_suffix: ".a".to_string(),
1200 abi_return_struct_as_int: false,
1202 is_like_solaris: false,
1203 is_like_windows: false,
1204 is_like_emscripten: false,
1205 is_like_msvc: false,
1206 is_like_fuchsia: false,
1207 dwarf_version: None,
1208 linker_is_gnu: false,
1209 allows_weak_linkage: true,
1211 no_default_libraries: true,
1212 position_independent_executables: false,
1213 static_position_independent_executables: false,
1215 relro_level: RelroLevel::None,
1216 pre_link_objects: Default::default(),
1217 post_link_objects: Default::default(),
1218 pre_link_objects_fallback: Default::default(),
1219 post_link_objects_fallback: Default::default(),
1220 crt_objects_fallback: None,
1221 late_link_args: LinkArgs::new(),
1222 late_link_args_dynamic: LinkArgs::new(),
1223 late_link_args_static: LinkArgs::new(),
1224 link_env: Vec::new(),
1225 link_env_remove: Vec::new(),
1226 archive_format: "gnu".to_string(),
1227 main_needs_argc_argv: true,
1230 obj_is_bitcode: false,
1231 forces_embed_bitcode: false,
1232 bitcode_llvm_cmdline: String::new(),
1233 min_atomic_width: None,
1234 max_atomic_width: None,
1236 panic_strategy: PanicStrategy::Unwind,
1237 unsupported_abis: vec![],
1238 crt_static_allows_dylibs: false,
1239 crt_static_default: false,
1240 crt_static_respected: false,
1241 stack_probes: StackProbeType::None,
1242 min_global_align: None,
1243 default_codegen_units: None,
1244 trap_unreachable: true,
1245 requires_lto: false,
1246 singlethread: false,
1248 default_hidden_visibility: false,
1249 emit_debug_gdb_scripts: true,
1250 requires_uwtable: false,
1251 simd_types_indirect: true,
1252 limit_rdylib_exports: true,
1253 override_export_symbols: None,
1254 merge_functions: MergeFunctions::Aliases,
1255 mcount: "mcount".to_string(),
1256 llvm_abiname: "".to_string(),
1257 relax_elf_relocations: false,
1259 use_ctors_section: false,
1260 eh_frame_header: true,
1261 has_thumb_interworking: false,
1262 split_debuginfo: SplitDebuginfo::Off,
1267 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1268 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1269 /// this `Deref` implementation is no longer necessary.
1270 impl Deref for Target {
1271 type Target = TargetOptions;
1273 fn deref(&self) -> &Self::Target {
1277 impl DerefMut for Target {
1278 fn deref_mut(&mut self) -> &mut Self::Target {
1284 /// Given a function ABI, turn it into the correct ABI for this target.
1285 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1288 if self.is_like_windows && self.arch == "x86" {
1294 // These ABI kinds are ignored on non-x86 Windows targets.
1295 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1296 // and the individual pages for __stdcall et al.
1297 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
1298 if self.is_like_windows && self.arch != "x86" { Abi::C } else { abi }
1301 if self.arch == "x86_64" {
1311 /// Minimum integer size in bits that this target can perform atomic
1313 pub fn min_atomic_width(&self) -> u64 {
1314 self.min_atomic_width.unwrap_or(8)
1317 /// Maximum integer size in bits that this target can perform atomic
1319 pub fn max_atomic_width(&self) -> u64 {
1320 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1323 pub fn is_abi_supported(&self, abi: Abi) -> bool {
1324 abi.generic() || !self.unsupported_abis.contains(&abi)
1327 /// Loads a target descriptor from a JSON object.
1328 pub fn from_json(obj: Json) -> Result<Target, String> {
1329 // While ugly, this code must remain this way to retain
1330 // compatibility with existing JSON fields and the internal
1331 // expected naming of the Target and TargetOptions structs.
1332 // To ensure compatibility is retained, the built-in targets
1333 // are round-tripped through this code to catch cases where
1334 // the JSON parser is not updated to match the structs.
1336 let get_req_field = |name: &str| {
1338 .map(|s| s.as_string())
1339 .and_then(|os| os.map(|s| s.to_string()))
1340 .ok_or_else(|| format!("Field {} in target specification is required", name))
1343 let mut base = Target {
1344 llvm_target: get_req_field("llvm-target")?,
1345 pointer_width: get_req_field("target-pointer-width")?
1347 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1348 data_layout: get_req_field("data-layout")?,
1349 arch: get_req_field("arch")?,
1350 options: Default::default(),
1354 ($key_name:ident) => ( {
1355 let name = (stringify!($key_name)).replace("_", "-");
1356 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1357 base.$key_name = s.to_string();
1360 ($key_name:ident = $json_name:expr) => ( {
1361 let name = $json_name;
1362 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1363 base.$key_name = s.to_string();
1366 ($key_name:ident, bool) => ( {
1367 let name = (stringify!($key_name)).replace("_", "-");
1368 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
1372 ($key_name:ident, Option<u32>) => ( {
1373 let name = (stringify!($key_name)).replace("_", "-");
1374 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1376 return Err("Not a valid DWARF version number".to_string());
1378 base.$key_name = Some(s as u32);
1381 ($key_name:ident, Option<u64>) => ( {
1382 let name = (stringify!($key_name)).replace("_", "-");
1383 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1384 base.$key_name = Some(s);
1387 ($key_name:ident, MergeFunctions) => ( {
1388 let name = (stringify!($key_name)).replace("_", "-");
1389 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1390 match s.parse::<MergeFunctions>() {
1391 Ok(mergefunc) => base.$key_name = mergefunc,
1392 _ => return Some(Err(format!("'{}' is not a valid value for \
1393 merge-functions. Use 'disabled', \
1394 'trampolines', or 'aliases'.",
1398 })).unwrap_or(Ok(()))
1400 ($key_name:ident, RelocModel) => ( {
1401 let name = (stringify!($key_name)).replace("_", "-");
1402 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1403 match s.parse::<RelocModel>() {
1404 Ok(relocation_model) => base.$key_name = relocation_model,
1405 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1406 Run `rustc --print relocation-models` to \
1407 see the list of supported values.", s))),
1410 })).unwrap_or(Ok(()))
1412 ($key_name:ident, CodeModel) => ( {
1413 let name = (stringify!($key_name)).replace("_", "-");
1414 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1415 match s.parse::<CodeModel>() {
1416 Ok(code_model) => base.$key_name = Some(code_model),
1417 _ => return Some(Err(format!("'{}' is not a valid code model. \
1418 Run `rustc --print code-models` to \
1419 see the list of supported values.", s))),
1422 })).unwrap_or(Ok(()))
1424 ($key_name:ident, TlsModel) => ( {
1425 let name = (stringify!($key_name)).replace("_", "-");
1426 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1427 match s.parse::<TlsModel>() {
1428 Ok(tls_model) => base.$key_name = tls_model,
1429 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1430 Run `rustc --print tls-models` to \
1431 see the list of supported values.", s))),
1434 })).unwrap_or(Ok(()))
1436 ($key_name:ident, PanicStrategy) => ( {
1437 let name = (stringify!($key_name)).replace("_", "-");
1438 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1440 "unwind" => base.$key_name = PanicStrategy::Unwind,
1441 "abort" => base.$key_name = PanicStrategy::Abort,
1442 _ => return Some(Err(format!("'{}' is not a valid value for \
1443 panic-strategy. Use 'unwind' or 'abort'.",
1447 })).unwrap_or(Ok(()))
1449 ($key_name:ident, RelroLevel) => ( {
1450 let name = (stringify!($key_name)).replace("_", "-");
1451 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1452 match s.parse::<RelroLevel>() {
1453 Ok(level) => base.$key_name = level,
1454 _ => return Some(Err(format!("'{}' is not a valid value for \
1455 relro-level. Use 'full', 'partial, or 'off'.",
1459 })).unwrap_or(Ok(()))
1461 ($key_name:ident, SplitDebuginfo) => ( {
1462 let name = (stringify!($key_name)).replace("_", "-");
1463 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1464 match s.parse::<SplitDebuginfo>() {
1465 Ok(level) => base.$key_name = level,
1466 _ => return Some(Err(format!("'{}' is not a valid value for \
1467 split-debuginfo. Use 'off' or 'dsymutil'.",
1471 })).unwrap_or(Ok(()))
1473 ($key_name:ident, list) => ( {
1474 let name = (stringify!($key_name)).replace("_", "-");
1475 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1476 base.$key_name = v.iter()
1477 .map(|a| a.as_string().unwrap().to_string())
1481 ($key_name:ident, opt_list) => ( {
1482 let name = (stringify!($key_name)).replace("_", "-");
1483 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1484 base.$key_name = Some(v.iter()
1485 .map(|a| a.as_string().unwrap().to_string())
1489 ($key_name:ident, optional) => ( {
1490 let name = (stringify!($key_name)).replace("_", "-");
1491 if let Some(o) = obj.find(&name[..]) {
1494 .map(|s| s.to_string() );
1497 ($key_name:ident = $json_name:expr, optional) => ( {
1498 let name = $json_name;
1499 if let Some(o) = obj.find(name) {
1502 .map(|s| s.to_string() );
1505 ($key_name:ident, LldFlavor) => ( {
1506 let name = (stringify!($key_name)).replace("_", "-");
1507 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1508 if let Some(flavor) = LldFlavor::from_str(&s) {
1509 base.$key_name = flavor;
1511 return Some(Err(format!(
1512 "'{}' is not a valid value for lld-flavor. \
1513 Use 'darwin', 'gnu', 'link' or 'wasm.",
1517 })).unwrap_or(Ok(()))
1519 ($key_name:ident, LinkerFlavor) => ( {
1520 let name = (stringify!($key_name)).replace("_", "-");
1521 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1522 match LinkerFlavor::from_str(s) {
1523 Some(linker_flavor) => base.$key_name = linker_flavor,
1524 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1525 Use {}", s, LinkerFlavor::one_of()))),
1528 })).unwrap_or(Ok(()))
1530 ($key_name:ident, StackProbeType) => ( {
1531 let name = (stringify!($key_name)).replace("_", "-");
1532 obj.find(&name[..]).and_then(|o| match StackProbeType::from_json(o) {
1538 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1540 }).unwrap_or(Ok(()))
1542 ($key_name:ident, crt_objects_fallback) => ( {
1543 let name = (stringify!($key_name)).replace("_", "-");
1544 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1545 match s.parse::<CrtObjectsFallback>() {
1546 Ok(fallback) => base.$key_name = Some(fallback),
1547 _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1548 Use 'musl', 'mingw' or 'wasm'", s))),
1551 })).unwrap_or(Ok(()))
1553 ($key_name:ident, link_objects) => ( {
1554 let name = (stringify!($key_name)).replace("_", "-");
1555 if let Some(val) = obj.find(&name[..]) {
1556 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1557 JSON object with fields per CRT object kind.", name))?;
1558 let mut args = CrtObjects::new();
1560 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1561 format!("{}: '{}' is not a valid value for CRT object kind. \
1562 Use '(dynamic,static)-(nopic,pic)-exe' or \
1563 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1566 let v = v.as_array().ok_or_else(||
1567 format!("{}.{}: expected a JSON array", name, k)
1568 )?.iter().enumerate()
1570 let s = s.as_string().ok_or_else(||
1571 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1574 .collect::<Result<Vec<_>, String>>()?;
1576 args.insert(kind, v);
1578 base.$key_name = args;
1581 ($key_name:ident, link_args) => ( {
1582 let name = (stringify!($key_name)).replace("_", "-");
1583 if let Some(val) = obj.find(&name[..]) {
1584 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1585 JSON object with fields per linker-flavor.", name))?;
1586 let mut args = LinkArgs::new();
1588 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1589 format!("{}: '{}' is not a valid value for linker-flavor. \
1590 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1593 let v = v.as_array().ok_or_else(||
1594 format!("{}.{}: expected a JSON array", name, k)
1595 )?.iter().enumerate()
1597 let s = s.as_string().ok_or_else(||
1598 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1601 .collect::<Result<Vec<_>, String>>()?;
1603 args.insert(flavor, v);
1605 base.$key_name = args;
1608 ($key_name:ident, env) => ( {
1609 let name = (stringify!($key_name)).replace("_", "-");
1610 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1612 if let Some(s) = o.as_string() {
1613 let p = s.split('=').collect::<Vec<_>>();
1615 let k = p[0].to_string();
1616 let v = p[1].to_string();
1617 base.$key_name.push((k, v));
1625 if let Some(s) = obj.find("target-endian").and_then(Json::as_string) {
1626 base.endian = s.parse()?;
1628 key!(is_builtin, bool);
1629 key!(c_int_width = "target-c-int-width");
1633 key!(linker_flavor, LinkerFlavor)?;
1634 key!(linker, optional);
1635 key!(lld_flavor, LldFlavor)?;
1636 key!(pre_link_objects, link_objects);
1637 key!(post_link_objects, link_objects);
1638 key!(pre_link_objects_fallback, link_objects);
1639 key!(post_link_objects_fallback, link_objects);
1640 key!(crt_objects_fallback, crt_objects_fallback)?;
1641 key!(pre_link_args, link_args);
1642 key!(late_link_args, link_args);
1643 key!(late_link_args_dynamic, link_args);
1644 key!(late_link_args_static, link_args);
1645 key!(post_link_args, link_args);
1646 key!(link_script, optional);
1647 key!(link_env, env);
1648 key!(link_env_remove, list);
1649 key!(asm_args, list);
1652 key!(dynamic_linking, bool);
1653 key!(only_cdylib, bool);
1654 key!(executables, bool);
1655 key!(relocation_model, RelocModel)?;
1656 key!(code_model, CodeModel)?;
1657 key!(tls_model, TlsModel)?;
1658 key!(disable_redzone, bool);
1659 key!(eliminate_frame_pointer, bool);
1660 key!(function_sections, bool);
1664 key!(staticlib_prefix);
1665 key!(staticlib_suffix);
1666 key!(os_family = "target-family", optional);
1667 key!(abi_return_struct_as_int, bool);
1668 key!(is_like_osx, bool);
1669 key!(is_like_solaris, bool);
1670 key!(is_like_windows, bool);
1671 key!(is_like_msvc, bool);
1672 key!(is_like_emscripten, bool);
1673 key!(is_like_fuchsia, bool);
1674 key!(dwarf_version, Option<u32>);
1675 key!(linker_is_gnu, bool);
1676 key!(allows_weak_linkage, bool);
1677 key!(has_rpath, bool);
1678 key!(no_default_libraries, bool);
1679 key!(position_independent_executables, bool);
1680 key!(static_position_independent_executables, bool);
1681 key!(needs_plt, bool);
1682 key!(relro_level, RelroLevel)?;
1683 key!(archive_format);
1684 key!(allow_asm, bool);
1685 key!(main_needs_argc_argv, bool);
1686 key!(has_elf_tls, bool);
1687 key!(obj_is_bitcode, bool);
1688 key!(forces_embed_bitcode, bool);
1689 key!(bitcode_llvm_cmdline);
1690 key!(max_atomic_width, Option<u64>);
1691 key!(min_atomic_width, Option<u64>);
1692 key!(atomic_cas, bool);
1693 key!(panic_strategy, PanicStrategy)?;
1694 key!(crt_static_allows_dylibs, bool);
1695 key!(crt_static_default, bool);
1696 key!(crt_static_respected, bool);
1697 key!(stack_probes, StackProbeType)?;
1698 key!(min_global_align, Option<u64>);
1699 key!(default_codegen_units, Option<u64>);
1700 key!(trap_unreachable, bool);
1701 key!(requires_lto, bool);
1702 key!(singlethread, bool);
1703 key!(no_builtins, bool);
1704 key!(default_hidden_visibility, bool);
1705 key!(emit_debug_gdb_scripts, bool);
1706 key!(requires_uwtable, bool);
1707 key!(simd_types_indirect, bool);
1708 key!(limit_rdylib_exports, bool);
1709 key!(override_export_symbols, opt_list);
1710 key!(merge_functions, MergeFunctions)?;
1711 key!(mcount = "target-mcount");
1713 key!(relax_elf_relocations, bool);
1714 key!(llvm_args, list);
1715 key!(use_ctors_section, bool);
1716 key!(eh_frame_header, bool);
1717 key!(has_thumb_interworking, bool);
1718 key!(split_debuginfo, SplitDebuginfo)?;
1720 // NB: The old name is deprecated, but support for it is retained for
1722 for name in ["abi-blacklist", "unsupported-abis"].iter() {
1723 if let Some(array) = obj.find(name).and_then(Json::as_array) {
1724 for name in array.iter().filter_map(|abi| abi.as_string()) {
1725 match lookup_abi(name) {
1729 "The ABI \"{}\" is considered to be supported on all \
1730 targets and cannot be marked unsupported",
1735 base.unsupported_abis.push(abi)
1739 "Unknown ABI \"{}\" in target specification",
1751 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1752 /// triple. Note that it could also just be a bare filename already, so also
1753 /// check for that. If one of the hardcoded targets we know about, just
1754 /// return it directly.
1756 /// The error string could come from any of the APIs called, including
1757 /// filesystem access and JSON decoding.
1758 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1759 use rustc_serialize::json;
1763 fn load_file(path: &Path) -> Result<Target, String> {
1764 let contents = fs::read(path).map_err(|e| e.to_string())?;
1765 let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1766 Target::from_json(obj)
1769 match *target_triple {
1770 TargetTriple::TargetTriple(ref target_triple) => {
1771 // check if triple is in list of built-in targets
1772 if let Some(t) = load_builtin(target_triple) {
1776 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1778 let mut target = target_triple.to_string();
1779 target.push_str(".json");
1780 PathBuf::from(target)
1783 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1785 // FIXME 16351: add a sane default search path?
1787 for dir in env::split_paths(&target_path) {
1788 let p = dir.join(&path);
1790 return load_file(&p);
1793 Err(format!("Could not find specification for target {:?}", target_triple))
1795 TargetTriple::TargetPath(ref target_path) => {
1796 if target_path.is_file() {
1797 return load_file(&target_path);
1799 Err(format!("Target path {:?} is not a valid file", target_path))
1805 impl ToJson for Target {
1806 fn to_json(&self) -> Json {
1807 let mut d = BTreeMap::new();
1808 let default: TargetOptions = Default::default();
1810 macro_rules! target_val {
1812 let name = (stringify!($attr)).replace("_", "-");
1813 d.insert(name, self.$attr.to_json());
1815 ($attr:ident, $key_name:expr) => {{
1816 let name = $key_name;
1817 d.insert(name.to_string(), self.$attr.to_json());
1821 macro_rules! target_option_val {
1823 let name = (stringify!($attr)).replace("_", "-");
1824 if default.$attr != self.$attr {
1825 d.insert(name, self.$attr.to_json());
1828 ($attr:ident, $key_name:expr) => {{
1829 let name = $key_name;
1830 if default.$attr != self.$attr {
1831 d.insert(name.to_string(), self.$attr.to_json());
1834 (link_args - $attr:ident) => {{
1835 let name = (stringify!($attr)).replace("_", "-");
1836 if default.$attr != self.$attr {
1840 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1841 .collect::<BTreeMap<_, _>>();
1842 d.insert(name, obj.to_json());
1845 (env - $attr:ident) => {{
1846 let name = (stringify!($attr)).replace("_", "-");
1847 if default.$attr != self.$attr {
1851 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1852 .collect::<Vec<_>>();
1853 d.insert(name, obj.to_json());
1858 target_val!(llvm_target);
1859 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
1861 target_val!(data_layout);
1863 target_option_val!(is_builtin);
1864 target_option_val!(endian, "target-endian");
1865 target_option_val!(c_int_width, "target-c-int-width");
1866 target_option_val!(os);
1867 target_option_val!(env);
1868 target_option_val!(vendor);
1869 target_option_val!(linker_flavor);
1870 target_option_val!(linker);
1871 target_option_val!(lld_flavor);
1872 target_option_val!(pre_link_objects);
1873 target_option_val!(post_link_objects);
1874 target_option_val!(pre_link_objects_fallback);
1875 target_option_val!(post_link_objects_fallback);
1876 target_option_val!(crt_objects_fallback);
1877 target_option_val!(link_args - pre_link_args);
1878 target_option_val!(link_args - late_link_args);
1879 target_option_val!(link_args - late_link_args_dynamic);
1880 target_option_val!(link_args - late_link_args_static);
1881 target_option_val!(link_args - post_link_args);
1882 target_option_val!(link_script);
1883 target_option_val!(env - link_env);
1884 target_option_val!(link_env_remove);
1885 target_option_val!(asm_args);
1886 target_option_val!(cpu);
1887 target_option_val!(features);
1888 target_option_val!(dynamic_linking);
1889 target_option_val!(only_cdylib);
1890 target_option_val!(executables);
1891 target_option_val!(relocation_model);
1892 target_option_val!(code_model);
1893 target_option_val!(tls_model);
1894 target_option_val!(disable_redzone);
1895 target_option_val!(eliminate_frame_pointer);
1896 target_option_val!(function_sections);
1897 target_option_val!(dll_prefix);
1898 target_option_val!(dll_suffix);
1899 target_option_val!(exe_suffix);
1900 target_option_val!(staticlib_prefix);
1901 target_option_val!(staticlib_suffix);
1902 target_option_val!(os_family, "target-family");
1903 target_option_val!(abi_return_struct_as_int);
1904 target_option_val!(is_like_osx);
1905 target_option_val!(is_like_solaris);
1906 target_option_val!(is_like_windows);
1907 target_option_val!(is_like_msvc);
1908 target_option_val!(is_like_emscripten);
1909 target_option_val!(is_like_fuchsia);
1910 target_option_val!(dwarf_version);
1911 target_option_val!(linker_is_gnu);
1912 target_option_val!(allows_weak_linkage);
1913 target_option_val!(has_rpath);
1914 target_option_val!(no_default_libraries);
1915 target_option_val!(position_independent_executables);
1916 target_option_val!(static_position_independent_executables);
1917 target_option_val!(needs_plt);
1918 target_option_val!(relro_level);
1919 target_option_val!(archive_format);
1920 target_option_val!(allow_asm);
1921 target_option_val!(main_needs_argc_argv);
1922 target_option_val!(has_elf_tls);
1923 target_option_val!(obj_is_bitcode);
1924 target_option_val!(forces_embed_bitcode);
1925 target_option_val!(bitcode_llvm_cmdline);
1926 target_option_val!(min_atomic_width);
1927 target_option_val!(max_atomic_width);
1928 target_option_val!(atomic_cas);
1929 target_option_val!(panic_strategy);
1930 target_option_val!(crt_static_allows_dylibs);
1931 target_option_val!(crt_static_default);
1932 target_option_val!(crt_static_respected);
1933 target_option_val!(stack_probes);
1934 target_option_val!(min_global_align);
1935 target_option_val!(default_codegen_units);
1936 target_option_val!(trap_unreachable);
1937 target_option_val!(requires_lto);
1938 target_option_val!(singlethread);
1939 target_option_val!(no_builtins);
1940 target_option_val!(default_hidden_visibility);
1941 target_option_val!(emit_debug_gdb_scripts);
1942 target_option_val!(requires_uwtable);
1943 target_option_val!(simd_types_indirect);
1944 target_option_val!(limit_rdylib_exports);
1945 target_option_val!(override_export_symbols);
1946 target_option_val!(merge_functions);
1947 target_option_val!(mcount, "target-mcount");
1948 target_option_val!(llvm_abiname);
1949 target_option_val!(relax_elf_relocations);
1950 target_option_val!(llvm_args);
1951 target_option_val!(use_ctors_section);
1952 target_option_val!(eh_frame_header);
1953 target_option_val!(has_thumb_interworking);
1954 target_option_val!(split_debuginfo);
1956 if default.unsupported_abis != self.unsupported_abis {
1958 "unsupported-abis".to_string(),
1959 self.unsupported_abis
1961 .map(|&name| Abi::name(name).to_json())
1962 .collect::<Vec<_>>()
1971 /// Either a target triple string or a path to a JSON file.
1972 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
1973 pub enum TargetTriple {
1974 TargetTriple(String),
1975 TargetPath(PathBuf),
1979 /// Creates a target triple from the passed target triple string.
1980 pub fn from_triple(triple: &str) -> Self {
1981 TargetTriple::TargetTriple(triple.to_string())
1984 /// Creates a target triple from the passed target path.
1985 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1986 let canonicalized_path = path.canonicalize()?;
1987 Ok(TargetTriple::TargetPath(canonicalized_path))
1990 /// Creates a target triple from its alias
1991 pub fn from_alias(triple: String) -> Self {
1992 macro_rules! target_aliases {
1993 ( $(($alias:literal, $target:literal ),)+ ) => {
1994 match triple.as_str() {
1995 $( $alias => TargetTriple::from_triple($target), )+
1996 _ => TargetTriple::TargetTriple(triple),
2002 // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
2003 // (See <https://github.com/rust-lang/rust/issues/40531>.)
2004 ("x86_64-pc-solaris", "x86_64-sun-solaris"),
2008 /// Returns a string triple for this target.
2010 /// If this target is a path, the file name (without extension) is returned.
2011 pub fn triple(&self) -> &str {
2013 TargetTriple::TargetTriple(ref triple) => triple,
2014 TargetTriple::TargetPath(ref path) => path
2016 .expect("target path must not be empty")
2018 .expect("target path must be valid unicode"),
2022 /// Returns an extended string triple for this target.
2024 /// If this target is a path, a hash of the path is appended to the triple returned
2026 pub fn debug_triple(&self) -> String {
2027 use std::collections::hash_map::DefaultHasher;
2028 use std::hash::{Hash, Hasher};
2030 let triple = self.triple();
2031 if let TargetTriple::TargetPath(ref path) = *self {
2032 let mut hasher = DefaultHasher::new();
2033 path.hash(&mut hasher);
2034 let hash = hasher.finish();
2035 format!("{}-{}", triple, hash)
2042 impl fmt::Display for TargetTriple {
2043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2044 write!(f, "{}", self.debug_triple())