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::call::Conv;
39 AbiAndPrefAlign, AddressSpace, Align, Endian, Integer, Size, TargetDataLayout,
40 TargetDataLayoutErrors,
42 use crate::json::{Json, ToJson};
43 use crate::spec::abi::{lookup as lookup_abi, Abi};
44 use crate::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
45 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
46 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
47 use rustc_span::symbol::{sym, Symbol};
48 use serde_json::Value;
50 use std::collections::BTreeMap;
51 use std::convert::TryFrom;
52 use std::hash::{Hash, Hasher};
53 use std::iter::FromIterator;
54 use std::ops::{Deref, DerefMut};
55 use std::path::{Path, PathBuf};
56 use std::str::FromStr;
59 use rustc_macros::HashStable_Generic;
79 mod linux_uclibc_base;
92 mod windows_gnullvm_base;
93 mod windows_msvc_base;
94 mod windows_uwp_gnu_base;
95 mod windows_uwp_msvc_base;
97 /// Linker is called through a C/C++ compiler.
98 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
105 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
111 /// All linkers have some kinds of command line interfaces and rustc needs to know which commands
112 /// to use with each of them. So we cluster all such interfaces into a (somewhat arbitrary) number
113 /// of classes that we call "linker flavors".
115 /// Technically, it's not even necessary, we can nearly always infer the flavor from linker name
116 /// and target properties like `is_like_windows`/`is_like_osx`/etc. However, the PRs originally
117 /// introducing `-Clinker-flavor` (#40018 and friends) were aiming to reduce this kind of inference
118 /// and provide something certain and explicitly specified instead, and that design goal is still
121 /// The second goal is to keep the number of flavors to the minimum if possible.
122 /// LLD somewhat forces our hand here because that linker is self-sufficient only if its executable
123 /// (`argv[0]`) is named in specific way, otherwise it doesn't work and requires a
124 /// `-flavor LLD_FLAVOR` argument to choose which logic to use. Our shipped `rust-lld` in
125 /// particular is not named in such specific way, so it needs the flavor option, so we make our
126 /// linker flavors sufficiently fine-grained to satisfy LLD without inferring its flavor from other
127 /// target properties, in accordance with the first design goal.
129 /// The first component of the flavor is tightly coupled with the compilation target,
130 /// while the `Cc` and `Lld` flags can vary withing the same target.
131 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
132 pub enum LinkerFlavor {
133 /// Unix-like linker with GNU extensions (both naked and compiler-wrapped forms).
134 /// Besides similar "default" Linux/BSD linkers this also includes Windows/GNU linker,
135 /// which is somewhat different because it doesn't produce ELFs.
137 /// Unix-like linker for Apple targets (both naked and compiler-wrapped forms).
138 /// Extracted from the "umbrella" `Unix` flavor due to its corresponding LLD flavor.
140 /// Unix-like linker for Wasm targets (both naked and compiler-wrapped forms).
141 /// Extracted from the "umbrella" `Unix` flavor due to its corresponding LLD flavor.
142 /// Non-LLD version does not exist, so the lld flag is currently hardcoded here.
144 /// Basic Unix-like linker for "any other Unix" targets (Solaris/illumos, L4Re, MSP430, etc),
145 /// possibly with non-GNU extensions (both naked and compiler-wrapped forms).
146 /// LLD doesn't support any of these.
148 /// MSVC-style linker for Windows and UEFI, LLD supports it.
150 /// Emscripten Compiler Frontend, a wrapper around `WasmLld(Cc::Yes)` that has a different
151 /// interface and produces some additional JavaScript output.
153 // Below: other linker-like tools with unique interfaces for exotic targets.
154 /// Linker tool for BPF.
156 /// Linker tool for Nvidia PTX.
160 /// Linker flavors available externally through command line (`-Clinker-flavor`)
161 /// or json target specifications.
162 /// FIXME: This set has accumulated historically, bring it more in line with the internal
163 /// linker flavors (`LinkerFlavor`).
164 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
165 pub enum LinkerFlavorCli {
175 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
184 pub fn as_str(&self) -> &'static str {
186 LldFlavor::Wasm => "wasm",
187 LldFlavor::Ld64 => "darwin",
188 LldFlavor::Ld => "gnu",
189 LldFlavor::Link => "link",
193 fn from_str(s: &str) -> Option<Self> {
195 "darwin" => LldFlavor::Ld64,
196 "gnu" => LldFlavor::Ld,
197 "link" => LldFlavor::Link,
198 "wasm" => LldFlavor::Wasm,
204 impl ToJson for LldFlavor {
205 fn to_json(&self) -> Json {
206 self.as_str().to_json()
211 pub fn from_cli(cli: LinkerFlavorCli, target: &TargetOptions) -> LinkerFlavor {
212 Self::from_cli_impl(cli, target.linker_flavor.lld_flavor(), target.linker_flavor.is_gnu())
215 /// The passed CLI flavor is preferred over other args coming from the default target spec,
216 /// so this function can produce a flavor that is incompatible with the current target.
217 /// FIXME: Produce errors when `-Clinker-flavor` is set to something incompatible
218 /// with the current target.
219 fn from_cli_impl(cli: LinkerFlavorCli, lld_flavor: LldFlavor, is_gnu: bool) -> LinkerFlavor {
221 LinkerFlavorCli::Gcc => match lld_flavor {
222 LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::Yes, Lld::No),
223 LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::Yes, Lld::No),
224 LldFlavor::Wasm => LinkerFlavor::WasmLld(Cc::Yes),
225 LldFlavor::Ld | LldFlavor::Link => LinkerFlavor::Unix(Cc::Yes),
227 LinkerFlavorCli::Ld => match lld_flavor {
228 LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::No, Lld::No),
229 LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::No, Lld::No),
230 LldFlavor::Ld | LldFlavor::Wasm | LldFlavor::Link => LinkerFlavor::Unix(Cc::No),
232 LinkerFlavorCli::Lld(LldFlavor::Ld) => LinkerFlavor::Gnu(Cc::No, Lld::Yes),
233 LinkerFlavorCli::Lld(LldFlavor::Ld64) => LinkerFlavor::Darwin(Cc::No, Lld::Yes),
234 LinkerFlavorCli::Lld(LldFlavor::Wasm) => LinkerFlavor::WasmLld(Cc::No),
235 LinkerFlavorCli::Lld(LldFlavor::Link) => LinkerFlavor::Msvc(Lld::Yes),
236 LinkerFlavorCli::Msvc => LinkerFlavor::Msvc(Lld::No),
237 LinkerFlavorCli::Em => LinkerFlavor::EmCc,
238 LinkerFlavorCli::BpfLinker => LinkerFlavor::Bpf,
239 LinkerFlavorCli::PtxLinker => LinkerFlavor::Ptx,
243 fn to_cli(self) -> LinkerFlavorCli {
245 LinkerFlavor::Gnu(Cc::Yes, _)
246 | LinkerFlavor::Darwin(Cc::Yes, _)
247 | LinkerFlavor::WasmLld(Cc::Yes)
248 | LinkerFlavor::Unix(Cc::Yes) => LinkerFlavorCli::Gcc,
249 LinkerFlavor::Gnu(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld),
250 LinkerFlavor::Darwin(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld64),
251 LinkerFlavor::WasmLld(..) => LinkerFlavorCli::Lld(LldFlavor::Wasm),
252 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
255 LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Link),
256 LinkerFlavor::Msvc(..) => LinkerFlavorCli::Msvc,
257 LinkerFlavor::EmCc => LinkerFlavorCli::Em,
258 LinkerFlavor::Bpf => LinkerFlavorCli::BpfLinker,
259 LinkerFlavor::Ptx => LinkerFlavorCli::PtxLinker,
263 pub fn lld_flavor(self) -> LldFlavor {
265 LinkerFlavor::Gnu(..)
266 | LinkerFlavor::Unix(..)
269 | LinkerFlavor::Ptx => LldFlavor::Ld,
270 LinkerFlavor::Darwin(..) => LldFlavor::Ld64,
271 LinkerFlavor::WasmLld(..) => LldFlavor::Wasm,
272 LinkerFlavor::Msvc(..) => LldFlavor::Link,
276 pub fn is_gnu(self) -> bool {
277 matches!(self, LinkerFlavor::Gnu(..))
281 macro_rules! linker_flavor_cli_impls {
282 ($(($($flavor:tt)*) $string:literal)*) => (
283 impl LinkerFlavorCli {
284 pub const fn one_of() -> &'static str {
285 concat!("one of: ", $($string, " ",)*)
288 pub fn from_str(s: &str) -> Option<LinkerFlavorCli> {
290 $($string => $($flavor)*,)*
295 pub fn desc(&self) -> &str {
297 $($($flavor)* => $string,)*
304 linker_flavor_cli_impls! {
305 (LinkerFlavorCli::Gcc) "gcc"
306 (LinkerFlavorCli::Ld) "ld"
307 (LinkerFlavorCli::Lld(LldFlavor::Ld)) "ld.lld"
308 (LinkerFlavorCli::Lld(LldFlavor::Ld64)) "ld64.lld"
309 (LinkerFlavorCli::Lld(LldFlavor::Link)) "lld-link"
310 (LinkerFlavorCli::Lld(LldFlavor::Wasm)) "wasm-ld"
311 (LinkerFlavorCli::Msvc) "msvc"
312 (LinkerFlavorCli::Em) "em"
313 (LinkerFlavorCli::BpfLinker) "bpf-linker"
314 (LinkerFlavorCli::PtxLinker) "ptx-linker"
317 impl ToJson for LinkerFlavorCli {
318 fn to_json(&self) -> Json {
319 self.desc().to_json()
323 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
324 pub enum PanicStrategy {
330 pub fn desc(&self) -> &str {
332 PanicStrategy::Unwind => "unwind",
333 PanicStrategy::Abort => "abort",
337 pub const fn desc_symbol(&self) -> Symbol {
339 PanicStrategy::Unwind => sym::unwind,
340 PanicStrategy::Abort => sym::abort,
344 pub const fn all() -> [Symbol; 2] {
345 [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
349 impl ToJson for PanicStrategy {
350 fn to_json(&self) -> Json {
352 PanicStrategy::Abort => "abort".to_json(),
353 PanicStrategy::Unwind => "unwind".to_json(),
358 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
359 pub enum RelroLevel {
367 pub fn desc(&self) -> &str {
369 RelroLevel::Full => "full",
370 RelroLevel::Partial => "partial",
371 RelroLevel::Off => "off",
372 RelroLevel::None => "none",
377 impl FromStr for RelroLevel {
380 fn from_str(s: &str) -> Result<RelroLevel, ()> {
382 "full" => Ok(RelroLevel::Full),
383 "partial" => Ok(RelroLevel::Partial),
384 "off" => Ok(RelroLevel::Off),
385 "none" => Ok(RelroLevel::None),
391 impl ToJson for RelroLevel {
392 fn to_json(&self) -> Json {
394 RelroLevel::Full => "full".to_json(),
395 RelroLevel::Partial => "partial".to_json(),
396 RelroLevel::Off => "off".to_json(),
397 RelroLevel::None => "None".to_json(),
402 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
403 pub enum MergeFunctions {
409 impl MergeFunctions {
410 pub fn desc(&self) -> &str {
412 MergeFunctions::Disabled => "disabled",
413 MergeFunctions::Trampolines => "trampolines",
414 MergeFunctions::Aliases => "aliases",
419 impl FromStr for MergeFunctions {
422 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
424 "disabled" => Ok(MergeFunctions::Disabled),
425 "trampolines" => Ok(MergeFunctions::Trampolines),
426 "aliases" => Ok(MergeFunctions::Aliases),
432 impl ToJson for MergeFunctions {
433 fn to_json(&self) -> Json {
435 MergeFunctions::Disabled => "disabled".to_json(),
436 MergeFunctions::Trampolines => "trampolines".to_json(),
437 MergeFunctions::Aliases => "aliases".to_json(),
442 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
443 pub enum RelocModel {
453 impl FromStr for RelocModel {
456 fn from_str(s: &str) -> Result<RelocModel, ()> {
458 "static" => RelocModel::Static,
459 "pic" => RelocModel::Pic,
460 "pie" => RelocModel::Pie,
461 "dynamic-no-pic" => RelocModel::DynamicNoPic,
462 "ropi" => RelocModel::Ropi,
463 "rwpi" => RelocModel::Rwpi,
464 "ropi-rwpi" => RelocModel::RopiRwpi,
470 impl ToJson for RelocModel {
471 fn to_json(&self) -> Json {
473 RelocModel::Static => "static",
474 RelocModel::Pic => "pic",
475 RelocModel::Pie => "pie",
476 RelocModel::DynamicNoPic => "dynamic-no-pic",
477 RelocModel::Ropi => "ropi",
478 RelocModel::Rwpi => "rwpi",
479 RelocModel::RopiRwpi => "ropi-rwpi",
485 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
494 impl FromStr for CodeModel {
497 fn from_str(s: &str) -> Result<CodeModel, ()> {
499 "tiny" => CodeModel::Tiny,
500 "small" => CodeModel::Small,
501 "kernel" => CodeModel::Kernel,
502 "medium" => CodeModel::Medium,
503 "large" => CodeModel::Large,
509 impl ToJson for CodeModel {
510 fn to_json(&self) -> Json {
512 CodeModel::Tiny => "tiny",
513 CodeModel::Small => "small",
514 CodeModel::Kernel => "kernel",
515 CodeModel::Medium => "medium",
516 CodeModel::Large => "large",
522 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
530 impl FromStr for TlsModel {
533 fn from_str(s: &str) -> Result<TlsModel, ()> {
535 // Note the difference "general" vs "global" difference. The model name is "general",
536 // but the user-facing option name is "global" for consistency with other compilers.
537 "global-dynamic" => TlsModel::GeneralDynamic,
538 "local-dynamic" => TlsModel::LocalDynamic,
539 "initial-exec" => TlsModel::InitialExec,
540 "local-exec" => TlsModel::LocalExec,
546 impl ToJson for TlsModel {
547 fn to_json(&self) -> Json {
549 TlsModel::GeneralDynamic => "global-dynamic",
550 TlsModel::LocalDynamic => "local-dynamic",
551 TlsModel::InitialExec => "initial-exec",
552 TlsModel::LocalExec => "local-exec",
558 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
559 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
560 pub enum LinkOutputKind {
561 /// Dynamically linked non position-independent executable.
563 /// Dynamically linked position-independent executable.
565 /// Statically linked non position-independent executable.
567 /// Statically linked position-independent executable.
569 /// Regular dynamic library ("dynamically linked").
571 /// Dynamic library with bundled libc ("statically linked").
573 /// WASI module with a lifetime past the _initialize entry point
577 impl LinkOutputKind {
578 fn as_str(&self) -> &'static str {
580 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
581 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
582 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
583 LinkOutputKind::StaticPicExe => "static-pic-exe",
584 LinkOutputKind::DynamicDylib => "dynamic-dylib",
585 LinkOutputKind::StaticDylib => "static-dylib",
586 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
590 pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
592 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
593 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
594 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
595 "static-pic-exe" => LinkOutputKind::StaticPicExe,
596 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
597 "static-dylib" => LinkOutputKind::StaticDylib,
598 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
604 impl fmt::Display for LinkOutputKind {
605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606 f.write_str(self.as_str())
610 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
611 pub type LinkArgsCli = BTreeMap<LinkerFlavorCli, Vec<StaticCow<str>>>;
613 /// Which kind of debuginfo does the target use?
615 /// Useful in determining whether a target supports Split DWARF (a target with
616 /// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example).
617 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
618 pub enum DebuginfoKind {
619 /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`).
622 /// DWARF debuginfo in dSYM files (such as on Apple platforms).
624 /// Program database files (such as on Windows).
629 fn as_str(&self) -> &'static str {
631 DebuginfoKind::Dwarf => "dwarf",
632 DebuginfoKind::DwarfDsym => "dwarf-dsym",
633 DebuginfoKind::Pdb => "pdb",
638 impl FromStr for DebuginfoKind {
641 fn from_str(s: &str) -> Result<Self, ()> {
643 "dwarf" => DebuginfoKind::Dwarf,
644 "dwarf-dsym" => DebuginfoKind::DwarfDsym,
645 "pdb" => DebuginfoKind::Pdb,
651 impl ToJson for DebuginfoKind {
652 fn to_json(&self) -> Json {
653 self.as_str().to_json()
657 impl fmt::Display for DebuginfoKind {
658 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659 f.write_str(self.as_str())
663 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
664 pub enum SplitDebuginfo {
665 /// Split debug-information is disabled, meaning that on supported platforms
666 /// you can find all debug information in the executable itself. This is
667 /// only supported for ELF effectively.
669 /// * Windows - not supported
670 /// * macOS - don't run `dsymutil`
671 /// * ELF - `.debug_*` sections
675 /// Split debug-information can be found in a "packed" location separate
676 /// from the final artifact. This is supported on all platforms.
678 /// * Windows - `*.pdb`
679 /// * macOS - `*.dSYM` (run `dsymutil`)
680 /// * ELF - `*.dwp` (run `thorin`)
683 /// Split debug-information can be found in individual object files on the
684 /// filesystem. The main executable may point to the object files.
686 /// * Windows - not supported
687 /// * macOS - supported, scattered object files
688 /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
692 impl SplitDebuginfo {
693 fn as_str(&self) -> &'static str {
695 SplitDebuginfo::Off => "off",
696 SplitDebuginfo::Packed => "packed",
697 SplitDebuginfo::Unpacked => "unpacked",
702 impl FromStr for SplitDebuginfo {
705 fn from_str(s: &str) -> Result<Self, ()> {
707 "off" => SplitDebuginfo::Off,
708 "unpacked" => SplitDebuginfo::Unpacked,
709 "packed" => SplitDebuginfo::Packed,
715 impl ToJson for SplitDebuginfo {
716 fn to_json(&self) -> Json {
717 self.as_str().to_json()
721 impl fmt::Display for SplitDebuginfo {
722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723 f.write_str(self.as_str())
727 #[derive(Clone, Debug, PartialEq, Eq)]
728 pub enum StackProbeType {
729 /// Don't emit any stack probes.
731 /// It is harmless to use this option even on targets that do not have backend support for
732 /// stack probes as the failure mode is the same as if no stack-probe option was specified in
735 /// Call `__rust_probestack` whenever stack needs to be probed.
737 /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
738 /// and call `__rust_probestack` otherwise.
739 InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
742 impl StackProbeType {
743 // LLVM X86 targets (ix86 and x86_64) can use inline-asm stack probes starting with LLVM 16.
744 // Notable past issues were rust#83139 (fixed in 14) and rust#84667 (fixed in 16).
745 const X86: Self = Self::InlineOrCall { min_llvm_version_for_inline: (16, 0, 0) };
747 fn from_json(json: &Json) -> Result<Self, String> {
748 let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
751 .and_then(|o| o.as_str())
752 .ok_or_else(|| "expected `kind` to be a string")?;
754 "none" => Ok(StackProbeType::None),
755 "inline" => Ok(StackProbeType::Inline),
756 "call" => Ok(StackProbeType::Call),
757 "inline-or-call" => {
758 let min_version = object
759 .get("min-llvm-version-for-inline")
760 .and_then(|o| o.as_array())
761 .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
762 let mut iter = min_version.into_iter().map(|v| {
763 let int = v.as_u64().ok_or_else(
764 || "expected `min-llvm-version-for-inline` values to be integers",
767 .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
769 let min_llvm_version_for_inline = (
770 iter.next().unwrap_or(Ok(11))?,
771 iter.next().unwrap_or(Ok(0))?,
772 iter.next().unwrap_or(Ok(0))?,
774 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
776 _ => Err(String::from(
777 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
783 impl ToJson for StackProbeType {
784 fn to_json(&self) -> Json {
785 Json::Object(match self {
786 StackProbeType::None => {
787 [(String::from("kind"), "none".to_json())].into_iter().collect()
789 StackProbeType::Inline => {
790 [(String::from("kind"), "inline".to_json())].into_iter().collect()
792 StackProbeType::Call => {
793 [(String::from("kind"), "call".to_json())].into_iter().collect()
795 StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
796 (String::from("kind"), "inline-or-call".to_json()),
798 String::from("min-llvm-version-for-inline"),
799 Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
808 bitflags::bitflags! {
809 #[derive(Default, Encodable, Decodable)]
810 pub struct SanitizerSet: u8 {
811 const ADDRESS = 1 << 0;
813 const MEMORY = 1 << 2;
814 const THREAD = 1 << 3;
815 const HWADDRESS = 1 << 4;
817 const MEMTAG = 1 << 6;
818 const SHADOWCALLSTACK = 1 << 7;
823 /// Return sanitizer's name
825 /// Returns none if the flags is a set of sanitizers numbering not exactly one.
826 pub fn as_str(self) -> Option<&'static str> {
828 SanitizerSet::ADDRESS => "address",
829 SanitizerSet::CFI => "cfi",
830 SanitizerSet::LEAK => "leak",
831 SanitizerSet::MEMORY => "memory",
832 SanitizerSet::MEMTAG => "memtag",
833 SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
834 SanitizerSet::THREAD => "thread",
835 SanitizerSet::HWADDRESS => "hwaddress",
841 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
842 impl fmt::Display for SanitizerSet {
843 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
844 let mut first = true;
846 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
857 impl IntoIterator for SanitizerSet {
858 type Item = SanitizerSet;
859 type IntoIter = std::vec::IntoIter<SanitizerSet>;
861 fn into_iter(self) -> Self::IntoIter {
863 SanitizerSet::ADDRESS,
866 SanitizerSet::MEMORY,
867 SanitizerSet::MEMTAG,
868 SanitizerSet::SHADOWCALLSTACK,
869 SanitizerSet::THREAD,
870 SanitizerSet::HWADDRESS,
874 .filter(|&s| self.contains(s))
880 impl<CTX> HashStable<CTX> for SanitizerSet {
881 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
882 self.bits().hash_stable(ctx, hasher);
886 impl ToJson for SanitizerSet {
887 fn to_json(&self) -> Json {
889 .map(|v| Some(v.as_str()?.to_json()))
890 .collect::<Option<Vec<_>>>()
896 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
897 pub enum FramePointer {
898 /// Forces the machine code generator to always preserve the frame pointers.
900 /// Forces the machine code generator to preserve the frame pointers except for the leaf
901 /// functions (i.e. those that don't call other functions).
903 /// Allows the machine code generator to omit the frame pointers.
905 /// This option does not guarantee that the frame pointers will be omitted.
909 impl FromStr for FramePointer {
911 fn from_str(s: &str) -> Result<Self, ()> {
913 "always" => Self::Always,
914 "non-leaf" => Self::NonLeaf,
915 "may-omit" => Self::MayOmit,
921 impl ToJson for FramePointer {
922 fn to_json(&self) -> Json {
924 Self::Always => "always",
925 Self::NonLeaf => "non-leaf",
926 Self::MayOmit => "may-omit",
932 /// Controls use of stack canaries.
933 #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
934 pub enum StackProtector {
935 /// Disable stack canary generation.
938 /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
939 /// llvm/docs/LangRef.rst). This triggers stack canary generation in
940 /// functions which contain an array of a byte-sized type with more than
944 /// On LLVM, mark all generated LLVM functions with the `sspstrong`
945 /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
946 /// generation in functions which either contain an array, or which take
947 /// the address of a local variable.
950 /// Generate stack canaries in all functions.
954 impl StackProtector {
955 fn as_str(&self) -> &'static str {
957 StackProtector::None => "none",
958 StackProtector::Basic => "basic",
959 StackProtector::Strong => "strong",
960 StackProtector::All => "all",
965 impl FromStr for StackProtector {
968 fn from_str(s: &str) -> Result<StackProtector, ()> {
970 "none" => StackProtector::None,
971 "basic" => StackProtector::Basic,
972 "strong" => StackProtector::Strong,
973 "all" => StackProtector::All,
979 impl fmt::Display for StackProtector {
980 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981 f.write_str(self.as_str())
985 macro_rules! supported_targets {
986 ( $(($triple:literal, $module:ident ),)+ ) => {
989 /// List of supported targets
990 pub const TARGETS: &[&str] = &[$($triple),+];
992 fn load_builtin(target: &str) -> Option<Target> {
993 let mut t = match target {
994 $( $triple => $module::target(), )+
998 debug!("got builtin target: {:?}", t);
1006 // Cannot put this into a separate file without duplication, make an exception.
1008 #[test] // `#[test]`
1010 tests_impl::test_target(super::$module::target());
1017 supported_targets! {
1018 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
1019 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
1020 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
1021 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
1022 ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
1023 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
1024 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
1025 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
1026 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
1027 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
1028 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
1029 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
1030 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
1031 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
1032 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
1033 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
1034 ("powerpc64-ibm-aix", powerpc64_ibm_aix),
1035 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
1036 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
1037 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
1038 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
1039 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
1040 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
1041 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
1042 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
1043 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
1044 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
1045 ("armeb-unknown-linux-gnueabi", armeb_unknown_linux_gnueabi),
1046 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
1047 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
1048 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
1049 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
1050 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
1051 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
1052 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
1053 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
1054 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
1055 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
1056 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
1057 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
1058 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
1059 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
1060 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
1061 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
1062 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
1063 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
1064 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
1065 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
1066 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
1067 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
1069 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
1070 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
1072 ("i686-linux-android", i686_linux_android),
1073 ("x86_64-linux-android", x86_64_linux_android),
1074 ("arm-linux-androideabi", arm_linux_androideabi),
1075 ("armv7-linux-androideabi", armv7_linux_androideabi),
1076 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
1077 ("aarch64-linux-android", aarch64_linux_android),
1079 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
1080 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
1081 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
1082 ("i686-unknown-freebsd", i686_unknown_freebsd),
1083 ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
1084 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
1085 ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
1086 ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
1087 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
1089 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
1091 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
1092 ("i686-unknown-openbsd", i686_unknown_openbsd),
1093 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
1094 ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
1095 ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
1096 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
1097 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
1099 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
1100 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
1101 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
1102 ("i686-unknown-netbsd", i686_unknown_netbsd),
1103 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
1104 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
1105 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
1107 ("i686-unknown-haiku", i686_unknown_haiku),
1108 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
1110 ("aarch64-apple-darwin", aarch64_apple_darwin),
1111 ("x86_64-apple-darwin", x86_64_apple_darwin),
1112 ("i686-apple-darwin", i686_apple_darwin),
1114 ("aarch64-fuchsia", aarch64_fuchsia),
1115 ("x86_64-fuchsia", x86_64_fuchsia),
1117 ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
1119 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
1121 ("aarch64-unknown-redox", aarch64_unknown_redox),
1122 ("x86_64-unknown-redox", x86_64_unknown_redox),
1124 ("i386-apple-ios", i386_apple_ios),
1125 ("x86_64-apple-ios", x86_64_apple_ios),
1126 ("aarch64-apple-ios", aarch64_apple_ios),
1127 ("armv7-apple-ios", armv7_apple_ios),
1128 ("armv7s-apple-ios", armv7s_apple_ios),
1129 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
1130 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
1131 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
1132 ("aarch64-apple-tvos", aarch64_apple_tvos),
1133 ("x86_64-apple-tvos", x86_64_apple_tvos),
1135 ("armv7k-apple-watchos", armv7k_apple_watchos),
1136 ("arm64_32-apple-watchos", arm64_32_apple_watchos),
1137 ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
1138 ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
1140 ("armebv7r-none-eabi", armebv7r_none_eabi),
1141 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
1142 ("armv7r-none-eabi", armv7r_none_eabi),
1143 ("armv7r-none-eabihf", armv7r_none_eabihf),
1145 ("x86_64-pc-solaris", x86_64_pc_solaris),
1146 ("x86_64-sun-solaris", x86_64_sun_solaris),
1147 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1149 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1151 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1152 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1153 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1154 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1156 ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1157 ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1159 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1160 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1161 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1162 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1163 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1164 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1165 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
1166 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1167 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1169 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
1170 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1171 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1172 ("wasm32-wasi", wasm32_wasi),
1173 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1175 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1176 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1177 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1178 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1179 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1180 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1181 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1183 ("armv7a-none-eabi", armv7a_none_eabi),
1184 ("armv7a-none-eabihf", armv7a_none_eabihf),
1186 ("msp430-none-elf", msp430_none_elf),
1188 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1189 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1191 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1192 ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1193 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1194 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1195 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1196 ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1197 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1198 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1199 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1200 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1201 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1202 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1204 ("aarch64-unknown-none", aarch64_unknown_none),
1205 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1207 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1209 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1210 ("i686-unknown-uefi", i686_unknown_uefi),
1211 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1213 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1215 ("i686-wrs-vxworks", i686_wrs_vxworks),
1216 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1217 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1218 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1219 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1220 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1221 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1223 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1224 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1225 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1227 ("mipsel-sony-psp", mipsel_sony_psp),
1228 ("mipsel-sony-psx", mipsel_sony_psx),
1229 ("mipsel-unknown-none", mipsel_unknown_none),
1230 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1231 ("armv4t-none-eabi", armv4t_none_eabi),
1232 ("thumbv5te-none-eabi", thumbv5te_none_eabi),
1233 ("armv5te-none-eabi", armv5te_none_eabi),
1235 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1236 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1237 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1239 ("bpfeb-unknown-none", bpfeb_unknown_none),
1240 ("bpfel-unknown-none", bpfel_unknown_none),
1242 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1244 ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1246 ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1247 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1249 ("x86_64-unknown-none", x86_64_unknown_none),
1251 ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1253 ("aarch64-unknown-nto-qnx7.1.0", aarch64_unknown_nto_qnx_710),
1254 ("x86_64-pc-nto-qnx7.1.0", x86_64_pc_nto_qnx710),
1257 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1260 ::std::borrow::Cow::Borrowed(&[])
1262 ($($x:expr),+ $(,)?) => {
1263 ::std::borrow::Cow::Borrowed(&[
1265 ::std::borrow::Cow::Borrowed($x),
1273 /// Warnings encountered when parsing the target `json`.
1275 /// Includes fields that weren't recognized and fields that don't have the expected type.
1276 #[derive(Debug, PartialEq)]
1277 pub struct TargetWarnings {
1278 unused_fields: Vec<String>,
1279 incorrect_type: Vec<String>,
1282 impl TargetWarnings {
1283 pub fn empty() -> Self {
1284 Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1287 pub fn warning_messages(&self) -> Vec<String> {
1288 let mut warnings = vec![];
1289 if !self.unused_fields.is_empty() {
1290 warnings.push(format!(
1291 "target json file contains unused fields: {}",
1292 self.unused_fields.join(", ")
1295 if !self.incorrect_type.is_empty() {
1296 warnings.push(format!(
1297 "target json file contains fields whose value doesn't have the correct json type: {}",
1298 self.incorrect_type.join(", ")
1305 /// Everything `rustc` knows about how to compile for a specific target.
1307 /// Every field here must be specified, and has no default value.
1308 #[derive(PartialEq, Clone, Debug)]
1310 /// Target triple to pass to LLVM.
1311 pub llvm_target: StaticCow<str>,
1312 /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1313 pub pointer_width: u32,
1314 /// Architecture to use for ABI considerations. Valid options include: "x86",
1315 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1316 pub arch: StaticCow<str>,
1317 /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1318 pub data_layout: StaticCow<str>,
1319 /// Optional settings with defaults.
1320 pub options: TargetOptions,
1324 pub fn parse_data_layout<'a>(&'a self) -> Result<TargetDataLayout, TargetDataLayoutErrors<'a>> {
1325 // Parse an address space index from a string.
1326 let parse_address_space = |s: &'a str, cause: &'a str| {
1327 s.parse::<u32>().map(AddressSpace).map_err(|err| {
1328 TargetDataLayoutErrors::InvalidAddressSpace { addr_space: s, cause, err }
1332 // Parse a bit count from a string.
1333 let parse_bits = |s: &'a str, kind: &'a str, cause: &'a str| {
1334 s.parse::<u64>().map_err(|err| TargetDataLayoutErrors::InvalidBits {
1342 // Parse a size string.
1343 let size = |s: &'a str, cause: &'a str| parse_bits(s, "size", cause).map(Size::from_bits);
1345 // Parse an alignment string.
1346 let align = |s: &[&'a str], cause: &'a str| {
1348 return Err(TargetDataLayoutErrors::MissingAlignment { cause });
1350 let align_from_bits = |bits| {
1351 Align::from_bits(bits)
1352 .map_err(|err| TargetDataLayoutErrors::InvalidAlignment { cause, err })
1354 let abi = parse_bits(s[0], "alignment", cause)?;
1355 let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
1356 Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? })
1359 let mut dl = TargetDataLayout::default();
1360 let mut i128_align_src = 64;
1361 for spec in self.data_layout.split('-') {
1362 let spec_parts = spec.split(':').collect::<Vec<_>>();
1364 match &*spec_parts {
1365 ["e"] => dl.endian = Endian::Little,
1366 ["E"] => dl.endian = Endian::Big,
1367 [p] if p.starts_with('P') => {
1368 dl.instruction_address_space = parse_address_space(&p[1..], "P")?
1370 ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?,
1371 ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?,
1372 ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?,
1373 [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => {
1374 dl.pointer_size = size(s, p)?;
1375 dl.pointer_align = align(a, p)?;
1377 [s, ref a @ ..] if s.starts_with('i') => {
1378 let Ok(bits) = s[1..].parse::<u64>() else {
1379 size(&s[1..], "i")?; // For the user error.
1382 let a = align(a, s)?;
1384 1 => dl.i1_align = a,
1385 8 => dl.i8_align = a,
1386 16 => dl.i16_align = a,
1387 32 => dl.i32_align = a,
1388 64 => dl.i64_align = a,
1391 if bits >= i128_align_src && bits <= 128 {
1392 // Default alignment for i128 is decided by taking the alignment of
1393 // largest-sized i{64..=128}.
1394 i128_align_src = bits;
1398 [s, ref a @ ..] if s.starts_with('v') => {
1399 let v_size = size(&s[1..], "v")?;
1400 let a = align(a, s)?;
1401 if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
1405 // No existing entry, add a new one.
1406 dl.vector_align.push((v_size, a));
1408 _ => {} // Ignore everything else.
1412 // Perform consistency checks against the Target information.
1413 if dl.endian != self.endian {
1414 return Err(TargetDataLayoutErrors::InconsistentTargetArchitecture {
1415 dl: dl.endian.as_str(),
1416 target: self.endian.as_str(),
1420 let target_pointer_width: u64 = self.pointer_width.into();
1421 if dl.pointer_size.bits() != target_pointer_width {
1422 return Err(TargetDataLayoutErrors::InconsistentTargetPointerWidth {
1423 pointer_size: dl.pointer_size.bits(),
1424 target: self.pointer_width,
1428 dl.c_enum_min_size = match Integer::from_size(Size::from_bits(self.c_enum_min_bits)) {
1430 Err(err) => return Err(TargetDataLayoutErrors::InvalidBitsSize { err }),
1437 pub trait HasTargetSpec {
1438 fn target_spec(&self) -> &Target;
1441 impl HasTargetSpec for Target {
1443 fn target_spec(&self) -> &Target {
1448 type StaticCow<T> = Cow<'static, T>;
1450 /// Optional aspects of a target specification.
1452 /// This has an implementation of `Default`, see each field for what the default is. In general,
1453 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1455 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1456 /// construction, all its fields logically belong to `Target` and available from `Target`
1457 /// through `Deref` impls.
1458 #[derive(PartialEq, Clone, Debug)]
1459 pub struct TargetOptions {
1460 /// Whether the target is built-in or loaded from a custom target specification.
1461 pub is_builtin: bool,
1463 /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1465 /// Width of c_int type. Defaults to "32".
1466 pub c_int_width: StaticCow<str>,
1467 /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1468 /// "none" implies a bare metal target without `std` library.
1469 /// A couple of targets having `std` also use "unknown" as an `os` value,
1470 /// but they are exceptions.
1471 pub os: StaticCow<str>,
1472 /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1473 pub env: StaticCow<str>,
1474 /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1475 /// or `"eabihf"`. Defaults to "".
1476 pub abi: StaticCow<str>,
1477 /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1478 pub vendor: StaticCow<str>,
1480 /// Linker to invoke
1481 pub linker: Option<StaticCow<str>>,
1482 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1483 /// on the command line. Defaults to `LinkerFlavor::Gnu(Cc::Yes, Lld::No)`.
1484 pub linker_flavor: LinkerFlavor,
1485 linker_flavor_json: LinkerFlavorCli,
1486 lld_flavor_json: LldFlavor,
1487 linker_is_gnu_json: bool,
1489 /// Objects to link before and after all other object code.
1490 pub pre_link_objects: CrtObjects,
1491 pub post_link_objects: CrtObjects,
1492 /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1493 pub pre_link_objects_self_contained: CrtObjects,
1494 pub post_link_objects_self_contained: CrtObjects,
1495 pub link_self_contained: LinkSelfContainedDefault,
1497 /// Linker arguments that are passed *before* any user-defined libraries.
1498 pub pre_link_args: LinkArgs,
1499 pre_link_args_json: LinkArgsCli,
1500 /// Linker arguments that are unconditionally passed after any
1501 /// user-defined but before post-link objects. Standard platform
1502 /// libraries that should be always be linked to, usually go here.
1503 pub late_link_args: LinkArgs,
1504 late_link_args_json: LinkArgsCli,
1505 /// Linker arguments used in addition to `late_link_args` if at least one
1506 /// Rust dependency is dynamically linked.
1507 pub late_link_args_dynamic: LinkArgs,
1508 late_link_args_dynamic_json: LinkArgsCli,
1509 /// Linker arguments used in addition to `late_link_args` if all Rust
1510 /// dependencies are statically linked.
1511 pub late_link_args_static: LinkArgs,
1512 late_link_args_static_json: LinkArgsCli,
1513 /// Linker arguments that are unconditionally passed *after* any
1514 /// user-defined libraries.
1515 pub post_link_args: LinkArgs,
1516 post_link_args_json: LinkArgsCli,
1518 /// Optional link script applied to `dylib` and `executable` crate types.
1519 /// This is a string containing the script, not a path. Can only be applied
1520 /// to linkers where linker flavor matches `LinkerFlavor::Gnu(..)`.
1521 pub link_script: Option<StaticCow<str>>,
1522 /// Environment variables to be set for the linker invocation.
1523 pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1524 /// Environment variables to be removed for the linker invocation.
1525 pub link_env_remove: StaticCow<[StaticCow<str>]>,
1527 /// Extra arguments to pass to the external assembler (when used)
1528 pub asm_args: StaticCow<[StaticCow<str>]>,
1530 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1532 pub cpu: StaticCow<str>,
1533 /// Default target features to pass to LLVM. These features will *always* be
1534 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1535 /// -mattr=$features`.
1536 pub features: StaticCow<str>,
1537 /// Whether dynamic linking is available on this target. Defaults to false.
1538 pub dynamic_linking: bool,
1539 /// If dynamic linking is available, whether only cdylibs are supported.
1540 pub only_cdylib: bool,
1541 /// Whether executables are available on this target. Defaults to true.
1542 pub executables: bool,
1543 /// Relocation model to use in object file. Corresponds to `llc
1544 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1545 pub relocation_model: RelocModel,
1546 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1547 /// Defaults to `None` which means "inherited from the base LLVM target".
1548 pub code_model: Option<CodeModel>,
1549 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1550 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1551 pub tls_model: TlsModel,
1552 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1553 pub disable_redzone: bool,
1554 /// Frame pointer mode for this target. Defaults to `MayOmit`.
1555 pub frame_pointer: FramePointer,
1556 /// Emit each function in its own section. Defaults to true.
1557 pub function_sections: bool,
1558 /// String to prepend to the name of every dynamic library. Defaults to "lib".
1559 pub dll_prefix: StaticCow<str>,
1560 /// String to append to the name of every dynamic library. Defaults to ".so".
1561 pub dll_suffix: StaticCow<str>,
1562 /// String to append to the name of every executable.
1563 pub exe_suffix: StaticCow<str>,
1564 /// String to prepend to the name of every static library. Defaults to "lib".
1565 pub staticlib_prefix: StaticCow<str>,
1566 /// String to append to the name of every static library. Defaults to ".a".
1567 pub staticlib_suffix: StaticCow<str>,
1568 /// Values of the `target_family` cfg set for this target.
1570 /// Common options are: "unix", "windows". Defaults to no families.
1572 /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1573 pub families: StaticCow<[StaticCow<str>]>,
1574 /// Whether the target toolchain's ABI supports returning small structs as an integer.
1575 pub abi_return_struct_as_int: bool,
1576 /// Whether the target toolchain is like AIX's. Linker options on AIX are special and it uses
1577 /// XCOFF as binary format. Defaults to false.
1578 pub is_like_aix: bool,
1579 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1580 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1581 /// Also indiates whether to use Apple-specific ABI changes, such as extending function
1582 /// parameters to 32-bits.
1583 pub is_like_osx: bool,
1584 /// Whether the target toolchain is like Solaris's.
1585 /// Only useful for compiling against Illumos/Solaris,
1586 /// as they have a different set of linker flags. Defaults to false.
1587 pub is_like_solaris: bool,
1588 /// Whether the target is like Windows.
1589 /// This is a combination of several more specific properties represented as a single flag:
1590 /// - The target uses a Windows ABI,
1591 /// - uses PE/COFF as a format for object code,
1592 /// - uses Windows-style dllexport/dllimport for shared libraries,
1593 /// - uses import libraries and .def files for symbol exports,
1594 /// - executables support setting a subsystem.
1595 pub is_like_windows: bool,
1596 /// Whether the target is like MSVC.
1597 /// This is a combination of several more specific properties represented as a single flag:
1598 /// - The target has all the properties from `is_like_windows`
1599 /// (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
1600 /// - has some MSVC-specific Windows ABI properties,
1601 /// - uses a link.exe-like linker,
1602 /// - uses CodeView/PDB for debuginfo and natvis for its visualization,
1603 /// - uses SEH-based unwinding,
1604 /// - supports control flow guard mechanism.
1605 pub is_like_msvc: bool,
1606 /// Whether a target toolchain is like WASM.
1607 pub is_like_wasm: bool,
1608 /// Whether a target toolchain is like Android, implying a Linux kernel and a Bionic libc
1609 pub is_like_android: bool,
1610 /// Default supported version of DWARF on this platform.
1611 /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1612 pub default_dwarf_version: u32,
1613 /// The MinGW toolchain has a known issue that prevents it from correctly
1614 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1615 /// symbol needs its own COMDAT section, weak linkage implies a large
1616 /// number sections that easily exceeds the given limit for larger
1617 /// codebases. Consequently we want a way to disallow weak linkage on some
1619 pub allows_weak_linkage: bool,
1620 /// Whether the linker support rpaths or not. Defaults to false.
1621 pub has_rpath: bool,
1622 /// Whether to disable linking to the default libraries, typically corresponds
1623 /// to `-nodefaultlibs`. Defaults to true.
1624 pub no_default_libraries: bool,
1625 /// Dynamically linked executables can be compiled as position independent
1626 /// if the default relocation model of position independent code is not
1627 /// changed. This is a requirement to take advantage of ASLR, as otherwise
1628 /// the functions in the executable are not randomized and can be used
1629 /// during an exploit of a vulnerability in any code.
1630 pub position_independent_executables: bool,
1631 /// Executables that are both statically linked and position-independent are supported.
1632 pub static_position_independent_executables: bool,
1633 /// Determines if the target always requires using the PLT for indirect
1634 /// library calls or not. This controls the default value of the `-Z plt` flag.
1635 pub needs_plt: bool,
1636 /// Either partial, full, or off. Full RELRO makes the dynamic linker
1637 /// resolve all symbols at startup and marks the GOT read-only before
1638 /// starting the program, preventing overwriting the GOT.
1639 pub relro_level: RelroLevel,
1640 /// Format that archives should be emitted in. This affects whether we use
1641 /// LLVM to assemble an archive or fall back to the system linker, and
1642 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1643 /// the system linker to be used.
1644 pub archive_format: StaticCow<str>,
1645 /// Is asm!() allowed? Defaults to true.
1646 pub allow_asm: bool,
1647 /// Whether the runtime startup code requires the `main` function be passed
1648 /// `argc` and `argv` values.
1649 pub main_needs_argc_argv: bool,
1651 /// Flag indicating whether #[thread_local] is available for this target.
1652 pub has_thread_local: bool,
1653 // This is mainly for easy compatibility with emscripten.
1654 // If we give emcc .o files that are actually .bc files it
1655 // will 'just work'.
1656 pub obj_is_bitcode: bool,
1657 /// Whether the target requires that emitted object code includes bitcode.
1658 pub forces_embed_bitcode: bool,
1659 /// Content of the LLVM cmdline section associated with embedded bitcode.
1660 pub bitcode_llvm_cmdline: StaticCow<str>,
1662 /// Don't use this field; instead use the `.min_atomic_width()` method.
1663 pub min_atomic_width: Option<u64>,
1665 /// Don't use this field; instead use the `.max_atomic_width()` method.
1666 pub max_atomic_width: Option<u64>,
1668 /// Whether the target supports atomic CAS operations natively
1669 pub atomic_cas: bool,
1671 /// Panic strategy: "unwind" or "abort"
1672 pub panic_strategy: PanicStrategy,
1674 /// Whether or not linking dylibs to a static CRT is allowed.
1675 pub crt_static_allows_dylibs: bool,
1676 /// Whether or not the CRT is statically linked by default.
1677 pub crt_static_default: bool,
1678 /// Whether or not crt-static is respected by the compiler (or is a no-op).
1679 pub crt_static_respected: bool,
1681 /// The implementation of stack probes to use.
1682 pub stack_probes: StackProbeType,
1684 /// The minimum alignment for global symbols.
1685 pub min_global_align: Option<u64>,
1687 /// Default number of codegen units to use in debug mode
1688 pub default_codegen_units: Option<u64>,
1690 /// Whether to generate trap instructions in places where optimization would
1691 /// otherwise produce control flow that falls through into unrelated memory.
1692 pub trap_unreachable: bool,
1694 /// This target requires everything to be compiled with LTO to emit a final
1695 /// executable, aka there is no native linker for this target.
1696 pub requires_lto: bool,
1698 /// This target has no support for threads.
1699 pub singlethread: bool,
1701 /// Whether library functions call lowering/optimization is disabled in LLVM
1702 /// for this target unconditionally.
1703 pub no_builtins: bool,
1705 /// The default visibility for symbols in this target should be "hidden"
1706 /// rather than "default"
1707 pub default_hidden_visibility: bool,
1709 /// Whether a .debug_gdb_scripts section will be added to the output object file
1710 pub emit_debug_gdb_scripts: bool,
1712 /// Whether or not to unconditionally `uwtable` attributes on functions,
1713 /// typically because the platform needs to unwind for things like stack
1715 pub requires_uwtable: bool,
1717 /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1718 /// is not specified and `uwtable` is not required on this target.
1719 pub default_uwtable: bool,
1721 /// Whether or not SIMD types are passed by reference in the Rust ABI,
1722 /// typically required if a target can be compiled with a mixed set of
1723 /// target features. This is `true` by default, and `false` for targets like
1724 /// wasm32 where the whole program either has simd or not.
1725 pub simd_types_indirect: bool,
1727 /// Pass a list of symbol which should be exported in the dylib to the linker.
1728 pub limit_rdylib_exports: bool,
1730 /// If set, have the linker export exactly these symbols, instead of using
1731 /// the usual logic to figure this out from the crate itself.
1732 pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1734 /// Determines how or whether the MergeFunctions LLVM pass should run for
1735 /// this target. Either "disabled", "trampolines", or "aliases".
1736 /// The MergeFunctions pass is generally useful, but some targets may need
1737 /// to opt out. The default is "aliases".
1739 /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1740 pub merge_functions: MergeFunctions,
1742 /// Use platform dependent mcount function
1743 pub mcount: StaticCow<str>,
1745 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1746 pub llvm_abiname: StaticCow<str>,
1748 /// Whether or not RelaxElfRelocation flag will be passed to the linker
1749 pub relax_elf_relocations: bool,
1751 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1752 pub llvm_args: StaticCow<[StaticCow<str>]>,
1754 /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1755 /// to false (uses .init_array).
1756 pub use_ctors_section: bool,
1758 /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1759 /// used to locate unwinding information is passed
1760 /// (only has effect if the linker is `ld`-like).
1761 pub eh_frame_header: bool,
1763 /// Is true if the target is an ARM architecture using thumb v1 which allows for
1764 /// thumb and arm interworking.
1765 pub has_thumb_interworking: bool,
1767 /// Which kind of debuginfo is used by this target?
1768 pub debuginfo_kind: DebuginfoKind,
1769 /// How to handle split debug information, if at all. Specifying `None` has
1770 /// target-specific meaning.
1771 pub split_debuginfo: SplitDebuginfo,
1772 /// Which kinds of split debuginfo are supported by the target?
1773 pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
1775 /// The sanitizers supported by this target
1777 /// Note that the support here is at a codegen level. If the machine code with sanitizer
1778 /// enabled can generated on this target, but the necessary supporting libraries are not
1779 /// distributed with the target, the sanitizer should still appear in this list for the target.
1780 pub supported_sanitizers: SanitizerSet,
1782 /// If present it's a default value to use for adjusting the C ABI.
1783 pub default_adjusted_cabi: Option<Abi>,
1785 /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1786 pub c_enum_min_bits: u64,
1788 /// Whether or not the DWARF `.debug_aranges` section should be generated.
1789 pub generate_arange_section: bool,
1791 /// Whether the target supports stack canary checks. `true` by default,
1792 /// since this is most common among tier 1 and tier 2 targets.
1793 pub supports_stack_protector: bool,
1795 // The name of entry function.
1796 // Default value is "main"
1797 pub entry_name: StaticCow<str>,
1799 // The ABI of entry function.
1800 // Default value is `Conv::C`, i.e. C call convention
1801 pub entry_abi: Conv,
1804 /// Add arguments for the given flavor and also for its "twin" flavors
1805 /// that have a compatible command line interface.
1806 fn add_link_args_iter(
1807 link_args: &mut LinkArgs,
1808 flavor: LinkerFlavor,
1809 args: impl Iterator<Item = StaticCow<str>> + Clone,
1811 let mut insert = |flavor| link_args.entry(flavor).or_default().extend(args.clone());
1814 LinkerFlavor::Gnu(cc, lld) => {
1815 assert_eq!(lld, Lld::No);
1816 insert(LinkerFlavor::Gnu(cc, Lld::Yes));
1818 LinkerFlavor::Darwin(cc, lld) => {
1819 assert_eq!(lld, Lld::No);
1820 insert(LinkerFlavor::Darwin(cc, Lld::Yes));
1822 LinkerFlavor::Msvc(lld) => {
1823 assert_eq!(lld, Lld::No);
1824 insert(LinkerFlavor::Msvc(Lld::Yes));
1826 LinkerFlavor::WasmLld(..)
1827 | LinkerFlavor::Unix(..)
1828 | LinkerFlavor::EmCc
1830 | LinkerFlavor::Ptx => {}
1834 fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
1835 add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
1838 impl TargetOptions {
1839 fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
1840 let mut link_args = LinkArgs::new();
1841 add_link_args(&mut link_args, flavor, args);
1845 fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1846 add_link_args(&mut self.pre_link_args, flavor, args);
1849 fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1850 add_link_args(&mut self.post_link_args, flavor, args);
1853 fn update_from_cli(&mut self) {
1854 self.linker_flavor = LinkerFlavor::from_cli_impl(
1855 self.linker_flavor_json,
1856 self.lld_flavor_json,
1857 self.linker_is_gnu_json,
1859 for (args, args_json) in [
1860 (&mut self.pre_link_args, &self.pre_link_args_json),
1861 (&mut self.late_link_args, &self.late_link_args_json),
1862 (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
1863 (&mut self.late_link_args_static, &self.late_link_args_static_json),
1864 (&mut self.post_link_args, &self.post_link_args_json),
1867 for (flavor, args_json) in args_json {
1868 // Cannot use `from_cli` due to borrow checker.
1869 let linker_flavor = LinkerFlavor::from_cli_impl(
1871 self.lld_flavor_json,
1872 self.linker_is_gnu_json,
1874 // Normalize to no lld to avoid asserts.
1875 let linker_flavor = match linker_flavor {
1876 LinkerFlavor::Gnu(cc, _) => LinkerFlavor::Gnu(cc, Lld::No),
1877 LinkerFlavor::Darwin(cc, _) => LinkerFlavor::Darwin(cc, Lld::No),
1878 LinkerFlavor::Msvc(_) => LinkerFlavor::Msvc(Lld::No),
1881 if !args.contains_key(&linker_flavor) {
1882 add_link_args_iter(args, linker_flavor, args_json.iter().cloned());
1888 fn update_to_cli(&mut self) {
1889 self.linker_flavor_json = self.linker_flavor.to_cli();
1890 self.lld_flavor_json = self.linker_flavor.lld_flavor();
1891 self.linker_is_gnu_json = self.linker_flavor.is_gnu();
1892 for (args, args_json) in [
1893 (&self.pre_link_args, &mut self.pre_link_args_json),
1894 (&self.late_link_args, &mut self.late_link_args_json),
1895 (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
1896 (&self.late_link_args_static, &mut self.late_link_args_static_json),
1897 (&self.post_link_args, &mut self.post_link_args_json),
1900 args.iter().map(|(flavor, args)| (flavor.to_cli(), args.clone())).collect();
1905 impl Default for TargetOptions {
1906 /// Creates a set of "sane defaults" for any target. This is still
1907 /// incomplete, and if used for compilation, will certainly not work.
1908 fn default() -> TargetOptions {
1911 endian: Endian::Little,
1912 c_int_width: "32".into(),
1916 vendor: "unknown".into(),
1917 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1918 linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
1919 linker_flavor_json: LinkerFlavorCli::Gcc,
1920 lld_flavor_json: LldFlavor::Ld,
1921 linker_is_gnu_json: true,
1924 cpu: "generic".into(),
1925 features: "".into(),
1926 dynamic_linking: false,
1929 relocation_model: RelocModel::Pic,
1931 tls_model: TlsModel::GeneralDynamic,
1932 disable_redzone: false,
1933 frame_pointer: FramePointer::MayOmit,
1934 function_sections: true,
1935 dll_prefix: "lib".into(),
1936 dll_suffix: ".so".into(),
1937 exe_suffix: "".into(),
1938 staticlib_prefix: "lib".into(),
1939 staticlib_suffix: ".a".into(),
1941 abi_return_struct_as_int: false,
1944 is_like_solaris: false,
1945 is_like_windows: false,
1946 is_like_msvc: false,
1947 is_like_wasm: false,
1948 is_like_android: false,
1949 default_dwarf_version: 4,
1950 allows_weak_linkage: true,
1952 no_default_libraries: true,
1953 position_independent_executables: false,
1954 static_position_independent_executables: false,
1956 relro_level: RelroLevel::None,
1957 pre_link_objects: Default::default(),
1958 post_link_objects: Default::default(),
1959 pre_link_objects_self_contained: Default::default(),
1960 post_link_objects_self_contained: Default::default(),
1961 link_self_contained: LinkSelfContainedDefault::False,
1962 pre_link_args: LinkArgs::new(),
1963 pre_link_args_json: LinkArgsCli::new(),
1964 late_link_args: LinkArgs::new(),
1965 late_link_args_json: LinkArgsCli::new(),
1966 late_link_args_dynamic: LinkArgs::new(),
1967 late_link_args_dynamic_json: LinkArgsCli::new(),
1968 late_link_args_static: LinkArgs::new(),
1969 late_link_args_static_json: LinkArgsCli::new(),
1970 post_link_args: LinkArgs::new(),
1971 post_link_args_json: LinkArgsCli::new(),
1973 link_env_remove: cvs![],
1974 archive_format: "gnu".into(),
1975 main_needs_argc_argv: true,
1977 has_thread_local: false,
1978 obj_is_bitcode: false,
1979 forces_embed_bitcode: false,
1980 bitcode_llvm_cmdline: "".into(),
1981 min_atomic_width: None,
1982 max_atomic_width: None,
1984 panic_strategy: PanicStrategy::Unwind,
1985 crt_static_allows_dylibs: false,
1986 crt_static_default: false,
1987 crt_static_respected: false,
1988 stack_probes: StackProbeType::None,
1989 min_global_align: None,
1990 default_codegen_units: None,
1991 trap_unreachable: true,
1992 requires_lto: false,
1993 singlethread: false,
1995 default_hidden_visibility: false,
1996 emit_debug_gdb_scripts: true,
1997 requires_uwtable: false,
1998 default_uwtable: false,
1999 simd_types_indirect: true,
2000 limit_rdylib_exports: true,
2001 override_export_symbols: None,
2002 merge_functions: MergeFunctions::Aliases,
2003 mcount: "mcount".into(),
2004 llvm_abiname: "".into(),
2005 relax_elf_relocations: false,
2007 use_ctors_section: false,
2008 eh_frame_header: true,
2009 has_thumb_interworking: false,
2010 debuginfo_kind: Default::default(),
2011 split_debuginfo: Default::default(),
2012 // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
2013 supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
2014 supported_sanitizers: SanitizerSet::empty(),
2015 default_adjusted_cabi: None,
2016 c_enum_min_bits: 32,
2017 generate_arange_section: true,
2018 supports_stack_protector: true,
2019 entry_name: "main".into(),
2025 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
2026 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
2027 /// this `Deref` implementation is no longer necessary.
2028 impl Deref for Target {
2029 type Target = TargetOptions;
2032 fn deref(&self) -> &Self::Target {
2036 impl DerefMut for Target {
2038 fn deref_mut(&mut self) -> &mut Self::Target {
2044 /// Given a function ABI, turn it into the correct ABI for this target.
2045 pub fn adjust_abi(&self, abi: Abi) -> Abi {
2047 Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
2048 Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
2049 Abi::Stdcall { unwind }
2051 Abi::System { unwind } => Abi::C { unwind },
2052 Abi::EfiApi if self.arch == "arm" => Abi::Aapcs { unwind: false },
2053 Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
2054 Abi::EfiApi => Abi::C { unwind: false },
2056 // See commentary in `is_abi_supported`.
2057 Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
2058 Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
2059 Abi::Fastcall { .. } if self.arch == "x86" => abi,
2060 Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
2061 Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
2067 /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
2068 pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
2081 ["arm", "aarch64", "riscv32", "riscv64", "x86", "x86_64"].contains(&&self.arch[..])
2083 X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
2084 Aapcs { .. } => "arm" == self.arch,
2085 CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
2086 Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
2087 PtxKernel => self.arch == "nvptx64",
2088 Msp430Interrupt => self.arch == "msp430",
2089 AmdGpuKernel => self.arch == "amdgcn",
2090 AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
2091 Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
2092 Thiscall { .. } => self.arch == "x86",
2093 // On windows these fall-back to platform native calling convention (C) when the
2094 // architecture is not supported.
2096 // This is I believe a historical accident that has occurred as part of Microsoft
2097 // striving to allow most of the code to "just" compile when support for 64-bit x86
2098 // was added and then later again, when support for ARM architectures was added.
2100 // This is well documented across MSDN. Support for this in Rust has been added in
2101 // #54576. This makes much more sense in context of Microsoft's C++ than it does in
2102 // Rust, but there isn't much leeway remaining here to change it back at the time this
2103 // comment has been written.
2105 // Following are the relevant excerpts from the MSDN documentation.
2107 // > The __vectorcall calling convention is only supported in native code on x86 and
2108 // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
2110 // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
2112 // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
2114 // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
2116 // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
2118 // > In most cases, keywords or compiler switches that specify an unsupported
2119 // > convention on a particular platform are ignored, and the platform default
2120 // > convention is used.
2122 // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
2123 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
2124 // Outside of Windows we want to only support these calling conventions for the
2125 // architectures for which these calling conventions are actually well defined.
2126 Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
2127 Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
2128 // Return a `None` for other cases so that we know to emit a future compat lint.
2129 Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
2133 /// Minimum integer size in bits that this target can perform atomic
2135 pub fn min_atomic_width(&self) -> u64 {
2136 self.min_atomic_width.unwrap_or(8)
2139 /// Maximum integer size in bits that this target can perform atomic
2141 pub fn max_atomic_width(&self) -> u64 {
2142 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
2145 /// Loads a target descriptor from a JSON object.
2146 pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
2147 // While ugly, this code must remain this way to retain
2148 // compatibility with existing JSON fields and the internal
2149 // expected naming of the Target and TargetOptions structs.
2150 // To ensure compatibility is retained, the built-in targets
2151 // are round-tripped through this code to catch cases where
2152 // the JSON parser is not updated to match the structs.
2154 let mut obj = match obj {
2155 Value::Object(obj) => obj,
2156 _ => return Err("Expected JSON object for target")?,
2159 let mut get_req_field = |name: &str| {
2161 .and_then(|j| j.as_str().map(str::to_string))
2162 .ok_or_else(|| format!("Field {} in target specification is required", name))
2165 let mut base = Target {
2166 llvm_target: get_req_field("llvm-target")?.into(),
2167 pointer_width: get_req_field("target-pointer-width")?
2169 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
2170 data_layout: get_req_field("data-layout")?.into(),
2171 arch: get_req_field("arch")?.into(),
2172 options: Default::default(),
2175 let mut incorrect_type = vec![];
2178 ($key_name:ident) => ( {
2179 let name = (stringify!($key_name)).replace("_", "-");
2180 if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
2184 ($key_name:ident = $json_name:expr) => ( {
2185 let name = $json_name;
2186 if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
2190 ($key_name:ident, bool) => ( {
2191 let name = (stringify!($key_name)).replace("_", "-");
2192 if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
2196 ($key_name:ident = $json_name:expr, bool) => ( {
2197 let name = $json_name;
2198 if let Some(s) = obj.remove(name).and_then(|b| b.as_bool()) {
2202 ($key_name:ident, u64) => ( {
2203 let name = (stringify!($key_name)).replace("_", "-");
2204 if let Some(s) = obj.remove(&name).and_then(|j| Json::as_u64(&j)) {
2208 ($key_name:ident, u32) => ( {
2209 let name = (stringify!($key_name)).replace("_", "-");
2210 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
2212 return Err("Not a valid DWARF version number".into());
2214 base.$key_name = s as u32;
2217 ($key_name:ident, Option<u64>) => ( {
2218 let name = (stringify!($key_name)).replace("_", "-");
2219 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
2220 base.$key_name = Some(s);
2223 ($key_name:ident, MergeFunctions) => ( {
2224 let name = (stringify!($key_name)).replace("_", "-");
2225 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2226 match s.parse::<MergeFunctions>() {
2227 Ok(mergefunc) => base.$key_name = mergefunc,
2228 _ => return Some(Err(format!("'{}' is not a valid value for \
2229 merge-functions. Use 'disabled', \
2230 'trampolines', or 'aliases'.",
2234 })).unwrap_or(Ok(()))
2236 ($key_name:ident, RelocModel) => ( {
2237 let name = (stringify!($key_name)).replace("_", "-");
2238 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2239 match s.parse::<RelocModel>() {
2240 Ok(relocation_model) => base.$key_name = relocation_model,
2241 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
2242 Run `rustc --print relocation-models` to \
2243 see the list of supported values.", s))),
2246 })).unwrap_or(Ok(()))
2248 ($key_name:ident, CodeModel) => ( {
2249 let name = (stringify!($key_name)).replace("_", "-");
2250 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2251 match s.parse::<CodeModel>() {
2252 Ok(code_model) => base.$key_name = Some(code_model),
2253 _ => return Some(Err(format!("'{}' is not a valid code model. \
2254 Run `rustc --print code-models` to \
2255 see the list of supported values.", s))),
2258 })).unwrap_or(Ok(()))
2260 ($key_name:ident, TlsModel) => ( {
2261 let name = (stringify!($key_name)).replace("_", "-");
2262 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2263 match s.parse::<TlsModel>() {
2264 Ok(tls_model) => base.$key_name = tls_model,
2265 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
2266 Run `rustc --print tls-models` to \
2267 see the list of supported values.", s))),
2270 })).unwrap_or(Ok(()))
2272 ($key_name:ident, PanicStrategy) => ( {
2273 let name = (stringify!($key_name)).replace("_", "-");
2274 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2276 "unwind" => base.$key_name = PanicStrategy::Unwind,
2277 "abort" => base.$key_name = PanicStrategy::Abort,
2278 _ => return Some(Err(format!("'{}' is not a valid value for \
2279 panic-strategy. Use 'unwind' or 'abort'.",
2283 })).unwrap_or(Ok(()))
2285 ($key_name:ident, RelroLevel) => ( {
2286 let name = (stringify!($key_name)).replace("_", "-");
2287 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2288 match s.parse::<RelroLevel>() {
2289 Ok(level) => base.$key_name = level,
2290 _ => return Some(Err(format!("'{}' is not a valid value for \
2291 relro-level. Use 'full', 'partial, or 'off'.",
2295 })).unwrap_or(Ok(()))
2297 ($key_name:ident, DebuginfoKind) => ( {
2298 let name = (stringify!($key_name)).replace("_", "-");
2299 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2300 match s.parse::<DebuginfoKind>() {
2301 Ok(level) => base.$key_name = level,
2302 _ => return Some(Err(
2303 format!("'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
2304 'dwarf-dsym' or 'pdb'.")
2308 })).unwrap_or(Ok(()))
2310 ($key_name:ident, SplitDebuginfo) => ( {
2311 let name = (stringify!($key_name)).replace("_", "-");
2312 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2313 match s.parse::<SplitDebuginfo>() {
2314 Ok(level) => base.$key_name = level,
2315 _ => return Some(Err(format!("'{}' is not a valid value for \
2316 split-debuginfo. Use 'off' or 'dsymutil'.",
2320 })).unwrap_or(Ok(()))
2322 ($key_name:ident, list) => ( {
2323 let name = (stringify!($key_name)).replace("_", "-");
2324 if let Some(j) = obj.remove(&name) {
2325 if let Some(v) = j.as_array() {
2326 base.$key_name = v.iter()
2327 .map(|a| a.as_str().unwrap().to_string().into())
2330 incorrect_type.push(name)
2334 ($key_name:ident, opt_list) => ( {
2335 let name = (stringify!($key_name)).replace("_", "-");
2336 if let Some(j) = obj.remove(&name) {
2337 if let Some(v) = j.as_array() {
2338 base.$key_name = Some(v.iter()
2339 .map(|a| a.as_str().unwrap().to_string().into())
2342 incorrect_type.push(name)
2346 ($key_name:ident, falliable_list) => ( {
2347 let name = (stringify!($key_name)).replace("_", "-");
2348 obj.remove(&name).and_then(|j| {
2349 if let Some(v) = j.as_array() {
2350 match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() {
2351 Ok(l) => { base.$key_name = l },
2352 // FIXME: `falliable_list` can't re-use the `key!` macro for list
2353 // elements and the error messages from that macro, so it has a bad
2354 // generic message instead
2355 Err(_) => return Some(Err(
2356 format!("`{:?}` is not a valid value for `{}`", j, name)
2360 incorrect_type.push(name)
2363 }).unwrap_or(Ok(()))
2365 ($key_name:ident, optional) => ( {
2366 let name = (stringify!($key_name)).replace("_", "-");
2367 if let Some(o) = obj.remove(&name) {
2370 .map(|s| s.to_string().into());
2373 ($key_name:ident = $json_name:expr, LldFlavor) => ( {
2374 let name = $json_name;
2375 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2376 if let Some(flavor) = LldFlavor::from_str(&s) {
2377 base.$key_name = flavor;
2379 return Some(Err(format!(
2380 "'{}' is not a valid value for lld-flavor. \
2381 Use 'darwin', 'gnu', 'link' or 'wasm.",
2385 })).unwrap_or(Ok(()))
2387 ($key_name:ident = $json_name:expr, LinkerFlavor) => ( {
2388 let name = $json_name;
2389 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2390 match LinkerFlavorCli::from_str(s) {
2391 Some(linker_flavor) => base.$key_name = linker_flavor,
2392 _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
2393 Use {}", s, LinkerFlavorCli::one_of()))),
2396 })).unwrap_or(Ok(()))
2398 ($key_name:ident, StackProbeType) => ( {
2399 let name = (stringify!($key_name)).replace("_", "-");
2400 obj.remove(&name).and_then(|o| match StackProbeType::from_json(&o) {
2406 format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
2408 }).unwrap_or(Ok(()))
2410 ($key_name:ident, SanitizerSet) => ( {
2411 let name = (stringify!($key_name)).replace("_", "-");
2412 if let Some(o) = obj.remove(&name) {
2413 if let Some(a) = o.as_array() {
2415 base.$key_name |= match s.as_str() {
2416 Some("address") => SanitizerSet::ADDRESS,
2417 Some("cfi") => SanitizerSet::CFI,
2418 Some("leak") => SanitizerSet::LEAK,
2419 Some("memory") => SanitizerSet::MEMORY,
2420 Some("memtag") => SanitizerSet::MEMTAG,
2421 Some("shadow-call-stack") => SanitizerSet::SHADOWCALLSTACK,
2422 Some("thread") => SanitizerSet::THREAD,
2423 Some("hwaddress") => SanitizerSet::HWADDRESS,
2424 Some(s) => return Err(format!("unknown sanitizer {}", s)),
2425 _ => return Err(format!("not a string: {:?}", s)),
2429 incorrect_type.push(name)
2432 Ok::<(), String>(())
2435 ($key_name:ident = $json_name:expr, link_self_contained) => ( {
2436 let name = $json_name;
2437 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2438 match s.parse::<LinkSelfContainedDefault>() {
2439 Ok(lsc_default) => base.$key_name = lsc_default,
2440 _ => return Some(Err(format!("'{}' is not a valid `-Clink-self-contained` default. \
2441 Use 'false', 'true', 'musl' or 'mingw'", s))),
2444 })).unwrap_or(Ok(()))
2446 ($key_name:ident = $json_name:expr, link_objects) => ( {
2447 let name = $json_name;
2448 if let Some(val) = obj.remove(name) {
2449 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2450 JSON object with fields per CRT object kind.", name))?;
2451 let mut args = CrtObjects::new();
2453 let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
2454 format!("{}: '{}' is not a valid value for CRT object kind. \
2455 Use '(dynamic,static)-(nopic,pic)-exe' or \
2456 '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
2459 let v = v.as_array().ok_or_else(||
2460 format!("{}.{}: expected a JSON array", name, k)
2461 )?.iter().enumerate()
2463 let s = s.as_str().ok_or_else(||
2464 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2465 Ok(s.to_string().into())
2467 .collect::<Result<Vec<_>, String>>()?;
2469 args.insert(kind, v);
2471 base.$key_name = args;
2474 ($key_name:ident = $json_name:expr, link_args) => ( {
2475 let name = $json_name;
2476 if let Some(val) = obj.remove(name) {
2477 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2478 JSON object with fields per linker-flavor.", name))?;
2479 let mut args = LinkArgsCli::new();
2481 let flavor = LinkerFlavorCli::from_str(&k).ok_or_else(|| {
2482 format!("{}: '{}' is not a valid value for linker-flavor. \
2483 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
2486 let v = v.as_array().ok_or_else(||
2487 format!("{}.{}: expected a JSON array", name, k)
2488 )?.iter().enumerate()
2490 let s = s.as_str().ok_or_else(||
2491 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2492 Ok(s.to_string().into())
2494 .collect::<Result<Vec<_>, String>>()?;
2496 args.insert(flavor, v);
2498 base.$key_name = args;
2501 ($key_name:ident, env) => ( {
2502 let name = (stringify!($key_name)).replace("_", "-");
2503 if let Some(o) = obj.remove(&name) {
2504 if let Some(a) = o.as_array() {
2506 if let Some(s) = o.as_str() {
2507 let p = s.split('=').collect::<Vec<_>>();
2509 let k = p[0].to_string();
2510 let v = p[1].to_string();
2511 base.$key_name.to_mut().push((k.into(), v.into()));
2516 incorrect_type.push(name)
2520 ($key_name:ident, Option<Abi>) => ( {
2521 let name = (stringify!($key_name)).replace("_", "-");
2522 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2523 match lookup_abi(s) {
2524 Some(abi) => base.$key_name = Some(abi),
2525 _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2528 })).unwrap_or(Ok(()))
2530 ($key_name:ident, TargetFamilies) => ( {
2531 if let Some(value) = obj.remove("target-family") {
2532 if let Some(v) = value.as_array() {
2533 base.$key_name = v.iter()
2534 .map(|a| a.as_str().unwrap().to_string().into())
2536 } else if let Some(v) = value.as_str() {
2537 base.$key_name = vec![v.to_string().into()].into();
2541 ($key_name:ident, Conv) => ( {
2542 let name = (stringify!($key_name)).replace("_", "-");
2543 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2544 match Conv::from_str(s) {
2549 Err(e) => Some(Err(e))
2551 })).unwrap_or(Ok(()))
2555 if let Some(j) = obj.remove("target-endian") {
2556 if let Some(s) = j.as_str() {
2557 base.endian = s.parse()?;
2559 incorrect_type.push("target-endian".into())
2563 if let Some(fp) = obj.remove("frame-pointer") {
2564 if let Some(s) = fp.as_str() {
2565 base.frame_pointer = s
2567 .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2569 incorrect_type.push("frame-pointer".into())
2573 key!(is_builtin, bool);
2574 key!(c_int_width = "target-c-int-width");
2579 key!(linker, optional);
2580 key!(linker_flavor_json = "linker-flavor", LinkerFlavor)?;
2581 key!(lld_flavor_json = "lld-flavor", LldFlavor)?;
2582 key!(linker_is_gnu_json = "linker-is-gnu", bool);
2583 key!(pre_link_objects = "pre-link-objects", link_objects);
2584 key!(post_link_objects = "post-link-objects", link_objects);
2585 key!(pre_link_objects_self_contained = "pre-link-objects-fallback", link_objects);
2586 key!(post_link_objects_self_contained = "post-link-objects-fallback", link_objects);
2587 key!(link_self_contained = "crt-objects-fallback", link_self_contained)?;
2588 key!(pre_link_args_json = "pre-link-args", link_args);
2589 key!(late_link_args_json = "late-link-args", link_args);
2590 key!(late_link_args_dynamic_json = "late-link-args-dynamic", link_args);
2591 key!(late_link_args_static_json = "late-link-args-static", link_args);
2592 key!(post_link_args_json = "post-link-args", link_args);
2593 key!(link_script, optional);
2594 key!(link_env, env);
2595 key!(link_env_remove, list);
2596 key!(asm_args, list);
2599 key!(dynamic_linking, bool);
2600 key!(only_cdylib, bool);
2601 key!(executables, bool);
2602 key!(relocation_model, RelocModel)?;
2603 key!(code_model, CodeModel)?;
2604 key!(tls_model, TlsModel)?;
2605 key!(disable_redzone, bool);
2606 key!(function_sections, bool);
2610 key!(staticlib_prefix);
2611 key!(staticlib_suffix);
2612 key!(families, TargetFamilies);
2613 key!(abi_return_struct_as_int, bool);
2614 key!(is_like_aix, bool);
2615 key!(is_like_osx, bool);
2616 key!(is_like_solaris, bool);
2617 key!(is_like_windows, bool);
2618 key!(is_like_msvc, bool);
2619 key!(is_like_wasm, bool);
2620 key!(is_like_android, bool);
2621 key!(default_dwarf_version, u32);
2622 key!(allows_weak_linkage, bool);
2623 key!(has_rpath, bool);
2624 key!(no_default_libraries, bool);
2625 key!(position_independent_executables, bool);
2626 key!(static_position_independent_executables, bool);
2627 key!(needs_plt, bool);
2628 key!(relro_level, RelroLevel)?;
2629 key!(archive_format);
2630 key!(allow_asm, bool);
2631 key!(main_needs_argc_argv, bool);
2632 key!(has_thread_local, bool);
2633 key!(obj_is_bitcode, bool);
2634 key!(forces_embed_bitcode, bool);
2635 key!(bitcode_llvm_cmdline);
2636 key!(max_atomic_width, Option<u64>);
2637 key!(min_atomic_width, Option<u64>);
2638 key!(atomic_cas, bool);
2639 key!(panic_strategy, PanicStrategy)?;
2640 key!(crt_static_allows_dylibs, bool);
2641 key!(crt_static_default, bool);
2642 key!(crt_static_respected, bool);
2643 key!(stack_probes, StackProbeType)?;
2644 key!(min_global_align, Option<u64>);
2645 key!(default_codegen_units, Option<u64>);
2646 key!(trap_unreachable, bool);
2647 key!(requires_lto, bool);
2648 key!(singlethread, bool);
2649 key!(no_builtins, bool);
2650 key!(default_hidden_visibility, bool);
2651 key!(emit_debug_gdb_scripts, bool);
2652 key!(requires_uwtable, bool);
2653 key!(default_uwtable, bool);
2654 key!(simd_types_indirect, bool);
2655 key!(limit_rdylib_exports, bool);
2656 key!(override_export_symbols, opt_list);
2657 key!(merge_functions, MergeFunctions)?;
2658 key!(mcount = "target-mcount");
2660 key!(relax_elf_relocations, bool);
2661 key!(llvm_args, list);
2662 key!(use_ctors_section, bool);
2663 key!(eh_frame_header, bool);
2664 key!(has_thumb_interworking, bool);
2665 key!(debuginfo_kind, DebuginfoKind)?;
2666 key!(split_debuginfo, SplitDebuginfo)?;
2667 key!(supported_split_debuginfo, falliable_list)?;
2668 key!(supported_sanitizers, SanitizerSet)?;
2669 key!(default_adjusted_cabi, Option<Abi>)?;
2670 key!(c_enum_min_bits, u64);
2671 key!(generate_arange_section, bool);
2672 key!(supports_stack_protector, bool);
2674 key!(entry_abi, Conv)?;
2676 if base.is_builtin {
2677 // This can cause unfortunate ICEs later down the line.
2678 return Err("may not set is_builtin for targets not built-in".into());
2680 base.update_from_cli();
2682 // Each field should have been read using `Json::remove` so any keys remaining are unused.
2683 let remaining_keys = obj.keys();
2686 TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2690 /// Load a built-in target
2691 pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2692 match *target_triple {
2693 TargetTriple::TargetTriple(ref target_triple) => {
2694 load_builtin(target_triple).expect("built-in target")
2696 TargetTriple::TargetJson { .. } => {
2697 panic!("built-in targets doesn't support target-paths")
2702 /// Search for a JSON file specifying the given target triple.
2704 /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2705 /// sysroot under the target-triple's `rustlib` directory. Note that it could also just be a
2706 /// bare filename already, so also check for that. If one of the hardcoded targets we know
2707 /// about, just return it directly.
2709 /// The error string could come from any of the APIs called, including filesystem access and
2712 target_triple: &TargetTriple,
2714 ) -> Result<(Target, TargetWarnings), String> {
2718 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2719 let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2720 let obj = serde_json::from_str(&contents).map_err(|e| e.to_string())?;
2721 Target::from_json(obj)
2724 match *target_triple {
2725 TargetTriple::TargetTriple(ref target_triple) => {
2726 // check if triple is in list of built-in targets
2727 if let Some(t) = load_builtin(target_triple) {
2728 return Ok((t, TargetWarnings::empty()));
2731 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2733 let mut target = target_triple.to_string();
2734 target.push_str(".json");
2735 PathBuf::from(target)
2738 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2740 for dir in env::split_paths(&target_path) {
2741 let p = dir.join(&path);
2743 return load_file(&p);
2747 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2749 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2750 let p = PathBuf::from_iter([
2752 Path::new(&rustlib_path),
2753 Path::new("target.json"),
2756 return load_file(&p);
2759 Err(format!("Could not find specification for target {:?}", target_triple))
2761 TargetTriple::TargetJson { ref contents, .. } => {
2762 let obj = serde_json::from_str(contents).map_err(|e| e.to_string())?;
2763 Target::from_json(obj)
2769 impl ToJson for Target {
2770 fn to_json(&self) -> Json {
2771 let mut d = serde_json::Map::new();
2772 let default: TargetOptions = Default::default();
2773 let mut target = self.clone();
2774 target.update_to_cli();
2776 macro_rules! target_val {
2778 let name = (stringify!($attr)).replace("_", "-");
2779 d.insert(name, target.$attr.to_json());
2783 macro_rules! target_option_val {
2785 let name = (stringify!($attr)).replace("_", "-");
2786 if default.$attr != target.$attr {
2787 d.insert(name, target.$attr.to_json());
2790 ($attr:ident, $json_name:expr) => {{
2791 let name = $json_name;
2792 if default.$attr != target.$attr {
2793 d.insert(name.into(), target.$attr.to_json());
2796 (link_args - $attr:ident, $json_name:expr) => {{
2797 let name = $json_name;
2798 if default.$attr != target.$attr {
2802 .map(|(k, v)| (k.desc().to_string(), v.clone()))
2803 .collect::<BTreeMap<_, _>>();
2804 d.insert(name.to_string(), obj.to_json());
2807 (env - $attr:ident) => {{
2808 let name = (stringify!($attr)).replace("_", "-");
2809 if default.$attr != target.$attr {
2813 .map(|&(ref k, ref v)| format!("{k}={v}"))
2814 .collect::<Vec<_>>();
2815 d.insert(name, obj.to_json());
2820 target_val!(llvm_target);
2821 d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2823 target_val!(data_layout);
2825 target_option_val!(is_builtin);
2826 target_option_val!(endian, "target-endian");
2827 target_option_val!(c_int_width, "target-c-int-width");
2828 target_option_val!(os);
2829 target_option_val!(env);
2830 target_option_val!(abi);
2831 target_option_val!(vendor);
2832 target_option_val!(linker);
2833 target_option_val!(linker_flavor_json, "linker-flavor");
2834 target_option_val!(lld_flavor_json, "lld-flavor");
2835 target_option_val!(linker_is_gnu_json, "linker-is-gnu");
2836 target_option_val!(pre_link_objects);
2837 target_option_val!(post_link_objects);
2838 target_option_val!(pre_link_objects_self_contained, "pre-link-objects-fallback");
2839 target_option_val!(post_link_objects_self_contained, "post-link-objects-fallback");
2840 target_option_val!(link_self_contained, "crt-objects-fallback");
2841 target_option_val!(link_args - pre_link_args_json, "pre-link-args");
2842 target_option_val!(link_args - late_link_args_json, "late-link-args");
2843 target_option_val!(link_args - late_link_args_dynamic_json, "late-link-args-dynamic");
2844 target_option_val!(link_args - late_link_args_static_json, "late-link-args-static");
2845 target_option_val!(link_args - post_link_args_json, "post-link-args");
2846 target_option_val!(link_script);
2847 target_option_val!(env - link_env);
2848 target_option_val!(link_env_remove);
2849 target_option_val!(asm_args);
2850 target_option_val!(cpu);
2851 target_option_val!(features);
2852 target_option_val!(dynamic_linking);
2853 target_option_val!(only_cdylib);
2854 target_option_val!(executables);
2855 target_option_val!(relocation_model);
2856 target_option_val!(code_model);
2857 target_option_val!(tls_model);
2858 target_option_val!(disable_redzone);
2859 target_option_val!(frame_pointer);
2860 target_option_val!(function_sections);
2861 target_option_val!(dll_prefix);
2862 target_option_val!(dll_suffix);
2863 target_option_val!(exe_suffix);
2864 target_option_val!(staticlib_prefix);
2865 target_option_val!(staticlib_suffix);
2866 target_option_val!(families, "target-family");
2867 target_option_val!(abi_return_struct_as_int);
2868 target_option_val!(is_like_aix);
2869 target_option_val!(is_like_osx);
2870 target_option_val!(is_like_solaris);
2871 target_option_val!(is_like_windows);
2872 target_option_val!(is_like_msvc);
2873 target_option_val!(is_like_wasm);
2874 target_option_val!(is_like_android);
2875 target_option_val!(default_dwarf_version);
2876 target_option_val!(allows_weak_linkage);
2877 target_option_val!(has_rpath);
2878 target_option_val!(no_default_libraries);
2879 target_option_val!(position_independent_executables);
2880 target_option_val!(static_position_independent_executables);
2881 target_option_val!(needs_plt);
2882 target_option_val!(relro_level);
2883 target_option_val!(archive_format);
2884 target_option_val!(allow_asm);
2885 target_option_val!(main_needs_argc_argv);
2886 target_option_val!(has_thread_local);
2887 target_option_val!(obj_is_bitcode);
2888 target_option_val!(forces_embed_bitcode);
2889 target_option_val!(bitcode_llvm_cmdline);
2890 target_option_val!(min_atomic_width);
2891 target_option_val!(max_atomic_width);
2892 target_option_val!(atomic_cas);
2893 target_option_val!(panic_strategy);
2894 target_option_val!(crt_static_allows_dylibs);
2895 target_option_val!(crt_static_default);
2896 target_option_val!(crt_static_respected);
2897 target_option_val!(stack_probes);
2898 target_option_val!(min_global_align);
2899 target_option_val!(default_codegen_units);
2900 target_option_val!(trap_unreachable);
2901 target_option_val!(requires_lto);
2902 target_option_val!(singlethread);
2903 target_option_val!(no_builtins);
2904 target_option_val!(default_hidden_visibility);
2905 target_option_val!(emit_debug_gdb_scripts);
2906 target_option_val!(requires_uwtable);
2907 target_option_val!(default_uwtable);
2908 target_option_val!(simd_types_indirect);
2909 target_option_val!(limit_rdylib_exports);
2910 target_option_val!(override_export_symbols);
2911 target_option_val!(merge_functions);
2912 target_option_val!(mcount, "target-mcount");
2913 target_option_val!(llvm_abiname);
2914 target_option_val!(relax_elf_relocations);
2915 target_option_val!(llvm_args);
2916 target_option_val!(use_ctors_section);
2917 target_option_val!(eh_frame_header);
2918 target_option_val!(has_thumb_interworking);
2919 target_option_val!(debuginfo_kind);
2920 target_option_val!(split_debuginfo);
2921 target_option_val!(supported_split_debuginfo);
2922 target_option_val!(supported_sanitizers);
2923 target_option_val!(c_enum_min_bits);
2924 target_option_val!(generate_arange_section);
2925 target_option_val!(supports_stack_protector);
2926 target_option_val!(entry_name);
2927 target_option_val!(entry_abi);
2929 if let Some(abi) = self.default_adjusted_cabi {
2930 d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2937 /// Either a target triple string or a path to a JSON file.
2938 #[derive(Clone, Debug)]
2939 pub enum TargetTriple {
2940 TargetTriple(String),
2942 /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
2943 /// inconsistencies as it is discarded during serialization.
2944 path_for_rustdoc: PathBuf,
2950 // Use a manual implementation to ignore the path field
2951 impl PartialEq for TargetTriple {
2952 fn eq(&self, other: &Self) -> bool {
2953 match (self, other) {
2954 (Self::TargetTriple(l0), Self::TargetTriple(r0)) => l0 == r0,
2956 Self::TargetJson { path_for_rustdoc: _, triple: l_triple, contents: l_contents },
2957 Self::TargetJson { path_for_rustdoc: _, triple: r_triple, contents: r_contents },
2958 ) => l_triple == r_triple && l_contents == r_contents,
2964 // Use a manual implementation to ignore the path field
2965 impl Hash for TargetTriple {
2966 fn hash<H: Hasher>(&self, state: &mut H) -> () {
2968 TargetTriple::TargetTriple(triple) => {
2972 TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => {
2975 contents.hash(state)
2981 // Use a manual implementation to prevent encoding the target json file path in the crate metadata
2982 impl<S: Encoder> Encodable<S> for TargetTriple {
2983 fn encode(&self, s: &mut S) {
2985 TargetTriple::TargetTriple(triple) => s.emit_enum_variant(0, |s| s.emit_str(triple)),
2986 TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => s
2987 .emit_enum_variant(1, |s| {
2989 s.emit_str(contents)
2995 impl<D: Decoder> Decodable<D> for TargetTriple {
2996 fn decode(d: &mut D) -> Self {
2997 match d.read_usize() {
2998 0 => TargetTriple::TargetTriple(d.read_str().to_owned()),
2999 1 => TargetTriple::TargetJson {
3000 path_for_rustdoc: PathBuf::new(),
3001 triple: d.read_str().to_owned(),
3002 contents: d.read_str().to_owned(),
3005 panic!("invalid enum variant tag while decoding `TargetTriple`, expected 0..2");
3012 /// Creates a target triple from the passed target triple string.
3013 pub fn from_triple(triple: &str) -> Self {
3014 TargetTriple::TargetTriple(triple.into())
3017 /// Creates a target triple from the passed target path.
3018 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
3019 let canonicalized_path = path.canonicalize()?;
3020 let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
3022 io::ErrorKind::InvalidInput,
3023 format!("target path {:?} is not a valid file: {}", canonicalized_path, err),
3026 let triple = canonicalized_path
3028 .expect("target path must not be empty")
3030 .expect("target path must be valid unicode")
3032 Ok(TargetTriple::TargetJson { path_for_rustdoc: canonicalized_path, triple, contents })
3035 /// Returns a string triple for this target.
3037 /// If this target is a path, the file name (without extension) is returned.
3038 pub fn triple(&self) -> &str {
3040 TargetTriple::TargetTriple(ref triple)
3041 | TargetTriple::TargetJson { ref triple, .. } => triple,
3045 /// Returns an extended string triple for this target.
3047 /// If this target is a path, a hash of the path is appended to the triple returned
3049 pub fn debug_triple(&self) -> String {
3050 use std::collections::hash_map::DefaultHasher;
3053 TargetTriple::TargetTriple(triple) => triple.to_owned(),
3054 TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents: content } => {
3055 let mut hasher = DefaultHasher::new();
3056 content.hash(&mut hasher);
3057 let hash = hasher.finish();
3058 format!("{}-{}", triple, hash)
3064 impl fmt::Display for TargetTriple {
3065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3066 write!(f, "{}", self.debug_triple())