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