1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
9 //! # Using custom targets
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
26 //! # Defining a new target
28 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
37 use crate::abi::Endian;
38 use crate::spec::abi::{lookup as lookup_abi, Abi};
39 use crate::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
40 use rustc_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;
66 mod hermit_kernel_base;
71 mod linux_kernel_base;
73 mod linux_uclibc_base;
85 mod windows_msvc_base;
86 mod windows_uwp_gnu_base;
87 mod windows_uwp_msvc_base;
89 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
90 pub enum LinkerFlavor {
100 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
109 fn from_str(s: &str) -> Option<Self> {
111 "darwin" => LldFlavor::Ld64,
112 "gnu" => LldFlavor::Ld,
113 "link" => LldFlavor::Link,
114 "wasm" => LldFlavor::Wasm,
120 impl ToJson for LldFlavor {
121 fn to_json(&self) -> Json {
123 LldFlavor::Ld64 => "darwin",
124 LldFlavor::Ld => "gnu",
125 LldFlavor::Link => "link",
126 LldFlavor::Wasm => "wasm",
132 impl ToJson for LinkerFlavor {
133 fn to_json(&self) -> Json {
134 self.desc().to_json()
137 macro_rules! flavor_mappings {
138 ($((($($flavor:tt)*), $string:expr),)*) => (
140 pub const fn one_of() -> &'static str {
141 concat!("one of: ", $($string, " ",)*)
144 pub fn from_str(s: &str) -> Option<Self> {
146 $($string => $($flavor)*,)*
151 pub fn desc(&self) -> &str {
153 $($($flavor)* => $string,)*
161 ((LinkerFlavor::Em), "em"),
162 ((LinkerFlavor::Gcc), "gcc"),
163 ((LinkerFlavor::Ld), "ld"),
164 ((LinkerFlavor::Msvc), "msvc"),
165 ((LinkerFlavor::PtxLinker), "ptx-linker"),
166 ((LinkerFlavor::BpfLinker), "bpf-linker"),
167 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
168 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
169 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
170 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
173 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
174 pub enum PanicStrategy {
180 pub fn desc(&self) -> &str {
182 PanicStrategy::Unwind => "unwind",
183 PanicStrategy::Abort => "abort",
187 pub fn desc_symbol(&self) -> Symbol {
189 PanicStrategy::Unwind => sym::unwind,
190 PanicStrategy::Abort => sym::abort,
195 impl ToJson for PanicStrategy {
196 fn to_json(&self) -> Json {
198 PanicStrategy::Abort => "abort".to_json(),
199 PanicStrategy::Unwind => "unwind".to_json(),
204 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
205 pub enum RelroLevel {
213 pub fn desc(&self) -> &str {
215 RelroLevel::Full => "full",
216 RelroLevel::Partial => "partial",
217 RelroLevel::Off => "off",
218 RelroLevel::None => "none",
223 impl FromStr for RelroLevel {
226 fn from_str(s: &str) -> Result<RelroLevel, ()> {
228 "full" => Ok(RelroLevel::Full),
229 "partial" => Ok(RelroLevel::Partial),
230 "off" => Ok(RelroLevel::Off),
231 "none" => Ok(RelroLevel::None),
237 impl ToJson for RelroLevel {
238 fn to_json(&self) -> Json {
240 RelroLevel::Full => "full".to_json(),
241 RelroLevel::Partial => "partial".to_json(),
242 RelroLevel::Off => "off".to_json(),
243 RelroLevel::None => "None".to_json(),
248 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
249 pub enum MergeFunctions {
255 impl MergeFunctions {
256 pub fn desc(&self) -> &str {
258 MergeFunctions::Disabled => "disabled",
259 MergeFunctions::Trampolines => "trampolines",
260 MergeFunctions::Aliases => "aliases",
265 impl FromStr for MergeFunctions {
268 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
270 "disabled" => Ok(MergeFunctions::Disabled),
271 "trampolines" => Ok(MergeFunctions::Trampolines),
272 "aliases" => Ok(MergeFunctions::Aliases),
278 impl ToJson for MergeFunctions {
279 fn to_json(&self) -> Json {
281 MergeFunctions::Disabled => "disabled".to_json(),
282 MergeFunctions::Trampolines => "trampolines".to_json(),
283 MergeFunctions::Aliases => "aliases".to_json(),
288 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
289 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 "dynamic-no-pic" => RelocModel::DynamicNoPic,
306 "ropi" => RelocModel::Ropi,
307 "rwpi" => RelocModel::Rwpi,
308 "ropi-rwpi" => RelocModel::RopiRwpi,
314 impl ToJson for RelocModel {
315 fn to_json(&self) -> Json {
317 RelocModel::Static => "static",
318 RelocModel::Pic => "pic",
319 RelocModel::DynamicNoPic => "dynamic-no-pic",
320 RelocModel::Ropi => "ropi",
321 RelocModel::Rwpi => "rwpi",
322 RelocModel::RopiRwpi => "ropi-rwpi",
328 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
337 impl FromStr for CodeModel {
340 fn from_str(s: &str) -> Result<CodeModel, ()> {
342 "tiny" => CodeModel::Tiny,
343 "small" => CodeModel::Small,
344 "kernel" => CodeModel::Kernel,
345 "medium" => CodeModel::Medium,
346 "large" => CodeModel::Large,
352 impl ToJson for CodeModel {
353 fn to_json(&self) -> Json {
355 CodeModel::Tiny => "tiny",
356 CodeModel::Small => "small",
357 CodeModel::Kernel => "kernel",
358 CodeModel::Medium => "medium",
359 CodeModel::Large => "large",
365 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
373 impl FromStr for TlsModel {
376 fn from_str(s: &str) -> Result<TlsModel, ()> {
378 // Note the difference "general" vs "global" difference. The model name is "general",
379 // but the user-facing option name is "global" for consistency with other compilers.
380 "global-dynamic" => TlsModel::GeneralDynamic,
381 "local-dynamic" => TlsModel::LocalDynamic,
382 "initial-exec" => TlsModel::InitialExec,
383 "local-exec" => TlsModel::LocalExec,
389 impl ToJson for TlsModel {
390 fn to_json(&self) -> Json {
392 TlsModel::GeneralDynamic => "global-dynamic",
393 TlsModel::LocalDynamic => "local-dynamic",
394 TlsModel::InitialExec => "initial-exec",
395 TlsModel::LocalExec => "local-exec",
401 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
402 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
403 pub enum LinkOutputKind {
404 /// Dynamically linked non position-independent executable.
406 /// Dynamically linked position-independent executable.
408 /// Statically linked non position-independent executable.
410 /// Statically linked position-independent executable.
412 /// Regular dynamic library ("dynamically linked").
414 /// Dynamic library with bundled libc ("statically linked").
416 /// WASI module with a lifetime past the _initialize entry point
420 impl LinkOutputKind {
421 fn as_str(&self) -> &'static str {
423 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
424 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
425 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
426 LinkOutputKind::StaticPicExe => "static-pic-exe",
427 LinkOutputKind::DynamicDylib => "dynamic-dylib",
428 LinkOutputKind::StaticDylib => "static-dylib",
429 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
433 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
435 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
436 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
437 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
438 "static-pic-exe" => LinkOutputKind::StaticPicExe,
439 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
440 "static-dylib" => LinkOutputKind::StaticDylib,
441 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
447 impl fmt::Display for LinkOutputKind {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 f.write_str(self.as_str())
453 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
455 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
456 pub enum SplitDebuginfo {
457 /// Split debug-information is disabled, meaning that on supported platforms
458 /// you can find all debug information in the executable itself. This is
459 /// only supported for ELF effectively.
461 /// * Windows - not supported
462 /// * macOS - don't run `dsymutil`
463 /// * ELF - `.dwarf_*` sections
466 /// Split debug-information can be found in a "packed" location separate
467 /// from the final artifact. This is supported on all platforms.
469 /// * Windows - `*.pdb`
470 /// * macOS - `*.dSYM` (run `dsymutil`)
471 /// * ELF - `*.dwp` (run `rust-llvm-dwp`)
474 /// Split debug-information can be found in individual object files on the
475 /// filesystem. The main executable may point to the object files.
477 /// * Windows - not supported
478 /// * macOS - supported, scattered object files
479 /// * ELF - supported, scattered `*.dwo` files
483 impl SplitDebuginfo {
484 fn as_str(&self) -> &'static str {
486 SplitDebuginfo::Off => "off",
487 SplitDebuginfo::Packed => "packed",
488 SplitDebuginfo::Unpacked => "unpacked",
493 impl FromStr for SplitDebuginfo {
496 fn from_str(s: &str) -> Result<SplitDebuginfo, ()> {
498 "off" => SplitDebuginfo::Off,
499 "unpacked" => SplitDebuginfo::Unpacked,
500 "packed" => SplitDebuginfo::Packed,
506 impl ToJson for SplitDebuginfo {
507 fn to_json(&self) -> Json {
508 self.as_str().to_json()
512 impl fmt::Display for SplitDebuginfo {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 f.write_str(self.as_str())
518 #[derive(Clone, Debug, PartialEq, Eq)]
519 pub enum StackProbeType {
520 /// Don't emit any stack probes.
522 /// It is harmless to use this option even on targets that do not have backend support for
523 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
526 /// Call `__rust_probestack` whenever stack needs to be probed.
528 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
529 /// and call `__rust_probestack` otherwise.
530 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
533 impl StackProbeType {
534 fn from_json(json: &Json) -> Result<Self, String> {
535 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
538 .and_then(|o| o.as_string())
539 .ok_or_else(|| "expected `kind` to be a string")?;
541 "none" => Ok(StackProbeType::None),
542 "inline" => Ok(StackProbeType::Inline),
543 "call" => Ok(StackProbeType::Call),
544 "inline-or-call" => {
545 let min_version = object
546 .get("min-llvm-version-for-inline")
547 .and_then(|o| o.as_array())
548 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
549 let mut iter = min_version.into_iter().map(|v| {
550 let int = v.as_u64().ok_or_else(
551 || "expected `min-llvm-version-for-inline` values to be integers",
554 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
556 let min_llvm_version_for_inline = (
557 iter.next().unwrap_or(Ok(11))?,
558 iter.next().unwrap_or(Ok(0))?,
559 iter.next().unwrap_or(Ok(0))?,
561 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
563 _ => Err(String::from(
564 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
570 impl ToJson for StackProbeType {
571 fn to_json(&self) -> Json {
572 Json::Object(match self {
573 StackProbeType::None => {
574 vec![(String::from("kind"), "none".to_json())].into_iter().collect()
576 StackProbeType::Inline => {
577 vec![(String::from("kind"), "inline".to_json())].into_iter().collect()
579 StackProbeType::Call => {
580 vec![(String::from("kind"), "call".to_json())].into_iter().collect()
582 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => vec![
583 (String::from("kind"), "inline-or-call".to_json()),
585 String::from("min-llvm-version-for-inline"),
586 min_llvm_version_for_inline.to_json(),
595 bitflags::bitflags! {
596 #[derive(Default, Encodable, Decodable)]
597 pub struct SanitizerSet: u8 {
598 const ADDRESS = 1 << 0;
600 const MEMORY = 1 << 2;
601 const THREAD = 1 << 3;
602 const HWADDRESS = 1 << 4;
607 /// Return sanitizer's name
609 /// Returns none if the flags is a set of sanitizers numbering not exactly one.
610 fn as_str(self) -> Option<&'static str> {
612 SanitizerSet::ADDRESS => "address",
613 SanitizerSet::LEAK => "leak",
614 SanitizerSet::MEMORY => "memory",
615 SanitizerSet::THREAD => "thread",
616 SanitizerSet::HWADDRESS => "hwaddress",
622 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
623 impl fmt::Display for SanitizerSet {
624 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625 let mut first = true;
627 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
638 impl IntoIterator for SanitizerSet {
639 type Item = SanitizerSet;
640 type IntoIter = std::vec::IntoIter<SanitizerSet>;
642 fn into_iter(self) -> Self::IntoIter {
644 SanitizerSet::ADDRESS,
646 SanitizerSet::MEMORY,
647 SanitizerSet::THREAD,
648 SanitizerSet::HWADDRESS,
652 .filter(|&s| self.contains(s))
658 impl<CTX> HashStable<CTX> for SanitizerSet {
659 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
660 self.bits().hash_stable(ctx, hasher);
664 impl ToJson for SanitizerSet {
665 fn to_json(&self) -> Json {
667 .map(|v| Some(v.as_str()?.to_json()))
668 .collect::<Option<Vec<_>>>()
669 .unwrap_or(Vec::new())
674 macro_rules! supported_targets {
675 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
678 /// List of supported targets
679 pub const TARGETS: &[&str] = &[$($($triple),+),+];
681 fn load_builtin(target: &str) -> Option<Target> {
682 let mut t = match target {
683 $( $($triple)|+ => $module::target(), )+
687 debug!("got builtin target: {:?}", t);
695 // Cannot put this into a separate file without duplication, make an exception.
699 tests_impl::test_target(super::$module::target());
707 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
708 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
709 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
710 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
711 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
712 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
713 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
714 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
715 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
716 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
717 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
718 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
719 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
720 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
721 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
722 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
723 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
724 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
725 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
726 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
727 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
728 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
729 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
730 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
731 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
732 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
733 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
734 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
735 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
736 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
737 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
738 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
739 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
740 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
741 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
742 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
743 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
744 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
745 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
746 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
747 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
748 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
749 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
750 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
751 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
752 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
753 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
755 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
756 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
758 ("i686-linux-android", i686_linux_android),
759 ("x86_64-linux-android", x86_64_linux_android),
760 ("arm-linux-androideabi", arm_linux_androideabi),
761 ("armv7-linux-androideabi", armv7_linux_androideabi),
762 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
763 ("aarch64-linux-android", aarch64_linux_android),
765 ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
767 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
768 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
769 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
770 ("i686-unknown-freebsd", i686_unknown_freebsd),
771 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
772 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
774 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
776 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
777 ("i686-unknown-openbsd", i686_unknown_openbsd),
778 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
779 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
780 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
782 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
783 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
784 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
785 ("i686-unknown-netbsd", i686_unknown_netbsd),
786 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
787 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
788 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
790 ("i686-unknown-haiku", i686_unknown_haiku),
791 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
793 ("aarch64-apple-darwin", aarch64_apple_darwin),
794 ("x86_64-apple-darwin", x86_64_apple_darwin),
795 ("i686-apple-darwin", i686_apple_darwin),
797 ("aarch64-fuchsia", aarch64_fuchsia),
798 ("x86_64-fuchsia", x86_64_fuchsia),
800 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
802 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
804 ("aarch64-unknown-redox", aarch64_unknown_redox),
805 ("x86_64-unknown-redox", x86_64_unknown_redox),
807 ("i386-apple-ios", i386_apple_ios),
808 ("x86_64-apple-ios", x86_64_apple_ios),
809 ("aarch64-apple-ios", aarch64_apple_ios),
810 ("armv7-apple-ios", armv7_apple_ios),
811 ("armv7s-apple-ios", armv7s_apple_ios),
812 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
813 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
814 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
815 ("aarch64-apple-tvos", aarch64_apple_tvos),
816 ("x86_64-apple-tvos", x86_64_apple_tvos),
818 ("armebv7r-none-eabi", armebv7r_none_eabi),
819 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
820 ("armv7r-none-eabi", armv7r_none_eabi),
821 ("armv7r-none-eabihf", armv7r_none_eabihf),
823 ("x86_64-pc-solaris", x86_64_pc_solaris),
824 ("x86_64-sun-solaris", x86_64_sun_solaris),
825 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
827 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
829 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
830 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
831 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
832 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
834 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
835 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
836 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
837 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
838 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
839 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
840 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
841 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
842 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
844 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
845 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
846 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
847 ("wasm32-wasi", wasm32_wasi),
848 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
850 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
851 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
852 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
853 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
854 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
855 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
856 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
858 ("armv7a-none-eabi", armv7a_none_eabi),
859 ("armv7a-none-eabihf", armv7a_none_eabihf),
861 ("msp430-none-elf", msp430_none_elf),
863 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
864 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
866 ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
868 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
869 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
870 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
871 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
872 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
873 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
874 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
875 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
876 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
878 ("aarch64-unknown-none", aarch64_unknown_none),
879 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
881 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
883 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
884 ("i686-unknown-uefi", i686_unknown_uefi),
886 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
888 ("i686-wrs-vxworks", i686_wrs_vxworks),
889 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
890 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
891 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
892 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
893 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
894 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
896 ("mipsel-sony-psp", mipsel_sony_psp),
897 ("mipsel-unknown-none", mipsel_unknown_none),
898 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
900 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
901 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
902 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
904 ("bpfeb-unknown-none", bpfeb_unknown_none),
905 ("bpfel-unknown-none", bpfel_unknown_none),
908 /// Everything `rustc` knows about how to compile for a specific target.
910 /// Every field here must be specified, and has no default value.
911 #[derive(PartialEq, Clone, Debug)]
913 /// Target triple to pass to LLVM.
914 pub llvm_target: String,
915 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
916 pub pointer_width: u32,
917 /// Architecture to use for ABI considerations. Valid options include: "x86",
918 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
920 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
921 pub data_layout: String,
922 /// Optional settings with defaults.
923 pub options: TargetOptions,
926 pub trait HasTargetSpec {
927 fn target_spec(&self) -> &Target;
930 impl HasTargetSpec for Target {
932 fn target_spec(&self) -> &Target {
937 /// Optional aspects of a target specification.
939 /// This has an implementation of `Default`, see each field for what the default is. In general,
940 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
942 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
943 /// construction, all its fields logically belong to `Target` and available from `Target`
944 /// through `Deref` impls.
945 #[derive(PartialEq, Clone, Debug)]
946 pub struct TargetOptions {
947 /// Whether the target is built-in or loaded from a custom target specification.
948 pub is_builtin: bool,
950 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
952 /// Width of c_int type. Defaults to "32".
953 pub c_int_width: String,
954 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
955 /// "none" implies a bare metal target without `std` library.
956 /// A couple of targets having `std` also use "unknown" as an `os` value,
957 /// but they are exceptions.
959 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
961 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
963 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
964 /// on the command line. Defaults to `LinkerFlavor::Gcc`.
965 pub linker_flavor: LinkerFlavor,
968 pub linker: Option<String>,
970 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
971 /// without clarifying its flavor in any way.
972 pub lld_flavor: LldFlavor,
974 /// Linker arguments that are passed *before* any user-defined libraries.
975 pub pre_link_args: LinkArgs,
976 /// Objects to link before and after all other object code.
977 pub pre_link_objects: CrtObjects,
978 pub post_link_objects: CrtObjects,
979 /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
980 /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
981 /// See `crt_objects.rs` for some more detailed documentation.
982 pub pre_link_objects_fallback: CrtObjects,
983 pub post_link_objects_fallback: CrtObjects,
984 /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
985 pub crt_objects_fallback: Option<CrtObjectsFallback>,
987 /// Linker arguments that are unconditionally passed after any
988 /// user-defined but before post-link objects. Standard platform
989 /// libraries that should be always be linked to, usually go here.
990 pub late_link_args: LinkArgs,
991 /// Linker arguments used in addition to `late_link_args` if at least one
992 /// Rust dependency is dynamically linked.
993 pub late_link_args_dynamic: LinkArgs,
994 /// Linker arguments used in addition to `late_link_args` if aall Rust
995 /// dependencies are statically linked.
996 pub late_link_args_static: LinkArgs,
997 /// Linker arguments that are unconditionally passed *after* any
998 /// user-defined libraries.
999 pub post_link_args: LinkArgs,
1000 /// Optional link script applied to `dylib` and `executable` crate types.
1001 /// This is a string containing the script, not a path. Can only be applied
1002 /// to linkers where `linker_is_gnu` is true.
1003 pub link_script: Option<String>,
1005 /// Environment variables to be set for the linker invocation.
1006 pub link_env: Vec<(String, String)>,
1007 /// Environment variables to be removed for the linker invocation.
1008 pub link_env_remove: Vec<String>,
1010 /// Extra arguments to pass to the external assembler (when used)
1011 pub asm_args: Vec<String>,
1013 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1016 /// Default target features to pass to LLVM. These features will *always* be
1017 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1018 /// -mattr=$features`.
1019 pub features: String,
1020 /// Whether dynamic linking is available on this target. Defaults to false.
1021 pub dynamic_linking: bool,
1022 /// If dynamic linking is available, whether only cdylibs are supported.
1023 pub only_cdylib: bool,
1024 /// Whether executables are available on this target. iOS, for example, only allows static
1025 /// libraries. Defaults to false.
1026 pub executables: bool,
1027 /// Relocation model to use in object file. Corresponds to `llc
1028 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1029 pub relocation_model: RelocModel,
1030 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1031 /// Defaults to `None` which means "inherited from the base LLVM target".
1032 pub code_model: Option<CodeModel>,
1033 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1034 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1035 pub tls_model: TlsModel,
1036 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1037 pub disable_redzone: bool,
1038 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
1039 pub eliminate_frame_pointer: bool,
1040 /// Emit each function in its own section. Defaults to true.
1041 pub function_sections: bool,
1042 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1043 pub dll_prefix: String,
1044 /// String to append to the name of every dynamic library. Defaults to ".so".
1045 pub dll_suffix: String,
1046 /// String to append to the name of every executable.
1047 pub exe_suffix: String,
1048 /// String to prepend to the name of every static library. Defaults to "lib".
1049 pub staticlib_prefix: String,
1050 /// String to append to the name of every static library. Defaults to ".a".
1051 pub staticlib_suffix: String,
1052 /// Values of the `target_family` cfg set for this target.
1054 /// Common options are: "unix", "windows". Defaults to no families.
1056 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1057 pub families: Vec<String>,
1058 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1059 pub abi_return_struct_as_int: bool,
1060 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1061 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1062 pub is_like_osx: bool,
1063 /// Whether the target toolchain is like Solaris's.
1064 /// Only useful for compiling against Illumos/Solaris,
1065 /// as they have a different set of linker flags. Defaults to false.
1066 pub is_like_solaris: bool,
1067 /// Whether the target is like Windows.
1068 /// This is a combination of several more specific properties represented as a single flag:
1069 /// - The target uses a Windows ABI,
1070 /// - uses PE/COFF as a format for object code,
1071 /// - uses Windows-style dllexport/dllimport for shared libraries,
1072 /// - uses import libraries and .def files for symbol exports,
1073 /// - executables support setting a subsystem.
1074 pub is_like_windows: bool,
1075 /// Whether the target is like MSVC.
1076 /// This is a combination of several more specific properties represented as a single flag:
1077 /// - The target has all the properties from `is_like_windows`
1078 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1079 /// - has some MSVC-specific Windows ABI properties,
1080 /// - uses a link.exe-like linker,
1081 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1082 /// - uses SEH-based unwinding,
1083 /// - supports control flow guard mechanism.
1084 pub is_like_msvc: bool,
1085 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1086 /// Emscripten toolchain.
1087 /// Defaults to false.
1088 pub is_like_emscripten: bool,
1089 /// Whether the target toolchain is like Fuchsia's.
1090 pub is_like_fuchsia: bool,
1091 /// Whether a target toolchain is like WASM.
1092 pub is_like_wasm: bool,
1093 /// Version of DWARF to use if not using the default.
1094 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1095 pub dwarf_version: Option<u32>,
1096 /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1097 pub linker_is_gnu: bool,
1098 /// The MinGW toolchain has a known issue that prevents it from correctly
1099 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1100 /// symbol needs its own COMDAT section, weak linkage implies a large
1101 /// number sections that easily exceeds the given limit for larger
1102 /// codebases. Consequently we want a way to disallow weak linkage on some
1104 pub allows_weak_linkage: bool,
1105 /// Whether the linker support rpaths or not. Defaults to false.
1106 pub has_rpath: bool,
1107 /// Whether to disable linking to the default libraries, typically corresponds
1108 /// to `-nodefaultlibs`. Defaults to true.
1109 pub no_default_libraries: bool,
1110 /// Dynamically linked executables can be compiled as position independent
1111 /// if the default relocation model of position independent code is not
1112 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1113 /// the functions in the executable are not randomized and can be used
1114 /// during an exploit of a vulnerability in any code.
1115 pub position_independent_executables: bool,
1116 /// Executables that are both statically linked and position-independent are supported.
1117 pub static_position_independent_executables: bool,
1118 /// Determines if the target always requires using the PLT for indirect
1119 /// library calls or not. This controls the default value of the `-Z plt` flag.
1120 pub needs_plt: bool,
1121 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1122 /// resolve all symbols at startup and marks the GOT read-only before
1123 /// starting the program, preventing overwriting the GOT.
1124 pub relro_level: RelroLevel,
1125 /// Format that archives should be emitted in. This affects whether we use
1126 /// LLVM to assemble an archive or fall back to the system linker, and
1127 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1128 /// the system linker to be used.
1129 pub archive_format: String,
1130 /// Is asm!() allowed? Defaults to true.
1131 pub allow_asm: bool,
1132 /// Whether the runtime startup code requires the `main` function be passed
1133 /// `argc` and `argv` values.
1134 pub main_needs_argc_argv: bool,
1136 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
1138 pub has_elf_tls: bool,
1139 // This is mainly for easy compatibility with emscripten.
1140 // If we give emcc .o files that are actually .bc files it
1141 // will 'just work'.
1142 pub obj_is_bitcode: bool,
1143 /// Whether the target requires that emitted object code includes bitcode.
1144 pub forces_embed_bitcode: bool,
1145 /// Content of the LLVM cmdline section associated with embedded bitcode.
1146 pub bitcode_llvm_cmdline: String,
1148 /// Don't use this field; instead use the `.min_atomic_width()` method.
1149 pub min_atomic_width: Option<u64>,
1151 /// Don't use this field; instead use the `.max_atomic_width()` method.
1152 pub max_atomic_width: Option<u64>,
1154 /// Whether the target supports atomic CAS operations natively
1155 pub atomic_cas: bool,
1157 /// Panic strategy: "unwind" or "abort"
1158 pub panic_strategy: PanicStrategy,
1160 /// A list of ABIs unsupported by the current target. Note that generic ABIs
1161 /// are considered to be supported on all platforms and cannot be marked
1163 pub unsupported_abis: Vec<Abi>,
1165 /// Whether or not linking dylibs to a static CRT is allowed.
1166 pub crt_static_allows_dylibs: bool,
1167 /// Whether or not the CRT is statically linked by default.
1168 pub crt_static_default: bool,
1169 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1170 pub crt_static_respected: bool,
1172 /// The implementation of stack probes to use.
1173 pub stack_probes: StackProbeType,
1175 /// The minimum alignment for global symbols.
1176 pub min_global_align: Option<u64>,
1178 /// Default number of codegen units to use in debug mode
1179 pub default_codegen_units: Option<u64>,
1181 /// Whether to generate trap instructions in places where optimization would
1182 /// otherwise produce control flow that falls through into unrelated memory.
1183 pub trap_unreachable: bool,
1185 /// This target requires everything to be compiled with LTO to emit a final
1186 /// executable, aka there is no native linker for this target.
1187 pub requires_lto: bool,
1189 /// This target has no support for threads.
1190 pub singlethread: bool,
1192 /// Whether library functions call lowering/optimization is disabled in LLVM
1193 /// for this target unconditionally.
1194 pub no_builtins: bool,
1196 /// The default visibility for symbols in this target should be "hidden"
1197 /// rather than "default"
1198 pub default_hidden_visibility: bool,
1200 /// Whether a .debug_gdb_scripts section will be added to the output object file
1201 pub emit_debug_gdb_scripts: bool,
1203 /// Whether or not to unconditionally `uwtable` attributes on functions,
1204 /// typically because the platform needs to unwind for things like stack
1206 pub requires_uwtable: bool,
1208 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1209 /// is not specified and `uwtable` is not required on this target.
1210 pub default_uwtable: bool,
1212 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1213 /// typically required if a target can be compiled with a mixed set of
1214 /// target features. This is `true` by default, and `false` for targets like
1215 /// wasm32 where the whole program either has simd or not.
1216 pub simd_types_indirect: bool,
1218 /// Pass a list of symbol which should be exported in the dylib to the linker.
1219 pub limit_rdylib_exports: bool,
1221 /// If set, have the linker export exactly these symbols, instead of using
1222 /// the usual logic to figure this out from the crate itself.
1223 pub override_export_symbols: Option<Vec<String>>,
1225 /// Determines how or whether the MergeFunctions LLVM pass should run for
1226 /// this target. Either "disabled", "trampolines", or "aliases".
1227 /// The MergeFunctions pass is generally useful, but some targets may need
1228 /// to opt out. The default is "aliases".
1230 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1231 pub merge_functions: MergeFunctions,
1233 /// Use platform dependent mcount function
1236 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1237 pub llvm_abiname: String,
1239 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1240 pub relax_elf_relocations: bool,
1242 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1243 pub llvm_args: Vec<String>,
1245 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1246 /// to false (uses .init_array).
1247 pub use_ctors_section: bool,
1249 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1250 /// used to locate unwinding information is passed
1251 /// (only has effect if the linker is `ld`-like).
1252 pub eh_frame_header: bool,
1254 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1255 /// thumb and arm interworking.
1256 pub has_thumb_interworking: bool,
1258 /// How to handle split debug information, if at all. Specifying `None` has
1259 /// target-specific meaning.
1260 pub split_debuginfo: SplitDebuginfo,
1262 /// The sanitizers supported by this target
1264 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1265 /// enabled can generated on this target, but the necessary supporting libraries are not
1266 /// distributed with the target, the sanitizer should still appear in this list for the target.
1267 pub supported_sanitizers: SanitizerSet,
1269 /// If present it's a default value to use for adjusting the C ABI.
1270 pub default_adjusted_cabi: Option<Abi>,
1273 impl Default for TargetOptions {
1274 /// Creates a set of "sane defaults" for any target. This is still
1275 /// incomplete, and if used for compilation, will certainly not work.
1276 fn default() -> TargetOptions {
1279 endian: Endian::Little,
1280 c_int_width: "32".to_string(),
1281 os: "none".to_string(),
1283 vendor: "unknown".to_string(),
1284 linker_flavor: LinkerFlavor::Gcc,
1285 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1286 lld_flavor: LldFlavor::Ld,
1287 pre_link_args: LinkArgs::new(),
1288 post_link_args: LinkArgs::new(),
1290 asm_args: Vec::new(),
1291 cpu: "generic".to_string(),
1292 features: String::new(),
1293 dynamic_linking: false,
1296 relocation_model: RelocModel::Pic,
1298 tls_model: TlsModel::GeneralDynamic,
1299 disable_redzone: false,
1300 eliminate_frame_pointer: true,
1301 function_sections: true,
1302 dll_prefix: "lib".to_string(),
1303 dll_suffix: ".so".to_string(),
1304 exe_suffix: String::new(),
1305 staticlib_prefix: "lib".to_string(),
1306 staticlib_suffix: ".a".to_string(),
1307 families: Vec::new(),
1308 abi_return_struct_as_int: false,
1310 is_like_solaris: false,
1311 is_like_windows: false,
1312 is_like_emscripten: false,
1313 is_like_msvc: false,
1314 is_like_fuchsia: false,
1315 is_like_wasm: false,
1316 dwarf_version: None,
1317 linker_is_gnu: true,
1318 allows_weak_linkage: true,
1320 no_default_libraries: true,
1321 position_independent_executables: false,
1322 static_position_independent_executables: false,
1324 relro_level: RelroLevel::None,
1325 pre_link_objects: Default::default(),
1326 post_link_objects: Default::default(),
1327 pre_link_objects_fallback: Default::default(),
1328 post_link_objects_fallback: Default::default(),
1329 crt_objects_fallback: None,
1330 late_link_args: LinkArgs::new(),
1331 late_link_args_dynamic: LinkArgs::new(),
1332 late_link_args_static: LinkArgs::new(),
1333 link_env: Vec::new(),
1334 link_env_remove: Vec::new(),
1335 archive_format: "gnu".to_string(),
1336 main_needs_argc_argv: true,
1339 obj_is_bitcode: false,
1340 forces_embed_bitcode: false,
1341 bitcode_llvm_cmdline: String::new(),
1342 min_atomic_width: None,
1343 max_atomic_width: None,
1345 panic_strategy: PanicStrategy::Unwind,
1346 unsupported_abis: vec![],
1347 crt_static_allows_dylibs: false,
1348 crt_static_default: false,
1349 crt_static_respected: false,
1350 stack_probes: StackProbeType::None,
1351 min_global_align: None,
1352 default_codegen_units: None,
1353 trap_unreachable: true,
1354 requires_lto: false,
1355 singlethread: false,
1357 default_hidden_visibility: false,
1358 emit_debug_gdb_scripts: true,
1359 requires_uwtable: false,
1360 default_uwtable: false,
1361 simd_types_indirect: true,
1362 limit_rdylib_exports: true,
1363 override_export_symbols: None,
1364 merge_functions: MergeFunctions::Aliases,
1365 mcount: "mcount".to_string(),
1366 llvm_abiname: "".to_string(),
1367 relax_elf_relocations: false,
1369 use_ctors_section: false,
1370 eh_frame_header: true,
1371 has_thumb_interworking: false,
1372 split_debuginfo: SplitDebuginfo::Off,
1373 supported_sanitizers: SanitizerSet::empty(),
1374 default_adjusted_cabi: None,
1379 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1380 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1381 /// this `Deref` implementation is no longer necessary.
1382 impl Deref for Target {
1383 type Target = TargetOptions;
1385 fn deref(&self) -> &Self::Target {
1389 impl DerefMut for Target {
1390 fn deref_mut(&mut self) -> &mut Self::Target {
1396 /// Given a function ABI, turn it into the correct ABI for this target.
1397 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1399 Abi::System { unwind } => {
1400 if self.is_like_windows && self.arch == "x86" {
1401 Abi::Stdcall { unwind }
1406 // These ABI kinds are ignored on non-x86 Windows targets.
1407 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1408 // and the individual pages for __stdcall et al.
1409 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => {
1410 if self.is_like_windows && self.arch != "x86" { Abi::C { unwind } } else { abi }
1412 Abi::Fastcall | Abi::Vectorcall => {
1413 if self.is_like_windows && self.arch != "x86" {
1414 Abi::C { unwind: false }
1420 if self.arch == "x86_64" {
1423 Abi::C { unwind: false }
1427 Abi::C { unwind } => self.default_adjusted_cabi.unwrap_or(Abi::C { unwind }),
1433 /// Minimum integer size in bits that this target can perform atomic
1435 pub fn min_atomic_width(&self) -> u64 {
1436 self.min_atomic_width.unwrap_or(8)
1439 /// Maximum integer size in bits that this target can perform atomic
1441 pub fn max_atomic_width(&self) -> u64 {
1442 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1445 pub fn is_abi_supported(&self, abi: Abi) -> bool {
1446 abi.generic() || !self.unsupported_abis.contains(&abi)
1449 /// Loads a target descriptor from a JSON object.
1450 pub fn from_json(obj: Json) -> Result<Target, String> {
1451 // While ugly, this code must remain this way to retain
1452 // compatibility with existing JSON fields and the internal
1453 // expected naming of the Target and TargetOptions structs.
1454 // To ensure compatibility is retained, the built-in targets
1455 // are round-tripped through this code to catch cases where
1456 // the JSON parser is not updated to match the structs.
1458 let get_req_field = |name: &str| {
1460 .and_then(Json::as_string)
1461 .map(str::to_string)
1462 .ok_or_else(|| format!("Field {} in target specification is required", name))
1465 let mut base = Target {
1466 llvm_target: get_req_field("llvm-target")?,
1467 pointer_width: get_req_field("target-pointer-width")?
1469 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1470 data_layout: get_req_field("data-layout")?,
1471 arch: get_req_field("arch")?,
1472 options: Default::default(),
1476 ($key_name:ident) => ( {
1477 let name = (stringify!($key_name)).replace("_", "-");
1478 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1479 base.$key_name = s.to_string();
1482 ($key_name:ident = $json_name:expr) => ( {
1483 let name = $json_name;
1484 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1485 base.$key_name = s.to_string();
1488 ($key_name:ident, bool) => ( {
1489 let name = (stringify!($key_name)).replace("_", "-");
1490 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
1494 ($key_name:ident, Option<u32>) => ( {
1495 let name = (stringify!($key_name)).replace("_", "-");
1496 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1498 return Err("Not a valid DWARF version number".to_string());
1500 base.$key_name = Some(s as u32);
1503 ($key_name:ident, Option<u64>) => ( {
1504 let name = (stringify!($key_name)).replace("_", "-");
1505 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1506 base.$key_name = Some(s);
1509 ($key_name:ident, MergeFunctions) => ( {
1510 let name = (stringify!($key_name)).replace("_", "-");
1511 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1512 match s.parse::<MergeFunctions>() {
1513 Ok(mergefunc) => base.$key_name = mergefunc,
1514 _ => return Some(Err(format!("'{}' is not a valid value for \
1515 merge-functions. Use 'disabled', \
1516 'trampolines', or 'aliases'.",
1520 })).unwrap_or(Ok(()))
1522 ($key_name:ident, RelocModel) => ( {
1523 let name = (stringify!($key_name)).replace("_", "-");
1524 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1525 match s.parse::<RelocModel>() {
1526 Ok(relocation_model) => base.$key_name = relocation_model,
1527 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1528 Run `rustc --print relocation-models` to \
1529 see the list of supported values.", s))),
1532 })).unwrap_or(Ok(()))
1534 ($key_name:ident, CodeModel) => ( {
1535 let name = (stringify!($key_name)).replace("_", "-");
1536 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1537 match s.parse::<CodeModel>() {
1538 Ok(code_model) => base.$key_name = Some(code_model),
1539 _ => return Some(Err(format!("'{}' is not a valid code model. \
1540 Run `rustc --print code-models` to \
1541 see the list of supported values.", s))),
1544 })).unwrap_or(Ok(()))
1546 ($key_name:ident, TlsModel) => ( {
1547 let name = (stringify!($key_name)).replace("_", "-");
1548 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1549 match s.parse::<TlsModel>() {
1550 Ok(tls_model) => base.$key_name = tls_model,
1551 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1552 Run `rustc --print tls-models` to \
1553 see the list of supported values.", s))),
1556 })).unwrap_or(Ok(()))
1558 ($key_name:ident, PanicStrategy) => ( {
1559 let name = (stringify!($key_name)).replace("_", "-");
1560 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1562 "unwind" => base.$key_name = PanicStrategy::Unwind,
1563 "abort" => base.$key_name = PanicStrategy::Abort,
1564 _ => return Some(Err(format!("'{}' is not a valid value for \
1565 panic-strategy. Use 'unwind' or 'abort'.",
1569 })).unwrap_or(Ok(()))
1571 ($key_name:ident, RelroLevel) => ( {
1572 let name = (stringify!($key_name)).replace("_", "-");
1573 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1574 match s.parse::<RelroLevel>() {
1575 Ok(level) => base.$key_name = level,
1576 _ => return Some(Err(format!("'{}' is not a valid value for \
1577 relro-level. Use 'full', 'partial, or 'off'.",
1581 })).unwrap_or(Ok(()))
1583 ($key_name:ident, SplitDebuginfo) => ( {
1584 let name = (stringify!($key_name)).replace("_", "-");
1585 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1586 match s.parse::<SplitDebuginfo>() {
1587 Ok(level) => base.$key_name = level,
1588 _ => return Some(Err(format!("'{}' is not a valid value for \
1589 split-debuginfo. Use 'off' or 'dsymutil'.",
1593 })).unwrap_or(Ok(()))
1595 ($key_name:ident, list) => ( {
1596 let name = (stringify!($key_name)).replace("_", "-");
1597 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1598 base.$key_name = v.iter()
1599 .map(|a| a.as_string().unwrap().to_string())
1603 ($key_name:ident, opt_list) => ( {
1604 let name = (stringify!($key_name)).replace("_", "-");
1605 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1606 base.$key_name = Some(v.iter()
1607 .map(|a| a.as_string().unwrap().to_string())
1611 ($key_name:ident, optional) => ( {
1612 let name = (stringify!($key_name)).replace("_", "-");
1613 if let Some(o) = obj.find(&name[..]) {
1616 .map(|s| s.to_string() );
1619 ($key_name:ident, LldFlavor) => ( {
1620 let name = (stringify!($key_name)).replace("_", "-");
1621 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1622 if let Some(flavor) = LldFlavor::from_str(&s) {
1623 base.$key_name = flavor;
1625 return Some(Err(format!(
1626 "'{}' is not a valid value for lld-flavor. \
1627 Use 'darwin', 'gnu', 'link' or 'wasm.",
1631 })).unwrap_or(Ok(()))
1633 ($key_name:ident, LinkerFlavor) => ( {
1634 let name = (stringify!($key_name)).replace("_", "-");
1635 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1636 match LinkerFlavor::from_str(s) {
1637 Some(linker_flavor) => base.$key_name = linker_flavor,
1638 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1639 Use {}", s, LinkerFlavor::one_of()))),
1642 })).unwrap_or(Ok(()))
1644 ($key_name:ident, StackProbeType) => ( {
1645 let name = (stringify!($key_name)).replace("_", "-");
1646 obj.find(&name[..]).and_then(|o| match StackProbeType::from_json(o) {
1652 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1654 }).unwrap_or(Ok(()))
1656 ($key_name:ident, SanitizerSet) => ( {
1657 let name = (stringify!($key_name)).replace("_", "-");
1658 obj.find(&name[..]).and_then(|o| o.as_array()).and_then(|a| {
1660 base.$key_name |= match s.as_string() {
1661 Some("address") => SanitizerSet::ADDRESS,
1662 Some("leak") => SanitizerSet::LEAK,
1663 Some("memory") => SanitizerSet::MEMORY,
1664 Some("thread") => SanitizerSet::THREAD,
1665 Some("hwaddress") => SanitizerSet::HWADDRESS,
1666 Some(s) => return Some(Err(format!("unknown sanitizer {}", s))),
1667 _ => return Some(Err(format!("not a string: {:?}", s))),
1671 }).unwrap_or(Ok(()))
1674 ($key_name:ident, crt_objects_fallback) => ( {
1675 let name = (stringify!($key_name)).replace("_", "-");
1676 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1677 match s.parse::<CrtObjectsFallback>() {
1678 Ok(fallback) => base.$key_name = Some(fallback),
1679 _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1680 Use 'musl', 'mingw' or 'wasm'", s))),
1683 })).unwrap_or(Ok(()))
1685 ($key_name:ident, link_objects) => ( {
1686 let name = (stringify!($key_name)).replace("_", "-");
1687 if let Some(val) = obj.find(&name[..]) {
1688 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1689 JSON object with fields per CRT object kind.", name))?;
1690 let mut args = CrtObjects::new();
1692 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1693 format!("{}: '{}' is not a valid value for CRT object kind. \
1694 Use '(dynamic,static)-(nopic,pic)-exe' or \
1695 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1698 let v = v.as_array().ok_or_else(||
1699 format!("{}.{}: expected a JSON array", name, k)
1700 )?.iter().enumerate()
1702 let s = s.as_string().ok_or_else(||
1703 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1706 .collect::<Result<Vec<_>, String>>()?;
1708 args.insert(kind, v);
1710 base.$key_name = args;
1713 ($key_name:ident, link_args) => ( {
1714 let name = (stringify!($key_name)).replace("_", "-");
1715 if let Some(val) = obj.find(&name[..]) {
1716 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1717 JSON object with fields per linker-flavor.", name))?;
1718 let mut args = LinkArgs::new();
1720 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1721 format!("{}: '{}' is not a valid value for linker-flavor. \
1722 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1725 let v = v.as_array().ok_or_else(||
1726 format!("{}.{}: expected a JSON array", name, k)
1727 )?.iter().enumerate()
1729 let s = s.as_string().ok_or_else(||
1730 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1733 .collect::<Result<Vec<_>, String>>()?;
1735 args.insert(flavor, v);
1737 base.$key_name = args;
1740 ($key_name:ident, env) => ( {
1741 let name = (stringify!($key_name)).replace("_", "-");
1742 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1744 if let Some(s) = o.as_string() {
1745 let p = s.split('=').collect::<Vec<_>>();
1747 let k = p[0].to_string();
1748 let v = p[1].to_string();
1749 base.$key_name.push((k, v));
1755 ($key_name:ident, Option<Abi>) => ( {
1756 let name = (stringify!($key_name)).replace("_", "-");
1757 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1758 match lookup_abi(s) {
1759 Some(abi) => base.$key_name = Some(abi),
1760 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
1763 })).unwrap_or(Ok(()))
1765 ($key_name:ident, TargetFamilies) => ( {
1766 let value = obj.find("target-family");
1767 if let Some(v) = value.and_then(Json::as_array) {
1768 base.$key_name = v.iter()
1769 .map(|a| a.as_string().unwrap().to_string())
1771 } else if let Some(v) = value.and_then(Json::as_string) {
1772 base.$key_name = vec![v.to_string()];
1777 if let Some(s) = obj.find("target-endian").and_then(Json::as_string) {
1778 base.endian = s.parse()?;
1780 key!(is_builtin, bool);
1781 key!(c_int_width = "target-c-int-width");
1785 key!(linker_flavor, LinkerFlavor)?;
1786 key!(linker, optional);
1787 key!(lld_flavor, LldFlavor)?;
1788 key!(pre_link_objects, link_objects);
1789 key!(post_link_objects, link_objects);
1790 key!(pre_link_objects_fallback, link_objects);
1791 key!(post_link_objects_fallback, link_objects);
1792 key!(crt_objects_fallback, crt_objects_fallback)?;
1793 key!(pre_link_args, link_args);
1794 key!(late_link_args, link_args);
1795 key!(late_link_args_dynamic, link_args);
1796 key!(late_link_args_static, link_args);
1797 key!(post_link_args, link_args);
1798 key!(link_script, optional);
1799 key!(link_env, env);
1800 key!(link_env_remove, list);
1801 key!(asm_args, list);
1804 key!(dynamic_linking, bool);
1805 key!(only_cdylib, bool);
1806 key!(executables, bool);
1807 key!(relocation_model, RelocModel)?;
1808 key!(code_model, CodeModel)?;
1809 key!(tls_model, TlsModel)?;
1810 key!(disable_redzone, bool);
1811 key!(eliminate_frame_pointer, bool);
1812 key!(function_sections, bool);
1816 key!(staticlib_prefix);
1817 key!(staticlib_suffix);
1818 key!(families, TargetFamilies);
1819 key!(abi_return_struct_as_int, bool);
1820 key!(is_like_osx, bool);
1821 key!(is_like_solaris, bool);
1822 key!(is_like_windows, bool);
1823 key!(is_like_msvc, bool);
1824 key!(is_like_emscripten, bool);
1825 key!(is_like_fuchsia, bool);
1826 key!(is_like_wasm, bool);
1827 key!(dwarf_version, Option<u32>);
1828 key!(linker_is_gnu, bool);
1829 key!(allows_weak_linkage, bool);
1830 key!(has_rpath, bool);
1831 key!(no_default_libraries, bool);
1832 key!(position_independent_executables, bool);
1833 key!(static_position_independent_executables, bool);
1834 key!(needs_plt, bool);
1835 key!(relro_level, RelroLevel)?;
1836 key!(archive_format);
1837 key!(allow_asm, bool);
1838 key!(main_needs_argc_argv, bool);
1839 key!(has_elf_tls, bool);
1840 key!(obj_is_bitcode, bool);
1841 key!(forces_embed_bitcode, bool);
1842 key!(bitcode_llvm_cmdline);
1843 key!(max_atomic_width, Option<u64>);
1844 key!(min_atomic_width, Option<u64>);
1845 key!(atomic_cas, bool);
1846 key!(panic_strategy, PanicStrategy)?;
1847 key!(crt_static_allows_dylibs, bool);
1848 key!(crt_static_default, bool);
1849 key!(crt_static_respected, bool);
1850 key!(stack_probes, StackProbeType)?;
1851 key!(min_global_align, Option<u64>);
1852 key!(default_codegen_units, Option<u64>);
1853 key!(trap_unreachable, bool);
1854 key!(requires_lto, bool);
1855 key!(singlethread, bool);
1856 key!(no_builtins, bool);
1857 key!(default_hidden_visibility, bool);
1858 key!(emit_debug_gdb_scripts, bool);
1859 key!(requires_uwtable, bool);
1860 key!(default_uwtable, bool);
1861 key!(simd_types_indirect, bool);
1862 key!(limit_rdylib_exports, bool);
1863 key!(override_export_symbols, opt_list);
1864 key!(merge_functions, MergeFunctions)?;
1865 key!(mcount = "target-mcount");
1867 key!(relax_elf_relocations, bool);
1868 key!(llvm_args, list);
1869 key!(use_ctors_section, bool);
1870 key!(eh_frame_header, bool);
1871 key!(has_thumb_interworking, bool);
1872 key!(split_debuginfo, SplitDebuginfo)?;
1873 key!(supported_sanitizers, SanitizerSet)?;
1874 key!(default_adjusted_cabi, Option<Abi>)?;
1876 // NB: The old name is deprecated, but support for it is retained for
1878 for name in ["abi-blacklist", "unsupported-abis"].iter() {
1879 if let Some(array) = obj.find(name).and_then(Json::as_array) {
1880 for name in array.iter().filter_map(|abi| abi.as_string()) {
1881 match lookup_abi(name) {
1885 "The ABI \"{}\" is considered to be supported on all \
1886 targets and cannot be marked unsupported",
1891 base.unsupported_abis.push(abi)
1895 "Unknown ABI \"{}\" in target specification",
1907 /// Search for a JSON file specifying the given target triple.
1909 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
1910 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
1911 /// bare filename already, so also check for that. If one of the hardcoded targets we know
1912 /// about, just return it directly.
1914 /// The error string could come from any of the APIs called, including filesystem access and
1916 pub fn search(target_triple: &TargetTriple, sysroot: &PathBuf) -> Result<Target, String> {
1917 use rustc_serialize::json;
1921 fn load_file(path: &Path) -> Result<Target, String> {
1922 let contents = fs::read(path).map_err(|e| e.to_string())?;
1923 let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1924 Target::from_json(obj)
1927 match *target_triple {
1928 TargetTriple::TargetTriple(ref target_triple) => {
1929 // check if triple is in list of built-in targets
1930 if let Some(t) = load_builtin(target_triple) {
1934 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1936 let mut target = target_triple.to_string();
1937 target.push_str(".json");
1938 PathBuf::from(target)
1941 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1943 for dir in env::split_paths(&target_path) {
1944 let p = dir.join(&path);
1946 return load_file(&p);
1950 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
1952 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
1953 let p = std::array::IntoIter::new([
1955 Path::new(&rustlib_path),
1956 Path::new("target.json"),
1958 .collect::<PathBuf>();
1960 return load_file(&p);
1963 Err(format!("Could not find specification for target {:?}", target_triple))
1965 TargetTriple::TargetPath(ref target_path) => {
1966 if target_path.is_file() {
1967 return load_file(&target_path);
1969 Err(format!("Target path {:?} is not a valid file", target_path))
1975 impl ToJson for Target {
1976 fn to_json(&self) -> Json {
1977 let mut d = BTreeMap::new();
1978 let default: TargetOptions = Default::default();
1980 macro_rules! target_val {
1982 let name = (stringify!($attr)).replace("_", "-");
1983 d.insert(name, self.$attr.to_json());
1985 ($attr:ident, $key_name:expr) => {{
1986 let name = $key_name;
1987 d.insert(name.to_string(), self.$attr.to_json());
1991 macro_rules! target_option_val {
1993 let name = (stringify!($attr)).replace("_", "-");
1994 if default.$attr != self.$attr {
1995 d.insert(name, self.$attr.to_json());
1998 ($attr:ident, $key_name:expr) => {{
1999 let name = $key_name;
2000 if default.$attr != self.$attr {
2001 d.insert(name.to_string(), self.$attr.to_json());
2004 (link_args - $attr:ident) => {{
2005 let name = (stringify!($attr)).replace("_", "-");
2006 if default.$attr != self.$attr {
2010 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
2011 .collect::<BTreeMap<_, _>>();
2012 d.insert(name, obj.to_json());
2015 (env - $attr:ident) => {{
2016 let name = (stringify!($attr)).replace("_", "-");
2017 if default.$attr != self.$attr {
2021 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
2022 .collect::<Vec<_>>();
2023 d.insert(name, obj.to_json());
2028 target_val!(llvm_target);
2029 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2031 target_val!(data_layout);
2033 target_option_val!(is_builtin);
2034 target_option_val!(endian, "target-endian");
2035 target_option_val!(c_int_width, "target-c-int-width");
2036 target_option_val!(os);
2037 target_option_val!(env);
2038 target_option_val!(vendor);
2039 target_option_val!(linker_flavor);
2040 target_option_val!(linker);
2041 target_option_val!(lld_flavor);
2042 target_option_val!(pre_link_objects);
2043 target_option_val!(post_link_objects);
2044 target_option_val!(pre_link_objects_fallback);
2045 target_option_val!(post_link_objects_fallback);
2046 target_option_val!(crt_objects_fallback);
2047 target_option_val!(link_args - pre_link_args);
2048 target_option_val!(link_args - late_link_args);
2049 target_option_val!(link_args - late_link_args_dynamic);
2050 target_option_val!(link_args - late_link_args_static);
2051 target_option_val!(link_args - post_link_args);
2052 target_option_val!(link_script);
2053 target_option_val!(env - link_env);
2054 target_option_val!(link_env_remove);
2055 target_option_val!(asm_args);
2056 target_option_val!(cpu);
2057 target_option_val!(features);
2058 target_option_val!(dynamic_linking);
2059 target_option_val!(only_cdylib);
2060 target_option_val!(executables);
2061 target_option_val!(relocation_model);
2062 target_option_val!(code_model);
2063 target_option_val!(tls_model);
2064 target_option_val!(disable_redzone);
2065 target_option_val!(eliminate_frame_pointer);
2066 target_option_val!(function_sections);
2067 target_option_val!(dll_prefix);
2068 target_option_val!(dll_suffix);
2069 target_option_val!(exe_suffix);
2070 target_option_val!(staticlib_prefix);
2071 target_option_val!(staticlib_suffix);
2072 target_option_val!(families, "target-family");
2073 target_option_val!(abi_return_struct_as_int);
2074 target_option_val!(is_like_osx);
2075 target_option_val!(is_like_solaris);
2076 target_option_val!(is_like_windows);
2077 target_option_val!(is_like_msvc);
2078 target_option_val!(is_like_emscripten);
2079 target_option_val!(is_like_fuchsia);
2080 target_option_val!(is_like_wasm);
2081 target_option_val!(dwarf_version);
2082 target_option_val!(linker_is_gnu);
2083 target_option_val!(allows_weak_linkage);
2084 target_option_val!(has_rpath);
2085 target_option_val!(no_default_libraries);
2086 target_option_val!(position_independent_executables);
2087 target_option_val!(static_position_independent_executables);
2088 target_option_val!(needs_plt);
2089 target_option_val!(relro_level);
2090 target_option_val!(archive_format);
2091 target_option_val!(allow_asm);
2092 target_option_val!(main_needs_argc_argv);
2093 target_option_val!(has_elf_tls);
2094 target_option_val!(obj_is_bitcode);
2095 target_option_val!(forces_embed_bitcode);
2096 target_option_val!(bitcode_llvm_cmdline);
2097 target_option_val!(min_atomic_width);
2098 target_option_val!(max_atomic_width);
2099 target_option_val!(atomic_cas);
2100 target_option_val!(panic_strategy);
2101 target_option_val!(crt_static_allows_dylibs);
2102 target_option_val!(crt_static_default);
2103 target_option_val!(crt_static_respected);
2104 target_option_val!(stack_probes);
2105 target_option_val!(min_global_align);
2106 target_option_val!(default_codegen_units);
2107 target_option_val!(trap_unreachable);
2108 target_option_val!(requires_lto);
2109 target_option_val!(singlethread);
2110 target_option_val!(no_builtins);
2111 target_option_val!(default_hidden_visibility);
2112 target_option_val!(emit_debug_gdb_scripts);
2113 target_option_val!(requires_uwtable);
2114 target_option_val!(default_uwtable);
2115 target_option_val!(simd_types_indirect);
2116 target_option_val!(limit_rdylib_exports);
2117 target_option_val!(override_export_symbols);
2118 target_option_val!(merge_functions);
2119 target_option_val!(mcount, "target-mcount");
2120 target_option_val!(llvm_abiname);
2121 target_option_val!(relax_elf_relocations);
2122 target_option_val!(llvm_args);
2123 target_option_val!(use_ctors_section);
2124 target_option_val!(eh_frame_header);
2125 target_option_val!(has_thumb_interworking);
2126 target_option_val!(split_debuginfo);
2127 target_option_val!(supported_sanitizers);
2129 if let Some(abi) = self.default_adjusted_cabi {
2130 d.insert("default-adjusted-cabi".to_string(), Abi::name(abi).to_json());
2133 if default.unsupported_abis != self.unsupported_abis {
2135 "unsupported-abis".to_string(),
2136 self.unsupported_abis
2138 .map(|&name| Abi::name(name).to_json())
2139 .collect::<Vec<_>>()
2148 /// Either a target triple string or a path to a JSON file.
2149 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2150 pub enum TargetTriple {
2151 TargetTriple(String),
2152 TargetPath(PathBuf),
2156 /// Creates a target triple from the passed target triple string.
2157 pub fn from_triple(triple: &str) -> Self {
2158 TargetTriple::TargetTriple(triple.to_string())
2161 /// Creates a target triple from the passed target path.
2162 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2163 let canonicalized_path = path.canonicalize()?;
2164 Ok(TargetTriple::TargetPath(canonicalized_path))
2167 /// Returns a string triple for this target.
2169 /// If this target is a path, the file name (without extension) is returned.
2170 pub fn triple(&self) -> &str {
2172 TargetTriple::TargetTriple(ref triple) => triple,
2173 TargetTriple::TargetPath(ref path) => path
2175 .expect("target path must not be empty")
2177 .expect("target path must be valid unicode"),
2181 /// Returns an extended string triple for this target.
2183 /// If this target is a path, a hash of the path is appended to the triple returned
2185 pub fn debug_triple(&self) -> String {
2186 use std::collections::hash_map::DefaultHasher;
2187 use std::hash::{Hash, Hasher};
2189 let triple = self.triple();
2190 if let TargetTriple::TargetPath(ref path) = *self {
2191 let mut hasher = DefaultHasher::new();
2192 path.hash(&mut hasher);
2193 let hash = hasher.finish();
2194 format!("{}-{}", triple, hash)
2201 impl fmt::Display for TargetTriple {
2202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2203 write!(f, "{}", self.debug_triple())