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