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](https://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_data_structures::stable_hasher::{HashStable, StableHasher};
41 use rustc_serialize::json::{Json, ToJson};
42 use rustc_span::symbol::{sym, Symbol};
44 use std::collections::BTreeMap;
45 use std::convert::TryFrom;
46 use std::iter::FromIterator;
47 use std::ops::{Deref, DerefMut};
48 use std::path::{Path, PathBuf};
49 use std::str::FromStr;
52 use rustc_macros::HashStable_Generic;
71 mod linux_kernel_base;
73 mod linux_uclibc_base;
85 mod windows_msvc_base;
86 mod windows_uwp_gnu_base;
87 mod windows_uwp_msvc_base;
89 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
90 pub enum LinkerFlavor {
101 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
110 fn from_str(s: &str) -> Option<Self> {
112 "darwin" => LldFlavor::Ld64,
113 "gnu" => LldFlavor::Ld,
114 "link" => LldFlavor::Link,
115 "wasm" => LldFlavor::Wasm,
121 impl ToJson for LldFlavor {
122 fn to_json(&self) -> Json {
124 LldFlavor::Ld64 => "darwin",
125 LldFlavor::Ld => "gnu",
126 LldFlavor::Link => "link",
127 LldFlavor::Wasm => "wasm",
133 impl ToJson for LinkerFlavor {
134 fn to_json(&self) -> Json {
135 self.desc().to_json()
138 macro_rules! flavor_mappings {
139 ($((($($flavor:tt)*), $string:expr),)*) => (
141 pub const fn one_of() -> &'static str {
142 concat!("one of: ", $($string, " ",)*)
145 pub fn from_str(s: &str) -> Option<Self> {
147 $($string => $($flavor)*,)*
152 pub fn desc(&self) -> &str {
154 $($($flavor)* => $string,)*
162 ((LinkerFlavor::Em), "em"),
163 ((LinkerFlavor::Gcc), "gcc"),
164 ((LinkerFlavor::L4Bender), "l4-bender"),
165 ((LinkerFlavor::Ld), "ld"),
166 ((LinkerFlavor::Msvc), "msvc"),
167 ((LinkerFlavor::PtxLinker), "ptx-linker"),
168 ((LinkerFlavor::BpfLinker), "bpf-linker"),
169 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
170 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
171 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
172 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
175 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
176 pub enum PanicStrategy {
182 pub fn desc(&self) -> &str {
184 PanicStrategy::Unwind => "unwind",
185 PanicStrategy::Abort => "abort",
189 pub const fn desc_symbol(&self) -> Symbol {
191 PanicStrategy::Unwind => sym::unwind,
192 PanicStrategy::Abort => sym::abort,
196 pub const fn all() -> [Symbol; 2] {
197 [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
201 impl ToJson for PanicStrategy {
202 fn to_json(&self) -> Json {
204 PanicStrategy::Abort => "abort".to_json(),
205 PanicStrategy::Unwind => "unwind".to_json(),
210 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
211 pub enum RelroLevel {
219 pub fn desc(&self) -> &str {
221 RelroLevel::Full => "full",
222 RelroLevel::Partial => "partial",
223 RelroLevel::Off => "off",
224 RelroLevel::None => "none",
229 impl FromStr for RelroLevel {
232 fn from_str(s: &str) -> Result<RelroLevel, ()> {
234 "full" => Ok(RelroLevel::Full),
235 "partial" => Ok(RelroLevel::Partial),
236 "off" => Ok(RelroLevel::Off),
237 "none" => Ok(RelroLevel::None),
243 impl ToJson for RelroLevel {
244 fn to_json(&self) -> Json {
246 RelroLevel::Full => "full".to_json(),
247 RelroLevel::Partial => "partial".to_json(),
248 RelroLevel::Off => "off".to_json(),
249 RelroLevel::None => "None".to_json(),
254 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
255 pub enum MergeFunctions {
261 impl MergeFunctions {
262 pub fn desc(&self) -> &str {
264 MergeFunctions::Disabled => "disabled",
265 MergeFunctions::Trampolines => "trampolines",
266 MergeFunctions::Aliases => "aliases",
271 impl FromStr for MergeFunctions {
274 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
276 "disabled" => Ok(MergeFunctions::Disabled),
277 "trampolines" => Ok(MergeFunctions::Trampolines),
278 "aliases" => Ok(MergeFunctions::Aliases),
284 impl ToJson for MergeFunctions {
285 fn to_json(&self) -> Json {
287 MergeFunctions::Disabled => "disabled".to_json(),
288 MergeFunctions::Trampolines => "trampolines".to_json(),
289 MergeFunctions::Aliases => "aliases".to_json(),
294 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
295 pub enum RelocModel {
305 impl FromStr for RelocModel {
308 fn from_str(s: &str) -> Result<RelocModel, ()> {
310 "static" => RelocModel::Static,
311 "pic" => RelocModel::Pic,
312 "pie" => RelocModel::Pie,
313 "dynamic-no-pic" => RelocModel::DynamicNoPic,
314 "ropi" => RelocModel::Ropi,
315 "rwpi" => RelocModel::Rwpi,
316 "ropi-rwpi" => RelocModel::RopiRwpi,
322 impl ToJson for RelocModel {
323 fn to_json(&self) -> Json {
325 RelocModel::Static => "static",
326 RelocModel::Pic => "pic",
327 RelocModel::Pie => "pie",
328 RelocModel::DynamicNoPic => "dynamic-no-pic",
329 RelocModel::Ropi => "ropi",
330 RelocModel::Rwpi => "rwpi",
331 RelocModel::RopiRwpi => "ropi-rwpi",
337 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
346 impl FromStr for CodeModel {
349 fn from_str(s: &str) -> Result<CodeModel, ()> {
351 "tiny" => CodeModel::Tiny,
352 "small" => CodeModel::Small,
353 "kernel" => CodeModel::Kernel,
354 "medium" => CodeModel::Medium,
355 "large" => CodeModel::Large,
361 impl ToJson for CodeModel {
362 fn to_json(&self) -> Json {
364 CodeModel::Tiny => "tiny",
365 CodeModel::Small => "small",
366 CodeModel::Kernel => "kernel",
367 CodeModel::Medium => "medium",
368 CodeModel::Large => "large",
374 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
382 impl FromStr for TlsModel {
385 fn from_str(s: &str) -> Result<TlsModel, ()> {
387 // Note the difference "general" vs "global" difference. The model name is "general",
388 // but the user-facing option name is "global" for consistency with other compilers.
389 "global-dynamic" => TlsModel::GeneralDynamic,
390 "local-dynamic" => TlsModel::LocalDynamic,
391 "initial-exec" => TlsModel::InitialExec,
392 "local-exec" => TlsModel::LocalExec,
398 impl ToJson for TlsModel {
399 fn to_json(&self) -> Json {
401 TlsModel::GeneralDynamic => "global-dynamic",
402 TlsModel::LocalDynamic => "local-dynamic",
403 TlsModel::InitialExec => "initial-exec",
404 TlsModel::LocalExec => "local-exec",
410 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
411 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
412 pub enum LinkOutputKind {
413 /// Dynamically linked non position-independent executable.
415 /// Dynamically linked position-independent executable.
417 /// Statically linked non position-independent executable.
419 /// Statically linked position-independent executable.
421 /// Regular dynamic library ("dynamically linked").
423 /// Dynamic library with bundled libc ("statically linked").
425 /// WASI module with a lifetime past the _initialize entry point
429 impl LinkOutputKind {
430 fn as_str(&self) -> &'static str {
432 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
433 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
434 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
435 LinkOutputKind::StaticPicExe => "static-pic-exe",
436 LinkOutputKind::DynamicDylib => "dynamic-dylib",
437 LinkOutputKind::StaticDylib => "static-dylib",
438 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
442 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
444 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
445 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
446 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
447 "static-pic-exe" => LinkOutputKind::StaticPicExe,
448 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
449 "static-dylib" => LinkOutputKind::StaticDylib,
450 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
456 impl fmt::Display for LinkOutputKind {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 f.write_str(self.as_str())
462 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
464 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
465 pub enum SplitDebuginfo {
466 /// Split debug-information is disabled, meaning that on supported platforms
467 /// you can find all debug information in the executable itself. This is
468 /// only supported for ELF effectively.
470 /// * Windows - not supported
471 /// * macOS - don't run `dsymutil`
472 /// * ELF - `.dwarf_*` sections
475 /// Split debug-information can be found in a "packed" location separate
476 /// from the final artifact. This is supported on all platforms.
478 /// * Windows - `*.pdb`
479 /// * macOS - `*.dSYM` (run `dsymutil`)
480 /// * ELF - `*.dwp` (run `rust-llvm-dwp`)
483 /// Split debug-information can be found in individual object files on the
484 /// filesystem. The main executable may point to the object files.
486 /// * Windows - not supported
487 /// * macOS - supported, scattered object files
488 /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
492 impl SplitDebuginfo {
493 fn as_str(&self) -> &'static str {
495 SplitDebuginfo::Off => "off",
496 SplitDebuginfo::Packed => "packed",
497 SplitDebuginfo::Unpacked => "unpacked",
502 impl FromStr for SplitDebuginfo {
505 fn from_str(s: &str) -> Result<SplitDebuginfo, ()> {
507 "off" => SplitDebuginfo::Off,
508 "unpacked" => SplitDebuginfo::Unpacked,
509 "packed" => SplitDebuginfo::Packed,
515 impl ToJson for SplitDebuginfo {
516 fn to_json(&self) -> Json {
517 self.as_str().to_json()
521 impl fmt::Display for SplitDebuginfo {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 f.write_str(self.as_str())
527 #[derive(Clone, Debug, PartialEq, Eq)]
528 pub enum StackProbeType {
529 /// Don't emit any stack probes.
531 /// It is harmless to use this option even on targets that do not have backend support for
532 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
535 /// Call `__rust_probestack` whenever stack needs to be probed.
537 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
538 /// and call `__rust_probestack` otherwise.
539 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
542 impl StackProbeType {
543 fn from_json(json: &Json) -> Result<Self, String> {
544 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
547 .and_then(|o| o.as_string())
548 .ok_or_else(|| "expected `kind` to be a string")?;
550 "none" => Ok(StackProbeType::None),
551 "inline" => Ok(StackProbeType::Inline),
552 "call" => Ok(StackProbeType::Call),
553 "inline-or-call" => {
554 let min_version = object
555 .get("min-llvm-version-for-inline")
556 .and_then(|o| o.as_array())
557 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
558 let mut iter = min_version.into_iter().map(|v| {
559 let int = v.as_u64().ok_or_else(
560 || "expected `min-llvm-version-for-inline` values to be integers",
563 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
565 let min_llvm_version_for_inline = (
566 iter.next().unwrap_or(Ok(11))?,
567 iter.next().unwrap_or(Ok(0))?,
568 iter.next().unwrap_or(Ok(0))?,
570 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
572 _ => Err(String::from(
573 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
579 impl ToJson for StackProbeType {
580 fn to_json(&self) -> Json {
581 Json::Object(match self {
582 StackProbeType::None => {
583 [(String::from("kind"), "none".to_json())].into_iter().collect()
585 StackProbeType::Inline => {
586 [(String::from("kind"), "inline".to_json())].into_iter().collect()
588 StackProbeType::Call => {
589 [(String::from("kind"), "call".to_json())].into_iter().collect()
591 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => [
592 (String::from("kind"), "inline-or-call".to_json()),
594 String::from("min-llvm-version-for-inline"),
595 min_llvm_version_for_inline.to_json(),
604 bitflags::bitflags! {
605 #[derive(Default, Encodable, Decodable)]
606 pub struct SanitizerSet: u8 {
607 const ADDRESS = 1 << 0;
609 const MEMORY = 1 << 2;
610 const THREAD = 1 << 3;
611 const HWADDRESS = 1 << 4;
613 const MEMTAG = 1 << 6;
618 /// Return sanitizer's name
620 /// Returns none if the flags is a set of sanitizers numbering not exactly one.
621 pub fn as_str(self) -> Option<&'static str> {
623 SanitizerSet::ADDRESS => "address",
624 SanitizerSet::CFI => "cfi",
625 SanitizerSet::LEAK => "leak",
626 SanitizerSet::MEMORY => "memory",
627 SanitizerSet::MEMTAG => "memtag",
628 SanitizerSet::THREAD => "thread",
629 SanitizerSet::HWADDRESS => "hwaddress",
635 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
636 impl fmt::Display for SanitizerSet {
637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638 let mut first = true;
640 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
651 impl IntoIterator for SanitizerSet {
652 type Item = SanitizerSet;
653 type IntoIter = std::vec::IntoIter<SanitizerSet>;
655 fn into_iter(self) -> Self::IntoIter {
657 SanitizerSet::ADDRESS,
660 SanitizerSet::MEMORY,
661 SanitizerSet::MEMTAG,
662 SanitizerSet::THREAD,
663 SanitizerSet::HWADDRESS,
667 .filter(|&s| self.contains(s))
673 impl<CTX> HashStable<CTX> for SanitizerSet {
674 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
675 self.bits().hash_stable(ctx, hasher);
679 impl ToJson for SanitizerSet {
680 fn to_json(&self) -> Json {
682 .map(|v| Some(v.as_str()?.to_json()))
683 .collect::<Option<Vec<_>>>()
689 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
690 pub enum FramePointer {
691 /// Forces the machine code generator to always preserve the frame pointers.
693 /// Forces the machine code generator to preserve the frame pointers except for the leaf
694 /// functions (i.e. those that don't call other functions).
696 /// Allows the machine code generator to omit the frame pointers.
698 /// This option does not guarantee that the frame pointers will be omitted.
702 impl FromStr for FramePointer {
704 fn from_str(s: &str) -> Result<Self, ()> {
706 "always" => Self::Always,
707 "non-leaf" => Self::NonLeaf,
708 "may-omit" => Self::MayOmit,
714 impl ToJson for FramePointer {
715 fn to_json(&self) -> Json {
717 Self::Always => "always",
718 Self::NonLeaf => "non-leaf",
719 Self::MayOmit => "may-omit",
725 /// Controls use of stack canaries.
726 #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
727 pub enum StackProtector {
728 /// Disable stack canary generation.
731 /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
732 /// llvm/docs/LangRef.rst). This triggers stack canary generation in
733 /// functions which contain an array of a byte-sized type with more than
737 /// On LLVM, mark all generated LLVM functions with the `sspstrong`
738 /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
739 /// generation in functions which either contain an array, or which take
740 /// the address of a local variable.
743 /// Generate stack canaries in all functions.
747 impl StackProtector {
748 fn as_str(&self) -> &'static str {
750 StackProtector::None => "none",
751 StackProtector::Basic => "basic",
752 StackProtector::Strong => "strong",
753 StackProtector::All => "all",
758 impl FromStr for StackProtector {
761 fn from_str(s: &str) -> Result<StackProtector, ()> {
763 "none" => StackProtector::None,
764 "basic" => StackProtector::Basic,
765 "strong" => StackProtector::Strong,
766 "all" => StackProtector::All,
772 impl fmt::Display for StackProtector {
773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
774 f.write_str(self.as_str())
778 macro_rules! supported_targets {
779 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
782 /// List of supported targets
783 pub const TARGETS: &[&str] = &[$($($triple),+),+];
785 fn load_builtin(target: &str) -> Option<Target> {
786 let mut t = match target {
787 $( $($triple)|+ => $module::target(), )+
791 debug!("got builtin target: {:?}", t);
799 // Cannot put this into a separate file without duplication, make an exception.
803 tests_impl::test_target(super::$module::target());
811 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
812 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
813 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
814 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
815 ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
816 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
817 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
818 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
819 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
820 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
821 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
822 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
823 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
824 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
825 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
826 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
827 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
828 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
829 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
830 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
831 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
832 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
833 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
834 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
835 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
836 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
837 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
838 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
839 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
840 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
841 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
842 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
843 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
844 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
845 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
846 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
847 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
848 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
849 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
850 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
851 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
852 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
853 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
854 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
855 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
856 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
857 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
858 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
860 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
861 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
863 ("i686-linux-android", i686_linux_android),
864 ("x86_64-linux-android", x86_64_linux_android),
865 ("arm-linux-androideabi", arm_linux_androideabi),
866 ("armv7-linux-androideabi", armv7_linux_androideabi),
867 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
868 ("aarch64-linux-android", aarch64_linux_android),
870 ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
872 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
873 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
874 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
875 ("i686-unknown-freebsd", i686_unknown_freebsd),
876 ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
877 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
878 ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
879 ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
880 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
882 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
884 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
885 ("i686-unknown-openbsd", i686_unknown_openbsd),
886 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
887 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
888 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
890 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
891 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
892 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
893 ("i686-unknown-netbsd", i686_unknown_netbsd),
894 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
895 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
896 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
898 ("i686-unknown-haiku", i686_unknown_haiku),
899 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
901 ("aarch64-apple-darwin", aarch64_apple_darwin),
902 ("x86_64-apple-darwin", x86_64_apple_darwin),
903 ("i686-apple-darwin", i686_apple_darwin),
905 ("aarch64-fuchsia", aarch64_fuchsia),
906 ("x86_64-fuchsia", x86_64_fuchsia),
908 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
910 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
912 ("aarch64-unknown-redox", aarch64_unknown_redox),
913 ("x86_64-unknown-redox", x86_64_unknown_redox),
915 ("i386-apple-ios", i386_apple_ios),
916 ("x86_64-apple-ios", x86_64_apple_ios),
917 ("aarch64-apple-ios", aarch64_apple_ios),
918 ("armv7-apple-ios", armv7_apple_ios),
919 ("armv7s-apple-ios", armv7s_apple_ios),
920 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
921 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
922 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
923 ("aarch64-apple-tvos", aarch64_apple_tvos),
924 ("x86_64-apple-tvos", x86_64_apple_tvos),
926 ("armebv7r-none-eabi", armebv7r_none_eabi),
927 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
928 ("armv7r-none-eabi", armv7r_none_eabi),
929 ("armv7r-none-eabihf", armv7r_none_eabihf),
931 ("x86_64-pc-solaris", x86_64_pc_solaris),
932 ("x86_64-sun-solaris", x86_64_sun_solaris),
933 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
935 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
937 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
938 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
939 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
940 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
942 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
943 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
944 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
945 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
946 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
947 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
948 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
949 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
950 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
952 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
953 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
954 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
955 ("wasm32-wasi", wasm32_wasi),
956 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
958 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
959 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
960 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
961 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
962 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
963 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
964 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
966 ("armv7a-none-eabi", armv7a_none_eabi),
967 ("armv7a-none-eabihf", armv7a_none_eabihf),
969 ("msp430-none-elf", msp430_none_elf),
971 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
972 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
974 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
975 ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
976 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
977 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
978 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
979 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
980 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
981 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
982 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
983 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
984 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
986 ("aarch64-unknown-none", aarch64_unknown_none),
987 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
989 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
991 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
992 ("i686-unknown-uefi", i686_unknown_uefi),
993 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
995 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
997 ("i686-wrs-vxworks", i686_wrs_vxworks),
998 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
999 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1000 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1001 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1002 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1003 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1005 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1006 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1007 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1009 ("mipsel-sony-psp", mipsel_sony_psp),
1010 ("mipsel-unknown-none", mipsel_unknown_none),
1011 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1013 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1014 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1015 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1017 ("bpfeb-unknown-none", bpfeb_unknown_none),
1018 ("bpfel-unknown-none", bpfel_unknown_none),
1020 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1022 ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1023 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1025 ("x86_64-unknown-none", x86_64_unknown_none),
1027 ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1030 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1033 ::std::borrow::Cow::Borrowed(&[])
1035 ($($x:expr),+ $(,)?) => {
1036 ::std::borrow::Cow::Borrowed(&[
1038 ::std::borrow::Cow::Borrowed($x),
1046 /// Warnings encountered when parsing the target `json`.
1048 /// Includes fields that weren't recognized and fields that don't have the expected type.
1049 #[derive(Debug, PartialEq)]
1050 pub struct TargetWarnings {
1051 unused_fields: Vec<String>,
1052 incorrect_type: Vec<String>,
1055 impl TargetWarnings {
1056 pub fn empty() -> Self {
1057 Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1060 pub fn warning_messages(&self) -> Vec<String> {
1061 let mut warnings = vec![];
1062 if !self.unused_fields.is_empty() {
1063 warnings.push(format!(
1064 "target json file contains unused fields: {}",
1065 self.unused_fields.join(", ")
1068 if !self.incorrect_type.is_empty() {
1069 warnings.push(format!(
1070 "target json file contains fields whose value doesn't have the correct json type: {}",
1071 self.incorrect_type.join(", ")
1078 /// Everything `rustc` knows about how to compile for a specific target.
1080 /// Every field here must be specified, and has no default value.
1081 #[derive(PartialEq, Clone, Debug)]
1083 /// Target triple to pass to LLVM.
1084 pub llvm_target: StaticCow<str>,
1085 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1086 pub pointer_width: u32,
1087 /// Architecture to use for ABI considerations. Valid options include: "x86",
1088 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1089 pub arch: StaticCow<str>,
1090 /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1091 pub data_layout: StaticCow<str>,
1092 /// Optional settings with defaults.
1093 pub options: TargetOptions,
1096 pub trait HasTargetSpec {
1097 fn target_spec(&self) -> &Target;
1100 impl HasTargetSpec for Target {
1102 fn target_spec(&self) -> &Target {
1107 type StaticCow<T> = Cow<'static, T>;
1109 /// Optional aspects of a target specification.
1111 /// This has an implementation of `Default`, see each field for what the default is. In general,
1112 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1114 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1115 /// construction, all its fields logically belong to `Target` and available from `Target`
1116 /// through `Deref` impls.
1117 #[derive(PartialEq, Clone, Debug)]
1118 pub struct TargetOptions {
1119 /// Whether the target is built-in or loaded from a custom target specification.
1120 pub is_builtin: bool,
1122 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1124 /// Width of c_int type. Defaults to "32".
1125 pub c_int_width: StaticCow<str>,
1126 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1127 /// "none" implies a bare metal target without `std` library.
1128 /// A couple of targets having `std` also use "unknown" as an `os` value,
1129 /// but they are exceptions.
1130 pub os: StaticCow<str>,
1131 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1132 pub env: StaticCow<str>,
1133 /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1134 /// or `"eabihf"`. Defaults to "".
1135 pub abi: StaticCow<str>,
1136 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1137 pub vendor: StaticCow<str>,
1138 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1139 /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1140 pub linker_flavor: LinkerFlavor,
1142 /// Linker to invoke
1143 pub linker: Option<StaticCow<str>>,
1145 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1146 /// without clarifying its flavor in any way.
1147 pub lld_flavor: LldFlavor,
1149 /// Linker arguments that are passed *before* any user-defined libraries.
1150 pub pre_link_args: LinkArgs,
1151 /// Objects to link before and after all other object code.
1152 pub pre_link_objects: CrtObjects,
1153 pub post_link_objects: CrtObjects,
1154 /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
1155 /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
1156 /// See `crt_objects.rs` for some more detailed documentation.
1157 pub pre_link_objects_fallback: CrtObjects,
1158 pub post_link_objects_fallback: CrtObjects,
1159 /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
1160 pub crt_objects_fallback: Option<CrtObjectsFallback>,
1162 /// Linker arguments that are unconditionally passed after any
1163 /// user-defined but before post-link objects. Standard platform
1164 /// libraries that should be always be linked to, usually go here.
1165 pub late_link_args: LinkArgs,
1166 /// Linker arguments used in addition to `late_link_args` if at least one
1167 /// Rust dependency is dynamically linked.
1168 pub late_link_args_dynamic: LinkArgs,
1169 /// Linker arguments used in addition to `late_link_args` if all Rust
1170 /// dependencies are statically linked.
1171 pub late_link_args_static: LinkArgs,
1172 /// Linker arguments that are unconditionally passed *after* any
1173 /// user-defined libraries.
1174 pub post_link_args: LinkArgs,
1175 /// Optional link script applied to `dylib` and `executable` crate types.
1176 /// This is a string containing the script, not a path. Can only be applied
1177 /// to linkers where `linker_is_gnu` is true.
1178 pub link_script: Option<StaticCow<str>>,
1180 /// Environment variables to be set for the linker invocation.
1181 pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1182 /// Environment variables to be removed for the linker invocation.
1183 pub link_env_remove: StaticCow<[StaticCow<str>]>,
1185 /// Extra arguments to pass to the external assembler (when used)
1186 pub asm_args: StaticCow<[StaticCow<str>]>,
1188 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1190 pub cpu: StaticCow<str>,
1191 /// Default target features to pass to LLVM. These features will *always* be
1192 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1193 /// -mattr=$features`.
1194 pub features: StaticCow<str>,
1195 /// Whether dynamic linking is available on this target. Defaults to false.
1196 pub dynamic_linking: bool,
1197 /// If dynamic linking is available, whether only cdylibs are supported.
1198 pub only_cdylib: bool,
1199 /// Whether executables are available on this target. iOS, for example, only allows static
1200 /// libraries. Defaults to false.
1201 pub executables: bool,
1202 /// Relocation model to use in object file. Corresponds to `llc
1203 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1204 pub relocation_model: RelocModel,
1205 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1206 /// Defaults to `None` which means "inherited from the base LLVM target".
1207 pub code_model: Option<CodeModel>,
1208 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1209 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1210 pub tls_model: TlsModel,
1211 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1212 pub disable_redzone: bool,
1213 /// Frame pointer mode for this target. Defaults to `MayOmit`.
1214 pub frame_pointer: FramePointer,
1215 /// Emit each function in its own section. Defaults to true.
1216 pub function_sections: bool,
1217 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1218 pub dll_prefix: StaticCow<str>,
1219 /// String to append to the name of every dynamic library. Defaults to ".so".
1220 pub dll_suffix: StaticCow<str>,
1221 /// String to append to the name of every executable.
1222 pub exe_suffix: StaticCow<str>,
1223 /// String to prepend to the name of every static library. Defaults to "lib".
1224 pub staticlib_prefix: StaticCow<str>,
1225 /// String to append to the name of every static library. Defaults to ".a".
1226 pub staticlib_suffix: StaticCow<str>,
1227 /// Values of the `target_family` cfg set for this target.
1229 /// Common options are: "unix", "windows". Defaults to no families.
1231 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1232 pub families: StaticCow<[StaticCow<str>]>,
1233 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1234 pub abi_return_struct_as_int: bool,
1235 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1236 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1237 pub is_like_osx: bool,
1238 /// Whether the target toolchain is like Solaris's.
1239 /// Only useful for compiling against Illumos/Solaris,
1240 /// as they have a different set of linker flags. Defaults to false.
1241 pub is_like_solaris: bool,
1242 /// Whether the target is like Windows.
1243 /// This is a combination of several more specific properties represented as a single flag:
1244 /// - The target uses a Windows ABI,
1245 /// - uses PE/COFF as a format for object code,
1246 /// - uses Windows-style dllexport/dllimport for shared libraries,
1247 /// - uses import libraries and .def files for symbol exports,
1248 /// - executables support setting a subsystem.
1249 pub is_like_windows: bool,
1250 /// Whether the target is like MSVC.
1251 /// This is a combination of several more specific properties represented as a single flag:
1252 /// - The target has all the properties from `is_like_windows`
1253 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1254 /// - has some MSVC-specific Windows ABI properties,
1255 /// - uses a link.exe-like linker,
1256 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1257 /// - uses SEH-based unwinding,
1258 /// - supports control flow guard mechanism.
1259 pub is_like_msvc: bool,
1260 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1261 /// Emscripten toolchain.
1262 /// Defaults to false.
1263 pub is_like_emscripten: bool,
1264 /// Whether the target toolchain is like Fuchsia's.
1265 pub is_like_fuchsia: bool,
1266 /// Whether a target toolchain is like WASM.
1267 pub is_like_wasm: bool,
1268 /// Version of DWARF to use if not using the default.
1269 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1270 pub dwarf_version: Option<u32>,
1271 /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1272 pub linker_is_gnu: bool,
1273 /// The MinGW toolchain has a known issue that prevents it from correctly
1274 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1275 /// symbol needs its own COMDAT section, weak linkage implies a large
1276 /// number sections that easily exceeds the given limit for larger
1277 /// codebases. Consequently we want a way to disallow weak linkage on some
1279 pub allows_weak_linkage: bool,
1280 /// Whether the linker support rpaths or not. Defaults to false.
1281 pub has_rpath: bool,
1282 /// Whether to disable linking to the default libraries, typically corresponds
1283 /// to `-nodefaultlibs`. Defaults to true.
1284 pub no_default_libraries: bool,
1285 /// Dynamically linked executables can be compiled as position independent
1286 /// if the default relocation model of position independent code is not
1287 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1288 /// the functions in the executable are not randomized and can be used
1289 /// during an exploit of a vulnerability in any code.
1290 pub position_independent_executables: bool,
1291 /// Executables that are both statically linked and position-independent are supported.
1292 pub static_position_independent_executables: bool,
1293 /// Determines if the target always requires using the PLT for indirect
1294 /// library calls or not. This controls the default value of the `-Z plt` flag.
1295 pub needs_plt: bool,
1296 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1297 /// resolve all symbols at startup and marks the GOT read-only before
1298 /// starting the program, preventing overwriting the GOT.
1299 pub relro_level: RelroLevel,
1300 /// Format that archives should be emitted in. This affects whether we use
1301 /// LLVM to assemble an archive or fall back to the system linker, and
1302 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1303 /// the system linker to be used.
1304 pub archive_format: StaticCow<str>,
1305 /// Is asm!() allowed? Defaults to true.
1306 pub allow_asm: bool,
1307 /// Whether the runtime startup code requires the `main` function be passed
1308 /// `argc` and `argv` values.
1309 pub main_needs_argc_argv: bool,
1311 /// Flag indicating whether #[thread_local] is available for this target.
1312 pub has_thread_local: bool,
1313 // This is mainly for easy compatibility with emscripten.
1314 // If we give emcc .o files that are actually .bc files it
1315 // will 'just work'.
1316 pub obj_is_bitcode: bool,
1317 /// Whether the target requires that emitted object code includes bitcode.
1318 pub forces_embed_bitcode: bool,
1319 /// Content of the LLVM cmdline section associated with embedded bitcode.
1320 pub bitcode_llvm_cmdline: StaticCow<str>,
1322 /// Don't use this field; instead use the `.min_atomic_width()` method.
1323 pub min_atomic_width: Option<u64>,
1325 /// Don't use this field; instead use the `.max_atomic_width()` method.
1326 pub max_atomic_width: Option<u64>,
1328 /// Whether the target supports atomic CAS operations natively
1329 pub atomic_cas: bool,
1331 /// Panic strategy: "unwind" or "abort"
1332 pub panic_strategy: PanicStrategy,
1334 /// Whether or not linking dylibs to a static CRT is allowed.
1335 pub crt_static_allows_dylibs: bool,
1336 /// Whether or not the CRT is statically linked by default.
1337 pub crt_static_default: bool,
1338 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1339 pub crt_static_respected: bool,
1341 /// The implementation of stack probes to use.
1342 pub stack_probes: StackProbeType,
1344 /// The minimum alignment for global symbols.
1345 pub min_global_align: Option<u64>,
1347 /// Default number of codegen units to use in debug mode
1348 pub default_codegen_units: Option<u64>,
1350 /// Whether to generate trap instructions in places where optimization would
1351 /// otherwise produce control flow that falls through into unrelated memory.
1352 pub trap_unreachable: bool,
1354 /// This target requires everything to be compiled with LTO to emit a final
1355 /// executable, aka there is no native linker for this target.
1356 pub requires_lto: bool,
1358 /// This target has no support for threads.
1359 pub singlethread: bool,
1361 /// Whether library functions call lowering/optimization is disabled in LLVM
1362 /// for this target unconditionally.
1363 pub no_builtins: bool,
1365 /// The default visibility for symbols in this target should be "hidden"
1366 /// rather than "default"
1367 pub default_hidden_visibility: bool,
1369 /// Whether a .debug_gdb_scripts section will be added to the output object file
1370 pub emit_debug_gdb_scripts: bool,
1372 /// Whether or not to unconditionally `uwtable` attributes on functions,
1373 /// typically because the platform needs to unwind for things like stack
1375 pub requires_uwtable: bool,
1377 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1378 /// is not specified and `uwtable` is not required on this target.
1379 pub default_uwtable: bool,
1381 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1382 /// typically required if a target can be compiled with a mixed set of
1383 /// target features. This is `true` by default, and `false` for targets like
1384 /// wasm32 where the whole program either has simd or not.
1385 pub simd_types_indirect: bool,
1387 /// Pass a list of symbol which should be exported in the dylib to the linker.
1388 pub limit_rdylib_exports: bool,
1390 /// If set, have the linker export exactly these symbols, instead of using
1391 /// the usual logic to figure this out from the crate itself.
1392 pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1394 /// Determines how or whether the MergeFunctions LLVM pass should run for
1395 /// this target. Either "disabled", "trampolines", or "aliases".
1396 /// The MergeFunctions pass is generally useful, but some targets may need
1397 /// to opt out. The default is "aliases".
1399 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1400 pub merge_functions: MergeFunctions,
1402 /// Use platform dependent mcount function
1403 pub mcount: StaticCow<str>,
1405 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1406 pub llvm_abiname: StaticCow<str>,
1408 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1409 pub relax_elf_relocations: bool,
1411 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1412 pub llvm_args: StaticCow<[StaticCow<str>]>,
1414 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1415 /// to false (uses .init_array).
1416 pub use_ctors_section: bool,
1418 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1419 /// used to locate unwinding information is passed
1420 /// (only has effect if the linker is `ld`-like).
1421 pub eh_frame_header: bool,
1423 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1424 /// thumb and arm interworking.
1425 pub has_thumb_interworking: bool,
1427 /// How to handle split debug information, if at all. Specifying `None` has
1428 /// target-specific meaning.
1429 pub split_debuginfo: SplitDebuginfo,
1431 /// The sanitizers supported by this target
1433 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1434 /// enabled can generated on this target, but the necessary supporting libraries are not
1435 /// distributed with the target, the sanitizer should still appear in this list for the target.
1436 pub supported_sanitizers: SanitizerSet,
1438 /// If present it's a default value to use for adjusting the C ABI.
1439 pub default_adjusted_cabi: Option<Abi>,
1441 /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1442 pub c_enum_min_bits: u64,
1444 /// Whether or not the DWARF `.debug_aranges` section should be generated.
1445 pub generate_arange_section: bool,
1447 /// Whether the target supports stack canary checks. `true` by default,
1448 /// since this is most common among tier 1 and tier 2 targets.
1449 pub supports_stack_protector: bool,
1452 impl Default for TargetOptions {
1453 /// Creates a set of "sane defaults" for any target. This is still
1454 /// incomplete, and if used for compilation, will certainly not work.
1455 fn default() -> TargetOptions {
1458 endian: Endian::Little,
1459 c_int_width: "32".into(),
1463 vendor: "unknown".into(),
1464 linker_flavor: LinkerFlavor::Gcc,
1465 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1466 lld_flavor: LldFlavor::Ld,
1467 pre_link_args: LinkArgs::new(),
1468 post_link_args: LinkArgs::new(),
1471 cpu: "generic".into(),
1472 features: "".into(),
1473 dynamic_linking: false,
1476 relocation_model: RelocModel::Pic,
1478 tls_model: TlsModel::GeneralDynamic,
1479 disable_redzone: false,
1480 frame_pointer: FramePointer::MayOmit,
1481 function_sections: true,
1482 dll_prefix: "lib".into(),
1483 dll_suffix: ".so".into(),
1484 exe_suffix: "".into(),
1485 staticlib_prefix: "lib".into(),
1486 staticlib_suffix: ".a".into(),
1488 abi_return_struct_as_int: false,
1490 is_like_solaris: false,
1491 is_like_windows: false,
1492 is_like_emscripten: false,
1493 is_like_msvc: false,
1494 is_like_fuchsia: false,
1495 is_like_wasm: false,
1496 dwarf_version: None,
1497 linker_is_gnu: true,
1498 allows_weak_linkage: true,
1500 no_default_libraries: true,
1501 position_independent_executables: false,
1502 static_position_independent_executables: false,
1504 relro_level: RelroLevel::None,
1505 pre_link_objects: Default::default(),
1506 post_link_objects: Default::default(),
1507 pre_link_objects_fallback: Default::default(),
1508 post_link_objects_fallback: Default::default(),
1509 crt_objects_fallback: None,
1510 late_link_args: LinkArgs::new(),
1511 late_link_args_dynamic: LinkArgs::new(),
1512 late_link_args_static: LinkArgs::new(),
1514 link_env_remove: cvs![],
1515 archive_format: "gnu".into(),
1516 main_needs_argc_argv: true,
1518 has_thread_local: false,
1519 obj_is_bitcode: false,
1520 forces_embed_bitcode: false,
1521 bitcode_llvm_cmdline: "".into(),
1522 min_atomic_width: None,
1523 max_atomic_width: None,
1525 panic_strategy: PanicStrategy::Unwind,
1526 crt_static_allows_dylibs: false,
1527 crt_static_default: false,
1528 crt_static_respected: false,
1529 stack_probes: StackProbeType::None,
1530 min_global_align: None,
1531 default_codegen_units: None,
1532 trap_unreachable: true,
1533 requires_lto: false,
1534 singlethread: false,
1536 default_hidden_visibility: false,
1537 emit_debug_gdb_scripts: true,
1538 requires_uwtable: false,
1539 default_uwtable: false,
1540 simd_types_indirect: true,
1541 limit_rdylib_exports: true,
1542 override_export_symbols: None,
1543 merge_functions: MergeFunctions::Aliases,
1544 mcount: "mcount".into(),
1545 llvm_abiname: "".into(),
1546 relax_elf_relocations: false,
1548 use_ctors_section: false,
1549 eh_frame_header: true,
1550 has_thumb_interworking: false,
1551 split_debuginfo: SplitDebuginfo::Off,
1552 supported_sanitizers: SanitizerSet::empty(),
1553 default_adjusted_cabi: None,
1554 c_enum_min_bits: 32,
1555 generate_arange_section: true,
1556 supports_stack_protector: true,
1561 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1562 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1563 /// this `Deref` implementation is no longer necessary.
1564 impl Deref for Target {
1565 type Target = TargetOptions;
1568 fn deref(&self) -> &Self::Target {
1572 impl DerefMut for Target {
1574 fn deref_mut(&mut self) -> &mut Self::Target {
1580 /// Given a function ABI, turn it into the correct ABI for this target.
1581 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1583 Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1584 Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1585 Abi::Stdcall { unwind }
1587 Abi::System { unwind } => Abi::C { unwind },
1588 Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1589 Abi::EfiApi => Abi::C { unwind: false },
1591 // See commentary in `is_abi_supported`.
1592 Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1593 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1594 Abi::Fastcall { .. } if self.arch == "x86" => abi,
1595 Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1596 Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1602 /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1603 pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1615 X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1616 Aapcs { .. } => "arm" == self.arch,
1617 CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1618 Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1619 PtxKernel => self.arch == "nvptx64",
1620 Msp430Interrupt => self.arch == "msp430",
1621 AmdGpuKernel => self.arch == "amdgcn",
1622 AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1623 Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1624 Thiscall { .. } => self.arch == "x86",
1625 // On windows these fall-back to platform native calling convention (C) when the
1626 // architecture is not supported.
1628 // This is I believe a historical accident that has occurred as part of Microsoft
1629 // striving to allow most of the code to "just" compile when support for 64-bit x86
1630 // was added and then later again, when support for ARM architectures was added.
1632 // This is well documented across MSDN. Support for this in Rust has been added in
1633 // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1634 // Rust, but there isn't much leeway remaining here to change it back at the time this
1635 // comment has been written.
1637 // Following are the relevant excerpts from the MSDN documentation.
1639 // > The __vectorcall calling convention is only supported in native code on x86 and
1640 // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1642 // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1644 // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1646 // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1648 // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1650 // > In most cases, keywords or compiler switches that specify an unsupported
1651 // > convention on a particular platform are ignored, and the platform default
1652 // > convention is used.
1654 // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1655 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1656 // Outside of Windows we want to only support these calling conventions for the
1657 // architectures for which these calling conventions are actually well defined.
1658 Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1659 Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1660 // Return a `None` for other cases so that we know to emit a future compat lint.
1661 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1665 /// Minimum integer size in bits that this target can perform atomic
1667 pub fn min_atomic_width(&self) -> u64 {
1668 self.min_atomic_width.unwrap_or(8)
1671 /// Maximum integer size in bits that this target can perform atomic
1673 pub fn max_atomic_width(&self) -> u64 {
1674 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1677 /// Loads a target descriptor from a JSON object.
1678 pub fn from_json(mut obj: Json) -> Result<(Target, TargetWarnings), String> {
1679 // While ugly, this code must remain this way to retain
1680 // compatibility with existing JSON fields and the internal
1681 // expected naming of the Target and TargetOptions structs.
1682 // To ensure compatibility is retained, the built-in targets
1683 // are round-tripped through this code to catch cases where
1684 // the JSON parser is not updated to match the structs.
1686 let mut get_req_field = |name: &str| {
1687 obj.remove_key(name)
1688 .and_then(|j| Json::as_string(&j).map(str::to_string))
1689 .ok_or_else(|| format!("Field {} in target specification is required", name))
1692 let mut base = Target {
1693 llvm_target: get_req_field("llvm-target")?.into(),
1694 pointer_width: get_req_field("target-pointer-width")?
1696 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1697 data_layout: get_req_field("data-layout")?.into(),
1698 arch: get_req_field("arch")?.into(),
1699 options: Default::default(),
1702 let mut incorrect_type = vec![];
1705 ($key_name:ident) => ( {
1706 let name = (stringify!($key_name)).replace("_", "-");
1707 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string).map(Cow::from)) {
1711 ($key_name:ident = $json_name:expr) => ( {
1712 let name = $json_name;
1713 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string).map(Cow::from)) {
1717 ($key_name:ident, bool) => ( {
1718 let name = (stringify!($key_name)).replace("_", "-");
1719 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_boolean(&j)) {
1723 ($key_name:ident, u64) => ( {
1724 let name = (stringify!($key_name)).replace("_", "-");
1725 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1729 ($key_name:ident, Option<u32>) => ( {
1730 let name = (stringify!($key_name)).replace("_", "-");
1731 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1733 return Err("Not a valid DWARF version number".into());
1735 base.$key_name = Some(s as u32);
1738 ($key_name:ident, Option<u64>) => ( {
1739 let name = (stringify!($key_name)).replace("_", "-");
1740 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1741 base.$key_name = Some(s);
1744 ($key_name:ident, MergeFunctions) => ( {
1745 let name = (stringify!($key_name)).replace("_", "-");
1746 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1747 match s.parse::<MergeFunctions>() {
1748 Ok(mergefunc) => base.$key_name = mergefunc,
1749 _ => return Some(Err(format!("'{}' is not a valid value for \
1750 merge-functions. Use 'disabled', \
1751 'trampolines', or 'aliases'.",
1755 })).unwrap_or(Ok(()))
1757 ($key_name:ident, RelocModel) => ( {
1758 let name = (stringify!($key_name)).replace("_", "-");
1759 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1760 match s.parse::<RelocModel>() {
1761 Ok(relocation_model) => base.$key_name = relocation_model,
1762 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1763 Run `rustc --print relocation-models` to \
1764 see the list of supported values.", s))),
1767 })).unwrap_or(Ok(()))
1769 ($key_name:ident, CodeModel) => ( {
1770 let name = (stringify!($key_name)).replace("_", "-");
1771 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1772 match s.parse::<CodeModel>() {
1773 Ok(code_model) => base.$key_name = Some(code_model),
1774 _ => return Some(Err(format!("'{}' is not a valid code model. \
1775 Run `rustc --print code-models` to \
1776 see the list of supported values.", s))),
1779 })).unwrap_or(Ok(()))
1781 ($key_name:ident, TlsModel) => ( {
1782 let name = (stringify!($key_name)).replace("_", "-");
1783 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1784 match s.parse::<TlsModel>() {
1785 Ok(tls_model) => base.$key_name = tls_model,
1786 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1787 Run `rustc --print tls-models` to \
1788 see the list of supported values.", s))),
1791 })).unwrap_or(Ok(()))
1793 ($key_name:ident, PanicStrategy) => ( {
1794 let name = (stringify!($key_name)).replace("_", "-");
1795 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1797 "unwind" => base.$key_name = PanicStrategy::Unwind,
1798 "abort" => base.$key_name = PanicStrategy::Abort,
1799 _ => return Some(Err(format!("'{}' is not a valid value for \
1800 panic-strategy. Use 'unwind' or 'abort'.",
1804 })).unwrap_or(Ok(()))
1806 ($key_name:ident, RelroLevel) => ( {
1807 let name = (stringify!($key_name)).replace("_", "-");
1808 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1809 match s.parse::<RelroLevel>() {
1810 Ok(level) => base.$key_name = level,
1811 _ => return Some(Err(format!("'{}' is not a valid value for \
1812 relro-level. Use 'full', 'partial, or 'off'.",
1816 })).unwrap_or(Ok(()))
1818 ($key_name:ident, SplitDebuginfo) => ( {
1819 let name = (stringify!($key_name)).replace("_", "-");
1820 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1821 match s.parse::<SplitDebuginfo>() {
1822 Ok(level) => base.$key_name = level,
1823 _ => return Some(Err(format!("'{}' is not a valid value for \
1824 split-debuginfo. Use 'off' or 'dsymutil'.",
1828 })).unwrap_or(Ok(()))
1830 ($key_name:ident, list) => ( {
1831 let name = (stringify!($key_name)).replace("_", "-");
1832 if let Some(j) = obj.remove_key(&name){
1833 if let Some(v) = Json::as_array(&j) {
1834 base.$key_name = v.iter()
1835 .map(|a| a.as_string().unwrap().to_string().into())
1838 incorrect_type.push(name)
1842 ($key_name:ident, opt_list) => ( {
1843 let name = (stringify!($key_name)).replace("_", "-");
1844 if let Some(j) = obj.remove_key(&name) {
1845 if let Some(v) = Json::as_array(&j) {
1846 base.$key_name = Some(v.iter()
1847 .map(|a| a.as_string().unwrap().to_string().into())
1850 incorrect_type.push(name)
1854 ($key_name:ident, optional) => ( {
1855 let name = (stringify!($key_name)).replace("_", "-");
1856 if let Some(o) = obj.remove_key(&name[..]) {
1859 .map(|s| s.to_string().into());
1862 ($key_name:ident, LldFlavor) => ( {
1863 let name = (stringify!($key_name)).replace("_", "-");
1864 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1865 if let Some(flavor) = LldFlavor::from_str(&s) {
1866 base.$key_name = flavor;
1868 return Some(Err(format!(
1869 "'{}' is not a valid value for lld-flavor. \
1870 Use 'darwin', 'gnu', 'link' or 'wasm.",
1874 })).unwrap_or(Ok(()))
1876 ($key_name:ident, LinkerFlavor) => ( {
1877 let name = (stringify!($key_name)).replace("_", "-");
1878 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1879 match LinkerFlavor::from_str(s) {
1880 Some(linker_flavor) => base.$key_name = linker_flavor,
1881 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1882 Use {}", s, LinkerFlavor::one_of()))),
1885 })).unwrap_or(Ok(()))
1887 ($key_name:ident, StackProbeType) => ( {
1888 let name = (stringify!($key_name)).replace("_", "-");
1889 obj.remove_key(&name[..]).and_then(|o| match StackProbeType::from_json(&o) {
1895 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1897 }).unwrap_or(Ok(()))
1899 ($key_name:ident, SanitizerSet) => ( {
1900 let name = (stringify!($key_name)).replace("_", "-");
1901 if let Some(o) = obj.remove_key(&name[..]) {
1902 if let Some(a) = o.as_array() {
1904 base.$key_name |= match s.as_string() {
1905 Some("address") => SanitizerSet::ADDRESS,
1906 Some("cfi") => SanitizerSet::CFI,
1907 Some("leak") => SanitizerSet::LEAK,
1908 Some("memory") => SanitizerSet::MEMORY,
1909 Some("memtag") => SanitizerSet::MEMTAG,
1910 Some("thread") => SanitizerSet::THREAD,
1911 Some("hwaddress") => SanitizerSet::HWADDRESS,
1912 Some(s) => return Err(format!("unknown sanitizer {}", s)),
1913 _ => return Err(format!("not a string: {:?}", s)),
1917 incorrect_type.push(name)
1920 Ok::<(), String>(())
1923 ($key_name:ident, crt_objects_fallback) => ( {
1924 let name = (stringify!($key_name)).replace("_", "-");
1925 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1926 match s.parse::<CrtObjectsFallback>() {
1927 Ok(fallback) => base.$key_name = Some(fallback),
1928 _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1929 Use 'musl', 'mingw' or 'wasm'", s))),
1932 })).unwrap_or(Ok(()))
1934 ($key_name:ident, link_objects) => ( {
1935 let name = (stringify!($key_name)).replace("_", "-");
1936 if let Some(val) = obj.remove_key(&name[..]) {
1937 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1938 JSON object with fields per CRT object kind.", name))?;
1939 let mut args = CrtObjects::new();
1941 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1942 format!("{}: '{}' is not a valid value for CRT object kind. \
1943 Use '(dynamic,static)-(nopic,pic)-exe' or \
1944 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1947 let v = v.as_array().ok_or_else(||
1948 format!("{}.{}: expected a JSON array", name, k)
1949 )?.iter().enumerate()
1951 let s = s.as_string().ok_or_else(||
1952 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1953 Ok(s.to_string().into())
1955 .collect::<Result<Vec<_>, String>>()?;
1957 args.insert(kind, v);
1959 base.$key_name = args;
1962 ($key_name:ident, link_args) => ( {
1963 let name = (stringify!($key_name)).replace("_", "-");
1964 if let Some(val) = obj.remove_key(&name[..]) {
1965 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1966 JSON object with fields per linker-flavor.", name))?;
1967 let mut args = LinkArgs::new();
1969 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1970 format!("{}: '{}' is not a valid value for linker-flavor. \
1971 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1974 let v = v.as_array().ok_or_else(||
1975 format!("{}.{}: expected a JSON array", name, k)
1976 )?.iter().enumerate()
1978 let s = s.as_string().ok_or_else(||
1979 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1980 Ok(s.to_string().into())
1982 .collect::<Result<Vec<_>, String>>()?;
1984 args.insert(flavor, v);
1986 base.$key_name = args;
1989 ($key_name:ident, env) => ( {
1990 let name = (stringify!($key_name)).replace("_", "-");
1991 if let Some(o) = obj.remove_key(&name[..]) {
1992 if let Some(a) = o.as_array() {
1994 if let Some(s) = o.as_string() {
1995 let p = s.split('=').collect::<Vec<_>>();
1997 let k = p[0].to_string();
1998 let v = p[1].to_string();
1999 base.$key_name.to_mut().push((k.into(), v.into()));
2004 incorrect_type.push(name)
2008 ($key_name:ident, Option<Abi>) => ( {
2009 let name = (stringify!($key_name)).replace("_", "-");
2010 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
2011 match lookup_abi(s) {
2012 Some(abi) => base.$key_name = Some(abi),
2013 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2016 })).unwrap_or(Ok(()))
2018 ($key_name:ident, TargetFamilies) => ( {
2019 if let Some(value) = obj.remove_key("target-family") {
2020 if let Some(v) = Json::as_array(&value) {
2021 base.$key_name = v.iter()
2022 .map(|a| a.as_string().unwrap().to_string().into())
2024 } else if let Some(v) = Json::as_string(&value) {
2025 base.$key_name = vec![v.to_string().into()].into();
2031 if let Some(j) = obj.remove_key("target-endian") {
2032 if let Some(s) = Json::as_string(&j) {
2033 base.endian = s.parse()?;
2035 incorrect_type.push("target-endian".into())
2039 if let Some(fp) = obj.remove_key("frame-pointer") {
2040 if let Some(s) = Json::as_string(&fp) {
2041 base.frame_pointer = s
2043 .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2045 incorrect_type.push("frame-pointer".into())
2049 key!(is_builtin, bool);
2050 key!(c_int_width = "target-c-int-width");
2055 key!(linker_flavor, LinkerFlavor)?;
2056 key!(linker, optional);
2057 key!(lld_flavor, LldFlavor)?;
2058 key!(pre_link_objects, link_objects);
2059 key!(post_link_objects, link_objects);
2060 key!(pre_link_objects_fallback, link_objects);
2061 key!(post_link_objects_fallback, link_objects);
2062 key!(crt_objects_fallback, crt_objects_fallback)?;
2063 key!(pre_link_args, link_args);
2064 key!(late_link_args, link_args);
2065 key!(late_link_args_dynamic, link_args);
2066 key!(late_link_args_static, link_args);
2067 key!(post_link_args, link_args);
2068 key!(link_script, optional);
2069 key!(link_env, env);
2070 key!(link_env_remove, list);
2071 key!(asm_args, list);
2074 key!(dynamic_linking, bool);
2075 key!(only_cdylib, bool);
2076 key!(executables, bool);
2077 key!(relocation_model, RelocModel)?;
2078 key!(code_model, CodeModel)?;
2079 key!(tls_model, TlsModel)?;
2080 key!(disable_redzone, bool);
2081 key!(function_sections, bool);
2085 key!(staticlib_prefix);
2086 key!(staticlib_suffix);
2087 key!(families, TargetFamilies);
2088 key!(abi_return_struct_as_int, bool);
2089 key!(is_like_osx, bool);
2090 key!(is_like_solaris, bool);
2091 key!(is_like_windows, bool);
2092 key!(is_like_msvc, bool);
2093 key!(is_like_emscripten, bool);
2094 key!(is_like_fuchsia, bool);
2095 key!(is_like_wasm, bool);
2096 key!(dwarf_version, Option<u32>);
2097 key!(linker_is_gnu, bool);
2098 key!(allows_weak_linkage, bool);
2099 key!(has_rpath, bool);
2100 key!(no_default_libraries, bool);
2101 key!(position_independent_executables, bool);
2102 key!(static_position_independent_executables, bool);
2103 key!(needs_plt, bool);
2104 key!(relro_level, RelroLevel)?;
2105 key!(archive_format);
2106 key!(allow_asm, bool);
2107 key!(main_needs_argc_argv, bool);
2108 key!(has_thread_local, bool);
2109 key!(obj_is_bitcode, bool);
2110 key!(forces_embed_bitcode, bool);
2111 key!(bitcode_llvm_cmdline);
2112 key!(max_atomic_width, Option<u64>);
2113 key!(min_atomic_width, Option<u64>);
2114 key!(atomic_cas, bool);
2115 key!(panic_strategy, PanicStrategy)?;
2116 key!(crt_static_allows_dylibs, bool);
2117 key!(crt_static_default, bool);
2118 key!(crt_static_respected, bool);
2119 key!(stack_probes, StackProbeType)?;
2120 key!(min_global_align, Option<u64>);
2121 key!(default_codegen_units, Option<u64>);
2122 key!(trap_unreachable, bool);
2123 key!(requires_lto, bool);
2124 key!(singlethread, bool);
2125 key!(no_builtins, bool);
2126 key!(default_hidden_visibility, bool);
2127 key!(emit_debug_gdb_scripts, bool);
2128 key!(requires_uwtable, bool);
2129 key!(default_uwtable, bool);
2130 key!(simd_types_indirect, bool);
2131 key!(limit_rdylib_exports, bool);
2132 key!(override_export_symbols, opt_list);
2133 key!(merge_functions, MergeFunctions)?;
2134 key!(mcount = "target-mcount");
2136 key!(relax_elf_relocations, bool);
2137 key!(llvm_args, list);
2138 key!(use_ctors_section, bool);
2139 key!(eh_frame_header, bool);
2140 key!(has_thumb_interworking, bool);
2141 key!(split_debuginfo, SplitDebuginfo)?;
2142 key!(supported_sanitizers, SanitizerSet)?;
2143 key!(default_adjusted_cabi, Option<Abi>)?;
2144 key!(c_enum_min_bits, u64);
2145 key!(generate_arange_section, bool);
2146 key!(supports_stack_protector, bool);
2148 if base.is_builtin {
2149 // This can cause unfortunate ICEs later down the line.
2150 return Err("may not set is_builtin for targets not built-in".into());
2152 // Each field should have been read using `Json::remove_key` so any keys remaining are unused.
2153 let remaining_keys = obj.as_object().ok_or("Expected JSON object for target")?.keys();
2156 TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2160 /// Load a built-in target
2161 pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2162 match *target_triple {
2163 TargetTriple::TargetTriple(ref target_triple) => {
2164 load_builtin(target_triple).expect("built-in target")
2166 TargetTriple::TargetPath(..) => {
2167 panic!("built-in targets doens't support target-paths")
2172 /// Search for a JSON file specifying the given target triple.
2174 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2175 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
2176 /// bare filename already, so also check for that. If one of the hardcoded targets we know
2177 /// about, just return it directly.
2179 /// The error string could come from any of the APIs called, including filesystem access and
2182 target_triple: &TargetTriple,
2184 ) -> Result<(Target, TargetWarnings), String> {
2185 use rustc_serialize::json;
2189 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2190 let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2191 let obj = json::from_str(&contents).map_err(|e| e.to_string())?;
2192 Target::from_json(obj)
2195 match *target_triple {
2196 TargetTriple::TargetTriple(ref target_triple) => {
2197 // check if triple is in list of built-in targets
2198 if let Some(t) = load_builtin(target_triple) {
2199 return Ok((t, TargetWarnings::empty()));
2202 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2204 let mut target = target_triple.to_string();
2205 target.push_str(".json");
2206 PathBuf::from(target)
2209 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2211 for dir in env::split_paths(&target_path) {
2212 let p = dir.join(&path);
2214 return load_file(&p);
2218 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2220 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2221 let p = PathBuf::from_iter([
2223 Path::new(&rustlib_path),
2224 Path::new("target.json"),
2227 return load_file(&p);
2230 Err(format!("Could not find specification for target {:?}", target_triple))
2232 TargetTriple::TargetPath(ref target_path) => {
2233 if target_path.is_file() {
2234 return load_file(&target_path);
2236 Err(format!("Target path {:?} is not a valid file", target_path))
2242 impl ToJson for Target {
2243 fn to_json(&self) -> Json {
2244 let mut d = BTreeMap::new();
2245 let default: TargetOptions = Default::default();
2247 macro_rules! target_val {
2249 let name = (stringify!($attr)).replace("_", "-");
2250 d.insert(name, self.$attr.to_json());
2252 ($attr:ident, $key_name:expr) => {{
2253 let name = $key_name;
2254 d.insert(name.into(), self.$attr.to_json());
2258 macro_rules! target_option_val {
2260 let name = (stringify!($attr)).replace("_", "-");
2261 if default.$attr != self.$attr {
2262 d.insert(name, self.$attr.to_json());
2265 ($attr:ident, $key_name:expr) => {{
2266 let name = $key_name;
2267 if default.$attr != self.$attr {
2268 d.insert(name.into(), self.$attr.to_json());
2271 (link_args - $attr:ident) => {{
2272 let name = (stringify!($attr)).replace("_", "-");
2273 if default.$attr != self.$attr {
2277 .map(|(k, v)| (k.desc().to_string(), v.clone()))
2278 .collect::<BTreeMap<_, _>>();
2279 d.insert(name, obj.to_json());
2282 (env - $attr:ident) => {{
2283 let name = (stringify!($attr)).replace("_", "-");
2284 if default.$attr != self.$attr {
2288 .map(|&(ref k, ref v)| format!("{k}={v}"))
2289 .collect::<Vec<_>>();
2290 d.insert(name, obj.to_json());
2295 target_val!(llvm_target);
2296 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2298 target_val!(data_layout);
2300 target_option_val!(is_builtin);
2301 target_option_val!(endian, "target-endian");
2302 target_option_val!(c_int_width, "target-c-int-width");
2303 target_option_val!(os);
2304 target_option_val!(env);
2305 target_option_val!(abi);
2306 target_option_val!(vendor);
2307 target_option_val!(linker_flavor);
2308 target_option_val!(linker);
2309 target_option_val!(lld_flavor);
2310 target_option_val!(pre_link_objects);
2311 target_option_val!(post_link_objects);
2312 target_option_val!(pre_link_objects_fallback);
2313 target_option_val!(post_link_objects_fallback);
2314 target_option_val!(crt_objects_fallback);
2315 target_option_val!(link_args - pre_link_args);
2316 target_option_val!(link_args - late_link_args);
2317 target_option_val!(link_args - late_link_args_dynamic);
2318 target_option_val!(link_args - late_link_args_static);
2319 target_option_val!(link_args - post_link_args);
2320 target_option_val!(link_script);
2321 target_option_val!(env - link_env);
2322 target_option_val!(link_env_remove);
2323 target_option_val!(asm_args);
2324 target_option_val!(cpu);
2325 target_option_val!(features);
2326 target_option_val!(dynamic_linking);
2327 target_option_val!(only_cdylib);
2328 target_option_val!(executables);
2329 target_option_val!(relocation_model);
2330 target_option_val!(code_model);
2331 target_option_val!(tls_model);
2332 target_option_val!(disable_redzone);
2333 target_option_val!(frame_pointer);
2334 target_option_val!(function_sections);
2335 target_option_val!(dll_prefix);
2336 target_option_val!(dll_suffix);
2337 target_option_val!(exe_suffix);
2338 target_option_val!(staticlib_prefix);
2339 target_option_val!(staticlib_suffix);
2340 target_option_val!(families, "target-family");
2341 target_option_val!(abi_return_struct_as_int);
2342 target_option_val!(is_like_osx);
2343 target_option_val!(is_like_solaris);
2344 target_option_val!(is_like_windows);
2345 target_option_val!(is_like_msvc);
2346 target_option_val!(is_like_emscripten);
2347 target_option_val!(is_like_fuchsia);
2348 target_option_val!(is_like_wasm);
2349 target_option_val!(dwarf_version);
2350 target_option_val!(linker_is_gnu);
2351 target_option_val!(allows_weak_linkage);
2352 target_option_val!(has_rpath);
2353 target_option_val!(no_default_libraries);
2354 target_option_val!(position_independent_executables);
2355 target_option_val!(static_position_independent_executables);
2356 target_option_val!(needs_plt);
2357 target_option_val!(relro_level);
2358 target_option_val!(archive_format);
2359 target_option_val!(allow_asm);
2360 target_option_val!(main_needs_argc_argv);
2361 target_option_val!(has_thread_local);
2362 target_option_val!(obj_is_bitcode);
2363 target_option_val!(forces_embed_bitcode);
2364 target_option_val!(bitcode_llvm_cmdline);
2365 target_option_val!(min_atomic_width);
2366 target_option_val!(max_atomic_width);
2367 target_option_val!(atomic_cas);
2368 target_option_val!(panic_strategy);
2369 target_option_val!(crt_static_allows_dylibs);
2370 target_option_val!(crt_static_default);
2371 target_option_val!(crt_static_respected);
2372 target_option_val!(stack_probes);
2373 target_option_val!(min_global_align);
2374 target_option_val!(default_codegen_units);
2375 target_option_val!(trap_unreachable);
2376 target_option_val!(requires_lto);
2377 target_option_val!(singlethread);
2378 target_option_val!(no_builtins);
2379 target_option_val!(default_hidden_visibility);
2380 target_option_val!(emit_debug_gdb_scripts);
2381 target_option_val!(requires_uwtable);
2382 target_option_val!(default_uwtable);
2383 target_option_val!(simd_types_indirect);
2384 target_option_val!(limit_rdylib_exports);
2385 target_option_val!(override_export_symbols);
2386 target_option_val!(merge_functions);
2387 target_option_val!(mcount, "target-mcount");
2388 target_option_val!(llvm_abiname);
2389 target_option_val!(relax_elf_relocations);
2390 target_option_val!(llvm_args);
2391 target_option_val!(use_ctors_section);
2392 target_option_val!(eh_frame_header);
2393 target_option_val!(has_thumb_interworking);
2394 target_option_val!(split_debuginfo);
2395 target_option_val!(supported_sanitizers);
2396 target_option_val!(c_enum_min_bits);
2397 target_option_val!(generate_arange_section);
2398 target_option_val!(supports_stack_protector);
2400 if let Some(abi) = self.default_adjusted_cabi {
2401 d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2408 /// Either a target triple string or a path to a JSON file.
2409 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2410 pub enum TargetTriple {
2411 TargetTriple(String),
2412 TargetPath(PathBuf),
2416 /// Creates a target triple from the passed target triple string.
2417 pub fn from_triple(triple: &str) -> Self {
2418 TargetTriple::TargetTriple(triple.into())
2421 /// Creates a target triple from the passed target path.
2422 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2423 let canonicalized_path = path.canonicalize()?;
2424 Ok(TargetTriple::TargetPath(canonicalized_path))
2427 /// Returns a string triple for this target.
2429 /// If this target is a path, the file name (without extension) is returned.
2430 pub fn triple(&self) -> &str {
2432 TargetTriple::TargetTriple(ref triple) => triple,
2433 TargetTriple::TargetPath(ref path) => path
2435 .expect("target path must not be empty")
2437 .expect("target path must be valid unicode"),
2441 /// Returns an extended string triple for this target.
2443 /// If this target is a path, a hash of the path is appended to the triple returned
2445 pub fn debug_triple(&self) -> String {
2446 use std::collections::hash_map::DefaultHasher;
2447 use std::hash::{Hash, Hasher};
2449 let triple = self.triple();
2450 if let TargetTriple::TargetPath(ref path) = *self {
2451 let mut hasher = DefaultHasher::new();
2452 path.hash(&mut hasher);
2453 let hash = hasher.finish();
2454 format!("{}-{}", triple, hash)
2461 impl fmt::Display for TargetTriple {
2462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2463 write!(f, "{}", self.debug_triple())