rustc_target/spec/
mod.rs

1//! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
2//!
3//! Rust targets a wide variety of usecases, and in the interest of flexibility,
4//! allows new target tuples 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.
8//!
9//! # Using targets and target.json
10//!
11//! Invoking "rustc --target=${TUPLE}" will result in rustc initiating the [`Target::search`] by
12//! - checking if "$TUPLE" is a complete path to a json (ending with ".json") and loading if so
13//! - checking builtin targets for "${TUPLE}"
14//! - checking directories in "${RUST_TARGET_PATH}" for "${TUPLE}.json"
15//! - checking for "${RUSTC_SYSROOT}/lib/rustlib/${TUPLE}/target.json"
16//!
17//! Code will then be compiled using the first discovered target spec.
18//!
19//! # Defining a new target
20//!
21//! Targets are defined using a struct which additionally has serialization to and from [JSON].
22//! The `Target` struct in this module loosely corresponds with the format the JSON takes.
23//! We usually try to make the fields equivalent but we have given up on a 1:1 correspondence
24//! between the JSON and the actual structure itself.
25//!
26//! Some fields are required in every target spec, and they should be embedded in Target directly.
27//! Optional keys are in TargetOptions, but Target derefs to it, for no practical difference.
28//! Most notable is the "data-layout" field which specifies Rust's notion of sizes and alignments
29//! for several key types, such as f64, pointers, and so on.
30//!
31//! At one point we felt `-C` options should override the target's settings, like in C compilers,
32//! but that was an essentially-unmarked route for making code incorrect and Rust unsound.
33//! Confronted with programmers who prefer a compiler with a good UX instead of a lethal weapon,
34//! we have almost-entirely recanted that notion, though we hope "target modifiers" will offer
35//! a way to have a decent UX yet still extend the necessary compiler controls, without
36//! requiring a new target spec for each and every single possible target micro-variant.
37//!
38//! [JSON]: https://json.org
39
40use core::result::Result;
41use std::borrow::Cow;
42use std::collections::BTreeMap;
43use std::hash::{Hash, Hasher};
44use std::ops::{Deref, DerefMut};
45use std::path::{Path, PathBuf};
46use std::str::FromStr;
47use std::{fmt, io};
48
49use rustc_abi::{
50    Align, CanonAbi, Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors,
51};
52use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
53use rustc_error_messages::{DiagArgValue, IntoDiagArg, into_diag_arg_using_display};
54use rustc_fs_util::try_canonicalize;
55use rustc_macros::{Decodable, Encodable, HashStable_Generic};
56use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
57use rustc_span::{Symbol, kw, sym};
58use serde_json::Value;
59use tracing::debug;
60
61use crate::json::{Json, ToJson};
62use crate::spec::crt_objects::CrtObjects;
63
64pub mod crt_objects;
65
66mod abi_map;
67mod base;
68mod json;
69
70pub use abi_map::{AbiMap, AbiMapping};
71pub use base::apple;
72pub use base::avr::ef_avr_arch;
73pub use json::json_schema;
74
75/// Linker is called through a C/C++ compiler.
76#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
77pub enum Cc {
78    Yes,
79    No,
80}
81
82/// Linker is LLD.
83#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
84pub enum Lld {
85    Yes,
86    No,
87}
88
89/// All linkers have some kinds of command line interfaces and rustc needs to know which commands
90/// to use with each of them. So we cluster all such interfaces into a (somewhat arbitrary) number
91/// of classes that we call "linker flavors".
92///
93/// Technically, it's not even necessary, we can nearly always infer the flavor from linker name
94/// and target properties like `is_like_windows`/`is_like_darwin`/etc. However, the PRs originally
95/// introducing `-Clinker-flavor` (#40018 and friends) were aiming to reduce this kind of inference
96/// and provide something certain and explicitly specified instead, and that design goal is still
97/// relevant now.
98///
99/// The second goal is to keep the number of flavors to the minimum if possible.
100/// LLD somewhat forces our hand here because that linker is self-sufficient only if its executable
101/// (`argv[0]`) is named in specific way, otherwise it doesn't work and requires a
102/// `-flavor LLD_FLAVOR` argument to choose which logic to use. Our shipped `rust-lld` in
103/// particular is not named in such specific way, so it needs the flavor option, so we make our
104/// linker flavors sufficiently fine-grained to satisfy LLD without inferring its flavor from other
105/// target properties, in accordance with the first design goal.
106///
107/// The first component of the flavor is tightly coupled with the compilation target,
108/// while the `Cc` and `Lld` flags can vary within the same target.
109#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
110pub enum LinkerFlavor {
111    /// Unix-like linker with GNU extensions (both naked and compiler-wrapped forms).
112    /// Besides similar "default" Linux/BSD linkers this also includes Windows/GNU linker,
113    /// which is somewhat different because it doesn't produce ELFs.
114    Gnu(Cc, Lld),
115    /// Unix-like linker for Apple targets (both naked and compiler-wrapped forms).
116    /// Extracted from the "umbrella" `Unix` flavor due to its corresponding LLD flavor.
117    Darwin(Cc, Lld),
118    /// Unix-like linker for Wasm targets (both naked and compiler-wrapped forms).
119    /// Extracted from the "umbrella" `Unix` flavor due to its corresponding LLD flavor.
120    /// Non-LLD version does not exist, so the lld flag is currently hardcoded here.
121    WasmLld(Cc),
122    /// Basic Unix-like linker for "any other Unix" targets (Solaris/illumos, L4Re, MSP430, etc),
123    /// possibly with non-GNU extensions (both naked and compiler-wrapped forms).
124    /// LLD doesn't support any of these.
125    Unix(Cc),
126    /// MSVC-style linker for Windows and UEFI, LLD supports it.
127    Msvc(Lld),
128    /// Emscripten Compiler Frontend, a wrapper around `WasmLld(Cc::Yes)` that has a different
129    /// interface and produces some additional JavaScript output.
130    EmCc,
131    // Below: other linker-like tools with unique interfaces for exotic targets.
132    /// Linker tool for BPF.
133    Bpf,
134    /// Linker tool for Nvidia PTX.
135    Ptx,
136    /// LLVM bitcode linker that can be used as a `self-contained` linker
137    Llbc,
138}
139
140/// Linker flavors available externally through command line (`-Clinker-flavor`)
141/// or json target specifications.
142/// This set has accumulated historically, and contains both (stable and unstable) legacy values, as
143/// well as modern ones matching the internal linker flavors (`LinkerFlavor`).
144#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
145pub enum LinkerFlavorCli {
146    // Modern (unstable) flavors, with direct counterparts in `LinkerFlavor`.
147    Gnu(Cc, Lld),
148    Darwin(Cc, Lld),
149    WasmLld(Cc),
150    Unix(Cc),
151    // Note: `Msvc(Lld::No)` is also a stable value.
152    Msvc(Lld),
153    EmCc,
154    Bpf,
155    Ptx,
156    Llbc,
157
158    // Legacy stable values
159    Gcc,
160    Ld,
161    Lld(LldFlavor),
162    Em,
163}
164
165impl LinkerFlavorCli {
166    /// Returns whether this `-C linker-flavor` option is one of the unstable values.
167    pub fn is_unstable(&self) -> bool {
168        match self {
169            LinkerFlavorCli::Gnu(..)
170            | LinkerFlavorCli::Darwin(..)
171            | LinkerFlavorCli::WasmLld(..)
172            | LinkerFlavorCli::Unix(..)
173            | LinkerFlavorCli::Msvc(Lld::Yes)
174            | LinkerFlavorCli::EmCc
175            | LinkerFlavorCli::Bpf
176            | LinkerFlavorCli::Llbc
177            | LinkerFlavorCli::Ptx => true,
178            LinkerFlavorCli::Gcc
179            | LinkerFlavorCli::Ld
180            | LinkerFlavorCli::Lld(..)
181            | LinkerFlavorCli::Msvc(Lld::No)
182            | LinkerFlavorCli::Em => false,
183        }
184    }
185}
186
187crate::target_spec_enum! {
188    pub enum LldFlavor {
189        Wasm = "wasm",
190        Ld64 = "darwin",
191        Ld = "gnu",
192        Link = "link",
193    }
194
195    parse_error_type = "LLD flavor";
196}
197
198impl LinkerFlavor {
199    /// At this point the target's reference linker flavor doesn't yet exist and we need to infer
200    /// it. The inference always succeeds and gives some result, and we don't report any flavor
201    /// incompatibility errors for json target specs. The CLI flavor is used as the main source
202    /// of truth, other flags are used in case of ambiguities.
203    fn from_cli_json(cli: LinkerFlavorCli, lld_flavor: LldFlavor, is_gnu: bool) -> LinkerFlavor {
204        match cli {
205            LinkerFlavorCli::Gnu(cc, lld) => LinkerFlavor::Gnu(cc, lld),
206            LinkerFlavorCli::Darwin(cc, lld) => LinkerFlavor::Darwin(cc, lld),
207            LinkerFlavorCli::WasmLld(cc) => LinkerFlavor::WasmLld(cc),
208            LinkerFlavorCli::Unix(cc) => LinkerFlavor::Unix(cc),
209            LinkerFlavorCli::Msvc(lld) => LinkerFlavor::Msvc(lld),
210            LinkerFlavorCli::EmCc => LinkerFlavor::EmCc,
211            LinkerFlavorCli::Bpf => LinkerFlavor::Bpf,
212            LinkerFlavorCli::Llbc => LinkerFlavor::Llbc,
213            LinkerFlavorCli::Ptx => LinkerFlavor::Ptx,
214
215            // Below: legacy stable values
216            LinkerFlavorCli::Gcc => match lld_flavor {
217                LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::Yes, Lld::No),
218                LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::Yes, Lld::No),
219                LldFlavor::Wasm => LinkerFlavor::WasmLld(Cc::Yes),
220                LldFlavor::Ld | LldFlavor::Link => LinkerFlavor::Unix(Cc::Yes),
221            },
222            LinkerFlavorCli::Ld => match lld_flavor {
223                LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::No, Lld::No),
224                LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::No, Lld::No),
225                LldFlavor::Ld | LldFlavor::Wasm | LldFlavor::Link => LinkerFlavor::Unix(Cc::No),
226            },
227            LinkerFlavorCli::Lld(LldFlavor::Ld) => LinkerFlavor::Gnu(Cc::No, Lld::Yes),
228            LinkerFlavorCli::Lld(LldFlavor::Ld64) => LinkerFlavor::Darwin(Cc::No, Lld::Yes),
229            LinkerFlavorCli::Lld(LldFlavor::Wasm) => LinkerFlavor::WasmLld(Cc::No),
230            LinkerFlavorCli::Lld(LldFlavor::Link) => LinkerFlavor::Msvc(Lld::Yes),
231            LinkerFlavorCli::Em => LinkerFlavor::EmCc,
232        }
233    }
234
235    /// Returns the corresponding backwards-compatible CLI flavor.
236    fn to_cli(self) -> LinkerFlavorCli {
237        match self {
238            LinkerFlavor::Gnu(Cc::Yes, _)
239            | LinkerFlavor::Darwin(Cc::Yes, _)
240            | LinkerFlavor::WasmLld(Cc::Yes)
241            | LinkerFlavor::Unix(Cc::Yes) => LinkerFlavorCli::Gcc,
242            LinkerFlavor::Gnu(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld),
243            LinkerFlavor::Darwin(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld64),
244            LinkerFlavor::WasmLld(..) => LinkerFlavorCli::Lld(LldFlavor::Wasm),
245            LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
246                LinkerFlavorCli::Ld
247            }
248            LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Link),
249            LinkerFlavor::Msvc(..) => LinkerFlavorCli::Msvc(Lld::No),
250            LinkerFlavor::EmCc => LinkerFlavorCli::Em,
251            LinkerFlavor::Bpf => LinkerFlavorCli::Bpf,
252            LinkerFlavor::Llbc => LinkerFlavorCli::Llbc,
253            LinkerFlavor::Ptx => LinkerFlavorCli::Ptx,
254        }
255    }
256
257    /// Returns the modern CLI flavor that is the counterpart of this flavor.
258    fn to_cli_counterpart(self) -> LinkerFlavorCli {
259        match self {
260            LinkerFlavor::Gnu(cc, lld) => LinkerFlavorCli::Gnu(cc, lld),
261            LinkerFlavor::Darwin(cc, lld) => LinkerFlavorCli::Darwin(cc, lld),
262            LinkerFlavor::WasmLld(cc) => LinkerFlavorCli::WasmLld(cc),
263            LinkerFlavor::Unix(cc) => LinkerFlavorCli::Unix(cc),
264            LinkerFlavor::Msvc(lld) => LinkerFlavorCli::Msvc(lld),
265            LinkerFlavor::EmCc => LinkerFlavorCli::EmCc,
266            LinkerFlavor::Bpf => LinkerFlavorCli::Bpf,
267            LinkerFlavor::Llbc => LinkerFlavorCli::Llbc,
268            LinkerFlavor::Ptx => LinkerFlavorCli::Ptx,
269        }
270    }
271
272    fn infer_cli_hints(cli: LinkerFlavorCli) -> (Option<Cc>, Option<Lld>) {
273        match cli {
274            LinkerFlavorCli::Gnu(cc, lld) | LinkerFlavorCli::Darwin(cc, lld) => {
275                (Some(cc), Some(lld))
276            }
277            LinkerFlavorCli::WasmLld(cc) => (Some(cc), Some(Lld::Yes)),
278            LinkerFlavorCli::Unix(cc) => (Some(cc), None),
279            LinkerFlavorCli::Msvc(lld) => (Some(Cc::No), Some(lld)),
280            LinkerFlavorCli::EmCc => (Some(Cc::Yes), Some(Lld::Yes)),
281            LinkerFlavorCli::Bpf | LinkerFlavorCli::Ptx => (None, None),
282            LinkerFlavorCli::Llbc => (None, None),
283
284            // Below: legacy stable values
285            LinkerFlavorCli::Gcc => (Some(Cc::Yes), None),
286            LinkerFlavorCli::Ld => (Some(Cc::No), Some(Lld::No)),
287            LinkerFlavorCli::Lld(_) => (Some(Cc::No), Some(Lld::Yes)),
288            LinkerFlavorCli::Em => (Some(Cc::Yes), Some(Lld::Yes)),
289        }
290    }
291
292    fn infer_linker_hints(linker_stem: &str) -> Result<Self, (Option<Cc>, Option<Lld>)> {
293        // Remove any version postfix.
294        let stem = linker_stem
295            .rsplit_once('-')
296            .and_then(|(lhs, rhs)| rhs.chars().all(char::is_numeric).then_some(lhs))
297            .unwrap_or(linker_stem);
298
299        if stem == "llvm-bitcode-linker" {
300            Ok(Self::Llbc)
301        } else if stem == "emcc" // GCC/Clang can have an optional target prefix.
302            || stem == "gcc"
303            || stem.ends_with("-gcc")
304            || stem == "g++"
305            || stem.ends_with("-g++")
306            || stem == "clang"
307            || stem.ends_with("-clang")
308            || stem == "clang++"
309            || stem.ends_with("-clang++")
310        {
311            Err((Some(Cc::Yes), Some(Lld::No)))
312        } else if stem == "wasm-ld"
313            || stem.ends_with("-wasm-ld")
314            || stem == "ld.lld"
315            || stem == "lld"
316            || stem == "rust-lld"
317            || stem == "lld-link"
318        {
319            Err((Some(Cc::No), Some(Lld::Yes)))
320        } else if stem == "ld" || stem.ends_with("-ld") || stem == "link" {
321            Err((Some(Cc::No), Some(Lld::No)))
322        } else {
323            Err((None, None))
324        }
325    }
326
327    fn with_hints(self, (cc_hint, lld_hint): (Option<Cc>, Option<Lld>)) -> LinkerFlavor {
328        match self {
329            LinkerFlavor::Gnu(cc, lld) => {
330                LinkerFlavor::Gnu(cc_hint.unwrap_or(cc), lld_hint.unwrap_or(lld))
331            }
332            LinkerFlavor::Darwin(cc, lld) => {
333                LinkerFlavor::Darwin(cc_hint.unwrap_or(cc), lld_hint.unwrap_or(lld))
334            }
335            LinkerFlavor::WasmLld(cc) => LinkerFlavor::WasmLld(cc_hint.unwrap_or(cc)),
336            LinkerFlavor::Unix(cc) => LinkerFlavor::Unix(cc_hint.unwrap_or(cc)),
337            LinkerFlavor::Msvc(lld) => LinkerFlavor::Msvc(lld_hint.unwrap_or(lld)),
338            LinkerFlavor::EmCc | LinkerFlavor::Bpf | LinkerFlavor::Llbc | LinkerFlavor::Ptx => self,
339        }
340    }
341
342    pub fn with_cli_hints(self, cli: LinkerFlavorCli) -> LinkerFlavor {
343        self.with_hints(LinkerFlavor::infer_cli_hints(cli))
344    }
345
346    pub fn with_linker_hints(self, linker_stem: &str) -> LinkerFlavor {
347        match LinkerFlavor::infer_linker_hints(linker_stem) {
348            Ok(linker_flavor) => linker_flavor,
349            Err(hints) => self.with_hints(hints),
350        }
351    }
352
353    pub fn check_compatibility(self, cli: LinkerFlavorCli) -> Option<String> {
354        let compatible = |cli| {
355            // The CLI flavor should be compatible with the target if:
356            match (self, cli) {
357                // 1. they are counterparts: they have the same principal flavor.
358                (LinkerFlavor::Gnu(..), LinkerFlavorCli::Gnu(..))
359                | (LinkerFlavor::Darwin(..), LinkerFlavorCli::Darwin(..))
360                | (LinkerFlavor::WasmLld(..), LinkerFlavorCli::WasmLld(..))
361                | (LinkerFlavor::Unix(..), LinkerFlavorCli::Unix(..))
362                | (LinkerFlavor::Msvc(..), LinkerFlavorCli::Msvc(..))
363                | (LinkerFlavor::EmCc, LinkerFlavorCli::EmCc)
364                | (LinkerFlavor::Bpf, LinkerFlavorCli::Bpf)
365                | (LinkerFlavor::Llbc, LinkerFlavorCli::Llbc)
366                | (LinkerFlavor::Ptx, LinkerFlavorCli::Ptx) => return true,
367                // 2. The linker flavor is independent of target and compatible
368                (LinkerFlavor::Ptx, LinkerFlavorCli::Llbc) => return true,
369                _ => {}
370            }
371
372            // 3. or, the flavor is legacy and survives this roundtrip.
373            cli == self.with_cli_hints(cli).to_cli()
374        };
375        (!compatible(cli)).then(|| {
376            LinkerFlavorCli::all()
377                .iter()
378                .filter(|cli| compatible(**cli))
379                .map(|cli| cli.desc())
380                .intersperse(", ")
381                .collect()
382        })
383    }
384
385    pub fn lld_flavor(self) -> LldFlavor {
386        match self {
387            LinkerFlavor::Gnu(..)
388            | LinkerFlavor::Unix(..)
389            | LinkerFlavor::EmCc
390            | LinkerFlavor::Bpf
391            | LinkerFlavor::Llbc
392            | LinkerFlavor::Ptx => LldFlavor::Ld,
393            LinkerFlavor::Darwin(..) => LldFlavor::Ld64,
394            LinkerFlavor::WasmLld(..) => LldFlavor::Wasm,
395            LinkerFlavor::Msvc(..) => LldFlavor::Link,
396        }
397    }
398
399    pub fn is_gnu(self) -> bool {
400        matches!(self, LinkerFlavor::Gnu(..))
401    }
402
403    /// Returns whether the flavor uses the `lld` linker.
404    pub fn uses_lld(self) -> bool {
405        // Exhaustive match in case new flavors are added in the future.
406        match self {
407            LinkerFlavor::Gnu(_, Lld::Yes)
408            | LinkerFlavor::Darwin(_, Lld::Yes)
409            | LinkerFlavor::WasmLld(..)
410            | LinkerFlavor::EmCc
411            | LinkerFlavor::Msvc(Lld::Yes) => true,
412            LinkerFlavor::Gnu(..)
413            | LinkerFlavor::Darwin(..)
414            | LinkerFlavor::Msvc(_)
415            | LinkerFlavor::Unix(_)
416            | LinkerFlavor::Bpf
417            | LinkerFlavor::Llbc
418            | LinkerFlavor::Ptx => false,
419        }
420    }
421
422    /// Returns whether the flavor calls the linker via a C/C++ compiler.
423    pub fn uses_cc(self) -> bool {
424        // Exhaustive match in case new flavors are added in the future.
425        match self {
426            LinkerFlavor::Gnu(Cc::Yes, _)
427            | LinkerFlavor::Darwin(Cc::Yes, _)
428            | LinkerFlavor::WasmLld(Cc::Yes)
429            | LinkerFlavor::Unix(Cc::Yes)
430            | LinkerFlavor::EmCc => true,
431            LinkerFlavor::Gnu(..)
432            | LinkerFlavor::Darwin(..)
433            | LinkerFlavor::WasmLld(_)
434            | LinkerFlavor::Msvc(_)
435            | LinkerFlavor::Unix(_)
436            | LinkerFlavor::Bpf
437            | LinkerFlavor::Llbc
438            | LinkerFlavor::Ptx => false,
439        }
440    }
441
442    /// For flavors with an `Lld` component, ensure it's enabled. Otherwise, returns the given
443    /// flavor unmodified.
444    pub fn with_lld_enabled(self) -> LinkerFlavor {
445        match self {
446            LinkerFlavor::Gnu(cc, Lld::No) => LinkerFlavor::Gnu(cc, Lld::Yes),
447            LinkerFlavor::Darwin(cc, Lld::No) => LinkerFlavor::Darwin(cc, Lld::Yes),
448            LinkerFlavor::Msvc(Lld::No) => LinkerFlavor::Msvc(Lld::Yes),
449            _ => self,
450        }
451    }
452
453    /// For flavors with an `Lld` component, ensure it's disabled. Otherwise, returns the given
454    /// flavor unmodified.
455    pub fn with_lld_disabled(self) -> LinkerFlavor {
456        match self {
457            LinkerFlavor::Gnu(cc, Lld::Yes) => LinkerFlavor::Gnu(cc, Lld::No),
458            LinkerFlavor::Darwin(cc, Lld::Yes) => LinkerFlavor::Darwin(cc, Lld::No),
459            LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavor::Msvc(Lld::No),
460            _ => self,
461        }
462    }
463}
464
465macro_rules! linker_flavor_cli_impls {
466    ($(($($flavor:tt)*) $string:literal)*) => (
467        impl LinkerFlavorCli {
468            const fn all() -> &'static [LinkerFlavorCli] {
469                &[$($($flavor)*,)*]
470            }
471
472            pub const fn one_of() -> &'static str {
473                concat!("one of: ", $($string, " ",)*)
474            }
475
476            pub fn desc(self) -> &'static str {
477                match self {
478                    $($($flavor)* => $string,)*
479                }
480            }
481        }
482
483        impl FromStr for LinkerFlavorCli {
484            type Err = String;
485
486            fn from_str(s: &str) -> Result<LinkerFlavorCli, Self::Err> {
487                Ok(match s {
488                    $($string => $($flavor)*,)*
489                    _ => return Err(format!("invalid linker flavor, allowed values: {}", Self::one_of())),
490                })
491            }
492        }
493    )
494}
495
496linker_flavor_cli_impls! {
497    (LinkerFlavorCli::Gnu(Cc::No, Lld::No)) "gnu"
498    (LinkerFlavorCli::Gnu(Cc::No, Lld::Yes)) "gnu-lld"
499    (LinkerFlavorCli::Gnu(Cc::Yes, Lld::No)) "gnu-cc"
500    (LinkerFlavorCli::Gnu(Cc::Yes, Lld::Yes)) "gnu-lld-cc"
501    (LinkerFlavorCli::Darwin(Cc::No, Lld::No)) "darwin"
502    (LinkerFlavorCli::Darwin(Cc::No, Lld::Yes)) "darwin-lld"
503    (LinkerFlavorCli::Darwin(Cc::Yes, Lld::No)) "darwin-cc"
504    (LinkerFlavorCli::Darwin(Cc::Yes, Lld::Yes)) "darwin-lld-cc"
505    (LinkerFlavorCli::WasmLld(Cc::No)) "wasm-lld"
506    (LinkerFlavorCli::WasmLld(Cc::Yes)) "wasm-lld-cc"
507    (LinkerFlavorCli::Unix(Cc::No)) "unix"
508    (LinkerFlavorCli::Unix(Cc::Yes)) "unix-cc"
509    (LinkerFlavorCli::Msvc(Lld::Yes)) "msvc-lld"
510    (LinkerFlavorCli::Msvc(Lld::No)) "msvc"
511    (LinkerFlavorCli::EmCc) "em-cc"
512    (LinkerFlavorCli::Bpf) "bpf"
513    (LinkerFlavorCli::Llbc) "llbc"
514    (LinkerFlavorCli::Ptx) "ptx"
515
516    // Legacy stable flavors
517    (LinkerFlavorCli::Gcc) "gcc"
518    (LinkerFlavorCli::Ld) "ld"
519    (LinkerFlavorCli::Lld(LldFlavor::Ld)) "ld.lld"
520    (LinkerFlavorCli::Lld(LldFlavor::Ld64)) "ld64.lld"
521    (LinkerFlavorCli::Lld(LldFlavor::Link)) "lld-link"
522    (LinkerFlavorCli::Lld(LldFlavor::Wasm)) "wasm-ld"
523    (LinkerFlavorCli::Em) "em"
524}
525
526crate::json::serde_deserialize_from_str!(LinkerFlavorCli);
527impl schemars::JsonSchema for LinkerFlavorCli {
528    fn schema_name() -> std::borrow::Cow<'static, str> {
529        "LinkerFlavor".into()
530    }
531    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
532        let all: Vec<&'static str> =
533            Self::all().iter().map(|flavor| flavor.desc()).collect::<Vec<_>>();
534        schemars::json_schema! ({
535            "type": "string",
536            "enum": all
537        })
538        .into()
539    }
540}
541
542impl ToJson for LinkerFlavorCli {
543    fn to_json(&self) -> Json {
544        self.desc().to_json()
545    }
546}
547
548/// The different `-Clink-self-contained` options that can be specified in a target spec:
549/// - enabling or disabling in bulk
550/// - some target-specific pieces of inference to determine whether to use self-contained linking
551///   if `-Clink-self-contained` is not specified explicitly (e.g. on musl/mingw)
552/// - explicitly enabling some of the self-contained linking components, e.g. the linker component
553///   to use `rust-lld`
554#[derive(Clone, Copy, PartialEq, Debug)]
555pub enum LinkSelfContainedDefault {
556    /// The target spec explicitly enables self-contained linking.
557    True,
558
559    /// The target spec explicitly disables self-contained linking.
560    False,
561
562    /// The target spec requests that the self-contained mode is inferred, in the context of musl.
563    InferredForMusl,
564
565    /// The target spec requests that the self-contained mode is inferred, in the context of mingw.
566    InferredForMingw,
567
568    /// The target spec explicitly enables a list of self-contained linking components: e.g. for
569    /// targets opting into a subset of components like the CLI's `-C link-self-contained=+linker`.
570    WithComponents(LinkSelfContainedComponents),
571}
572
573/// Parses a backwards-compatible `-Clink-self-contained` option string, without components.
574impl FromStr for LinkSelfContainedDefault {
575    type Err = String;
576
577    fn from_str(s: &str) -> Result<LinkSelfContainedDefault, Self::Err> {
578        Ok(match s {
579            "false" => LinkSelfContainedDefault::False,
580            "true" | "wasm" => LinkSelfContainedDefault::True,
581            "musl" => LinkSelfContainedDefault::InferredForMusl,
582            "mingw" => LinkSelfContainedDefault::InferredForMingw,
583            _ => {
584                return Err(format!(
585                    "'{s}' is not a valid `-Clink-self-contained` default. \
586                        Use 'false', 'true', 'wasm', 'musl' or 'mingw'",
587                ));
588            }
589        })
590    }
591}
592
593crate::json::serde_deserialize_from_str!(LinkSelfContainedDefault);
594impl schemars::JsonSchema for LinkSelfContainedDefault {
595    fn schema_name() -> std::borrow::Cow<'static, str> {
596        "LinkSelfContainedDefault".into()
597    }
598    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
599        schemars::json_schema! ({
600            "type": "string",
601            "enum": ["false", "true", "wasm", "musl", "mingw"]
602        })
603        .into()
604    }
605}
606
607impl ToJson for LinkSelfContainedDefault {
608    fn to_json(&self) -> Json {
609        match *self {
610            LinkSelfContainedDefault::WithComponents(components) => {
611                // Serialize the components in a json object's `components` field, to prepare for a
612                // future where `crt-objects-fallback` is removed from the json specs and
613                // incorporated as a field here.
614                let mut map = BTreeMap::new();
615                map.insert("components", components);
616                map.to_json()
617            }
618
619            // Stable backwards-compatible values
620            LinkSelfContainedDefault::True => "true".to_json(),
621            LinkSelfContainedDefault::False => "false".to_json(),
622            LinkSelfContainedDefault::InferredForMusl => "musl".to_json(),
623            LinkSelfContainedDefault::InferredForMingw => "mingw".to_json(),
624        }
625    }
626}
627
628impl LinkSelfContainedDefault {
629    /// Returns whether the target spec has self-contained linking explicitly disabled. Used to emit
630    /// errors if the user then enables it on the CLI.
631    pub fn is_disabled(self) -> bool {
632        self == LinkSelfContainedDefault::False
633    }
634
635    /// Returns the key to use when serializing the setting to json:
636    /// - individual components in a `link-self-contained` object value
637    /// - the other variants as a backwards-compatible `crt-objects-fallback` string
638    fn json_key(self) -> &'static str {
639        match self {
640            LinkSelfContainedDefault::WithComponents(_) => "link-self-contained",
641            _ => "crt-objects-fallback",
642        }
643    }
644
645    /// Creates a `LinkSelfContainedDefault` enabling the self-contained linker for target specs
646    /// (the equivalent of `-Clink-self-contained=+linker` on the CLI).
647    pub fn with_linker() -> LinkSelfContainedDefault {
648        LinkSelfContainedDefault::WithComponents(LinkSelfContainedComponents::LINKER)
649    }
650}
651
652bitflags::bitflags! {
653    #[derive(Clone, Copy, PartialEq, Eq, Default)]
654    /// The `-C link-self-contained` components that can individually be enabled or disabled.
655    pub struct LinkSelfContainedComponents: u8 {
656        /// CRT objects (e.g. on `windows-gnu`, `musl`, `wasi` targets)
657        const CRT_OBJECTS = 1 << 0;
658        /// libc static library (e.g. on `musl`, `wasi` targets)
659        const LIBC        = 1 << 1;
660        /// libgcc/libunwind (e.g. on `windows-gnu`, `fuchsia`, `fortanix`, `gnullvm` targets)
661        const UNWIND      = 1 << 2;
662        /// Linker, dlltool, and their necessary libraries (e.g. on `windows-gnu` and for `rust-lld`)
663        const LINKER      = 1 << 3;
664        /// Sanitizer runtime libraries
665        const SANITIZERS  = 1 << 4;
666        /// Other MinGW libs and Windows import libs
667        const MINGW       = 1 << 5;
668    }
669}
670rustc_data_structures::external_bitflags_debug! { LinkSelfContainedComponents }
671
672impl LinkSelfContainedComponents {
673    /// Return the component's name.
674    ///
675    /// Returns `None` if the bitflags aren't a singular component (but a mix of multiple flags).
676    pub fn as_str(self) -> Option<&'static str> {
677        Some(match self {
678            LinkSelfContainedComponents::CRT_OBJECTS => "crto",
679            LinkSelfContainedComponents::LIBC => "libc",
680            LinkSelfContainedComponents::UNWIND => "unwind",
681            LinkSelfContainedComponents::LINKER => "linker",
682            LinkSelfContainedComponents::SANITIZERS => "sanitizers",
683            LinkSelfContainedComponents::MINGW => "mingw",
684            _ => return None,
685        })
686    }
687
688    /// Returns an array of all the components.
689    fn all_components() -> [LinkSelfContainedComponents; 6] {
690        [
691            LinkSelfContainedComponents::CRT_OBJECTS,
692            LinkSelfContainedComponents::LIBC,
693            LinkSelfContainedComponents::UNWIND,
694            LinkSelfContainedComponents::LINKER,
695            LinkSelfContainedComponents::SANITIZERS,
696            LinkSelfContainedComponents::MINGW,
697        ]
698    }
699
700    /// Returns whether at least a component is enabled.
701    pub fn are_any_components_enabled(self) -> bool {
702        !self.is_empty()
703    }
704
705    /// Returns whether `LinkSelfContainedComponents::LINKER` is enabled.
706    pub fn is_linker_enabled(self) -> bool {
707        self.contains(LinkSelfContainedComponents::LINKER)
708    }
709
710    /// Returns whether `LinkSelfContainedComponents::CRT_OBJECTS` is enabled.
711    pub fn is_crt_objects_enabled(self) -> bool {
712        self.contains(LinkSelfContainedComponents::CRT_OBJECTS)
713    }
714}
715
716impl FromStr for LinkSelfContainedComponents {
717    type Err = String;
718
719    /// Parses a single `-Clink-self-contained` well-known component, not a set of flags.
720    fn from_str(s: &str) -> Result<Self, Self::Err> {
721        Ok(match s {
722            "crto" => LinkSelfContainedComponents::CRT_OBJECTS,
723            "libc" => LinkSelfContainedComponents::LIBC,
724            "unwind" => LinkSelfContainedComponents::UNWIND,
725            "linker" => LinkSelfContainedComponents::LINKER,
726            "sanitizers" => LinkSelfContainedComponents::SANITIZERS,
727            "mingw" => LinkSelfContainedComponents::MINGW,
728            _ => {
729                return Err(format!(
730                    "'{s}' is not a valid link-self-contained component, expected 'crto', 'libc', 'unwind', 'linker', 'sanitizers', 'mingw'"
731                ));
732            }
733        })
734    }
735}
736
737crate::json::serde_deserialize_from_str!(LinkSelfContainedComponents);
738impl schemars::JsonSchema for LinkSelfContainedComponents {
739    fn schema_name() -> std::borrow::Cow<'static, str> {
740        "LinkSelfContainedComponents".into()
741    }
742    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
743        let all =
744            Self::all_components().iter().map(|component| component.as_str()).collect::<Vec<_>>();
745        schemars::json_schema! ({
746            "type": "string",
747            "enum": all,
748        })
749        .into()
750    }
751}
752
753impl ToJson for LinkSelfContainedComponents {
754    fn to_json(&self) -> Json {
755        let components: Vec<_> = Self::all_components()
756            .into_iter()
757            .filter(|c| self.contains(*c))
758            .map(|c| {
759                // We can unwrap because we're iterating over all the known singular components,
760                // not an actual set of flags where `as_str` can fail.
761                c.as_str().unwrap().to_owned()
762            })
763            .collect();
764
765        components.to_json()
766    }
767}
768
769bitflags::bitflags! {
770    /// The `-C linker-features` components that can individually be enabled or disabled.
771    ///
772    /// They are feature flags intended to be a more flexible mechanism than linker flavors, and
773    /// also to prevent a combinatorial explosion of flavors whenever a new linker feature is
774    /// required. These flags are "generic", in the sense that they can work on multiple targets on
775    /// the CLI. Otherwise, one would have to select different linkers flavors for each target.
776    ///
777    /// Here are some examples of the advantages they offer:
778    /// - default feature sets for principal flavors, or for specific targets.
779    /// - flavor-specific features: for example, clang offers automatic cross-linking with
780    ///   `--target`, which gcc-style compilers don't support. The *flavor* is still a C/C++
781    ///   compiler, and we don't need to multiply the number of flavors for this use-case. Instead,
782    ///   we can have a single `+target` feature.
783    /// - umbrella features: for example if clang accumulates more features in the future than just
784    ///   the `+target` above. That could be modeled as `+clang`.
785    /// - niche features for resolving specific issues: for example, on Apple targets the linker
786    ///   flag implementing the `as-needed` native link modifier (#99424) is only possible on
787    ///   sufficiently recent linker versions.
788    /// - still allows for discovery and automation, for example via feature detection. This can be
789    ///   useful in exotic environments/build systems.
790    #[derive(Clone, Copy, PartialEq, Eq, Default)]
791    pub struct LinkerFeatures: u8 {
792        /// Invoke the linker via a C/C++ compiler (e.g. on most unix targets).
793        const CC  = 1 << 0;
794        /// Use the lld linker, either the system lld or the self-contained linker `rust-lld`.
795        const LLD = 1 << 1;
796    }
797}
798rustc_data_structures::external_bitflags_debug! { LinkerFeatures }
799
800impl LinkerFeatures {
801    /// Parses a single `-C linker-features` well-known feature, not a set of flags.
802    pub fn from_str(s: &str) -> Option<LinkerFeatures> {
803        Some(match s {
804            "cc" => LinkerFeatures::CC,
805            "lld" => LinkerFeatures::LLD,
806            _ => return None,
807        })
808    }
809
810    /// Return the linker feature name, as would be passed on the CLI.
811    ///
812    /// Returns `None` if the bitflags aren't a singular component (but a mix of multiple flags).
813    pub fn as_str(self) -> Option<&'static str> {
814        Some(match self {
815            LinkerFeatures::CC => "cc",
816            LinkerFeatures::LLD => "lld",
817            _ => return None,
818        })
819    }
820
821    /// Returns whether the `lld` linker feature is enabled.
822    pub fn is_lld_enabled(self) -> bool {
823        self.contains(LinkerFeatures::LLD)
824    }
825
826    /// Returns whether the `cc` linker feature is enabled.
827    pub fn is_cc_enabled(self) -> bool {
828        self.contains(LinkerFeatures::CC)
829    }
830}
831
832crate::target_spec_enum! {
833    #[derive(Encodable, Decodable, HashStable_Generic)]
834    pub enum PanicStrategy {
835        Unwind = "unwind",
836        Abort = "abort",
837        ImmediateAbort = "immediate-abort",
838    }
839
840    parse_error_type = "panic strategy";
841}
842
843#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
844pub enum OnBrokenPipe {
845    Default,
846    Kill,
847    Error,
848    Inherit,
849}
850
851impl PanicStrategy {
852    pub const fn desc_symbol(&self) -> Symbol {
853        match *self {
854            PanicStrategy::Unwind => sym::unwind,
855            PanicStrategy::Abort => sym::abort,
856            PanicStrategy::ImmediateAbort => sym::immediate_abort,
857        }
858    }
859
860    pub fn unwinds(self) -> bool {
861        matches!(self, PanicStrategy::Unwind)
862    }
863}
864
865crate::target_spec_enum! {
866    pub enum RelroLevel {
867        Full = "full",
868        Partial = "partial",
869        Off = "off",
870        None = "none",
871    }
872
873    parse_error_type = "relro level";
874}
875
876impl IntoDiagArg for PanicStrategy {
877    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
878        DiagArgValue::Str(Cow::Owned(self.desc().to_string()))
879    }
880}
881
882crate::target_spec_enum! {
883    pub enum SymbolVisibility {
884        Hidden = "hidden",
885        Protected = "protected",
886        Interposable = "interposable",
887    }
888
889    parse_error_type = "symbol visibility";
890}
891
892#[derive(Clone, Debug, PartialEq, Hash)]
893pub enum SmallDataThresholdSupport {
894    None,
895    DefaultForArch,
896    LlvmModuleFlag(StaticCow<str>),
897    LlvmArg(StaticCow<str>),
898}
899
900impl FromStr for SmallDataThresholdSupport {
901    type Err = String;
902
903    fn from_str(s: &str) -> Result<Self, Self::Err> {
904        if s == "none" {
905            Ok(Self::None)
906        } else if s == "default-for-arch" {
907            Ok(Self::DefaultForArch)
908        } else if let Some(flag) = s.strip_prefix("llvm-module-flag=") {
909            Ok(Self::LlvmModuleFlag(flag.to_string().into()))
910        } else if let Some(arg) = s.strip_prefix("llvm-arg=") {
911            Ok(Self::LlvmArg(arg.to_string().into()))
912        } else {
913            Err(format!("'{s}' is not a valid value for small-data-threshold-support."))
914        }
915    }
916}
917
918crate::json::serde_deserialize_from_str!(SmallDataThresholdSupport);
919impl schemars::JsonSchema for SmallDataThresholdSupport {
920    fn schema_name() -> std::borrow::Cow<'static, str> {
921        "SmallDataThresholdSupport".into()
922    }
923    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
924        schemars::json_schema! ({
925            "type": "string",
926            "pattern": r#"^none|default-for-arch|llvm-module-flag=.+|llvm-arg=.+$"#,
927        })
928        .into()
929    }
930}
931
932impl ToJson for SmallDataThresholdSupport {
933    fn to_json(&self) -> Value {
934        match self {
935            Self::None => "none".to_json(),
936            Self::DefaultForArch => "default-for-arch".to_json(),
937            Self::LlvmModuleFlag(flag) => format!("llvm-module-flag={flag}").to_json(),
938            Self::LlvmArg(arg) => format!("llvm-arg={arg}").to_json(),
939        }
940    }
941}
942
943crate::target_spec_enum! {
944    pub enum MergeFunctions {
945        Disabled = "disabled",
946        Trampolines = "trampolines",
947        Aliases = "aliases",
948    }
949
950    parse_error_type = "value for merge-functions";
951}
952
953crate::target_spec_enum! {
954    pub enum RelocModel {
955        Static = "static",
956        Pic = "pic",
957        Pie = "pie",
958        DynamicNoPic = "dynamic-no-pic",
959        Ropi = "ropi",
960        Rwpi = "rwpi",
961        RopiRwpi = "ropi-rwpi",
962    }
963
964    parse_error_type = "relocation model";
965}
966
967impl RelocModel {
968    pub const fn desc_symbol(&self) -> Symbol {
969        match *self {
970            RelocModel::Static => kw::Static,
971            RelocModel::Pic => sym::pic,
972            RelocModel::Pie => sym::pie,
973            RelocModel::DynamicNoPic => sym::dynamic_no_pic,
974            RelocModel::Ropi => sym::ropi,
975            RelocModel::Rwpi => sym::rwpi,
976            RelocModel::RopiRwpi => sym::ropi_rwpi,
977        }
978    }
979}
980
981crate::target_spec_enum! {
982    pub enum CodeModel {
983        Tiny = "tiny",
984        Small = "small",
985        Kernel = "kernel",
986        Medium = "medium",
987        Large = "large",
988    }
989
990    parse_error_type = "code model";
991}
992
993crate::target_spec_enum! {
994    /// The float ABI setting to be configured in the LLVM target machine.
995    pub enum FloatAbi {
996        Soft = "soft",
997        Hard = "hard",
998    }
999
1000    parse_error_type = "float abi";
1001}
1002
1003crate::target_spec_enum! {
1004    /// The Rustc-specific variant of the ABI used for this target.
1005    pub enum RustcAbi {
1006        /// On x86-32 only: make use of SSE and SSE2 for ABI purposes.
1007        X86Sse2 = "x86-sse2",
1008        /// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI.
1009        X86Softfloat = "x86-softfloat",
1010    }
1011
1012    parse_error_type = "rustc abi";
1013}
1014
1015crate::target_spec_enum! {
1016    pub enum TlsModel {
1017        GeneralDynamic = "global-dynamic",
1018        LocalDynamic = "local-dynamic",
1019        InitialExec = "initial-exec",
1020        LocalExec = "local-exec",
1021        Emulated = "emulated",
1022    }
1023
1024    parse_error_type = "TLS model";
1025}
1026
1027crate::target_spec_enum! {
1028    /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
1029    pub enum LinkOutputKind {
1030        /// Dynamically linked non position-independent executable.
1031        DynamicNoPicExe = "dynamic-nopic-exe",
1032        /// Dynamically linked position-independent executable.
1033        DynamicPicExe = "dynamic-pic-exe",
1034        /// Statically linked non position-independent executable.
1035        StaticNoPicExe = "static-nopic-exe",
1036        /// Statically linked position-independent executable.
1037        StaticPicExe = "static-pic-exe",
1038        /// Regular dynamic library ("dynamically linked").
1039        DynamicDylib = "dynamic-dylib",
1040        /// Dynamic library with bundled libc ("statically linked").
1041        StaticDylib = "static-dylib",
1042        /// WASI module with a lifetime past the _initialize entry point
1043        WasiReactorExe = "wasi-reactor-exe",
1044    }
1045
1046    parse_error_type = "CRT object kind";
1047}
1048
1049impl LinkOutputKind {
1050    pub fn can_link_dylib(self) -> bool {
1051        match self {
1052            LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe => false,
1053            LinkOutputKind::DynamicNoPicExe
1054            | LinkOutputKind::DynamicPicExe
1055            | LinkOutputKind::DynamicDylib
1056            | LinkOutputKind::StaticDylib
1057            | LinkOutputKind::WasiReactorExe => true,
1058        }
1059    }
1060}
1061
1062pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
1063pub type LinkArgsCli = BTreeMap<LinkerFlavorCli, Vec<StaticCow<str>>>;
1064
1065crate::target_spec_enum! {
1066    /// Which kind of debuginfo does the target use?
1067    ///
1068    /// Useful in determining whether a target supports Split DWARF (a target with
1069    /// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example).
1070    #[derive(Default)]
1071    pub enum DebuginfoKind {
1072        /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`).
1073        #[default]
1074        Dwarf = "dwarf",
1075        /// DWARF debuginfo in dSYM files (such as on Apple platforms).
1076        DwarfDsym = "dwarf-dsym",
1077        /// Program database files (such as on Windows).
1078        Pdb = "pdb",
1079    }
1080
1081    parse_error_type = "debuginfo kind";
1082}
1083
1084crate::target_spec_enum! {
1085    #[derive(Default)]
1086    pub enum SplitDebuginfo {
1087        /// Split debug-information is disabled, meaning that on supported platforms
1088        /// you can find all debug information in the executable itself. This is
1089        /// only supported for ELF effectively.
1090        ///
1091        /// * Windows - not supported
1092        /// * macOS - don't run `dsymutil`
1093        /// * ELF - `.debug_*` sections
1094        #[default]
1095        Off = "off",
1096
1097        /// Split debug-information can be found in a "packed" location separate
1098        /// from the final artifact. This is supported on all platforms.
1099        ///
1100        /// * Windows - `*.pdb`
1101        /// * macOS - `*.dSYM` (run `dsymutil`)
1102        /// * ELF - `*.dwp` (run `thorin`)
1103        Packed = "packed",
1104
1105        /// Split debug-information can be found in individual object files on the
1106        /// filesystem. The main executable may point to the object files.
1107        ///
1108        /// * Windows - not supported
1109        /// * macOS - supported, scattered object files
1110        /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
1111        Unpacked = "unpacked",
1112    }
1113
1114    parse_error_type = "split debuginfo";
1115}
1116
1117into_diag_arg_using_display!(SplitDebuginfo);
1118
1119#[derive(Clone, Debug, PartialEq, Eq, serde_derive::Deserialize, schemars::JsonSchema)]
1120#[serde(tag = "kind")]
1121#[serde(rename_all = "kebab-case")]
1122pub enum StackProbeType {
1123    /// Don't emit any stack probes.
1124    None,
1125    /// It is harmless to use this option even on targets that do not have backend support for
1126    /// stack probes as the failure mode is the same as if no stack-probe option was specified in
1127    /// the first place.
1128    Inline,
1129    /// Call `__rust_probestack` whenever stack needs to be probed.
1130    Call,
1131    /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
1132    /// and call `__rust_probestack` otherwise.
1133    InlineOrCall {
1134        #[serde(rename = "min-llvm-version-for-inline")]
1135        min_llvm_version_for_inline: (u32, u32, u32),
1136    },
1137}
1138
1139impl ToJson for StackProbeType {
1140    fn to_json(&self) -> Json {
1141        Json::Object(match self {
1142            StackProbeType::None => {
1143                [(String::from("kind"), "none".to_json())].into_iter().collect()
1144            }
1145            StackProbeType::Inline => {
1146                [(String::from("kind"), "inline".to_json())].into_iter().collect()
1147            }
1148            StackProbeType::Call => {
1149                [(String::from("kind"), "call".to_json())].into_iter().collect()
1150            }
1151            StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
1152                (String::from("kind"), "inline-or-call".to_json()),
1153                (
1154                    String::from("min-llvm-version-for-inline"),
1155                    Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
1156                ),
1157            ]
1158            .into_iter()
1159            .collect(),
1160        })
1161    }
1162}
1163
1164#[derive(Default, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
1165pub struct SanitizerSet(u16);
1166bitflags::bitflags! {
1167    impl SanitizerSet: u16 {
1168        const ADDRESS = 1 << 0;
1169        const LEAK    = 1 << 1;
1170        const MEMORY  = 1 << 2;
1171        const THREAD  = 1 << 3;
1172        const HWADDRESS = 1 << 4;
1173        const CFI     = 1 << 5;
1174        const MEMTAG  = 1 << 6;
1175        const SHADOWCALLSTACK = 1 << 7;
1176        const KCFI    = 1 << 8;
1177        const KERNELADDRESS = 1 << 9;
1178        const SAFESTACK = 1 << 10;
1179        const DATAFLOW = 1 << 11;
1180    }
1181}
1182rustc_data_structures::external_bitflags_debug! { SanitizerSet }
1183
1184impl SanitizerSet {
1185    // Taken from LLVM's sanitizer compatibility logic:
1186    // https://github.com/llvm/llvm-project/blob/release/18.x/clang/lib/Driver/SanitizerArgs.cpp#L512
1187    const MUTUALLY_EXCLUSIVE: &'static [(SanitizerSet, SanitizerSet)] = &[
1188        (SanitizerSet::ADDRESS, SanitizerSet::MEMORY),
1189        (SanitizerSet::ADDRESS, SanitizerSet::THREAD),
1190        (SanitizerSet::ADDRESS, SanitizerSet::HWADDRESS),
1191        (SanitizerSet::ADDRESS, SanitizerSet::MEMTAG),
1192        (SanitizerSet::ADDRESS, SanitizerSet::KERNELADDRESS),
1193        (SanitizerSet::ADDRESS, SanitizerSet::SAFESTACK),
1194        (SanitizerSet::LEAK, SanitizerSet::MEMORY),
1195        (SanitizerSet::LEAK, SanitizerSet::THREAD),
1196        (SanitizerSet::LEAK, SanitizerSet::KERNELADDRESS),
1197        (SanitizerSet::LEAK, SanitizerSet::SAFESTACK),
1198        (SanitizerSet::MEMORY, SanitizerSet::THREAD),
1199        (SanitizerSet::MEMORY, SanitizerSet::HWADDRESS),
1200        (SanitizerSet::MEMORY, SanitizerSet::KERNELADDRESS),
1201        (SanitizerSet::MEMORY, SanitizerSet::SAFESTACK),
1202        (SanitizerSet::THREAD, SanitizerSet::HWADDRESS),
1203        (SanitizerSet::THREAD, SanitizerSet::KERNELADDRESS),
1204        (SanitizerSet::THREAD, SanitizerSet::SAFESTACK),
1205        (SanitizerSet::HWADDRESS, SanitizerSet::MEMTAG),
1206        (SanitizerSet::HWADDRESS, SanitizerSet::KERNELADDRESS),
1207        (SanitizerSet::HWADDRESS, SanitizerSet::SAFESTACK),
1208        (SanitizerSet::CFI, SanitizerSet::KCFI),
1209        (SanitizerSet::MEMTAG, SanitizerSet::KERNELADDRESS),
1210        (SanitizerSet::KERNELADDRESS, SanitizerSet::SAFESTACK),
1211    ];
1212
1213    /// Return sanitizer's name
1214    ///
1215    /// Returns none if the flags is a set of sanitizers numbering not exactly one.
1216    pub fn as_str(self) -> Option<&'static str> {
1217        Some(match self {
1218            SanitizerSet::ADDRESS => "address",
1219            SanitizerSet::CFI => "cfi",
1220            SanitizerSet::DATAFLOW => "dataflow",
1221            SanitizerSet::KCFI => "kcfi",
1222            SanitizerSet::KERNELADDRESS => "kernel-address",
1223            SanitizerSet::LEAK => "leak",
1224            SanitizerSet::MEMORY => "memory",
1225            SanitizerSet::MEMTAG => "memtag",
1226            SanitizerSet::SAFESTACK => "safestack",
1227            SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
1228            SanitizerSet::THREAD => "thread",
1229            SanitizerSet::HWADDRESS => "hwaddress",
1230            _ => return None,
1231        })
1232    }
1233
1234    pub fn mutually_exclusive(self) -> Option<(SanitizerSet, SanitizerSet)> {
1235        Self::MUTUALLY_EXCLUSIVE
1236            .into_iter()
1237            .find(|&(a, b)| self.contains(*a) && self.contains(*b))
1238            .copied()
1239    }
1240}
1241
1242/// Formats a sanitizer set as a comma separated list of sanitizers' names.
1243impl fmt::Display for SanitizerSet {
1244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245        let mut first = true;
1246        for s in *self {
1247            let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {s:?}"));
1248            if !first {
1249                f.write_str(", ")?;
1250            }
1251            f.write_str(name)?;
1252            first = false;
1253        }
1254        Ok(())
1255    }
1256}
1257
1258impl FromStr for SanitizerSet {
1259    type Err = String;
1260    fn from_str(s: &str) -> Result<Self, Self::Err> {
1261        Ok(match s {
1262            "address" => SanitizerSet::ADDRESS,
1263            "cfi" => SanitizerSet::CFI,
1264            "dataflow" => SanitizerSet::DATAFLOW,
1265            "kcfi" => SanitizerSet::KCFI,
1266            "kernel-address" => SanitizerSet::KERNELADDRESS,
1267            "leak" => SanitizerSet::LEAK,
1268            "memory" => SanitizerSet::MEMORY,
1269            "memtag" => SanitizerSet::MEMTAG,
1270            "safestack" => SanitizerSet::SAFESTACK,
1271            "shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
1272            "thread" => SanitizerSet::THREAD,
1273            "hwaddress" => SanitizerSet::HWADDRESS,
1274            s => return Err(format!("unknown sanitizer {s}")),
1275        })
1276    }
1277}
1278
1279crate::json::serde_deserialize_from_str!(SanitizerSet);
1280impl schemars::JsonSchema for SanitizerSet {
1281    fn schema_name() -> std::borrow::Cow<'static, str> {
1282        "SanitizerSet".into()
1283    }
1284    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1285        let all = Self::all().iter().map(|sanitizer| sanitizer.as_str()).collect::<Vec<_>>();
1286        schemars::json_schema! ({
1287            "type": "string",
1288            "enum": all,
1289        })
1290        .into()
1291    }
1292}
1293
1294impl ToJson for SanitizerSet {
1295    fn to_json(&self) -> Json {
1296        self.into_iter()
1297            .map(|v| Some(v.as_str()?.to_json()))
1298            .collect::<Option<Vec<_>>>()
1299            .unwrap_or_default()
1300            .to_json()
1301    }
1302}
1303
1304crate::target_spec_enum! {
1305    pub enum FramePointer {
1306        /// Forces the machine code generator to always preserve the frame pointers.
1307        Always = "always",
1308        /// Forces the machine code generator to preserve the frame pointers except for the leaf
1309        /// functions (i.e. those that don't call other functions).
1310        NonLeaf = "non-leaf",
1311        /// Allows the machine code generator to omit the frame pointers.
1312        ///
1313        /// This option does not guarantee that the frame pointers will be omitted.
1314        MayOmit = "may-omit",
1315    }
1316
1317    parse_error_type = "frame pointer";
1318}
1319
1320impl FramePointer {
1321    /// It is intended that the "force frame pointer" transition is "one way"
1322    /// so this convenience assures such if used
1323    #[inline]
1324    pub fn ratchet(&mut self, rhs: FramePointer) -> FramePointer {
1325        *self = match (*self, rhs) {
1326            (FramePointer::Always, _) | (_, FramePointer::Always) => FramePointer::Always,
1327            (FramePointer::NonLeaf, _) | (_, FramePointer::NonLeaf) => FramePointer::NonLeaf,
1328            _ => FramePointer::MayOmit,
1329        };
1330        *self
1331    }
1332}
1333
1334crate::target_spec_enum! {
1335    /// Controls use of stack canaries.
1336    pub enum StackProtector {
1337        /// Disable stack canary generation.
1338        None = "none",
1339
1340        /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
1341        /// llvm/docs/LangRef.rst). This triggers stack canary generation in
1342        /// functions which contain an array of a byte-sized type with more than
1343        /// eight elements.
1344        Basic = "basic",
1345
1346        /// On LLVM, mark all generated LLVM functions with the `sspstrong`
1347        /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
1348        /// generation in functions which either contain an array, or which take
1349        /// the address of a local variable.
1350        Strong = "strong",
1351
1352        /// Generate stack canaries in all functions.
1353        All = "all",
1354    }
1355
1356    parse_error_type = "stack protector";
1357}
1358
1359into_diag_arg_using_display!(StackProtector);
1360
1361crate::target_spec_enum! {
1362    pub enum BinaryFormat {
1363        Coff = "coff",
1364        Elf = "elf",
1365        MachO = "mach-o",
1366        Wasm = "wasm",
1367        Xcoff = "xcoff",
1368    }
1369
1370    parse_error_type = "binary format";
1371}
1372
1373impl BinaryFormat {
1374    /// Returns [`object::BinaryFormat`] for given `BinaryFormat`
1375    pub fn to_object(&self) -> object::BinaryFormat {
1376        match self {
1377            Self::Coff => object::BinaryFormat::Coff,
1378            Self::Elf => object::BinaryFormat::Elf,
1379            Self::MachO => object::BinaryFormat::MachO,
1380            Self::Wasm => object::BinaryFormat::Wasm,
1381            Self::Xcoff => object::BinaryFormat::Xcoff,
1382        }
1383    }
1384}
1385
1386impl ToJson for Align {
1387    fn to_json(&self) -> Json {
1388        self.bits().to_json()
1389    }
1390}
1391
1392macro_rules! supported_targets {
1393    ( $(($tuple:literal, $module:ident),)+ ) => {
1394        mod targets {
1395            $(pub(crate) mod $module;)+
1396        }
1397
1398        /// List of supported targets
1399        pub static TARGETS: &[&str] = &[$($tuple),+];
1400
1401        fn load_builtin(target: &str) -> Option<Target> {
1402            let t = match target {
1403                $( $tuple => targets::$module::target(), )+
1404                _ => return None,
1405            };
1406            debug!("got builtin target: {:?}", t);
1407            Some(t)
1408        }
1409
1410        fn load_all_builtins() -> impl Iterator<Item = Target> {
1411            [
1412                $( targets::$module::target, )+
1413            ]
1414            .into_iter()
1415            .map(|f| f())
1416        }
1417
1418        #[cfg(test)]
1419        mod tests {
1420            // Cannot put this into a separate file without duplication, make an exception.
1421            $(
1422                #[test] // `#[test]`
1423                fn $module() {
1424                    crate::spec::targets::$module::target().test_target()
1425                }
1426            )+
1427        }
1428    };
1429}
1430
1431supported_targets! {
1432    ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
1433    ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
1434    ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
1435    ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
1436    ("loongarch64-unknown-linux-gnu", loongarch64_unknown_linux_gnu),
1437    ("loongarch64-unknown-linux-musl", loongarch64_unknown_linux_musl),
1438    ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
1439    ("m68k-unknown-none-elf", m68k_unknown_none_elf),
1440    ("csky-unknown-linux-gnuabiv2", csky_unknown_linux_gnuabiv2),
1441    ("csky-unknown-linux-gnuabiv2hf", csky_unknown_linux_gnuabiv2hf),
1442    ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
1443    ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
1444    ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
1445    ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
1446    ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
1447    ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
1448    ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
1449    ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
1450    ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
1451    ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
1452    ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
1453    ("powerpc-unknown-linux-muslspe", powerpc_unknown_linux_muslspe),
1454    ("powerpc64-ibm-aix", powerpc64_ibm_aix),
1455    ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
1456    ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
1457    ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
1458    ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
1459    ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
1460    ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
1461    ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
1462    ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
1463    ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
1464    ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
1465    ("armeb-unknown-linux-gnueabi", armeb_unknown_linux_gnueabi),
1466    ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
1467    ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
1468    ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
1469    ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
1470    ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
1471    ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
1472    ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
1473    ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
1474    ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
1475    ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
1476    ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
1477    ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
1478    ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
1479    ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
1480    ("aarch64_be-unknown-linux-musl", aarch64_be_unknown_linux_musl),
1481    ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
1482    ("i686-unknown-linux-musl", i686_unknown_linux_musl),
1483    ("i586-unknown-linux-musl", i586_unknown_linux_musl),
1484    ("mips-unknown-linux-musl", mips_unknown_linux_musl),
1485    ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
1486    ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
1487    ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
1488    ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
1489    ("hexagon-unknown-none-elf", hexagon_unknown_none_elf),
1490
1491    ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
1492    ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
1493
1494    ("i686-linux-android", i686_linux_android),
1495    ("x86_64-linux-android", x86_64_linux_android),
1496    ("arm-linux-androideabi", arm_linux_androideabi),
1497    ("armv7-linux-androideabi", armv7_linux_androideabi),
1498    ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
1499    ("aarch64-linux-android", aarch64_linux_android),
1500    ("riscv64-linux-android", riscv64_linux_android),
1501
1502    ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
1503    ("armv6-unknown-freebsd", armv6_unknown_freebsd),
1504    ("armv7-unknown-freebsd", armv7_unknown_freebsd),
1505    ("i686-unknown-freebsd", i686_unknown_freebsd),
1506    ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
1507    ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
1508    ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
1509    ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
1510    ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
1511
1512    ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
1513
1514    ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
1515    ("i686-unknown-openbsd", i686_unknown_openbsd),
1516    ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
1517    ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
1518    ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
1519    ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
1520    ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
1521
1522    ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
1523    ("aarch64_be-unknown-netbsd", aarch64_be_unknown_netbsd),
1524    ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
1525    ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
1526    ("i586-unknown-netbsd", i586_unknown_netbsd),
1527    ("i686-unknown-netbsd", i686_unknown_netbsd),
1528    ("mipsel-unknown-netbsd", mipsel_unknown_netbsd),
1529    ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
1530    ("riscv64gc-unknown-netbsd", riscv64gc_unknown_netbsd),
1531    ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
1532    ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
1533
1534    ("i686-unknown-haiku", i686_unknown_haiku),
1535    ("x86_64-unknown-haiku", x86_64_unknown_haiku),
1536
1537    ("i686-unknown-hurd-gnu", i686_unknown_hurd_gnu),
1538    ("x86_64-unknown-hurd-gnu", x86_64_unknown_hurd_gnu),
1539
1540    ("aarch64-apple-darwin", aarch64_apple_darwin),
1541    ("arm64e-apple-darwin", arm64e_apple_darwin),
1542    ("x86_64-apple-darwin", x86_64_apple_darwin),
1543    ("x86_64h-apple-darwin", x86_64h_apple_darwin),
1544    ("i686-apple-darwin", i686_apple_darwin),
1545
1546    ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia),
1547    ("riscv64gc-unknown-fuchsia", riscv64gc_unknown_fuchsia),
1548    ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
1549
1550    ("avr-none", avr_none),
1551
1552    ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
1553
1554    ("aarch64-unknown-redox", aarch64_unknown_redox),
1555    ("i586-unknown-redox", i586_unknown_redox),
1556    ("riscv64gc-unknown-redox", riscv64gc_unknown_redox),
1557    ("x86_64-unknown-redox", x86_64_unknown_redox),
1558
1559    ("x86_64-unknown-managarm-mlibc", x86_64_unknown_managarm_mlibc),
1560    ("aarch64-unknown-managarm-mlibc", aarch64_unknown_managarm_mlibc),
1561    ("riscv64gc-unknown-managarm-mlibc", riscv64gc_unknown_managarm_mlibc),
1562
1563    ("i386-apple-ios", i386_apple_ios),
1564    ("x86_64-apple-ios", x86_64_apple_ios),
1565    ("aarch64-apple-ios", aarch64_apple_ios),
1566    ("arm64e-apple-ios", arm64e_apple_ios),
1567    ("armv7s-apple-ios", armv7s_apple_ios),
1568    ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
1569    ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
1570    ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
1571
1572    ("aarch64-apple-tvos", aarch64_apple_tvos),
1573    ("aarch64-apple-tvos-sim", aarch64_apple_tvos_sim),
1574    ("arm64e-apple-tvos", arm64e_apple_tvos),
1575    ("x86_64-apple-tvos", x86_64_apple_tvos),
1576
1577    ("armv7k-apple-watchos", armv7k_apple_watchos),
1578    ("arm64_32-apple-watchos", arm64_32_apple_watchos),
1579    ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
1580    ("aarch64-apple-watchos", aarch64_apple_watchos),
1581    ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
1582
1583    ("aarch64-apple-visionos", aarch64_apple_visionos),
1584    ("aarch64-apple-visionos-sim", aarch64_apple_visionos_sim),
1585
1586    ("armebv7r-none-eabi", armebv7r_none_eabi),
1587    ("armebv7r-none-eabihf", armebv7r_none_eabihf),
1588    ("armv7r-none-eabi", armv7r_none_eabi),
1589    ("armv7r-none-eabihf", armv7r_none_eabihf),
1590    ("armv8r-none-eabihf", armv8r_none_eabihf),
1591
1592    ("armv7-rtems-eabihf", armv7_rtems_eabihf),
1593
1594    ("x86_64-pc-solaris", x86_64_pc_solaris),
1595    ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1596
1597    ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1598    ("aarch64-unknown-illumos", aarch64_unknown_illumos),
1599
1600    ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1601    ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1602    ("x86_64-win7-windows-gnu", x86_64_win7_windows_gnu),
1603    ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1604    ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1605    ("i686-win7-windows-gnu", i686_win7_windows_gnu),
1606
1607    ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1608    ("i686-pc-windows-gnullvm", i686_pc_windows_gnullvm),
1609    ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1610
1611    ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1612    ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1613    ("arm64ec-pc-windows-msvc", arm64ec_pc_windows_msvc),
1614    ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1615    ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1616    ("x86_64-win7-windows-msvc", x86_64_win7_windows_msvc),
1617    ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1618    ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1619    ("i686-win7-windows-msvc", i686_win7_windows_msvc),
1620    ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1621    ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1622
1623    ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1624    ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1625    ("wasm32v1-none", wasm32v1_none),
1626    ("wasm32-wasip1", wasm32_wasip1),
1627    ("wasm32-wasip2", wasm32_wasip2),
1628    ("wasm32-wasip3", wasm32_wasip3),
1629    ("wasm32-wasip1-threads", wasm32_wasip1_threads),
1630    ("wasm32-wali-linux-musl", wasm32_wali_linux_musl),
1631    ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1632
1633    ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1634    ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1635    ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1636    ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1637    ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1638    ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1639    ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1640
1641    ("armv7a-none-eabi", armv7a_none_eabi),
1642    ("armv7a-none-eabihf", armv7a_none_eabihf),
1643    ("armv7a-nuttx-eabi", armv7a_nuttx_eabi),
1644    ("armv7a-nuttx-eabihf", armv7a_nuttx_eabihf),
1645    ("armv7a-vex-v5", armv7a_vex_v5),
1646
1647    ("msp430-none-elf", msp430_none_elf),
1648
1649    ("aarch64_be-unknown-hermit", aarch64_be_unknown_hermit),
1650    ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1651    ("riscv64gc-unknown-hermit", riscv64gc_unknown_hermit),
1652    ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1653    ("x86_64-unknown-motor", x86_64_unknown_motor),
1654
1655    ("x86_64-unikraft-linux-musl", x86_64_unikraft_linux_musl),
1656
1657    ("armv7-unknown-trusty", armv7_unknown_trusty),
1658    ("aarch64-unknown-trusty", aarch64_unknown_trusty),
1659    ("x86_64-unknown-trusty", x86_64_unknown_trusty),
1660
1661    ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1662    ("riscv32im-risc0-zkvm-elf", riscv32im_risc0_zkvm_elf),
1663    ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1664    ("riscv32ima-unknown-none-elf", riscv32ima_unknown_none_elf),
1665    ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1666    ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1667    ("riscv32imac-esp-espidf", riscv32imac_esp_espidf),
1668    ("riscv32imafc-esp-espidf", riscv32imafc_esp_espidf),
1669
1670    ("riscv32e-unknown-none-elf", riscv32e_unknown_none_elf),
1671    ("riscv32em-unknown-none-elf", riscv32em_unknown_none_elf),
1672    ("riscv32emc-unknown-none-elf", riscv32emc_unknown_none_elf),
1673
1674    ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1675    ("riscv32imafc-unknown-none-elf", riscv32imafc_unknown_none_elf),
1676    ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1677    ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1678    ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1679    ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1680    ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1681    ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1682    ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1683    ("riscv64a23-unknown-linux-gnu", riscv64a23_unknown_linux_gnu),
1684
1685    ("sparc-unknown-none-elf", sparc_unknown_none_elf),
1686
1687    ("loongarch32-unknown-none", loongarch32_unknown_none),
1688    ("loongarch32-unknown-none-softfloat", loongarch32_unknown_none_softfloat),
1689    ("loongarch64-unknown-none", loongarch64_unknown_none),
1690    ("loongarch64-unknown-none-softfloat", loongarch64_unknown_none_softfloat),
1691
1692    ("aarch64-unknown-none", aarch64_unknown_none),
1693    ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1694    ("aarch64_be-unknown-none-softfloat", aarch64_be_unknown_none_softfloat),
1695    ("aarch64-unknown-nuttx", aarch64_unknown_nuttx),
1696
1697    ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1698
1699    ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1700    ("i686-unknown-uefi", i686_unknown_uefi),
1701    ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1702
1703    ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1704
1705    ("amdgcn-amd-amdhsa", amdgcn_amd_amdhsa),
1706
1707    ("xtensa-esp32-none-elf", xtensa_esp32_none_elf),
1708    ("xtensa-esp32-espidf", xtensa_esp32_espidf),
1709    ("xtensa-esp32s2-none-elf", xtensa_esp32s2_none_elf),
1710    ("xtensa-esp32s2-espidf", xtensa_esp32s2_espidf),
1711    ("xtensa-esp32s3-none-elf", xtensa_esp32s3_none_elf),
1712    ("xtensa-esp32s3-espidf", xtensa_esp32s3_espidf),
1713
1714    ("i686-wrs-vxworks", i686_wrs_vxworks),
1715    ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1716    ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1717    ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1718    ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1719    ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1720    ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1721    ("riscv32-wrs-vxworks", riscv32_wrs_vxworks),
1722    ("riscv64-wrs-vxworks", riscv64_wrs_vxworks),
1723
1724    ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1725    ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1726    ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1727
1728    ("mipsel-sony-psp", mipsel_sony_psp),
1729    ("mipsel-sony-psx", mipsel_sony_psx),
1730    ("mipsel-unknown-none", mipsel_unknown_none),
1731    ("mips-mti-none-elf", mips_mti_none_elf),
1732    ("mipsel-mti-none-elf", mipsel_mti_none_elf),
1733    ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1734    ("armv4t-none-eabi", armv4t_none_eabi),
1735    ("thumbv5te-none-eabi", thumbv5te_none_eabi),
1736    ("armv5te-none-eabi", armv5te_none_eabi),
1737
1738    ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1739    ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1740    ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1741
1742    ("bpfeb-unknown-none", bpfeb_unknown_none),
1743    ("bpfel-unknown-none", bpfel_unknown_none),
1744
1745    ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1746
1747    ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1748
1749    ("armv7-sony-vita-newlibeabihf", armv7_sony_vita_newlibeabihf),
1750
1751    ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1752    ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1753
1754    ("x86_64-unknown-none", x86_64_unknown_none),
1755
1756    ("aarch64-unknown-teeos", aarch64_unknown_teeos),
1757
1758    ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1759
1760    ("aarch64-unknown-nto-qnx700", aarch64_unknown_nto_qnx700),
1761    ("aarch64-unknown-nto-qnx710", aarch64_unknown_nto_qnx710),
1762    ("aarch64-unknown-nto-qnx710_iosock", aarch64_unknown_nto_qnx710_iosock),
1763    ("aarch64-unknown-nto-qnx800", aarch64_unknown_nto_qnx800),
1764    ("x86_64-pc-nto-qnx710", x86_64_pc_nto_qnx710),
1765    ("x86_64-pc-nto-qnx710_iosock", x86_64_pc_nto_qnx710_iosock),
1766    ("x86_64-pc-nto-qnx800", x86_64_pc_nto_qnx800),
1767    ("i686-pc-nto-qnx700", i686_pc_nto_qnx700),
1768
1769    ("aarch64-unknown-linux-ohos", aarch64_unknown_linux_ohos),
1770    ("armv7-unknown-linux-ohos", armv7_unknown_linux_ohos),
1771    ("loongarch64-unknown-linux-ohos", loongarch64_unknown_linux_ohos),
1772    ("x86_64-unknown-linux-ohos", x86_64_unknown_linux_ohos),
1773
1774    ("x86_64-unknown-linux-none", x86_64_unknown_linux_none),
1775
1776    ("thumbv6m-nuttx-eabi", thumbv6m_nuttx_eabi),
1777    ("thumbv7a-nuttx-eabi", thumbv7a_nuttx_eabi),
1778    ("thumbv7a-nuttx-eabihf", thumbv7a_nuttx_eabihf),
1779    ("thumbv7m-nuttx-eabi", thumbv7m_nuttx_eabi),
1780    ("thumbv7em-nuttx-eabi", thumbv7em_nuttx_eabi),
1781    ("thumbv7em-nuttx-eabihf", thumbv7em_nuttx_eabihf),
1782    ("thumbv8m.base-nuttx-eabi", thumbv8m_base_nuttx_eabi),
1783    ("thumbv8m.main-nuttx-eabi", thumbv8m_main_nuttx_eabi),
1784    ("thumbv8m.main-nuttx-eabihf", thumbv8m_main_nuttx_eabihf),
1785    ("riscv32imc-unknown-nuttx-elf", riscv32imc_unknown_nuttx_elf),
1786    ("riscv32imac-unknown-nuttx-elf", riscv32imac_unknown_nuttx_elf),
1787    ("riscv32imafc-unknown-nuttx-elf", riscv32imafc_unknown_nuttx_elf),
1788    ("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf),
1789    ("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf),
1790    ("x86_64-lynx-lynxos178", x86_64_lynx_lynxos178),
1791
1792    ("x86_64-pc-cygwin", x86_64_pc_cygwin),
1793}
1794
1795/// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1796macro_rules! cvs {
1797    () => {
1798        ::std::borrow::Cow::Borrowed(&[])
1799    };
1800    ($($x:expr),+ $(,)?) => {
1801        ::std::borrow::Cow::Borrowed(&[
1802            $(
1803                ::std::borrow::Cow::Borrowed($x),
1804            )*
1805        ])
1806    };
1807}
1808
1809pub(crate) use cvs;
1810
1811/// Warnings encountered when parsing the target `json`.
1812///
1813/// Includes fields that weren't recognized and fields that don't have the expected type.
1814#[derive(Debug, PartialEq)]
1815pub struct TargetWarnings {
1816    unused_fields: Vec<String>,
1817}
1818
1819impl TargetWarnings {
1820    pub fn empty() -> Self {
1821        Self { unused_fields: Vec::new() }
1822    }
1823
1824    pub fn warning_messages(&self) -> Vec<String> {
1825        let mut warnings = vec![];
1826        if !self.unused_fields.is_empty() {
1827            warnings.push(format!(
1828                "target json file contains unused fields: {}",
1829                self.unused_fields.join(", ")
1830            ));
1831        }
1832        warnings
1833    }
1834}
1835
1836/// For the [`Target::check_consistency`] function, determines whether the given target is a builtin or a JSON
1837/// target.
1838#[derive(Copy, Clone, Debug, PartialEq)]
1839enum TargetKind {
1840    Json,
1841    Builtin,
1842}
1843
1844/// Everything `rustc` knows about how to compile for a specific target.
1845///
1846/// Every field here must be specified, and has no default value.
1847#[derive(PartialEq, Clone, Debug)]
1848pub struct Target {
1849    /// Unversioned target tuple to pass to LLVM.
1850    ///
1851    /// Target tuples can optionally contain an OS version (notably Apple targets), which rustc
1852    /// cannot know without querying the environment.
1853    ///
1854    /// Use `rustc_codegen_ssa::back::versioned_llvm_target` if you need the full LLVM target.
1855    pub llvm_target: StaticCow<str>,
1856    /// Metadata about a target, for example the description or tier.
1857    /// Used for generating target documentation.
1858    pub metadata: TargetMetadata,
1859    /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1860    pub pointer_width: u16,
1861    /// Architecture to use for ABI considerations. Valid options include: "x86",
1862    /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1863    pub arch: StaticCow<str>,
1864    /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1865    pub data_layout: StaticCow<str>,
1866    /// Optional settings with defaults.
1867    pub options: TargetOptions,
1868}
1869
1870/// Metadata about a target like the description or tier.
1871/// Part of #120745.
1872/// All fields are optional for now, but intended to be required in the future.
1873#[derive(Default, PartialEq, Clone, Debug)]
1874pub struct TargetMetadata {
1875    /// A short description of the target including platform requirements,
1876    /// for example "64-bit Linux (kernel 3.2+, glibc 2.17+)".
1877    pub description: Option<StaticCow<str>>,
1878    /// The tier of the target. 1, 2 or 3.
1879    pub tier: Option<u64>,
1880    /// Whether the Rust project ships host tools for a target.
1881    pub host_tools: Option<bool>,
1882    /// Whether a target has the `std` library. This is usually true for targets running
1883    /// on an operating system.
1884    pub std: Option<bool>,
1885}
1886
1887impl Target {
1888    pub fn parse_data_layout(&self) -> Result<TargetDataLayout, TargetDataLayoutErrors<'_>> {
1889        let mut dl = TargetDataLayout::parse_from_llvm_datalayout_string(
1890            &self.data_layout,
1891            self.options.default_address_space,
1892        )?;
1893
1894        // Perform consistency checks against the Target information.
1895        if dl.endian != self.endian {
1896            return Err(TargetDataLayoutErrors::InconsistentTargetArchitecture {
1897                dl: dl.endian.as_str(),
1898                target: self.endian.as_str(),
1899            });
1900        }
1901
1902        let target_pointer_width: u64 = self.pointer_width.into();
1903        let dl_pointer_size: u64 = dl.pointer_size().bits();
1904        if dl_pointer_size != target_pointer_width {
1905            return Err(TargetDataLayoutErrors::InconsistentTargetPointerWidth {
1906                pointer_size: dl_pointer_size,
1907                target: self.pointer_width,
1908            });
1909        }
1910
1911        dl.c_enum_min_size = Integer::from_size(Size::from_bits(
1912            self.c_enum_min_bits.unwrap_or(self.c_int_width as _),
1913        ))
1914        .map_err(|err| TargetDataLayoutErrors::InvalidBitsSize { err })?;
1915
1916        Ok(dl)
1917    }
1918}
1919
1920pub trait HasTargetSpec {
1921    fn target_spec(&self) -> &Target;
1922}
1923
1924impl HasTargetSpec for Target {
1925    #[inline]
1926    fn target_spec(&self) -> &Target {
1927        self
1928    }
1929}
1930
1931/// x86 (32-bit) abi options.
1932#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1933pub struct X86Abi {
1934    /// On x86-32 targets, the regparm N causes the compiler to pass arguments
1935    /// in registers EAX, EDX, and ECX instead of on the stack.
1936    pub regparm: Option<u32>,
1937    /// Override the default ABI to return small structs in registers
1938    pub reg_struct_return: bool,
1939}
1940
1941pub trait HasX86AbiOpt {
1942    fn x86_abi_opt(&self) -> X86Abi;
1943}
1944
1945type StaticCow<T> = Cow<'static, T>;
1946
1947/// Optional aspects of a target specification.
1948///
1949/// This has an implementation of `Default`, see each field for what the default is. In general,
1950/// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1951///
1952/// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1953/// construction, all its fields logically belong to `Target` and available from `Target`
1954/// through `Deref` impls.
1955#[derive(PartialEq, Clone, Debug)]
1956pub struct TargetOptions {
1957    /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1958    pub endian: Endian,
1959    /// Width of c_int type. Defaults to "32".
1960    pub c_int_width: u16,
1961    /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1962    /// "none" implies a bare metal target without `std` library.
1963    /// A couple of targets having `std` also use "unknown" as an `os` value,
1964    /// but they are exceptions.
1965    pub os: StaticCow<str>,
1966    /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1967    pub env: StaticCow<str>,
1968    /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1969    /// or `"eabihf"`. Defaults to "".
1970    /// This field is *not* forwarded directly to LLVM; its primary purpose is `cfg(target_abi)`.
1971    /// However, parts of the backend do check this field for specific values to enable special behavior.
1972    pub abi: StaticCow<str>,
1973    /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1974    pub vendor: StaticCow<str>,
1975
1976    /// Linker to invoke
1977    pub linker: Option<StaticCow<str>>,
1978    /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1979    /// on the command line. Defaults to `LinkerFlavor::Gnu(Cc::Yes, Lld::No)`.
1980    pub linker_flavor: LinkerFlavor,
1981    linker_flavor_json: LinkerFlavorCli,
1982    lld_flavor_json: LldFlavor,
1983    linker_is_gnu_json: bool,
1984
1985    /// Objects to link before and after all other object code.
1986    pub pre_link_objects: CrtObjects,
1987    pub post_link_objects: CrtObjects,
1988    /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1989    pub pre_link_objects_self_contained: CrtObjects,
1990    pub post_link_objects_self_contained: CrtObjects,
1991    /// Behavior for the self-contained linking mode: inferred for some targets, or explicitly
1992    /// enabled (in bulk, or with individual components).
1993    pub link_self_contained: LinkSelfContainedDefault,
1994
1995    /// Linker arguments that are passed *before* any user-defined libraries.
1996    pub pre_link_args: LinkArgs,
1997    pre_link_args_json: LinkArgsCli,
1998    /// Linker arguments that are unconditionally passed after any
1999    /// user-defined but before post-link objects. Standard platform
2000    /// libraries that should be always be linked to, usually go here.
2001    pub late_link_args: LinkArgs,
2002    late_link_args_json: LinkArgsCli,
2003    /// Linker arguments used in addition to `late_link_args` if at least one
2004    /// Rust dependency is dynamically linked.
2005    pub late_link_args_dynamic: LinkArgs,
2006    late_link_args_dynamic_json: LinkArgsCli,
2007    /// Linker arguments used in addition to `late_link_args` if all Rust
2008    /// dependencies are statically linked.
2009    pub late_link_args_static: LinkArgs,
2010    late_link_args_static_json: LinkArgsCli,
2011    /// Linker arguments that are unconditionally passed *after* any
2012    /// user-defined libraries.
2013    pub post_link_args: LinkArgs,
2014    post_link_args_json: LinkArgsCli,
2015
2016    /// Optional link script applied to `dylib` and `executable` crate types.
2017    /// This is a string containing the script, not a path. Can only be applied
2018    /// to linkers where linker flavor matches `LinkerFlavor::Gnu(..)`.
2019    pub link_script: Option<StaticCow<str>>,
2020    /// Environment variables to be set for the linker invocation.
2021    pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
2022    /// Environment variables to be removed for the linker invocation.
2023    pub link_env_remove: StaticCow<[StaticCow<str>]>,
2024
2025    /// Extra arguments to pass to the external assembler (when used)
2026    pub asm_args: StaticCow<[StaticCow<str>]>,
2027
2028    /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
2029    /// to "generic".
2030    pub cpu: StaticCow<str>,
2031    /// Whether a cpu needs to be explicitly set.
2032    /// Set to true if there is no default cpu. Defaults to false.
2033    pub need_explicit_cpu: bool,
2034    /// Default target features to pass to LLVM. These features overwrite
2035    /// `-Ctarget-cpu` but can be overwritten with `-Ctarget-features`.
2036    /// Corresponds to `llc -mattr=$features`.
2037    /// Note that these are LLVM feature names, not Rust feature names!
2038    ///
2039    /// Generally it is a bad idea to use negative target features because they often interact very
2040    /// poorly with how `-Ctarget-cpu` works. Instead, try to use a lower "base CPU" and enable the
2041    /// features you want to use.
2042    pub features: StaticCow<str>,
2043    /// Direct or use GOT indirect to reference external data symbols
2044    pub direct_access_external_data: Option<bool>,
2045    /// Whether dynamic linking is available on this target. Defaults to false.
2046    pub dynamic_linking: bool,
2047    /// Whether dynamic linking can export TLS globals. Defaults to true.
2048    pub dll_tls_export: bool,
2049    /// If dynamic linking is available, whether only cdylibs are supported.
2050    pub only_cdylib: bool,
2051    /// Whether executables are available on this target. Defaults to true.
2052    pub executables: bool,
2053    /// Relocation model to use in object file. Corresponds to `llc
2054    /// -relocation-model=$relocation_model`. Defaults to `Pic`.
2055    pub relocation_model: RelocModel,
2056    /// Code model to use. Corresponds to `llc -code-model=$code_model`.
2057    /// Defaults to `None` which means "inherited from the base LLVM target".
2058    pub code_model: Option<CodeModel>,
2059    /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
2060    /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
2061    pub tls_model: TlsModel,
2062    /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
2063    pub disable_redzone: bool,
2064    /// Frame pointer mode for this target. Defaults to `MayOmit`.
2065    pub frame_pointer: FramePointer,
2066    /// Emit each function in its own section. Defaults to true.
2067    pub function_sections: bool,
2068    /// String to prepend to the name of every dynamic library. Defaults to "lib".
2069    pub dll_prefix: StaticCow<str>,
2070    /// String to append to the name of every dynamic library. Defaults to ".so".
2071    pub dll_suffix: StaticCow<str>,
2072    /// String to append to the name of every executable.
2073    pub exe_suffix: StaticCow<str>,
2074    /// String to prepend to the name of every static library. Defaults to "lib".
2075    pub staticlib_prefix: StaticCow<str>,
2076    /// String to append to the name of every static library. Defaults to ".a".
2077    pub staticlib_suffix: StaticCow<str>,
2078    /// Values of the `target_family` cfg set for this target.
2079    ///
2080    /// Common options are: "unix", "windows". Defaults to no families.
2081    ///
2082    /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
2083    pub families: StaticCow<[StaticCow<str>]>,
2084    /// Whether the target toolchain's ABI supports returning small structs as an integer.
2085    pub abi_return_struct_as_int: bool,
2086    /// Whether the target toolchain is like AIX's. Linker options on AIX are special and it uses
2087    /// XCOFF as binary format. Defaults to false.
2088    pub is_like_aix: bool,
2089    /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
2090    /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
2091    /// Also indicates whether to use Apple-specific ABI changes, such as extending function
2092    /// parameters to 32-bits.
2093    pub is_like_darwin: bool,
2094    /// Whether the target toolchain is like Solaris's.
2095    /// Only useful for compiling against Illumos/Solaris,
2096    /// as they have a different set of linker flags. Defaults to false.
2097    pub is_like_solaris: bool,
2098    /// Whether the target is like Windows.
2099    /// This is a combination of several more specific properties represented as a single flag:
2100    ///   - The target uses a Windows ABI,
2101    ///   - uses PE/COFF as a format for object code,
2102    ///   - uses Windows-style dllexport/dllimport for shared libraries,
2103    ///   - uses import libraries and .def files for symbol exports,
2104    ///   - executables support setting a subsystem.
2105    pub is_like_windows: bool,
2106    /// Whether the target is like MSVC.
2107    /// This is a combination of several more specific properties represented as a single flag:
2108    ///   - The target has all the properties from `is_like_windows`
2109    ///     (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
2110    ///   - has some MSVC-specific Windows ABI properties,
2111    ///   - uses a link.exe-like linker,
2112    ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
2113    ///   - uses SEH-based unwinding,
2114    ///   - supports control flow guard mechanism.
2115    pub is_like_msvc: bool,
2116    /// Whether a target toolchain is like WASM.
2117    pub is_like_wasm: bool,
2118    /// Whether a target toolchain is like Android, implying a Linux kernel and a Bionic libc
2119    pub is_like_android: bool,
2120    /// Whether a target toolchain is like VEXos, the operating system used by the VEX Robotics V5 Brain.
2121    pub is_like_vexos: bool,
2122    /// Target's binary file format. Defaults to BinaryFormat::Elf
2123    pub binary_format: BinaryFormat,
2124    /// Default supported version of DWARF on this platform.
2125    /// Useful because some platforms (osx, bsd) only want up to DWARF2.
2126    pub default_dwarf_version: u32,
2127    /// The MinGW toolchain has a known issue that prevents it from correctly
2128    /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
2129    /// symbol needs its own COMDAT section, weak linkage implies a large
2130    /// number sections that easily exceeds the given limit for larger
2131    /// codebases. Consequently we want a way to disallow weak linkage on some
2132    /// platforms.
2133    pub allows_weak_linkage: bool,
2134    /// Whether the linker support rpaths or not. Defaults to false.
2135    pub has_rpath: bool,
2136    /// Whether to disable linking to the default libraries, typically corresponds
2137    /// to `-nodefaultlibs`. Defaults to true.
2138    pub no_default_libraries: bool,
2139    /// Dynamically linked executables can be compiled as position independent
2140    /// if the default relocation model of position independent code is not
2141    /// changed. This is a requirement to take advantage of ASLR, as otherwise
2142    /// the functions in the executable are not randomized and can be used
2143    /// during an exploit of a vulnerability in any code.
2144    pub position_independent_executables: bool,
2145    /// Executables that are both statically linked and position-independent are supported.
2146    pub static_position_independent_executables: bool,
2147    /// Determines if the target always requires using the PLT for indirect
2148    /// library calls or not. This controls the default value of the `-Z plt` flag.
2149    pub plt_by_default: bool,
2150    /// Either partial, full, or off. Full RELRO makes the dynamic linker
2151    /// resolve all symbols at startup and marks the GOT read-only before
2152    /// starting the program, preventing overwriting the GOT.
2153    pub relro_level: RelroLevel,
2154    /// Format that archives should be emitted in. This affects whether we use
2155    /// LLVM to assemble an archive or fall back to the system linker, and
2156    /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
2157    /// the system linker to be used.
2158    pub archive_format: StaticCow<str>,
2159    /// Is asm!() allowed? Defaults to true.
2160    pub allow_asm: bool,
2161    /// Whether the runtime startup code requires the `main` function be passed
2162    /// `argc` and `argv` values.
2163    pub main_needs_argc_argv: bool,
2164
2165    /// Flag indicating whether #[thread_local] is available for this target.
2166    pub has_thread_local: bool,
2167    /// This is mainly for easy compatibility with emscripten.
2168    /// If we give emcc .o files that are actually .bc files it
2169    /// will 'just work'.
2170    pub obj_is_bitcode: bool,
2171
2172    /// Don't use this field; instead use the `.min_atomic_width()` method.
2173    pub min_atomic_width: Option<u64>,
2174
2175    /// Don't use this field; instead use the `.max_atomic_width()` method.
2176    pub max_atomic_width: Option<u64>,
2177
2178    /// Whether the target supports atomic CAS operations natively
2179    pub atomic_cas: bool,
2180
2181    /// Panic strategy: "unwind" or "abort"
2182    pub panic_strategy: PanicStrategy,
2183
2184    /// Whether or not linking dylibs to a static CRT is allowed.
2185    pub crt_static_allows_dylibs: bool,
2186    /// Whether or not the CRT is statically linked by default.
2187    pub crt_static_default: bool,
2188    /// Whether or not crt-static is respected by the compiler (or is a no-op).
2189    pub crt_static_respected: bool,
2190
2191    /// The implementation of stack probes to use.
2192    pub stack_probes: StackProbeType,
2193
2194    /// The minimum alignment for global symbols.
2195    pub min_global_align: Option<Align>,
2196
2197    /// Default number of codegen units to use in debug mode
2198    pub default_codegen_units: Option<u64>,
2199
2200    /// Default codegen backend used for this target. Defaults to `None`.
2201    ///
2202    /// If `None`, then `CFG_DEFAULT_CODEGEN_BACKEND` environmental variable captured when
2203    /// compiling `rustc` will be used instead (or llvm if it is not set).
2204    ///
2205    /// N.B. when *using* the compiler, backend can always be overridden with `-Zcodegen-backend`.
2206    ///
2207    /// This was added by WaffleLapkin in #116793. The motivation is a rustc fork that requires a
2208    /// custom codegen backend for a particular target.
2209    pub default_codegen_backend: Option<StaticCow<str>>,
2210
2211    /// Whether to generate trap instructions in places where optimization would
2212    /// otherwise produce control flow that falls through into unrelated memory.
2213    pub trap_unreachable: bool,
2214
2215    /// This target requires everything to be compiled with LTO to emit a final
2216    /// executable, aka there is no native linker for this target.
2217    pub requires_lto: bool,
2218
2219    /// This target has no support for threads.
2220    pub singlethread: bool,
2221
2222    /// Whether library functions call lowering/optimization is disabled in LLVM
2223    /// for this target unconditionally.
2224    pub no_builtins: bool,
2225
2226    /// The default visibility for symbols in this target.
2227    ///
2228    /// This value typically shouldn't be accessed directly, but through the
2229    /// `rustc_session::Session::default_visibility` method, which allows `rustc` users to override
2230    /// this setting using cmdline flags.
2231    pub default_visibility: Option<SymbolVisibility>,
2232
2233    /// Whether a .debug_gdb_scripts section will be added to the output object file
2234    pub emit_debug_gdb_scripts: bool,
2235
2236    /// Whether or not to unconditionally `uwtable` attributes on functions,
2237    /// typically because the platform needs to unwind for things like stack
2238    /// unwinders.
2239    pub requires_uwtable: bool,
2240
2241    /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
2242    /// is not specified and `uwtable` is not required on this target.
2243    pub default_uwtable: bool,
2244
2245    /// Whether or not SIMD types are passed by reference in the Rust ABI,
2246    /// typically required if a target can be compiled with a mixed set of
2247    /// target features. This is `true` by default, and `false` for targets like
2248    /// wasm32 where the whole program either has simd or not.
2249    pub simd_types_indirect: bool,
2250
2251    /// Pass a list of symbol which should be exported in the dylib to the linker.
2252    pub limit_rdylib_exports: bool,
2253
2254    /// If set, have the linker export exactly these symbols, instead of using
2255    /// the usual logic to figure this out from the crate itself.
2256    pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
2257
2258    /// Determines how or whether the MergeFunctions LLVM pass should run for
2259    /// this target. Either "disabled", "trampolines", or "aliases".
2260    /// The MergeFunctions pass is generally useful, but some targets may need
2261    /// to opt out. The default is "aliases".
2262    ///
2263    /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
2264    pub merge_functions: MergeFunctions,
2265
2266    /// Use platform dependent mcount function
2267    pub mcount: StaticCow<str>,
2268
2269    /// Use LLVM intrinsic for mcount function name
2270    pub llvm_mcount_intrinsic: Option<StaticCow<str>>,
2271
2272    /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
2273    /// and the `-target-abi` flag in llc. In the LLVM API this is `MCOptions.ABIName`.
2274    pub llvm_abiname: StaticCow<str>,
2275
2276    /// Control the float ABI to use, for architectures that support it. The only architecture we
2277    /// currently use this for is ARM. Corresponds to the `-float-abi` flag in llc. In the LLVM API
2278    /// this is `FloatABIType`. (clang's `-mfloat-abi` is similar but more complicated since it
2279    /// can also affect the `soft-float` target feature.)
2280    ///
2281    /// If not provided, LLVM will infer the float ABI from the target triple (`llvm_target`).
2282    pub llvm_floatabi: Option<FloatAbi>,
2283
2284    /// Picks a specific ABI for this target. This is *not* just for "Rust" ABI functions,
2285    /// it can also affect "C" ABI functions; the point is that this flag is interpreted by
2286    /// rustc and not forwarded to LLVM.
2287    /// So far, this is only used on x86.
2288    pub rustc_abi: Option<RustcAbi>,
2289
2290    /// Whether or not RelaxElfRelocation flag will be passed to the linker
2291    pub relax_elf_relocations: bool,
2292
2293    /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
2294    pub llvm_args: StaticCow<[StaticCow<str>]>,
2295
2296    /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
2297    /// to false (uses .init_array).
2298    pub use_ctors_section: bool,
2299
2300    /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
2301    /// used to locate unwinding information is passed
2302    /// (only has effect if the linker is `ld`-like).
2303    pub eh_frame_header: bool,
2304
2305    /// Is true if the target is an ARM architecture using thumb v1 which allows for
2306    /// thumb and arm interworking.
2307    pub has_thumb_interworking: bool,
2308
2309    /// Which kind of debuginfo is used by this target?
2310    pub debuginfo_kind: DebuginfoKind,
2311    /// How to handle split debug information, if at all. Specifying `None` has
2312    /// target-specific meaning.
2313    pub split_debuginfo: SplitDebuginfo,
2314    /// Which kinds of split debuginfo are supported by the target?
2315    pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
2316
2317    /// The sanitizers supported by this target
2318    ///
2319    /// Note that the support here is at a codegen level. If the machine code with sanitizer
2320    /// enabled can generated on this target, but the necessary supporting libraries are not
2321    /// distributed with the target, the sanitizer should still appear in this list for the target.
2322    pub supported_sanitizers: SanitizerSet,
2323
2324    /// Minimum number of bits in #[repr(C)] enum. Defaults to the size of c_int
2325    pub c_enum_min_bits: Option<u64>,
2326
2327    /// Whether or not the DWARF `.debug_aranges` section should be generated.
2328    pub generate_arange_section: bool,
2329
2330    /// Whether the target supports stack canary checks. `true` by default,
2331    /// since this is most common among tier 1 and tier 2 targets.
2332    pub supports_stack_protector: bool,
2333
2334    /// The name of entry function.
2335    /// Default value is "main"
2336    pub entry_name: StaticCow<str>,
2337
2338    /// The ABI of the entry function.
2339    /// Default value is `CanonAbi::C`
2340    pub entry_abi: CanonAbi,
2341
2342    /// Whether the target supports XRay instrumentation.
2343    pub supports_xray: bool,
2344
2345    /// The default address space for this target. When using LLVM as a backend, most targets simply
2346    /// use LLVM's default address space (0). Some other targets, such as CHERI targets, use a
2347    /// custom default address space (in this specific case, `200`).
2348    pub default_address_space: rustc_abi::AddressSpace,
2349
2350    /// Whether the targets supports -Z small-data-threshold
2351    small_data_threshold_support: SmallDataThresholdSupport,
2352}
2353
2354/// Add arguments for the given flavor and also for its "twin" flavors
2355/// that have a compatible command line interface.
2356fn add_link_args_iter(
2357    link_args: &mut LinkArgs,
2358    flavor: LinkerFlavor,
2359    args: impl Iterator<Item = StaticCow<str>> + Clone,
2360) {
2361    let mut insert = |flavor| link_args.entry(flavor).or_default().extend(args.clone());
2362    insert(flavor);
2363    match flavor {
2364        LinkerFlavor::Gnu(cc, lld) => {
2365            assert_eq!(lld, Lld::No);
2366            insert(LinkerFlavor::Gnu(cc, Lld::Yes));
2367        }
2368        LinkerFlavor::Darwin(cc, lld) => {
2369            assert_eq!(lld, Lld::No);
2370            insert(LinkerFlavor::Darwin(cc, Lld::Yes));
2371        }
2372        LinkerFlavor::Msvc(lld) => {
2373            assert_eq!(lld, Lld::No);
2374            insert(LinkerFlavor::Msvc(Lld::Yes));
2375        }
2376        LinkerFlavor::WasmLld(..)
2377        | LinkerFlavor::Unix(..)
2378        | LinkerFlavor::EmCc
2379        | LinkerFlavor::Bpf
2380        | LinkerFlavor::Llbc
2381        | LinkerFlavor::Ptx => {}
2382    }
2383}
2384
2385fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
2386    add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
2387}
2388
2389impl TargetOptions {
2390    pub fn supports_comdat(&self) -> bool {
2391        // XCOFF and MachO don't support COMDAT.
2392        !self.is_like_aix && !self.is_like_darwin
2393    }
2394}
2395
2396impl TargetOptions {
2397    fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
2398        let mut link_args = LinkArgs::new();
2399        add_link_args(&mut link_args, flavor, args);
2400        link_args
2401    }
2402
2403    fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
2404        add_link_args(&mut self.pre_link_args, flavor, args);
2405    }
2406
2407    fn update_from_cli(&mut self) {
2408        self.linker_flavor = LinkerFlavor::from_cli_json(
2409            self.linker_flavor_json,
2410            self.lld_flavor_json,
2411            self.linker_is_gnu_json,
2412        );
2413        for (args, args_json) in [
2414            (&mut self.pre_link_args, &self.pre_link_args_json),
2415            (&mut self.late_link_args, &self.late_link_args_json),
2416            (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
2417            (&mut self.late_link_args_static, &self.late_link_args_static_json),
2418            (&mut self.post_link_args, &self.post_link_args_json),
2419        ] {
2420            args.clear();
2421            for (flavor, args_json) in args_json {
2422                let linker_flavor = self.linker_flavor.with_cli_hints(*flavor);
2423                // Normalize to no lld to avoid asserts.
2424                let linker_flavor = match linker_flavor {
2425                    LinkerFlavor::Gnu(cc, _) => LinkerFlavor::Gnu(cc, Lld::No),
2426                    LinkerFlavor::Darwin(cc, _) => LinkerFlavor::Darwin(cc, Lld::No),
2427                    LinkerFlavor::Msvc(_) => LinkerFlavor::Msvc(Lld::No),
2428                    _ => linker_flavor,
2429                };
2430                if !args.contains_key(&linker_flavor) {
2431                    add_link_args_iter(args, linker_flavor, args_json.iter().cloned());
2432                }
2433            }
2434        }
2435    }
2436
2437    fn update_to_cli(&mut self) {
2438        self.linker_flavor_json = self.linker_flavor.to_cli_counterpart();
2439        self.lld_flavor_json = self.linker_flavor.lld_flavor();
2440        self.linker_is_gnu_json = self.linker_flavor.is_gnu();
2441        for (args, args_json) in [
2442            (&self.pre_link_args, &mut self.pre_link_args_json),
2443            (&self.late_link_args, &mut self.late_link_args_json),
2444            (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
2445            (&self.late_link_args_static, &mut self.late_link_args_static_json),
2446            (&self.post_link_args, &mut self.post_link_args_json),
2447        ] {
2448            *args_json = args
2449                .iter()
2450                .map(|(flavor, args)| (flavor.to_cli_counterpart(), args.clone()))
2451                .collect();
2452        }
2453    }
2454}
2455
2456impl Default for TargetOptions {
2457    /// Creates a set of "sane defaults" for any target. This is still
2458    /// incomplete, and if used for compilation, will certainly not work.
2459    fn default() -> TargetOptions {
2460        TargetOptions {
2461            endian: Endian::Little,
2462            c_int_width: 32,
2463            os: "none".into(),
2464            env: "".into(),
2465            abi: "".into(),
2466            vendor: "unknown".into(),
2467            linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
2468            linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
2469            linker_flavor_json: LinkerFlavorCli::Gcc,
2470            lld_flavor_json: LldFlavor::Ld,
2471            linker_is_gnu_json: true,
2472            link_script: None,
2473            asm_args: cvs![],
2474            cpu: "generic".into(),
2475            need_explicit_cpu: false,
2476            features: "".into(),
2477            direct_access_external_data: None,
2478            dynamic_linking: false,
2479            dll_tls_export: true,
2480            only_cdylib: false,
2481            executables: true,
2482            relocation_model: RelocModel::Pic,
2483            code_model: None,
2484            tls_model: TlsModel::GeneralDynamic,
2485            disable_redzone: false,
2486            frame_pointer: FramePointer::MayOmit,
2487            function_sections: true,
2488            dll_prefix: "lib".into(),
2489            dll_suffix: ".so".into(),
2490            exe_suffix: "".into(),
2491            staticlib_prefix: "lib".into(),
2492            staticlib_suffix: ".a".into(),
2493            families: cvs![],
2494            abi_return_struct_as_int: false,
2495            is_like_aix: false,
2496            is_like_darwin: false,
2497            is_like_solaris: false,
2498            is_like_windows: false,
2499            is_like_msvc: false,
2500            is_like_wasm: false,
2501            is_like_android: false,
2502            is_like_vexos: false,
2503            binary_format: BinaryFormat::Elf,
2504            default_dwarf_version: 4,
2505            allows_weak_linkage: true,
2506            has_rpath: false,
2507            no_default_libraries: true,
2508            position_independent_executables: false,
2509            static_position_independent_executables: false,
2510            plt_by_default: true,
2511            relro_level: RelroLevel::None,
2512            pre_link_objects: Default::default(),
2513            post_link_objects: Default::default(),
2514            pre_link_objects_self_contained: Default::default(),
2515            post_link_objects_self_contained: Default::default(),
2516            link_self_contained: LinkSelfContainedDefault::False,
2517            pre_link_args: LinkArgs::new(),
2518            pre_link_args_json: LinkArgsCli::new(),
2519            late_link_args: LinkArgs::new(),
2520            late_link_args_json: LinkArgsCli::new(),
2521            late_link_args_dynamic: LinkArgs::new(),
2522            late_link_args_dynamic_json: LinkArgsCli::new(),
2523            late_link_args_static: LinkArgs::new(),
2524            late_link_args_static_json: LinkArgsCli::new(),
2525            post_link_args: LinkArgs::new(),
2526            post_link_args_json: LinkArgsCli::new(),
2527            link_env: cvs![],
2528            link_env_remove: cvs![],
2529            archive_format: "gnu".into(),
2530            main_needs_argc_argv: true,
2531            allow_asm: true,
2532            has_thread_local: false,
2533            obj_is_bitcode: false,
2534            min_atomic_width: None,
2535            max_atomic_width: None,
2536            atomic_cas: true,
2537            panic_strategy: PanicStrategy::Unwind,
2538            crt_static_allows_dylibs: false,
2539            crt_static_default: false,
2540            crt_static_respected: false,
2541            stack_probes: StackProbeType::None,
2542            min_global_align: None,
2543            default_codegen_units: None,
2544            default_codegen_backend: None,
2545            trap_unreachable: true,
2546            requires_lto: false,
2547            singlethread: false,
2548            no_builtins: false,
2549            default_visibility: None,
2550            emit_debug_gdb_scripts: true,
2551            requires_uwtable: false,
2552            default_uwtable: false,
2553            simd_types_indirect: true,
2554            limit_rdylib_exports: true,
2555            override_export_symbols: None,
2556            merge_functions: MergeFunctions::Aliases,
2557            mcount: "mcount".into(),
2558            llvm_mcount_intrinsic: None,
2559            llvm_abiname: "".into(),
2560            llvm_floatabi: None,
2561            rustc_abi: None,
2562            relax_elf_relocations: false,
2563            llvm_args: cvs![],
2564            use_ctors_section: false,
2565            eh_frame_header: true,
2566            has_thumb_interworking: false,
2567            debuginfo_kind: Default::default(),
2568            split_debuginfo: Default::default(),
2569            // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
2570            supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
2571            supported_sanitizers: SanitizerSet::empty(),
2572            c_enum_min_bits: None,
2573            generate_arange_section: true,
2574            supports_stack_protector: true,
2575            entry_name: "main".into(),
2576            entry_abi: CanonAbi::C,
2577            supports_xray: false,
2578            default_address_space: rustc_abi::AddressSpace::ZERO,
2579            small_data_threshold_support: SmallDataThresholdSupport::DefaultForArch,
2580        }
2581    }
2582}
2583
2584/// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
2585/// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
2586/// this `Deref` implementation is no longer necessary.
2587impl Deref for Target {
2588    type Target = TargetOptions;
2589
2590    #[inline]
2591    fn deref(&self) -> &Self::Target {
2592        &self.options
2593    }
2594}
2595impl DerefMut for Target {
2596    #[inline]
2597    fn deref_mut(&mut self) -> &mut Self::Target {
2598        &mut self.options
2599    }
2600}
2601
2602impl Target {
2603    pub fn is_abi_supported(&self, abi: ExternAbi) -> bool {
2604        let abi_map = AbiMap::from_target(self);
2605        abi_map.canonize_abi(abi, false).is_mapped()
2606    }
2607
2608    /// Minimum integer size in bits that this target can perform atomic
2609    /// operations on.
2610    pub fn min_atomic_width(&self) -> u64 {
2611        self.min_atomic_width.unwrap_or(8)
2612    }
2613
2614    /// Maximum integer size in bits that this target can perform atomic
2615    /// operations on.
2616    pub fn max_atomic_width(&self) -> u64 {
2617        self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
2618    }
2619
2620    /// Check some basic consistency of the current target. For JSON targets we are less strict;
2621    /// some of these checks are more guidelines than strict rules.
2622    fn check_consistency(&self, kind: TargetKind) -> Result<(), String> {
2623        macro_rules! check {
2624            ($b:expr, $($msg:tt)*) => {
2625                if !$b {
2626                    return Err(format!($($msg)*));
2627                }
2628            }
2629        }
2630        macro_rules! check_eq {
2631            ($left:expr, $right:expr, $($msg:tt)*) => {
2632                if ($left) != ($right) {
2633                    return Err(format!($($msg)*));
2634                }
2635            }
2636        }
2637        macro_rules! check_ne {
2638            ($left:expr, $right:expr, $($msg:tt)*) => {
2639                if ($left) == ($right) {
2640                    return Err(format!($($msg)*));
2641                }
2642            }
2643        }
2644        macro_rules! check_matches {
2645            ($left:expr, $right:pat, $($msg:tt)*) => {
2646                if !matches!($left, $right) {
2647                    return Err(format!($($msg)*));
2648                }
2649            }
2650        }
2651
2652        check_eq!(
2653            self.is_like_darwin,
2654            self.vendor == "apple",
2655            "`is_like_darwin` must be set if and only if `vendor` is `apple`"
2656        );
2657        check_eq!(
2658            self.is_like_solaris,
2659            self.os == "solaris" || self.os == "illumos",
2660            "`is_like_solaris` must be set if and only if `os` is `solaris` or `illumos`"
2661        );
2662        check_eq!(
2663            self.is_like_windows,
2664            self.os == "windows" || self.os == "uefi" || self.os == "cygwin",
2665            "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`"
2666        );
2667        check_eq!(
2668            self.is_like_wasm,
2669            self.arch == "wasm32" || self.arch == "wasm64",
2670            "`is_like_wasm` must be set if and only if `arch` is `wasm32` or `wasm64`"
2671        );
2672        if self.is_like_msvc {
2673            check!(self.is_like_windows, "if `is_like_msvc` is set, `is_like_windows` must be set");
2674        }
2675        if self.os == "emscripten" {
2676            check!(self.is_like_wasm, "the `emcscripten` os only makes sense on wasm-like targets");
2677        }
2678
2679        // Check that default linker flavor is compatible with some other key properties.
2680        check_eq!(
2681            self.is_like_darwin,
2682            matches!(self.linker_flavor, LinkerFlavor::Darwin(..)),
2683            "`linker_flavor` must be `darwin` if and only if `is_like_darwin` is set"
2684        );
2685        check_eq!(
2686            self.is_like_msvc,
2687            matches!(self.linker_flavor, LinkerFlavor::Msvc(..)),
2688            "`linker_flavor` must be `msvc` if and only if `is_like_msvc` is set"
2689        );
2690        check_eq!(
2691            self.is_like_wasm && self.os != "emscripten",
2692            matches!(self.linker_flavor, LinkerFlavor::WasmLld(..)),
2693            "`linker_flavor` must be `wasm-lld` if and only if `is_like_wasm` is set and the `os` is not `emscripten`",
2694        );
2695        check_eq!(
2696            self.os == "emscripten",
2697            matches!(self.linker_flavor, LinkerFlavor::EmCc),
2698            "`linker_flavor` must be `em-cc` if and only if `os` is `emscripten`"
2699        );
2700        check_eq!(
2701            self.arch == "bpf",
2702            matches!(self.linker_flavor, LinkerFlavor::Bpf),
2703            "`linker_flavor` must be `bpf` if and only if `arch` is `bpf`"
2704        );
2705        check_eq!(
2706            self.arch == "nvptx64",
2707            matches!(self.linker_flavor, LinkerFlavor::Ptx),
2708            "`linker_flavor` must be `ptc` if and only if `arch` is `nvptx64`"
2709        );
2710
2711        for args in [
2712            &self.pre_link_args,
2713            &self.late_link_args,
2714            &self.late_link_args_dynamic,
2715            &self.late_link_args_static,
2716            &self.post_link_args,
2717        ] {
2718            for (&flavor, flavor_args) in args {
2719                check!(
2720                    !flavor_args.is_empty() || self.arch == "avr",
2721                    "linker flavor args must not be empty"
2722                );
2723                // Check that flavors mentioned in link args are compatible with the default flavor.
2724                match self.linker_flavor {
2725                    LinkerFlavor::Gnu(..) => {
2726                        check_matches!(
2727                            flavor,
2728                            LinkerFlavor::Gnu(..),
2729                            "mixing GNU and non-GNU linker flavors"
2730                        );
2731                    }
2732                    LinkerFlavor::Darwin(..) => {
2733                        check_matches!(
2734                            flavor,
2735                            LinkerFlavor::Darwin(..),
2736                            "mixing Darwin and non-Darwin linker flavors"
2737                        )
2738                    }
2739                    LinkerFlavor::WasmLld(..) => {
2740                        check_matches!(
2741                            flavor,
2742                            LinkerFlavor::WasmLld(..),
2743                            "mixing wasm and non-wasm linker flavors"
2744                        )
2745                    }
2746                    LinkerFlavor::Unix(..) => {
2747                        check_matches!(
2748                            flavor,
2749                            LinkerFlavor::Unix(..),
2750                            "mixing unix and non-unix linker flavors"
2751                        );
2752                    }
2753                    LinkerFlavor::Msvc(..) => {
2754                        check_matches!(
2755                            flavor,
2756                            LinkerFlavor::Msvc(..),
2757                            "mixing MSVC and non-MSVC linker flavors"
2758                        );
2759                    }
2760                    LinkerFlavor::EmCc
2761                    | LinkerFlavor::Bpf
2762                    | LinkerFlavor::Ptx
2763                    | LinkerFlavor::Llbc => {
2764                        check_eq!(flavor, self.linker_flavor, "mixing different linker flavors")
2765                    }
2766                }
2767
2768                // Check that link args for cc and non-cc versions of flavors are consistent.
2769                let check_noncc = |noncc_flavor| -> Result<(), String> {
2770                    if let Some(noncc_args) = args.get(&noncc_flavor) {
2771                        for arg in flavor_args {
2772                            if let Some(suffix) = arg.strip_prefix("-Wl,") {
2773                                check!(
2774                                    noncc_args.iter().any(|a| a == suffix),
2775                                    " link args for cc and non-cc versions of flavors are not consistent"
2776                                );
2777                            }
2778                        }
2779                    }
2780                    Ok(())
2781                };
2782
2783                match self.linker_flavor {
2784                    LinkerFlavor::Gnu(Cc::Yes, lld) => check_noncc(LinkerFlavor::Gnu(Cc::No, lld))?,
2785                    LinkerFlavor::WasmLld(Cc::Yes) => check_noncc(LinkerFlavor::WasmLld(Cc::No))?,
2786                    LinkerFlavor::Unix(Cc::Yes) => check_noncc(LinkerFlavor::Unix(Cc::No))?,
2787                    _ => {}
2788                }
2789            }
2790
2791            // Check that link args for lld and non-lld versions of flavors are consistent.
2792            for cc in [Cc::No, Cc::Yes] {
2793                check_eq!(
2794                    args.get(&LinkerFlavor::Gnu(cc, Lld::No)),
2795                    args.get(&LinkerFlavor::Gnu(cc, Lld::Yes)),
2796                    "link args for lld and non-lld versions of flavors are not consistent",
2797                );
2798                check_eq!(
2799                    args.get(&LinkerFlavor::Darwin(cc, Lld::No)),
2800                    args.get(&LinkerFlavor::Darwin(cc, Lld::Yes)),
2801                    "link args for lld and non-lld versions of flavors are not consistent",
2802                );
2803            }
2804            check_eq!(
2805                args.get(&LinkerFlavor::Msvc(Lld::No)),
2806                args.get(&LinkerFlavor::Msvc(Lld::Yes)),
2807                "link args for lld and non-lld versions of flavors are not consistent",
2808            );
2809        }
2810
2811        if self.link_self_contained.is_disabled() {
2812            check!(
2813                self.pre_link_objects_self_contained.is_empty()
2814                    && self.post_link_objects_self_contained.is_empty(),
2815                "if `link_self_contained` is disabled, then `pre_link_objects_self_contained` and `post_link_objects_self_contained` must be empty",
2816            );
2817        }
2818
2819        // If your target really needs to deviate from the rules below,
2820        // except it and document the reasons.
2821        // Keep the default "unknown" vendor instead.
2822        check_ne!(self.vendor, "", "`vendor` cannot be empty");
2823        check_ne!(self.os, "", "`os` cannot be empty");
2824        if !self.can_use_os_unknown() {
2825            // Keep the default "none" for bare metal targets instead.
2826            check_ne!(
2827                self.os,
2828                "unknown",
2829                "`unknown` os can only be used on particular targets; use `none` for bare-metal targets"
2830            );
2831        }
2832
2833        // Check dynamic linking stuff.
2834        // We skip this for JSON targets since otherwise, our default values would fail this test.
2835        // These checks are not critical for correctness, but more like default guidelines.
2836        // FIXME (https://github.com/rust-lang/rust/issues/133459): do we want to change the JSON
2837        // target defaults so that they pass these checks?
2838        if kind == TargetKind::Builtin {
2839            // BPF: when targeting user space vms (like rbpf), those can load dynamic libraries.
2840            // hexagon: when targeting QuRT, that OS can load dynamic libraries.
2841            // wasm{32,64}: dynamic linking is inherent in the definition of the VM.
2842            if self.os == "none"
2843                && (self.arch != "bpf"
2844                    && self.arch != "hexagon"
2845                    && self.arch != "wasm32"
2846                    && self.arch != "wasm64")
2847            {
2848                check!(
2849                    !self.dynamic_linking,
2850                    "dynamic linking is not supported on this OS/architecture"
2851                );
2852            }
2853            if self.only_cdylib
2854                || self.crt_static_allows_dylibs
2855                || !self.late_link_args_dynamic.is_empty()
2856            {
2857                check!(
2858                    self.dynamic_linking,
2859                    "dynamic linking must be allowed when `only_cdylib` or `crt_static_allows_dylibs` or `late_link_args_dynamic` are set"
2860                );
2861            }
2862            // Apparently PIC was slow on wasm at some point, see comments in wasm_base.rs
2863            if self.dynamic_linking && !self.is_like_wasm {
2864                check_eq!(
2865                    self.relocation_model,
2866                    RelocModel::Pic,
2867                    "targets that support dynamic linking must use the `pic` relocation model"
2868                );
2869            }
2870            if self.position_independent_executables {
2871                check_eq!(
2872                    self.relocation_model,
2873                    RelocModel::Pic,
2874                    "targets that support position-independent executables must use the `pic` relocation model"
2875                );
2876            }
2877            // The UEFI targets do not support dynamic linking but still require PIC (#101377).
2878            if self.relocation_model == RelocModel::Pic && (self.os != "uefi") {
2879                check!(
2880                    self.dynamic_linking || self.position_independent_executables,
2881                    "when the relocation model is `pic`, the target must support dynamic linking or use position-independent executables. \
2882                Set the relocation model to `static` to avoid this requirement"
2883                );
2884            }
2885            if self.static_position_independent_executables {
2886                check!(
2887                    self.position_independent_executables,
2888                    "if `static_position_independent_executables` is set, then `position_independent_executables` must be set"
2889                );
2890            }
2891            if self.position_independent_executables {
2892                check!(
2893                    self.executables,
2894                    "if `position_independent_executables` is set then `executables` must be set"
2895                );
2896            }
2897        }
2898
2899        // Check crt static stuff
2900        if self.crt_static_default || self.crt_static_allows_dylibs {
2901            check!(
2902                self.crt_static_respected,
2903                "static CRT can be enabled but `crt_static_respected` is not set"
2904            );
2905        }
2906
2907        // Check that RISC-V targets always specify which ABI they use,
2908        // and that ARM targets specify their float ABI.
2909        match &*self.arch {
2910            "riscv32" => {
2911                check_matches!(
2912                    &*self.llvm_abiname,
2913                    "ilp32" | "ilp32f" | "ilp32d" | "ilp32e",
2914                    "invalid RISC-V ABI name: {}",
2915                    self.llvm_abiname,
2916                );
2917            }
2918            "riscv64" => {
2919                // Note that the `lp64e` is still unstable as it's not (yet) part of the ELF psABI.
2920                check_matches!(
2921                    &*self.llvm_abiname,
2922                    "lp64" | "lp64f" | "lp64d" | "lp64e",
2923                    "invalid RISC-V ABI name: {}",
2924                    self.llvm_abiname,
2925                );
2926            }
2927            "arm" => {
2928                check!(
2929                    self.llvm_floatabi.is_some(),
2930                    "ARM targets must set `llvm-floatabi` to `hard` or `soft`",
2931                )
2932            }
2933            _ => {}
2934        }
2935
2936        // Check consistency of Rust ABI declaration.
2937        if let Some(rust_abi) = self.rustc_abi {
2938            match rust_abi {
2939                RustcAbi::X86Sse2 => check_matches!(
2940                    &*self.arch,
2941                    "x86",
2942                    "`x86-sse2` ABI is only valid for x86-32 targets"
2943                ),
2944                RustcAbi::X86Softfloat => check_matches!(
2945                    &*self.arch,
2946                    "x86" | "x86_64",
2947                    "`x86-softfloat` ABI is only valid for x86 targets"
2948                ),
2949            }
2950        }
2951
2952        // Check that the given target-features string makes some basic sense.
2953        if !self.features.is_empty() {
2954            let mut features_enabled = FxHashSet::default();
2955            let mut features_disabled = FxHashSet::default();
2956            for feat in self.features.split(',') {
2957                if let Some(feat) = feat.strip_prefix("+") {
2958                    features_enabled.insert(feat);
2959                    if features_disabled.contains(feat) {
2960                        return Err(format!(
2961                            "target feature `{feat}` is both enabled and disabled"
2962                        ));
2963                    }
2964                } else if let Some(feat) = feat.strip_prefix("-") {
2965                    features_disabled.insert(feat);
2966                    if features_enabled.contains(feat) {
2967                        return Err(format!(
2968                            "target feature `{feat}` is both enabled and disabled"
2969                        ));
2970                    }
2971                } else {
2972                    return Err(format!(
2973                        "target feature `{feat}` is invalid, must start with `+` or `-`"
2974                    ));
2975                }
2976            }
2977            // Check that we don't mis-set any of the ABI-relevant features.
2978            let abi_feature_constraints = self.abi_required_features();
2979            for feat in abi_feature_constraints.required {
2980                // The feature might be enabled by default so we can't *require* it to show up.
2981                // But it must not be *disabled*.
2982                if features_disabled.contains(feat) {
2983                    return Err(format!(
2984                        "target feature `{feat}` is required by the ABI but gets disabled in target spec"
2985                    ));
2986                }
2987            }
2988            for feat in abi_feature_constraints.incompatible {
2989                // The feature might be disabled by default so we can't *require* it to show up.
2990                // But it must not be *enabled*.
2991                if features_enabled.contains(feat) {
2992                    return Err(format!(
2993                        "target feature `{feat}` is incompatible with the ABI but gets enabled in target spec"
2994                    ));
2995                }
2996            }
2997        }
2998
2999        Ok(())
3000    }
3001
3002    /// Test target self-consistency and JSON encoding/decoding roundtrip.
3003    #[cfg(test)]
3004    fn test_target(mut self) {
3005        let recycled_target =
3006            Target::from_json(&serde_json::to_string(&self.to_json()).unwrap()).map(|(j, _)| j);
3007        self.update_to_cli();
3008        self.check_consistency(TargetKind::Builtin).unwrap();
3009        assert_eq!(recycled_target, Ok(self));
3010    }
3011
3012    // Add your target to the whitelist if it has `std` library
3013    // and you certainly want "unknown" for the OS name.
3014    fn can_use_os_unknown(&self) -> bool {
3015        self.llvm_target == "wasm32-unknown-unknown"
3016            || self.llvm_target == "wasm64-unknown-unknown"
3017            || (self.env == "sgx" && self.vendor == "fortanix")
3018    }
3019
3020    /// Load a built-in target
3021    pub fn expect_builtin(target_tuple: &TargetTuple) -> Target {
3022        match *target_tuple {
3023            TargetTuple::TargetTuple(ref target_tuple) => {
3024                load_builtin(target_tuple).expect("built-in target")
3025            }
3026            TargetTuple::TargetJson { .. } => {
3027                panic!("built-in targets doesn't support target-paths")
3028            }
3029        }
3030    }
3031
3032    /// Load all built-in targets
3033    pub fn builtins() -> impl Iterator<Item = Target> {
3034        load_all_builtins()
3035    }
3036
3037    /// Search for a JSON file specifying the given target tuple.
3038    ///
3039    /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
3040    /// sysroot under the target-tuple's `rustlib` directory. Note that it could also just be a
3041    /// bare filename already, so also check for that. If one of the hardcoded targets we know
3042    /// about, just return it directly.
3043    ///
3044    /// The error string could come from any of the APIs called, including filesystem access and
3045    /// JSON decoding.
3046    pub fn search(
3047        target_tuple: &TargetTuple,
3048        sysroot: &Path,
3049    ) -> Result<(Target, TargetWarnings), String> {
3050        use std::{env, fs};
3051
3052        fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
3053            let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
3054            Target::from_json(&contents)
3055        }
3056
3057        match *target_tuple {
3058            TargetTuple::TargetTuple(ref target_tuple) => {
3059                // check if tuple is in list of built-in targets
3060                if let Some(t) = load_builtin(target_tuple) {
3061                    return Ok((t, TargetWarnings::empty()));
3062                }
3063
3064                // search for a file named `target_tuple`.json in RUST_TARGET_PATH
3065                let path = {
3066                    let mut target = target_tuple.to_string();
3067                    target.push_str(".json");
3068                    PathBuf::from(target)
3069                };
3070
3071                let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
3072
3073                for dir in env::split_paths(&target_path) {
3074                    let p = dir.join(&path);
3075                    if p.is_file() {
3076                        return load_file(&p);
3077                    }
3078                }
3079
3080                // Additionally look in the sysroot under `lib/rustlib/<tuple>/target.json`
3081                // as a fallback.
3082                let rustlib_path = crate::relative_target_rustlib_path(sysroot, target_tuple);
3083                let p = PathBuf::from_iter([
3084                    Path::new(sysroot),
3085                    Path::new(&rustlib_path),
3086                    Path::new("target.json"),
3087                ]);
3088                if p.is_file() {
3089                    return load_file(&p);
3090                }
3091
3092                // Leave in a specialized error message for the removed target.
3093                // FIXME: If you see this and it's been a few months after this has been released,
3094                // you can probably remove it.
3095                if target_tuple == "i586-pc-windows-msvc" {
3096                    Err("the `i586-pc-windows-msvc` target has been removed. Use the `i686-pc-windows-msvc` target instead.\n\
3097                        Windows 10 (the minimum required OS version) requires a CPU baseline of at least i686 so you can safely switch".into())
3098                } else {
3099                    Err(format!("could not find specification for target {target_tuple:?}"))
3100                }
3101            }
3102            TargetTuple::TargetJson { ref contents, .. } => Target::from_json(contents),
3103        }
3104    }
3105
3106    /// Return the target's small data threshold support, converting
3107    /// `DefaultForArch` into a concrete value.
3108    pub fn small_data_threshold_support(&self) -> SmallDataThresholdSupport {
3109        match &self.options.small_data_threshold_support {
3110            // Avoid having to duplicate the small data support in every
3111            // target file by supporting a default value for each
3112            // architecture.
3113            SmallDataThresholdSupport::DefaultForArch => match self.arch.as_ref() {
3114                "mips" | "mips64" | "mips32r6" => {
3115                    SmallDataThresholdSupport::LlvmArg("mips-ssection-threshold".into())
3116                }
3117                "hexagon" => {
3118                    SmallDataThresholdSupport::LlvmArg("hexagon-small-data-threshold".into())
3119                }
3120                "m68k" => SmallDataThresholdSupport::LlvmArg("m68k-ssection-threshold".into()),
3121                "riscv32" | "riscv64" => {
3122                    SmallDataThresholdSupport::LlvmModuleFlag("SmallDataLimit".into())
3123                }
3124                _ => SmallDataThresholdSupport::None,
3125            },
3126            s => s.clone(),
3127        }
3128    }
3129
3130    pub fn object_architecture(
3131        &self,
3132        unstable_target_features: &FxIndexSet<Symbol>,
3133    ) -> Option<(object::Architecture, Option<object::SubArchitecture>)> {
3134        use object::Architecture;
3135        Some(match self.arch.as_ref() {
3136            "arm" => (Architecture::Arm, None),
3137            "aarch64" => (
3138                if self.pointer_width == 32 {
3139                    Architecture::Aarch64_Ilp32
3140                } else {
3141                    Architecture::Aarch64
3142                },
3143                None,
3144            ),
3145            "x86" => (Architecture::I386, None),
3146            "s390x" => (Architecture::S390x, None),
3147            "m68k" => (Architecture::M68k, None),
3148            "mips" | "mips32r6" => (Architecture::Mips, None),
3149            "mips64" | "mips64r6" => (
3150                // While there are currently no builtin targets
3151                // using the N32 ABI, it is possible to specify
3152                // it using a custom target specification. N32
3153                // is an ILP32 ABI like the Aarch64_Ilp32
3154                // and X86_64_X32 cases above and below this one.
3155                if self.options.llvm_abiname.as_ref() == "n32" {
3156                    Architecture::Mips64_N32
3157                } else {
3158                    Architecture::Mips64
3159                },
3160                None,
3161            ),
3162            "x86_64" => (
3163                if self.pointer_width == 32 {
3164                    Architecture::X86_64_X32
3165                } else {
3166                    Architecture::X86_64
3167                },
3168                None,
3169            ),
3170            "powerpc" => (Architecture::PowerPc, None),
3171            "powerpc64" => (Architecture::PowerPc64, None),
3172            "riscv32" => (Architecture::Riscv32, None),
3173            "riscv64" => (Architecture::Riscv64, None),
3174            "sparc" => {
3175                if unstable_target_features.contains(&sym::v8plus) {
3176                    // Target uses V8+, aka EM_SPARC32PLUS, aka 64-bit V9 but in 32-bit mode
3177                    (Architecture::Sparc32Plus, None)
3178                } else {
3179                    // Target uses V7 or V8, aka EM_SPARC
3180                    (Architecture::Sparc, None)
3181                }
3182            }
3183            "sparc64" => (Architecture::Sparc64, None),
3184            "avr" => (Architecture::Avr, None),
3185            "msp430" => (Architecture::Msp430, None),
3186            "hexagon" => (Architecture::Hexagon, None),
3187            "xtensa" => (Architecture::Xtensa, None),
3188            "bpf" => (Architecture::Bpf, None),
3189            "loongarch32" => (Architecture::LoongArch32, None),
3190            "loongarch64" => (Architecture::LoongArch64, None),
3191            "csky" => (Architecture::Csky, None),
3192            "arm64ec" => (Architecture::Aarch64, Some(object::SubArchitecture::Arm64EC)),
3193            // Unsupported architecture.
3194            _ => return None,
3195        })
3196    }
3197
3198    /// Returns whether this target is known to have unreliable alignment:
3199    /// native C code for the target fails to align some data to the degree
3200    /// required by the C standard. We can't *really* do anything about that
3201    /// since unsafe Rust code may assume alignment any time, but we can at least
3202    /// inhibit some optimizations, and we suppress the alignment checks that
3203    /// would detect this unsoundness.
3204    ///
3205    /// Every target that returns less than `Align::MAX` here is still has a soundness bug.
3206    pub fn max_reliable_alignment(&self) -> Align {
3207        // FIXME(#112480) MSVC on x86-32 is unsound and fails to properly align many types with
3208        // more-than-4-byte-alignment on the stack. This makes alignments larger than 4 generally
3209        // unreliable on 32bit Windows.
3210        if self.is_like_windows && self.arch == "x86" {
3211            Align::from_bytes(4).unwrap()
3212        } else {
3213            Align::MAX
3214        }
3215    }
3216}
3217
3218/// Either a target tuple string or a path to a JSON file.
3219#[derive(Clone, Debug)]
3220pub enum TargetTuple {
3221    TargetTuple(String),
3222    TargetJson {
3223        /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
3224        /// inconsistencies as it is discarded during serialization.
3225        path_for_rustdoc: PathBuf,
3226        tuple: String,
3227        contents: String,
3228    },
3229}
3230
3231// Use a manual implementation to ignore the path field
3232impl PartialEq for TargetTuple {
3233    fn eq(&self, other: &Self) -> bool {
3234        match (self, other) {
3235            (Self::TargetTuple(l0), Self::TargetTuple(r0)) => l0 == r0,
3236            (
3237                Self::TargetJson { path_for_rustdoc: _, tuple: l_tuple, contents: l_contents },
3238                Self::TargetJson { path_for_rustdoc: _, tuple: r_tuple, contents: r_contents },
3239            ) => l_tuple == r_tuple && l_contents == r_contents,
3240            _ => false,
3241        }
3242    }
3243}
3244
3245// Use a manual implementation to ignore the path field
3246impl Hash for TargetTuple {
3247    fn hash<H: Hasher>(&self, state: &mut H) -> () {
3248        match self {
3249            TargetTuple::TargetTuple(tuple) => {
3250                0u8.hash(state);
3251                tuple.hash(state)
3252            }
3253            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3254                1u8.hash(state);
3255                tuple.hash(state);
3256                contents.hash(state)
3257            }
3258        }
3259    }
3260}
3261
3262// Use a manual implementation to prevent encoding the target json file path in the crate metadata
3263impl<S: Encoder> Encodable<S> for TargetTuple {
3264    fn encode(&self, s: &mut S) {
3265        match self {
3266            TargetTuple::TargetTuple(tuple) => {
3267                s.emit_u8(0);
3268                s.emit_str(tuple);
3269            }
3270            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3271                s.emit_u8(1);
3272                s.emit_str(tuple);
3273                s.emit_str(contents);
3274            }
3275        }
3276    }
3277}
3278
3279impl<D: Decoder> Decodable<D> for TargetTuple {
3280    fn decode(d: &mut D) -> Self {
3281        match d.read_u8() {
3282            0 => TargetTuple::TargetTuple(d.read_str().to_owned()),
3283            1 => TargetTuple::TargetJson {
3284                path_for_rustdoc: PathBuf::new(),
3285                tuple: d.read_str().to_owned(),
3286                contents: d.read_str().to_owned(),
3287            },
3288            _ => {
3289                panic!("invalid enum variant tag while decoding `TargetTuple`, expected 0..2");
3290            }
3291        }
3292    }
3293}
3294
3295impl TargetTuple {
3296    /// Creates a target tuple from the passed target tuple string.
3297    pub fn from_tuple(tuple: &str) -> Self {
3298        TargetTuple::TargetTuple(tuple.into())
3299    }
3300
3301    /// Creates a target tuple from the passed target path.
3302    pub fn from_path(path: &Path) -> Result<Self, io::Error> {
3303        let canonicalized_path = try_canonicalize(path)?;
3304        let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
3305            io::Error::new(
3306                io::ErrorKind::InvalidInput,
3307                format!("target path {canonicalized_path:?} is not a valid file: {err}"),
3308            )
3309        })?;
3310        let tuple = canonicalized_path
3311            .file_stem()
3312            .expect("target path must not be empty")
3313            .to_str()
3314            .expect("target path must be valid unicode")
3315            .to_owned();
3316        Ok(TargetTuple::TargetJson { path_for_rustdoc: canonicalized_path, tuple, contents })
3317    }
3318
3319    /// Returns a string tuple for this target.
3320    ///
3321    /// If this target is a path, the file name (without extension) is returned.
3322    pub fn tuple(&self) -> &str {
3323        match *self {
3324            TargetTuple::TargetTuple(ref tuple) | TargetTuple::TargetJson { ref tuple, .. } => {
3325                tuple
3326            }
3327        }
3328    }
3329
3330    /// Returns an extended string tuple for this target.
3331    ///
3332    /// If this target is a path, a hash of the path is appended to the tuple returned
3333    /// by `tuple()`.
3334    pub fn debug_tuple(&self) -> String {
3335        use std::hash::DefaultHasher;
3336
3337        match self {
3338            TargetTuple::TargetTuple(tuple) => tuple.to_owned(),
3339            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents: content } => {
3340                let mut hasher = DefaultHasher::new();
3341                content.hash(&mut hasher);
3342                let hash = hasher.finish();
3343                format!("{tuple}-{hash}")
3344            }
3345        }
3346    }
3347}
3348
3349impl fmt::Display for TargetTuple {
3350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3351        write!(f, "{}", self.debug_tuple())
3352    }
3353}
3354
3355into_diag_arg_using_display!(&TargetTuple);