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    ("x86_64-unknown-redox", x86_64_unknown_redox),
1557
1558    ("x86_64-unknown-managarm-mlibc", x86_64_unknown_managarm_mlibc),
1559    ("aarch64-unknown-managarm-mlibc", aarch64_unknown_managarm_mlibc),
1560    ("riscv64gc-unknown-managarm-mlibc", riscv64gc_unknown_managarm_mlibc),
1561
1562    ("i386-apple-ios", i386_apple_ios),
1563    ("x86_64-apple-ios", x86_64_apple_ios),
1564    ("aarch64-apple-ios", aarch64_apple_ios),
1565    ("arm64e-apple-ios", arm64e_apple_ios),
1566    ("armv7s-apple-ios", armv7s_apple_ios),
1567    ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
1568    ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
1569    ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
1570
1571    ("aarch64-apple-tvos", aarch64_apple_tvos),
1572    ("aarch64-apple-tvos-sim", aarch64_apple_tvos_sim),
1573    ("arm64e-apple-tvos", arm64e_apple_tvos),
1574    ("x86_64-apple-tvos", x86_64_apple_tvos),
1575
1576    ("armv7k-apple-watchos", armv7k_apple_watchos),
1577    ("arm64_32-apple-watchos", arm64_32_apple_watchos),
1578    ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
1579    ("aarch64-apple-watchos", aarch64_apple_watchos),
1580    ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
1581
1582    ("aarch64-apple-visionos", aarch64_apple_visionos),
1583    ("aarch64-apple-visionos-sim", aarch64_apple_visionos_sim),
1584
1585    ("armebv7r-none-eabi", armebv7r_none_eabi),
1586    ("armebv7r-none-eabihf", armebv7r_none_eabihf),
1587    ("armv7r-none-eabi", armv7r_none_eabi),
1588    ("armv7r-none-eabihf", armv7r_none_eabihf),
1589    ("armv8r-none-eabihf", armv8r_none_eabihf),
1590
1591    ("armv7-rtems-eabihf", armv7_rtems_eabihf),
1592
1593    ("x86_64-pc-solaris", x86_64_pc_solaris),
1594    ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1595
1596    ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1597    ("aarch64-unknown-illumos", aarch64_unknown_illumos),
1598
1599    ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1600    ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1601    ("x86_64-win7-windows-gnu", x86_64_win7_windows_gnu),
1602    ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1603    ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1604    ("i686-win7-windows-gnu", i686_win7_windows_gnu),
1605
1606    ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1607    ("i686-pc-windows-gnullvm", i686_pc_windows_gnullvm),
1608    ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1609
1610    ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1611    ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1612    ("arm64ec-pc-windows-msvc", arm64ec_pc_windows_msvc),
1613    ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1614    ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1615    ("x86_64-win7-windows-msvc", x86_64_win7_windows_msvc),
1616    ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1617    ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1618    ("i686-win7-windows-msvc", i686_win7_windows_msvc),
1619    ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1620    ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1621
1622    ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1623    ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1624    ("wasm32v1-none", wasm32v1_none),
1625    ("wasm32-wasip1", wasm32_wasip1),
1626    ("wasm32-wasip2", wasm32_wasip2),
1627    ("wasm32-wasip3", wasm32_wasip3),
1628    ("wasm32-wasip1-threads", wasm32_wasip1_threads),
1629    ("wasm32-wali-linux-musl", wasm32_wali_linux_musl),
1630    ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1631
1632    ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1633    ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1634    ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1635    ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1636    ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1637    ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1638    ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1639
1640    ("armv7a-none-eabi", armv7a_none_eabi),
1641    ("armv7a-none-eabihf", armv7a_none_eabihf),
1642    ("armv7a-nuttx-eabi", armv7a_nuttx_eabi),
1643    ("armv7a-nuttx-eabihf", armv7a_nuttx_eabihf),
1644    ("armv7a-vex-v5", armv7a_vex_v5),
1645
1646    ("msp430-none-elf", msp430_none_elf),
1647
1648    ("aarch64_be-unknown-hermit", aarch64_be_unknown_hermit),
1649    ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1650    ("riscv64gc-unknown-hermit", riscv64gc_unknown_hermit),
1651    ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1652    ("x86_64-unknown-motor", x86_64_unknown_motor),
1653
1654    ("x86_64-unikraft-linux-musl", x86_64_unikraft_linux_musl),
1655
1656    ("armv7-unknown-trusty", armv7_unknown_trusty),
1657    ("aarch64-unknown-trusty", aarch64_unknown_trusty),
1658    ("x86_64-unknown-trusty", x86_64_unknown_trusty),
1659
1660    ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1661    ("riscv32im-risc0-zkvm-elf", riscv32im_risc0_zkvm_elf),
1662    ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1663    ("riscv32ima-unknown-none-elf", riscv32ima_unknown_none_elf),
1664    ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1665    ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1666    ("riscv32imac-esp-espidf", riscv32imac_esp_espidf),
1667    ("riscv32imafc-esp-espidf", riscv32imafc_esp_espidf),
1668
1669    ("riscv32e-unknown-none-elf", riscv32e_unknown_none_elf),
1670    ("riscv32em-unknown-none-elf", riscv32em_unknown_none_elf),
1671    ("riscv32emc-unknown-none-elf", riscv32emc_unknown_none_elf),
1672
1673    ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1674    ("riscv32imafc-unknown-none-elf", riscv32imafc_unknown_none_elf),
1675    ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1676    ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1677    ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1678    ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1679    ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1680    ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1681    ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1682    ("riscv64a23-unknown-linux-gnu", riscv64a23_unknown_linux_gnu),
1683
1684    ("sparc-unknown-none-elf", sparc_unknown_none_elf),
1685
1686    ("loongarch32-unknown-none", loongarch32_unknown_none),
1687    ("loongarch32-unknown-none-softfloat", loongarch32_unknown_none_softfloat),
1688    ("loongarch64-unknown-none", loongarch64_unknown_none),
1689    ("loongarch64-unknown-none-softfloat", loongarch64_unknown_none_softfloat),
1690
1691    ("aarch64-unknown-none", aarch64_unknown_none),
1692    ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1693    ("aarch64_be-unknown-none-softfloat", aarch64_be_unknown_none_softfloat),
1694    ("aarch64-unknown-nuttx", aarch64_unknown_nuttx),
1695
1696    ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1697
1698    ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1699    ("i686-unknown-uefi", i686_unknown_uefi),
1700    ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1701
1702    ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1703
1704    ("amdgcn-amd-amdhsa", amdgcn_amd_amdhsa),
1705
1706    ("xtensa-esp32-none-elf", xtensa_esp32_none_elf),
1707    ("xtensa-esp32-espidf", xtensa_esp32_espidf),
1708    ("xtensa-esp32s2-none-elf", xtensa_esp32s2_none_elf),
1709    ("xtensa-esp32s2-espidf", xtensa_esp32s2_espidf),
1710    ("xtensa-esp32s3-none-elf", xtensa_esp32s3_none_elf),
1711    ("xtensa-esp32s3-espidf", xtensa_esp32s3_espidf),
1712
1713    ("i686-wrs-vxworks", i686_wrs_vxworks),
1714    ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1715    ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1716    ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1717    ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1718    ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1719    ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1720    ("riscv32-wrs-vxworks", riscv32_wrs_vxworks),
1721    ("riscv64-wrs-vxworks", riscv64_wrs_vxworks),
1722
1723    ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1724    ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1725    ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1726
1727    ("mipsel-sony-psp", mipsel_sony_psp),
1728    ("mipsel-sony-psx", mipsel_sony_psx),
1729    ("mipsel-unknown-none", mipsel_unknown_none),
1730    ("mips-mti-none-elf", mips_mti_none_elf),
1731    ("mipsel-mti-none-elf", mipsel_mti_none_elf),
1732    ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1733    ("armv4t-none-eabi", armv4t_none_eabi),
1734    ("thumbv5te-none-eabi", thumbv5te_none_eabi),
1735    ("armv5te-none-eabi", armv5te_none_eabi),
1736
1737    ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1738    ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1739    ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1740
1741    ("bpfeb-unknown-none", bpfeb_unknown_none),
1742    ("bpfel-unknown-none", bpfel_unknown_none),
1743
1744    ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1745
1746    ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1747
1748    ("armv7-sony-vita-newlibeabihf", armv7_sony_vita_newlibeabihf),
1749
1750    ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1751    ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1752
1753    ("x86_64-unknown-none", x86_64_unknown_none),
1754
1755    ("aarch64-unknown-teeos", aarch64_unknown_teeos),
1756
1757    ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1758
1759    ("aarch64-unknown-nto-qnx700", aarch64_unknown_nto_qnx700),
1760    ("aarch64-unknown-nto-qnx710", aarch64_unknown_nto_qnx710),
1761    ("aarch64-unknown-nto-qnx710_iosock", aarch64_unknown_nto_qnx710_iosock),
1762    ("aarch64-unknown-nto-qnx800", aarch64_unknown_nto_qnx800),
1763    ("x86_64-pc-nto-qnx710", x86_64_pc_nto_qnx710),
1764    ("x86_64-pc-nto-qnx710_iosock", x86_64_pc_nto_qnx710_iosock),
1765    ("x86_64-pc-nto-qnx800", x86_64_pc_nto_qnx800),
1766    ("i686-pc-nto-qnx700", i686_pc_nto_qnx700),
1767
1768    ("aarch64-unknown-linux-ohos", aarch64_unknown_linux_ohos),
1769    ("armv7-unknown-linux-ohos", armv7_unknown_linux_ohos),
1770    ("loongarch64-unknown-linux-ohos", loongarch64_unknown_linux_ohos),
1771    ("x86_64-unknown-linux-ohos", x86_64_unknown_linux_ohos),
1772
1773    ("x86_64-unknown-linux-none", x86_64_unknown_linux_none),
1774
1775    ("thumbv6m-nuttx-eabi", thumbv6m_nuttx_eabi),
1776    ("thumbv7a-nuttx-eabi", thumbv7a_nuttx_eabi),
1777    ("thumbv7a-nuttx-eabihf", thumbv7a_nuttx_eabihf),
1778    ("thumbv7m-nuttx-eabi", thumbv7m_nuttx_eabi),
1779    ("thumbv7em-nuttx-eabi", thumbv7em_nuttx_eabi),
1780    ("thumbv7em-nuttx-eabihf", thumbv7em_nuttx_eabihf),
1781    ("thumbv8m.base-nuttx-eabi", thumbv8m_base_nuttx_eabi),
1782    ("thumbv8m.main-nuttx-eabi", thumbv8m_main_nuttx_eabi),
1783    ("thumbv8m.main-nuttx-eabihf", thumbv8m_main_nuttx_eabihf),
1784    ("riscv32imc-unknown-nuttx-elf", riscv32imc_unknown_nuttx_elf),
1785    ("riscv32imac-unknown-nuttx-elf", riscv32imac_unknown_nuttx_elf),
1786    ("riscv32imafc-unknown-nuttx-elf", riscv32imafc_unknown_nuttx_elf),
1787    ("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf),
1788    ("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf),
1789    ("x86_64-lynx-lynxos178", x86_64_lynx_lynxos178),
1790
1791    ("x86_64-pc-cygwin", x86_64_pc_cygwin),
1792}
1793
1794/// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1795macro_rules! cvs {
1796    () => {
1797        ::std::borrow::Cow::Borrowed(&[])
1798    };
1799    ($($x:expr),+ $(,)?) => {
1800        ::std::borrow::Cow::Borrowed(&[
1801            $(
1802                ::std::borrow::Cow::Borrowed($x),
1803            )*
1804        ])
1805    };
1806}
1807
1808pub(crate) use cvs;
1809
1810/// Warnings encountered when parsing the target `json`.
1811///
1812/// Includes fields that weren't recognized and fields that don't have the expected type.
1813#[derive(Debug, PartialEq)]
1814pub struct TargetWarnings {
1815    unused_fields: Vec<String>,
1816}
1817
1818impl TargetWarnings {
1819    pub fn empty() -> Self {
1820        Self { unused_fields: Vec::new() }
1821    }
1822
1823    pub fn warning_messages(&self) -> Vec<String> {
1824        let mut warnings = vec![];
1825        if !self.unused_fields.is_empty() {
1826            warnings.push(format!(
1827                "target json file contains unused fields: {}",
1828                self.unused_fields.join(", ")
1829            ));
1830        }
1831        warnings
1832    }
1833}
1834
1835/// For the [`Target::check_consistency`] function, determines whether the given target is a builtin or a JSON
1836/// target.
1837#[derive(Copy, Clone, Debug, PartialEq)]
1838enum TargetKind {
1839    Json,
1840    Builtin,
1841}
1842
1843/// Everything `rustc` knows about how to compile for a specific target.
1844///
1845/// Every field here must be specified, and has no default value.
1846#[derive(PartialEq, Clone, Debug)]
1847pub struct Target {
1848    /// Unversioned target tuple to pass to LLVM.
1849    ///
1850    /// Target tuples can optionally contain an OS version (notably Apple targets), which rustc
1851    /// cannot know without querying the environment.
1852    ///
1853    /// Use `rustc_codegen_ssa::back::versioned_llvm_target` if you need the full LLVM target.
1854    pub llvm_target: StaticCow<str>,
1855    /// Metadata about a target, for example the description or tier.
1856    /// Used for generating target documentation.
1857    pub metadata: TargetMetadata,
1858    /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1859    pub pointer_width: u16,
1860    /// Architecture to use for ABI considerations. Valid options include: "x86",
1861    /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1862    pub arch: StaticCow<str>,
1863    /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1864    pub data_layout: StaticCow<str>,
1865    /// Optional settings with defaults.
1866    pub options: TargetOptions,
1867}
1868
1869/// Metadata about a target like the description or tier.
1870/// Part of #120745.
1871/// All fields are optional for now, but intended to be required in the future.
1872#[derive(Default, PartialEq, Clone, Debug)]
1873pub struct TargetMetadata {
1874    /// A short description of the target including platform requirements,
1875    /// for example "64-bit Linux (kernel 3.2+, glibc 2.17+)".
1876    pub description: Option<StaticCow<str>>,
1877    /// The tier of the target. 1, 2 or 3.
1878    pub tier: Option<u64>,
1879    /// Whether the Rust project ships host tools for a target.
1880    pub host_tools: Option<bool>,
1881    /// Whether a target has the `std` library. This is usually true for targets running
1882    /// on an operating system.
1883    pub std: Option<bool>,
1884}
1885
1886impl Target {
1887    pub fn parse_data_layout(&self) -> Result<TargetDataLayout, TargetDataLayoutErrors<'_>> {
1888        let mut dl = TargetDataLayout::parse_from_llvm_datalayout_string(
1889            &self.data_layout,
1890            self.options.default_address_space,
1891        )?;
1892
1893        // Perform consistency checks against the Target information.
1894        if dl.endian != self.endian {
1895            return Err(TargetDataLayoutErrors::InconsistentTargetArchitecture {
1896                dl: dl.endian.as_str(),
1897                target: self.endian.as_str(),
1898            });
1899        }
1900
1901        let target_pointer_width: u64 = self.pointer_width.into();
1902        let dl_pointer_size: u64 = dl.pointer_size().bits();
1903        if dl_pointer_size != target_pointer_width {
1904            return Err(TargetDataLayoutErrors::InconsistentTargetPointerWidth {
1905                pointer_size: dl_pointer_size,
1906                target: self.pointer_width,
1907            });
1908        }
1909
1910        dl.c_enum_min_size = Integer::from_size(Size::from_bits(
1911            self.c_enum_min_bits.unwrap_or(self.c_int_width as _),
1912        ))
1913        .map_err(|err| TargetDataLayoutErrors::InvalidBitsSize { err })?;
1914
1915        Ok(dl)
1916    }
1917}
1918
1919pub trait HasTargetSpec {
1920    fn target_spec(&self) -> &Target;
1921}
1922
1923impl HasTargetSpec for Target {
1924    #[inline]
1925    fn target_spec(&self) -> &Target {
1926        self
1927    }
1928}
1929
1930/// x86 (32-bit) abi options.
1931#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1932pub struct X86Abi {
1933    /// On x86-32 targets, the regparm N causes the compiler to pass arguments
1934    /// in registers EAX, EDX, and ECX instead of on the stack.
1935    pub regparm: Option<u32>,
1936    /// Override the default ABI to return small structs in registers
1937    pub reg_struct_return: bool,
1938}
1939
1940pub trait HasX86AbiOpt {
1941    fn x86_abi_opt(&self) -> X86Abi;
1942}
1943
1944type StaticCow<T> = Cow<'static, T>;
1945
1946/// Optional aspects of a target specification.
1947///
1948/// This has an implementation of `Default`, see each field for what the default is. In general,
1949/// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1950///
1951/// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1952/// construction, all its fields logically belong to `Target` and available from `Target`
1953/// through `Deref` impls.
1954#[derive(PartialEq, Clone, Debug)]
1955pub struct TargetOptions {
1956    /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1957    pub endian: Endian,
1958    /// Width of c_int type. Defaults to "32".
1959    pub c_int_width: u16,
1960    /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1961    /// "none" implies a bare metal target without `std` library.
1962    /// A couple of targets having `std` also use "unknown" as an `os` value,
1963    /// but they are exceptions.
1964    pub os: StaticCow<str>,
1965    /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1966    pub env: StaticCow<str>,
1967    /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1968    /// or `"eabihf"`. Defaults to "".
1969    /// This field is *not* forwarded directly to LLVM; its primary purpose is `cfg(target_abi)`.
1970    /// However, parts of the backend do check this field for specific values to enable special behavior.
1971    pub abi: StaticCow<str>,
1972    /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1973    pub vendor: StaticCow<str>,
1974
1975    /// Linker to invoke
1976    pub linker: Option<StaticCow<str>>,
1977    /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1978    /// on the command line. Defaults to `LinkerFlavor::Gnu(Cc::Yes, Lld::No)`.
1979    pub linker_flavor: LinkerFlavor,
1980    linker_flavor_json: LinkerFlavorCli,
1981    lld_flavor_json: LldFlavor,
1982    linker_is_gnu_json: bool,
1983
1984    /// Objects to link before and after all other object code.
1985    pub pre_link_objects: CrtObjects,
1986    pub post_link_objects: CrtObjects,
1987    /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1988    pub pre_link_objects_self_contained: CrtObjects,
1989    pub post_link_objects_self_contained: CrtObjects,
1990    /// Behavior for the self-contained linking mode: inferred for some targets, or explicitly
1991    /// enabled (in bulk, or with individual components).
1992    pub link_self_contained: LinkSelfContainedDefault,
1993
1994    /// Linker arguments that are passed *before* any user-defined libraries.
1995    pub pre_link_args: LinkArgs,
1996    pre_link_args_json: LinkArgsCli,
1997    /// Linker arguments that are unconditionally passed after any
1998    /// user-defined but before post-link objects. Standard platform
1999    /// libraries that should be always be linked to, usually go here.
2000    pub late_link_args: LinkArgs,
2001    late_link_args_json: LinkArgsCli,
2002    /// Linker arguments used in addition to `late_link_args` if at least one
2003    /// Rust dependency is dynamically linked.
2004    pub late_link_args_dynamic: LinkArgs,
2005    late_link_args_dynamic_json: LinkArgsCli,
2006    /// Linker arguments used in addition to `late_link_args` if all Rust
2007    /// dependencies are statically linked.
2008    pub late_link_args_static: LinkArgs,
2009    late_link_args_static_json: LinkArgsCli,
2010    /// Linker arguments that are unconditionally passed *after* any
2011    /// user-defined libraries.
2012    pub post_link_args: LinkArgs,
2013    post_link_args_json: LinkArgsCli,
2014
2015    /// Optional link script applied to `dylib` and `executable` crate types.
2016    /// This is a string containing the script, not a path. Can only be applied
2017    /// to linkers where linker flavor matches `LinkerFlavor::Gnu(..)`.
2018    pub link_script: Option<StaticCow<str>>,
2019    /// Environment variables to be set for the linker invocation.
2020    pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
2021    /// Environment variables to be removed for the linker invocation.
2022    pub link_env_remove: StaticCow<[StaticCow<str>]>,
2023
2024    /// Extra arguments to pass to the external assembler (when used)
2025    pub asm_args: StaticCow<[StaticCow<str>]>,
2026
2027    /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
2028    /// to "generic".
2029    pub cpu: StaticCow<str>,
2030    /// Whether a cpu needs to be explicitly set.
2031    /// Set to true if there is no default cpu. Defaults to false.
2032    pub need_explicit_cpu: bool,
2033    /// Default target features to pass to LLVM. These features overwrite
2034    /// `-Ctarget-cpu` but can be overwritten with `-Ctarget-features`.
2035    /// Corresponds to `llc -mattr=$features`.
2036    /// Note that these are LLVM feature names, not Rust feature names!
2037    ///
2038    /// Generally it is a bad idea to use negative target features because they often interact very
2039    /// poorly with how `-Ctarget-cpu` works. Instead, try to use a lower "base CPU" and enable the
2040    /// features you want to use.
2041    pub features: StaticCow<str>,
2042    /// Direct or use GOT indirect to reference external data symbols
2043    pub direct_access_external_data: Option<bool>,
2044    /// Whether dynamic linking is available on this target. Defaults to false.
2045    pub dynamic_linking: bool,
2046    /// Whether dynamic linking can export TLS globals. Defaults to true.
2047    pub dll_tls_export: bool,
2048    /// If dynamic linking is available, whether only cdylibs are supported.
2049    pub only_cdylib: bool,
2050    /// Whether executables are available on this target. Defaults to true.
2051    pub executables: bool,
2052    /// Relocation model to use in object file. Corresponds to `llc
2053    /// -relocation-model=$relocation_model`. Defaults to `Pic`.
2054    pub relocation_model: RelocModel,
2055    /// Code model to use. Corresponds to `llc -code-model=$code_model`.
2056    /// Defaults to `None` which means "inherited from the base LLVM target".
2057    pub code_model: Option<CodeModel>,
2058    /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
2059    /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
2060    pub tls_model: TlsModel,
2061    /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
2062    pub disable_redzone: bool,
2063    /// Frame pointer mode for this target. Defaults to `MayOmit`.
2064    pub frame_pointer: FramePointer,
2065    /// Emit each function in its own section. Defaults to true.
2066    pub function_sections: bool,
2067    /// String to prepend to the name of every dynamic library. Defaults to "lib".
2068    pub dll_prefix: StaticCow<str>,
2069    /// String to append to the name of every dynamic library. Defaults to ".so".
2070    pub dll_suffix: StaticCow<str>,
2071    /// String to append to the name of every executable.
2072    pub exe_suffix: StaticCow<str>,
2073    /// String to prepend to the name of every static library. Defaults to "lib".
2074    pub staticlib_prefix: StaticCow<str>,
2075    /// String to append to the name of every static library. Defaults to ".a".
2076    pub staticlib_suffix: StaticCow<str>,
2077    /// Values of the `target_family` cfg set for this target.
2078    ///
2079    /// Common options are: "unix", "windows". Defaults to no families.
2080    ///
2081    /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
2082    pub families: StaticCow<[StaticCow<str>]>,
2083    /// Whether the target toolchain's ABI supports returning small structs as an integer.
2084    pub abi_return_struct_as_int: bool,
2085    /// Whether the target toolchain is like AIX's. Linker options on AIX are special and it uses
2086    /// XCOFF as binary format. Defaults to false.
2087    pub is_like_aix: bool,
2088    /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
2089    /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
2090    /// Also indicates whether to use Apple-specific ABI changes, such as extending function
2091    /// parameters to 32-bits.
2092    pub is_like_darwin: bool,
2093    /// Whether the target toolchain is like Solaris's.
2094    /// Only useful for compiling against Illumos/Solaris,
2095    /// as they have a different set of linker flags. Defaults to false.
2096    pub is_like_solaris: bool,
2097    /// Whether the target is like Windows.
2098    /// This is a combination of several more specific properties represented as a single flag:
2099    ///   - The target uses a Windows ABI,
2100    ///   - uses PE/COFF as a format for object code,
2101    ///   - uses Windows-style dllexport/dllimport for shared libraries,
2102    ///   - uses import libraries and .def files for symbol exports,
2103    ///   - executables support setting a subsystem.
2104    pub is_like_windows: bool,
2105    /// Whether the target is like MSVC.
2106    /// This is a combination of several more specific properties represented as a single flag:
2107    ///   - The target has all the properties from `is_like_windows`
2108    ///     (for in-tree targets "is_like_msvc ⇒ is_like_windows" is ensured by a unit test),
2109    ///   - has some MSVC-specific Windows ABI properties,
2110    ///   - uses a link.exe-like linker,
2111    ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
2112    ///   - uses SEH-based unwinding,
2113    ///   - supports control flow guard mechanism.
2114    pub is_like_msvc: bool,
2115    /// Whether a target toolchain is like WASM.
2116    pub is_like_wasm: bool,
2117    /// Whether a target toolchain is like Android, implying a Linux kernel and a Bionic libc
2118    pub is_like_android: bool,
2119    /// Whether a target toolchain is like VEXos, the operating system used by the VEX Robotics V5 Brain.
2120    pub is_like_vexos: bool,
2121    /// Target's binary file format. Defaults to BinaryFormat::Elf
2122    pub binary_format: BinaryFormat,
2123    /// Default supported version of DWARF on this platform.
2124    /// Useful because some platforms (osx, bsd) only want up to DWARF2.
2125    pub default_dwarf_version: u32,
2126    /// The MinGW toolchain has a known issue that prevents it from correctly
2127    /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
2128    /// symbol needs its own COMDAT section, weak linkage implies a large
2129    /// number sections that easily exceeds the given limit for larger
2130    /// codebases. Consequently we want a way to disallow weak linkage on some
2131    /// platforms.
2132    pub allows_weak_linkage: bool,
2133    /// Whether the linker support rpaths or not. Defaults to false.
2134    pub has_rpath: bool,
2135    /// Whether to disable linking to the default libraries, typically corresponds
2136    /// to `-nodefaultlibs`. Defaults to true.
2137    pub no_default_libraries: bool,
2138    /// Dynamically linked executables can be compiled as position independent
2139    /// if the default relocation model of position independent code is not
2140    /// changed. This is a requirement to take advantage of ASLR, as otherwise
2141    /// the functions in the executable are not randomized and can be used
2142    /// during an exploit of a vulnerability in any code.
2143    pub position_independent_executables: bool,
2144    /// Executables that are both statically linked and position-independent are supported.
2145    pub static_position_independent_executables: bool,
2146    /// Determines if the target always requires using the PLT for indirect
2147    /// library calls or not. This controls the default value of the `-Z plt` flag.
2148    pub plt_by_default: bool,
2149    /// Either partial, full, or off. Full RELRO makes the dynamic linker
2150    /// resolve all symbols at startup and marks the GOT read-only before
2151    /// starting the program, preventing overwriting the GOT.
2152    pub relro_level: RelroLevel,
2153    /// Format that archives should be emitted in. This affects whether we use
2154    /// LLVM to assemble an archive or fall back to the system linker, and
2155    /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
2156    /// the system linker to be used.
2157    pub archive_format: StaticCow<str>,
2158    /// Is asm!() allowed? Defaults to true.
2159    pub allow_asm: bool,
2160    /// Whether the runtime startup code requires the `main` function be passed
2161    /// `argc` and `argv` values.
2162    pub main_needs_argc_argv: bool,
2163
2164    /// Flag indicating whether #[thread_local] is available for this target.
2165    pub has_thread_local: bool,
2166    /// This is mainly for easy compatibility with emscripten.
2167    /// If we give emcc .o files that are actually .bc files it
2168    /// will 'just work'.
2169    pub obj_is_bitcode: bool,
2170
2171    /// Don't use this field; instead use the `.min_atomic_width()` method.
2172    pub min_atomic_width: Option<u64>,
2173
2174    /// Don't use this field; instead use the `.max_atomic_width()` method.
2175    pub max_atomic_width: Option<u64>,
2176
2177    /// Whether the target supports atomic CAS operations natively
2178    pub atomic_cas: bool,
2179
2180    /// Panic strategy: "unwind" or "abort"
2181    pub panic_strategy: PanicStrategy,
2182
2183    /// Whether or not linking dylibs to a static CRT is allowed.
2184    pub crt_static_allows_dylibs: bool,
2185    /// Whether or not the CRT is statically linked by default.
2186    pub crt_static_default: bool,
2187    /// Whether or not crt-static is respected by the compiler (or is a no-op).
2188    pub crt_static_respected: bool,
2189
2190    /// The implementation of stack probes to use.
2191    pub stack_probes: StackProbeType,
2192
2193    /// The minimum alignment for global symbols.
2194    pub min_global_align: Option<Align>,
2195
2196    /// Default number of codegen units to use in debug mode
2197    pub default_codegen_units: Option<u64>,
2198
2199    /// Default codegen backend used for this target. Defaults to `None`.
2200    ///
2201    /// If `None`, then `CFG_DEFAULT_CODEGEN_BACKEND` environmental variable captured when
2202    /// compiling `rustc` will be used instead (or llvm if it is not set).
2203    ///
2204    /// N.B. when *using* the compiler, backend can always be overridden with `-Zcodegen-backend`.
2205    ///
2206    /// This was added by WaffleLapkin in #116793. The motivation is a rustc fork that requires a
2207    /// custom codegen backend for a particular target.
2208    pub default_codegen_backend: Option<StaticCow<str>>,
2209
2210    /// Whether to generate trap instructions in places where optimization would
2211    /// otherwise produce control flow that falls through into unrelated memory.
2212    pub trap_unreachable: bool,
2213
2214    /// This target requires everything to be compiled with LTO to emit a final
2215    /// executable, aka there is no native linker for this target.
2216    pub requires_lto: bool,
2217
2218    /// This target has no support for threads.
2219    pub singlethread: bool,
2220
2221    /// Whether library functions call lowering/optimization is disabled in LLVM
2222    /// for this target unconditionally.
2223    pub no_builtins: bool,
2224
2225    /// The default visibility for symbols in this target.
2226    ///
2227    /// This value typically shouldn't be accessed directly, but through the
2228    /// `rustc_session::Session::default_visibility` method, which allows `rustc` users to override
2229    /// this setting using cmdline flags.
2230    pub default_visibility: Option<SymbolVisibility>,
2231
2232    /// Whether a .debug_gdb_scripts section will be added to the output object file
2233    pub emit_debug_gdb_scripts: bool,
2234
2235    /// Whether or not to unconditionally `uwtable` attributes on functions,
2236    /// typically because the platform needs to unwind for things like stack
2237    /// unwinders.
2238    pub requires_uwtable: bool,
2239
2240    /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
2241    /// is not specified and `uwtable` is not required on this target.
2242    pub default_uwtable: bool,
2243
2244    /// Whether or not SIMD types are passed by reference in the Rust ABI,
2245    /// typically required if a target can be compiled with a mixed set of
2246    /// target features. This is `true` by default, and `false` for targets like
2247    /// wasm32 where the whole program either has simd or not.
2248    pub simd_types_indirect: bool,
2249
2250    /// Pass a list of symbol which should be exported in the dylib to the linker.
2251    pub limit_rdylib_exports: bool,
2252
2253    /// If set, have the linker export exactly these symbols, instead of using
2254    /// the usual logic to figure this out from the crate itself.
2255    pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
2256
2257    /// Determines how or whether the MergeFunctions LLVM pass should run for
2258    /// this target. Either "disabled", "trampolines", or "aliases".
2259    /// The MergeFunctions pass is generally useful, but some targets may need
2260    /// to opt out. The default is "aliases".
2261    ///
2262    /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
2263    pub merge_functions: MergeFunctions,
2264
2265    /// Use platform dependent mcount function
2266    pub mcount: StaticCow<str>,
2267
2268    /// Use LLVM intrinsic for mcount function name
2269    pub llvm_mcount_intrinsic: Option<StaticCow<str>>,
2270
2271    /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
2272    /// and the `-target-abi` flag in llc. In the LLVM API this is `MCOptions.ABIName`.
2273    pub llvm_abiname: StaticCow<str>,
2274
2275    /// Control the float ABI to use, for architectures that support it. The only architecture we
2276    /// currently use this for is ARM. Corresponds to the `-float-abi` flag in llc. In the LLVM API
2277    /// this is `FloatABIType`. (clang's `-mfloat-abi` is similar but more complicated since it
2278    /// can also affect the `soft-float` target feature.)
2279    ///
2280    /// If not provided, LLVM will infer the float ABI from the target triple (`llvm_target`).
2281    pub llvm_floatabi: Option<FloatAbi>,
2282
2283    /// Picks a specific ABI for this target. This is *not* just for "Rust" ABI functions,
2284    /// it can also affect "C" ABI functions; the point is that this flag is interpreted by
2285    /// rustc and not forwarded to LLVM.
2286    /// So far, this is only used on x86.
2287    pub rustc_abi: Option<RustcAbi>,
2288
2289    /// Whether or not RelaxElfRelocation flag will be passed to the linker
2290    pub relax_elf_relocations: bool,
2291
2292    /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
2293    pub llvm_args: StaticCow<[StaticCow<str>]>,
2294
2295    /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
2296    /// to false (uses .init_array).
2297    pub use_ctors_section: bool,
2298
2299    /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
2300    /// used to locate unwinding information is passed
2301    /// (only has effect if the linker is `ld`-like).
2302    pub eh_frame_header: bool,
2303
2304    /// Is true if the target is an ARM architecture using thumb v1 which allows for
2305    /// thumb and arm interworking.
2306    pub has_thumb_interworking: bool,
2307
2308    /// Which kind of debuginfo is used by this target?
2309    pub debuginfo_kind: DebuginfoKind,
2310    /// How to handle split debug information, if at all. Specifying `None` has
2311    /// target-specific meaning.
2312    pub split_debuginfo: SplitDebuginfo,
2313    /// Which kinds of split debuginfo are supported by the target?
2314    pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
2315
2316    /// The sanitizers supported by this target
2317    ///
2318    /// Note that the support here is at a codegen level. If the machine code with sanitizer
2319    /// enabled can generated on this target, but the necessary supporting libraries are not
2320    /// distributed with the target, the sanitizer should still appear in this list for the target.
2321    pub supported_sanitizers: SanitizerSet,
2322
2323    /// Minimum number of bits in #[repr(C)] enum. Defaults to the size of c_int
2324    pub c_enum_min_bits: Option<u64>,
2325
2326    /// Whether or not the DWARF `.debug_aranges` section should be generated.
2327    pub generate_arange_section: bool,
2328
2329    /// Whether the target supports stack canary checks. `true` by default,
2330    /// since this is most common among tier 1 and tier 2 targets.
2331    pub supports_stack_protector: bool,
2332
2333    /// The name of entry function.
2334    /// Default value is "main"
2335    pub entry_name: StaticCow<str>,
2336
2337    /// The ABI of the entry function.
2338    /// Default value is `CanonAbi::C`
2339    pub entry_abi: CanonAbi,
2340
2341    /// Whether the target supports XRay instrumentation.
2342    pub supports_xray: bool,
2343
2344    /// The default address space for this target. When using LLVM as a backend, most targets simply
2345    /// use LLVM's default address space (0). Some other targets, such as CHERI targets, use a
2346    /// custom default address space (in this specific case, `200`).
2347    pub default_address_space: rustc_abi::AddressSpace,
2348
2349    /// Whether the targets supports -Z small-data-threshold
2350    small_data_threshold_support: SmallDataThresholdSupport,
2351}
2352
2353/// Add arguments for the given flavor and also for its "twin" flavors
2354/// that have a compatible command line interface.
2355fn add_link_args_iter(
2356    link_args: &mut LinkArgs,
2357    flavor: LinkerFlavor,
2358    args: impl Iterator<Item = StaticCow<str>> + Clone,
2359) {
2360    let mut insert = |flavor| link_args.entry(flavor).or_default().extend(args.clone());
2361    insert(flavor);
2362    match flavor {
2363        LinkerFlavor::Gnu(cc, lld) => {
2364            assert_eq!(lld, Lld::No);
2365            insert(LinkerFlavor::Gnu(cc, Lld::Yes));
2366        }
2367        LinkerFlavor::Darwin(cc, lld) => {
2368            assert_eq!(lld, Lld::No);
2369            insert(LinkerFlavor::Darwin(cc, Lld::Yes));
2370        }
2371        LinkerFlavor::Msvc(lld) => {
2372            assert_eq!(lld, Lld::No);
2373            insert(LinkerFlavor::Msvc(Lld::Yes));
2374        }
2375        LinkerFlavor::WasmLld(..)
2376        | LinkerFlavor::Unix(..)
2377        | LinkerFlavor::EmCc
2378        | LinkerFlavor::Bpf
2379        | LinkerFlavor::Llbc
2380        | LinkerFlavor::Ptx => {}
2381    }
2382}
2383
2384fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
2385    add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
2386}
2387
2388impl TargetOptions {
2389    pub fn supports_comdat(&self) -> bool {
2390        // XCOFF and MachO don't support COMDAT.
2391        !self.is_like_aix && !self.is_like_darwin
2392    }
2393}
2394
2395impl TargetOptions {
2396    fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
2397        let mut link_args = LinkArgs::new();
2398        add_link_args(&mut link_args, flavor, args);
2399        link_args
2400    }
2401
2402    fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
2403        add_link_args(&mut self.pre_link_args, flavor, args);
2404    }
2405
2406    fn update_from_cli(&mut self) {
2407        self.linker_flavor = LinkerFlavor::from_cli_json(
2408            self.linker_flavor_json,
2409            self.lld_flavor_json,
2410            self.linker_is_gnu_json,
2411        );
2412        for (args, args_json) in [
2413            (&mut self.pre_link_args, &self.pre_link_args_json),
2414            (&mut self.late_link_args, &self.late_link_args_json),
2415            (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
2416            (&mut self.late_link_args_static, &self.late_link_args_static_json),
2417            (&mut self.post_link_args, &self.post_link_args_json),
2418        ] {
2419            args.clear();
2420            for (flavor, args_json) in args_json {
2421                let linker_flavor = self.linker_flavor.with_cli_hints(*flavor);
2422                // Normalize to no lld to avoid asserts.
2423                let linker_flavor = match linker_flavor {
2424                    LinkerFlavor::Gnu(cc, _) => LinkerFlavor::Gnu(cc, Lld::No),
2425                    LinkerFlavor::Darwin(cc, _) => LinkerFlavor::Darwin(cc, Lld::No),
2426                    LinkerFlavor::Msvc(_) => LinkerFlavor::Msvc(Lld::No),
2427                    _ => linker_flavor,
2428                };
2429                if !args.contains_key(&linker_flavor) {
2430                    add_link_args_iter(args, linker_flavor, args_json.iter().cloned());
2431                }
2432            }
2433        }
2434    }
2435
2436    fn update_to_cli(&mut self) {
2437        self.linker_flavor_json = self.linker_flavor.to_cli_counterpart();
2438        self.lld_flavor_json = self.linker_flavor.lld_flavor();
2439        self.linker_is_gnu_json = self.linker_flavor.is_gnu();
2440        for (args, args_json) in [
2441            (&self.pre_link_args, &mut self.pre_link_args_json),
2442            (&self.late_link_args, &mut self.late_link_args_json),
2443            (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
2444            (&self.late_link_args_static, &mut self.late_link_args_static_json),
2445            (&self.post_link_args, &mut self.post_link_args_json),
2446        ] {
2447            *args_json = args
2448                .iter()
2449                .map(|(flavor, args)| (flavor.to_cli_counterpart(), args.clone()))
2450                .collect();
2451        }
2452    }
2453}
2454
2455impl Default for TargetOptions {
2456    /// Creates a set of "sane defaults" for any target. This is still
2457    /// incomplete, and if used for compilation, will certainly not work.
2458    fn default() -> TargetOptions {
2459        TargetOptions {
2460            endian: Endian::Little,
2461            c_int_width: 32,
2462            os: "none".into(),
2463            env: "".into(),
2464            abi: "".into(),
2465            vendor: "unknown".into(),
2466            linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
2467            linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
2468            linker_flavor_json: LinkerFlavorCli::Gcc,
2469            lld_flavor_json: LldFlavor::Ld,
2470            linker_is_gnu_json: true,
2471            link_script: None,
2472            asm_args: cvs![],
2473            cpu: "generic".into(),
2474            need_explicit_cpu: false,
2475            features: "".into(),
2476            direct_access_external_data: None,
2477            dynamic_linking: false,
2478            dll_tls_export: true,
2479            only_cdylib: false,
2480            executables: true,
2481            relocation_model: RelocModel::Pic,
2482            code_model: None,
2483            tls_model: TlsModel::GeneralDynamic,
2484            disable_redzone: false,
2485            frame_pointer: FramePointer::MayOmit,
2486            function_sections: true,
2487            dll_prefix: "lib".into(),
2488            dll_suffix: ".so".into(),
2489            exe_suffix: "".into(),
2490            staticlib_prefix: "lib".into(),
2491            staticlib_suffix: ".a".into(),
2492            families: cvs![],
2493            abi_return_struct_as_int: false,
2494            is_like_aix: false,
2495            is_like_darwin: false,
2496            is_like_solaris: false,
2497            is_like_windows: false,
2498            is_like_msvc: false,
2499            is_like_wasm: false,
2500            is_like_android: false,
2501            is_like_vexos: false,
2502            binary_format: BinaryFormat::Elf,
2503            default_dwarf_version: 4,
2504            allows_weak_linkage: true,
2505            has_rpath: false,
2506            no_default_libraries: true,
2507            position_independent_executables: false,
2508            static_position_independent_executables: false,
2509            plt_by_default: true,
2510            relro_level: RelroLevel::None,
2511            pre_link_objects: Default::default(),
2512            post_link_objects: Default::default(),
2513            pre_link_objects_self_contained: Default::default(),
2514            post_link_objects_self_contained: Default::default(),
2515            link_self_contained: LinkSelfContainedDefault::False,
2516            pre_link_args: LinkArgs::new(),
2517            pre_link_args_json: LinkArgsCli::new(),
2518            late_link_args: LinkArgs::new(),
2519            late_link_args_json: LinkArgsCli::new(),
2520            late_link_args_dynamic: LinkArgs::new(),
2521            late_link_args_dynamic_json: LinkArgsCli::new(),
2522            late_link_args_static: LinkArgs::new(),
2523            late_link_args_static_json: LinkArgsCli::new(),
2524            post_link_args: LinkArgs::new(),
2525            post_link_args_json: LinkArgsCli::new(),
2526            link_env: cvs![],
2527            link_env_remove: cvs![],
2528            archive_format: "gnu".into(),
2529            main_needs_argc_argv: true,
2530            allow_asm: true,
2531            has_thread_local: false,
2532            obj_is_bitcode: false,
2533            min_atomic_width: None,
2534            max_atomic_width: None,
2535            atomic_cas: true,
2536            panic_strategy: PanicStrategy::Unwind,
2537            crt_static_allows_dylibs: false,
2538            crt_static_default: false,
2539            crt_static_respected: false,
2540            stack_probes: StackProbeType::None,
2541            min_global_align: None,
2542            default_codegen_units: None,
2543            default_codegen_backend: None,
2544            trap_unreachable: true,
2545            requires_lto: false,
2546            singlethread: false,
2547            no_builtins: false,
2548            default_visibility: None,
2549            emit_debug_gdb_scripts: true,
2550            requires_uwtable: false,
2551            default_uwtable: false,
2552            simd_types_indirect: true,
2553            limit_rdylib_exports: true,
2554            override_export_symbols: None,
2555            merge_functions: MergeFunctions::Aliases,
2556            mcount: "mcount".into(),
2557            llvm_mcount_intrinsic: None,
2558            llvm_abiname: "".into(),
2559            llvm_floatabi: None,
2560            rustc_abi: None,
2561            relax_elf_relocations: false,
2562            llvm_args: cvs![],
2563            use_ctors_section: false,
2564            eh_frame_header: true,
2565            has_thumb_interworking: false,
2566            debuginfo_kind: Default::default(),
2567            split_debuginfo: Default::default(),
2568            // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
2569            supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
2570            supported_sanitizers: SanitizerSet::empty(),
2571            c_enum_min_bits: None,
2572            generate_arange_section: true,
2573            supports_stack_protector: true,
2574            entry_name: "main".into(),
2575            entry_abi: CanonAbi::C,
2576            supports_xray: false,
2577            default_address_space: rustc_abi::AddressSpace::ZERO,
2578            small_data_threshold_support: SmallDataThresholdSupport::DefaultForArch,
2579        }
2580    }
2581}
2582
2583/// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
2584/// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
2585/// this `Deref` implementation is no longer necessary.
2586impl Deref for Target {
2587    type Target = TargetOptions;
2588
2589    #[inline]
2590    fn deref(&self) -> &Self::Target {
2591        &self.options
2592    }
2593}
2594impl DerefMut for Target {
2595    #[inline]
2596    fn deref_mut(&mut self) -> &mut Self::Target {
2597        &mut self.options
2598    }
2599}
2600
2601impl Target {
2602    pub fn is_abi_supported(&self, abi: ExternAbi) -> bool {
2603        let abi_map = AbiMap::from_target(self);
2604        abi_map.canonize_abi(abi, false).is_mapped()
2605    }
2606
2607    /// Minimum integer size in bits that this target can perform atomic
2608    /// operations on.
2609    pub fn min_atomic_width(&self) -> u64 {
2610        self.min_atomic_width.unwrap_or(8)
2611    }
2612
2613    /// Maximum integer size in bits that this target can perform atomic
2614    /// operations on.
2615    pub fn max_atomic_width(&self) -> u64 {
2616        self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
2617    }
2618
2619    /// Check some basic consistency of the current target. For JSON targets we are less strict;
2620    /// some of these checks are more guidelines than strict rules.
2621    fn check_consistency(&self, kind: TargetKind) -> Result<(), String> {
2622        macro_rules! check {
2623            ($b:expr, $($msg:tt)*) => {
2624                if !$b {
2625                    return Err(format!($($msg)*));
2626                }
2627            }
2628        }
2629        macro_rules! check_eq {
2630            ($left:expr, $right:expr, $($msg:tt)*) => {
2631                if ($left) != ($right) {
2632                    return Err(format!($($msg)*));
2633                }
2634            }
2635        }
2636        macro_rules! check_ne {
2637            ($left:expr, $right:expr, $($msg:tt)*) => {
2638                if ($left) == ($right) {
2639                    return Err(format!($($msg)*));
2640                }
2641            }
2642        }
2643        macro_rules! check_matches {
2644            ($left:expr, $right:pat, $($msg:tt)*) => {
2645                if !matches!($left, $right) {
2646                    return Err(format!($($msg)*));
2647                }
2648            }
2649        }
2650
2651        check_eq!(
2652            self.is_like_darwin,
2653            self.vendor == "apple",
2654            "`is_like_darwin` must be set if and only if `vendor` is `apple`"
2655        );
2656        check_eq!(
2657            self.is_like_solaris,
2658            self.os == "solaris" || self.os == "illumos",
2659            "`is_like_solaris` must be set if and only if `os` is `solaris` or `illumos`"
2660        );
2661        check_eq!(
2662            self.is_like_windows,
2663            self.os == "windows" || self.os == "uefi" || self.os == "cygwin",
2664            "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`"
2665        );
2666        check_eq!(
2667            self.is_like_wasm,
2668            self.arch == "wasm32" || self.arch == "wasm64",
2669            "`is_like_wasm` must be set if and only if `arch` is `wasm32` or `wasm64`"
2670        );
2671        if self.is_like_msvc {
2672            check!(self.is_like_windows, "if `is_like_msvc` is set, `is_like_windows` must be set");
2673        }
2674        if self.os == "emscripten" {
2675            check!(self.is_like_wasm, "the `emcscripten` os only makes sense on wasm-like targets");
2676        }
2677
2678        // Check that default linker flavor is compatible with some other key properties.
2679        check_eq!(
2680            self.is_like_darwin,
2681            matches!(self.linker_flavor, LinkerFlavor::Darwin(..)),
2682            "`linker_flavor` must be `darwin` if and only if `is_like_darwin` is set"
2683        );
2684        check_eq!(
2685            self.is_like_msvc,
2686            matches!(self.linker_flavor, LinkerFlavor::Msvc(..)),
2687            "`linker_flavor` must be `msvc` if and only if `is_like_msvc` is set"
2688        );
2689        check_eq!(
2690            self.is_like_wasm && self.os != "emscripten",
2691            matches!(self.linker_flavor, LinkerFlavor::WasmLld(..)),
2692            "`linker_flavor` must be `wasm-lld` if and only if `is_like_wasm` is set and the `os` is not `emscripten`",
2693        );
2694        check_eq!(
2695            self.os == "emscripten",
2696            matches!(self.linker_flavor, LinkerFlavor::EmCc),
2697            "`linker_flavor` must be `em-cc` if and only if `os` is `emscripten`"
2698        );
2699        check_eq!(
2700            self.arch == "bpf",
2701            matches!(self.linker_flavor, LinkerFlavor::Bpf),
2702            "`linker_flavor` must be `bpf` if and only if `arch` is `bpf`"
2703        );
2704        check_eq!(
2705            self.arch == "nvptx64",
2706            matches!(self.linker_flavor, LinkerFlavor::Ptx),
2707            "`linker_flavor` must be `ptc` if and only if `arch` is `nvptx64`"
2708        );
2709
2710        for args in [
2711            &self.pre_link_args,
2712            &self.late_link_args,
2713            &self.late_link_args_dynamic,
2714            &self.late_link_args_static,
2715            &self.post_link_args,
2716        ] {
2717            for (&flavor, flavor_args) in args {
2718                check!(
2719                    !flavor_args.is_empty() || self.arch == "avr",
2720                    "linker flavor args must not be empty"
2721                );
2722                // Check that flavors mentioned in link args are compatible with the default flavor.
2723                match self.linker_flavor {
2724                    LinkerFlavor::Gnu(..) => {
2725                        check_matches!(
2726                            flavor,
2727                            LinkerFlavor::Gnu(..),
2728                            "mixing GNU and non-GNU linker flavors"
2729                        );
2730                    }
2731                    LinkerFlavor::Darwin(..) => {
2732                        check_matches!(
2733                            flavor,
2734                            LinkerFlavor::Darwin(..),
2735                            "mixing Darwin and non-Darwin linker flavors"
2736                        )
2737                    }
2738                    LinkerFlavor::WasmLld(..) => {
2739                        check_matches!(
2740                            flavor,
2741                            LinkerFlavor::WasmLld(..),
2742                            "mixing wasm and non-wasm linker flavors"
2743                        )
2744                    }
2745                    LinkerFlavor::Unix(..) => {
2746                        check_matches!(
2747                            flavor,
2748                            LinkerFlavor::Unix(..),
2749                            "mixing unix and non-unix linker flavors"
2750                        );
2751                    }
2752                    LinkerFlavor::Msvc(..) => {
2753                        check_matches!(
2754                            flavor,
2755                            LinkerFlavor::Msvc(..),
2756                            "mixing MSVC and non-MSVC linker flavors"
2757                        );
2758                    }
2759                    LinkerFlavor::EmCc
2760                    | LinkerFlavor::Bpf
2761                    | LinkerFlavor::Ptx
2762                    | LinkerFlavor::Llbc => {
2763                        check_eq!(flavor, self.linker_flavor, "mixing different linker flavors")
2764                    }
2765                }
2766
2767                // Check that link args for cc and non-cc versions of flavors are consistent.
2768                let check_noncc = |noncc_flavor| -> Result<(), String> {
2769                    if let Some(noncc_args) = args.get(&noncc_flavor) {
2770                        for arg in flavor_args {
2771                            if let Some(suffix) = arg.strip_prefix("-Wl,") {
2772                                check!(
2773                                    noncc_args.iter().any(|a| a == suffix),
2774                                    " link args for cc and non-cc versions of flavors are not consistent"
2775                                );
2776                            }
2777                        }
2778                    }
2779                    Ok(())
2780                };
2781
2782                match self.linker_flavor {
2783                    LinkerFlavor::Gnu(Cc::Yes, lld) => check_noncc(LinkerFlavor::Gnu(Cc::No, lld))?,
2784                    LinkerFlavor::WasmLld(Cc::Yes) => check_noncc(LinkerFlavor::WasmLld(Cc::No))?,
2785                    LinkerFlavor::Unix(Cc::Yes) => check_noncc(LinkerFlavor::Unix(Cc::No))?,
2786                    _ => {}
2787                }
2788            }
2789
2790            // Check that link args for lld and non-lld versions of flavors are consistent.
2791            for cc in [Cc::No, Cc::Yes] {
2792                check_eq!(
2793                    args.get(&LinkerFlavor::Gnu(cc, Lld::No)),
2794                    args.get(&LinkerFlavor::Gnu(cc, Lld::Yes)),
2795                    "link args for lld and non-lld versions of flavors are not consistent",
2796                );
2797                check_eq!(
2798                    args.get(&LinkerFlavor::Darwin(cc, Lld::No)),
2799                    args.get(&LinkerFlavor::Darwin(cc, Lld::Yes)),
2800                    "link args for lld and non-lld versions of flavors are not consistent",
2801                );
2802            }
2803            check_eq!(
2804                args.get(&LinkerFlavor::Msvc(Lld::No)),
2805                args.get(&LinkerFlavor::Msvc(Lld::Yes)),
2806                "link args for lld and non-lld versions of flavors are not consistent",
2807            );
2808        }
2809
2810        if self.link_self_contained.is_disabled() {
2811            check!(
2812                self.pre_link_objects_self_contained.is_empty()
2813                    && self.post_link_objects_self_contained.is_empty(),
2814                "if `link_self_contained` is disabled, then `pre_link_objects_self_contained` and `post_link_objects_self_contained` must be empty",
2815            );
2816        }
2817
2818        // If your target really needs to deviate from the rules below,
2819        // except it and document the reasons.
2820        // Keep the default "unknown" vendor instead.
2821        check_ne!(self.vendor, "", "`vendor` cannot be empty");
2822        check_ne!(self.os, "", "`os` cannot be empty");
2823        if !self.can_use_os_unknown() {
2824            // Keep the default "none" for bare metal targets instead.
2825            check_ne!(
2826                self.os,
2827                "unknown",
2828                "`unknown` os can only be used on particular targets; use `none` for bare-metal targets"
2829            );
2830        }
2831
2832        // Check dynamic linking stuff.
2833        // We skip this for JSON targets since otherwise, our default values would fail this test.
2834        // These checks are not critical for correctness, but more like default guidelines.
2835        // FIXME (https://github.com/rust-lang/rust/issues/133459): do we want to change the JSON
2836        // target defaults so that they pass these checks?
2837        if kind == TargetKind::Builtin {
2838            // BPF: when targeting user space vms (like rbpf), those can load dynamic libraries.
2839            // hexagon: when targeting QuRT, that OS can load dynamic libraries.
2840            // wasm{32,64}: dynamic linking is inherent in the definition of the VM.
2841            if self.os == "none"
2842                && (self.arch != "bpf"
2843                    && self.arch != "hexagon"
2844                    && self.arch != "wasm32"
2845                    && self.arch != "wasm64")
2846            {
2847                check!(
2848                    !self.dynamic_linking,
2849                    "dynamic linking is not supported on this OS/architecture"
2850                );
2851            }
2852            if self.only_cdylib
2853                || self.crt_static_allows_dylibs
2854                || !self.late_link_args_dynamic.is_empty()
2855            {
2856                check!(
2857                    self.dynamic_linking,
2858                    "dynamic linking must be allowed when `only_cdylib` or `crt_static_allows_dylibs` or `late_link_args_dynamic` are set"
2859                );
2860            }
2861            // Apparently PIC was slow on wasm at some point, see comments in wasm_base.rs
2862            if self.dynamic_linking && !self.is_like_wasm {
2863                check_eq!(
2864                    self.relocation_model,
2865                    RelocModel::Pic,
2866                    "targets that support dynamic linking must use the `pic` relocation model"
2867                );
2868            }
2869            if self.position_independent_executables {
2870                check_eq!(
2871                    self.relocation_model,
2872                    RelocModel::Pic,
2873                    "targets that support position-independent executables must use the `pic` relocation model"
2874                );
2875            }
2876            // The UEFI targets do not support dynamic linking but still require PIC (#101377).
2877            if self.relocation_model == RelocModel::Pic && (self.os != "uefi") {
2878                check!(
2879                    self.dynamic_linking || self.position_independent_executables,
2880                    "when the relocation model is `pic`, the target must support dynamic linking or use position-independent executables. \
2881                Set the relocation model to `static` to avoid this requirement"
2882                );
2883            }
2884            if self.static_position_independent_executables {
2885                check!(
2886                    self.position_independent_executables,
2887                    "if `static_position_independent_executables` is set, then `position_independent_executables` must be set"
2888                );
2889            }
2890            if self.position_independent_executables {
2891                check!(
2892                    self.executables,
2893                    "if `position_independent_executables` is set then `executables` must be set"
2894                );
2895            }
2896        }
2897
2898        // Check crt static stuff
2899        if self.crt_static_default || self.crt_static_allows_dylibs {
2900            check!(
2901                self.crt_static_respected,
2902                "static CRT can be enabled but `crt_static_respected` is not set"
2903            );
2904        }
2905
2906        // Check that RISC-V targets always specify which ABI they use,
2907        // and that ARM targets specify their float ABI.
2908        match &*self.arch {
2909            "riscv32" => {
2910                check_matches!(
2911                    &*self.llvm_abiname,
2912                    "ilp32" | "ilp32f" | "ilp32d" | "ilp32e",
2913                    "invalid RISC-V ABI name: {}",
2914                    self.llvm_abiname,
2915                );
2916            }
2917            "riscv64" => {
2918                // Note that the `lp64e` is still unstable as it's not (yet) part of the ELF psABI.
2919                check_matches!(
2920                    &*self.llvm_abiname,
2921                    "lp64" | "lp64f" | "lp64d" | "lp64e",
2922                    "invalid RISC-V ABI name: {}",
2923                    self.llvm_abiname,
2924                );
2925            }
2926            "arm" => {
2927                check!(
2928                    self.llvm_floatabi.is_some(),
2929                    "ARM targets must set `llvm-floatabi` to `hard` or `soft`",
2930                )
2931            }
2932            _ => {}
2933        }
2934
2935        // Check consistency of Rust ABI declaration.
2936        if let Some(rust_abi) = self.rustc_abi {
2937            match rust_abi {
2938                RustcAbi::X86Sse2 => check_matches!(
2939                    &*self.arch,
2940                    "x86",
2941                    "`x86-sse2` ABI is only valid for x86-32 targets"
2942                ),
2943                RustcAbi::X86Softfloat => check_matches!(
2944                    &*self.arch,
2945                    "x86" | "x86_64",
2946                    "`x86-softfloat` ABI is only valid for x86 targets"
2947                ),
2948            }
2949        }
2950
2951        // Check that the given target-features string makes some basic sense.
2952        if !self.features.is_empty() {
2953            let mut features_enabled = FxHashSet::default();
2954            let mut features_disabled = FxHashSet::default();
2955            for feat in self.features.split(',') {
2956                if let Some(feat) = feat.strip_prefix("+") {
2957                    features_enabled.insert(feat);
2958                    if features_disabled.contains(feat) {
2959                        return Err(format!(
2960                            "target feature `{feat}` is both enabled and disabled"
2961                        ));
2962                    }
2963                } else if let Some(feat) = feat.strip_prefix("-") {
2964                    features_disabled.insert(feat);
2965                    if features_enabled.contains(feat) {
2966                        return Err(format!(
2967                            "target feature `{feat}` is both enabled and disabled"
2968                        ));
2969                    }
2970                } else {
2971                    return Err(format!(
2972                        "target feature `{feat}` is invalid, must start with `+` or `-`"
2973                    ));
2974                }
2975            }
2976            // Check that we don't mis-set any of the ABI-relevant features.
2977            let abi_feature_constraints = self.abi_required_features();
2978            for feat in abi_feature_constraints.required {
2979                // The feature might be enabled by default so we can't *require* it to show up.
2980                // But it must not be *disabled*.
2981                if features_disabled.contains(feat) {
2982                    return Err(format!(
2983                        "target feature `{feat}` is required by the ABI but gets disabled in target spec"
2984                    ));
2985                }
2986            }
2987            for feat in abi_feature_constraints.incompatible {
2988                // The feature might be disabled by default so we can't *require* it to show up.
2989                // But it must not be *enabled*.
2990                if features_enabled.contains(feat) {
2991                    return Err(format!(
2992                        "target feature `{feat}` is incompatible with the ABI but gets enabled in target spec"
2993                    ));
2994                }
2995            }
2996        }
2997
2998        Ok(())
2999    }
3000
3001    /// Test target self-consistency and JSON encoding/decoding roundtrip.
3002    #[cfg(test)]
3003    fn test_target(mut self) {
3004        let recycled_target =
3005            Target::from_json(&serde_json::to_string(&self.to_json()).unwrap()).map(|(j, _)| j);
3006        self.update_to_cli();
3007        self.check_consistency(TargetKind::Builtin).unwrap();
3008        assert_eq!(recycled_target, Ok(self));
3009    }
3010
3011    // Add your target to the whitelist if it has `std` library
3012    // and you certainly want "unknown" for the OS name.
3013    fn can_use_os_unknown(&self) -> bool {
3014        self.llvm_target == "wasm32-unknown-unknown"
3015            || self.llvm_target == "wasm64-unknown-unknown"
3016            || (self.env == "sgx" && self.vendor == "fortanix")
3017    }
3018
3019    /// Load a built-in target
3020    pub fn expect_builtin(target_tuple: &TargetTuple) -> Target {
3021        match *target_tuple {
3022            TargetTuple::TargetTuple(ref target_tuple) => {
3023                load_builtin(target_tuple).expect("built-in target")
3024            }
3025            TargetTuple::TargetJson { .. } => {
3026                panic!("built-in targets doesn't support target-paths")
3027            }
3028        }
3029    }
3030
3031    /// Load all built-in targets
3032    pub fn builtins() -> impl Iterator<Item = Target> {
3033        load_all_builtins()
3034    }
3035
3036    /// Search for a JSON file specifying the given target tuple.
3037    ///
3038    /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
3039    /// sysroot under the target-tuple's `rustlib` directory. Note that it could also just be a
3040    /// bare filename already, so also check for that. If one of the hardcoded targets we know
3041    /// about, just return it directly.
3042    ///
3043    /// The error string could come from any of the APIs called, including filesystem access and
3044    /// JSON decoding.
3045    pub fn search(
3046        target_tuple: &TargetTuple,
3047        sysroot: &Path,
3048    ) -> Result<(Target, TargetWarnings), String> {
3049        use std::{env, fs};
3050
3051        fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
3052            let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
3053            Target::from_json(&contents)
3054        }
3055
3056        match *target_tuple {
3057            TargetTuple::TargetTuple(ref target_tuple) => {
3058                // check if tuple is in list of built-in targets
3059                if let Some(t) = load_builtin(target_tuple) {
3060                    return Ok((t, TargetWarnings::empty()));
3061                }
3062
3063                // search for a file named `target_tuple`.json in RUST_TARGET_PATH
3064                let path = {
3065                    let mut target = target_tuple.to_string();
3066                    target.push_str(".json");
3067                    PathBuf::from(target)
3068                };
3069
3070                let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
3071
3072                for dir in env::split_paths(&target_path) {
3073                    let p = dir.join(&path);
3074                    if p.is_file() {
3075                        return load_file(&p);
3076                    }
3077                }
3078
3079                // Additionally look in the sysroot under `lib/rustlib/<tuple>/target.json`
3080                // as a fallback.
3081                let rustlib_path = crate::relative_target_rustlib_path(sysroot, target_tuple);
3082                let p = PathBuf::from_iter([
3083                    Path::new(sysroot),
3084                    Path::new(&rustlib_path),
3085                    Path::new("target.json"),
3086                ]);
3087                if p.is_file() {
3088                    return load_file(&p);
3089                }
3090
3091                // Leave in a specialized error message for the removed target.
3092                // FIXME: If you see this and it's been a few months after this has been released,
3093                // you can probably remove it.
3094                if target_tuple == "i586-pc-windows-msvc" {
3095                    Err("the `i586-pc-windows-msvc` target has been removed. Use the `i686-pc-windows-msvc` target instead.\n\
3096                        Windows 10 (the minimum required OS version) requires a CPU baseline of at least i686 so you can safely switch".into())
3097                } else {
3098                    Err(format!("could not find specification for target {target_tuple:?}"))
3099                }
3100            }
3101            TargetTuple::TargetJson { ref contents, .. } => Target::from_json(contents),
3102        }
3103    }
3104
3105    /// Return the target's small data threshold support, converting
3106    /// `DefaultForArch` into a concrete value.
3107    pub fn small_data_threshold_support(&self) -> SmallDataThresholdSupport {
3108        match &self.options.small_data_threshold_support {
3109            // Avoid having to duplicate the small data support in every
3110            // target file by supporting a default value for each
3111            // architecture.
3112            SmallDataThresholdSupport::DefaultForArch => match self.arch.as_ref() {
3113                "mips" | "mips64" | "mips32r6" => {
3114                    SmallDataThresholdSupport::LlvmArg("mips-ssection-threshold".into())
3115                }
3116                "hexagon" => {
3117                    SmallDataThresholdSupport::LlvmArg("hexagon-small-data-threshold".into())
3118                }
3119                "m68k" => SmallDataThresholdSupport::LlvmArg("m68k-ssection-threshold".into()),
3120                "riscv32" | "riscv64" => {
3121                    SmallDataThresholdSupport::LlvmModuleFlag("SmallDataLimit".into())
3122                }
3123                _ => SmallDataThresholdSupport::None,
3124            },
3125            s => s.clone(),
3126        }
3127    }
3128
3129    pub fn object_architecture(
3130        &self,
3131        unstable_target_features: &FxIndexSet<Symbol>,
3132    ) -> Option<(object::Architecture, Option<object::SubArchitecture>)> {
3133        use object::Architecture;
3134        Some(match self.arch.as_ref() {
3135            "arm" => (Architecture::Arm, None),
3136            "aarch64" => (
3137                if self.pointer_width == 32 {
3138                    Architecture::Aarch64_Ilp32
3139                } else {
3140                    Architecture::Aarch64
3141                },
3142                None,
3143            ),
3144            "x86" => (Architecture::I386, None),
3145            "s390x" => (Architecture::S390x, None),
3146            "m68k" => (Architecture::M68k, None),
3147            "mips" | "mips32r6" => (Architecture::Mips, None),
3148            "mips64" | "mips64r6" => (
3149                // While there are currently no builtin targets
3150                // using the N32 ABI, it is possible to specify
3151                // it using a custom target specification. N32
3152                // is an ILP32 ABI like the Aarch64_Ilp32
3153                // and X86_64_X32 cases above and below this one.
3154                if self.options.llvm_abiname.as_ref() == "n32" {
3155                    Architecture::Mips64_N32
3156                } else {
3157                    Architecture::Mips64
3158                },
3159                None,
3160            ),
3161            "x86_64" => (
3162                if self.pointer_width == 32 {
3163                    Architecture::X86_64_X32
3164                } else {
3165                    Architecture::X86_64
3166                },
3167                None,
3168            ),
3169            "powerpc" => (Architecture::PowerPc, None),
3170            "powerpc64" => (Architecture::PowerPc64, None),
3171            "riscv32" => (Architecture::Riscv32, None),
3172            "riscv64" => (Architecture::Riscv64, None),
3173            "sparc" => {
3174                if unstable_target_features.contains(&sym::v8plus) {
3175                    // Target uses V8+, aka EM_SPARC32PLUS, aka 64-bit V9 but in 32-bit mode
3176                    (Architecture::Sparc32Plus, None)
3177                } else {
3178                    // Target uses V7 or V8, aka EM_SPARC
3179                    (Architecture::Sparc, None)
3180                }
3181            }
3182            "sparc64" => (Architecture::Sparc64, None),
3183            "avr" => (Architecture::Avr, None),
3184            "msp430" => (Architecture::Msp430, None),
3185            "hexagon" => (Architecture::Hexagon, None),
3186            "xtensa" => (Architecture::Xtensa, None),
3187            "bpf" => (Architecture::Bpf, None),
3188            "loongarch32" => (Architecture::LoongArch32, None),
3189            "loongarch64" => (Architecture::LoongArch64, None),
3190            "csky" => (Architecture::Csky, None),
3191            "arm64ec" => (Architecture::Aarch64, Some(object::SubArchitecture::Arm64EC)),
3192            // Unsupported architecture.
3193            _ => return None,
3194        })
3195    }
3196
3197    /// Returns whether this target is known to have unreliable alignment:
3198    /// native C code for the target fails to align some data to the degree
3199    /// required by the C standard. We can't *really* do anything about that
3200    /// since unsafe Rust code may assume alignment any time, but we can at least
3201    /// inhibit some optimizations, and we suppress the alignment checks that
3202    /// would detect this unsoundness.
3203    ///
3204    /// Every target that returns less than `Align::MAX` here is still has a soundness bug.
3205    pub fn max_reliable_alignment(&self) -> Align {
3206        // FIXME(#112480) MSVC on x86-32 is unsound and fails to properly align many types with
3207        // more-than-4-byte-alignment on the stack. This makes alignments larger than 4 generally
3208        // unreliable on 32bit Windows.
3209        if self.is_like_windows && self.arch == "x86" {
3210            Align::from_bytes(4).unwrap()
3211        } else {
3212            Align::MAX
3213        }
3214    }
3215}
3216
3217/// Either a target tuple string or a path to a JSON file.
3218#[derive(Clone, Debug)]
3219pub enum TargetTuple {
3220    TargetTuple(String),
3221    TargetJson {
3222        /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
3223        /// inconsistencies as it is discarded during serialization.
3224        path_for_rustdoc: PathBuf,
3225        tuple: String,
3226        contents: String,
3227    },
3228}
3229
3230// Use a manual implementation to ignore the path field
3231impl PartialEq for TargetTuple {
3232    fn eq(&self, other: &Self) -> bool {
3233        match (self, other) {
3234            (Self::TargetTuple(l0), Self::TargetTuple(r0)) => l0 == r0,
3235            (
3236                Self::TargetJson { path_for_rustdoc: _, tuple: l_tuple, contents: l_contents },
3237                Self::TargetJson { path_for_rustdoc: _, tuple: r_tuple, contents: r_contents },
3238            ) => l_tuple == r_tuple && l_contents == r_contents,
3239            _ => false,
3240        }
3241    }
3242}
3243
3244// Use a manual implementation to ignore the path field
3245impl Hash for TargetTuple {
3246    fn hash<H: Hasher>(&self, state: &mut H) -> () {
3247        match self {
3248            TargetTuple::TargetTuple(tuple) => {
3249                0u8.hash(state);
3250                tuple.hash(state)
3251            }
3252            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3253                1u8.hash(state);
3254                tuple.hash(state);
3255                contents.hash(state)
3256            }
3257        }
3258    }
3259}
3260
3261// Use a manual implementation to prevent encoding the target json file path in the crate metadata
3262impl<S: Encoder> Encodable<S> for TargetTuple {
3263    fn encode(&self, s: &mut S) {
3264        match self {
3265            TargetTuple::TargetTuple(tuple) => {
3266                s.emit_u8(0);
3267                s.emit_str(tuple);
3268            }
3269            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3270                s.emit_u8(1);
3271                s.emit_str(tuple);
3272                s.emit_str(contents);
3273            }
3274        }
3275    }
3276}
3277
3278impl<D: Decoder> Decodable<D> for TargetTuple {
3279    fn decode(d: &mut D) -> Self {
3280        match d.read_u8() {
3281            0 => TargetTuple::TargetTuple(d.read_str().to_owned()),
3282            1 => TargetTuple::TargetJson {
3283                path_for_rustdoc: PathBuf::new(),
3284                tuple: d.read_str().to_owned(),
3285                contents: d.read_str().to_owned(),
3286            },
3287            _ => {
3288                panic!("invalid enum variant tag while decoding `TargetTuple`, expected 0..2");
3289            }
3290        }
3291    }
3292}
3293
3294impl TargetTuple {
3295    /// Creates a target tuple from the passed target tuple string.
3296    pub fn from_tuple(tuple: &str) -> Self {
3297        TargetTuple::TargetTuple(tuple.into())
3298    }
3299
3300    /// Creates a target tuple from the passed target path.
3301    pub fn from_path(path: &Path) -> Result<Self, io::Error> {
3302        let canonicalized_path = try_canonicalize(path)?;
3303        let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
3304            io::Error::new(
3305                io::ErrorKind::InvalidInput,
3306                format!("target path {canonicalized_path:?} is not a valid file: {err}"),
3307            )
3308        })?;
3309        let tuple = canonicalized_path
3310            .file_stem()
3311            .expect("target path must not be empty")
3312            .to_str()
3313            .expect("target path must be valid unicode")
3314            .to_owned();
3315        Ok(TargetTuple::TargetJson { path_for_rustdoc: canonicalized_path, tuple, contents })
3316    }
3317
3318    /// Returns a string tuple for this target.
3319    ///
3320    /// If this target is a path, the file name (without extension) is returned.
3321    pub fn tuple(&self) -> &str {
3322        match *self {
3323            TargetTuple::TargetTuple(ref tuple) | TargetTuple::TargetJson { ref tuple, .. } => {
3324                tuple
3325            }
3326        }
3327    }
3328
3329    /// Returns an extended string tuple for this target.
3330    ///
3331    /// If this target is a path, a hash of the path is appended to the tuple returned
3332    /// by `tuple()`.
3333    pub fn debug_tuple(&self) -> String {
3334        use std::hash::DefaultHasher;
3335
3336        match self {
3337            TargetTuple::TargetTuple(tuple) => tuple.to_owned(),
3338            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents: content } => {
3339                let mut hasher = DefaultHasher::new();
3340                content.hash(&mut hasher);
3341                let hash = hasher.finish();
3342                format!("{tuple}-{hash}")
3343            }
3344        }
3345    }
3346}
3347
3348impl fmt::Display for TargetTuple {
3349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3350        write!(f, "{}", self.debug_tuple())
3351    }
3352}
3353
3354into_diag_arg_using_display!(&TargetTuple);