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::ops::{Deref, DerefMut};
46 use std::path::{Path, PathBuf};
47 use std::str::FromStr;
50 use rustc_macros::HashStable_Generic;
65 mod hermit_kernel_base;
70 mod linux_kernel_base;
72 mod linux_uclibc_base;
84 mod windows_msvc_base;
85 mod windows_uwp_gnu_base;
86 mod windows_uwp_msvc_base;
88 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
89 pub enum LinkerFlavor {
99 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
108 fn from_str(s: &str) -> Option<Self> {
110 "darwin" => LldFlavor::Ld64,
111 "gnu" => LldFlavor::Ld,
112 "link" => LldFlavor::Link,
113 "wasm" => LldFlavor::Wasm,
119 impl ToJson for LldFlavor {
120 fn to_json(&self) -> Json {
122 LldFlavor::Ld64 => "darwin",
123 LldFlavor::Ld => "gnu",
124 LldFlavor::Link => "link",
125 LldFlavor::Wasm => "wasm",
131 impl ToJson for LinkerFlavor {
132 fn to_json(&self) -> Json {
133 self.desc().to_json()
136 macro_rules! flavor_mappings {
137 ($((($($flavor:tt)*), $string:expr),)*) => (
139 pub const fn one_of() -> &'static str {
140 concat!("one of: ", $($string, " ",)*)
143 pub fn from_str(s: &str) -> Option<Self> {
145 $($string => $($flavor)*,)*
150 pub fn desc(&self) -> &str {
152 $($($flavor)* => $string,)*
160 ((LinkerFlavor::Em), "em"),
161 ((LinkerFlavor::Gcc), "gcc"),
162 ((LinkerFlavor::Ld), "ld"),
163 ((LinkerFlavor::Msvc), "msvc"),
164 ((LinkerFlavor::PtxLinker), "ptx-linker"),
165 ((LinkerFlavor::BpfLinker), "bpf-linker"),
166 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
167 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
168 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
169 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
172 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
173 pub enum PanicStrategy {
179 pub fn desc(&self) -> &str {
181 PanicStrategy::Unwind => "unwind",
182 PanicStrategy::Abort => "abort",
186 pub fn desc_symbol(&self) -> Symbol {
188 PanicStrategy::Unwind => sym::unwind,
189 PanicStrategy::Abort => sym::abort,
194 impl ToJson for PanicStrategy {
195 fn to_json(&self) -> Json {
197 PanicStrategy::Abort => "abort".to_json(),
198 PanicStrategy::Unwind => "unwind".to_json(),
203 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
204 pub enum RelroLevel {
212 pub fn desc(&self) -> &str {
214 RelroLevel::Full => "full",
215 RelroLevel::Partial => "partial",
216 RelroLevel::Off => "off",
217 RelroLevel::None => "none",
222 impl FromStr for RelroLevel {
225 fn from_str(s: &str) -> Result<RelroLevel, ()> {
227 "full" => Ok(RelroLevel::Full),
228 "partial" => Ok(RelroLevel::Partial),
229 "off" => Ok(RelroLevel::Off),
230 "none" => Ok(RelroLevel::None),
236 impl ToJson for RelroLevel {
237 fn to_json(&self) -> Json {
239 RelroLevel::Full => "full".to_json(),
240 RelroLevel::Partial => "partial".to_json(),
241 RelroLevel::Off => "off".to_json(),
242 RelroLevel::None => "None".to_json(),
247 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
248 pub enum MergeFunctions {
254 impl MergeFunctions {
255 pub fn desc(&self) -> &str {
257 MergeFunctions::Disabled => "disabled",
258 MergeFunctions::Trampolines => "trampolines",
259 MergeFunctions::Aliases => "aliases",
264 impl FromStr for MergeFunctions {
267 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
269 "disabled" => Ok(MergeFunctions::Disabled),
270 "trampolines" => Ok(MergeFunctions::Trampolines),
271 "aliases" => Ok(MergeFunctions::Aliases),
277 impl ToJson for MergeFunctions {
278 fn to_json(&self) -> Json {
280 MergeFunctions::Disabled => "disabled".to_json(),
281 MergeFunctions::Trampolines => "trampolines".to_json(),
282 MergeFunctions::Aliases => "aliases".to_json(),
287 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
288 pub enum RelocModel {
298 impl FromStr for RelocModel {
301 fn from_str(s: &str) -> Result<RelocModel, ()> {
303 "static" => RelocModel::Static,
304 "pic" => RelocModel::Pic,
305 "pie" => RelocModel::Pie,
306 "dynamic-no-pic" => RelocModel::DynamicNoPic,
307 "ropi" => RelocModel::Ropi,
308 "rwpi" => RelocModel::Rwpi,
309 "ropi-rwpi" => RelocModel::RopiRwpi,
315 impl ToJson for RelocModel {
316 fn to_json(&self) -> Json {
318 RelocModel::Static => "static",
319 RelocModel::Pic => "pic",
320 RelocModel::Pie => "pie",
321 RelocModel::DynamicNoPic => "dynamic-no-pic",
322 RelocModel::Ropi => "ropi",
323 RelocModel::Rwpi => "rwpi",
324 RelocModel::RopiRwpi => "ropi-rwpi",
330 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
339 impl FromStr for CodeModel {
342 fn from_str(s: &str) -> Result<CodeModel, ()> {
344 "tiny" => CodeModel::Tiny,
345 "small" => CodeModel::Small,
346 "kernel" => CodeModel::Kernel,
347 "medium" => CodeModel::Medium,
348 "large" => CodeModel::Large,
354 impl ToJson for CodeModel {
355 fn to_json(&self) -> Json {
357 CodeModel::Tiny => "tiny",
358 CodeModel::Small => "small",
359 CodeModel::Kernel => "kernel",
360 CodeModel::Medium => "medium",
361 CodeModel::Large => "large",
367 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
375 impl FromStr for TlsModel {
378 fn from_str(s: &str) -> Result<TlsModel, ()> {
380 // Note the difference "general" vs "global" difference. The model name is "general",
381 // but the user-facing option name is "global" for consistency with other compilers.
382 "global-dynamic" => TlsModel::GeneralDynamic,
383 "local-dynamic" => TlsModel::LocalDynamic,
384 "initial-exec" => TlsModel::InitialExec,
385 "local-exec" => TlsModel::LocalExec,
391 impl ToJson for TlsModel {
392 fn to_json(&self) -> Json {
394 TlsModel::GeneralDynamic => "global-dynamic",
395 TlsModel::LocalDynamic => "local-dynamic",
396 TlsModel::InitialExec => "initial-exec",
397 TlsModel::LocalExec => "local-exec",
403 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
404 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
405 pub enum LinkOutputKind {
406 /// Dynamically linked non position-independent executable.
408 /// Dynamically linked position-independent executable.
410 /// Statically linked non position-independent executable.
412 /// Statically linked position-independent executable.
414 /// Regular dynamic library ("dynamically linked").
416 /// Dynamic library with bundled libc ("statically linked").
418 /// WASI module with a lifetime past the _initialize entry point
422 impl LinkOutputKind {
423 fn as_str(&self) -> &'static str {
425 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
426 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
427 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
428 LinkOutputKind::StaticPicExe => "static-pic-exe",
429 LinkOutputKind::DynamicDylib => "dynamic-dylib",
430 LinkOutputKind::StaticDylib => "static-dylib",
431 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
435 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
437 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
438 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
439 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
440 "static-pic-exe" => LinkOutputKind::StaticPicExe,
441 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
442 "static-dylib" => LinkOutputKind::StaticDylib,
443 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
449 impl fmt::Display for LinkOutputKind {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 f.write_str(self.as_str())
455 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
457 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
458 pub enum SplitDebuginfo {
459 /// Split debug-information is disabled, meaning that on supported platforms
460 /// you can find all debug information in the executable itself. This is
461 /// only supported for ELF effectively.
463 /// * Windows - not supported
464 /// * macOS - don't run `dsymutil`
465 /// * ELF - `.dwarf_*` sections
468 /// Split debug-information can be found in a "packed" location separate
469 /// from the final artifact. This is supported on all platforms.
471 /// * Windows - `*.pdb`
472 /// * macOS - `*.dSYM` (run `dsymutil`)
473 /// * ELF - `*.dwp` (run `rust-llvm-dwp`)
476 /// Split debug-information can be found in individual object files on the
477 /// filesystem. The main executable may point to the object files.
479 /// * Windows - not supported
480 /// * macOS - supported, scattered object files
481 /// * ELF - supported, scattered `*.dwo` files
485 impl SplitDebuginfo {
486 fn as_str(&self) -> &'static str {
488 SplitDebuginfo::Off => "off",
489 SplitDebuginfo::Packed => "packed",
490 SplitDebuginfo::Unpacked => "unpacked",
495 impl FromStr for SplitDebuginfo {
498 fn from_str(s: &str) -> Result<SplitDebuginfo, ()> {
500 "off" => SplitDebuginfo::Off,
501 "unpacked" => SplitDebuginfo::Unpacked,
502 "packed" => SplitDebuginfo::Packed,
508 impl ToJson for SplitDebuginfo {
509 fn to_json(&self) -> Json {
510 self.as_str().to_json()
514 impl fmt::Display for SplitDebuginfo {
515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516 f.write_str(self.as_str())
520 #[derive(Clone, Debug, PartialEq, Eq)]
521 pub enum StackProbeType {
522 /// Don't emit any stack probes.
524 /// It is harmless to use this option even on targets that do not have backend support for
525 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
528 /// Call `__rust_probestack` whenever stack needs to be probed.
530 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
531 /// and call `__rust_probestack` otherwise.
532 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
535 impl StackProbeType {
536 fn from_json(json: &Json) -> Result<Self, String> {
537 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
540 .and_then(|o| o.as_string())
541 .ok_or_else(|| "expected `kind` to be a string")?;
543 "none" => Ok(StackProbeType::None),
544 "inline" => Ok(StackProbeType::Inline),
545 "call" => Ok(StackProbeType::Call),
546 "inline-or-call" => {
547 let min_version = object
548 .get("min-llvm-version-for-inline")
549 .and_then(|o| o.as_array())
550 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
551 let mut iter = min_version.into_iter().map(|v| {
552 let int = v.as_u64().ok_or_else(
553 || "expected `min-llvm-version-for-inline` values to be integers",
556 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
558 let min_llvm_version_for_inline = (
559 iter.next().unwrap_or(Ok(11))?,
560 iter.next().unwrap_or(Ok(0))?,
561 iter.next().unwrap_or(Ok(0))?,
563 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
565 _ => Err(String::from(
566 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
572 impl ToJson for StackProbeType {
573 fn to_json(&self) -> Json {
574 Json::Object(match self {
575 StackProbeType::None => {
576 vec![(String::from("kind"), "none".to_json())].into_iter().collect()
578 StackProbeType::Inline => {
579 vec![(String::from("kind"), "inline".to_json())].into_iter().collect()
581 StackProbeType::Call => {
582 vec![(String::from("kind"), "call".to_json())].into_iter().collect()
584 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => vec![
585 (String::from("kind"), "inline-or-call".to_json()),
587 String::from("min-llvm-version-for-inline"),
588 min_llvm_version_for_inline.to_json(),
597 bitflags::bitflags! {
598 #[derive(Default, Encodable, Decodable)]
599 pub struct SanitizerSet: u8 {
600 const ADDRESS = 1 << 0;
602 const MEMORY = 1 << 2;
603 const THREAD = 1 << 3;
604 const HWADDRESS = 1 << 4;
609 /// Return sanitizer's name
611 /// Returns none if the flags is a set of sanitizers numbering not exactly one.
612 fn as_str(self) -> Option<&'static str> {
614 SanitizerSet::ADDRESS => "address",
615 SanitizerSet::LEAK => "leak",
616 SanitizerSet::MEMORY => "memory",
617 SanitizerSet::THREAD => "thread",
618 SanitizerSet::HWADDRESS => "hwaddress",
624 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
625 impl fmt::Display for SanitizerSet {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 let mut first = true;
629 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
640 impl IntoIterator for SanitizerSet {
641 type Item = SanitizerSet;
642 type IntoIter = std::vec::IntoIter<SanitizerSet>;
644 fn into_iter(self) -> Self::IntoIter {
646 SanitizerSet::ADDRESS,
648 SanitizerSet::MEMORY,
649 SanitizerSet::THREAD,
650 SanitizerSet::HWADDRESS,
654 .filter(|&s| self.contains(s))
660 impl<CTX> HashStable<CTX> for SanitizerSet {
661 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
662 self.bits().hash_stable(ctx, hasher);
666 impl ToJson for SanitizerSet {
667 fn to_json(&self) -> Json {
669 .map(|v| Some(v.as_str()?.to_json()))
670 .collect::<Option<Vec<_>>>()
676 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
677 pub enum FramePointer {
678 /// Forces the machine code generator to always preserve the frame pointers.
680 /// Forces the machine code generator to preserve the frame pointers except for the leaf
681 /// functions (i.e. those that don't call other functions).
683 /// Allows the machine code generator to omit the frame pointers.
685 /// This option does not guarantee that the frame pointers will be omitted.
689 impl FromStr for FramePointer {
691 fn from_str(s: &str) -> Result<Self, ()> {
693 "always" => Self::Always,
694 "non-leaf" => Self::NonLeaf,
695 "may-omit" => Self::MayOmit,
701 impl ToJson for FramePointer {
702 fn to_json(&self) -> Json {
704 Self::Always => "always",
705 Self::NonLeaf => "non-leaf",
706 Self::MayOmit => "may-omit",
712 macro_rules! supported_targets {
713 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
716 /// List of supported targets
717 pub const TARGETS: &[&str] = &[$($($triple),+),+];
719 fn load_builtin(target: &str) -> Option<Target> {
720 let mut t = match target {
721 $( $($triple)|+ => $module::target(), )+
725 debug!("got builtin target: {:?}", t);
733 // Cannot put this into a separate file without duplication, make an exception.
737 tests_impl::test_target(super::$module::target());
745 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
746 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
747 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
748 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
749 ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
750 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
751 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
752 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
753 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
754 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
755 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
756 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
757 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
758 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
759 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
760 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
761 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
762 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
763 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
764 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
765 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
766 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
767 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
768 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
769 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
770 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
771 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
772 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
773 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
774 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
775 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
776 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
777 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
778 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
779 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
780 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
781 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
782 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
783 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
784 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
785 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
786 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
787 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
788 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
789 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
790 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
791 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
792 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
794 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
795 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
797 ("i686-linux-android", i686_linux_android),
798 ("x86_64-linux-android", x86_64_linux_android),
799 ("arm-linux-androideabi", arm_linux_androideabi),
800 ("armv7-linux-androideabi", armv7_linux_androideabi),
801 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
802 ("aarch64-linux-android", aarch64_linux_android),
804 ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
806 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
807 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
808 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
809 ("i686-unknown-freebsd", i686_unknown_freebsd),
810 ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
811 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
812 ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
813 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
815 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
817 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
818 ("i686-unknown-openbsd", i686_unknown_openbsd),
819 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
820 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
821 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
823 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
824 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
825 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
826 ("i686-unknown-netbsd", i686_unknown_netbsd),
827 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
828 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
829 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
831 ("i686-unknown-haiku", i686_unknown_haiku),
832 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
834 ("aarch64-apple-darwin", aarch64_apple_darwin),
835 ("x86_64-apple-darwin", x86_64_apple_darwin),
836 ("i686-apple-darwin", i686_apple_darwin),
838 ("aarch64-fuchsia", aarch64_fuchsia),
839 ("x86_64-fuchsia", x86_64_fuchsia),
841 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
843 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
845 ("aarch64-unknown-redox", aarch64_unknown_redox),
846 ("x86_64-unknown-redox", x86_64_unknown_redox),
848 ("i386-apple-ios", i386_apple_ios),
849 ("x86_64-apple-ios", x86_64_apple_ios),
850 ("aarch64-apple-ios", aarch64_apple_ios),
851 ("armv7-apple-ios", armv7_apple_ios),
852 ("armv7s-apple-ios", armv7s_apple_ios),
853 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
854 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
855 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
856 ("aarch64-apple-tvos", aarch64_apple_tvos),
857 ("x86_64-apple-tvos", x86_64_apple_tvos),
859 ("armebv7r-none-eabi", armebv7r_none_eabi),
860 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
861 ("armv7r-none-eabi", armv7r_none_eabi),
862 ("armv7r-none-eabihf", armv7r_none_eabihf),
864 ("x86_64-pc-solaris", x86_64_pc_solaris),
865 ("x86_64-sun-solaris", x86_64_sun_solaris),
866 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
868 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
870 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
871 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
872 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
873 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
875 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
876 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
877 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
878 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
879 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
880 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
881 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
882 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
883 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
885 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
886 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
887 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
888 ("wasm32-wasi", wasm32_wasi),
889 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
891 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
892 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
893 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
894 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
895 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
896 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
897 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
899 ("armv7a-none-eabi", armv7a_none_eabi),
900 ("armv7a-none-eabihf", armv7a_none_eabihf),
902 ("msp430-none-elf", msp430_none_elf),
904 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
905 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
907 ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
909 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
910 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
911 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
912 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
913 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
914 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
915 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
916 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
917 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
918 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
920 ("aarch64-unknown-none", aarch64_unknown_none),
921 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
923 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
925 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
926 ("i686-unknown-uefi", i686_unknown_uefi),
927 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
929 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
931 ("i686-wrs-vxworks", i686_wrs_vxworks),
932 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
933 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
934 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
935 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
936 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
937 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
939 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
940 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
941 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
943 ("mipsel-sony-psp", mipsel_sony_psp),
944 ("mipsel-unknown-none", mipsel_unknown_none),
945 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
947 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
948 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
949 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
951 ("bpfeb-unknown-none", bpfeb_unknown_none),
952 ("bpfel-unknown-none", bpfel_unknown_none),
954 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
956 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
959 /// Warnings encountered when parsing the target `json`.
961 /// Includes fields that weren't recognized and fields that don't have the expected type.
962 #[derive(Debug, PartialEq)]
963 pub struct TargetWarnings {
964 unused_fields: Vec<String>,
965 incorrect_type: Vec<String>,
968 impl TargetWarnings {
969 pub fn empty() -> Self {
970 Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
973 pub fn warning_messages(&self) -> Vec<String> {
974 let mut warnings = vec![];
975 if !self.unused_fields.is_empty() {
976 warnings.push(format!(
977 "target json file contains unused fields: {}",
978 self.unused_fields.join(", ")
981 if !self.incorrect_type.is_empty() {
982 warnings.push(format!(
983 "target json file contains fields whose value doesn't have the correct json type: {}",
984 self.incorrect_type.join(", ")
991 /// Everything `rustc` knows about how to compile for a specific target.
993 /// Every field here must be specified, and has no default value.
994 #[derive(PartialEq, Clone, Debug)]
996 /// Target triple to pass to LLVM.
997 pub llvm_target: String,
998 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
999 pub pointer_width: u32,
1000 /// Architecture to use for ABI considerations. Valid options include: "x86",
1001 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1003 /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1004 pub data_layout: String,
1005 /// Optional settings with defaults.
1006 pub options: TargetOptions,
1009 pub trait HasTargetSpec {
1010 fn target_spec(&self) -> &Target;
1013 impl HasTargetSpec for Target {
1015 fn target_spec(&self) -> &Target {
1020 /// Optional aspects of a target specification.
1022 /// This has an implementation of `Default`, see each field for what the default is. In general,
1023 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1025 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1026 /// construction, all its fields logically belong to `Target` and available from `Target`
1027 /// through `Deref` impls.
1028 #[derive(PartialEq, Clone, Debug)]
1029 pub struct TargetOptions {
1030 /// Whether the target is built-in or loaded from a custom target specification.
1031 pub is_builtin: bool,
1033 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1035 /// Width of c_int type. Defaults to "32".
1036 pub c_int_width: String,
1037 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1038 /// "none" implies a bare metal target without `std` library.
1039 /// A couple of targets having `std` also use "unknown" as an `os` value,
1040 /// but they are exceptions.
1042 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1044 /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1045 /// or `"eabihf"`. Defaults to "".
1047 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1049 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1050 /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1051 pub linker_flavor: LinkerFlavor,
1053 /// Linker to invoke
1054 pub linker: Option<String>,
1056 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1057 /// without clarifying its flavor in any way.
1058 pub lld_flavor: LldFlavor,
1060 /// Linker arguments that are passed *before* any user-defined libraries.
1061 pub pre_link_args: LinkArgs,
1062 /// Objects to link before and after all other object code.
1063 pub pre_link_objects: CrtObjects,
1064 pub post_link_objects: CrtObjects,
1065 /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
1066 /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
1067 /// See `crt_objects.rs` for some more detailed documentation.
1068 pub pre_link_objects_fallback: CrtObjects,
1069 pub post_link_objects_fallback: CrtObjects,
1070 /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
1071 pub crt_objects_fallback: Option<CrtObjectsFallback>,
1073 /// Linker arguments that are unconditionally passed after any
1074 /// user-defined but before post-link objects. Standard platform
1075 /// libraries that should be always be linked to, usually go here.
1076 pub late_link_args: LinkArgs,
1077 /// Linker arguments used in addition to `late_link_args` if at least one
1078 /// Rust dependency is dynamically linked.
1079 pub late_link_args_dynamic: LinkArgs,
1080 /// Linker arguments used in addition to `late_link_args` if aall Rust
1081 /// dependencies are statically linked.
1082 pub late_link_args_static: LinkArgs,
1083 /// Linker arguments that are unconditionally passed *after* any
1084 /// user-defined libraries.
1085 pub post_link_args: LinkArgs,
1086 /// Optional link script applied to `dylib` and `executable` crate types.
1087 /// This is a string containing the script, not a path. Can only be applied
1088 /// to linkers where `linker_is_gnu` is true.
1089 pub link_script: Option<String>,
1091 /// Environment variables to be set for the linker invocation.
1092 pub link_env: Vec<(String, String)>,
1093 /// Environment variables to be removed for the linker invocation.
1094 pub link_env_remove: Vec<String>,
1096 /// Extra arguments to pass to the external assembler (when used)
1097 pub asm_args: Vec<String>,
1099 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1102 /// Default target features to pass to LLVM. These features will *always* be
1103 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1104 /// -mattr=$features`.
1105 pub features: String,
1106 /// Whether dynamic linking is available on this target. Defaults to false.
1107 pub dynamic_linking: bool,
1108 /// If dynamic linking is available, whether only cdylibs are supported.
1109 pub only_cdylib: bool,
1110 /// Whether executables are available on this target. iOS, for example, only allows static
1111 /// libraries. Defaults to false.
1112 pub executables: bool,
1113 /// Relocation model to use in object file. Corresponds to `llc
1114 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1115 pub relocation_model: RelocModel,
1116 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1117 /// Defaults to `None` which means "inherited from the base LLVM target".
1118 pub code_model: Option<CodeModel>,
1119 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1120 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1121 pub tls_model: TlsModel,
1122 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1123 pub disable_redzone: bool,
1124 /// Frame pointer mode for this target. Defaults to `MayOmit`.
1125 pub frame_pointer: FramePointer,
1126 /// Emit each function in its own section. Defaults to true.
1127 pub function_sections: bool,
1128 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1129 pub dll_prefix: String,
1130 /// String to append to the name of every dynamic library. Defaults to ".so".
1131 pub dll_suffix: String,
1132 /// String to append to the name of every executable.
1133 pub exe_suffix: String,
1134 /// String to prepend to the name of every static library. Defaults to "lib".
1135 pub staticlib_prefix: String,
1136 /// String to append to the name of every static library. Defaults to ".a".
1137 pub staticlib_suffix: String,
1138 /// Values of the `target_family` cfg set for this target.
1140 /// Common options are: "unix", "windows". Defaults to no families.
1142 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1143 pub families: Vec<String>,
1144 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1145 pub abi_return_struct_as_int: bool,
1146 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1147 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1148 pub is_like_osx: bool,
1149 /// Whether the target toolchain is like Solaris's.
1150 /// Only useful for compiling against Illumos/Solaris,
1151 /// as they have a different set of linker flags. Defaults to false.
1152 pub is_like_solaris: bool,
1153 /// Whether the target is like Windows.
1154 /// This is a combination of several more specific properties represented as a single flag:
1155 /// - The target uses a Windows ABI,
1156 /// - uses PE/COFF as a format for object code,
1157 /// - uses Windows-style dllexport/dllimport for shared libraries,
1158 /// - uses import libraries and .def files for symbol exports,
1159 /// - executables support setting a subsystem.
1160 pub is_like_windows: bool,
1161 /// Whether the target is like MSVC.
1162 /// This is a combination of several more specific properties represented as a single flag:
1163 /// - The target has all the properties from `is_like_windows`
1164 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1165 /// - has some MSVC-specific Windows ABI properties,
1166 /// - uses a link.exe-like linker,
1167 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1168 /// - uses SEH-based unwinding,
1169 /// - supports control flow guard mechanism.
1170 pub is_like_msvc: bool,
1171 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1172 /// Emscripten toolchain.
1173 /// Defaults to false.
1174 pub is_like_emscripten: bool,
1175 /// Whether the target toolchain is like Fuchsia's.
1176 pub is_like_fuchsia: bool,
1177 /// Whether a target toolchain is like WASM.
1178 pub is_like_wasm: bool,
1179 /// Version of DWARF to use if not using the default.
1180 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1181 pub dwarf_version: Option<u32>,
1182 /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1183 pub linker_is_gnu: bool,
1184 /// The MinGW toolchain has a known issue that prevents it from correctly
1185 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1186 /// symbol needs its own COMDAT section, weak linkage implies a large
1187 /// number sections that easily exceeds the given limit for larger
1188 /// codebases. Consequently we want a way to disallow weak linkage on some
1190 pub allows_weak_linkage: bool,
1191 /// Whether the linker support rpaths or not. Defaults to false.
1192 pub has_rpath: bool,
1193 /// Whether to disable linking to the default libraries, typically corresponds
1194 /// to `-nodefaultlibs`. Defaults to true.
1195 pub no_default_libraries: bool,
1196 /// Dynamically linked executables can be compiled as position independent
1197 /// if the default relocation model of position independent code is not
1198 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1199 /// the functions in the executable are not randomized and can be used
1200 /// during an exploit of a vulnerability in any code.
1201 pub position_independent_executables: bool,
1202 /// Executables that are both statically linked and position-independent are supported.
1203 pub static_position_independent_executables: bool,
1204 /// Determines if the target always requires using the PLT for indirect
1205 /// library calls or not. This controls the default value of the `-Z plt` flag.
1206 pub needs_plt: bool,
1207 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1208 /// resolve all symbols at startup and marks the GOT read-only before
1209 /// starting the program, preventing overwriting the GOT.
1210 pub relro_level: RelroLevel,
1211 /// Format that archives should be emitted in. This affects whether we use
1212 /// LLVM to assemble an archive or fall back to the system linker, and
1213 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1214 /// the system linker to be used.
1215 pub archive_format: String,
1216 /// Is asm!() allowed? Defaults to true.
1217 pub allow_asm: bool,
1218 /// Whether the runtime startup code requires the `main` function be passed
1219 /// `argc` and `argv` values.
1220 pub main_needs_argc_argv: bool,
1222 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
1224 pub has_elf_tls: bool,
1225 // This is mainly for easy compatibility with emscripten.
1226 // If we give emcc .o files that are actually .bc files it
1227 // will 'just work'.
1228 pub obj_is_bitcode: bool,
1229 /// Whether the target requires that emitted object code includes bitcode.
1230 pub forces_embed_bitcode: bool,
1231 /// Content of the LLVM cmdline section associated with embedded bitcode.
1232 pub bitcode_llvm_cmdline: String,
1234 /// Don't use this field; instead use the `.min_atomic_width()` method.
1235 pub min_atomic_width: Option<u64>,
1237 /// Don't use this field; instead use the `.max_atomic_width()` method.
1238 pub max_atomic_width: Option<u64>,
1240 /// Whether the target supports atomic CAS operations natively
1241 pub atomic_cas: bool,
1243 /// Panic strategy: "unwind" or "abort"
1244 pub panic_strategy: PanicStrategy,
1246 /// Whether or not linking dylibs to a static CRT is allowed.
1247 pub crt_static_allows_dylibs: bool,
1248 /// Whether or not the CRT is statically linked by default.
1249 pub crt_static_default: bool,
1250 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1251 pub crt_static_respected: bool,
1253 /// The implementation of stack probes to use.
1254 pub stack_probes: StackProbeType,
1256 /// The minimum alignment for global symbols.
1257 pub min_global_align: Option<u64>,
1259 /// Default number of codegen units to use in debug mode
1260 pub default_codegen_units: Option<u64>,
1262 /// Whether to generate trap instructions in places where optimization would
1263 /// otherwise produce control flow that falls through into unrelated memory.
1264 pub trap_unreachable: bool,
1266 /// This target requires everything to be compiled with LTO to emit a final
1267 /// executable, aka there is no native linker for this target.
1268 pub requires_lto: bool,
1270 /// This target has no support for threads.
1271 pub singlethread: bool,
1273 /// Whether library functions call lowering/optimization is disabled in LLVM
1274 /// for this target unconditionally.
1275 pub no_builtins: bool,
1277 /// The default visibility for symbols in this target should be "hidden"
1278 /// rather than "default"
1279 pub default_hidden_visibility: bool,
1281 /// Whether a .debug_gdb_scripts section will be added to the output object file
1282 pub emit_debug_gdb_scripts: bool,
1284 /// Whether or not to unconditionally `uwtable` attributes on functions,
1285 /// typically because the platform needs to unwind for things like stack
1287 pub requires_uwtable: bool,
1289 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1290 /// is not specified and `uwtable` is not required on this target.
1291 pub default_uwtable: bool,
1293 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1294 /// typically required if a target can be compiled with a mixed set of
1295 /// target features. This is `true` by default, and `false` for targets like
1296 /// wasm32 where the whole program either has simd or not.
1297 pub simd_types_indirect: bool,
1299 /// Pass a list of symbol which should be exported in the dylib to the linker.
1300 pub limit_rdylib_exports: bool,
1302 /// If set, have the linker export exactly these symbols, instead of using
1303 /// the usual logic to figure this out from the crate itself.
1304 pub override_export_symbols: Option<Vec<String>>,
1306 /// Determines how or whether the MergeFunctions LLVM pass should run for
1307 /// this target. Either "disabled", "trampolines", or "aliases".
1308 /// The MergeFunctions pass is generally useful, but some targets may need
1309 /// to opt out. The default is "aliases".
1311 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1312 pub merge_functions: MergeFunctions,
1314 /// Use platform dependent mcount function
1317 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1318 pub llvm_abiname: String,
1320 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1321 pub relax_elf_relocations: bool,
1323 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1324 pub llvm_args: Vec<String>,
1326 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1327 /// to false (uses .init_array).
1328 pub use_ctors_section: bool,
1330 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1331 /// used to locate unwinding information is passed
1332 /// (only has effect if the linker is `ld`-like).
1333 pub eh_frame_header: bool,
1335 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1336 /// thumb and arm interworking.
1337 pub has_thumb_interworking: bool,
1339 /// How to handle split debug information, if at all. Specifying `None` has
1340 /// target-specific meaning.
1341 pub split_debuginfo: SplitDebuginfo,
1343 /// The sanitizers supported by this target
1345 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1346 /// enabled can generated on this target, but the necessary supporting libraries are not
1347 /// distributed with the target, the sanitizer should still appear in this list for the target.
1348 pub supported_sanitizers: SanitizerSet,
1350 /// If present it's a default value to use for adjusting the C ABI.
1351 pub default_adjusted_cabi: Option<Abi>,
1353 /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1354 pub c_enum_min_bits: u64,
1357 impl Default for TargetOptions {
1358 /// Creates a set of "sane defaults" for any target. This is still
1359 /// incomplete, and if used for compilation, will certainly not work.
1360 fn default() -> TargetOptions {
1363 endian: Endian::Little,
1364 c_int_width: "32".to_string(),
1365 os: "none".to_string(),
1368 vendor: "unknown".to_string(),
1369 linker_flavor: LinkerFlavor::Gcc,
1370 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1371 lld_flavor: LldFlavor::Ld,
1372 pre_link_args: LinkArgs::new(),
1373 post_link_args: LinkArgs::new(),
1375 asm_args: Vec::new(),
1376 cpu: "generic".to_string(),
1377 features: String::new(),
1378 dynamic_linking: false,
1381 relocation_model: RelocModel::Pic,
1383 tls_model: TlsModel::GeneralDynamic,
1384 disable_redzone: false,
1385 frame_pointer: FramePointer::MayOmit,
1386 function_sections: true,
1387 dll_prefix: "lib".to_string(),
1388 dll_suffix: ".so".to_string(),
1389 exe_suffix: String::new(),
1390 staticlib_prefix: "lib".to_string(),
1391 staticlib_suffix: ".a".to_string(),
1392 families: Vec::new(),
1393 abi_return_struct_as_int: false,
1395 is_like_solaris: false,
1396 is_like_windows: false,
1397 is_like_emscripten: false,
1398 is_like_msvc: false,
1399 is_like_fuchsia: false,
1400 is_like_wasm: false,
1401 dwarf_version: None,
1402 linker_is_gnu: true,
1403 allows_weak_linkage: true,
1405 no_default_libraries: true,
1406 position_independent_executables: false,
1407 static_position_independent_executables: false,
1409 relro_level: RelroLevel::None,
1410 pre_link_objects: Default::default(),
1411 post_link_objects: Default::default(),
1412 pre_link_objects_fallback: Default::default(),
1413 post_link_objects_fallback: Default::default(),
1414 crt_objects_fallback: None,
1415 late_link_args: LinkArgs::new(),
1416 late_link_args_dynamic: LinkArgs::new(),
1417 late_link_args_static: LinkArgs::new(),
1418 link_env: Vec::new(),
1419 link_env_remove: Vec::new(),
1420 archive_format: "gnu".to_string(),
1421 main_needs_argc_argv: true,
1424 obj_is_bitcode: false,
1425 forces_embed_bitcode: false,
1426 bitcode_llvm_cmdline: String::new(),
1427 min_atomic_width: None,
1428 max_atomic_width: None,
1430 panic_strategy: PanicStrategy::Unwind,
1431 crt_static_allows_dylibs: false,
1432 crt_static_default: false,
1433 crt_static_respected: false,
1434 stack_probes: StackProbeType::None,
1435 min_global_align: None,
1436 default_codegen_units: None,
1437 trap_unreachable: true,
1438 requires_lto: false,
1439 singlethread: false,
1441 default_hidden_visibility: false,
1442 emit_debug_gdb_scripts: true,
1443 requires_uwtable: false,
1444 default_uwtable: false,
1445 simd_types_indirect: true,
1446 limit_rdylib_exports: true,
1447 override_export_symbols: None,
1448 merge_functions: MergeFunctions::Aliases,
1449 mcount: "mcount".to_string(),
1450 llvm_abiname: "".to_string(),
1451 relax_elf_relocations: false,
1453 use_ctors_section: false,
1454 eh_frame_header: true,
1455 has_thumb_interworking: false,
1456 split_debuginfo: SplitDebuginfo::Off,
1457 supported_sanitizers: SanitizerSet::empty(),
1458 default_adjusted_cabi: None,
1459 c_enum_min_bits: 32,
1464 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1465 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1466 /// this `Deref` implementation is no longer necessary.
1467 impl Deref for Target {
1468 type Target = TargetOptions;
1470 fn deref(&self) -> &Self::Target {
1474 impl DerefMut for Target {
1475 fn deref_mut(&mut self) -> &mut Self::Target {
1481 /// Given a function ABI, turn it into the correct ABI for this target.
1482 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1484 Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1485 Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1486 Abi::Stdcall { unwind }
1488 Abi::System { unwind } => Abi::C { unwind },
1489 Abi::EfiApi if self.arch == "x86_64" => Abi::Win64,
1490 Abi::EfiApi => Abi::C { unwind: false },
1492 // See commentary in `is_abi_supported`.
1493 Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1494 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1495 Abi::Fastcall if self.arch == "x86" => abi,
1496 Abi::Vectorcall if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1497 Abi::Fastcall | Abi::Vectorcall => Abi::C { unwind: false },
1503 /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1504 pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1516 X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1517 Aapcs => "arm" == self.arch,
1518 CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1519 Win64 | SysV64 => self.arch == "x86_64",
1520 PtxKernel => self.arch == "nvptx64",
1521 Msp430Interrupt => self.arch == "msp430",
1522 AmdGpuKernel => self.arch == "amdgcn",
1523 AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1524 Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1525 Thiscall { .. } => self.arch == "x86",
1526 // On windows these fall-back to platform native calling convention (C) when the
1527 // architecture is not supported.
1529 // This is I believe a historical accident that has occurred as part of Microsoft
1530 // striving to allow most of the code to "just" compile when support for 64-bit x86
1531 // was added and then later again, when support for ARM architectures was added.
1533 // This is well documented across MSDN. Support for this in Rust has been added in
1534 // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1535 // Rust, but there isn't much leeway remaining here to change it back at the time this
1536 // comment has been written.
1538 // Following are the relevant excerpts from the MSDN documentation.
1540 // > The __vectorcall calling convention is only supported in native code on x86 and
1541 // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1543 // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1545 // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1547 // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1549 // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1551 // > In most cases, keywords or compiler switches that specify an unsupported
1552 // > convention on a particular platform are ignored, and the platform default
1553 // > convention is used.
1555 // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1556 Stdcall { .. } | Fastcall | Vectorcall if self.is_like_windows => true,
1557 // Outside of Windows we want to only support these calling conventions for the
1558 // architectures for which these calling conventions are actually well defined.
1559 Stdcall { .. } | Fastcall if self.arch == "x86" => true,
1560 Vectorcall if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1561 // Return a `None` for other cases so that we know to emit a future compat lint.
1562 Stdcall { .. } | Fastcall | Vectorcall => return None,
1566 /// Minimum integer size in bits that this target can perform atomic
1568 pub fn min_atomic_width(&self) -> u64 {
1569 self.min_atomic_width.unwrap_or(8)
1572 /// Maximum integer size in bits that this target can perform atomic
1574 pub fn max_atomic_width(&self) -> u64 {
1575 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1578 /// Loads a target descriptor from a JSON object.
1579 pub fn from_json(mut obj: Json) -> Result<(Target, TargetWarnings), String> {
1580 // While ugly, this code must remain this way to retain
1581 // compatibility with existing JSON fields and the internal
1582 // expected naming of the Target and TargetOptions structs.
1583 // To ensure compatibility is retained, the built-in targets
1584 // are round-tripped through this code to catch cases where
1585 // the JSON parser is not updated to match the structs.
1587 let mut get_req_field = |name: &str| {
1588 obj.remove_key(name)
1589 .and_then(|j| Json::as_string(&j).map(str::to_string))
1590 .ok_or_else(|| format!("Field {} in target specification is required", name))
1593 let mut base = Target {
1594 llvm_target: get_req_field("llvm-target")?,
1595 pointer_width: get_req_field("target-pointer-width")?
1597 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1598 data_layout: get_req_field("data-layout")?,
1599 arch: get_req_field("arch")?,
1600 options: Default::default(),
1603 let mut incorrect_type = vec![];
1606 ($key_name:ident) => ( {
1607 let name = (stringify!($key_name)).replace("_", "-");
1608 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1612 ($key_name:ident = $json_name:expr) => ( {
1613 let name = $json_name;
1614 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1618 ($key_name:ident, bool) => ( {
1619 let name = (stringify!($key_name)).replace("_", "-");
1620 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_boolean(&j)) {
1624 ($key_name:ident, u64) => ( {
1625 let name = (stringify!($key_name)).replace("_", "-");
1626 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1630 ($key_name:ident, Option<u32>) => ( {
1631 let name = (stringify!($key_name)).replace("_", "-");
1632 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1634 return Err("Not a valid DWARF version number".to_string());
1636 base.$key_name = Some(s as u32);
1639 ($key_name:ident, Option<u64>) => ( {
1640 let name = (stringify!($key_name)).replace("_", "-");
1641 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1642 base.$key_name = Some(s);
1645 ($key_name:ident, MergeFunctions) => ( {
1646 let name = (stringify!($key_name)).replace("_", "-");
1647 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1648 match s.parse::<MergeFunctions>() {
1649 Ok(mergefunc) => base.$key_name = mergefunc,
1650 _ => return Some(Err(format!("'{}' is not a valid value for \
1651 merge-functions. Use 'disabled', \
1652 'trampolines', or 'aliases'.",
1656 })).unwrap_or(Ok(()))
1658 ($key_name:ident, RelocModel) => ( {
1659 let name = (stringify!($key_name)).replace("_", "-");
1660 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1661 match s.parse::<RelocModel>() {
1662 Ok(relocation_model) => base.$key_name = relocation_model,
1663 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1664 Run `rustc --print relocation-models` to \
1665 see the list of supported values.", s))),
1668 })).unwrap_or(Ok(()))
1670 ($key_name:ident, CodeModel) => ( {
1671 let name = (stringify!($key_name)).replace("_", "-");
1672 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1673 match s.parse::<CodeModel>() {
1674 Ok(code_model) => base.$key_name = Some(code_model),
1675 _ => return Some(Err(format!("'{}' is not a valid code model. \
1676 Run `rustc --print code-models` to \
1677 see the list of supported values.", s))),
1680 })).unwrap_or(Ok(()))
1682 ($key_name:ident, TlsModel) => ( {
1683 let name = (stringify!($key_name)).replace("_", "-");
1684 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1685 match s.parse::<TlsModel>() {
1686 Ok(tls_model) => base.$key_name = tls_model,
1687 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1688 Run `rustc --print tls-models` to \
1689 see the list of supported values.", s))),
1692 })).unwrap_or(Ok(()))
1694 ($key_name:ident, PanicStrategy) => ( {
1695 let name = (stringify!($key_name)).replace("_", "-");
1696 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1698 "unwind" => base.$key_name = PanicStrategy::Unwind,
1699 "abort" => base.$key_name = PanicStrategy::Abort,
1700 _ => return Some(Err(format!("'{}' is not a valid value for \
1701 panic-strategy. Use 'unwind' or 'abort'.",
1705 })).unwrap_or(Ok(()))
1707 ($key_name:ident, RelroLevel) => ( {
1708 let name = (stringify!($key_name)).replace("_", "-");
1709 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1710 match s.parse::<RelroLevel>() {
1711 Ok(level) => base.$key_name = level,
1712 _ => return Some(Err(format!("'{}' is not a valid value for \
1713 relro-level. Use 'full', 'partial, or 'off'.",
1717 })).unwrap_or(Ok(()))
1719 ($key_name:ident, SplitDebuginfo) => ( {
1720 let name = (stringify!($key_name)).replace("_", "-");
1721 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1722 match s.parse::<SplitDebuginfo>() {
1723 Ok(level) => base.$key_name = level,
1724 _ => return Some(Err(format!("'{}' is not a valid value for \
1725 split-debuginfo. Use 'off' or 'dsymutil'.",
1729 })).unwrap_or(Ok(()))
1731 ($key_name:ident, list) => ( {
1732 let name = (stringify!($key_name)).replace("_", "-");
1733 if let Some(j) = obj.remove_key(&name){
1734 if let Some(v) = Json::as_array(&j) {
1735 base.$key_name = v.iter()
1736 .map(|a| a.as_string().unwrap().to_string())
1739 incorrect_type.push(name)
1743 ($key_name:ident, opt_list) => ( {
1744 let name = (stringify!($key_name)).replace("_", "-");
1745 if let Some(j) = obj.remove_key(&name) {
1746 if let Some(v) = Json::as_array(&j) {
1747 base.$key_name = Some(v.iter()
1748 .map(|a| a.as_string().unwrap().to_string())
1751 incorrect_type.push(name)
1755 ($key_name:ident, optional) => ( {
1756 let name = (stringify!($key_name)).replace("_", "-");
1757 if let Some(o) = obj.remove_key(&name[..]) {
1760 .map(|s| s.to_string() );
1763 ($key_name:ident, LldFlavor) => ( {
1764 let name = (stringify!($key_name)).replace("_", "-");
1765 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1766 if let Some(flavor) = LldFlavor::from_str(&s) {
1767 base.$key_name = flavor;
1769 return Some(Err(format!(
1770 "'{}' is not a valid value for lld-flavor. \
1771 Use 'darwin', 'gnu', 'link' or 'wasm.",
1775 })).unwrap_or(Ok(()))
1777 ($key_name:ident, LinkerFlavor) => ( {
1778 let name = (stringify!($key_name)).replace("_", "-");
1779 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1780 match LinkerFlavor::from_str(s) {
1781 Some(linker_flavor) => base.$key_name = linker_flavor,
1782 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1783 Use {}", s, LinkerFlavor::one_of()))),
1786 })).unwrap_or(Ok(()))
1788 ($key_name:ident, StackProbeType) => ( {
1789 let name = (stringify!($key_name)).replace("_", "-");
1790 obj.remove_key(&name[..]).and_then(|o| match StackProbeType::from_json(&o) {
1796 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1798 }).unwrap_or(Ok(()))
1800 ($key_name:ident, SanitizerSet) => ( {
1801 let name = (stringify!($key_name)).replace("_", "-");
1802 if let Some(o) = obj.remove_key(&name[..]) {
1803 if let Some(a) = o.as_array() {
1805 base.$key_name |= match s.as_string() {
1806 Some("address") => SanitizerSet::ADDRESS,
1807 Some("leak") => SanitizerSet::LEAK,
1808 Some("memory") => SanitizerSet::MEMORY,
1809 Some("thread") => SanitizerSet::THREAD,
1810 Some("hwaddress") => SanitizerSet::HWADDRESS,
1811 Some(s) => return Err(format!("unknown sanitizer {}", s)),
1812 _ => return Err(format!("not a string: {:?}", s)),
1816 incorrect_type.push(name)
1819 Ok::<(), String>(())
1822 ($key_name:ident, crt_objects_fallback) => ( {
1823 let name = (stringify!($key_name)).replace("_", "-");
1824 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1825 match s.parse::<CrtObjectsFallback>() {
1826 Ok(fallback) => base.$key_name = Some(fallback),
1827 _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1828 Use 'musl', 'mingw' or 'wasm'", s))),
1831 })).unwrap_or(Ok(()))
1833 ($key_name:ident, link_objects) => ( {
1834 let name = (stringify!($key_name)).replace("_", "-");
1835 if let Some(val) = obj.remove_key(&name[..]) {
1836 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1837 JSON object with fields per CRT object kind.", name))?;
1838 let mut args = CrtObjects::new();
1840 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1841 format!("{}: '{}' is not a valid value for CRT object kind. \
1842 Use '(dynamic,static)-(nopic,pic)-exe' or \
1843 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1846 let v = v.as_array().ok_or_else(||
1847 format!("{}.{}: expected a JSON array", name, k)
1848 )?.iter().enumerate()
1850 let s = s.as_string().ok_or_else(||
1851 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1854 .collect::<Result<Vec<_>, String>>()?;
1856 args.insert(kind, v);
1858 base.$key_name = args;
1861 ($key_name:ident, link_args) => ( {
1862 let name = (stringify!($key_name)).replace("_", "-");
1863 if let Some(val) = obj.remove_key(&name[..]) {
1864 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1865 JSON object with fields per linker-flavor.", name))?;
1866 let mut args = LinkArgs::new();
1868 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1869 format!("{}: '{}' is not a valid value for linker-flavor. \
1870 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1873 let v = v.as_array().ok_or_else(||
1874 format!("{}.{}: expected a JSON array", name, k)
1875 )?.iter().enumerate()
1877 let s = s.as_string().ok_or_else(||
1878 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1881 .collect::<Result<Vec<_>, String>>()?;
1883 args.insert(flavor, v);
1885 base.$key_name = args;
1888 ($key_name:ident, env) => ( {
1889 let name = (stringify!($key_name)).replace("_", "-");
1890 if let Some(o) = obj.remove_key(&name[..]) {
1891 if let Some(a) = o.as_array() {
1893 if let Some(s) = o.as_string() {
1894 let p = s.split('=').collect::<Vec<_>>();
1896 let k = p[0].to_string();
1897 let v = p[1].to_string();
1898 base.$key_name.push((k, v));
1903 incorrect_type.push(name)
1907 ($key_name:ident, Option<Abi>) => ( {
1908 let name = (stringify!($key_name)).replace("_", "-");
1909 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1910 match lookup_abi(s) {
1911 Some(abi) => base.$key_name = Some(abi),
1912 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
1915 })).unwrap_or(Ok(()))
1917 ($key_name:ident, TargetFamilies) => ( {
1918 if let Some(value) = obj.remove_key("target-family") {
1919 if let Some(v) = Json::as_array(&value) {
1920 base.$key_name = v.iter()
1921 .map(|a| a.as_string().unwrap().to_string())
1923 } else if let Some(v) = Json::as_string(&value) {
1924 base.$key_name = vec![v.to_string()];
1930 if let Some(j) = obj.remove_key("target-endian") {
1931 if let Some(s) = Json::as_string(&j) {
1932 base.endian = s.parse()?;
1934 incorrect_type.push("target-endian".to_string())
1938 if let Some(fp) = obj.remove_key("frame-pointer") {
1939 if let Some(s) = Json::as_string(&fp) {
1940 base.frame_pointer = s
1942 .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
1944 incorrect_type.push("frame-pointer".to_string())
1948 key!(is_builtin, bool);
1949 key!(c_int_width = "target-c-int-width");
1954 key!(linker_flavor, LinkerFlavor)?;
1955 key!(linker, optional);
1956 key!(lld_flavor, LldFlavor)?;
1957 key!(pre_link_objects, link_objects);
1958 key!(post_link_objects, link_objects);
1959 key!(pre_link_objects_fallback, link_objects);
1960 key!(post_link_objects_fallback, link_objects);
1961 key!(crt_objects_fallback, crt_objects_fallback)?;
1962 key!(pre_link_args, link_args);
1963 key!(late_link_args, link_args);
1964 key!(late_link_args_dynamic, link_args);
1965 key!(late_link_args_static, link_args);
1966 key!(post_link_args, link_args);
1967 key!(link_script, optional);
1968 key!(link_env, env);
1969 key!(link_env_remove, list);
1970 key!(asm_args, list);
1973 key!(dynamic_linking, bool);
1974 key!(only_cdylib, bool);
1975 key!(executables, bool);
1976 key!(relocation_model, RelocModel)?;
1977 key!(code_model, CodeModel)?;
1978 key!(tls_model, TlsModel)?;
1979 key!(disable_redzone, bool);
1980 key!(function_sections, bool);
1984 key!(staticlib_prefix);
1985 key!(staticlib_suffix);
1986 key!(families, TargetFamilies);
1987 key!(abi_return_struct_as_int, bool);
1988 key!(is_like_osx, bool);
1989 key!(is_like_solaris, bool);
1990 key!(is_like_windows, bool);
1991 key!(is_like_msvc, bool);
1992 key!(is_like_emscripten, bool);
1993 key!(is_like_fuchsia, bool);
1994 key!(is_like_wasm, bool);
1995 key!(dwarf_version, Option<u32>);
1996 key!(linker_is_gnu, bool);
1997 key!(allows_weak_linkage, bool);
1998 key!(has_rpath, bool);
1999 key!(no_default_libraries, bool);
2000 key!(position_independent_executables, bool);
2001 key!(static_position_independent_executables, bool);
2002 key!(needs_plt, bool);
2003 key!(relro_level, RelroLevel)?;
2004 key!(archive_format);
2005 key!(allow_asm, bool);
2006 key!(main_needs_argc_argv, bool);
2007 key!(has_elf_tls, bool);
2008 key!(obj_is_bitcode, bool);
2009 key!(forces_embed_bitcode, bool);
2010 key!(bitcode_llvm_cmdline);
2011 key!(max_atomic_width, Option<u64>);
2012 key!(min_atomic_width, Option<u64>);
2013 key!(atomic_cas, bool);
2014 key!(panic_strategy, PanicStrategy)?;
2015 key!(crt_static_allows_dylibs, bool);
2016 key!(crt_static_default, bool);
2017 key!(crt_static_respected, bool);
2018 key!(stack_probes, StackProbeType)?;
2019 key!(min_global_align, Option<u64>);
2020 key!(default_codegen_units, Option<u64>);
2021 key!(trap_unreachable, bool);
2022 key!(requires_lto, bool);
2023 key!(singlethread, bool);
2024 key!(no_builtins, bool);
2025 key!(default_hidden_visibility, bool);
2026 key!(emit_debug_gdb_scripts, bool);
2027 key!(requires_uwtable, bool);
2028 key!(default_uwtable, bool);
2029 key!(simd_types_indirect, bool);
2030 key!(limit_rdylib_exports, bool);
2031 key!(override_export_symbols, opt_list);
2032 key!(merge_functions, MergeFunctions)?;
2033 key!(mcount = "target-mcount");
2035 key!(relax_elf_relocations, bool);
2036 key!(llvm_args, list);
2037 key!(use_ctors_section, bool);
2038 key!(eh_frame_header, bool);
2039 key!(has_thumb_interworking, bool);
2040 key!(split_debuginfo, SplitDebuginfo)?;
2041 key!(supported_sanitizers, SanitizerSet)?;
2042 key!(default_adjusted_cabi, Option<Abi>)?;
2043 key!(c_enum_min_bits, u64);
2045 if base.is_builtin {
2046 // This can cause unfortunate ICEs later down the line.
2047 return Err("may not set is_builtin for targets not built-in".to_string());
2049 // Each field should have been read using `Json::remove_key` so any keys remaining are unused.
2050 let remaining_keys = obj.as_object().ok_or("Expected JSON object for target")?.keys();
2053 TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2057 /// Search for a JSON file specifying the given target triple.
2059 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2060 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
2061 /// bare filename already, so also check for that. If one of the hardcoded targets we know
2062 /// about, just return it directly.
2064 /// The error string could come from any of the APIs called, including filesystem access and
2067 target_triple: &TargetTriple,
2069 ) -> Result<(Target, TargetWarnings), String> {
2070 use rustc_serialize::json;
2074 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2075 let contents = fs::read(path).map_err(|e| e.to_string())?;
2076 let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
2077 Target::from_json(obj)
2080 match *target_triple {
2081 TargetTriple::TargetTriple(ref target_triple) => {
2082 // check if triple is in list of built-in targets
2083 if let Some(t) = load_builtin(target_triple) {
2084 return Ok((t, TargetWarnings::empty()));
2087 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2089 let mut target = target_triple.to_string();
2090 target.push_str(".json");
2091 PathBuf::from(target)
2094 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2096 for dir in env::split_paths(&target_path) {
2097 let p = dir.join(&path);
2099 return load_file(&p);
2103 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2105 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2106 let p = std::array::IntoIter::new([
2108 Path::new(&rustlib_path),
2109 Path::new("target.json"),
2111 .collect::<PathBuf>();
2113 return load_file(&p);
2116 Err(format!("Could not find specification for target {:?}", target_triple))
2118 TargetTriple::TargetPath(ref target_path) => {
2119 if target_path.is_file() {
2120 return load_file(&target_path);
2122 Err(format!("Target path {:?} is not a valid file", target_path))
2128 impl ToJson for Target {
2129 fn to_json(&self) -> Json {
2130 let mut d = BTreeMap::new();
2131 let default: TargetOptions = Default::default();
2133 macro_rules! target_val {
2135 let name = (stringify!($attr)).replace("_", "-");
2136 d.insert(name, self.$attr.to_json());
2138 ($attr:ident, $key_name:expr) => {{
2139 let name = $key_name;
2140 d.insert(name.to_string(), self.$attr.to_json());
2144 macro_rules! target_option_val {
2146 let name = (stringify!($attr)).replace("_", "-");
2147 if default.$attr != self.$attr {
2148 d.insert(name, self.$attr.to_json());
2151 ($attr:ident, $key_name:expr) => {{
2152 let name = $key_name;
2153 if default.$attr != self.$attr {
2154 d.insert(name.to_string(), self.$attr.to_json());
2157 (link_args - $attr:ident) => {{
2158 let name = (stringify!($attr)).replace("_", "-");
2159 if default.$attr != self.$attr {
2163 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
2164 .collect::<BTreeMap<_, _>>();
2165 d.insert(name, obj.to_json());
2168 (env - $attr:ident) => {{
2169 let name = (stringify!($attr)).replace("_", "-");
2170 if default.$attr != self.$attr {
2174 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
2175 .collect::<Vec<_>>();
2176 d.insert(name, obj.to_json());
2181 target_val!(llvm_target);
2182 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2184 target_val!(data_layout);
2186 target_option_val!(is_builtin);
2187 target_option_val!(endian, "target-endian");
2188 target_option_val!(c_int_width, "target-c-int-width");
2189 target_option_val!(os);
2190 target_option_val!(env);
2191 target_option_val!(abi);
2192 target_option_val!(vendor);
2193 target_option_val!(linker_flavor);
2194 target_option_val!(linker);
2195 target_option_val!(lld_flavor);
2196 target_option_val!(pre_link_objects);
2197 target_option_val!(post_link_objects);
2198 target_option_val!(pre_link_objects_fallback);
2199 target_option_val!(post_link_objects_fallback);
2200 target_option_val!(crt_objects_fallback);
2201 target_option_val!(link_args - pre_link_args);
2202 target_option_val!(link_args - late_link_args);
2203 target_option_val!(link_args - late_link_args_dynamic);
2204 target_option_val!(link_args - late_link_args_static);
2205 target_option_val!(link_args - post_link_args);
2206 target_option_val!(link_script);
2207 target_option_val!(env - link_env);
2208 target_option_val!(link_env_remove);
2209 target_option_val!(asm_args);
2210 target_option_val!(cpu);
2211 target_option_val!(features);
2212 target_option_val!(dynamic_linking);
2213 target_option_val!(only_cdylib);
2214 target_option_val!(executables);
2215 target_option_val!(relocation_model);
2216 target_option_val!(code_model);
2217 target_option_val!(tls_model);
2218 target_option_val!(disable_redzone);
2219 target_option_val!(frame_pointer);
2220 target_option_val!(function_sections);
2221 target_option_val!(dll_prefix);
2222 target_option_val!(dll_suffix);
2223 target_option_val!(exe_suffix);
2224 target_option_val!(staticlib_prefix);
2225 target_option_val!(staticlib_suffix);
2226 target_option_val!(families, "target-family");
2227 target_option_val!(abi_return_struct_as_int);
2228 target_option_val!(is_like_osx);
2229 target_option_val!(is_like_solaris);
2230 target_option_val!(is_like_windows);
2231 target_option_val!(is_like_msvc);
2232 target_option_val!(is_like_emscripten);
2233 target_option_val!(is_like_fuchsia);
2234 target_option_val!(is_like_wasm);
2235 target_option_val!(dwarf_version);
2236 target_option_val!(linker_is_gnu);
2237 target_option_val!(allows_weak_linkage);
2238 target_option_val!(has_rpath);
2239 target_option_val!(no_default_libraries);
2240 target_option_val!(position_independent_executables);
2241 target_option_val!(static_position_independent_executables);
2242 target_option_val!(needs_plt);
2243 target_option_val!(relro_level);
2244 target_option_val!(archive_format);
2245 target_option_val!(allow_asm);
2246 target_option_val!(main_needs_argc_argv);
2247 target_option_val!(has_elf_tls);
2248 target_option_val!(obj_is_bitcode);
2249 target_option_val!(forces_embed_bitcode);
2250 target_option_val!(bitcode_llvm_cmdline);
2251 target_option_val!(min_atomic_width);
2252 target_option_val!(max_atomic_width);
2253 target_option_val!(atomic_cas);
2254 target_option_val!(panic_strategy);
2255 target_option_val!(crt_static_allows_dylibs);
2256 target_option_val!(crt_static_default);
2257 target_option_val!(crt_static_respected);
2258 target_option_val!(stack_probes);
2259 target_option_val!(min_global_align);
2260 target_option_val!(default_codegen_units);
2261 target_option_val!(trap_unreachable);
2262 target_option_val!(requires_lto);
2263 target_option_val!(singlethread);
2264 target_option_val!(no_builtins);
2265 target_option_val!(default_hidden_visibility);
2266 target_option_val!(emit_debug_gdb_scripts);
2267 target_option_val!(requires_uwtable);
2268 target_option_val!(default_uwtable);
2269 target_option_val!(simd_types_indirect);
2270 target_option_val!(limit_rdylib_exports);
2271 target_option_val!(override_export_symbols);
2272 target_option_val!(merge_functions);
2273 target_option_val!(mcount, "target-mcount");
2274 target_option_val!(llvm_abiname);
2275 target_option_val!(relax_elf_relocations);
2276 target_option_val!(llvm_args);
2277 target_option_val!(use_ctors_section);
2278 target_option_val!(eh_frame_header);
2279 target_option_val!(has_thumb_interworking);
2280 target_option_val!(split_debuginfo);
2281 target_option_val!(supported_sanitizers);
2282 target_option_val!(c_enum_min_bits);
2284 if let Some(abi) = self.default_adjusted_cabi {
2285 d.insert("default-adjusted-cabi".to_string(), Abi::name(abi).to_json());
2292 /// Either a target triple string or a path to a JSON file.
2293 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2294 pub enum TargetTriple {
2295 TargetTriple(String),
2296 TargetPath(PathBuf),
2300 /// Creates a target triple from the passed target triple string.
2301 pub fn from_triple(triple: &str) -> Self {
2302 TargetTriple::TargetTriple(triple.to_string())
2305 /// Creates a target triple from the passed target path.
2306 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2307 let canonicalized_path = path.canonicalize()?;
2308 Ok(TargetTriple::TargetPath(canonicalized_path))
2311 /// Returns a string triple for this target.
2313 /// If this target is a path, the file name (without extension) is returned.
2314 pub fn triple(&self) -> &str {
2316 TargetTriple::TargetTriple(ref triple) => triple,
2317 TargetTriple::TargetPath(ref path) => path
2319 .expect("target path must not be empty")
2321 .expect("target path must be valid unicode"),
2325 /// Returns an extended string triple for this target.
2327 /// If this target is a path, a hash of the path is appended to the triple returned
2329 pub fn debug_triple(&self) -> String {
2330 use std::collections::hash_map::DefaultHasher;
2331 use std::hash::{Hash, Hasher};
2333 let triple = self.triple();
2334 if let TargetTriple::TargetPath(ref path) = *self {
2335 let mut hasher = DefaultHasher::new();
2336 path.hash(&mut hasher);
2337 let hash = hasher.finish();
2338 format!("{}-{}", triple, hash)
2345 impl fmt::Display for TargetTriple {
2346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2347 write!(f, "{}", self.debug_triple())