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::json::{Json, ToJson};
39 use crate::spec::abi::{lookup as lookup_abi, Abi};
40 use crate::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
41 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
42 use rustc_span::symbol::{sym, Symbol};
43 use serde_json::Value;
45 use std::collections::BTreeMap;
46 use std::convert::TryFrom;
47 use std::iter::FromIterator;
48 use std::ops::{Deref, DerefMut};
49 use std::path::{Path, PathBuf};
50 use std::str::FromStr;
53 use rustc_macros::HashStable_Generic;
72 mod linux_kernel_base;
74 mod linux_uclibc_base;
86 mod windows_gnullvm_base;
87 mod windows_msvc_base;
88 mod windows_uwp_gnu_base;
89 mod windows_uwp_msvc_base;
91 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
92 pub enum LinkerFlavor {
103 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
112 pub fn as_str(&self) -> &'static str {
114 LldFlavor::Wasm => "wasm",
115 LldFlavor::Ld64 => "darwin",
116 LldFlavor::Ld => "gnu",
117 LldFlavor::Link => "link",
121 fn from_str(s: &str) -> Option<Self> {
123 "darwin" => LldFlavor::Ld64,
124 "gnu" => LldFlavor::Ld,
125 "link" => LldFlavor::Link,
126 "wasm" => LldFlavor::Wasm,
132 impl ToJson for LldFlavor {
133 fn to_json(&self) -> Json {
134 self.as_str().to_json()
138 impl ToJson for LinkerFlavor {
139 fn to_json(&self) -> Json {
140 self.desc().to_json()
143 macro_rules! flavor_mappings {
144 ($((($($flavor:tt)*), $string:expr),)*) => (
146 pub const fn one_of() -> &'static str {
147 concat!("one of: ", $($string, " ",)*)
150 pub fn from_str(s: &str) -> Option<Self> {
152 $($string => $($flavor)*,)*
157 pub fn desc(&self) -> &str {
159 $($($flavor)* => $string,)*
167 ((LinkerFlavor::Em), "em"),
168 ((LinkerFlavor::Gcc), "gcc"),
169 ((LinkerFlavor::L4Bender), "l4-bender"),
170 ((LinkerFlavor::Ld), "ld"),
171 ((LinkerFlavor::Msvc), "msvc"),
172 ((LinkerFlavor::PtxLinker), "ptx-linker"),
173 ((LinkerFlavor::BpfLinker), "bpf-linker"),
174 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
175 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
176 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
177 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
180 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
181 pub enum PanicStrategy {
187 pub fn desc(&self) -> &str {
189 PanicStrategy::Unwind => "unwind",
190 PanicStrategy::Abort => "abort",
194 pub const fn desc_symbol(&self) -> Symbol {
196 PanicStrategy::Unwind => sym::unwind,
197 PanicStrategy::Abort => sym::abort,
201 pub const fn all() -> [Symbol; 2] {
202 [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
206 impl ToJson for PanicStrategy {
207 fn to_json(&self) -> Json {
209 PanicStrategy::Abort => "abort".to_json(),
210 PanicStrategy::Unwind => "unwind".to_json(),
215 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
216 pub enum RelroLevel {
224 pub fn desc(&self) -> &str {
226 RelroLevel::Full => "full",
227 RelroLevel::Partial => "partial",
228 RelroLevel::Off => "off",
229 RelroLevel::None => "none",
234 impl FromStr for RelroLevel {
237 fn from_str(s: &str) -> Result<RelroLevel, ()> {
239 "full" => Ok(RelroLevel::Full),
240 "partial" => Ok(RelroLevel::Partial),
241 "off" => Ok(RelroLevel::Off),
242 "none" => Ok(RelroLevel::None),
248 impl ToJson for RelroLevel {
249 fn to_json(&self) -> Json {
251 RelroLevel::Full => "full".to_json(),
252 RelroLevel::Partial => "partial".to_json(),
253 RelroLevel::Off => "off".to_json(),
254 RelroLevel::None => "None".to_json(),
259 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
260 pub enum MergeFunctions {
266 impl MergeFunctions {
267 pub fn desc(&self) -> &str {
269 MergeFunctions::Disabled => "disabled",
270 MergeFunctions::Trampolines => "trampolines",
271 MergeFunctions::Aliases => "aliases",
276 impl FromStr for MergeFunctions {
279 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
281 "disabled" => Ok(MergeFunctions::Disabled),
282 "trampolines" => Ok(MergeFunctions::Trampolines),
283 "aliases" => Ok(MergeFunctions::Aliases),
289 impl ToJson for MergeFunctions {
290 fn to_json(&self) -> Json {
292 MergeFunctions::Disabled => "disabled".to_json(),
293 MergeFunctions::Trampolines => "trampolines".to_json(),
294 MergeFunctions::Aliases => "aliases".to_json(),
299 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
300 pub enum RelocModel {
310 impl FromStr for RelocModel {
313 fn from_str(s: &str) -> Result<RelocModel, ()> {
315 "static" => RelocModel::Static,
316 "pic" => RelocModel::Pic,
317 "pie" => RelocModel::Pie,
318 "dynamic-no-pic" => RelocModel::DynamicNoPic,
319 "ropi" => RelocModel::Ropi,
320 "rwpi" => RelocModel::Rwpi,
321 "ropi-rwpi" => RelocModel::RopiRwpi,
327 impl ToJson for RelocModel {
328 fn to_json(&self) -> Json {
330 RelocModel::Static => "static",
331 RelocModel::Pic => "pic",
332 RelocModel::Pie => "pie",
333 RelocModel::DynamicNoPic => "dynamic-no-pic",
334 RelocModel::Ropi => "ropi",
335 RelocModel::Rwpi => "rwpi",
336 RelocModel::RopiRwpi => "ropi-rwpi",
342 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
351 impl FromStr for CodeModel {
354 fn from_str(s: &str) -> Result<CodeModel, ()> {
356 "tiny" => CodeModel::Tiny,
357 "small" => CodeModel::Small,
358 "kernel" => CodeModel::Kernel,
359 "medium" => CodeModel::Medium,
360 "large" => CodeModel::Large,
366 impl ToJson for CodeModel {
367 fn to_json(&self) -> Json {
369 CodeModel::Tiny => "tiny",
370 CodeModel::Small => "small",
371 CodeModel::Kernel => "kernel",
372 CodeModel::Medium => "medium",
373 CodeModel::Large => "large",
379 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
387 impl FromStr for TlsModel {
390 fn from_str(s: &str) -> Result<TlsModel, ()> {
392 // Note the difference "general" vs "global" difference. The model name is "general",
393 // but the user-facing option name is "global" for consistency with other compilers.
394 "global-dynamic" => TlsModel::GeneralDynamic,
395 "local-dynamic" => TlsModel::LocalDynamic,
396 "initial-exec" => TlsModel::InitialExec,
397 "local-exec" => TlsModel::LocalExec,
403 impl ToJson for TlsModel {
404 fn to_json(&self) -> Json {
406 TlsModel::GeneralDynamic => "global-dynamic",
407 TlsModel::LocalDynamic => "local-dynamic",
408 TlsModel::InitialExec => "initial-exec",
409 TlsModel::LocalExec => "local-exec",
415 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
416 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
417 pub enum LinkOutputKind {
418 /// Dynamically linked non position-independent executable.
420 /// Dynamically linked position-independent executable.
422 /// Statically linked non position-independent executable.
424 /// Statically linked position-independent executable.
426 /// Regular dynamic library ("dynamically linked").
428 /// Dynamic library with bundled libc ("statically linked").
430 /// WASI module with a lifetime past the _initialize entry point
434 impl LinkOutputKind {
435 fn as_str(&self) -> &'static str {
437 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
438 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
439 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
440 LinkOutputKind::StaticPicExe => "static-pic-exe",
441 LinkOutputKind::DynamicDylib => "dynamic-dylib",
442 LinkOutputKind::StaticDylib => "static-dylib",
443 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
447 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
449 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
450 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
451 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
452 "static-pic-exe" => LinkOutputKind::StaticPicExe,
453 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
454 "static-dylib" => LinkOutputKind::StaticDylib,
455 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
461 impl fmt::Display for LinkOutputKind {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 f.write_str(self.as_str())
467 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
469 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
470 pub enum SplitDebuginfo {
471 /// Split debug-information is disabled, meaning that on supported platforms
472 /// you can find all debug information in the executable itself. This is
473 /// only supported for ELF effectively.
475 /// * Windows - not supported
476 /// * macOS - don't run `dsymutil`
477 /// * ELF - `.dwarf_*` sections
480 /// Split debug-information can be found in a "packed" location separate
481 /// from the final artifact. This is supported on all platforms.
483 /// * Windows - `*.pdb`
484 /// * macOS - `*.dSYM` (run `dsymutil`)
485 /// * ELF - `*.dwp` (run `rust-llvm-dwp`)
488 /// Split debug-information can be found in individual object files on the
489 /// filesystem. The main executable may point to the object files.
491 /// * Windows - not supported
492 /// * macOS - supported, scattered object files
493 /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
497 impl SplitDebuginfo {
498 fn as_str(&self) -> &'static str {
500 SplitDebuginfo::Off => "off",
501 SplitDebuginfo::Packed => "packed",
502 SplitDebuginfo::Unpacked => "unpacked",
507 impl FromStr for SplitDebuginfo {
510 fn from_str(s: &str) -> Result<SplitDebuginfo, ()> {
512 "off" => SplitDebuginfo::Off,
513 "unpacked" => SplitDebuginfo::Unpacked,
514 "packed" => SplitDebuginfo::Packed,
520 impl ToJson for SplitDebuginfo {
521 fn to_json(&self) -> Json {
522 self.as_str().to_json()
526 impl fmt::Display for SplitDebuginfo {
527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 f.write_str(self.as_str())
532 #[derive(Clone, Debug, PartialEq, Eq)]
533 pub enum StackProbeType {
534 /// Don't emit any stack probes.
536 /// It is harmless to use this option even on targets that do not have backend support for
537 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
540 /// Call `__rust_probestack` whenever stack needs to be probed.
542 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
543 /// and call `__rust_probestack` otherwise.
544 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
547 impl StackProbeType {
548 fn from_json(json: &Json) -> Result<Self, String> {
549 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
552 .and_then(|o| o.as_str())
553 .ok_or_else(|| "expected `kind` to be a string")?;
555 "none" => Ok(StackProbeType::None),
556 "inline" => Ok(StackProbeType::Inline),
557 "call" => Ok(StackProbeType::Call),
558 "inline-or-call" => {
559 let min_version = object
560 .get("min-llvm-version-for-inline")
561 .and_then(|o| o.as_array())
562 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
563 let mut iter = min_version.into_iter().map(|v| {
564 let int = v.as_u64().ok_or_else(
565 || "expected `min-llvm-version-for-inline` values to be integers",
568 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
570 let min_llvm_version_for_inline = (
571 iter.next().unwrap_or(Ok(11))?,
572 iter.next().unwrap_or(Ok(0))?,
573 iter.next().unwrap_or(Ok(0))?,
575 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
577 _ => Err(String::from(
578 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
584 impl ToJson for StackProbeType {
585 fn to_json(&self) -> Json {
586 Json::Object(match self {
587 StackProbeType::None => {
588 [(String::from("kind"), "none".to_json())].into_iter().collect()
590 StackProbeType::Inline => {
591 [(String::from("kind"), "inline".to_json())].into_iter().collect()
593 StackProbeType::Call => {
594 [(String::from("kind"), "call".to_json())].into_iter().collect()
596 StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
597 (String::from("kind"), "inline-or-call".to_json()),
599 String::from("min-llvm-version-for-inline"),
600 Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
609 bitflags::bitflags! {
610 #[derive(Default, Encodable, Decodable)]
611 pub struct SanitizerSet: u8 {
612 const ADDRESS = 1 << 0;
614 const MEMORY = 1 << 2;
615 const THREAD = 1 << 3;
616 const HWADDRESS = 1 << 4;
618 const MEMTAG = 1 << 6;
623 /// Return sanitizer's name
625 /// Returns none if the flags is a set of sanitizers numbering not exactly one.
626 pub fn as_str(self) -> Option<&'static str> {
628 SanitizerSet::ADDRESS => "address",
629 SanitizerSet::CFI => "cfi",
630 SanitizerSet::LEAK => "leak",
631 SanitizerSet::MEMORY => "memory",
632 SanitizerSet::MEMTAG => "memtag",
633 SanitizerSet::THREAD => "thread",
634 SanitizerSet::HWADDRESS => "hwaddress",
640 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
641 impl fmt::Display for SanitizerSet {
642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 let mut first = true;
645 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
656 impl IntoIterator for SanitizerSet {
657 type Item = SanitizerSet;
658 type IntoIter = std::vec::IntoIter<SanitizerSet>;
660 fn into_iter(self) -> Self::IntoIter {
662 SanitizerSet::ADDRESS,
665 SanitizerSet::MEMORY,
666 SanitizerSet::MEMTAG,
667 SanitizerSet::THREAD,
668 SanitizerSet::HWADDRESS,
672 .filter(|&s| self.contains(s))
678 impl<CTX> HashStable<CTX> for SanitizerSet {
679 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
680 self.bits().hash_stable(ctx, hasher);
684 impl ToJson for SanitizerSet {
685 fn to_json(&self) -> Json {
687 .map(|v| Some(v.as_str()?.to_json()))
688 .collect::<Option<Vec<_>>>()
694 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
695 pub enum FramePointer {
696 /// Forces the machine code generator to always preserve the frame pointers.
698 /// Forces the machine code generator to preserve the frame pointers except for the leaf
699 /// functions (i.e. those that don't call other functions).
701 /// Allows the machine code generator to omit the frame pointers.
703 /// This option does not guarantee that the frame pointers will be omitted.
707 impl FromStr for FramePointer {
709 fn from_str(s: &str) -> Result<Self, ()> {
711 "always" => Self::Always,
712 "non-leaf" => Self::NonLeaf,
713 "may-omit" => Self::MayOmit,
719 impl ToJson for FramePointer {
720 fn to_json(&self) -> Json {
722 Self::Always => "always",
723 Self::NonLeaf => "non-leaf",
724 Self::MayOmit => "may-omit",
730 /// Controls use of stack canaries.
731 #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
732 pub enum StackProtector {
733 /// Disable stack canary generation.
736 /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
737 /// llvm/docs/LangRef.rst). This triggers stack canary generation in
738 /// functions which contain an array of a byte-sized type with more than
742 /// On LLVM, mark all generated LLVM functions with the `sspstrong`
743 /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
744 /// generation in functions which either contain an array, or which take
745 /// the address of a local variable.
748 /// Generate stack canaries in all functions.
752 impl StackProtector {
753 fn as_str(&self) -> &'static str {
755 StackProtector::None => "none",
756 StackProtector::Basic => "basic",
757 StackProtector::Strong => "strong",
758 StackProtector::All => "all",
763 impl FromStr for StackProtector {
766 fn from_str(s: &str) -> Result<StackProtector, ()> {
768 "none" => StackProtector::None,
769 "basic" => StackProtector::Basic,
770 "strong" => StackProtector::Strong,
771 "all" => StackProtector::All,
777 impl fmt::Display for StackProtector {
778 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779 f.write_str(self.as_str())
783 macro_rules! supported_targets {
784 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
787 /// List of supported targets
788 pub const TARGETS: &[&str] = &[$($($triple),+),+];
790 fn load_builtin(target: &str) -> Option<Target> {
791 let mut t = match target {
792 $( $($triple)|+ => $module::target(), )+
796 debug!("got builtin target: {:?}", t);
804 // Cannot put this into a separate file without duplication, make an exception.
808 tests_impl::test_target(super::$module::target());
816 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
817 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
818 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
819 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
820 ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
821 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
822 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
823 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
824 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
825 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
826 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
827 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
828 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
829 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
830 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
831 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
832 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
833 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
834 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
835 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
836 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
837 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
838 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
839 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
840 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
841 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
842 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
843 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
844 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
845 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
846 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
847 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
848 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
849 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
850 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
851 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
852 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
853 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
854 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
855 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
856 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
857 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
858 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
859 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
860 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
861 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
862 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
863 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
865 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
866 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
868 ("i686-linux-android", i686_linux_android),
869 ("x86_64-linux-android", x86_64_linux_android),
870 ("arm-linux-androideabi", arm_linux_androideabi),
871 ("armv7-linux-androideabi", armv7_linux_androideabi),
872 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
873 ("aarch64-linux-android", aarch64_linux_android),
875 ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
877 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
878 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
879 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
880 ("i686-unknown-freebsd", i686_unknown_freebsd),
881 ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
882 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
883 ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
884 ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
885 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
887 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
889 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
890 ("i686-unknown-openbsd", i686_unknown_openbsd),
891 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
892 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
893 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
895 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
896 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
897 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
898 ("i686-unknown-netbsd", i686_unknown_netbsd),
899 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
900 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
901 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
903 ("i686-unknown-haiku", i686_unknown_haiku),
904 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
906 ("aarch64-apple-darwin", aarch64_apple_darwin),
907 ("x86_64-apple-darwin", x86_64_apple_darwin),
908 ("i686-apple-darwin", i686_apple_darwin),
910 ("aarch64-fuchsia", aarch64_fuchsia),
911 ("x86_64-fuchsia", x86_64_fuchsia),
913 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
915 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
917 ("aarch64-unknown-redox", aarch64_unknown_redox),
918 ("x86_64-unknown-redox", x86_64_unknown_redox),
920 ("i386-apple-ios", i386_apple_ios),
921 ("x86_64-apple-ios", x86_64_apple_ios),
922 ("aarch64-apple-ios", aarch64_apple_ios),
923 ("armv7-apple-ios", armv7_apple_ios),
924 ("armv7s-apple-ios", armv7s_apple_ios),
925 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
926 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
927 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
928 ("aarch64-apple-tvos", aarch64_apple_tvos),
929 ("x86_64-apple-tvos", x86_64_apple_tvos),
931 ("armebv7r-none-eabi", armebv7r_none_eabi),
932 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
933 ("armv7r-none-eabi", armv7r_none_eabi),
934 ("armv7r-none-eabihf", armv7r_none_eabihf),
936 ("x86_64-pc-solaris", x86_64_pc_solaris),
937 ("x86_64-sun-solaris", x86_64_sun_solaris),
938 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
940 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
942 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
943 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
944 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
945 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
947 ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
948 ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
950 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
951 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
952 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
953 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
954 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
955 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
956 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
957 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
958 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
960 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
961 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
962 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
963 ("wasm32-wasi", wasm32_wasi),
964 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
966 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
967 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
968 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
969 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
970 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
971 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
972 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
974 ("armv7a-none-eabi", armv7a_none_eabi),
975 ("armv7a-none-eabihf", armv7a_none_eabihf),
977 ("msp430-none-elf", msp430_none_elf),
979 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
980 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
982 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
983 ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
984 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
985 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
986 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
987 ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
988 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
989 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
990 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
991 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
992 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
993 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
995 ("aarch64-unknown-none", aarch64_unknown_none),
996 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
998 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1000 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1001 ("i686-unknown-uefi", i686_unknown_uefi),
1002 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1004 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1006 ("i686-wrs-vxworks", i686_wrs_vxworks),
1007 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1008 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1009 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1010 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1011 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1012 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1014 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1015 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1016 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1018 ("mipsel-sony-psp", mipsel_sony_psp),
1019 ("mipsel-unknown-none", mipsel_unknown_none),
1020 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1022 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1023 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1024 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1026 ("bpfeb-unknown-none", bpfeb_unknown_none),
1027 ("bpfel-unknown-none", bpfel_unknown_none),
1029 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1031 ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1032 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1034 ("x86_64-unknown-none", x86_64_unknown_none),
1036 ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1039 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1042 ::std::borrow::Cow::Borrowed(&[])
1044 ($($x:expr),+ $(,)?) => {
1045 ::std::borrow::Cow::Borrowed(&[
1047 ::std::borrow::Cow::Borrowed($x),
1055 /// Warnings encountered when parsing the target `json`.
1057 /// Includes fields that weren't recognized and fields that don't have the expected type.
1058 #[derive(Debug, PartialEq)]
1059 pub struct TargetWarnings {
1060 unused_fields: Vec<String>,
1061 incorrect_type: Vec<String>,
1064 impl TargetWarnings {
1065 pub fn empty() -> Self {
1066 Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1069 pub fn warning_messages(&self) -> Vec<String> {
1070 let mut warnings = vec![];
1071 if !self.unused_fields.is_empty() {
1072 warnings.push(format!(
1073 "target json file contains unused fields: {}",
1074 self.unused_fields.join(", ")
1077 if !self.incorrect_type.is_empty() {
1078 warnings.push(format!(
1079 "target json file contains fields whose value doesn't have the correct json type: {}",
1080 self.incorrect_type.join(", ")
1087 /// Everything `rustc` knows about how to compile for a specific target.
1089 /// Every field here must be specified, and has no default value.
1090 #[derive(PartialEq, Clone, Debug)]
1092 /// Target triple to pass to LLVM.
1093 pub llvm_target: StaticCow<str>,
1094 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1095 pub pointer_width: u32,
1096 /// Architecture to use for ABI considerations. Valid options include: "x86",
1097 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1098 pub arch: StaticCow<str>,
1099 /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1100 pub data_layout: StaticCow<str>,
1101 /// Optional settings with defaults.
1102 pub options: TargetOptions,
1105 pub trait HasTargetSpec {
1106 fn target_spec(&self) -> &Target;
1109 impl HasTargetSpec for Target {
1111 fn target_spec(&self) -> &Target {
1116 type StaticCow<T> = Cow<'static, T>;
1118 /// Optional aspects of a target specification.
1120 /// This has an implementation of `Default`, see each field for what the default is. In general,
1121 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1123 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1124 /// construction, all its fields logically belong to `Target` and available from `Target`
1125 /// through `Deref` impls.
1126 #[derive(PartialEq, Clone, Debug)]
1127 pub struct TargetOptions {
1128 /// Whether the target is built-in or loaded from a custom target specification.
1129 pub is_builtin: bool,
1131 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1133 /// Width of c_int type. Defaults to "32".
1134 pub c_int_width: StaticCow<str>,
1135 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1136 /// "none" implies a bare metal target without `std` library.
1137 /// A couple of targets having `std` also use "unknown" as an `os` value,
1138 /// but they are exceptions.
1139 pub os: StaticCow<str>,
1140 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1141 pub env: StaticCow<str>,
1142 /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1143 /// or `"eabihf"`. Defaults to "".
1144 pub abi: StaticCow<str>,
1145 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1146 pub vendor: StaticCow<str>,
1147 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1148 /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1149 pub linker_flavor: LinkerFlavor,
1151 /// Linker to invoke
1152 pub linker: Option<StaticCow<str>>,
1154 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1155 /// without clarifying its flavor in any way.
1156 pub lld_flavor: LldFlavor,
1158 /// Linker arguments that are passed *before* any user-defined libraries.
1159 pub pre_link_args: LinkArgs,
1160 /// Objects to link before and after all other object code.
1161 pub pre_link_objects: CrtObjects,
1162 pub post_link_objects: CrtObjects,
1163 /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
1164 /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
1165 /// See `crt_objects.rs` for some more detailed documentation.
1166 pub pre_link_objects_fallback: CrtObjects,
1167 pub post_link_objects_fallback: CrtObjects,
1168 /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
1169 pub crt_objects_fallback: Option<CrtObjectsFallback>,
1171 /// Linker arguments that are unconditionally passed after any
1172 /// user-defined but before post-link objects. Standard platform
1173 /// libraries that should be always be linked to, usually go here.
1174 pub late_link_args: LinkArgs,
1175 /// Linker arguments used in addition to `late_link_args` if at least one
1176 /// Rust dependency is dynamically linked.
1177 pub late_link_args_dynamic: LinkArgs,
1178 /// Linker arguments used in addition to `late_link_args` if all Rust
1179 /// dependencies are statically linked.
1180 pub late_link_args_static: LinkArgs,
1181 /// Linker arguments that are unconditionally passed *after* any
1182 /// user-defined libraries.
1183 pub post_link_args: LinkArgs,
1184 /// Optional link script applied to `dylib` and `executable` crate types.
1185 /// This is a string containing the script, not a path. Can only be applied
1186 /// to linkers where `linker_is_gnu` is true.
1187 pub link_script: Option<StaticCow<str>>,
1189 /// Environment variables to be set for the linker invocation.
1190 pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1191 /// Environment variables to be removed for the linker invocation.
1192 pub link_env_remove: StaticCow<[StaticCow<str>]>,
1194 /// Extra arguments to pass to the external assembler (when used)
1195 pub asm_args: StaticCow<[StaticCow<str>]>,
1197 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1199 pub cpu: StaticCow<str>,
1200 /// Default target features to pass to LLVM. These features will *always* be
1201 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1202 /// -mattr=$features`.
1203 pub features: StaticCow<str>,
1204 /// Whether dynamic linking is available on this target. Defaults to false.
1205 pub dynamic_linking: bool,
1206 /// If dynamic linking is available, whether only cdylibs are supported.
1207 pub only_cdylib: bool,
1208 /// Whether executables are available on this target. iOS, for example, only allows static
1209 /// libraries. Defaults to false.
1210 pub executables: bool,
1211 /// Relocation model to use in object file. Corresponds to `llc
1212 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1213 pub relocation_model: RelocModel,
1214 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1215 /// Defaults to `None` which means "inherited from the base LLVM target".
1216 pub code_model: Option<CodeModel>,
1217 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1218 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1219 pub tls_model: TlsModel,
1220 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1221 pub disable_redzone: bool,
1222 /// Frame pointer mode for this target. Defaults to `MayOmit`.
1223 pub frame_pointer: FramePointer,
1224 /// Emit each function in its own section. Defaults to true.
1225 pub function_sections: bool,
1226 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1227 pub dll_prefix: StaticCow<str>,
1228 /// String to append to the name of every dynamic library. Defaults to ".so".
1229 pub dll_suffix: StaticCow<str>,
1230 /// String to append to the name of every executable.
1231 pub exe_suffix: StaticCow<str>,
1232 /// String to prepend to the name of every static library. Defaults to "lib".
1233 pub staticlib_prefix: StaticCow<str>,
1234 /// String to append to the name of every static library. Defaults to ".a".
1235 pub staticlib_suffix: StaticCow<str>,
1236 /// Values of the `target_family` cfg set for this target.
1238 /// Common options are: "unix", "windows". Defaults to no families.
1240 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1241 pub families: StaticCow<[StaticCow<str>]>,
1242 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1243 pub abi_return_struct_as_int: bool,
1244 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1245 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1246 pub is_like_osx: bool,
1247 /// Whether the target toolchain is like Solaris's.
1248 /// Only useful for compiling against Illumos/Solaris,
1249 /// as they have a different set of linker flags. Defaults to false.
1250 pub is_like_solaris: bool,
1251 /// Whether the target is like Windows.
1252 /// This is a combination of several more specific properties represented as a single flag:
1253 /// - The target uses a Windows ABI,
1254 /// - uses PE/COFF as a format for object code,
1255 /// - uses Windows-style dllexport/dllimport for shared libraries,
1256 /// - uses import libraries and .def files for symbol exports,
1257 /// - executables support setting a subsystem.
1258 pub is_like_windows: bool,
1259 /// Whether the target is like MSVC.
1260 /// This is a combination of several more specific properties represented as a single flag:
1261 /// - The target has all the properties from `is_like_windows`
1262 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1263 /// - has some MSVC-specific Windows ABI properties,
1264 /// - uses a link.exe-like linker,
1265 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1266 /// - uses SEH-based unwinding,
1267 /// - supports control flow guard mechanism.
1268 pub is_like_msvc: bool,
1269 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1270 /// Emscripten toolchain.
1271 /// Defaults to false.
1272 pub is_like_emscripten: bool,
1273 /// Whether the target toolchain is like Fuchsia's.
1274 pub is_like_fuchsia: bool,
1275 /// Whether a target toolchain is like WASM.
1276 pub is_like_wasm: bool,
1277 /// Version of DWARF to use if not using the default.
1278 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1279 pub dwarf_version: Option<u32>,
1280 /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1281 pub linker_is_gnu: bool,
1282 /// The MinGW toolchain has a known issue that prevents it from correctly
1283 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1284 /// symbol needs its own COMDAT section, weak linkage implies a large
1285 /// number sections that easily exceeds the given limit for larger
1286 /// codebases. Consequently we want a way to disallow weak linkage on some
1288 pub allows_weak_linkage: bool,
1289 /// Whether the linker support rpaths or not. Defaults to false.
1290 pub has_rpath: bool,
1291 /// Whether to disable linking to the default libraries, typically corresponds
1292 /// to `-nodefaultlibs`. Defaults to true.
1293 pub no_default_libraries: bool,
1294 /// Dynamically linked executables can be compiled as position independent
1295 /// if the default relocation model of position independent code is not
1296 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1297 /// the functions in the executable are not randomized and can be used
1298 /// during an exploit of a vulnerability in any code.
1299 pub position_independent_executables: bool,
1300 /// Executables that are both statically linked and position-independent are supported.
1301 pub static_position_independent_executables: bool,
1302 /// Determines if the target always requires using the PLT for indirect
1303 /// library calls or not. This controls the default value of the `-Z plt` flag.
1304 pub needs_plt: bool,
1305 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1306 /// resolve all symbols at startup and marks the GOT read-only before
1307 /// starting the program, preventing overwriting the GOT.
1308 pub relro_level: RelroLevel,
1309 /// Format that archives should be emitted in. This affects whether we use
1310 /// LLVM to assemble an archive or fall back to the system linker, and
1311 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1312 /// the system linker to be used.
1313 pub archive_format: StaticCow<str>,
1314 /// Is asm!() allowed? Defaults to true.
1315 pub allow_asm: bool,
1316 /// Whether the runtime startup code requires the `main` function be passed
1317 /// `argc` and `argv` values.
1318 pub main_needs_argc_argv: bool,
1320 /// Flag indicating whether #[thread_local] is available for this target.
1321 pub has_thread_local: bool,
1322 // This is mainly for easy compatibility with emscripten.
1323 // If we give emcc .o files that are actually .bc files it
1324 // will 'just work'.
1325 pub obj_is_bitcode: bool,
1326 /// Whether the target requires that emitted object code includes bitcode.
1327 pub forces_embed_bitcode: bool,
1328 /// Content of the LLVM cmdline section associated with embedded bitcode.
1329 pub bitcode_llvm_cmdline: StaticCow<str>,
1331 /// Don't use this field; instead use the `.min_atomic_width()` method.
1332 pub min_atomic_width: Option<u64>,
1334 /// Don't use this field; instead use the `.max_atomic_width()` method.
1335 pub max_atomic_width: Option<u64>,
1337 /// Whether the target supports atomic CAS operations natively
1338 pub atomic_cas: bool,
1340 /// Panic strategy: "unwind" or "abort"
1341 pub panic_strategy: PanicStrategy,
1343 /// Whether or not linking dylibs to a static CRT is allowed.
1344 pub crt_static_allows_dylibs: bool,
1345 /// Whether or not the CRT is statically linked by default.
1346 pub crt_static_default: bool,
1347 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1348 pub crt_static_respected: bool,
1350 /// The implementation of stack probes to use.
1351 pub stack_probes: StackProbeType,
1353 /// The minimum alignment for global symbols.
1354 pub min_global_align: Option<u64>,
1356 /// Default number of codegen units to use in debug mode
1357 pub default_codegen_units: Option<u64>,
1359 /// Whether to generate trap instructions in places where optimization would
1360 /// otherwise produce control flow that falls through into unrelated memory.
1361 pub trap_unreachable: bool,
1363 /// This target requires everything to be compiled with LTO to emit a final
1364 /// executable, aka there is no native linker for this target.
1365 pub requires_lto: bool,
1367 /// This target has no support for threads.
1368 pub singlethread: bool,
1370 /// Whether library functions call lowering/optimization is disabled in LLVM
1371 /// for this target unconditionally.
1372 pub no_builtins: bool,
1374 /// The default visibility for symbols in this target should be "hidden"
1375 /// rather than "default"
1376 pub default_hidden_visibility: bool,
1378 /// Whether a .debug_gdb_scripts section will be added to the output object file
1379 pub emit_debug_gdb_scripts: bool,
1381 /// Whether or not to unconditionally `uwtable` attributes on functions,
1382 /// typically because the platform needs to unwind for things like stack
1384 pub requires_uwtable: bool,
1386 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1387 /// is not specified and `uwtable` is not required on this target.
1388 pub default_uwtable: bool,
1390 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1391 /// typically required if a target can be compiled with a mixed set of
1392 /// target features. This is `true` by default, and `false` for targets like
1393 /// wasm32 where the whole program either has simd or not.
1394 pub simd_types_indirect: bool,
1396 /// Pass a list of symbol which should be exported in the dylib to the linker.
1397 pub limit_rdylib_exports: bool,
1399 /// If set, have the linker export exactly these symbols, instead of using
1400 /// the usual logic to figure this out from the crate itself.
1401 pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1403 /// Determines how or whether the MergeFunctions LLVM pass should run for
1404 /// this target. Either "disabled", "trampolines", or "aliases".
1405 /// The MergeFunctions pass is generally useful, but some targets may need
1406 /// to opt out. The default is "aliases".
1408 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1409 pub merge_functions: MergeFunctions,
1411 /// Use platform dependent mcount function
1412 pub mcount: StaticCow<str>,
1414 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1415 pub llvm_abiname: StaticCow<str>,
1417 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1418 pub relax_elf_relocations: bool,
1420 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1421 pub llvm_args: StaticCow<[StaticCow<str>]>,
1423 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1424 /// to false (uses .init_array).
1425 pub use_ctors_section: bool,
1427 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1428 /// used to locate unwinding information is passed
1429 /// (only has effect if the linker is `ld`-like).
1430 pub eh_frame_header: bool,
1432 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1433 /// thumb and arm interworking.
1434 pub has_thumb_interworking: bool,
1436 /// How to handle split debug information, if at all. Specifying `None` has
1437 /// target-specific meaning.
1438 pub split_debuginfo: SplitDebuginfo,
1440 /// The sanitizers supported by this target
1442 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1443 /// enabled can generated on this target, but the necessary supporting libraries are not
1444 /// distributed with the target, the sanitizer should still appear in this list for the target.
1445 pub supported_sanitizers: SanitizerSet,
1447 /// If present it's a default value to use for adjusting the C ABI.
1448 pub default_adjusted_cabi: Option<Abi>,
1450 /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1451 pub c_enum_min_bits: u64,
1453 /// Whether or not the DWARF `.debug_aranges` section should be generated.
1454 pub generate_arange_section: bool,
1456 /// Whether the target supports stack canary checks. `true` by default,
1457 /// since this is most common among tier 1 and tier 2 targets.
1458 pub supports_stack_protector: bool,
1461 impl Default for TargetOptions {
1462 /// Creates a set of "sane defaults" for any target. This is still
1463 /// incomplete, and if used for compilation, will certainly not work.
1464 fn default() -> TargetOptions {
1467 endian: Endian::Little,
1468 c_int_width: "32".into(),
1472 vendor: "unknown".into(),
1473 linker_flavor: LinkerFlavor::Gcc,
1474 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1475 lld_flavor: LldFlavor::Ld,
1476 pre_link_args: LinkArgs::new(),
1477 post_link_args: LinkArgs::new(),
1480 cpu: "generic".into(),
1481 features: "".into(),
1482 dynamic_linking: false,
1485 relocation_model: RelocModel::Pic,
1487 tls_model: TlsModel::GeneralDynamic,
1488 disable_redzone: false,
1489 frame_pointer: FramePointer::MayOmit,
1490 function_sections: true,
1491 dll_prefix: "lib".into(),
1492 dll_suffix: ".so".into(),
1493 exe_suffix: "".into(),
1494 staticlib_prefix: "lib".into(),
1495 staticlib_suffix: ".a".into(),
1497 abi_return_struct_as_int: false,
1499 is_like_solaris: false,
1500 is_like_windows: false,
1501 is_like_emscripten: false,
1502 is_like_msvc: false,
1503 is_like_fuchsia: false,
1504 is_like_wasm: false,
1505 dwarf_version: None,
1506 linker_is_gnu: true,
1507 allows_weak_linkage: true,
1509 no_default_libraries: true,
1510 position_independent_executables: false,
1511 static_position_independent_executables: false,
1513 relro_level: RelroLevel::None,
1514 pre_link_objects: Default::default(),
1515 post_link_objects: Default::default(),
1516 pre_link_objects_fallback: Default::default(),
1517 post_link_objects_fallback: Default::default(),
1518 crt_objects_fallback: None,
1519 late_link_args: LinkArgs::new(),
1520 late_link_args_dynamic: LinkArgs::new(),
1521 late_link_args_static: LinkArgs::new(),
1523 link_env_remove: cvs![],
1524 archive_format: "gnu".into(),
1525 main_needs_argc_argv: true,
1527 has_thread_local: false,
1528 obj_is_bitcode: false,
1529 forces_embed_bitcode: false,
1530 bitcode_llvm_cmdline: "".into(),
1531 min_atomic_width: None,
1532 max_atomic_width: None,
1534 panic_strategy: PanicStrategy::Unwind,
1535 crt_static_allows_dylibs: false,
1536 crt_static_default: false,
1537 crt_static_respected: false,
1538 stack_probes: StackProbeType::None,
1539 min_global_align: None,
1540 default_codegen_units: None,
1541 trap_unreachable: true,
1542 requires_lto: false,
1543 singlethread: false,
1545 default_hidden_visibility: false,
1546 emit_debug_gdb_scripts: true,
1547 requires_uwtable: false,
1548 default_uwtable: false,
1549 simd_types_indirect: true,
1550 limit_rdylib_exports: true,
1551 override_export_symbols: None,
1552 merge_functions: MergeFunctions::Aliases,
1553 mcount: "mcount".into(),
1554 llvm_abiname: "".into(),
1555 relax_elf_relocations: false,
1557 use_ctors_section: false,
1558 eh_frame_header: true,
1559 has_thumb_interworking: false,
1560 split_debuginfo: SplitDebuginfo::Off,
1561 supported_sanitizers: SanitizerSet::empty(),
1562 default_adjusted_cabi: None,
1563 c_enum_min_bits: 32,
1564 generate_arange_section: true,
1565 supports_stack_protector: true,
1570 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1571 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1572 /// this `Deref` implementation is no longer necessary.
1573 impl Deref for Target {
1574 type Target = TargetOptions;
1577 fn deref(&self) -> &Self::Target {
1581 impl DerefMut for Target {
1583 fn deref_mut(&mut self) -> &mut Self::Target {
1589 /// Given a function ABI, turn it into the correct ABI for this target.
1590 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1592 Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1593 Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1594 Abi::Stdcall { unwind }
1596 Abi::System { unwind } => Abi::C { unwind },
1597 Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1598 Abi::EfiApi => Abi::C { unwind: false },
1600 // See commentary in `is_abi_supported`.
1601 Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1602 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1603 Abi::Fastcall { .. } if self.arch == "x86" => abi,
1604 Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1605 Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1611 /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1612 pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1625 X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1626 Aapcs { .. } => "arm" == self.arch,
1627 CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1628 Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1629 PtxKernel => self.arch == "nvptx64",
1630 Msp430Interrupt => self.arch == "msp430",
1631 AmdGpuKernel => self.arch == "amdgcn",
1632 AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1633 Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1634 Thiscall { .. } => self.arch == "x86",
1635 // On windows these fall-back to platform native calling convention (C) when the
1636 // architecture is not supported.
1638 // This is I believe a historical accident that has occurred as part of Microsoft
1639 // striving to allow most of the code to "just" compile when support for 64-bit x86
1640 // was added and then later again, when support for ARM architectures was added.
1642 // This is well documented across MSDN. Support for this in Rust has been added in
1643 // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1644 // Rust, but there isn't much leeway remaining here to change it back at the time this
1645 // comment has been written.
1647 // Following are the relevant excerpts from the MSDN documentation.
1649 // > The __vectorcall calling convention is only supported in native code on x86 and
1650 // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1652 // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1654 // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1656 // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1658 // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1660 // > In most cases, keywords or compiler switches that specify an unsupported
1661 // > convention on a particular platform are ignored, and the platform default
1662 // > convention is used.
1664 // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1665 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1666 // Outside of Windows we want to only support these calling conventions for the
1667 // architectures for which these calling conventions are actually well defined.
1668 Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1669 Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1670 // Return a `None` for other cases so that we know to emit a future compat lint.
1671 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1675 /// Minimum integer size in bits that this target can perform atomic
1677 pub fn min_atomic_width(&self) -> u64 {
1678 self.min_atomic_width.unwrap_or(8)
1681 /// Maximum integer size in bits that this target can perform atomic
1683 pub fn max_atomic_width(&self) -> u64 {
1684 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1687 /// Loads a target descriptor from a JSON object.
1688 pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
1689 // While ugly, this code must remain this way to retain
1690 // compatibility with existing JSON fields and the internal
1691 // expected naming of the Target and TargetOptions structs.
1692 // To ensure compatibility is retained, the built-in targets
1693 // are round-tripped through this code to catch cases where
1694 // the JSON parser is not updated to match the structs.
1696 let mut obj = match obj {
1697 Value::Object(obj) => obj,
1698 _ => return Err("Expected JSON object for target")?,
1701 let mut get_req_field = |name: &str| {
1703 .and_then(|j| j.as_str().map(str::to_string))
1704 .ok_or_else(|| format!("Field {} in target specification is required", name))
1707 let mut base = Target {
1708 llvm_target: get_req_field("llvm-target")?.into(),
1709 pointer_width: get_req_field("target-pointer-width")?
1711 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1712 data_layout: get_req_field("data-layout")?.into(),
1713 arch: get_req_field("arch")?.into(),
1714 options: Default::default(),
1717 let mut incorrect_type = vec![];
1720 ($key_name:ident) => ( {
1721 let name = (stringify!($key_name)).replace("_", "-");
1722 if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1726 ($key_name:ident = $json_name:expr) => ( {
1727 let name = $json_name;
1728 if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1732 ($key_name:ident, bool) => ( {
1733 let name = (stringify!($key_name)).replace("_", "-");
1734 if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
1738 ($key_name:ident, u64) => ( {
1739 let name = (stringify!($key_name)).replace("_", "-");
1740 if let Some(s) = obj.remove(&name).and_then(|j| Json::as_u64(&j)) {
1744 ($key_name:ident, Option<u32>) => ( {
1745 let name = (stringify!($key_name)).replace("_", "-");
1746 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1748 return Err("Not a valid DWARF version number".into());
1750 base.$key_name = Some(s as u32);
1753 ($key_name:ident, Option<u64>) => ( {
1754 let name = (stringify!($key_name)).replace("_", "-");
1755 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1756 base.$key_name = Some(s);
1759 ($key_name:ident, MergeFunctions) => ( {
1760 let name = (stringify!($key_name)).replace("_", "-");
1761 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1762 match s.parse::<MergeFunctions>() {
1763 Ok(mergefunc) => base.$key_name = mergefunc,
1764 _ => return Some(Err(format!("'{}' is not a valid value for \
1765 merge-functions. Use 'disabled', \
1766 'trampolines', or 'aliases'.",
1770 })).unwrap_or(Ok(()))
1772 ($key_name:ident, RelocModel) => ( {
1773 let name = (stringify!($key_name)).replace("_", "-");
1774 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1775 match s.parse::<RelocModel>() {
1776 Ok(relocation_model) => base.$key_name = relocation_model,
1777 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1778 Run `rustc --print relocation-models` to \
1779 see the list of supported values.", s))),
1782 })).unwrap_or(Ok(()))
1784 ($key_name:ident, CodeModel) => ( {
1785 let name = (stringify!($key_name)).replace("_", "-");
1786 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1787 match s.parse::<CodeModel>() {
1788 Ok(code_model) => base.$key_name = Some(code_model),
1789 _ => return Some(Err(format!("'{}' is not a valid code model. \
1790 Run `rustc --print code-models` to \
1791 see the list of supported values.", s))),
1794 })).unwrap_or(Ok(()))
1796 ($key_name:ident, TlsModel) => ( {
1797 let name = (stringify!($key_name)).replace("_", "-");
1798 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1799 match s.parse::<TlsModel>() {
1800 Ok(tls_model) => base.$key_name = tls_model,
1801 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1802 Run `rustc --print tls-models` to \
1803 see the list of supported values.", s))),
1806 })).unwrap_or(Ok(()))
1808 ($key_name:ident, PanicStrategy) => ( {
1809 let name = (stringify!($key_name)).replace("_", "-");
1810 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1812 "unwind" => base.$key_name = PanicStrategy::Unwind,
1813 "abort" => base.$key_name = PanicStrategy::Abort,
1814 _ => return Some(Err(format!("'{}' is not a valid value for \
1815 panic-strategy. Use 'unwind' or 'abort'.",
1819 })).unwrap_or(Ok(()))
1821 ($key_name:ident, RelroLevel) => ( {
1822 let name = (stringify!($key_name)).replace("_", "-");
1823 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1824 match s.parse::<RelroLevel>() {
1825 Ok(level) => base.$key_name = level,
1826 _ => return Some(Err(format!("'{}' is not a valid value for \
1827 relro-level. Use 'full', 'partial, or 'off'.",
1831 })).unwrap_or(Ok(()))
1833 ($key_name:ident, SplitDebuginfo) => ( {
1834 let name = (stringify!($key_name)).replace("_", "-");
1835 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1836 match s.parse::<SplitDebuginfo>() {
1837 Ok(level) => base.$key_name = level,
1838 _ => return Some(Err(format!("'{}' is not a valid value for \
1839 split-debuginfo. Use 'off' or 'dsymutil'.",
1843 })).unwrap_or(Ok(()))
1845 ($key_name:ident, list) => ( {
1846 let name = (stringify!($key_name)).replace("_", "-");
1847 if let Some(j) = obj.remove(&name) {
1848 if let Some(v) = j.as_array() {
1849 base.$key_name = v.iter()
1850 .map(|a| a.as_str().unwrap().to_string().into())
1853 incorrect_type.push(name)
1857 ($key_name:ident, opt_list) => ( {
1858 let name = (stringify!($key_name)).replace("_", "-");
1859 if let Some(j) = obj.remove(&name) {
1860 if let Some(v) = j.as_array() {
1861 base.$key_name = Some(v.iter()
1862 .map(|a| a.as_str().unwrap().to_string().into())
1865 incorrect_type.push(name)
1869 ($key_name:ident, optional) => ( {
1870 let name = (stringify!($key_name)).replace("_", "-");
1871 if let Some(o) = obj.remove(&name) {
1874 .map(|s| s.to_string().into());
1877 ($key_name:ident, LldFlavor) => ( {
1878 let name = (stringify!($key_name)).replace("_", "-");
1879 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1880 if let Some(flavor) = LldFlavor::from_str(&s) {
1881 base.$key_name = flavor;
1883 return Some(Err(format!(
1884 "'{}' is not a valid value for lld-flavor. \
1885 Use 'darwin', 'gnu', 'link' or 'wasm.",
1889 })).unwrap_or(Ok(()))
1891 ($key_name:ident, LinkerFlavor) => ( {
1892 let name = (stringify!($key_name)).replace("_", "-");
1893 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1894 match LinkerFlavor::from_str(s) {
1895 Some(linker_flavor) => base.$key_name = linker_flavor,
1896 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1897 Use {}", s, LinkerFlavor::one_of()))),
1900 })).unwrap_or(Ok(()))
1902 ($key_name:ident, StackProbeType) => ( {
1903 let name = (stringify!($key_name)).replace("_", "-");
1904 obj.remove(&name).and_then(|o| match StackProbeType::from_json(&o) {
1910 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1912 }).unwrap_or(Ok(()))
1914 ($key_name:ident, SanitizerSet) => ( {
1915 let name = (stringify!($key_name)).replace("_", "-");
1916 if let Some(o) = obj.remove(&name) {
1917 if let Some(a) = o.as_array() {
1919 base.$key_name |= match s.as_str() {
1920 Some("address") => SanitizerSet::ADDRESS,
1921 Some("cfi") => SanitizerSet::CFI,
1922 Some("leak") => SanitizerSet::LEAK,
1923 Some("memory") => SanitizerSet::MEMORY,
1924 Some("memtag") => SanitizerSet::MEMTAG,
1925 Some("thread") => SanitizerSet::THREAD,
1926 Some("hwaddress") => SanitizerSet::HWADDRESS,
1927 Some(s) => return Err(format!("unknown sanitizer {}", s)),
1928 _ => return Err(format!("not a string: {:?}", s)),
1932 incorrect_type.push(name)
1935 Ok::<(), String>(())
1938 ($key_name:ident, crt_objects_fallback) => ( {
1939 let name = (stringify!($key_name)).replace("_", "-");
1940 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1941 match s.parse::<CrtObjectsFallback>() {
1942 Ok(fallback) => base.$key_name = Some(fallback),
1943 _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1944 Use 'musl', 'mingw' or 'wasm'", s))),
1947 })).unwrap_or(Ok(()))
1949 ($key_name:ident, link_objects) => ( {
1950 let name = (stringify!($key_name)).replace("_", "-");
1951 if let Some(val) = obj.remove(&name) {
1952 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1953 JSON object with fields per CRT object kind.", name))?;
1954 let mut args = CrtObjects::new();
1956 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1957 format!("{}: '{}' is not a valid value for CRT object kind. \
1958 Use '(dynamic,static)-(nopic,pic)-exe' or \
1959 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1962 let v = v.as_array().ok_or_else(||
1963 format!("{}.{}: expected a JSON array", name, k)
1964 )?.iter().enumerate()
1966 let s = s.as_str().ok_or_else(||
1967 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1968 Ok(s.to_string().into())
1970 .collect::<Result<Vec<_>, String>>()?;
1972 args.insert(kind, v);
1974 base.$key_name = args;
1977 ($key_name:ident, link_args) => ( {
1978 let name = (stringify!($key_name)).replace("_", "-");
1979 if let Some(val) = obj.remove(&name) {
1980 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1981 JSON object with fields per linker-flavor.", name))?;
1982 let mut args = LinkArgs::new();
1984 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1985 format!("{}: '{}' is not a valid value for linker-flavor. \
1986 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1989 let v = v.as_array().ok_or_else(||
1990 format!("{}.{}: expected a JSON array", name, k)
1991 )?.iter().enumerate()
1993 let s = s.as_str().ok_or_else(||
1994 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1995 Ok(s.to_string().into())
1997 .collect::<Result<Vec<_>, String>>()?;
1999 args.insert(flavor, v);
2001 base.$key_name = args;
2004 ($key_name:ident, env) => ( {
2005 let name = (stringify!($key_name)).replace("_", "-");
2006 if let Some(o) = obj.remove(&name) {
2007 if let Some(a) = o.as_array() {
2009 if let Some(s) = o.as_str() {
2010 let p = s.split('=').collect::<Vec<_>>();
2012 let k = p[0].to_string();
2013 let v = p[1].to_string();
2014 base.$key_name.to_mut().push((k.into(), v.into()));
2019 incorrect_type.push(name)
2023 ($key_name:ident, Option<Abi>) => ( {
2024 let name = (stringify!($key_name)).replace("_", "-");
2025 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2026 match lookup_abi(s) {
2027 Some(abi) => base.$key_name = Some(abi),
2028 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2031 })).unwrap_or(Ok(()))
2033 ($key_name:ident, TargetFamilies) => ( {
2034 if let Some(value) = obj.remove("target-family") {
2035 if let Some(v) = value.as_array() {
2036 base.$key_name = v.iter()
2037 .map(|a| a.as_str().unwrap().to_string().into())
2039 } else if let Some(v) = value.as_str() {
2040 base.$key_name = vec![v.to_string().into()].into();
2046 if let Some(j) = obj.remove("target-endian") {
2047 if let Some(s) = j.as_str() {
2048 base.endian = s.parse()?;
2050 incorrect_type.push("target-endian".into())
2054 if let Some(fp) = obj.remove("frame-pointer") {
2055 if let Some(s) = fp.as_str() {
2056 base.frame_pointer = s
2058 .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2060 incorrect_type.push("frame-pointer".into())
2064 key!(is_builtin, bool);
2065 key!(c_int_width = "target-c-int-width");
2070 key!(linker_flavor, LinkerFlavor)?;
2071 key!(linker, optional);
2072 key!(lld_flavor, LldFlavor)?;
2073 key!(pre_link_objects, link_objects);
2074 key!(post_link_objects, link_objects);
2075 key!(pre_link_objects_fallback, link_objects);
2076 key!(post_link_objects_fallback, link_objects);
2077 key!(crt_objects_fallback, crt_objects_fallback)?;
2078 key!(pre_link_args, link_args);
2079 key!(late_link_args, link_args);
2080 key!(late_link_args_dynamic, link_args);
2081 key!(late_link_args_static, link_args);
2082 key!(post_link_args, link_args);
2083 key!(link_script, optional);
2084 key!(link_env, env);
2085 key!(link_env_remove, list);
2086 key!(asm_args, list);
2089 key!(dynamic_linking, bool);
2090 key!(only_cdylib, bool);
2091 key!(executables, bool);
2092 key!(relocation_model, RelocModel)?;
2093 key!(code_model, CodeModel)?;
2094 key!(tls_model, TlsModel)?;
2095 key!(disable_redzone, bool);
2096 key!(function_sections, bool);
2100 key!(staticlib_prefix);
2101 key!(staticlib_suffix);
2102 key!(families, TargetFamilies);
2103 key!(abi_return_struct_as_int, bool);
2104 key!(is_like_osx, bool);
2105 key!(is_like_solaris, bool);
2106 key!(is_like_windows, bool);
2107 key!(is_like_msvc, bool);
2108 key!(is_like_emscripten, bool);
2109 key!(is_like_fuchsia, bool);
2110 key!(is_like_wasm, bool);
2111 key!(dwarf_version, Option<u32>);
2112 key!(linker_is_gnu, bool);
2113 key!(allows_weak_linkage, bool);
2114 key!(has_rpath, bool);
2115 key!(no_default_libraries, bool);
2116 key!(position_independent_executables, bool);
2117 key!(static_position_independent_executables, bool);
2118 key!(needs_plt, bool);
2119 key!(relro_level, RelroLevel)?;
2120 key!(archive_format);
2121 key!(allow_asm, bool);
2122 key!(main_needs_argc_argv, bool);
2123 key!(has_thread_local, bool);
2124 key!(obj_is_bitcode, bool);
2125 key!(forces_embed_bitcode, bool);
2126 key!(bitcode_llvm_cmdline);
2127 key!(max_atomic_width, Option<u64>);
2128 key!(min_atomic_width, Option<u64>);
2129 key!(atomic_cas, bool);
2130 key!(panic_strategy, PanicStrategy)?;
2131 key!(crt_static_allows_dylibs, bool);
2132 key!(crt_static_default, bool);
2133 key!(crt_static_respected, bool);
2134 key!(stack_probes, StackProbeType)?;
2135 key!(min_global_align, Option<u64>);
2136 key!(default_codegen_units, Option<u64>);
2137 key!(trap_unreachable, bool);
2138 key!(requires_lto, bool);
2139 key!(singlethread, bool);
2140 key!(no_builtins, bool);
2141 key!(default_hidden_visibility, bool);
2142 key!(emit_debug_gdb_scripts, bool);
2143 key!(requires_uwtable, bool);
2144 key!(default_uwtable, bool);
2145 key!(simd_types_indirect, bool);
2146 key!(limit_rdylib_exports, bool);
2147 key!(override_export_symbols, opt_list);
2148 key!(merge_functions, MergeFunctions)?;
2149 key!(mcount = "target-mcount");
2151 key!(relax_elf_relocations, bool);
2152 key!(llvm_args, list);
2153 key!(use_ctors_section, bool);
2154 key!(eh_frame_header, bool);
2155 key!(has_thumb_interworking, bool);
2156 key!(split_debuginfo, SplitDebuginfo)?;
2157 key!(supported_sanitizers, SanitizerSet)?;
2158 key!(default_adjusted_cabi, Option<Abi>)?;
2159 key!(c_enum_min_bits, u64);
2160 key!(generate_arange_section, bool);
2161 key!(supports_stack_protector, bool);
2163 if base.is_builtin {
2164 // This can cause unfortunate ICEs later down the line.
2165 return Err("may not set is_builtin for targets not built-in".into());
2167 // Each field should have been read using `Json::remove` so any keys remaining are unused.
2168 let remaining_keys = obj.keys();
2171 TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2175 /// Load a built-in target
2176 pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2177 match *target_triple {
2178 TargetTriple::TargetTriple(ref target_triple) => {
2179 load_builtin(target_triple).expect("built-in target")
2181 TargetTriple::TargetPath(..) => {
2182 panic!("built-in targets doens't support target-paths")
2187 /// Search for a JSON file specifying the given target triple.
2189 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2190 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
2191 /// bare filename already, so also check for that. If one of the hardcoded targets we know
2192 /// about, just return it directly.
2194 /// The error string could come from any of the APIs called, including filesystem access and
2197 target_triple: &TargetTriple,
2199 ) -> Result<(Target, TargetWarnings), String> {
2203 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2204 let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2205 let obj = serde_json::from_str(&contents).map_err(|e| e.to_string())?;
2206 Target::from_json(obj)
2209 match *target_triple {
2210 TargetTriple::TargetTriple(ref target_triple) => {
2211 // check if triple is in list of built-in targets
2212 if let Some(t) = load_builtin(target_triple) {
2213 return Ok((t, TargetWarnings::empty()));
2216 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2218 let mut target = target_triple.to_string();
2219 target.push_str(".json");
2220 PathBuf::from(target)
2223 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2225 for dir in env::split_paths(&target_path) {
2226 let p = dir.join(&path);
2228 return load_file(&p);
2232 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2234 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2235 let p = PathBuf::from_iter([
2237 Path::new(&rustlib_path),
2238 Path::new("target.json"),
2241 return load_file(&p);
2244 Err(format!("Could not find specification for target {:?}", target_triple))
2246 TargetTriple::TargetPath(ref target_path) => {
2247 if target_path.is_file() {
2248 return load_file(&target_path);
2250 Err(format!("Target path {:?} is not a valid file", target_path))
2256 impl ToJson for Target {
2257 fn to_json(&self) -> Json {
2258 let mut d = serde_json::Map::new();
2259 let default: TargetOptions = Default::default();
2261 macro_rules! target_val {
2263 let name = (stringify!($attr)).replace("_", "-");
2264 d.insert(name, self.$attr.to_json());
2268 macro_rules! target_option_val {
2270 let name = (stringify!($attr)).replace("_", "-");
2271 if default.$attr != self.$attr {
2272 d.insert(name, self.$attr.to_json());
2275 ($attr:ident, $key_name:expr) => {{
2276 let name = $key_name;
2277 if default.$attr != self.$attr {
2278 d.insert(name.into(), self.$attr.to_json());
2281 (link_args - $attr:ident) => {{
2282 let name = (stringify!($attr)).replace("_", "-");
2283 if default.$attr != self.$attr {
2287 .map(|(k, v)| (k.desc().to_string(), v.clone()))
2288 .collect::<BTreeMap<_, _>>();
2289 d.insert(name, obj.to_json());
2292 (env - $attr:ident) => {{
2293 let name = (stringify!($attr)).replace("_", "-");
2294 if default.$attr != self.$attr {
2298 .map(|&(ref k, ref v)| format!("{k}={v}"))
2299 .collect::<Vec<_>>();
2300 d.insert(name, obj.to_json());
2305 target_val!(llvm_target);
2306 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2308 target_val!(data_layout);
2310 target_option_val!(is_builtin);
2311 target_option_val!(endian, "target-endian");
2312 target_option_val!(c_int_width, "target-c-int-width");
2313 target_option_val!(os);
2314 target_option_val!(env);
2315 target_option_val!(abi);
2316 target_option_val!(vendor);
2317 target_option_val!(linker_flavor);
2318 target_option_val!(linker);
2319 target_option_val!(lld_flavor);
2320 target_option_val!(pre_link_objects);
2321 target_option_val!(post_link_objects);
2322 target_option_val!(pre_link_objects_fallback);
2323 target_option_val!(post_link_objects_fallback);
2324 target_option_val!(crt_objects_fallback);
2325 target_option_val!(link_args - pre_link_args);
2326 target_option_val!(link_args - late_link_args);
2327 target_option_val!(link_args - late_link_args_dynamic);
2328 target_option_val!(link_args - late_link_args_static);
2329 target_option_val!(link_args - post_link_args);
2330 target_option_val!(link_script);
2331 target_option_val!(env - link_env);
2332 target_option_val!(link_env_remove);
2333 target_option_val!(asm_args);
2334 target_option_val!(cpu);
2335 target_option_val!(features);
2336 target_option_val!(dynamic_linking);
2337 target_option_val!(only_cdylib);
2338 target_option_val!(executables);
2339 target_option_val!(relocation_model);
2340 target_option_val!(code_model);
2341 target_option_val!(tls_model);
2342 target_option_val!(disable_redzone);
2343 target_option_val!(frame_pointer);
2344 target_option_val!(function_sections);
2345 target_option_val!(dll_prefix);
2346 target_option_val!(dll_suffix);
2347 target_option_val!(exe_suffix);
2348 target_option_val!(staticlib_prefix);
2349 target_option_val!(staticlib_suffix);
2350 target_option_val!(families, "target-family");
2351 target_option_val!(abi_return_struct_as_int);
2352 target_option_val!(is_like_osx);
2353 target_option_val!(is_like_solaris);
2354 target_option_val!(is_like_windows);
2355 target_option_val!(is_like_msvc);
2356 target_option_val!(is_like_emscripten);
2357 target_option_val!(is_like_fuchsia);
2358 target_option_val!(is_like_wasm);
2359 target_option_val!(dwarf_version);
2360 target_option_val!(linker_is_gnu);
2361 target_option_val!(allows_weak_linkage);
2362 target_option_val!(has_rpath);
2363 target_option_val!(no_default_libraries);
2364 target_option_val!(position_independent_executables);
2365 target_option_val!(static_position_independent_executables);
2366 target_option_val!(needs_plt);
2367 target_option_val!(relro_level);
2368 target_option_val!(archive_format);
2369 target_option_val!(allow_asm);
2370 target_option_val!(main_needs_argc_argv);
2371 target_option_val!(has_thread_local);
2372 target_option_val!(obj_is_bitcode);
2373 target_option_val!(forces_embed_bitcode);
2374 target_option_val!(bitcode_llvm_cmdline);
2375 target_option_val!(min_atomic_width);
2376 target_option_val!(max_atomic_width);
2377 target_option_val!(atomic_cas);
2378 target_option_val!(panic_strategy);
2379 target_option_val!(crt_static_allows_dylibs);
2380 target_option_val!(crt_static_default);
2381 target_option_val!(crt_static_respected);
2382 target_option_val!(stack_probes);
2383 target_option_val!(min_global_align);
2384 target_option_val!(default_codegen_units);
2385 target_option_val!(trap_unreachable);
2386 target_option_val!(requires_lto);
2387 target_option_val!(singlethread);
2388 target_option_val!(no_builtins);
2389 target_option_val!(default_hidden_visibility);
2390 target_option_val!(emit_debug_gdb_scripts);
2391 target_option_val!(requires_uwtable);
2392 target_option_val!(default_uwtable);
2393 target_option_val!(simd_types_indirect);
2394 target_option_val!(limit_rdylib_exports);
2395 target_option_val!(override_export_symbols);
2396 target_option_val!(merge_functions);
2397 target_option_val!(mcount, "target-mcount");
2398 target_option_val!(llvm_abiname);
2399 target_option_val!(relax_elf_relocations);
2400 target_option_val!(llvm_args);
2401 target_option_val!(use_ctors_section);
2402 target_option_val!(eh_frame_header);
2403 target_option_val!(has_thumb_interworking);
2404 target_option_val!(split_debuginfo);
2405 target_option_val!(supported_sanitizers);
2406 target_option_val!(c_enum_min_bits);
2407 target_option_val!(generate_arange_section);
2408 target_option_val!(supports_stack_protector);
2410 if let Some(abi) = self.default_adjusted_cabi {
2411 d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2418 /// Either a target triple string or a path to a JSON file.
2419 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2420 pub enum TargetTriple {
2421 TargetTriple(String),
2422 TargetPath(PathBuf),
2426 /// Creates a target triple from the passed target triple string.
2427 pub fn from_triple(triple: &str) -> Self {
2428 TargetTriple::TargetTriple(triple.into())
2431 /// Creates a target triple from the passed target path.
2432 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2433 let canonicalized_path = path.canonicalize()?;
2434 Ok(TargetTriple::TargetPath(canonicalized_path))
2437 /// Returns a string triple for this target.
2439 /// If this target is a path, the file name (without extension) is returned.
2440 pub fn triple(&self) -> &str {
2442 TargetTriple::TargetTriple(ref triple) => triple,
2443 TargetTriple::TargetPath(ref path) => path
2445 .expect("target path must not be empty")
2447 .expect("target path must be valid unicode"),
2451 /// Returns an extended string triple for this target.
2453 /// If this target is a path, a hash of the path is appended to the triple returned
2455 pub fn debug_triple(&self) -> String {
2456 use std::collections::hash_map::DefaultHasher;
2457 use std::hash::{Hash, Hasher};
2459 let triple = self.triple();
2460 if let TargetTriple::TargetPath(ref path) = *self {
2461 let mut hasher = DefaultHasher::new();
2462 path.hash(&mut hasher);
2463 let hash = hasher.finish();
2464 format!("{}-{}", triple, hash)
2471 impl fmt::Display for TargetTriple {
2472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2473 write!(f, "{}", self.debug_triple())