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};
43 use std::collections::BTreeMap;
44 use std::convert::TryFrom;
45 use std::iter::FromIterator;
46 use std::ops::{Deref, DerefMut};
47 use std::path::{Path, PathBuf};
48 use std::str::FromStr;
51 use rustc_macros::HashStable_Generic;
66 mod hermit_kernel_base;
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<String>>;
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 ("aarch64-unknown-none-hermitkernel", aarch64_unknown_none_hermitkernel),
975 ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
977 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
978 ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
979 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
980 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
981 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
982 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
983 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
984 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
985 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
986 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
987 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
989 ("aarch64-unknown-none", aarch64_unknown_none),
990 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
992 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
994 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
995 ("i686-unknown-uefi", i686_unknown_uefi),
996 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
998 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1000 ("i686-wrs-vxworks", i686_wrs_vxworks),
1001 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1002 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1003 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1004 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1005 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1006 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1008 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1009 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1010 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1012 ("mipsel-sony-psp", mipsel_sony_psp),
1013 ("mipsel-unknown-none", mipsel_unknown_none),
1014 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1016 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1017 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1018 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1020 ("bpfeb-unknown-none", bpfeb_unknown_none),
1021 ("bpfel-unknown-none", bpfel_unknown_none),
1023 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1025 ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1026 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1028 ("x86_64-unknown-none", x86_64_unknown_none),
1030 ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1033 /// Warnings encountered when parsing the target `json`.
1035 /// Includes fields that weren't recognized and fields that don't have the expected type.
1036 #[derive(Debug, PartialEq)]
1037 pub struct TargetWarnings {
1038 unused_fields: Vec<String>,
1039 incorrect_type: Vec<String>,
1042 impl TargetWarnings {
1043 pub fn empty() -> Self {
1044 Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1047 pub fn warning_messages(&self) -> Vec<String> {
1048 let mut warnings = vec![];
1049 if !self.unused_fields.is_empty() {
1050 warnings.push(format!(
1051 "target json file contains unused fields: {}",
1052 self.unused_fields.join(", ")
1055 if !self.incorrect_type.is_empty() {
1056 warnings.push(format!(
1057 "target json file contains fields whose value doesn't have the correct json type: {}",
1058 self.incorrect_type.join(", ")
1065 /// Everything `rustc` knows about how to compile for a specific target.
1067 /// Every field here must be specified, and has no default value.
1068 #[derive(PartialEq, Clone, Debug)]
1070 /// Target triple to pass to LLVM.
1071 pub llvm_target: String,
1072 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1073 pub pointer_width: u32,
1074 /// Architecture to use for ABI considerations. Valid options include: "x86",
1075 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1077 /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1078 pub data_layout: String,
1079 /// Optional settings with defaults.
1080 pub options: TargetOptions,
1083 pub trait HasTargetSpec {
1084 fn target_spec(&self) -> &Target;
1087 impl HasTargetSpec for Target {
1089 fn target_spec(&self) -> &Target {
1094 /// Optional aspects of a target specification.
1096 /// This has an implementation of `Default`, see each field for what the default is. In general,
1097 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1099 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1100 /// construction, all its fields logically belong to `Target` and available from `Target`
1101 /// through `Deref` impls.
1102 #[derive(PartialEq, Clone, Debug)]
1103 pub struct TargetOptions {
1104 /// Whether the target is built-in or loaded from a custom target specification.
1105 pub is_builtin: bool,
1107 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1109 /// Width of c_int type. Defaults to "32".
1110 pub c_int_width: String,
1111 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1112 /// "none" implies a bare metal target without `std` library.
1113 /// A couple of targets having `std` also use "unknown" as an `os` value,
1114 /// but they are exceptions.
1116 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1118 /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1119 /// or `"eabihf"`. Defaults to "".
1121 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1123 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1124 /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1125 pub linker_flavor: LinkerFlavor,
1127 /// Linker to invoke
1128 pub linker: Option<String>,
1130 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1131 /// without clarifying its flavor in any way.
1132 pub lld_flavor: LldFlavor,
1134 /// Linker arguments that are passed *before* any user-defined libraries.
1135 pub pre_link_args: LinkArgs,
1136 /// Objects to link before and after all other object code.
1137 pub pre_link_objects: CrtObjects,
1138 pub post_link_objects: CrtObjects,
1139 /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
1140 /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
1141 /// See `crt_objects.rs` for some more detailed documentation.
1142 pub pre_link_objects_fallback: CrtObjects,
1143 pub post_link_objects_fallback: CrtObjects,
1144 /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
1145 pub crt_objects_fallback: Option<CrtObjectsFallback>,
1147 /// Linker arguments that are unconditionally passed after any
1148 /// user-defined but before post-link objects. Standard platform
1149 /// libraries that should be always be linked to, usually go here.
1150 pub late_link_args: LinkArgs,
1151 /// Linker arguments used in addition to `late_link_args` if at least one
1152 /// Rust dependency is dynamically linked.
1153 pub late_link_args_dynamic: LinkArgs,
1154 /// Linker arguments used in addition to `late_link_args` if aall Rust
1155 /// dependencies are statically linked.
1156 pub late_link_args_static: LinkArgs,
1157 /// Linker arguments that are unconditionally passed *after* any
1158 /// user-defined libraries.
1159 pub post_link_args: LinkArgs,
1160 /// Optional link script applied to `dylib` and `executable` crate types.
1161 /// This is a string containing the script, not a path. Can only be applied
1162 /// to linkers where `linker_is_gnu` is true.
1163 pub link_script: Option<String>,
1165 /// Environment variables to be set for the linker invocation.
1166 pub link_env: Vec<(String, String)>,
1167 /// Environment variables to be removed for the linker invocation.
1168 pub link_env_remove: Vec<String>,
1170 /// Extra arguments to pass to the external assembler (when used)
1171 pub asm_args: Vec<String>,
1173 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1176 /// Default target features to pass to LLVM. These features will *always* be
1177 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1178 /// -mattr=$features`.
1179 pub features: String,
1180 /// Whether dynamic linking is available on this target. Defaults to false.
1181 pub dynamic_linking: bool,
1182 /// If dynamic linking is available, whether only cdylibs are supported.
1183 pub only_cdylib: bool,
1184 /// Whether executables are available on this target. iOS, for example, only allows static
1185 /// libraries. Defaults to false.
1186 pub executables: bool,
1187 /// Relocation model to use in object file. Corresponds to `llc
1188 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1189 pub relocation_model: RelocModel,
1190 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1191 /// Defaults to `None` which means "inherited from the base LLVM target".
1192 pub code_model: Option<CodeModel>,
1193 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1194 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1195 pub tls_model: TlsModel,
1196 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1197 pub disable_redzone: bool,
1198 /// Frame pointer mode for this target. Defaults to `MayOmit`.
1199 pub frame_pointer: FramePointer,
1200 /// Emit each function in its own section. Defaults to true.
1201 pub function_sections: bool,
1202 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1203 pub dll_prefix: String,
1204 /// String to append to the name of every dynamic library. Defaults to ".so".
1205 pub dll_suffix: String,
1206 /// String to append to the name of every executable.
1207 pub exe_suffix: String,
1208 /// String to prepend to the name of every static library. Defaults to "lib".
1209 pub staticlib_prefix: String,
1210 /// String to append to the name of every static library. Defaults to ".a".
1211 pub staticlib_suffix: String,
1212 /// Values of the `target_family` cfg set for this target.
1214 /// Common options are: "unix", "windows". Defaults to no families.
1216 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1217 pub families: Vec<String>,
1218 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1219 pub abi_return_struct_as_int: bool,
1220 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1221 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1222 pub is_like_osx: bool,
1223 /// Whether the target toolchain is like Solaris's.
1224 /// Only useful for compiling against Illumos/Solaris,
1225 /// as they have a different set of linker flags. Defaults to false.
1226 pub is_like_solaris: bool,
1227 /// Whether the target is like Windows.
1228 /// This is a combination of several more specific properties represented as a single flag:
1229 /// - The target uses a Windows ABI,
1230 /// - uses PE/COFF as a format for object code,
1231 /// - uses Windows-style dllexport/dllimport for shared libraries,
1232 /// - uses import libraries and .def files for symbol exports,
1233 /// - executables support setting a subsystem.
1234 pub is_like_windows: bool,
1235 /// Whether the target is like MSVC.
1236 /// This is a combination of several more specific properties represented as a single flag:
1237 /// - The target has all the properties from `is_like_windows`
1238 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1239 /// - has some MSVC-specific Windows ABI properties,
1240 /// - uses a link.exe-like linker,
1241 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1242 /// - uses SEH-based unwinding,
1243 /// - supports control flow guard mechanism.
1244 pub is_like_msvc: bool,
1245 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1246 /// Emscripten toolchain.
1247 /// Defaults to false.
1248 pub is_like_emscripten: bool,
1249 /// Whether the target toolchain is like Fuchsia's.
1250 pub is_like_fuchsia: bool,
1251 /// Whether a target toolchain is like WASM.
1252 pub is_like_wasm: bool,
1253 /// Version of DWARF to use if not using the default.
1254 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1255 pub dwarf_version: Option<u32>,
1256 /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1257 pub linker_is_gnu: bool,
1258 /// The MinGW toolchain has a known issue that prevents it from correctly
1259 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1260 /// symbol needs its own COMDAT section, weak linkage implies a large
1261 /// number sections that easily exceeds the given limit for larger
1262 /// codebases. Consequently we want a way to disallow weak linkage on some
1264 pub allows_weak_linkage: bool,
1265 /// Whether the linker support rpaths or not. Defaults to false.
1266 pub has_rpath: bool,
1267 /// Whether to disable linking to the default libraries, typically corresponds
1268 /// to `-nodefaultlibs`. Defaults to true.
1269 pub no_default_libraries: bool,
1270 /// Dynamically linked executables can be compiled as position independent
1271 /// if the default relocation model of position independent code is not
1272 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1273 /// the functions in the executable are not randomized and can be used
1274 /// during an exploit of a vulnerability in any code.
1275 pub position_independent_executables: bool,
1276 /// Executables that are both statically linked and position-independent are supported.
1277 pub static_position_independent_executables: bool,
1278 /// Determines if the target always requires using the PLT for indirect
1279 /// library calls or not. This controls the default value of the `-Z plt` flag.
1280 pub needs_plt: bool,
1281 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1282 /// resolve all symbols at startup and marks the GOT read-only before
1283 /// starting the program, preventing overwriting the GOT.
1284 pub relro_level: RelroLevel,
1285 /// Format that archives should be emitted in. This affects whether we use
1286 /// LLVM to assemble an archive or fall back to the system linker, and
1287 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1288 /// the system linker to be used.
1289 pub archive_format: String,
1290 /// Is asm!() allowed? Defaults to true.
1291 pub allow_asm: bool,
1292 /// Whether the runtime startup code requires the `main` function be passed
1293 /// `argc` and `argv` values.
1294 pub main_needs_argc_argv: bool,
1296 /// Flag indicating whether #[thread_local] is available for this target.
1297 pub has_thread_local: bool,
1298 // This is mainly for easy compatibility with emscripten.
1299 // If we give emcc .o files that are actually .bc files it
1300 // will 'just work'.
1301 pub obj_is_bitcode: bool,
1302 /// Whether the target requires that emitted object code includes bitcode.
1303 pub forces_embed_bitcode: bool,
1304 /// Content of the LLVM cmdline section associated with embedded bitcode.
1305 pub bitcode_llvm_cmdline: String,
1307 /// Don't use this field; instead use the `.min_atomic_width()` method.
1308 pub min_atomic_width: Option<u64>,
1310 /// Don't use this field; instead use the `.max_atomic_width()` method.
1311 pub max_atomic_width: Option<u64>,
1313 /// Whether the target supports atomic CAS operations natively
1314 pub atomic_cas: bool,
1316 /// Panic strategy: "unwind" or "abort"
1317 pub panic_strategy: PanicStrategy,
1319 /// Whether or not linking dylibs to a static CRT is allowed.
1320 pub crt_static_allows_dylibs: bool,
1321 /// Whether or not the CRT is statically linked by default.
1322 pub crt_static_default: bool,
1323 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1324 pub crt_static_respected: bool,
1326 /// The implementation of stack probes to use.
1327 pub stack_probes: StackProbeType,
1329 /// The minimum alignment for global symbols.
1330 pub min_global_align: Option<u64>,
1332 /// Default number of codegen units to use in debug mode
1333 pub default_codegen_units: Option<u64>,
1335 /// Whether to generate trap instructions in places where optimization would
1336 /// otherwise produce control flow that falls through into unrelated memory.
1337 pub trap_unreachable: bool,
1339 /// This target requires everything to be compiled with LTO to emit a final
1340 /// executable, aka there is no native linker for this target.
1341 pub requires_lto: bool,
1343 /// This target has no support for threads.
1344 pub singlethread: bool,
1346 /// Whether library functions call lowering/optimization is disabled in LLVM
1347 /// for this target unconditionally.
1348 pub no_builtins: bool,
1350 /// The default visibility for symbols in this target should be "hidden"
1351 /// rather than "default"
1352 pub default_hidden_visibility: bool,
1354 /// Whether a .debug_gdb_scripts section will be added to the output object file
1355 pub emit_debug_gdb_scripts: bool,
1357 /// Whether or not to unconditionally `uwtable` attributes on functions,
1358 /// typically because the platform needs to unwind for things like stack
1360 pub requires_uwtable: bool,
1362 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1363 /// is not specified and `uwtable` is not required on this target.
1364 pub default_uwtable: bool,
1366 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1367 /// typically required if a target can be compiled with a mixed set of
1368 /// target features. This is `true` by default, and `false` for targets like
1369 /// wasm32 where the whole program either has simd or not.
1370 pub simd_types_indirect: bool,
1372 /// Pass a list of symbol which should be exported in the dylib to the linker.
1373 pub limit_rdylib_exports: bool,
1375 /// If set, have the linker export exactly these symbols, instead of using
1376 /// the usual logic to figure this out from the crate itself.
1377 pub override_export_symbols: Option<Vec<String>>,
1379 /// Determines how or whether the MergeFunctions LLVM pass should run for
1380 /// this target. Either "disabled", "trampolines", or "aliases".
1381 /// The MergeFunctions pass is generally useful, but some targets may need
1382 /// to opt out. The default is "aliases".
1384 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1385 pub merge_functions: MergeFunctions,
1387 /// Use platform dependent mcount function
1390 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1391 pub llvm_abiname: String,
1393 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1394 pub relax_elf_relocations: bool,
1396 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1397 pub llvm_args: Vec<String>,
1399 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1400 /// to false (uses .init_array).
1401 pub use_ctors_section: bool,
1403 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1404 /// used to locate unwinding information is passed
1405 /// (only has effect if the linker is `ld`-like).
1406 pub eh_frame_header: bool,
1408 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1409 /// thumb and arm interworking.
1410 pub has_thumb_interworking: bool,
1412 /// How to handle split debug information, if at all. Specifying `None` has
1413 /// target-specific meaning.
1414 pub split_debuginfo: SplitDebuginfo,
1416 /// The sanitizers supported by this target
1418 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1419 /// enabled can generated on this target, but the necessary supporting libraries are not
1420 /// distributed with the target, the sanitizer should still appear in this list for the target.
1421 pub supported_sanitizers: SanitizerSet,
1423 /// If present it's a default value to use for adjusting the C ABI.
1424 pub default_adjusted_cabi: Option<Abi>,
1426 /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1427 pub c_enum_min_bits: u64,
1429 /// Whether or not the DWARF `.debug_aranges` section should be generated.
1430 pub generate_arange_section: bool,
1432 /// Whether the target supports stack canary checks. `true` by default,
1433 /// since this is most common among tier 1 and tier 2 targets.
1434 pub supports_stack_protector: bool,
1437 impl Default for TargetOptions {
1438 /// Creates a set of "sane defaults" for any target. This is still
1439 /// incomplete, and if used for compilation, will certainly not work.
1440 fn default() -> TargetOptions {
1443 endian: Endian::Little,
1444 c_int_width: "32".to_string(),
1445 os: "none".to_string(),
1448 vendor: "unknown".to_string(),
1449 linker_flavor: LinkerFlavor::Gcc,
1450 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1451 lld_flavor: LldFlavor::Ld,
1452 pre_link_args: LinkArgs::new(),
1453 post_link_args: LinkArgs::new(),
1455 asm_args: Vec::new(),
1456 cpu: "generic".to_string(),
1457 features: String::new(),
1458 dynamic_linking: false,
1461 relocation_model: RelocModel::Pic,
1463 tls_model: TlsModel::GeneralDynamic,
1464 disable_redzone: false,
1465 frame_pointer: FramePointer::MayOmit,
1466 function_sections: true,
1467 dll_prefix: "lib".to_string(),
1468 dll_suffix: ".so".to_string(),
1469 exe_suffix: String::new(),
1470 staticlib_prefix: "lib".to_string(),
1471 staticlib_suffix: ".a".to_string(),
1472 families: Vec::new(),
1473 abi_return_struct_as_int: false,
1475 is_like_solaris: false,
1476 is_like_windows: false,
1477 is_like_emscripten: false,
1478 is_like_msvc: false,
1479 is_like_fuchsia: false,
1480 is_like_wasm: false,
1481 dwarf_version: None,
1482 linker_is_gnu: true,
1483 allows_weak_linkage: true,
1485 no_default_libraries: true,
1486 position_independent_executables: false,
1487 static_position_independent_executables: false,
1489 relro_level: RelroLevel::None,
1490 pre_link_objects: Default::default(),
1491 post_link_objects: Default::default(),
1492 pre_link_objects_fallback: Default::default(),
1493 post_link_objects_fallback: Default::default(),
1494 crt_objects_fallback: None,
1495 late_link_args: LinkArgs::new(),
1496 late_link_args_dynamic: LinkArgs::new(),
1497 late_link_args_static: LinkArgs::new(),
1498 link_env: Vec::new(),
1499 link_env_remove: Vec::new(),
1500 archive_format: "gnu".to_string(),
1501 main_needs_argc_argv: true,
1503 has_thread_local: false,
1504 obj_is_bitcode: false,
1505 forces_embed_bitcode: false,
1506 bitcode_llvm_cmdline: String::new(),
1507 min_atomic_width: None,
1508 max_atomic_width: None,
1510 panic_strategy: PanicStrategy::Unwind,
1511 crt_static_allows_dylibs: false,
1512 crt_static_default: false,
1513 crt_static_respected: false,
1514 stack_probes: StackProbeType::None,
1515 min_global_align: None,
1516 default_codegen_units: None,
1517 trap_unreachable: true,
1518 requires_lto: false,
1519 singlethread: false,
1521 default_hidden_visibility: false,
1522 emit_debug_gdb_scripts: true,
1523 requires_uwtable: false,
1524 default_uwtable: false,
1525 simd_types_indirect: true,
1526 limit_rdylib_exports: true,
1527 override_export_symbols: None,
1528 merge_functions: MergeFunctions::Aliases,
1529 mcount: "mcount".to_string(),
1530 llvm_abiname: "".to_string(),
1531 relax_elf_relocations: false,
1533 use_ctors_section: false,
1534 eh_frame_header: true,
1535 has_thumb_interworking: false,
1536 split_debuginfo: SplitDebuginfo::Off,
1537 supported_sanitizers: SanitizerSet::empty(),
1538 default_adjusted_cabi: None,
1539 c_enum_min_bits: 32,
1540 generate_arange_section: true,
1541 supports_stack_protector: true,
1546 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1547 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1548 /// this `Deref` implementation is no longer necessary.
1549 impl Deref for Target {
1550 type Target = TargetOptions;
1553 fn deref(&self) -> &Self::Target {
1557 impl DerefMut for Target {
1559 fn deref_mut(&mut self) -> &mut Self::Target {
1565 /// Given a function ABI, turn it into the correct ABI for this target.
1566 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1568 Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1569 Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1570 Abi::Stdcall { unwind }
1572 Abi::System { unwind } => Abi::C { unwind },
1573 Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1574 Abi::EfiApi => Abi::C { unwind: false },
1576 // See commentary in `is_abi_supported`.
1577 Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1578 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1579 Abi::Fastcall { .. } if self.arch == "x86" => abi,
1580 Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1581 Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1587 /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1588 pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1600 X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1601 Aapcs { .. } => "arm" == self.arch,
1602 CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1603 Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1604 PtxKernel => self.arch == "nvptx64",
1605 Msp430Interrupt => self.arch == "msp430",
1606 AmdGpuKernel => self.arch == "amdgcn",
1607 AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1608 Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1609 Thiscall { .. } => self.arch == "x86",
1610 // On windows these fall-back to platform native calling convention (C) when the
1611 // architecture is not supported.
1613 // This is I believe a historical accident that has occurred as part of Microsoft
1614 // striving to allow most of the code to "just" compile when support for 64-bit x86
1615 // was added and then later again, when support for ARM architectures was added.
1617 // This is well documented across MSDN. Support for this in Rust has been added in
1618 // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1619 // Rust, but there isn't much leeway remaining here to change it back at the time this
1620 // comment has been written.
1622 // Following are the relevant excerpts from the MSDN documentation.
1624 // > The __vectorcall calling convention is only supported in native code on x86 and
1625 // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1627 // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1629 // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1631 // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1633 // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1635 // > In most cases, keywords or compiler switches that specify an unsupported
1636 // > convention on a particular platform are ignored, and the platform default
1637 // > convention is used.
1639 // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1640 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1641 // Outside of Windows we want to only support these calling conventions for the
1642 // architectures for which these calling conventions are actually well defined.
1643 Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1644 Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1645 // Return a `None` for other cases so that we know to emit a future compat lint.
1646 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1650 /// Minimum integer size in bits that this target can perform atomic
1652 pub fn min_atomic_width(&self) -> u64 {
1653 self.min_atomic_width.unwrap_or(8)
1656 /// Maximum integer size in bits that this target can perform atomic
1658 pub fn max_atomic_width(&self) -> u64 {
1659 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1662 /// Loads a target descriptor from a JSON object.
1663 pub fn from_json(mut obj: Json) -> Result<(Target, TargetWarnings), String> {
1664 // While ugly, this code must remain this way to retain
1665 // compatibility with existing JSON fields and the internal
1666 // expected naming of the Target and TargetOptions structs.
1667 // To ensure compatibility is retained, the built-in targets
1668 // are round-tripped through this code to catch cases where
1669 // the JSON parser is not updated to match the structs.
1671 let mut get_req_field = |name: &str| {
1672 obj.remove_key(name)
1673 .and_then(|j| Json::as_string(&j).map(str::to_string))
1674 .ok_or_else(|| format!("Field {} in target specification is required", name))
1677 let mut base = Target {
1678 llvm_target: get_req_field("llvm-target")?,
1679 pointer_width: get_req_field("target-pointer-width")?
1681 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1682 data_layout: get_req_field("data-layout")?,
1683 arch: get_req_field("arch")?,
1684 options: Default::default(),
1687 let mut incorrect_type = vec![];
1690 ($key_name:ident) => ( {
1691 let name = (stringify!($key_name)).replace("_", "-");
1692 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1696 ($key_name:ident = $json_name:expr) => ( {
1697 let name = $json_name;
1698 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1702 ($key_name:ident, bool) => ( {
1703 let name = (stringify!($key_name)).replace("_", "-");
1704 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_boolean(&j)) {
1708 ($key_name:ident, u64) => ( {
1709 let name = (stringify!($key_name)).replace("_", "-");
1710 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1714 ($key_name:ident, Option<u32>) => ( {
1715 let name = (stringify!($key_name)).replace("_", "-");
1716 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1718 return Err("Not a valid DWARF version number".to_string());
1720 base.$key_name = Some(s as u32);
1723 ($key_name:ident, Option<u64>) => ( {
1724 let name = (stringify!($key_name)).replace("_", "-");
1725 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1726 base.$key_name = Some(s);
1729 ($key_name:ident, MergeFunctions) => ( {
1730 let name = (stringify!($key_name)).replace("_", "-");
1731 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1732 match s.parse::<MergeFunctions>() {
1733 Ok(mergefunc) => base.$key_name = mergefunc,
1734 _ => return Some(Err(format!("'{}' is not a valid value for \
1735 merge-functions. Use 'disabled', \
1736 'trampolines', or 'aliases'.",
1740 })).unwrap_or(Ok(()))
1742 ($key_name:ident, RelocModel) => ( {
1743 let name = (stringify!($key_name)).replace("_", "-");
1744 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1745 match s.parse::<RelocModel>() {
1746 Ok(relocation_model) => base.$key_name = relocation_model,
1747 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1748 Run `rustc --print relocation-models` to \
1749 see the list of supported values.", s))),
1752 })).unwrap_or(Ok(()))
1754 ($key_name:ident, CodeModel) => ( {
1755 let name = (stringify!($key_name)).replace("_", "-");
1756 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1757 match s.parse::<CodeModel>() {
1758 Ok(code_model) => base.$key_name = Some(code_model),
1759 _ => return Some(Err(format!("'{}' is not a valid code model. \
1760 Run `rustc --print code-models` to \
1761 see the list of supported values.", s))),
1764 })).unwrap_or(Ok(()))
1766 ($key_name:ident, TlsModel) => ( {
1767 let name = (stringify!($key_name)).replace("_", "-");
1768 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1769 match s.parse::<TlsModel>() {
1770 Ok(tls_model) => base.$key_name = tls_model,
1771 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1772 Run `rustc --print tls-models` to \
1773 see the list of supported values.", s))),
1776 })).unwrap_or(Ok(()))
1778 ($key_name:ident, PanicStrategy) => ( {
1779 let name = (stringify!($key_name)).replace("_", "-");
1780 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1782 "unwind" => base.$key_name = PanicStrategy::Unwind,
1783 "abort" => base.$key_name = PanicStrategy::Abort,
1784 _ => return Some(Err(format!("'{}' is not a valid value for \
1785 panic-strategy. Use 'unwind' or 'abort'.",
1789 })).unwrap_or(Ok(()))
1791 ($key_name:ident, RelroLevel) => ( {
1792 let name = (stringify!($key_name)).replace("_", "-");
1793 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1794 match s.parse::<RelroLevel>() {
1795 Ok(level) => base.$key_name = level,
1796 _ => return Some(Err(format!("'{}' is not a valid value for \
1797 relro-level. Use 'full', 'partial, or 'off'.",
1801 })).unwrap_or(Ok(()))
1803 ($key_name:ident, SplitDebuginfo) => ( {
1804 let name = (stringify!($key_name)).replace("_", "-");
1805 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1806 match s.parse::<SplitDebuginfo>() {
1807 Ok(level) => base.$key_name = level,
1808 _ => return Some(Err(format!("'{}' is not a valid value for \
1809 split-debuginfo. Use 'off' or 'dsymutil'.",
1813 })).unwrap_or(Ok(()))
1815 ($key_name:ident, list) => ( {
1816 let name = (stringify!($key_name)).replace("_", "-");
1817 if let Some(j) = obj.remove_key(&name){
1818 if let Some(v) = Json::as_array(&j) {
1819 base.$key_name = v.iter()
1820 .map(|a| a.as_string().unwrap().to_string())
1823 incorrect_type.push(name)
1827 ($key_name:ident, opt_list) => ( {
1828 let name = (stringify!($key_name)).replace("_", "-");
1829 if let Some(j) = obj.remove_key(&name) {
1830 if let Some(v) = Json::as_array(&j) {
1831 base.$key_name = Some(v.iter()
1832 .map(|a| a.as_string().unwrap().to_string())
1835 incorrect_type.push(name)
1839 ($key_name:ident, optional) => ( {
1840 let name = (stringify!($key_name)).replace("_", "-");
1841 if let Some(o) = obj.remove_key(&name[..]) {
1844 .map(|s| s.to_string() );
1847 ($key_name:ident, LldFlavor) => ( {
1848 let name = (stringify!($key_name)).replace("_", "-");
1849 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1850 if let Some(flavor) = LldFlavor::from_str(&s) {
1851 base.$key_name = flavor;
1853 return Some(Err(format!(
1854 "'{}' is not a valid value for lld-flavor. \
1855 Use 'darwin', 'gnu', 'link' or 'wasm.",
1859 })).unwrap_or(Ok(()))
1861 ($key_name:ident, LinkerFlavor) => ( {
1862 let name = (stringify!($key_name)).replace("_", "-");
1863 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1864 match LinkerFlavor::from_str(s) {
1865 Some(linker_flavor) => base.$key_name = linker_flavor,
1866 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1867 Use {}", s, LinkerFlavor::one_of()))),
1870 })).unwrap_or(Ok(()))
1872 ($key_name:ident, StackProbeType) => ( {
1873 let name = (stringify!($key_name)).replace("_", "-");
1874 obj.remove_key(&name[..]).and_then(|o| match StackProbeType::from_json(&o) {
1880 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1882 }).unwrap_or(Ok(()))
1884 ($key_name:ident, SanitizerSet) => ( {
1885 let name = (stringify!($key_name)).replace("_", "-");
1886 if let Some(o) = obj.remove_key(&name[..]) {
1887 if let Some(a) = o.as_array() {
1889 base.$key_name |= match s.as_string() {
1890 Some("address") => SanitizerSet::ADDRESS,
1891 Some("cfi") => SanitizerSet::CFI,
1892 Some("leak") => SanitizerSet::LEAK,
1893 Some("memory") => SanitizerSet::MEMORY,
1894 Some("memtag") => SanitizerSet::MEMTAG,
1895 Some("thread") => SanitizerSet::THREAD,
1896 Some("hwaddress") => SanitizerSet::HWADDRESS,
1897 Some(s) => return Err(format!("unknown sanitizer {}", s)),
1898 _ => return Err(format!("not a string: {:?}", s)),
1902 incorrect_type.push(name)
1905 Ok::<(), String>(())
1908 ($key_name:ident, crt_objects_fallback) => ( {
1909 let name = (stringify!($key_name)).replace("_", "-");
1910 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1911 match s.parse::<CrtObjectsFallback>() {
1912 Ok(fallback) => base.$key_name = Some(fallback),
1913 _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1914 Use 'musl', 'mingw' or 'wasm'", s))),
1917 })).unwrap_or(Ok(()))
1919 ($key_name:ident, link_objects) => ( {
1920 let name = (stringify!($key_name)).replace("_", "-");
1921 if let Some(val) = obj.remove_key(&name[..]) {
1922 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1923 JSON object with fields per CRT object kind.", name))?;
1924 let mut args = CrtObjects::new();
1926 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1927 format!("{}: '{}' is not a valid value for CRT object kind. \
1928 Use '(dynamic,static)-(nopic,pic)-exe' or \
1929 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1932 let v = v.as_array().ok_or_else(||
1933 format!("{}.{}: expected a JSON array", name, k)
1934 )?.iter().enumerate()
1936 let s = s.as_string().ok_or_else(||
1937 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1940 .collect::<Result<Vec<_>, String>>()?;
1942 args.insert(kind, v);
1944 base.$key_name = args;
1947 ($key_name:ident, link_args) => ( {
1948 let name = (stringify!($key_name)).replace("_", "-");
1949 if let Some(val) = obj.remove_key(&name[..]) {
1950 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1951 JSON object with fields per linker-flavor.", name))?;
1952 let mut args = LinkArgs::new();
1954 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1955 format!("{}: '{}' is not a valid value for linker-flavor. \
1956 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1959 let v = v.as_array().ok_or_else(||
1960 format!("{}.{}: expected a JSON array", name, k)
1961 )?.iter().enumerate()
1963 let s = s.as_string().ok_or_else(||
1964 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1967 .collect::<Result<Vec<_>, String>>()?;
1969 args.insert(flavor, v);
1971 base.$key_name = args;
1974 ($key_name:ident, env) => ( {
1975 let name = (stringify!($key_name)).replace("_", "-");
1976 if let Some(o) = obj.remove_key(&name[..]) {
1977 if let Some(a) = o.as_array() {
1979 if let Some(s) = o.as_string() {
1980 let p = s.split('=').collect::<Vec<_>>();
1982 let k = p[0].to_string();
1983 let v = p[1].to_string();
1984 base.$key_name.push((k, v));
1989 incorrect_type.push(name)
1993 ($key_name:ident, Option<Abi>) => ( {
1994 let name = (stringify!($key_name)).replace("_", "-");
1995 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1996 match lookup_abi(s) {
1997 Some(abi) => base.$key_name = Some(abi),
1998 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2001 })).unwrap_or(Ok(()))
2003 ($key_name:ident, TargetFamilies) => ( {
2004 if let Some(value) = obj.remove_key("target-family") {
2005 if let Some(v) = Json::as_array(&value) {
2006 base.$key_name = v.iter()
2007 .map(|a| a.as_string().unwrap().to_string())
2009 } else if let Some(v) = Json::as_string(&value) {
2010 base.$key_name = vec![v.to_string()];
2016 if let Some(j) = obj.remove_key("target-endian") {
2017 if let Some(s) = Json::as_string(&j) {
2018 base.endian = s.parse()?;
2020 incorrect_type.push("target-endian".to_string())
2024 if let Some(fp) = obj.remove_key("frame-pointer") {
2025 if let Some(s) = Json::as_string(&fp) {
2026 base.frame_pointer = s
2028 .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2030 incorrect_type.push("frame-pointer".to_string())
2034 key!(is_builtin, bool);
2035 key!(c_int_width = "target-c-int-width");
2040 key!(linker_flavor, LinkerFlavor)?;
2041 key!(linker, optional);
2042 key!(lld_flavor, LldFlavor)?;
2043 key!(pre_link_objects, link_objects);
2044 key!(post_link_objects, link_objects);
2045 key!(pre_link_objects_fallback, link_objects);
2046 key!(post_link_objects_fallback, link_objects);
2047 key!(crt_objects_fallback, crt_objects_fallback)?;
2048 key!(pre_link_args, link_args);
2049 key!(late_link_args, link_args);
2050 key!(late_link_args_dynamic, link_args);
2051 key!(late_link_args_static, link_args);
2052 key!(post_link_args, link_args);
2053 key!(link_script, optional);
2054 key!(link_env, env);
2055 key!(link_env_remove, list);
2056 key!(asm_args, list);
2059 key!(dynamic_linking, bool);
2060 key!(only_cdylib, bool);
2061 key!(executables, bool);
2062 key!(relocation_model, RelocModel)?;
2063 key!(code_model, CodeModel)?;
2064 key!(tls_model, TlsModel)?;
2065 key!(disable_redzone, bool);
2066 key!(function_sections, bool);
2070 key!(staticlib_prefix);
2071 key!(staticlib_suffix);
2072 key!(families, TargetFamilies);
2073 key!(abi_return_struct_as_int, bool);
2074 key!(is_like_osx, bool);
2075 key!(is_like_solaris, bool);
2076 key!(is_like_windows, bool);
2077 key!(is_like_msvc, bool);
2078 key!(is_like_emscripten, bool);
2079 key!(is_like_fuchsia, bool);
2080 key!(is_like_wasm, bool);
2081 key!(dwarf_version, Option<u32>);
2082 key!(linker_is_gnu, bool);
2083 key!(allows_weak_linkage, bool);
2084 key!(has_rpath, bool);
2085 key!(no_default_libraries, bool);
2086 key!(position_independent_executables, bool);
2087 key!(static_position_independent_executables, bool);
2088 key!(needs_plt, bool);
2089 key!(relro_level, RelroLevel)?;
2090 key!(archive_format);
2091 key!(allow_asm, bool);
2092 key!(main_needs_argc_argv, bool);
2093 key!(has_thread_local, bool);
2094 key!(obj_is_bitcode, bool);
2095 key!(forces_embed_bitcode, bool);
2096 key!(bitcode_llvm_cmdline);
2097 key!(max_atomic_width, Option<u64>);
2098 key!(min_atomic_width, Option<u64>);
2099 key!(atomic_cas, bool);
2100 key!(panic_strategy, PanicStrategy)?;
2101 key!(crt_static_allows_dylibs, bool);
2102 key!(crt_static_default, bool);
2103 key!(crt_static_respected, bool);
2104 key!(stack_probes, StackProbeType)?;
2105 key!(min_global_align, Option<u64>);
2106 key!(default_codegen_units, Option<u64>);
2107 key!(trap_unreachable, bool);
2108 key!(requires_lto, bool);
2109 key!(singlethread, bool);
2110 key!(no_builtins, bool);
2111 key!(default_hidden_visibility, bool);
2112 key!(emit_debug_gdb_scripts, bool);
2113 key!(requires_uwtable, bool);
2114 key!(default_uwtable, bool);
2115 key!(simd_types_indirect, bool);
2116 key!(limit_rdylib_exports, bool);
2117 key!(override_export_symbols, opt_list);
2118 key!(merge_functions, MergeFunctions)?;
2119 key!(mcount = "target-mcount");
2121 key!(relax_elf_relocations, bool);
2122 key!(llvm_args, list);
2123 key!(use_ctors_section, bool);
2124 key!(eh_frame_header, bool);
2125 key!(has_thumb_interworking, bool);
2126 key!(split_debuginfo, SplitDebuginfo)?;
2127 key!(supported_sanitizers, SanitizerSet)?;
2128 key!(default_adjusted_cabi, Option<Abi>)?;
2129 key!(c_enum_min_bits, u64);
2130 key!(generate_arange_section, bool);
2131 key!(supports_stack_protector, bool);
2133 if base.is_builtin {
2134 // This can cause unfortunate ICEs later down the line.
2135 return Err("may not set is_builtin for targets not built-in".to_string());
2137 // Each field should have been read using `Json::remove_key` so any keys remaining are unused.
2138 let remaining_keys = obj.as_object().ok_or("Expected JSON object for target")?.keys();
2141 TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2145 /// Load a built-in target
2146 pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2147 match *target_triple {
2148 TargetTriple::TargetTriple(ref target_triple) => {
2149 load_builtin(target_triple).expect("built-in target")
2151 TargetTriple::TargetPath(..) => {
2152 panic!("built-in targets doens't support target-paths")
2157 /// Search for a JSON file specifying the given target triple.
2159 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2160 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
2161 /// bare filename already, so also check for that. If one of the hardcoded targets we know
2162 /// about, just return it directly.
2164 /// The error string could come from any of the APIs called, including filesystem access and
2167 target_triple: &TargetTriple,
2169 ) -> Result<(Target, TargetWarnings), String> {
2170 use rustc_serialize::json;
2174 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2175 let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2176 let obj = json::from_str(&contents).map_err(|e| e.to_string())?;
2177 Target::from_json(obj)
2180 match *target_triple {
2181 TargetTriple::TargetTriple(ref target_triple) => {
2182 // check if triple is in list of built-in targets
2183 if let Some(t) = load_builtin(target_triple) {
2184 return Ok((t, TargetWarnings::empty()));
2187 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2189 let mut target = target_triple.to_string();
2190 target.push_str(".json");
2191 PathBuf::from(target)
2194 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2196 for dir in env::split_paths(&target_path) {
2197 let p = dir.join(&path);
2199 return load_file(&p);
2203 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2205 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2206 let p = PathBuf::from_iter([
2208 Path::new(&rustlib_path),
2209 Path::new("target.json"),
2212 return load_file(&p);
2215 Err(format!("Could not find specification for target {:?}", target_triple))
2217 TargetTriple::TargetPath(ref target_path) => {
2218 if target_path.is_file() {
2219 return load_file(&target_path);
2221 Err(format!("Target path {:?} is not a valid file", target_path))
2227 impl ToJson for Target {
2228 fn to_json(&self) -> Json {
2229 let mut d = BTreeMap::new();
2230 let default: TargetOptions = Default::default();
2232 macro_rules! target_val {
2234 let name = (stringify!($attr)).replace("_", "-");
2235 d.insert(name, self.$attr.to_json());
2237 ($attr:ident, $key_name:expr) => {{
2238 let name = $key_name;
2239 d.insert(name.to_string(), self.$attr.to_json());
2243 macro_rules! target_option_val {
2245 let name = (stringify!($attr)).replace("_", "-");
2246 if default.$attr != self.$attr {
2247 d.insert(name, self.$attr.to_json());
2250 ($attr:ident, $key_name:expr) => {{
2251 let name = $key_name;
2252 if default.$attr != self.$attr {
2253 d.insert(name.to_string(), self.$attr.to_json());
2256 (link_args - $attr:ident) => {{
2257 let name = (stringify!($attr)).replace("_", "-");
2258 if default.$attr != self.$attr {
2262 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
2263 .collect::<BTreeMap<_, _>>();
2264 d.insert(name, obj.to_json());
2267 (env - $attr:ident) => {{
2268 let name = (stringify!($attr)).replace("_", "-");
2269 if default.$attr != self.$attr {
2273 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
2274 .collect::<Vec<_>>();
2275 d.insert(name, obj.to_json());
2280 target_val!(llvm_target);
2281 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2283 target_val!(data_layout);
2285 target_option_val!(is_builtin);
2286 target_option_val!(endian, "target-endian");
2287 target_option_val!(c_int_width, "target-c-int-width");
2288 target_option_val!(os);
2289 target_option_val!(env);
2290 target_option_val!(abi);
2291 target_option_val!(vendor);
2292 target_option_val!(linker_flavor);
2293 target_option_val!(linker);
2294 target_option_val!(lld_flavor);
2295 target_option_val!(pre_link_objects);
2296 target_option_val!(post_link_objects);
2297 target_option_val!(pre_link_objects_fallback);
2298 target_option_val!(post_link_objects_fallback);
2299 target_option_val!(crt_objects_fallback);
2300 target_option_val!(link_args - pre_link_args);
2301 target_option_val!(link_args - late_link_args);
2302 target_option_val!(link_args - late_link_args_dynamic);
2303 target_option_val!(link_args - late_link_args_static);
2304 target_option_val!(link_args - post_link_args);
2305 target_option_val!(link_script);
2306 target_option_val!(env - link_env);
2307 target_option_val!(link_env_remove);
2308 target_option_val!(asm_args);
2309 target_option_val!(cpu);
2310 target_option_val!(features);
2311 target_option_val!(dynamic_linking);
2312 target_option_val!(only_cdylib);
2313 target_option_val!(executables);
2314 target_option_val!(relocation_model);
2315 target_option_val!(code_model);
2316 target_option_val!(tls_model);
2317 target_option_val!(disable_redzone);
2318 target_option_val!(frame_pointer);
2319 target_option_val!(function_sections);
2320 target_option_val!(dll_prefix);
2321 target_option_val!(dll_suffix);
2322 target_option_val!(exe_suffix);
2323 target_option_val!(staticlib_prefix);
2324 target_option_val!(staticlib_suffix);
2325 target_option_val!(families, "target-family");
2326 target_option_val!(abi_return_struct_as_int);
2327 target_option_val!(is_like_osx);
2328 target_option_val!(is_like_solaris);
2329 target_option_val!(is_like_windows);
2330 target_option_val!(is_like_msvc);
2331 target_option_val!(is_like_emscripten);
2332 target_option_val!(is_like_fuchsia);
2333 target_option_val!(is_like_wasm);
2334 target_option_val!(dwarf_version);
2335 target_option_val!(linker_is_gnu);
2336 target_option_val!(allows_weak_linkage);
2337 target_option_val!(has_rpath);
2338 target_option_val!(no_default_libraries);
2339 target_option_val!(position_independent_executables);
2340 target_option_val!(static_position_independent_executables);
2341 target_option_val!(needs_plt);
2342 target_option_val!(relro_level);
2343 target_option_val!(archive_format);
2344 target_option_val!(allow_asm);
2345 target_option_val!(main_needs_argc_argv);
2346 target_option_val!(has_thread_local);
2347 target_option_val!(obj_is_bitcode);
2348 target_option_val!(forces_embed_bitcode);
2349 target_option_val!(bitcode_llvm_cmdline);
2350 target_option_val!(min_atomic_width);
2351 target_option_val!(max_atomic_width);
2352 target_option_val!(atomic_cas);
2353 target_option_val!(panic_strategy);
2354 target_option_val!(crt_static_allows_dylibs);
2355 target_option_val!(crt_static_default);
2356 target_option_val!(crt_static_respected);
2357 target_option_val!(stack_probes);
2358 target_option_val!(min_global_align);
2359 target_option_val!(default_codegen_units);
2360 target_option_val!(trap_unreachable);
2361 target_option_val!(requires_lto);
2362 target_option_val!(singlethread);
2363 target_option_val!(no_builtins);
2364 target_option_val!(default_hidden_visibility);
2365 target_option_val!(emit_debug_gdb_scripts);
2366 target_option_val!(requires_uwtable);
2367 target_option_val!(default_uwtable);
2368 target_option_val!(simd_types_indirect);
2369 target_option_val!(limit_rdylib_exports);
2370 target_option_val!(override_export_symbols);
2371 target_option_val!(merge_functions);
2372 target_option_val!(mcount, "target-mcount");
2373 target_option_val!(llvm_abiname);
2374 target_option_val!(relax_elf_relocations);
2375 target_option_val!(llvm_args);
2376 target_option_val!(use_ctors_section);
2377 target_option_val!(eh_frame_header);
2378 target_option_val!(has_thumb_interworking);
2379 target_option_val!(split_debuginfo);
2380 target_option_val!(supported_sanitizers);
2381 target_option_val!(c_enum_min_bits);
2382 target_option_val!(generate_arange_section);
2383 target_option_val!(supports_stack_protector);
2385 if let Some(abi) = self.default_adjusted_cabi {
2386 d.insert("default-adjusted-cabi".to_string(), Abi::name(abi).to_json());
2393 /// Either a target triple string or a path to a JSON file.
2394 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2395 pub enum TargetTriple {
2396 TargetTriple(String),
2397 TargetPath(PathBuf),
2401 /// Creates a target triple from the passed target triple string.
2402 pub fn from_triple(triple: &str) -> Self {
2403 TargetTriple::TargetTriple(triple.to_string())
2406 /// Creates a target triple from the passed target path.
2407 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2408 let canonicalized_path = path.canonicalize()?;
2409 Ok(TargetTriple::TargetPath(canonicalized_path))
2412 /// Returns a string triple for this target.
2414 /// If this target is a path, the file name (without extension) is returned.
2415 pub fn triple(&self) -> &str {
2417 TargetTriple::TargetTriple(ref triple) => triple,
2418 TargetTriple::TargetPath(ref path) => path
2420 .expect("target path must not be empty")
2422 .expect("target path must be valid unicode"),
2426 /// Returns an extended string triple for this target.
2428 /// If this target is a path, a hash of the path is appended to the triple returned
2430 pub fn debug_triple(&self) -> String {
2431 use std::collections::hash_map::DefaultHasher;
2432 use std::hash::{Hash, Hasher};
2434 let triple = self.triple();
2435 if let TargetTriple::TargetPath(ref path) = *self {
2436 let mut hasher = DefaultHasher::new();
2437 path.hash(&mut hasher);
2438 let hash = hasher.finish();
2439 format!("{}-{}", triple, hash)
2446 impl fmt::Display for TargetTriple {
2447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2448 write!(f, "{}", self.debug_triple())