1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
9 //! # Using custom targets
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
26 //! # Defining a new target
28 //! Targets are defined using [JSON](https://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
37 use crate::abi::Endian;
38 use crate::json::{Json, ToJson};
39 use crate::spec::abi::{lookup as lookup_abi, Abi};
40 use crate::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
41 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
42 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
43 use rustc_span::symbol::{sym, Symbol};
44 use serde_json::Value;
46 use std::collections::BTreeMap;
47 use std::convert::TryFrom;
48 use std::hash::{Hash, Hasher};
49 use std::iter::FromIterator;
50 use std::ops::{Deref, DerefMut};
51 use std::path::{Path, PathBuf};
52 use std::str::FromStr;
55 use rustc_macros::HashStable_Generic;
74 mod linux_uclibc_base;
86 mod windows_gnullvm_base;
87 mod windows_msvc_base;
88 mod windows_uwp_gnu_base;
89 mod windows_uwp_msvc_base;
91 /// Linker is called through a C/C++ compiler.
92 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
99 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
105 /// All linkers have some kinds of command line interfaces and rustc needs to know which commands
106 /// to use with each of them. So we cluster all such interfaces into a (somewhat arbitrary) number
107 /// of classes that we call "linker flavors".
109 /// Technically, it's not even necessary, we can nearly always infer the flavor from linker name
110 /// and target properties like `is_like_windows`/`is_like_osx`/etc. However, the PRs originally
111 /// introducing `-Clinker-flavor` (#40018 and friends) were aiming to reduce this kind of inference
112 /// and provide something certain and explicitly specified instead, and that design goal is still
115 /// The second goal is to keep the number of flavors to the minimum if possible.
116 /// LLD somewhat forces our hand here because that linker is self-sufficent only if its executable
117 /// (`argv[0]`) is named in specific way, otherwise it doesn't work and requires a
118 /// `-flavor LLD_FLAVOR` argument to choose which logic to use. Our shipped `rust-lld` in
119 /// particular is not named in such specific way, so it needs the flavor option, so we make our
120 /// linker flavors sufficiently fine-grained to satisfy LLD without inferring its flavor from other
121 /// target properties, in accordance with the first design goal.
123 /// The first component of the flavor is tightly coupled with the compilation target,
124 /// while the `Cc` and `Lld` flags can vary withing the same target.
125 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
126 pub enum LinkerFlavor {
127 /// Unix-like linker with GNU extensions (both naked and compiler-wrapped forms).
128 /// Besides similar "default" Linux/BSD linkers this also includes Windows/GNU linker,
129 /// which is somewhat different because it doesn't produce ELFs.
131 /// Unix-like linker for Apple targets (both naked and compiler-wrapped forms).
132 /// Extracted from the "umbrella" `Unix` flavor due to its corresponding LLD flavor.
134 /// Unix-like linker for Wasm targets (both naked and compiler-wrapped forms).
135 /// Extracted from the "umbrella" `Unix` flavor due to its corresponding LLD flavor.
136 /// Non-LLD version does not exist, so the lld flag is currently hardcoded here.
138 /// Basic Unix-like linker for "any other Unix" targets (Solaris/illumos, L4Re, MSP430, etc),
139 /// possibly with non-GNU extensions (both naked and compiler-wrapped forms).
140 /// LLD doesn't support any of these.
142 /// MSVC-style linker for Windows and UEFI, LLD supports it.
144 /// Emscripten Compiler Frontend, a wrapper around `WasmLld(Cc::Yes)` that has a different
145 /// interface and produces some additional JavaScript output.
147 // Below: other linker-like tools with unique interfaces for exotic targets.
148 /// Linker tool for BPF.
150 /// Linker tool for Nvidia PTX.
154 /// Linker flavors available externally through command line (`-Clinker-flavor`)
155 /// or json target specifications.
156 /// FIXME: This set has accumulated historically, bring it more in line with the internal
157 /// linker flavors (`LinkerFlavor`).
158 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
159 pub enum LinkerFlavorCli {
169 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
178 pub fn as_str(&self) -> &'static str {
180 LldFlavor::Wasm => "wasm",
181 LldFlavor::Ld64 => "darwin",
182 LldFlavor::Ld => "gnu",
183 LldFlavor::Link => "link",
187 fn from_str(s: &str) -> Option<Self> {
189 "darwin" => LldFlavor::Ld64,
190 "gnu" => LldFlavor::Ld,
191 "link" => LldFlavor::Link,
192 "wasm" => LldFlavor::Wasm,
198 impl ToJson for LldFlavor {
199 fn to_json(&self) -> Json {
200 self.as_str().to_json()
205 pub fn from_cli(cli: LinkerFlavorCli, target: &TargetOptions) -> LinkerFlavor {
206 Self::from_cli_impl(cli, target.linker_flavor.lld_flavor(), target.linker_flavor.is_gnu())
209 /// The passed CLI flavor is preferred over other args coming from the default target spec,
210 /// so this function can produce a flavor that is incompatible with the current target.
211 /// FIXME: Produce errors when `-Clinker-flavor` is set to something incompatible
212 /// with the current target.
213 fn from_cli_impl(cli: LinkerFlavorCli, lld_flavor: LldFlavor, is_gnu: bool) -> LinkerFlavor {
215 LinkerFlavorCli::Gcc => match lld_flavor {
216 LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::Yes, Lld::No),
217 LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::Yes, Lld::No),
218 LldFlavor::Wasm => LinkerFlavor::WasmLld(Cc::Yes),
219 LldFlavor::Ld | LldFlavor::Link => LinkerFlavor::Unix(Cc::Yes),
221 LinkerFlavorCli::Ld => match lld_flavor {
222 LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::No, Lld::No),
223 LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::No, Lld::No),
224 LldFlavor::Ld | LldFlavor::Wasm | LldFlavor::Link => LinkerFlavor::Unix(Cc::No),
226 LinkerFlavorCli::Lld(LldFlavor::Ld) => LinkerFlavor::Gnu(Cc::No, Lld::Yes),
227 LinkerFlavorCli::Lld(LldFlavor::Ld64) => LinkerFlavor::Darwin(Cc::No, Lld::Yes),
228 LinkerFlavorCli::Lld(LldFlavor::Wasm) => LinkerFlavor::WasmLld(Cc::No),
229 LinkerFlavorCli::Lld(LldFlavor::Link) => LinkerFlavor::Msvc(Lld::Yes),
230 LinkerFlavorCli::Msvc => LinkerFlavor::Msvc(Lld::No),
231 LinkerFlavorCli::Em => LinkerFlavor::EmCc,
232 LinkerFlavorCli::BpfLinker => LinkerFlavor::Bpf,
233 LinkerFlavorCli::PtxLinker => LinkerFlavor::Ptx,
237 fn to_cli(self) -> LinkerFlavorCli {
239 LinkerFlavor::Gnu(Cc::Yes, _)
240 | LinkerFlavor::Darwin(Cc::Yes, _)
241 | LinkerFlavor::WasmLld(Cc::Yes)
242 | LinkerFlavor::Unix(Cc::Yes) => LinkerFlavorCli::Gcc,
243 LinkerFlavor::Gnu(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld),
244 LinkerFlavor::Darwin(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld64),
245 LinkerFlavor::WasmLld(..) => LinkerFlavorCli::Lld(LldFlavor::Wasm),
246 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
249 LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Link),
250 LinkerFlavor::Msvc(..) => LinkerFlavorCli::Msvc,
251 LinkerFlavor::EmCc => LinkerFlavorCli::Em,
252 LinkerFlavor::Bpf => LinkerFlavorCli::BpfLinker,
253 LinkerFlavor::Ptx => LinkerFlavorCli::PtxLinker,
257 pub fn lld_flavor(self) -> LldFlavor {
259 LinkerFlavor::Gnu(..)
260 | LinkerFlavor::Unix(..)
263 | LinkerFlavor::Ptx => LldFlavor::Ld,
264 LinkerFlavor::Darwin(..) => LldFlavor::Ld64,
265 LinkerFlavor::WasmLld(..) => LldFlavor::Wasm,
266 LinkerFlavor::Msvc(..) => LldFlavor::Link,
270 pub fn is_gnu(self) -> bool {
271 matches!(self, LinkerFlavor::Gnu(..))
275 macro_rules! linker_flavor_cli_impls {
276 ($(($($flavor:tt)*) $string:literal)*) => (
277 impl LinkerFlavorCli {
278 pub const fn one_of() -> &'static str {
279 concat!("one of: ", $($string, " ",)*)
282 pub fn from_str(s: &str) -> Option<LinkerFlavorCli> {
284 $($string => $($flavor)*,)*
289 pub fn desc(&self) -> &str {
291 $($($flavor)* => $string,)*
298 linker_flavor_cli_impls! {
299 (LinkerFlavorCli::Gcc) "gcc"
300 (LinkerFlavorCli::Ld) "ld"
301 (LinkerFlavorCli::Lld(LldFlavor::Ld)) "ld.lld"
302 (LinkerFlavorCli::Lld(LldFlavor::Ld64)) "ld64.lld"
303 (LinkerFlavorCli::Lld(LldFlavor::Link)) "lld-link"
304 (LinkerFlavorCli::Lld(LldFlavor::Wasm)) "wasm-ld"
305 (LinkerFlavorCli::Msvc) "msvc"
306 (LinkerFlavorCli::Em) "em"
307 (LinkerFlavorCli::BpfLinker) "bpf-linker"
308 (LinkerFlavorCli::PtxLinker) "ptx-linker"
311 impl ToJson for LinkerFlavorCli {
312 fn to_json(&self) -> Json {
313 self.desc().to_json()
317 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
318 pub enum PanicStrategy {
324 pub fn desc(&self) -> &str {
326 PanicStrategy::Unwind => "unwind",
327 PanicStrategy::Abort => "abort",
331 pub const fn desc_symbol(&self) -> Symbol {
333 PanicStrategy::Unwind => sym::unwind,
334 PanicStrategy::Abort => sym::abort,
338 pub const fn all() -> [Symbol; 2] {
339 [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
343 impl ToJson for PanicStrategy {
344 fn to_json(&self) -> Json {
346 PanicStrategy::Abort => "abort".to_json(),
347 PanicStrategy::Unwind => "unwind".to_json(),
352 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
353 pub enum RelroLevel {
361 pub fn desc(&self) -> &str {
363 RelroLevel::Full => "full",
364 RelroLevel::Partial => "partial",
365 RelroLevel::Off => "off",
366 RelroLevel::None => "none",
371 impl FromStr for RelroLevel {
374 fn from_str(s: &str) -> Result<RelroLevel, ()> {
376 "full" => Ok(RelroLevel::Full),
377 "partial" => Ok(RelroLevel::Partial),
378 "off" => Ok(RelroLevel::Off),
379 "none" => Ok(RelroLevel::None),
385 impl ToJson for RelroLevel {
386 fn to_json(&self) -> Json {
388 RelroLevel::Full => "full".to_json(),
389 RelroLevel::Partial => "partial".to_json(),
390 RelroLevel::Off => "off".to_json(),
391 RelroLevel::None => "None".to_json(),
396 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
397 pub enum MergeFunctions {
403 impl MergeFunctions {
404 pub fn desc(&self) -> &str {
406 MergeFunctions::Disabled => "disabled",
407 MergeFunctions::Trampolines => "trampolines",
408 MergeFunctions::Aliases => "aliases",
413 impl FromStr for MergeFunctions {
416 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
418 "disabled" => Ok(MergeFunctions::Disabled),
419 "trampolines" => Ok(MergeFunctions::Trampolines),
420 "aliases" => Ok(MergeFunctions::Aliases),
426 impl ToJson for MergeFunctions {
427 fn to_json(&self) -> Json {
429 MergeFunctions::Disabled => "disabled".to_json(),
430 MergeFunctions::Trampolines => "trampolines".to_json(),
431 MergeFunctions::Aliases => "aliases".to_json(),
436 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
437 pub enum RelocModel {
447 impl FromStr for RelocModel {
450 fn from_str(s: &str) -> Result<RelocModel, ()> {
452 "static" => RelocModel::Static,
453 "pic" => RelocModel::Pic,
454 "pie" => RelocModel::Pie,
455 "dynamic-no-pic" => RelocModel::DynamicNoPic,
456 "ropi" => RelocModel::Ropi,
457 "rwpi" => RelocModel::Rwpi,
458 "ropi-rwpi" => RelocModel::RopiRwpi,
464 impl ToJson for RelocModel {
465 fn to_json(&self) -> Json {
467 RelocModel::Static => "static",
468 RelocModel::Pic => "pic",
469 RelocModel::Pie => "pie",
470 RelocModel::DynamicNoPic => "dynamic-no-pic",
471 RelocModel::Ropi => "ropi",
472 RelocModel::Rwpi => "rwpi",
473 RelocModel::RopiRwpi => "ropi-rwpi",
479 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
488 impl FromStr for CodeModel {
491 fn from_str(s: &str) -> Result<CodeModel, ()> {
493 "tiny" => CodeModel::Tiny,
494 "small" => CodeModel::Small,
495 "kernel" => CodeModel::Kernel,
496 "medium" => CodeModel::Medium,
497 "large" => CodeModel::Large,
503 impl ToJson for CodeModel {
504 fn to_json(&self) -> Json {
506 CodeModel::Tiny => "tiny",
507 CodeModel::Small => "small",
508 CodeModel::Kernel => "kernel",
509 CodeModel::Medium => "medium",
510 CodeModel::Large => "large",
516 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
524 impl FromStr for TlsModel {
527 fn from_str(s: &str) -> Result<TlsModel, ()> {
529 // Note the difference "general" vs "global" difference. The model name is "general",
530 // but the user-facing option name is "global" for consistency with other compilers.
531 "global-dynamic" => TlsModel::GeneralDynamic,
532 "local-dynamic" => TlsModel::LocalDynamic,
533 "initial-exec" => TlsModel::InitialExec,
534 "local-exec" => TlsModel::LocalExec,
540 impl ToJson for TlsModel {
541 fn to_json(&self) -> Json {
543 TlsModel::GeneralDynamic => "global-dynamic",
544 TlsModel::LocalDynamic => "local-dynamic",
545 TlsModel::InitialExec => "initial-exec",
546 TlsModel::LocalExec => "local-exec",
552 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
553 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
554 pub enum LinkOutputKind {
555 /// Dynamically linked non position-independent executable.
557 /// Dynamically linked position-independent executable.
559 /// Statically linked non position-independent executable.
561 /// Statically linked position-independent executable.
563 /// Regular dynamic library ("dynamically linked").
565 /// Dynamic library with bundled libc ("statically linked").
567 /// WASI module with a lifetime past the _initialize entry point
571 impl LinkOutputKind {
572 fn as_str(&self) -> &'static str {
574 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
575 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
576 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
577 LinkOutputKind::StaticPicExe => "static-pic-exe",
578 LinkOutputKind::DynamicDylib => "dynamic-dylib",
579 LinkOutputKind::StaticDylib => "static-dylib",
580 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
584 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
586 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
587 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
588 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
589 "static-pic-exe" => LinkOutputKind::StaticPicExe,
590 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
591 "static-dylib" => LinkOutputKind::StaticDylib,
592 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
598 impl fmt::Display for LinkOutputKind {
599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600 f.write_str(self.as_str())
604 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
605 pub type LinkArgsCli = BTreeMap<LinkerFlavorCli, Vec<StaticCow<str>>>;
607 /// Which kind of debuginfo does the target use?
609 /// Useful in determining whether a target supports Split DWARF (a target with
610 /// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example).
611 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
612 pub enum DebuginfoKind {
613 /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`).
616 /// DWARF debuginfo in dSYM files (such as on Apple platforms).
618 /// Program database files (such as on Windows).
623 fn as_str(&self) -> &'static str {
625 DebuginfoKind::Dwarf => "dwarf",
626 DebuginfoKind::DwarfDsym => "dwarf-dsym",
627 DebuginfoKind::Pdb => "pdb",
632 impl FromStr for DebuginfoKind {
635 fn from_str(s: &str) -> Result<Self, ()> {
637 "dwarf" => DebuginfoKind::Dwarf,
638 "dwarf-dsym" => DebuginfoKind::DwarfDsym,
639 "pdb" => DebuginfoKind::Pdb,
645 impl ToJson for DebuginfoKind {
646 fn to_json(&self) -> Json {
647 self.as_str().to_json()
651 impl fmt::Display for DebuginfoKind {
652 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653 f.write_str(self.as_str())
657 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
658 pub enum SplitDebuginfo {
659 /// Split debug-information is disabled, meaning that on supported platforms
660 /// you can find all debug information in the executable itself. This is
661 /// only supported for ELF effectively.
663 /// * Windows - not supported
664 /// * macOS - don't run `dsymutil`
665 /// * ELF - `.debug_*` sections
669 /// Split debug-information can be found in a "packed" location separate
670 /// from the final artifact. This is supported on all platforms.
672 /// * Windows - `*.pdb`
673 /// * macOS - `*.dSYM` (run `dsymutil`)
674 /// * ELF - `*.dwp` (run `thorin`)
677 /// Split debug-information can be found in individual object files on the
678 /// filesystem. The main executable may point to the object files.
680 /// * Windows - not supported
681 /// * macOS - supported, scattered object files
682 /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
686 impl SplitDebuginfo {
687 fn as_str(&self) -> &'static str {
689 SplitDebuginfo::Off => "off",
690 SplitDebuginfo::Packed => "packed",
691 SplitDebuginfo::Unpacked => "unpacked",
696 impl FromStr for SplitDebuginfo {
699 fn from_str(s: &str) -> Result<Self, ()> {
701 "off" => SplitDebuginfo::Off,
702 "unpacked" => SplitDebuginfo::Unpacked,
703 "packed" => SplitDebuginfo::Packed,
709 impl ToJson for SplitDebuginfo {
710 fn to_json(&self) -> Json {
711 self.as_str().to_json()
715 impl fmt::Display for SplitDebuginfo {
716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
717 f.write_str(self.as_str())
721 #[derive(Clone, Debug, PartialEq, Eq)]
722 pub enum StackProbeType {
723 /// Don't emit any stack probes.
725 /// It is harmless to use this option even on targets that do not have backend support for
726 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
729 /// Call `__rust_probestack` whenever stack needs to be probed.
731 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
732 /// and call `__rust_probestack` otherwise.
733 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
736 impl StackProbeType {
737 // LLVM X86 targets (ix86 and x86_64) can use inline-asm stack probes starting with LLVM 16.
738 // Notable past issues were rust#83139 (fixed in 14) and rust#84667 (fixed in 16).
739 const X86: Self = Self::InlineOrCall { min_llvm_version_for_inline: (16, 0, 0) };
741 fn from_json(json: &Json) -> Result<Self, String> {
742 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
745 .and_then(|o| o.as_str())
746 .ok_or_else(|| "expected `kind` to be a string")?;
748 "none" => Ok(StackProbeType::None),
749 "inline" => Ok(StackProbeType::Inline),
750 "call" => Ok(StackProbeType::Call),
751 "inline-or-call" => {
752 let min_version = object
753 .get("min-llvm-version-for-inline")
754 .and_then(|o| o.as_array())
755 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
756 let mut iter = min_version.into_iter().map(|v| {
757 let int = v.as_u64().ok_or_else(
758 || "expected `min-llvm-version-for-inline` values to be integers",
761 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
763 let min_llvm_version_for_inline = (
764 iter.next().unwrap_or(Ok(11))?,
765 iter.next().unwrap_or(Ok(0))?,
766 iter.next().unwrap_or(Ok(0))?,
768 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
770 _ => Err(String::from(
771 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
777 impl ToJson for StackProbeType {
778 fn to_json(&self) -> Json {
779 Json::Object(match self {
780 StackProbeType::None => {
781 [(String::from("kind"), "none".to_json())].into_iter().collect()
783 StackProbeType::Inline => {
784 [(String::from("kind"), "inline".to_json())].into_iter().collect()
786 StackProbeType::Call => {
787 [(String::from("kind"), "call".to_json())].into_iter().collect()
789 StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
790 (String::from("kind"), "inline-or-call".to_json()),
792 String::from("min-llvm-version-for-inline"),
793 Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
802 bitflags::bitflags! {
803 #[derive(Default, Encodable, Decodable)]
804 pub struct SanitizerSet: u8 {
805 const ADDRESS = 1 << 0;
807 const MEMORY = 1 << 2;
808 const THREAD = 1 << 3;
809 const HWADDRESS = 1 << 4;
811 const MEMTAG = 1 << 6;
812 const SHADOWCALLSTACK = 1 << 7;
817 /// Return sanitizer's name
819 /// Returns none if the flags is a set of sanitizers numbering not exactly one.
820 pub fn as_str(self) -> Option<&'static str> {
822 SanitizerSet::ADDRESS => "address",
823 SanitizerSet::CFI => "cfi",
824 SanitizerSet::LEAK => "leak",
825 SanitizerSet::MEMORY => "memory",
826 SanitizerSet::MEMTAG => "memtag",
827 SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
828 SanitizerSet::THREAD => "thread",
829 SanitizerSet::HWADDRESS => "hwaddress",
835 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
836 impl fmt::Display for SanitizerSet {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 let mut first = true;
840 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
851 impl IntoIterator for SanitizerSet {
852 type Item = SanitizerSet;
853 type IntoIter = std::vec::IntoIter<SanitizerSet>;
855 fn into_iter(self) -> Self::IntoIter {
857 SanitizerSet::ADDRESS,
860 SanitizerSet::MEMORY,
861 SanitizerSet::MEMTAG,
862 SanitizerSet::SHADOWCALLSTACK,
863 SanitizerSet::THREAD,
864 SanitizerSet::HWADDRESS,
868 .filter(|&s| self.contains(s))
874 impl<CTX> HashStable<CTX> for SanitizerSet {
875 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
876 self.bits().hash_stable(ctx, hasher);
880 impl ToJson for SanitizerSet {
881 fn to_json(&self) -> Json {
883 .map(|v| Some(v.as_str()?.to_json()))
884 .collect::<Option<Vec<_>>>()
890 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
891 pub enum FramePointer {
892 /// Forces the machine code generator to always preserve the frame pointers.
894 /// Forces the machine code generator to preserve the frame pointers except for the leaf
895 /// functions (i.e. those that don't call other functions).
897 /// Allows the machine code generator to omit the frame pointers.
899 /// This option does not guarantee that the frame pointers will be omitted.
903 impl FromStr for FramePointer {
905 fn from_str(s: &str) -> Result<Self, ()> {
907 "always" => Self::Always,
908 "non-leaf" => Self::NonLeaf,
909 "may-omit" => Self::MayOmit,
915 impl ToJson for FramePointer {
916 fn to_json(&self) -> Json {
918 Self::Always => "always",
919 Self::NonLeaf => "non-leaf",
920 Self::MayOmit => "may-omit",
926 /// Controls use of stack canaries.
927 #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
928 pub enum StackProtector {
929 /// Disable stack canary generation.
932 /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
933 /// llvm/docs/LangRef.rst). This triggers stack canary generation in
934 /// functions which contain an array of a byte-sized type with more than
938 /// On LLVM, mark all generated LLVM functions with the `sspstrong`
939 /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
940 /// generation in functions which either contain an array, or which take
941 /// the address of a local variable.
944 /// Generate stack canaries in all functions.
948 impl StackProtector {
949 fn as_str(&self) -> &'static str {
951 StackProtector::None => "none",
952 StackProtector::Basic => "basic",
953 StackProtector::Strong => "strong",
954 StackProtector::All => "all",
959 impl FromStr for StackProtector {
962 fn from_str(s: &str) -> Result<StackProtector, ()> {
964 "none" => StackProtector::None,
965 "basic" => StackProtector::Basic,
966 "strong" => StackProtector::Strong,
967 "all" => StackProtector::All,
973 impl fmt::Display for StackProtector {
974 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
975 f.write_str(self.as_str())
979 macro_rules! supported_targets {
980 ( $(($triple:literal, $module:ident ),)+ ) => {
983 /// List of supported targets
984 pub const TARGETS: &[&str] = &[$($triple),+];
986 fn load_builtin(target: &str) -> Option<Target> {
987 let mut t = match target {
988 $( $triple => $module::target(), )+
992 debug!("got builtin target: {:?}", t);
1000 // Cannot put this into a separate file without duplication, make an exception.
1002 #[test] // `#[test]`
1004 tests_impl::test_target(super::$module::target());
1011 supported_targets! {
1012 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
1013 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
1014 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
1015 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
1016 ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
1017 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
1018 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
1019 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
1020 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
1021 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
1022 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
1023 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
1024 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
1025 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
1026 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
1027 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
1028 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
1029 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
1030 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
1031 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
1032 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
1033 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
1034 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
1035 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
1036 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
1037 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
1038 ("armeb-unknown-linux-gnueabi", armeb_unknown_linux_gnueabi),
1039 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
1040 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
1041 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
1042 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
1043 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
1044 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
1045 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
1046 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
1047 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
1048 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
1049 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
1050 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
1051 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
1052 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
1053 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
1054 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
1055 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
1056 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
1057 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
1058 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
1059 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
1060 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
1062 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
1063 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
1065 ("i686-linux-android", i686_linux_android),
1066 ("x86_64-linux-android", x86_64_linux_android),
1067 ("arm-linux-androideabi", arm_linux_androideabi),
1068 ("armv7-linux-androideabi", armv7_linux_androideabi),
1069 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
1070 ("aarch64-linux-android", aarch64_linux_android),
1072 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
1073 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
1074 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
1075 ("i686-unknown-freebsd", i686_unknown_freebsd),
1076 ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
1077 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
1078 ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
1079 ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
1080 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
1082 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
1084 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
1085 ("i686-unknown-openbsd", i686_unknown_openbsd),
1086 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
1087 ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
1088 ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
1089 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
1090 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
1092 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
1093 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
1094 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
1095 ("i686-unknown-netbsd", i686_unknown_netbsd),
1096 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
1097 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
1098 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
1100 ("i686-unknown-haiku", i686_unknown_haiku),
1101 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
1103 ("aarch64-apple-darwin", aarch64_apple_darwin),
1104 ("x86_64-apple-darwin", x86_64_apple_darwin),
1105 ("i686-apple-darwin", i686_apple_darwin),
1107 ("aarch64-fuchsia", aarch64_fuchsia),
1108 ("x86_64-fuchsia", x86_64_fuchsia),
1110 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
1112 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
1114 ("aarch64-unknown-redox", aarch64_unknown_redox),
1115 ("x86_64-unknown-redox", x86_64_unknown_redox),
1117 ("i386-apple-ios", i386_apple_ios),
1118 ("x86_64-apple-ios", x86_64_apple_ios),
1119 ("aarch64-apple-ios", aarch64_apple_ios),
1120 ("armv7-apple-ios", armv7_apple_ios),
1121 ("armv7s-apple-ios", armv7s_apple_ios),
1122 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
1123 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
1124 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
1125 ("aarch64-apple-tvos", aarch64_apple_tvos),
1126 ("x86_64-apple-tvos", x86_64_apple_tvos),
1128 ("armv7k-apple-watchos", armv7k_apple_watchos),
1129 ("arm64_32-apple-watchos", arm64_32_apple_watchos),
1130 ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
1131 ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
1133 ("armebv7r-none-eabi", armebv7r_none_eabi),
1134 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
1135 ("armv7r-none-eabi", armv7r_none_eabi),
1136 ("armv7r-none-eabihf", armv7r_none_eabihf),
1138 ("x86_64-pc-solaris", x86_64_pc_solaris),
1139 ("x86_64-sun-solaris", x86_64_sun_solaris),
1140 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1142 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1144 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1145 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1146 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1147 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1149 ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1150 ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1152 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1153 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1154 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1155 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1156 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1157 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1158 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
1159 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1160 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1162 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
1163 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1164 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1165 ("wasm32-wasi", wasm32_wasi),
1166 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1168 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1169 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1170 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1171 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1172 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1173 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1174 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1176 ("armv7a-none-eabi", armv7a_none_eabi),
1177 ("armv7a-none-eabihf", armv7a_none_eabihf),
1179 ("msp430-none-elf", msp430_none_elf),
1181 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1182 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1184 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1185 ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1186 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1187 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1188 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1189 ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1190 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1191 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1192 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1193 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1194 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1195 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1197 ("aarch64-unknown-none", aarch64_unknown_none),
1198 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1200 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1202 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1203 ("i686-unknown-uefi", i686_unknown_uefi),
1204 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1206 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1208 ("i686-wrs-vxworks", i686_wrs_vxworks),
1209 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1210 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1211 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1212 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1213 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1214 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1216 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1217 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1218 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1220 ("mipsel-sony-psp", mipsel_sony_psp),
1221 ("mipsel-sony-psx", mipsel_sony_psx),
1222 ("mipsel-unknown-none", mipsel_unknown_none),
1223 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1224 ("armv4t-none-eabi", armv4t_none_eabi),
1225 ("thumbv5te-none-eabi", thumbv5te_none_eabi),
1226 ("armv5te-none-eabi", armv5te_none_eabi),
1228 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1229 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1230 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1232 ("bpfeb-unknown-none", bpfeb_unknown_none),
1233 ("bpfel-unknown-none", bpfel_unknown_none),
1235 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1237 ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1239 ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1240 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1242 ("x86_64-unknown-none", x86_64_unknown_none),
1244 ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1247 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1250 ::std::borrow::Cow::Borrowed(&[])
1252 ($($x:expr),+ $(,)?) => {
1253 ::std::borrow::Cow::Borrowed(&[
1255 ::std::borrow::Cow::Borrowed($x),
1263 /// Warnings encountered when parsing the target `json`.
1265 /// Includes fields that weren't recognized and fields that don't have the expected type.
1266 #[derive(Debug, PartialEq)]
1267 pub struct TargetWarnings {
1268 unused_fields: Vec<String>,
1269 incorrect_type: Vec<String>,
1272 impl TargetWarnings {
1273 pub fn empty() -> Self {
1274 Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1277 pub fn warning_messages(&self) -> Vec<String> {
1278 let mut warnings = vec![];
1279 if !self.unused_fields.is_empty() {
1280 warnings.push(format!(
1281 "target json file contains unused fields: {}",
1282 self.unused_fields.join(", ")
1285 if !self.incorrect_type.is_empty() {
1286 warnings.push(format!(
1287 "target json file contains fields whose value doesn't have the correct json type: {}",
1288 self.incorrect_type.join(", ")
1295 /// Everything `rustc` knows about how to compile for a specific target.
1297 /// Every field here must be specified, and has no default value.
1298 #[derive(PartialEq, Clone, Debug)]
1300 /// Target triple to pass to LLVM.
1301 pub llvm_target: StaticCow<str>,
1302 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1303 pub pointer_width: u32,
1304 /// Architecture to use for ABI considerations. Valid options include: "x86",
1305 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1306 pub arch: StaticCow<str>,
1307 /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1308 pub data_layout: StaticCow<str>,
1309 /// Optional settings with defaults.
1310 pub options: TargetOptions,
1313 pub trait HasTargetSpec {
1314 fn target_spec(&self) -> &Target;
1317 impl HasTargetSpec for Target {
1319 fn target_spec(&self) -> &Target {
1324 type StaticCow<T> = Cow<'static, T>;
1326 /// Optional aspects of a target specification.
1328 /// This has an implementation of `Default`, see each field for what the default is. In general,
1329 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1331 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1332 /// construction, all its fields logically belong to `Target` and available from `Target`
1333 /// through `Deref` impls.
1334 #[derive(PartialEq, Clone, Debug)]
1335 pub struct TargetOptions {
1336 /// Whether the target is built-in or loaded from a custom target specification.
1337 pub is_builtin: bool,
1339 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1341 /// Width of c_int type. Defaults to "32".
1342 pub c_int_width: StaticCow<str>,
1343 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1344 /// "none" implies a bare metal target without `std` library.
1345 /// A couple of targets having `std` also use "unknown" as an `os` value,
1346 /// but they are exceptions.
1347 pub os: StaticCow<str>,
1348 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1349 pub env: StaticCow<str>,
1350 /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1351 /// or `"eabihf"`. Defaults to "".
1352 pub abi: StaticCow<str>,
1353 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1354 pub vendor: StaticCow<str>,
1356 /// Linker to invoke
1357 pub linker: Option<StaticCow<str>>,
1358 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1359 /// on the command line. Defaults to `LinkerFlavor::Gnu(Cc::Yes, Lld::No)`.
1360 pub linker_flavor: LinkerFlavor,
1361 linker_flavor_json: LinkerFlavorCli,
1362 lld_flavor_json: LldFlavor,
1363 linker_is_gnu_json: bool,
1365 /// Objects to link before and after all other object code.
1366 pub pre_link_objects: CrtObjects,
1367 pub post_link_objects: CrtObjects,
1368 /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1369 pub pre_link_objects_self_contained: CrtObjects,
1370 pub post_link_objects_self_contained: CrtObjects,
1371 pub link_self_contained: LinkSelfContainedDefault,
1373 /// Linker arguments that are passed *before* any user-defined libraries.
1374 pub pre_link_args: LinkArgs,
1375 pre_link_args_json: LinkArgsCli,
1376 /// Linker arguments that are unconditionally passed after any
1377 /// user-defined but before post-link objects. Standard platform
1378 /// libraries that should be always be linked to, usually go here.
1379 pub late_link_args: LinkArgs,
1380 late_link_args_json: LinkArgsCli,
1381 /// Linker arguments used in addition to `late_link_args` if at least one
1382 /// Rust dependency is dynamically linked.
1383 pub late_link_args_dynamic: LinkArgs,
1384 late_link_args_dynamic_json: LinkArgsCli,
1385 /// Linker arguments used in addition to `late_link_args` if all Rust
1386 /// dependencies are statically linked.
1387 pub late_link_args_static: LinkArgs,
1388 late_link_args_static_json: LinkArgsCli,
1389 /// Linker arguments that are unconditionally passed *after* any
1390 /// user-defined libraries.
1391 pub post_link_args: LinkArgs,
1392 post_link_args_json: LinkArgsCli,
1394 /// Optional link script applied to `dylib` and `executable` crate types.
1395 /// This is a string containing the script, not a path. Can only be applied
1396 /// to linkers where linker flavor matches `LinkerFlavor::Gnu(..)`.
1397 pub link_script: Option<StaticCow<str>>,
1398 /// Environment variables to be set for the linker invocation.
1399 pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1400 /// Environment variables to be removed for the linker invocation.
1401 pub link_env_remove: StaticCow<[StaticCow<str>]>,
1403 /// Extra arguments to pass to the external assembler (when used)
1404 pub asm_args: StaticCow<[StaticCow<str>]>,
1406 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1408 pub cpu: StaticCow<str>,
1409 /// Default target features to pass to LLVM. These features will *always* be
1410 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1411 /// -mattr=$features`.
1412 pub features: StaticCow<str>,
1413 /// Whether dynamic linking is available on this target. Defaults to false.
1414 pub dynamic_linking: bool,
1415 /// If dynamic linking is available, whether only cdylibs are supported.
1416 pub only_cdylib: bool,
1417 /// Whether executables are available on this target. Defaults to true.
1418 pub executables: bool,
1419 /// Relocation model to use in object file. Corresponds to `llc
1420 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1421 pub relocation_model: RelocModel,
1422 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1423 /// Defaults to `None` which means "inherited from the base LLVM target".
1424 pub code_model: Option<CodeModel>,
1425 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1426 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1427 pub tls_model: TlsModel,
1428 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1429 pub disable_redzone: bool,
1430 /// Frame pointer mode for this target. Defaults to `MayOmit`.
1431 pub frame_pointer: FramePointer,
1432 /// Emit each function in its own section. Defaults to true.
1433 pub function_sections: bool,
1434 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1435 pub dll_prefix: StaticCow<str>,
1436 /// String to append to the name of every dynamic library. Defaults to ".so".
1437 pub dll_suffix: StaticCow<str>,
1438 /// String to append to the name of every executable.
1439 pub exe_suffix: StaticCow<str>,
1440 /// String to prepend to the name of every static library. Defaults to "lib".
1441 pub staticlib_prefix: StaticCow<str>,
1442 /// String to append to the name of every static library. Defaults to ".a".
1443 pub staticlib_suffix: StaticCow<str>,
1444 /// Values of the `target_family` cfg set for this target.
1446 /// Common options are: "unix", "windows". Defaults to no families.
1448 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1449 pub families: StaticCow<[StaticCow<str>]>,
1450 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1451 pub abi_return_struct_as_int: bool,
1452 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1453 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1454 /// Also indiates whether to use Apple-specific ABI changes, such as extending function
1455 /// parameters to 32-bits.
1456 pub is_like_osx: bool,
1457 /// Whether the target toolchain is like Solaris's.
1458 /// Only useful for compiling against Illumos/Solaris,
1459 /// as they have a different set of linker flags. Defaults to false.
1460 pub is_like_solaris: bool,
1461 /// Whether the target is like Windows.
1462 /// This is a combination of several more specific properties represented as a single flag:
1463 /// - The target uses a Windows ABI,
1464 /// - uses PE/COFF as a format for object code,
1465 /// - uses Windows-style dllexport/dllimport for shared libraries,
1466 /// - uses import libraries and .def files for symbol exports,
1467 /// - executables support setting a subsystem.
1468 pub is_like_windows: bool,
1469 /// Whether the target is like MSVC.
1470 /// This is a combination of several more specific properties represented as a single flag:
1471 /// - The target has all the properties from `is_like_windows`
1472 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1473 /// - has some MSVC-specific Windows ABI properties,
1474 /// - uses a link.exe-like linker,
1475 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1476 /// - uses SEH-based unwinding,
1477 /// - supports control flow guard mechanism.
1478 pub is_like_msvc: bool,
1479 /// Whether a target toolchain is like WASM.
1480 pub is_like_wasm: bool,
1481 /// Whether a target toolchain is like Android, implying a Linux kernel and a Bionic libc
1482 pub is_like_android: bool,
1483 /// Default supported version of DWARF on this platform.
1484 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1485 pub default_dwarf_version: u32,
1486 /// The MinGW toolchain has a known issue that prevents it from correctly
1487 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1488 /// symbol needs its own COMDAT section, weak linkage implies a large
1489 /// number sections that easily exceeds the given limit for larger
1490 /// codebases. Consequently we want a way to disallow weak linkage on some
1492 pub allows_weak_linkage: bool,
1493 /// Whether the linker support rpaths or not. Defaults to false.
1494 pub has_rpath: bool,
1495 /// Whether to disable linking to the default libraries, typically corresponds
1496 /// to `-nodefaultlibs`. Defaults to true.
1497 pub no_default_libraries: bool,
1498 /// Dynamically linked executables can be compiled as position independent
1499 /// if the default relocation model of position independent code is not
1500 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1501 /// the functions in the executable are not randomized and can be used
1502 /// during an exploit of a vulnerability in any code.
1503 pub position_independent_executables: bool,
1504 /// Executables that are both statically linked and position-independent are supported.
1505 pub static_position_independent_executables: bool,
1506 /// Determines if the target always requires using the PLT for indirect
1507 /// library calls or not. This controls the default value of the `-Z plt` flag.
1508 pub needs_plt: bool,
1509 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1510 /// resolve all symbols at startup and marks the GOT read-only before
1511 /// starting the program, preventing overwriting the GOT.
1512 pub relro_level: RelroLevel,
1513 /// Format that archives should be emitted in. This affects whether we use
1514 /// LLVM to assemble an archive or fall back to the system linker, and
1515 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1516 /// the system linker to be used.
1517 pub archive_format: StaticCow<str>,
1518 /// Is asm!() allowed? Defaults to true.
1519 pub allow_asm: bool,
1520 /// Whether the runtime startup code requires the `main` function be passed
1521 /// `argc` and `argv` values.
1522 pub main_needs_argc_argv: bool,
1524 /// Flag indicating whether #[thread_local] is available for this target.
1525 pub has_thread_local: bool,
1526 // This is mainly for easy compatibility with emscripten.
1527 // If we give emcc .o files that are actually .bc files it
1528 // will 'just work'.
1529 pub obj_is_bitcode: bool,
1530 /// Whether the target requires that emitted object code includes bitcode.
1531 pub forces_embed_bitcode: bool,
1532 /// Content of the LLVM cmdline section associated with embedded bitcode.
1533 pub bitcode_llvm_cmdline: StaticCow<str>,
1535 /// Don't use this field; instead use the `.min_atomic_width()` method.
1536 pub min_atomic_width: Option<u64>,
1538 /// Don't use this field; instead use the `.max_atomic_width()` method.
1539 pub max_atomic_width: Option<u64>,
1541 /// Whether the target supports atomic CAS operations natively
1542 pub atomic_cas: bool,
1544 /// Panic strategy: "unwind" or "abort"
1545 pub panic_strategy: PanicStrategy,
1547 /// Whether or not linking dylibs to a static CRT is allowed.
1548 pub crt_static_allows_dylibs: bool,
1549 /// Whether or not the CRT is statically linked by default.
1550 pub crt_static_default: bool,
1551 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1552 pub crt_static_respected: bool,
1554 /// The implementation of stack probes to use.
1555 pub stack_probes: StackProbeType,
1557 /// The minimum alignment for global symbols.
1558 pub min_global_align: Option<u64>,
1560 /// Default number of codegen units to use in debug mode
1561 pub default_codegen_units: Option<u64>,
1563 /// Whether to generate trap instructions in places where optimization would
1564 /// otherwise produce control flow that falls through into unrelated memory.
1565 pub trap_unreachable: bool,
1567 /// This target requires everything to be compiled with LTO to emit a final
1568 /// executable, aka there is no native linker for this target.
1569 pub requires_lto: bool,
1571 /// This target has no support for threads.
1572 pub singlethread: bool,
1574 /// Whether library functions call lowering/optimization is disabled in LLVM
1575 /// for this target unconditionally.
1576 pub no_builtins: bool,
1578 /// The default visibility for symbols in this target should be "hidden"
1579 /// rather than "default"
1580 pub default_hidden_visibility: bool,
1582 /// Whether a .debug_gdb_scripts section will be added to the output object file
1583 pub emit_debug_gdb_scripts: bool,
1585 /// Whether or not to unconditionally `uwtable` attributes on functions,
1586 /// typically because the platform needs to unwind for things like stack
1588 pub requires_uwtable: bool,
1590 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1591 /// is not specified and `uwtable` is not required on this target.
1592 pub default_uwtable: bool,
1594 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1595 /// typically required if a target can be compiled with a mixed set of
1596 /// target features. This is `true` by default, and `false` for targets like
1597 /// wasm32 where the whole program either has simd or not.
1598 pub simd_types_indirect: bool,
1600 /// Pass a list of symbol which should be exported in the dylib to the linker.
1601 pub limit_rdylib_exports: bool,
1603 /// If set, have the linker export exactly these symbols, instead of using
1604 /// the usual logic to figure this out from the crate itself.
1605 pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1607 /// Determines how or whether the MergeFunctions LLVM pass should run for
1608 /// this target. Either "disabled", "trampolines", or "aliases".
1609 /// The MergeFunctions pass is generally useful, but some targets may need
1610 /// to opt out. The default is "aliases".
1612 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1613 pub merge_functions: MergeFunctions,
1615 /// Use platform dependent mcount function
1616 pub mcount: StaticCow<str>,
1618 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1619 pub llvm_abiname: StaticCow<str>,
1621 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1622 pub relax_elf_relocations: bool,
1624 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1625 pub llvm_args: StaticCow<[StaticCow<str>]>,
1627 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1628 /// to false (uses .init_array).
1629 pub use_ctors_section: bool,
1631 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1632 /// used to locate unwinding information is passed
1633 /// (only has effect if the linker is `ld`-like).
1634 pub eh_frame_header: bool,
1636 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1637 /// thumb and arm interworking.
1638 pub has_thumb_interworking: bool,
1640 /// Which kind of debuginfo is used by this target?
1641 pub debuginfo_kind: DebuginfoKind,
1642 /// How to handle split debug information, if at all. Specifying `None` has
1643 /// target-specific meaning.
1644 pub split_debuginfo: SplitDebuginfo,
1645 /// Which kinds of split debuginfo are supported by the target?
1646 pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
1648 /// The sanitizers supported by this target
1650 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1651 /// enabled can generated on this target, but the necessary supporting libraries are not
1652 /// distributed with the target, the sanitizer should still appear in this list for the target.
1653 pub supported_sanitizers: SanitizerSet,
1655 /// If present it's a default value to use for adjusting the C ABI.
1656 pub default_adjusted_cabi: Option<Abi>,
1658 /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1659 pub c_enum_min_bits: u64,
1661 /// Whether or not the DWARF `.debug_aranges` section should be generated.
1662 pub generate_arange_section: bool,
1664 /// Whether the target supports stack canary checks. `true` by default,
1665 /// since this is most common among tier 1 and tier 2 targets.
1666 pub supports_stack_protector: bool,
1669 /// Add arguments for the given flavor and also for its "twin" flavors
1670 /// that have a compatible command line interface.
1671 fn add_link_args_iter(
1672 link_args: &mut LinkArgs,
1673 flavor: LinkerFlavor,
1674 args: impl Iterator<Item = StaticCow<str>> + Clone,
1676 let mut insert = |flavor| link_args.entry(flavor).or_default().extend(args.clone());
1679 LinkerFlavor::Gnu(cc, lld) => {
1680 assert_eq!(lld, Lld::No);
1681 insert(LinkerFlavor::Gnu(cc, Lld::Yes));
1683 LinkerFlavor::Darwin(cc, lld) => {
1684 assert_eq!(lld, Lld::No);
1685 insert(LinkerFlavor::Darwin(cc, Lld::Yes));
1687 LinkerFlavor::Msvc(lld) => {
1688 assert_eq!(lld, Lld::No);
1689 insert(LinkerFlavor::Msvc(Lld::Yes));
1691 LinkerFlavor::WasmLld(..)
1692 | LinkerFlavor::Unix(..)
1693 | LinkerFlavor::EmCc
1695 | LinkerFlavor::Ptx => {}
1699 fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
1700 add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
1703 impl TargetOptions {
1704 fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
1705 let mut link_args = LinkArgs::new();
1706 add_link_args(&mut link_args, flavor, args);
1710 fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1711 add_link_args(&mut self.pre_link_args, flavor, args);
1714 fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1715 add_link_args(&mut self.post_link_args, flavor, args);
1718 fn update_from_cli(&mut self) {
1719 self.linker_flavor = LinkerFlavor::from_cli_impl(
1720 self.linker_flavor_json,
1721 self.lld_flavor_json,
1722 self.linker_is_gnu_json,
1724 for (args, args_json) in [
1725 (&mut self.pre_link_args, &self.pre_link_args_json),
1726 (&mut self.late_link_args, &self.late_link_args_json),
1727 (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
1728 (&mut self.late_link_args_static, &self.late_link_args_static_json),
1729 (&mut self.post_link_args, &self.post_link_args_json),
1732 for (flavor, args_json) in args_json {
1733 // Cannot use `from_cli` due to borrow checker.
1734 let linker_flavor = LinkerFlavor::from_cli_impl(
1736 self.lld_flavor_json,
1737 self.linker_is_gnu_json,
1739 // Normalize to no lld to avoid asserts.
1740 let linker_flavor = match linker_flavor {
1741 LinkerFlavor::Gnu(cc, _) => LinkerFlavor::Gnu(cc, Lld::No),
1742 LinkerFlavor::Darwin(cc, _) => LinkerFlavor::Darwin(cc, Lld::No),
1743 LinkerFlavor::Msvc(_) => LinkerFlavor::Msvc(Lld::No),
1746 if !args.contains_key(&linker_flavor) {
1747 add_link_args_iter(args, linker_flavor, args_json.iter().cloned());
1753 fn update_to_cli(&mut self) {
1754 self.linker_flavor_json = self.linker_flavor.to_cli();
1755 self.lld_flavor_json = self.linker_flavor.lld_flavor();
1756 self.linker_is_gnu_json = self.linker_flavor.is_gnu();
1757 for (args, args_json) in [
1758 (&self.pre_link_args, &mut self.pre_link_args_json),
1759 (&self.late_link_args, &mut self.late_link_args_json),
1760 (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
1761 (&self.late_link_args_static, &mut self.late_link_args_static_json),
1762 (&self.post_link_args, &mut self.post_link_args_json),
1765 args.iter().map(|(flavor, args)| (flavor.to_cli(), args.clone())).collect();
1770 impl Default for TargetOptions {
1771 /// Creates a set of "sane defaults" for any target. This is still
1772 /// incomplete, and if used for compilation, will certainly not work.
1773 fn default() -> TargetOptions {
1776 endian: Endian::Little,
1777 c_int_width: "32".into(),
1781 vendor: "unknown".into(),
1782 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1783 linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
1784 linker_flavor_json: LinkerFlavorCli::Gcc,
1785 lld_flavor_json: LldFlavor::Ld,
1786 linker_is_gnu_json: true,
1789 cpu: "generic".into(),
1790 features: "".into(),
1791 dynamic_linking: false,
1794 relocation_model: RelocModel::Pic,
1796 tls_model: TlsModel::GeneralDynamic,
1797 disable_redzone: false,
1798 frame_pointer: FramePointer::MayOmit,
1799 function_sections: true,
1800 dll_prefix: "lib".into(),
1801 dll_suffix: ".so".into(),
1802 exe_suffix: "".into(),
1803 staticlib_prefix: "lib".into(),
1804 staticlib_suffix: ".a".into(),
1806 abi_return_struct_as_int: false,
1808 is_like_solaris: false,
1809 is_like_windows: false,
1810 is_like_msvc: false,
1811 is_like_wasm: false,
1812 is_like_android: false,
1813 default_dwarf_version: 4,
1814 allows_weak_linkage: true,
1816 no_default_libraries: true,
1817 position_independent_executables: false,
1818 static_position_independent_executables: false,
1820 relro_level: RelroLevel::None,
1821 pre_link_objects: Default::default(),
1822 post_link_objects: Default::default(),
1823 pre_link_objects_self_contained: Default::default(),
1824 post_link_objects_self_contained: Default::default(),
1825 link_self_contained: LinkSelfContainedDefault::False,
1826 pre_link_args: LinkArgs::new(),
1827 pre_link_args_json: LinkArgsCli::new(),
1828 late_link_args: LinkArgs::new(),
1829 late_link_args_json: LinkArgsCli::new(),
1830 late_link_args_dynamic: LinkArgs::new(),
1831 late_link_args_dynamic_json: LinkArgsCli::new(),
1832 late_link_args_static: LinkArgs::new(),
1833 late_link_args_static_json: LinkArgsCli::new(),
1834 post_link_args: LinkArgs::new(),
1835 post_link_args_json: LinkArgsCli::new(),
1837 link_env_remove: cvs![],
1838 archive_format: "gnu".into(),
1839 main_needs_argc_argv: true,
1841 has_thread_local: false,
1842 obj_is_bitcode: false,
1843 forces_embed_bitcode: false,
1844 bitcode_llvm_cmdline: "".into(),
1845 min_atomic_width: None,
1846 max_atomic_width: None,
1848 panic_strategy: PanicStrategy::Unwind,
1849 crt_static_allows_dylibs: false,
1850 crt_static_default: false,
1851 crt_static_respected: false,
1852 stack_probes: StackProbeType::None,
1853 min_global_align: None,
1854 default_codegen_units: None,
1855 trap_unreachable: true,
1856 requires_lto: false,
1857 singlethread: false,
1859 default_hidden_visibility: false,
1860 emit_debug_gdb_scripts: true,
1861 requires_uwtable: false,
1862 default_uwtable: false,
1863 simd_types_indirect: true,
1864 limit_rdylib_exports: true,
1865 override_export_symbols: None,
1866 merge_functions: MergeFunctions::Aliases,
1867 mcount: "mcount".into(),
1868 llvm_abiname: "".into(),
1869 relax_elf_relocations: false,
1871 use_ctors_section: false,
1872 eh_frame_header: true,
1873 has_thumb_interworking: false,
1874 debuginfo_kind: Default::default(),
1875 split_debuginfo: Default::default(),
1876 // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
1877 supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
1878 supported_sanitizers: SanitizerSet::empty(),
1879 default_adjusted_cabi: None,
1880 c_enum_min_bits: 32,
1881 generate_arange_section: true,
1882 supports_stack_protector: true,
1887 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1888 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1889 /// this `Deref` implementation is no longer necessary.
1890 impl Deref for Target {
1891 type Target = TargetOptions;
1894 fn deref(&self) -> &Self::Target {
1898 impl DerefMut for Target {
1900 fn deref_mut(&mut self) -> &mut Self::Target {
1906 /// Given a function ABI, turn it into the correct ABI for this target.
1907 pub fn adjust_abi(&self, abi: Abi) -> Abi {
1909 Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1910 Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1911 Abi::Stdcall { unwind }
1913 Abi::System { unwind } => Abi::C { unwind },
1914 Abi::EfiApi if self.arch == "arm" => Abi::Aapcs { unwind: false },
1915 Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1916 Abi::EfiApi => Abi::C { unwind: false },
1918 // See commentary in `is_abi_supported`.
1919 Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1920 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1921 Abi::Fastcall { .. } if self.arch == "x86" => abi,
1922 Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1923 Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1929 /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1930 pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1943 ["arm", "aarch64", "riscv32", "riscv64", "x86", "x86_64"].contains(&&self.arch[..])
1945 X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1946 Aapcs { .. } => "arm" == self.arch,
1947 CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1948 Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1949 PtxKernel => self.arch == "nvptx64",
1950 Msp430Interrupt => self.arch == "msp430",
1951 AmdGpuKernel => self.arch == "amdgcn",
1952 AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1953 Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1954 Thiscall { .. } => self.arch == "x86",
1955 // On windows these fall-back to platform native calling convention (C) when the
1956 // architecture is not supported.
1958 // This is I believe a historical accident that has occurred as part of Microsoft
1959 // striving to allow most of the code to "just" compile when support for 64-bit x86
1960 // was added and then later again, when support for ARM architectures was added.
1962 // This is well documented across MSDN. Support for this in Rust has been added in
1963 // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1964 // Rust, but there isn't much leeway remaining here to change it back at the time this
1965 // comment has been written.
1967 // Following are the relevant excerpts from the MSDN documentation.
1969 // > The __vectorcall calling convention is only supported in native code on x86 and
1970 // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1972 // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1974 // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1976 // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1978 // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1980 // > In most cases, keywords or compiler switches that specify an unsupported
1981 // > convention on a particular platform are ignored, and the platform default
1982 // > convention is used.
1984 // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1985 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1986 // Outside of Windows we want to only support these calling conventions for the
1987 // architectures for which these calling conventions are actually well defined.
1988 Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1989 Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1990 // Return a `None` for other cases so that we know to emit a future compat lint.
1991 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1995 /// Minimum integer size in bits that this target can perform atomic
1997 pub fn min_atomic_width(&self) -> u64 {
1998 self.min_atomic_width.unwrap_or(8)
2001 /// Maximum integer size in bits that this target can perform atomic
2003 pub fn max_atomic_width(&self) -> u64 {
2004 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
2007 /// Loads a target descriptor from a JSON object.
2008 pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
2009 // While ugly, this code must remain this way to retain
2010 // compatibility with existing JSON fields and the internal
2011 // expected naming of the Target and TargetOptions structs.
2012 // To ensure compatibility is retained, the built-in targets
2013 // are round-tripped through this code to catch cases where
2014 // the JSON parser is not updated to match the structs.
2016 let mut obj = match obj {
2017 Value::Object(obj) => obj,
2018 _ => return Err("Expected JSON object for target")?,
2021 let mut get_req_field = |name: &str| {
2023 .and_then(|j| j.as_str().map(str::to_string))
2024 .ok_or_else(|| format!("Field {} in target specification is required", name))
2027 let mut base = Target {
2028 llvm_target: get_req_field("llvm-target")?.into(),
2029 pointer_width: get_req_field("target-pointer-width")?
2031 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
2032 data_layout: get_req_field("data-layout")?.into(),
2033 arch: get_req_field("arch")?.into(),
2034 options: Default::default(),
2037 let mut incorrect_type = vec![];
2040 ($key_name:ident) => ( {
2041 let name = (stringify!($key_name)).replace("_", "-");
2042 if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
2046 ($key_name:ident = $json_name:expr) => ( {
2047 let name = $json_name;
2048 if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
2052 ($key_name:ident, bool) => ( {
2053 let name = (stringify!($key_name)).replace("_", "-");
2054 if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
2058 ($key_name:ident = $json_name:expr, bool) => ( {
2059 let name = $json_name;
2060 if let Some(s) = obj.remove(name).and_then(|b| b.as_bool()) {
2064 ($key_name:ident, u64) => ( {
2065 let name = (stringify!($key_name)).replace("_", "-");
2066 if let Some(s) = obj.remove(&name).and_then(|j| Json::as_u64(&j)) {
2070 ($key_name:ident, u32) => ( {
2071 let name = (stringify!($key_name)).replace("_", "-");
2072 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
2074 return Err("Not a valid DWARF version number".into());
2076 base.$key_name = s as u32;
2079 ($key_name:ident, Option<u64>) => ( {
2080 let name = (stringify!($key_name)).replace("_", "-");
2081 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
2082 base.$key_name = Some(s);
2085 ($key_name:ident, MergeFunctions) => ( {
2086 let name = (stringify!($key_name)).replace("_", "-");
2087 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2088 match s.parse::<MergeFunctions>() {
2089 Ok(mergefunc) => base.$key_name = mergefunc,
2090 _ => return Some(Err(format!("'{}' is not a valid value for \
2091 merge-functions. Use 'disabled', \
2092 'trampolines', or 'aliases'.",
2096 })).unwrap_or(Ok(()))
2098 ($key_name:ident, RelocModel) => ( {
2099 let name = (stringify!($key_name)).replace("_", "-");
2100 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2101 match s.parse::<RelocModel>() {
2102 Ok(relocation_model) => base.$key_name = relocation_model,
2103 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
2104 Run `rustc --print relocation-models` to \
2105 see the list of supported values.", s))),
2108 })).unwrap_or(Ok(()))
2110 ($key_name:ident, CodeModel) => ( {
2111 let name = (stringify!($key_name)).replace("_", "-");
2112 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2113 match s.parse::<CodeModel>() {
2114 Ok(code_model) => base.$key_name = Some(code_model),
2115 _ => return Some(Err(format!("'{}' is not a valid code model. \
2116 Run `rustc --print code-models` to \
2117 see the list of supported values.", s))),
2120 })).unwrap_or(Ok(()))
2122 ($key_name:ident, TlsModel) => ( {
2123 let name = (stringify!($key_name)).replace("_", "-");
2124 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2125 match s.parse::<TlsModel>() {
2126 Ok(tls_model) => base.$key_name = tls_model,
2127 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
2128 Run `rustc --print tls-models` to \
2129 see the list of supported values.", s))),
2132 })).unwrap_or(Ok(()))
2134 ($key_name:ident, PanicStrategy) => ( {
2135 let name = (stringify!($key_name)).replace("_", "-");
2136 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2138 "unwind" => base.$key_name = PanicStrategy::Unwind,
2139 "abort" => base.$key_name = PanicStrategy::Abort,
2140 _ => return Some(Err(format!("'{}' is not a valid value for \
2141 panic-strategy. Use 'unwind' or 'abort'.",
2145 })).unwrap_or(Ok(()))
2147 ($key_name:ident, RelroLevel) => ( {
2148 let name = (stringify!($key_name)).replace("_", "-");
2149 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2150 match s.parse::<RelroLevel>() {
2151 Ok(level) => base.$key_name = level,
2152 _ => return Some(Err(format!("'{}' is not a valid value for \
2153 relro-level. Use 'full', 'partial, or 'off'.",
2157 })).unwrap_or(Ok(()))
2159 ($key_name:ident, DebuginfoKind) => ( {
2160 let name = (stringify!($key_name)).replace("_", "-");
2161 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2162 match s.parse::<DebuginfoKind>() {
2163 Ok(level) => base.$key_name = level,
2164 _ => return Some(Err(
2165 format!("'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
2166 'dwarf-dsym' or 'pdb'.")
2170 })).unwrap_or(Ok(()))
2172 ($key_name:ident, SplitDebuginfo) => ( {
2173 let name = (stringify!($key_name)).replace("_", "-");
2174 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2175 match s.parse::<SplitDebuginfo>() {
2176 Ok(level) => base.$key_name = level,
2177 _ => return Some(Err(format!("'{}' is not a valid value for \
2178 split-debuginfo. Use 'off' or 'dsymutil'.",
2182 })).unwrap_or(Ok(()))
2184 ($key_name:ident, list) => ( {
2185 let name = (stringify!($key_name)).replace("_", "-");
2186 if let Some(j) = obj.remove(&name) {
2187 if let Some(v) = j.as_array() {
2188 base.$key_name = v.iter()
2189 .map(|a| a.as_str().unwrap().to_string().into())
2192 incorrect_type.push(name)
2196 ($key_name:ident, opt_list) => ( {
2197 let name = (stringify!($key_name)).replace("_", "-");
2198 if let Some(j) = obj.remove(&name) {
2199 if let Some(v) = j.as_array() {
2200 base.$key_name = Some(v.iter()
2201 .map(|a| a.as_str().unwrap().to_string().into())
2204 incorrect_type.push(name)
2208 ($key_name:ident, falliable_list) => ( {
2209 let name = (stringify!($key_name)).replace("_", "-");
2210 obj.remove(&name).and_then(|j| {
2211 if let Some(v) = j.as_array() {
2212 match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() {
2213 Ok(l) => { base.$key_name = l },
2214 // FIXME: `falliable_list` can't re-use the `key!` macro for list
2215 // elements and the error messages from that macro, so it has a bad
2216 // generic message instead
2217 Err(_) => return Some(Err(
2218 format!("`{:?}` is not a valid value for `{}`", j, name)
2222 incorrect_type.push(name)
2225 }).unwrap_or(Ok(()))
2227 ($key_name:ident, optional) => ( {
2228 let name = (stringify!($key_name)).replace("_", "-");
2229 if let Some(o) = obj.remove(&name) {
2232 .map(|s| s.to_string().into());
2235 ($key_name:ident = $json_name:expr, LldFlavor) => ( {
2236 let name = $json_name;
2237 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2238 if let Some(flavor) = LldFlavor::from_str(&s) {
2239 base.$key_name = flavor;
2241 return Some(Err(format!(
2242 "'{}' is not a valid value for lld-flavor. \
2243 Use 'darwin', 'gnu', 'link' or 'wasm.",
2247 })).unwrap_or(Ok(()))
2249 ($key_name:ident = $json_name:expr, LinkerFlavor) => ( {
2250 let name = $json_name;
2251 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2252 match LinkerFlavorCli::from_str(s) {
2253 Some(linker_flavor) => base.$key_name = linker_flavor,
2254 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
2255 Use {}", s, LinkerFlavorCli::one_of()))),
2258 })).unwrap_or(Ok(()))
2260 ($key_name:ident, StackProbeType) => ( {
2261 let name = (stringify!($key_name)).replace("_", "-");
2262 obj.remove(&name).and_then(|o| match StackProbeType::from_json(&o) {
2268 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
2270 }).unwrap_or(Ok(()))
2272 ($key_name:ident, SanitizerSet) => ( {
2273 let name = (stringify!($key_name)).replace("_", "-");
2274 if let Some(o) = obj.remove(&name) {
2275 if let Some(a) = o.as_array() {
2277 base.$key_name |= match s.as_str() {
2278 Some("address") => SanitizerSet::ADDRESS,
2279 Some("cfi") => SanitizerSet::CFI,
2280 Some("leak") => SanitizerSet::LEAK,
2281 Some("memory") => SanitizerSet::MEMORY,
2282 Some("memtag") => SanitizerSet::MEMTAG,
2283 Some("shadow-call-stack") => SanitizerSet::SHADOWCALLSTACK,
2284 Some("thread") => SanitizerSet::THREAD,
2285 Some("hwaddress") => SanitizerSet::HWADDRESS,
2286 Some(s) => return Err(format!("unknown sanitizer {}", s)),
2287 _ => return Err(format!("not a string: {:?}", s)),
2291 incorrect_type.push(name)
2294 Ok::<(), String>(())
2297 ($key_name:ident = $json_name:expr, link_self_contained) => ( {
2298 let name = $json_name;
2299 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2300 match s.parse::<LinkSelfContainedDefault>() {
2301 Ok(lsc_default) => base.$key_name = lsc_default,
2302 _ => return Some(Err(format!("'{}' is not a valid `-Clink-self-contained` default. \
2303 Use 'false', 'true', 'musl' or 'mingw'", s))),
2306 })).unwrap_or(Ok(()))
2308 ($key_name:ident = $json_name:expr, link_objects) => ( {
2309 let name = $json_name;
2310 if let Some(val) = obj.remove(name) {
2311 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2312 JSON object with fields per CRT object kind.", name))?;
2313 let mut args = CrtObjects::new();
2315 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
2316 format!("{}: '{}' is not a valid value for CRT object kind. \
2317 Use '(dynamic,static)-(nopic,pic)-exe' or \
2318 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
2321 let v = v.as_array().ok_or_else(||
2322 format!("{}.{}: expected a JSON array", name, k)
2323 )?.iter().enumerate()
2325 let s = s.as_str().ok_or_else(||
2326 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2327 Ok(s.to_string().into())
2329 .collect::<Result<Vec<_>, String>>()?;
2331 args.insert(kind, v);
2333 base.$key_name = args;
2336 ($key_name:ident = $json_name:expr, link_args) => ( {
2337 let name = $json_name;
2338 if let Some(val) = obj.remove(name) {
2339 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2340 JSON object with fields per linker-flavor.", name))?;
2341 let mut args = LinkArgsCli::new();
2343 let flavor = LinkerFlavorCli::from_str(&k).ok_or_else(|| {
2344 format!("{}: '{}' is not a valid value for linker-flavor. \
2345 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
2348 let v = v.as_array().ok_or_else(||
2349 format!("{}.{}: expected a JSON array", name, k)
2350 )?.iter().enumerate()
2352 let s = s.as_str().ok_or_else(||
2353 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2354 Ok(s.to_string().into())
2356 .collect::<Result<Vec<_>, String>>()?;
2358 args.insert(flavor, v);
2360 base.$key_name = args;
2363 ($key_name:ident, env) => ( {
2364 let name = (stringify!($key_name)).replace("_", "-");
2365 if let Some(o) = obj.remove(&name) {
2366 if let Some(a) = o.as_array() {
2368 if let Some(s) = o.as_str() {
2369 let p = s.split('=').collect::<Vec<_>>();
2371 let k = p[0].to_string();
2372 let v = p[1].to_string();
2373 base.$key_name.to_mut().push((k.into(), v.into()));
2378 incorrect_type.push(name)
2382 ($key_name:ident, Option<Abi>) => ( {
2383 let name = (stringify!($key_name)).replace("_", "-");
2384 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2385 match lookup_abi(s) {
2386 Some(abi) => base.$key_name = Some(abi),
2387 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2390 })).unwrap_or(Ok(()))
2392 ($key_name:ident, TargetFamilies) => ( {
2393 if let Some(value) = obj.remove("target-family") {
2394 if let Some(v) = value.as_array() {
2395 base.$key_name = v.iter()
2396 .map(|a| a.as_str().unwrap().to_string().into())
2398 } else if let Some(v) = value.as_str() {
2399 base.$key_name = vec![v.to_string().into()].into();
2405 if let Some(j) = obj.remove("target-endian") {
2406 if let Some(s) = j.as_str() {
2407 base.endian = s.parse()?;
2409 incorrect_type.push("target-endian".into())
2413 if let Some(fp) = obj.remove("frame-pointer") {
2414 if let Some(s) = fp.as_str() {
2415 base.frame_pointer = s
2417 .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2419 incorrect_type.push("frame-pointer".into())
2423 key!(is_builtin, bool);
2424 key!(c_int_width = "target-c-int-width");
2429 key!(linker, optional);
2430 key!(linker_flavor_json = "linker-flavor", LinkerFlavor)?;
2431 key!(lld_flavor_json = "lld-flavor", LldFlavor)?;
2432 key!(linker_is_gnu_json = "linker-is-gnu", bool);
2433 key!(pre_link_objects = "pre-link-objects", link_objects);
2434 key!(post_link_objects = "post-link-objects", link_objects);
2435 key!(pre_link_objects_self_contained = "pre-link-objects-fallback", link_objects);
2436 key!(post_link_objects_self_contained = "post-link-objects-fallback", link_objects);
2437 key!(link_self_contained = "crt-objects-fallback", link_self_contained)?;
2438 key!(pre_link_args_json = "pre-link-args", link_args);
2439 key!(late_link_args_json = "late-link-args", link_args);
2440 key!(late_link_args_dynamic_json = "late-link-args-dynamic", link_args);
2441 key!(late_link_args_static_json = "late-link-args-static", link_args);
2442 key!(post_link_args_json = "post-link-args", link_args);
2443 key!(link_script, optional);
2444 key!(link_env, env);
2445 key!(link_env_remove, list);
2446 key!(asm_args, list);
2449 key!(dynamic_linking, bool);
2450 key!(only_cdylib, bool);
2451 key!(executables, bool);
2452 key!(relocation_model, RelocModel)?;
2453 key!(code_model, CodeModel)?;
2454 key!(tls_model, TlsModel)?;
2455 key!(disable_redzone, bool);
2456 key!(function_sections, bool);
2460 key!(staticlib_prefix);
2461 key!(staticlib_suffix);
2462 key!(families, TargetFamilies);
2463 key!(abi_return_struct_as_int, bool);
2464 key!(is_like_osx, bool);
2465 key!(is_like_solaris, bool);
2466 key!(is_like_windows, bool);
2467 key!(is_like_msvc, bool);
2468 key!(is_like_wasm, bool);
2469 key!(is_like_android, bool);
2470 key!(default_dwarf_version, u32);
2471 key!(allows_weak_linkage, bool);
2472 key!(has_rpath, bool);
2473 key!(no_default_libraries, bool);
2474 key!(position_independent_executables, bool);
2475 key!(static_position_independent_executables, bool);
2476 key!(needs_plt, bool);
2477 key!(relro_level, RelroLevel)?;
2478 key!(archive_format);
2479 key!(allow_asm, bool);
2480 key!(main_needs_argc_argv, bool);
2481 key!(has_thread_local, bool);
2482 key!(obj_is_bitcode, bool);
2483 key!(forces_embed_bitcode, bool);
2484 key!(bitcode_llvm_cmdline);
2485 key!(max_atomic_width, Option<u64>);
2486 key!(min_atomic_width, Option<u64>);
2487 key!(atomic_cas, bool);
2488 key!(panic_strategy, PanicStrategy)?;
2489 key!(crt_static_allows_dylibs, bool);
2490 key!(crt_static_default, bool);
2491 key!(crt_static_respected, bool);
2492 key!(stack_probes, StackProbeType)?;
2493 key!(min_global_align, Option<u64>);
2494 key!(default_codegen_units, Option<u64>);
2495 key!(trap_unreachable, bool);
2496 key!(requires_lto, bool);
2497 key!(singlethread, bool);
2498 key!(no_builtins, bool);
2499 key!(default_hidden_visibility, bool);
2500 key!(emit_debug_gdb_scripts, bool);
2501 key!(requires_uwtable, bool);
2502 key!(default_uwtable, bool);
2503 key!(simd_types_indirect, bool);
2504 key!(limit_rdylib_exports, bool);
2505 key!(override_export_symbols, opt_list);
2506 key!(merge_functions, MergeFunctions)?;
2507 key!(mcount = "target-mcount");
2509 key!(relax_elf_relocations, bool);
2510 key!(llvm_args, list);
2511 key!(use_ctors_section, bool);
2512 key!(eh_frame_header, bool);
2513 key!(has_thumb_interworking, bool);
2514 key!(debuginfo_kind, DebuginfoKind)?;
2515 key!(split_debuginfo, SplitDebuginfo)?;
2516 key!(supported_split_debuginfo, falliable_list)?;
2517 key!(supported_sanitizers, SanitizerSet)?;
2518 key!(default_adjusted_cabi, Option<Abi>)?;
2519 key!(c_enum_min_bits, u64);
2520 key!(generate_arange_section, bool);
2521 key!(supports_stack_protector, bool);
2523 if base.is_builtin {
2524 // This can cause unfortunate ICEs later down the line.
2525 return Err("may not set is_builtin for targets not built-in".into());
2527 base.update_from_cli();
2529 // Each field should have been read using `Json::remove` so any keys remaining are unused.
2530 let remaining_keys = obj.keys();
2533 TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2537 /// Load a built-in target
2538 pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2539 match *target_triple {
2540 TargetTriple::TargetTriple(ref target_triple) => {
2541 load_builtin(target_triple).expect("built-in target")
2543 TargetTriple::TargetJson { .. } => {
2544 panic!("built-in targets doesn't support target-paths")
2549 /// Search for a JSON file specifying the given target triple.
2551 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2552 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
2553 /// bare filename already, so also check for that. If one of the hardcoded targets we know
2554 /// about, just return it directly.
2556 /// The error string could come from any of the APIs called, including filesystem access and
2559 target_triple: &TargetTriple,
2561 ) -> Result<(Target, TargetWarnings), String> {
2565 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2566 let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2567 let obj = serde_json::from_str(&contents).map_err(|e| e.to_string())?;
2568 Target::from_json(obj)
2571 match *target_triple {
2572 TargetTriple::TargetTriple(ref target_triple) => {
2573 // check if triple is in list of built-in targets
2574 if let Some(t) = load_builtin(target_triple) {
2575 return Ok((t, TargetWarnings::empty()));
2578 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2580 let mut target = target_triple.to_string();
2581 target.push_str(".json");
2582 PathBuf::from(target)
2585 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2587 for dir in env::split_paths(&target_path) {
2588 let p = dir.join(&path);
2590 return load_file(&p);
2594 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2596 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2597 let p = PathBuf::from_iter([
2599 Path::new(&rustlib_path),
2600 Path::new("target.json"),
2603 return load_file(&p);
2606 Err(format!("Could not find specification for target {:?}", target_triple))
2608 TargetTriple::TargetJson { ref contents, .. } => {
2609 let obj = serde_json::from_str(contents).map_err(|e| e.to_string())?;
2610 Target::from_json(obj)
2616 impl ToJson for Target {
2617 fn to_json(&self) -> Json {
2618 let mut d = serde_json::Map::new();
2619 let default: TargetOptions = Default::default();
2620 let mut target = self.clone();
2621 target.update_to_cli();
2623 macro_rules! target_val {
2625 let name = (stringify!($attr)).replace("_", "-");
2626 d.insert(name, target.$attr.to_json());
2630 macro_rules! target_option_val {
2632 let name = (stringify!($attr)).replace("_", "-");
2633 if default.$attr != target.$attr {
2634 d.insert(name, target.$attr.to_json());
2637 ($attr:ident, $json_name:expr) => {{
2638 let name = $json_name;
2639 if default.$attr != target.$attr {
2640 d.insert(name.into(), target.$attr.to_json());
2643 (link_args - $attr:ident, $json_name:expr) => {{
2644 let name = $json_name;
2645 if default.$attr != target.$attr {
2649 .map(|(k, v)| (k.desc().to_string(), v.clone()))
2650 .collect::<BTreeMap<_, _>>();
2651 d.insert(name.to_string(), obj.to_json());
2654 (env - $attr:ident) => {{
2655 let name = (stringify!($attr)).replace("_", "-");
2656 if default.$attr != target.$attr {
2660 .map(|&(ref k, ref v)| format!("{k}={v}"))
2661 .collect::<Vec<_>>();
2662 d.insert(name, obj.to_json());
2667 target_val!(llvm_target);
2668 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2670 target_val!(data_layout);
2672 target_option_val!(is_builtin);
2673 target_option_val!(endian, "target-endian");
2674 target_option_val!(c_int_width, "target-c-int-width");
2675 target_option_val!(os);
2676 target_option_val!(env);
2677 target_option_val!(abi);
2678 target_option_val!(vendor);
2679 target_option_val!(linker);
2680 target_option_val!(linker_flavor_json, "linker-flavor");
2681 target_option_val!(lld_flavor_json, "lld-flavor");
2682 target_option_val!(linker_is_gnu_json, "linker-is-gnu");
2683 target_option_val!(pre_link_objects);
2684 target_option_val!(post_link_objects);
2685 target_option_val!(pre_link_objects_self_contained, "pre-link-objects-fallback");
2686 target_option_val!(post_link_objects_self_contained, "post-link-objects-fallback");
2687 target_option_val!(link_self_contained, "crt-objects-fallback");
2688 target_option_val!(link_args - pre_link_args_json, "pre-link-args");
2689 target_option_val!(link_args - late_link_args_json, "late-link-args");
2690 target_option_val!(link_args - late_link_args_dynamic_json, "late-link-args-dynamic");
2691 target_option_val!(link_args - late_link_args_static_json, "late-link-args-static");
2692 target_option_val!(link_args - post_link_args_json, "post-link-args");
2693 target_option_val!(link_script);
2694 target_option_val!(env - link_env);
2695 target_option_val!(link_env_remove);
2696 target_option_val!(asm_args);
2697 target_option_val!(cpu);
2698 target_option_val!(features);
2699 target_option_val!(dynamic_linking);
2700 target_option_val!(only_cdylib);
2701 target_option_val!(executables);
2702 target_option_val!(relocation_model);
2703 target_option_val!(code_model);
2704 target_option_val!(tls_model);
2705 target_option_val!(disable_redzone);
2706 target_option_val!(frame_pointer);
2707 target_option_val!(function_sections);
2708 target_option_val!(dll_prefix);
2709 target_option_val!(dll_suffix);
2710 target_option_val!(exe_suffix);
2711 target_option_val!(staticlib_prefix);
2712 target_option_val!(staticlib_suffix);
2713 target_option_val!(families, "target-family");
2714 target_option_val!(abi_return_struct_as_int);
2715 target_option_val!(is_like_osx);
2716 target_option_val!(is_like_solaris);
2717 target_option_val!(is_like_windows);
2718 target_option_val!(is_like_msvc);
2719 target_option_val!(is_like_wasm);
2720 target_option_val!(is_like_android);
2721 target_option_val!(default_dwarf_version);
2722 target_option_val!(allows_weak_linkage);
2723 target_option_val!(has_rpath);
2724 target_option_val!(no_default_libraries);
2725 target_option_val!(position_independent_executables);
2726 target_option_val!(static_position_independent_executables);
2727 target_option_val!(needs_plt);
2728 target_option_val!(relro_level);
2729 target_option_val!(archive_format);
2730 target_option_val!(allow_asm);
2731 target_option_val!(main_needs_argc_argv);
2732 target_option_val!(has_thread_local);
2733 target_option_val!(obj_is_bitcode);
2734 target_option_val!(forces_embed_bitcode);
2735 target_option_val!(bitcode_llvm_cmdline);
2736 target_option_val!(min_atomic_width);
2737 target_option_val!(max_atomic_width);
2738 target_option_val!(atomic_cas);
2739 target_option_val!(panic_strategy);
2740 target_option_val!(crt_static_allows_dylibs);
2741 target_option_val!(crt_static_default);
2742 target_option_val!(crt_static_respected);
2743 target_option_val!(stack_probes);
2744 target_option_val!(min_global_align);
2745 target_option_val!(default_codegen_units);
2746 target_option_val!(trap_unreachable);
2747 target_option_val!(requires_lto);
2748 target_option_val!(singlethread);
2749 target_option_val!(no_builtins);
2750 target_option_val!(default_hidden_visibility);
2751 target_option_val!(emit_debug_gdb_scripts);
2752 target_option_val!(requires_uwtable);
2753 target_option_val!(default_uwtable);
2754 target_option_val!(simd_types_indirect);
2755 target_option_val!(limit_rdylib_exports);
2756 target_option_val!(override_export_symbols);
2757 target_option_val!(merge_functions);
2758 target_option_val!(mcount, "target-mcount");
2759 target_option_val!(llvm_abiname);
2760 target_option_val!(relax_elf_relocations);
2761 target_option_val!(llvm_args);
2762 target_option_val!(use_ctors_section);
2763 target_option_val!(eh_frame_header);
2764 target_option_val!(has_thumb_interworking);
2765 target_option_val!(debuginfo_kind);
2766 target_option_val!(split_debuginfo);
2767 target_option_val!(supported_split_debuginfo);
2768 target_option_val!(supported_sanitizers);
2769 target_option_val!(c_enum_min_bits);
2770 target_option_val!(generate_arange_section);
2771 target_option_val!(supports_stack_protector);
2773 if let Some(abi) = self.default_adjusted_cabi {
2774 d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2781 /// Either a target triple string or a path to a JSON file.
2782 #[derive(Clone, Debug)]
2783 pub enum TargetTriple {
2784 TargetTriple(String),
2786 /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
2787 /// inconsistencies as it is discarded during serialization.
2788 path_for_rustdoc: PathBuf,
2794 // Use a manual implementation to ignore the path field
2795 impl PartialEq for TargetTriple {
2796 fn eq(&self, other: &Self) -> bool {
2797 match (self, other) {
2798 (Self::TargetTriple(l0), Self::TargetTriple(r0)) => l0 == r0,
2800 Self::TargetJson { path_for_rustdoc: _, triple: l_triple, contents: l_contents },
2801 Self::TargetJson { path_for_rustdoc: _, triple: r_triple, contents: r_contents },
2802 ) => l_triple == r_triple && l_contents == r_contents,
2808 // Use a manual implementation to ignore the path field
2809 impl Hash for TargetTriple {
2810 fn hash<H: Hasher>(&self, state: &mut H) -> () {
2812 TargetTriple::TargetTriple(triple) => {
2816 TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => {
2819 contents.hash(state)
2825 // Use a manual implementation to prevent encoding the target json file path in the crate metadata
2826 impl<S: Encoder> Encodable<S> for TargetTriple {
2827 fn encode(&self, s: &mut S) {
2829 TargetTriple::TargetTriple(triple) => s.emit_enum_variant(0, |s| s.emit_str(triple)),
2830 TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => s
2831 .emit_enum_variant(1, |s| {
2833 s.emit_str(contents)
2839 impl<D: Decoder> Decodable<D> for TargetTriple {
2840 fn decode(d: &mut D) -> Self {
2841 match d.read_usize() {
2842 0 => TargetTriple::TargetTriple(d.read_str().to_owned()),
2843 1 => TargetTriple::TargetJson {
2844 path_for_rustdoc: PathBuf::new(),
2845 triple: d.read_str().to_owned(),
2846 contents: d.read_str().to_owned(),
2849 panic!("invalid enum variant tag while decoding `TargetTriple`, expected 0..2");
2856 /// Creates a target triple from the passed target triple string.
2857 pub fn from_triple(triple: &str) -> Self {
2858 TargetTriple::TargetTriple(triple.into())
2861 /// Creates a target triple from the passed target path.
2862 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2863 let canonicalized_path = path.canonicalize()?;
2864 let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
2866 io::ErrorKind::InvalidInput,
2867 format!("target path {:?} is not a valid file: {}", canonicalized_path, err),
2870 let triple = canonicalized_path
2872 .expect("target path must not be empty")
2874 .expect("target path must be valid unicode")
2876 Ok(TargetTriple::TargetJson { path_for_rustdoc: canonicalized_path, triple, contents })
2879 /// Returns a string triple for this target.
2881 /// If this target is a path, the file name (without extension) is returned.
2882 pub fn triple(&self) -> &str {
2884 TargetTriple::TargetTriple(ref triple)
2885 | TargetTriple::TargetJson { ref triple, .. } => triple,
2889 /// Returns an extended string triple for this target.
2891 /// If this target is a path, a hash of the path is appended to the triple returned
2893 pub fn debug_triple(&self) -> String {
2894 use std::collections::hash_map::DefaultHasher;
2897 TargetTriple::TargetTriple(triple) => triple.to_owned(),
2898 TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents: content } => {
2899 let mut hasher = DefaultHasher::new();
2900 content.hash(&mut hasher);
2901 let hash = hasher.finish();
2902 format!("{}-{}", triple, hash)
2908 impl fmt::Display for TargetTriple {
2909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2910 write!(f, "{}", self.debug_triple())