rustc_target/spec/
mod.rs

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