1use core::result::Result;
41use std::borrow::Cow;
42use std::collections::BTreeMap;
43use std::hash::{Hash, Hasher};
44use std::ops::{Deref, DerefMut};
45use std::path::{Path, PathBuf};
46use std::str::FromStr;
47use std::{fmt, io};
48
49use rustc_abi::{
50    Align, CanonAbi, Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors,
51};
52use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
53use rustc_error_messages::{DiagArgValue, IntoDiagArg, into_diag_arg_using_display};
54use rustc_fs_util::try_canonicalize;
55use rustc_macros::{Decodable, Encodable, HashStable_Generic};
56use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
57use rustc_span::{Symbol, kw, sym};
58use serde_json::Value;
59use tracing::debug;
60
61use crate::json::{Json, ToJson};
62use crate::spec::crt_objects::CrtObjects;
63
64pub mod crt_objects;
65
66mod abi_map;
67mod base;
68mod json;
69
70pub use abi_map::{AbiMap, AbiMapping};
71pub use base::apple;
72pub use base::avr::ef_avr_arch;
73pub use json::json_schema;
74
75#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
77pub enum Cc {
78    Yes,
79    No,
80}
81
82#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
84pub enum Lld {
85    Yes,
86    No,
87}
88
89#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
110pub enum LinkerFlavor {
111    Gnu(Cc, Lld),
115    Darwin(Cc, Lld),
118    WasmLld(Cc),
122    Unix(Cc),
126    Msvc(Lld),
128    EmCc,
131    Bpf,
134    Ptx,
136    Llbc,
138}
139
140#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
145pub enum LinkerFlavorCli {
146    Gnu(Cc, Lld),
148    Darwin(Cc, Lld),
149    WasmLld(Cc),
150    Unix(Cc),
151    Msvc(Lld),
153    EmCc,
154    Bpf,
155    Ptx,
156    Llbc,
157
158    Gcc,
160    Ld,
161    Lld(LldFlavor),
162    Em,
163}
164
165impl LinkerFlavorCli {
166    pub fn is_unstable(&self) -> bool {
168        match self {
169            LinkerFlavorCli::Gnu(..)
170            | LinkerFlavorCli::Darwin(..)
171            | LinkerFlavorCli::WasmLld(..)
172            | LinkerFlavorCli::Unix(..)
173            | LinkerFlavorCli::Msvc(Lld::Yes)
174            | LinkerFlavorCli::EmCc
175            | LinkerFlavorCli::Bpf
176            | LinkerFlavorCli::Llbc
177            | LinkerFlavorCli::Ptx => true,
178            LinkerFlavorCli::Gcc
179            | LinkerFlavorCli::Ld
180            | LinkerFlavorCli::Lld(..)
181            | LinkerFlavorCli::Msvc(Lld::No)
182            | LinkerFlavorCli::Em => false,
183        }
184    }
185}
186
187crate::target_spec_enum! {
188    pub enum LldFlavor {
189        Wasm = "wasm",
190        Ld64 = "darwin",
191        Ld = "gnu",
192        Link = "link",
193    }
194
195    parse_error_type = "LLD flavor";
196}
197
198impl LinkerFlavor {
199    fn from_cli_json(cli: LinkerFlavorCli, lld_flavor: LldFlavor, is_gnu: bool) -> LinkerFlavor {
204        match cli {
205            LinkerFlavorCli::Gnu(cc, lld) => LinkerFlavor::Gnu(cc, lld),
206            LinkerFlavorCli::Darwin(cc, lld) => LinkerFlavor::Darwin(cc, lld),
207            LinkerFlavorCli::WasmLld(cc) => LinkerFlavor::WasmLld(cc),
208            LinkerFlavorCli::Unix(cc) => LinkerFlavor::Unix(cc),
209            LinkerFlavorCli::Msvc(lld) => LinkerFlavor::Msvc(lld),
210            LinkerFlavorCli::EmCc => LinkerFlavor::EmCc,
211            LinkerFlavorCli::Bpf => LinkerFlavor::Bpf,
212            LinkerFlavorCli::Llbc => LinkerFlavor::Llbc,
213            LinkerFlavorCli::Ptx => LinkerFlavor::Ptx,
214
215            LinkerFlavorCli::Gcc => match lld_flavor {
217                LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::Yes, Lld::No),
218                LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::Yes, Lld::No),
219                LldFlavor::Wasm => LinkerFlavor::WasmLld(Cc::Yes),
220                LldFlavor::Ld | LldFlavor::Link => LinkerFlavor::Unix(Cc::Yes),
221            },
222            LinkerFlavorCli::Ld => match lld_flavor {
223                LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::No, Lld::No),
224                LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::No, Lld::No),
225                LldFlavor::Ld | LldFlavor::Wasm | LldFlavor::Link => LinkerFlavor::Unix(Cc::No),
226            },
227            LinkerFlavorCli::Lld(LldFlavor::Ld) => LinkerFlavor::Gnu(Cc::No, Lld::Yes),
228            LinkerFlavorCli::Lld(LldFlavor::Ld64) => LinkerFlavor::Darwin(Cc::No, Lld::Yes),
229            LinkerFlavorCli::Lld(LldFlavor::Wasm) => LinkerFlavor::WasmLld(Cc::No),
230            LinkerFlavorCli::Lld(LldFlavor::Link) => LinkerFlavor::Msvc(Lld::Yes),
231            LinkerFlavorCli::Em => LinkerFlavor::EmCc,
232        }
233    }
234
235    fn to_cli(self) -> LinkerFlavorCli {
237        match self {
238            LinkerFlavor::Gnu(Cc::Yes, _)
239            | LinkerFlavor::Darwin(Cc::Yes, _)
240            | LinkerFlavor::WasmLld(Cc::Yes)
241            | LinkerFlavor::Unix(Cc::Yes) => LinkerFlavorCli::Gcc,
242            LinkerFlavor::Gnu(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld),
243            LinkerFlavor::Darwin(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld64),
244            LinkerFlavor::WasmLld(..) => LinkerFlavorCli::Lld(LldFlavor::Wasm),
245            LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
246                LinkerFlavorCli::Ld
247            }
248            LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Link),
249            LinkerFlavor::Msvc(..) => LinkerFlavorCli::Msvc(Lld::No),
250            LinkerFlavor::EmCc => LinkerFlavorCli::Em,
251            LinkerFlavor::Bpf => LinkerFlavorCli::Bpf,
252            LinkerFlavor::Llbc => LinkerFlavorCli::Llbc,
253            LinkerFlavor::Ptx => LinkerFlavorCli::Ptx,
254        }
255    }
256
257    fn to_cli_counterpart(self) -> LinkerFlavorCli {
259        match self {
260            LinkerFlavor::Gnu(cc, lld) => LinkerFlavorCli::Gnu(cc, lld),
261            LinkerFlavor::Darwin(cc, lld) => LinkerFlavorCli::Darwin(cc, lld),
262            LinkerFlavor::WasmLld(cc) => LinkerFlavorCli::WasmLld(cc),
263            LinkerFlavor::Unix(cc) => LinkerFlavorCli::Unix(cc),
264            LinkerFlavor::Msvc(lld) => LinkerFlavorCli::Msvc(lld),
265            LinkerFlavor::EmCc => LinkerFlavorCli::EmCc,
266            LinkerFlavor::Bpf => LinkerFlavorCli::Bpf,
267            LinkerFlavor::Llbc => LinkerFlavorCli::Llbc,
268            LinkerFlavor::Ptx => LinkerFlavorCli::Ptx,
269        }
270    }
271
272    fn infer_cli_hints(cli: LinkerFlavorCli) -> (Option<Cc>, Option<Lld>) {
273        match cli {
274            LinkerFlavorCli::Gnu(cc, lld) | LinkerFlavorCli::Darwin(cc, lld) => {
275                (Some(cc), Some(lld))
276            }
277            LinkerFlavorCli::WasmLld(cc) => (Some(cc), Some(Lld::Yes)),
278            LinkerFlavorCli::Unix(cc) => (Some(cc), None),
279            LinkerFlavorCli::Msvc(lld) => (Some(Cc::No), Some(lld)),
280            LinkerFlavorCli::EmCc => (Some(Cc::Yes), Some(Lld::Yes)),
281            LinkerFlavorCli::Bpf | LinkerFlavorCli::Ptx => (None, None),
282            LinkerFlavorCli::Llbc => (None, None),
283
284            LinkerFlavorCli::Gcc => (Some(Cc::Yes), None),
286            LinkerFlavorCli::Ld => (Some(Cc::No), Some(Lld::No)),
287            LinkerFlavorCli::Lld(_) => (Some(Cc::No), Some(Lld::Yes)),
288            LinkerFlavorCli::Em => (Some(Cc::Yes), Some(Lld::Yes)),
289        }
290    }
291
292    fn infer_linker_hints(linker_stem: &str) -> Result<Self, (Option<Cc>, Option<Lld>)> {
293        let stem = linker_stem
295            .rsplit_once('-')
296            .and_then(|(lhs, rhs)| rhs.chars().all(char::is_numeric).then_some(lhs))
297            .unwrap_or(linker_stem);
298
299        if stem == "llvm-bitcode-linker" {
300            Ok(Self::Llbc)
301        } else if stem == "emcc" || stem == "gcc"
303            || stem.ends_with("-gcc")
304            || stem == "g++"
305            || stem.ends_with("-g++")
306            || stem == "clang"
307            || stem.ends_with("-clang")
308            || stem == "clang++"
309            || stem.ends_with("-clang++")
310        {
311            Err((Some(Cc::Yes), Some(Lld::No)))
312        } else if stem == "wasm-ld"
313            || stem.ends_with("-wasm-ld")
314            || stem == "ld.lld"
315            || stem == "lld"
316            || stem == "rust-lld"
317            || stem == "lld-link"
318        {
319            Err((Some(Cc::No), Some(Lld::Yes)))
320        } else if stem == "ld" || stem.ends_with("-ld") || stem == "link" {
321            Err((Some(Cc::No), Some(Lld::No)))
322        } else {
323            Err((None, None))
324        }
325    }
326
327    fn with_hints(self, (cc_hint, lld_hint): (Option<Cc>, Option<Lld>)) -> LinkerFlavor {
328        match self {
329            LinkerFlavor::Gnu(cc, lld) => {
330                LinkerFlavor::Gnu(cc_hint.unwrap_or(cc), lld_hint.unwrap_or(lld))
331            }
332            LinkerFlavor::Darwin(cc, lld) => {
333                LinkerFlavor::Darwin(cc_hint.unwrap_or(cc), lld_hint.unwrap_or(lld))
334            }
335            LinkerFlavor::WasmLld(cc) => LinkerFlavor::WasmLld(cc_hint.unwrap_or(cc)),
336            LinkerFlavor::Unix(cc) => LinkerFlavor::Unix(cc_hint.unwrap_or(cc)),
337            LinkerFlavor::Msvc(lld) => LinkerFlavor::Msvc(lld_hint.unwrap_or(lld)),
338            LinkerFlavor::EmCc | LinkerFlavor::Bpf | LinkerFlavor::Llbc | LinkerFlavor::Ptx => self,
339        }
340    }
341
342    pub fn with_cli_hints(self, cli: LinkerFlavorCli) -> LinkerFlavor {
343        self.with_hints(LinkerFlavor::infer_cli_hints(cli))
344    }
345
346    pub fn with_linker_hints(self, linker_stem: &str) -> LinkerFlavor {
347        match LinkerFlavor::infer_linker_hints(linker_stem) {
348            Ok(linker_flavor) => linker_flavor,
349            Err(hints) => self.with_hints(hints),
350        }
351    }
352
353    pub fn check_compatibility(self, cli: LinkerFlavorCli) -> Option<String> {
354        let compatible = |cli| {
355            match (self, cli) {
357                (LinkerFlavor::Gnu(..), LinkerFlavorCli::Gnu(..))
359                | (LinkerFlavor::Darwin(..), LinkerFlavorCli::Darwin(..))
360                | (LinkerFlavor::WasmLld(..), LinkerFlavorCli::WasmLld(..))
361                | (LinkerFlavor::Unix(..), LinkerFlavorCli::Unix(..))
362                | (LinkerFlavor::Msvc(..), LinkerFlavorCli::Msvc(..))
363                | (LinkerFlavor::EmCc, LinkerFlavorCli::EmCc)
364                | (LinkerFlavor::Bpf, LinkerFlavorCli::Bpf)
365                | (LinkerFlavor::Llbc, LinkerFlavorCli::Llbc)
366                | (LinkerFlavor::Ptx, LinkerFlavorCli::Ptx) => return true,
367                (LinkerFlavor::Ptx, LinkerFlavorCli::Llbc) => return true,
369                _ => {}
370            }
371
372            cli == self.with_cli_hints(cli).to_cli()
374        };
375        (!compatible(cli)).then(|| {
376            LinkerFlavorCli::all()
377                .iter()
378                .filter(|cli| compatible(**cli))
379                .map(|cli| cli.desc())
380                .intersperse(", ")
381                .collect()
382        })
383    }
384
385    pub fn lld_flavor(self) -> LldFlavor {
386        match self {
387            LinkerFlavor::Gnu(..)
388            | LinkerFlavor::Unix(..)
389            | LinkerFlavor::EmCc
390            | LinkerFlavor::Bpf
391            | LinkerFlavor::Llbc
392            | LinkerFlavor::Ptx => LldFlavor::Ld,
393            LinkerFlavor::Darwin(..) => LldFlavor::Ld64,
394            LinkerFlavor::WasmLld(..) => LldFlavor::Wasm,
395            LinkerFlavor::Msvc(..) => LldFlavor::Link,
396        }
397    }
398
399    pub fn is_gnu(self) -> bool {
400        matches!(self, LinkerFlavor::Gnu(..))
401    }
402
403    pub fn uses_lld(self) -> bool {
405        match self {
407            LinkerFlavor::Gnu(_, Lld::Yes)
408            | LinkerFlavor::Darwin(_, Lld::Yes)
409            | LinkerFlavor::WasmLld(..)
410            | LinkerFlavor::EmCc
411            | LinkerFlavor::Msvc(Lld::Yes) => true,
412            LinkerFlavor::Gnu(..)
413            | LinkerFlavor::Darwin(..)
414            | LinkerFlavor::Msvc(_)
415            | LinkerFlavor::Unix(_)
416            | LinkerFlavor::Bpf
417            | LinkerFlavor::Llbc
418            | LinkerFlavor::Ptx => false,
419        }
420    }
421
422    pub fn uses_cc(self) -> bool {
424        match self {
426            LinkerFlavor::Gnu(Cc::Yes, _)
427            | LinkerFlavor::Darwin(Cc::Yes, _)
428            | LinkerFlavor::WasmLld(Cc::Yes)
429            | LinkerFlavor::Unix(Cc::Yes)
430            | LinkerFlavor::EmCc => true,
431            LinkerFlavor::Gnu(..)
432            | LinkerFlavor::Darwin(..)
433            | LinkerFlavor::WasmLld(_)
434            | LinkerFlavor::Msvc(_)
435            | LinkerFlavor::Unix(_)
436            | LinkerFlavor::Bpf
437            | LinkerFlavor::Llbc
438            | LinkerFlavor::Ptx => false,
439        }
440    }
441
442    pub fn with_lld_enabled(self) -> LinkerFlavor {
445        match self {
446            LinkerFlavor::Gnu(cc, Lld::No) => LinkerFlavor::Gnu(cc, Lld::Yes),
447            LinkerFlavor::Darwin(cc, Lld::No) => LinkerFlavor::Darwin(cc, Lld::Yes),
448            LinkerFlavor::Msvc(Lld::No) => LinkerFlavor::Msvc(Lld::Yes),
449            _ => self,
450        }
451    }
452
453    pub fn with_lld_disabled(self) -> LinkerFlavor {
456        match self {
457            LinkerFlavor::Gnu(cc, Lld::Yes) => LinkerFlavor::Gnu(cc, Lld::No),
458            LinkerFlavor::Darwin(cc, Lld::Yes) => LinkerFlavor::Darwin(cc, Lld::No),
459            LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavor::Msvc(Lld::No),
460            _ => self,
461        }
462    }
463}
464
465macro_rules! linker_flavor_cli_impls {
466    ($(($($flavor:tt)*) $string:literal)*) => (
467        impl LinkerFlavorCli {
468            const fn all() -> &'static [LinkerFlavorCli] {
469                &[$($($flavor)*,)*]
470            }
471
472            pub const fn one_of() -> &'static str {
473                concat!("one of: ", $($string, " ",)*)
474            }
475
476            pub fn desc(self) -> &'static str {
477                match self {
478                    $($($flavor)* => $string,)*
479                }
480            }
481        }
482
483        impl FromStr for LinkerFlavorCli {
484            type Err = String;
485
486            fn from_str(s: &str) -> Result<LinkerFlavorCli, Self::Err> {
487                Ok(match s {
488                    $($string => $($flavor)*,)*
489                    _ => return Err(format!("invalid linker flavor, allowed values: {}", Self::one_of())),
490                })
491            }
492        }
493    )
494}
495
496linker_flavor_cli_impls! {
497    (LinkerFlavorCli::Gnu(Cc::No, Lld::No)) "gnu"
498    (LinkerFlavorCli::Gnu(Cc::No, Lld::Yes)) "gnu-lld"
499    (LinkerFlavorCli::Gnu(Cc::Yes, Lld::No)) "gnu-cc"
500    (LinkerFlavorCli::Gnu(Cc::Yes, Lld::Yes)) "gnu-lld-cc"
501    (LinkerFlavorCli::Darwin(Cc::No, Lld::No)) "darwin"
502    (LinkerFlavorCli::Darwin(Cc::No, Lld::Yes)) "darwin-lld"
503    (LinkerFlavorCli::Darwin(Cc::Yes, Lld::No)) "darwin-cc"
504    (LinkerFlavorCli::Darwin(Cc::Yes, Lld::Yes)) "darwin-lld-cc"
505    (LinkerFlavorCli::WasmLld(Cc::No)) "wasm-lld"
506    (LinkerFlavorCli::WasmLld(Cc::Yes)) "wasm-lld-cc"
507    (LinkerFlavorCli::Unix(Cc::No)) "unix"
508    (LinkerFlavorCli::Unix(Cc::Yes)) "unix-cc"
509    (LinkerFlavorCli::Msvc(Lld::Yes)) "msvc-lld"
510    (LinkerFlavorCli::Msvc(Lld::No)) "msvc"
511    (LinkerFlavorCli::EmCc) "em-cc"
512    (LinkerFlavorCli::Bpf) "bpf"
513    (LinkerFlavorCli::Llbc) "llbc"
514    (LinkerFlavorCli::Ptx) "ptx"
515
516    (LinkerFlavorCli::Gcc) "gcc"
518    (LinkerFlavorCli::Ld) "ld"
519    (LinkerFlavorCli::Lld(LldFlavor::Ld)) "ld.lld"
520    (LinkerFlavorCli::Lld(LldFlavor::Ld64)) "ld64.lld"
521    (LinkerFlavorCli::Lld(LldFlavor::Link)) "lld-link"
522    (LinkerFlavorCli::Lld(LldFlavor::Wasm)) "wasm-ld"
523    (LinkerFlavorCli::Em) "em"
524}
525
526crate::json::serde_deserialize_from_str!(LinkerFlavorCli);
527impl schemars::JsonSchema for LinkerFlavorCli {
528    fn schema_name() -> std::borrow::Cow<'static, str> {
529        "LinkerFlavor".into()
530    }
531    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
532        let all: Vec<&'static str> =
533            Self::all().iter().map(|flavor| flavor.desc()).collect::<Vec<_>>();
534        schemars::json_schema! ({
535            "type": "string",
536            "enum": all
537        })
538        .into()
539    }
540}
541
542impl ToJson for LinkerFlavorCli {
543    fn to_json(&self) -> Json {
544        self.desc().to_json()
545    }
546}
547
548#[derive(Clone, Copy, PartialEq, Debug)]
555pub enum LinkSelfContainedDefault {
556    True,
558
559    False,
561
562    InferredForMusl,
564
565    InferredForMingw,
567
568    WithComponents(LinkSelfContainedComponents),
571}
572
573impl FromStr for LinkSelfContainedDefault {
575    type Err = String;
576
577    fn from_str(s: &str) -> Result<LinkSelfContainedDefault, Self::Err> {
578        Ok(match s {
579            "false" => LinkSelfContainedDefault::False,
580            "true" | "wasm" => LinkSelfContainedDefault::True,
581            "musl" => LinkSelfContainedDefault::InferredForMusl,
582            "mingw" => LinkSelfContainedDefault::InferredForMingw,
583            _ => {
584                return Err(format!(
585                    "'{s}' is not a valid `-Clink-self-contained` default. \
586                        Use 'false', 'true', 'wasm', 'musl' or 'mingw'",
587                ));
588            }
589        })
590    }
591}
592
593crate::json::serde_deserialize_from_str!(LinkSelfContainedDefault);
594impl schemars::JsonSchema for LinkSelfContainedDefault {
595    fn schema_name() -> std::borrow::Cow<'static, str> {
596        "LinkSelfContainedDefault".into()
597    }
598    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
599        schemars::json_schema! ({
600            "type": "string",
601            "enum": ["false", "true", "wasm", "musl", "mingw"]
602        })
603        .into()
604    }
605}
606
607impl ToJson for LinkSelfContainedDefault {
608    fn to_json(&self) -> Json {
609        match *self {
610            LinkSelfContainedDefault::WithComponents(components) => {
611                let mut map = BTreeMap::new();
615                map.insert("components", components);
616                map.to_json()
617            }
618
619            LinkSelfContainedDefault::True => "true".to_json(),
621            LinkSelfContainedDefault::False => "false".to_json(),
622            LinkSelfContainedDefault::InferredForMusl => "musl".to_json(),
623            LinkSelfContainedDefault::InferredForMingw => "mingw".to_json(),
624        }
625    }
626}
627
628impl LinkSelfContainedDefault {
629    pub fn is_disabled(self) -> bool {
632        self == LinkSelfContainedDefault::False
633    }
634
635    fn json_key(self) -> &'static str {
639        match self {
640            LinkSelfContainedDefault::WithComponents(_) => "link-self-contained",
641            _ => "crt-objects-fallback",
642        }
643    }
644
645    pub fn with_linker() -> LinkSelfContainedDefault {
648        LinkSelfContainedDefault::WithComponents(LinkSelfContainedComponents::LINKER)
649    }
650}
651
652bitflags::bitflags! {
653    #[derive(Clone, Copy, PartialEq, Eq, Default)]
654    pub struct LinkSelfContainedComponents: u8 {
656        const CRT_OBJECTS = 1 << 0;
658        const LIBC        = 1 << 1;
660        const UNWIND      = 1 << 2;
662        const LINKER      = 1 << 3;
664        const SANITIZERS  = 1 << 4;
666        const MINGW       = 1 << 5;
668    }
669}
670rustc_data_structures::external_bitflags_debug! { LinkSelfContainedComponents }
671
672impl LinkSelfContainedComponents {
673    pub fn as_str(self) -> Option<&'static str> {
677        Some(match self {
678            LinkSelfContainedComponents::CRT_OBJECTS => "crto",
679            LinkSelfContainedComponents::LIBC => "libc",
680            LinkSelfContainedComponents::UNWIND => "unwind",
681            LinkSelfContainedComponents::LINKER => "linker",
682            LinkSelfContainedComponents::SANITIZERS => "sanitizers",
683            LinkSelfContainedComponents::MINGW => "mingw",
684            _ => return None,
685        })
686    }
687
688    fn all_components() -> [LinkSelfContainedComponents; 6] {
690        [
691            LinkSelfContainedComponents::CRT_OBJECTS,
692            LinkSelfContainedComponents::LIBC,
693            LinkSelfContainedComponents::UNWIND,
694            LinkSelfContainedComponents::LINKER,
695            LinkSelfContainedComponents::SANITIZERS,
696            LinkSelfContainedComponents::MINGW,
697        ]
698    }
699
700    pub fn are_any_components_enabled(self) -> bool {
702        !self.is_empty()
703    }
704
705    pub fn is_linker_enabled(self) -> bool {
707        self.contains(LinkSelfContainedComponents::LINKER)
708    }
709
710    pub fn is_crt_objects_enabled(self) -> bool {
712        self.contains(LinkSelfContainedComponents::CRT_OBJECTS)
713    }
714}
715
716impl FromStr for LinkSelfContainedComponents {
717    type Err = String;
718
719    fn from_str(s: &str) -> Result<Self, Self::Err> {
721        Ok(match s {
722            "crto" => LinkSelfContainedComponents::CRT_OBJECTS,
723            "libc" => LinkSelfContainedComponents::LIBC,
724            "unwind" => LinkSelfContainedComponents::UNWIND,
725            "linker" => LinkSelfContainedComponents::LINKER,
726            "sanitizers" => LinkSelfContainedComponents::SANITIZERS,
727            "mingw" => LinkSelfContainedComponents::MINGW,
728            _ => {
729                return Err(format!(
730                    "'{s}' is not a valid link-self-contained component, expected 'crto', 'libc', 'unwind', 'linker', 'sanitizers', 'mingw'"
731                ));
732            }
733        })
734    }
735}
736
737crate::json::serde_deserialize_from_str!(LinkSelfContainedComponents);
738impl schemars::JsonSchema for LinkSelfContainedComponents {
739    fn schema_name() -> std::borrow::Cow<'static, str> {
740        "LinkSelfContainedComponents".into()
741    }
742    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
743        let all =
744            Self::all_components().iter().map(|component| component.as_str()).collect::<Vec<_>>();
745        schemars::json_schema! ({
746            "type": "string",
747            "enum": all,
748        })
749        .into()
750    }
751}
752
753impl ToJson for LinkSelfContainedComponents {
754    fn to_json(&self) -> Json {
755        let components: Vec<_> = Self::all_components()
756            .into_iter()
757            .filter(|c| self.contains(*c))
758            .map(|c| {
759                c.as_str().unwrap().to_owned()
762            })
763            .collect();
764
765        components.to_json()
766    }
767}
768
769bitflags::bitflags! {
770    #[derive(Clone, Copy, PartialEq, Eq, Default)]
791    pub struct LinkerFeatures: u8 {
792        const CC  = 1 << 0;
794        const LLD = 1 << 1;
796    }
797}
798rustc_data_structures::external_bitflags_debug! { LinkerFeatures }
799
800impl LinkerFeatures {
801    pub fn from_str(s: &str) -> Option<LinkerFeatures> {
803        Some(match s {
804            "cc" => LinkerFeatures::CC,
805            "lld" => LinkerFeatures::LLD,
806            _ => return None,
807        })
808    }
809
810    pub fn as_str(self) -> Option<&'static str> {
814        Some(match self {
815            LinkerFeatures::CC => "cc",
816            LinkerFeatures::LLD => "lld",
817            _ => return None,
818        })
819    }
820
821    pub fn is_lld_enabled(self) -> bool {
823        self.contains(LinkerFeatures::LLD)
824    }
825
826    pub fn is_cc_enabled(self) -> bool {
828        self.contains(LinkerFeatures::CC)
829    }
830}
831
832crate::target_spec_enum! {
833    #[derive(Encodable, Decodable, HashStable_Generic)]
834    pub enum PanicStrategy {
835        Unwind = "unwind",
836        Abort = "abort",
837        ImmediateAbort = "immediate-abort",
838    }
839
840    parse_error_type = "panic strategy";
841}
842
843#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
844pub enum OnBrokenPipe {
845    Default,
846    Kill,
847    Error,
848    Inherit,
849}
850
851impl PanicStrategy {
852    pub const fn desc_symbol(&self) -> Symbol {
853        match *self {
854            PanicStrategy::Unwind => sym::unwind,
855            PanicStrategy::Abort => sym::abort,
856            PanicStrategy::ImmediateAbort => sym::immediate_abort,
857        }
858    }
859
860    pub fn unwinds(self) -> bool {
861        matches!(self, PanicStrategy::Unwind)
862    }
863}
864
865crate::target_spec_enum! {
866    pub enum RelroLevel {
867        Full = "full",
868        Partial = "partial",
869        Off = "off",
870        None = "none",
871    }
872
873    parse_error_type = "relro level";
874}
875
876impl IntoDiagArg for PanicStrategy {
877    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
878        DiagArgValue::Str(Cow::Owned(self.desc().to_string()))
879    }
880}
881
882crate::target_spec_enum! {
883    pub enum SymbolVisibility {
884        Hidden = "hidden",
885        Protected = "protected",
886        Interposable = "interposable",
887    }
888
889    parse_error_type = "symbol visibility";
890}
891
892#[derive(Clone, Debug, PartialEq, Hash)]
893pub enum SmallDataThresholdSupport {
894    None,
895    DefaultForArch,
896    LlvmModuleFlag(StaticCow<str>),
897    LlvmArg(StaticCow<str>),
898}
899
900impl FromStr for SmallDataThresholdSupport {
901    type Err = String;
902
903    fn from_str(s: &str) -> Result<Self, Self::Err> {
904        if s == "none" {
905            Ok(Self::None)
906        } else if s == "default-for-arch" {
907            Ok(Self::DefaultForArch)
908        } else if let Some(flag) = s.strip_prefix("llvm-module-flag=") {
909            Ok(Self::LlvmModuleFlag(flag.to_string().into()))
910        } else if let Some(arg) = s.strip_prefix("llvm-arg=") {
911            Ok(Self::LlvmArg(arg.to_string().into()))
912        } else {
913            Err(format!("'{s}' is not a valid value for small-data-threshold-support."))
914        }
915    }
916}
917
918crate::json::serde_deserialize_from_str!(SmallDataThresholdSupport);
919impl schemars::JsonSchema for SmallDataThresholdSupport {
920    fn schema_name() -> std::borrow::Cow<'static, str> {
921        "SmallDataThresholdSupport".into()
922    }
923    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
924        schemars::json_schema! ({
925            "type": "string",
926            "pattern": r#"^none|default-for-arch|llvm-module-flag=.+|llvm-arg=.+$"#,
927        })
928        .into()
929    }
930}
931
932impl ToJson for SmallDataThresholdSupport {
933    fn to_json(&self) -> Value {
934        match self {
935            Self::None => "none".to_json(),
936            Self::DefaultForArch => "default-for-arch".to_json(),
937            Self::LlvmModuleFlag(flag) => format!("llvm-module-flag={flag}").to_json(),
938            Self::LlvmArg(arg) => format!("llvm-arg={arg}").to_json(),
939        }
940    }
941}
942
943crate::target_spec_enum! {
944    pub enum MergeFunctions {
945        Disabled = "disabled",
946        Trampolines = "trampolines",
947        Aliases = "aliases",
948    }
949
950    parse_error_type = "value for merge-functions";
951}
952
953crate::target_spec_enum! {
954    pub enum RelocModel {
955        Static = "static",
956        Pic = "pic",
957        Pie = "pie",
958        DynamicNoPic = "dynamic-no-pic",
959        Ropi = "ropi",
960        Rwpi = "rwpi",
961        RopiRwpi = "ropi-rwpi",
962    }
963
964    parse_error_type = "relocation model";
965}
966
967impl RelocModel {
968    pub const fn desc_symbol(&self) -> Symbol {
969        match *self {
970            RelocModel::Static => kw::Static,
971            RelocModel::Pic => sym::pic,
972            RelocModel::Pie => sym::pie,
973            RelocModel::DynamicNoPic => sym::dynamic_no_pic,
974            RelocModel::Ropi => sym::ropi,
975            RelocModel::Rwpi => sym::rwpi,
976            RelocModel::RopiRwpi => sym::ropi_rwpi,
977        }
978    }
979}
980
981crate::target_spec_enum! {
982    pub enum CodeModel {
983        Tiny = "tiny",
984        Small = "small",
985        Kernel = "kernel",
986        Medium = "medium",
987        Large = "large",
988    }
989
990    parse_error_type = "code model";
991}
992
993crate::target_spec_enum! {
994    pub enum FloatAbi {
996        Soft = "soft",
997        Hard = "hard",
998    }
999
1000    parse_error_type = "float abi";
1001}
1002
1003crate::target_spec_enum! {
1004    pub enum RustcAbi {
1006        X86Sse2 = "x86-sse2",
1008        X86Softfloat = "x86-softfloat",
1010    }
1011
1012    parse_error_type = "rustc abi";
1013}
1014
1015crate::target_spec_enum! {
1016    pub enum TlsModel {
1017        GeneralDynamic = "global-dynamic",
1018        LocalDynamic = "local-dynamic",
1019        InitialExec = "initial-exec",
1020        LocalExec = "local-exec",
1021        Emulated = "emulated",
1022    }
1023
1024    parse_error_type = "TLS model";
1025}
1026
1027crate::target_spec_enum! {
1028    pub enum LinkOutputKind {
1030        DynamicNoPicExe = "dynamic-nopic-exe",
1032        DynamicPicExe = "dynamic-pic-exe",
1034        StaticNoPicExe = "static-nopic-exe",
1036        StaticPicExe = "static-pic-exe",
1038        DynamicDylib = "dynamic-dylib",
1040        StaticDylib = "static-dylib",
1042        WasiReactorExe = "wasi-reactor-exe",
1044    }
1045
1046    parse_error_type = "CRT object kind";
1047}
1048
1049impl LinkOutputKind {
1050    pub fn can_link_dylib(self) -> bool {
1051        match self {
1052            LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe => false,
1053            LinkOutputKind::DynamicNoPicExe
1054            | LinkOutputKind::DynamicPicExe
1055            | LinkOutputKind::DynamicDylib
1056            | LinkOutputKind::StaticDylib
1057            | LinkOutputKind::WasiReactorExe => true,
1058        }
1059    }
1060}
1061
1062pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
1063pub type LinkArgsCli = BTreeMap<LinkerFlavorCli, Vec<StaticCow<str>>>;
1064
1065crate::target_spec_enum! {
1066    #[derive(Default)]
1071    pub enum DebuginfoKind {
1072        #[default]
1074        Dwarf = "dwarf",
1075        DwarfDsym = "dwarf-dsym",
1077        Pdb = "pdb",
1079    }
1080
1081    parse_error_type = "debuginfo kind";
1082}
1083
1084crate::target_spec_enum! {
1085    #[derive(Default)]
1086    pub enum SplitDebuginfo {
1087        #[default]
1095        Off = "off",
1096
1097        Packed = "packed",
1104
1105        Unpacked = "unpacked",
1112    }
1113
1114    parse_error_type = "split debuginfo";
1115}
1116
1117into_diag_arg_using_display!(SplitDebuginfo);
1118
1119#[derive(Clone, Debug, PartialEq, Eq, serde_derive::Deserialize, schemars::JsonSchema)]
1120#[serde(tag = "kind")]
1121#[serde(rename_all = "kebab-case")]
1122pub enum StackProbeType {
1123    None,
1125    Inline,
1129    Call,
1131    InlineOrCall {
1134        #[serde(rename = "min-llvm-version-for-inline")]
1135        min_llvm_version_for_inline: (u32, u32, u32),
1136    },
1137}
1138
1139impl ToJson for StackProbeType {
1140    fn to_json(&self) -> Json {
1141        Json::Object(match self {
1142            StackProbeType::None => {
1143                [(String::from("kind"), "none".to_json())].into_iter().collect()
1144            }
1145            StackProbeType::Inline => {
1146                [(String::from("kind"), "inline".to_json())].into_iter().collect()
1147            }
1148            StackProbeType::Call => {
1149                [(String::from("kind"), "call".to_json())].into_iter().collect()
1150            }
1151            StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
1152                (String::from("kind"), "inline-or-call".to_json()),
1153                (
1154                    String::from("min-llvm-version-for-inline"),
1155                    Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
1156                ),
1157            ]
1158            .into_iter()
1159            .collect(),
1160        })
1161    }
1162}
1163
1164#[derive(Default, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
1165pub struct SanitizerSet(u16);
1166bitflags::bitflags! {
1167    impl SanitizerSet: u16 {
1168        const ADDRESS = 1 << 0;
1169        const LEAK    = 1 << 1;
1170        const MEMORY  = 1 << 2;
1171        const THREAD  = 1 << 3;
1172        const HWADDRESS = 1 << 4;
1173        const CFI     = 1 << 5;
1174        const MEMTAG  = 1 << 6;
1175        const SHADOWCALLSTACK = 1 << 7;
1176        const KCFI    = 1 << 8;
1177        const KERNELADDRESS = 1 << 9;
1178        const SAFESTACK = 1 << 10;
1179        const DATAFLOW = 1 << 11;
1180    }
1181}
1182rustc_data_structures::external_bitflags_debug! { SanitizerSet }
1183
1184impl SanitizerSet {
1185    const MUTUALLY_EXCLUSIVE: &'static [(SanitizerSet, SanitizerSet)] = &[
1188        (SanitizerSet::ADDRESS, SanitizerSet::MEMORY),
1189        (SanitizerSet::ADDRESS, SanitizerSet::THREAD),
1190        (SanitizerSet::ADDRESS, SanitizerSet::HWADDRESS),
1191        (SanitizerSet::ADDRESS, SanitizerSet::MEMTAG),
1192        (SanitizerSet::ADDRESS, SanitizerSet::KERNELADDRESS),
1193        (SanitizerSet::ADDRESS, SanitizerSet::SAFESTACK),
1194        (SanitizerSet::LEAK, SanitizerSet::MEMORY),
1195        (SanitizerSet::LEAK, SanitizerSet::THREAD),
1196        (SanitizerSet::LEAK, SanitizerSet::KERNELADDRESS),
1197        (SanitizerSet::LEAK, SanitizerSet::SAFESTACK),
1198        (SanitizerSet::MEMORY, SanitizerSet::THREAD),
1199        (SanitizerSet::MEMORY, SanitizerSet::HWADDRESS),
1200        (SanitizerSet::MEMORY, SanitizerSet::KERNELADDRESS),
1201        (SanitizerSet::MEMORY, SanitizerSet::SAFESTACK),
1202        (SanitizerSet::THREAD, SanitizerSet::HWADDRESS),
1203        (SanitizerSet::THREAD, SanitizerSet::KERNELADDRESS),
1204        (SanitizerSet::THREAD, SanitizerSet::SAFESTACK),
1205        (SanitizerSet::HWADDRESS, SanitizerSet::MEMTAG),
1206        (SanitizerSet::HWADDRESS, SanitizerSet::KERNELADDRESS),
1207        (SanitizerSet::HWADDRESS, SanitizerSet::SAFESTACK),
1208        (SanitizerSet::CFI, SanitizerSet::KCFI),
1209        (SanitizerSet::MEMTAG, SanitizerSet::KERNELADDRESS),
1210        (SanitizerSet::KERNELADDRESS, SanitizerSet::SAFESTACK),
1211    ];
1212
1213    pub fn as_str(self) -> Option<&'static str> {
1217        Some(match self {
1218            SanitizerSet::ADDRESS => "address",
1219            SanitizerSet::CFI => "cfi",
1220            SanitizerSet::DATAFLOW => "dataflow",
1221            SanitizerSet::KCFI => "kcfi",
1222            SanitizerSet::KERNELADDRESS => "kernel-address",
1223            SanitizerSet::LEAK => "leak",
1224            SanitizerSet::MEMORY => "memory",
1225            SanitizerSet::MEMTAG => "memtag",
1226            SanitizerSet::SAFESTACK => "safestack",
1227            SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
1228            SanitizerSet::THREAD => "thread",
1229            SanitizerSet::HWADDRESS => "hwaddress",
1230            _ => return None,
1231        })
1232    }
1233
1234    pub fn mutually_exclusive(self) -> Option<(SanitizerSet, SanitizerSet)> {
1235        Self::MUTUALLY_EXCLUSIVE
1236            .into_iter()
1237            .find(|&(a, b)| self.contains(*a) && self.contains(*b))
1238            .copied()
1239    }
1240}
1241
1242impl fmt::Display for SanitizerSet {
1244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245        let mut first = true;
1246        for s in *self {
1247            let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {s:?}"));
1248            if !first {
1249                f.write_str(", ")?;
1250            }
1251            f.write_str(name)?;
1252            first = false;
1253        }
1254        Ok(())
1255    }
1256}
1257
1258impl FromStr for SanitizerSet {
1259    type Err = String;
1260    fn from_str(s: &str) -> Result<Self, Self::Err> {
1261        Ok(match s {
1262            "address" => SanitizerSet::ADDRESS,
1263            "cfi" => SanitizerSet::CFI,
1264            "dataflow" => SanitizerSet::DATAFLOW,
1265            "kcfi" => SanitizerSet::KCFI,
1266            "kernel-address" => SanitizerSet::KERNELADDRESS,
1267            "leak" => SanitizerSet::LEAK,
1268            "memory" => SanitizerSet::MEMORY,
1269            "memtag" => SanitizerSet::MEMTAG,
1270            "safestack" => SanitizerSet::SAFESTACK,
1271            "shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
1272            "thread" => SanitizerSet::THREAD,
1273            "hwaddress" => SanitizerSet::HWADDRESS,
1274            s => return Err(format!("unknown sanitizer {s}")),
1275        })
1276    }
1277}
1278
1279crate::json::serde_deserialize_from_str!(SanitizerSet);
1280impl schemars::JsonSchema for SanitizerSet {
1281    fn schema_name() -> std::borrow::Cow<'static, str> {
1282        "SanitizerSet".into()
1283    }
1284    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1285        let all = Self::all().iter().map(|sanitizer| sanitizer.as_str()).collect::<Vec<_>>();
1286        schemars::json_schema! ({
1287            "type": "string",
1288            "enum": all,
1289        })
1290        .into()
1291    }
1292}
1293
1294impl ToJson for SanitizerSet {
1295    fn to_json(&self) -> Json {
1296        self.into_iter()
1297            .map(|v| Some(v.as_str()?.to_json()))
1298            .collect::<Option<Vec<_>>>()
1299            .unwrap_or_default()
1300            .to_json()
1301    }
1302}
1303
1304crate::target_spec_enum! {
1305    pub enum FramePointer {
1306        Always = "always",
1308        NonLeaf = "non-leaf",
1311        MayOmit = "may-omit",
1315    }
1316
1317    parse_error_type = "frame pointer";
1318}
1319
1320impl FramePointer {
1321    #[inline]
1324    pub fn ratchet(&mut self, rhs: FramePointer) -> FramePointer {
1325        *self = match (*self, rhs) {
1326            (FramePointer::Always, _) | (_, FramePointer::Always) => FramePointer::Always,
1327            (FramePointer::NonLeaf, _) | (_, FramePointer::NonLeaf) => FramePointer::NonLeaf,
1328            _ => FramePointer::MayOmit,
1329        };
1330        *self
1331    }
1332}
1333
1334crate::target_spec_enum! {
1335    pub enum StackProtector {
1337        None = "none",
1339
1340        Basic = "basic",
1345
1346        Strong = "strong",
1351
1352        All = "all",
1354    }
1355
1356    parse_error_type = "stack protector";
1357}
1358
1359into_diag_arg_using_display!(StackProtector);
1360
1361crate::target_spec_enum! {
1362    pub enum BinaryFormat {
1363        Coff = "coff",
1364        Elf = "elf",
1365        MachO = "mach-o",
1366        Wasm = "wasm",
1367        Xcoff = "xcoff",
1368    }
1369
1370    parse_error_type = "binary format";
1371}
1372
1373impl BinaryFormat {
1374    pub fn to_object(&self) -> object::BinaryFormat {
1376        match self {
1377            Self::Coff => object::BinaryFormat::Coff,
1378            Self::Elf => object::BinaryFormat::Elf,
1379            Self::MachO => object::BinaryFormat::MachO,
1380            Self::Wasm => object::BinaryFormat::Wasm,
1381            Self::Xcoff => object::BinaryFormat::Xcoff,
1382        }
1383    }
1384}
1385
1386impl ToJson for Align {
1387    fn to_json(&self) -> Json {
1388        self.bits().to_json()
1389    }
1390}
1391
1392macro_rules! supported_targets {
1393    ( $(($tuple:literal, $module:ident),)+ ) => {
1394        mod targets {
1395            $(pub(crate) mod $module;)+
1396        }
1397
1398        pub static TARGETS: &[&str] = &[$($tuple),+];
1400
1401        fn load_builtin(target: &str) -> Option<Target> {
1402            let t = match target {
1403                $( $tuple => targets::$module::target(), )+
1404                _ => return None,
1405            };
1406            debug!("got builtin target: {:?}", t);
1407            Some(t)
1408        }
1409
1410        fn load_all_builtins() -> impl Iterator<Item = Target> {
1411            [
1412                $( targets::$module::target, )+
1413            ]
1414            .into_iter()
1415            .map(|f| f())
1416        }
1417
1418        #[cfg(test)]
1419        mod tests {
1420            $(
1422                #[test] fn $module() {
1424                    crate::spec::targets::$module::target().test_target()
1425                }
1426            )+
1427        }
1428    };
1429}
1430
1431supported_targets! {
1432    ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
1433    ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
1434    ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
1435    ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
1436    ("loongarch64-unknown-linux-gnu", loongarch64_unknown_linux_gnu),
1437    ("loongarch64-unknown-linux-musl", loongarch64_unknown_linux_musl),
1438    ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
1439    ("m68k-unknown-none-elf", m68k_unknown_none_elf),
1440    ("csky-unknown-linux-gnuabiv2", csky_unknown_linux_gnuabiv2),
1441    ("csky-unknown-linux-gnuabiv2hf", csky_unknown_linux_gnuabiv2hf),
1442    ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
1443    ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
1444    ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
1445    ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
1446    ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
1447    ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
1448    ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
1449    ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
1450    ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
1451    ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
1452    ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
1453    ("powerpc-unknown-linux-muslspe", powerpc_unknown_linux_muslspe),
1454    ("powerpc64-ibm-aix", powerpc64_ibm_aix),
1455    ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
1456    ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
1457    ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
1458    ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
1459    ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
1460    ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
1461    ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
1462    ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
1463    ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
1464    ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
1465    ("armeb-unknown-linux-gnueabi", armeb_unknown_linux_gnueabi),
1466    ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
1467    ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
1468    ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
1469    ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
1470    ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
1471    ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
1472    ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
1473    ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
1474    ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
1475    ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
1476    ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
1477    ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
1478    ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
1479    ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
1480    ("aarch64_be-unknown-linux-musl", aarch64_be_unknown_linux_musl),
1481    ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
1482    ("i686-unknown-linux-musl", i686_unknown_linux_musl),
1483    ("i586-unknown-linux-musl", i586_unknown_linux_musl),
1484    ("mips-unknown-linux-musl", mips_unknown_linux_musl),
1485    ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
1486    ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
1487    ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
1488    ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
1489    ("hexagon-unknown-none-elf", hexagon_unknown_none_elf),
1490
1491    ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
1492    ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
1493
1494    ("i686-linux-android", i686_linux_android),
1495    ("x86_64-linux-android", x86_64_linux_android),
1496    ("arm-linux-androideabi", arm_linux_androideabi),
1497    ("armv7-linux-androideabi", armv7_linux_androideabi),
1498    ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
1499    ("aarch64-linux-android", aarch64_linux_android),
1500    ("riscv64-linux-android", riscv64_linux_android),
1501
1502    ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
1503    ("armv6-unknown-freebsd", armv6_unknown_freebsd),
1504    ("armv7-unknown-freebsd", armv7_unknown_freebsd),
1505    ("i686-unknown-freebsd", i686_unknown_freebsd),
1506    ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
1507    ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
1508    ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
1509    ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
1510    ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
1511
1512    ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
1513
1514    ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
1515    ("i686-unknown-openbsd", i686_unknown_openbsd),
1516    ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
1517    ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
1518    ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
1519    ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
1520    ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
1521
1522    ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
1523    ("aarch64_be-unknown-netbsd", aarch64_be_unknown_netbsd),
1524    ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
1525    ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
1526    ("i586-unknown-netbsd", i586_unknown_netbsd),
1527    ("i686-unknown-netbsd", i686_unknown_netbsd),
1528    ("mipsel-unknown-netbsd", mipsel_unknown_netbsd),
1529    ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
1530    ("riscv64gc-unknown-netbsd", riscv64gc_unknown_netbsd),
1531    ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
1532    ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
1533
1534    ("i686-unknown-haiku", i686_unknown_haiku),
1535    ("x86_64-unknown-haiku", x86_64_unknown_haiku),
1536
1537    ("i686-unknown-hurd-gnu", i686_unknown_hurd_gnu),
1538    ("x86_64-unknown-hurd-gnu", x86_64_unknown_hurd_gnu),
1539
1540    ("aarch64-apple-darwin", aarch64_apple_darwin),
1541    ("arm64e-apple-darwin", arm64e_apple_darwin),
1542    ("x86_64-apple-darwin", x86_64_apple_darwin),
1543    ("x86_64h-apple-darwin", x86_64h_apple_darwin),
1544    ("i686-apple-darwin", i686_apple_darwin),
1545
1546    ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia),
1547    ("riscv64gc-unknown-fuchsia", riscv64gc_unknown_fuchsia),
1548    ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
1549
1550    ("avr-none", avr_none),
1551
1552    ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
1553
1554    ("aarch64-unknown-redox", aarch64_unknown_redox),
1555    ("i586-unknown-redox", i586_unknown_redox),
1556    ("riscv64gc-unknown-redox", riscv64gc_unknown_redox),
1557    ("x86_64-unknown-redox", x86_64_unknown_redox),
1558
1559    ("x86_64-unknown-managarm-mlibc", x86_64_unknown_managarm_mlibc),
1560    ("aarch64-unknown-managarm-mlibc", aarch64_unknown_managarm_mlibc),
1561    ("riscv64gc-unknown-managarm-mlibc", riscv64gc_unknown_managarm_mlibc),
1562
1563    ("i386-apple-ios", i386_apple_ios),
1564    ("x86_64-apple-ios", x86_64_apple_ios),
1565    ("aarch64-apple-ios", aarch64_apple_ios),
1566    ("arm64e-apple-ios", arm64e_apple_ios),
1567    ("armv7s-apple-ios", armv7s_apple_ios),
1568    ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
1569    ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
1570    ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
1571
1572    ("aarch64-apple-tvos", aarch64_apple_tvos),
1573    ("aarch64-apple-tvos-sim", aarch64_apple_tvos_sim),
1574    ("arm64e-apple-tvos", arm64e_apple_tvos),
1575    ("x86_64-apple-tvos", x86_64_apple_tvos),
1576
1577    ("armv7k-apple-watchos", armv7k_apple_watchos),
1578    ("arm64_32-apple-watchos", arm64_32_apple_watchos),
1579    ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
1580    ("aarch64-apple-watchos", aarch64_apple_watchos),
1581    ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
1582
1583    ("aarch64-apple-visionos", aarch64_apple_visionos),
1584    ("aarch64-apple-visionos-sim", aarch64_apple_visionos_sim),
1585
1586    ("armebv7r-none-eabi", armebv7r_none_eabi),
1587    ("armebv7r-none-eabihf", armebv7r_none_eabihf),
1588    ("armv7r-none-eabi", armv7r_none_eabi),
1589    ("armv7r-none-eabihf", armv7r_none_eabihf),
1590    ("armv8r-none-eabihf", armv8r_none_eabihf),
1591
1592    ("armv7-rtems-eabihf", armv7_rtems_eabihf),
1593
1594    ("x86_64-pc-solaris", x86_64_pc_solaris),
1595    ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1596
1597    ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1598    ("aarch64-unknown-illumos", aarch64_unknown_illumos),
1599
1600    ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1601    ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1602    ("x86_64-win7-windows-gnu", x86_64_win7_windows_gnu),
1603    ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1604    ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1605    ("i686-win7-windows-gnu", i686_win7_windows_gnu),
1606
1607    ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1608    ("i686-pc-windows-gnullvm", i686_pc_windows_gnullvm),
1609    ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1610
1611    ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1612    ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1613    ("arm64ec-pc-windows-msvc", arm64ec_pc_windows_msvc),
1614    ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1615    ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1616    ("x86_64-win7-windows-msvc", x86_64_win7_windows_msvc),
1617    ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1618    ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1619    ("i686-win7-windows-msvc", i686_win7_windows_msvc),
1620    ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1621    ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1622
1623    ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1624    ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1625    ("wasm32v1-none", wasm32v1_none),
1626    ("wasm32-wasip1", wasm32_wasip1),
1627    ("wasm32-wasip2", wasm32_wasip2),
1628    ("wasm32-wasip3", wasm32_wasip3),
1629    ("wasm32-wasip1-threads", wasm32_wasip1_threads),
1630    ("wasm32-wali-linux-musl", wasm32_wali_linux_musl),
1631    ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1632
1633    ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1634    ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1635    ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1636    ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1637    ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1638    ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1639    ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1640
1641    ("armv7a-none-eabi", armv7a_none_eabi),
1642    ("armv7a-none-eabihf", armv7a_none_eabihf),
1643    ("armv7a-nuttx-eabi", armv7a_nuttx_eabi),
1644    ("armv7a-nuttx-eabihf", armv7a_nuttx_eabihf),
1645    ("armv7a-vex-v5", armv7a_vex_v5),
1646
1647    ("msp430-none-elf", msp430_none_elf),
1648
1649    ("aarch64_be-unknown-hermit", aarch64_be_unknown_hermit),
1650    ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1651    ("riscv64gc-unknown-hermit", riscv64gc_unknown_hermit),
1652    ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1653    ("x86_64-unknown-motor", x86_64_unknown_motor),
1654
1655    ("x86_64-unikraft-linux-musl", x86_64_unikraft_linux_musl),
1656
1657    ("armv7-unknown-trusty", armv7_unknown_trusty),
1658    ("aarch64-unknown-trusty", aarch64_unknown_trusty),
1659    ("x86_64-unknown-trusty", x86_64_unknown_trusty),
1660
1661    ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1662    ("riscv32im-risc0-zkvm-elf", riscv32im_risc0_zkvm_elf),
1663    ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1664    ("riscv32ima-unknown-none-elf", riscv32ima_unknown_none_elf),
1665    ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1666    ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1667    ("riscv32imac-esp-espidf", riscv32imac_esp_espidf),
1668    ("riscv32imafc-esp-espidf", riscv32imafc_esp_espidf),
1669
1670    ("riscv32e-unknown-none-elf", riscv32e_unknown_none_elf),
1671    ("riscv32em-unknown-none-elf", riscv32em_unknown_none_elf),
1672    ("riscv32emc-unknown-none-elf", riscv32emc_unknown_none_elf),
1673
1674    ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1675    ("riscv32imafc-unknown-none-elf", riscv32imafc_unknown_none_elf),
1676    ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1677    ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1678    ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1679    ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1680    ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1681    ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1682    ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1683    ("riscv64a23-unknown-linux-gnu", riscv64a23_unknown_linux_gnu),
1684
1685    ("sparc-unknown-none-elf", sparc_unknown_none_elf),
1686
1687    ("loongarch32-unknown-none", loongarch32_unknown_none),
1688    ("loongarch32-unknown-none-softfloat", loongarch32_unknown_none_softfloat),
1689    ("loongarch64-unknown-none", loongarch64_unknown_none),
1690    ("loongarch64-unknown-none-softfloat", loongarch64_unknown_none_softfloat),
1691
1692    ("aarch64-unknown-none", aarch64_unknown_none),
1693    ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1694    ("aarch64_be-unknown-none-softfloat", aarch64_be_unknown_none_softfloat),
1695    ("aarch64-unknown-nuttx", aarch64_unknown_nuttx),
1696
1697    ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1698
1699    ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1700    ("i686-unknown-uefi", i686_unknown_uefi),
1701    ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1702
1703    ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1704
1705    ("amdgcn-amd-amdhsa", amdgcn_amd_amdhsa),
1706
1707    ("xtensa-esp32-none-elf", xtensa_esp32_none_elf),
1708    ("xtensa-esp32-espidf", xtensa_esp32_espidf),
1709    ("xtensa-esp32s2-none-elf", xtensa_esp32s2_none_elf),
1710    ("xtensa-esp32s2-espidf", xtensa_esp32s2_espidf),
1711    ("xtensa-esp32s3-none-elf", xtensa_esp32s3_none_elf),
1712    ("xtensa-esp32s3-espidf", xtensa_esp32s3_espidf),
1713
1714    ("i686-wrs-vxworks", i686_wrs_vxworks),
1715    ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1716    ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1717    ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1718    ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1719    ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1720    ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1721    ("riscv32-wrs-vxworks", riscv32_wrs_vxworks),
1722    ("riscv64-wrs-vxworks", riscv64_wrs_vxworks),
1723
1724    ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1725    ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1726    ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1727
1728    ("mipsel-sony-psp", mipsel_sony_psp),
1729    ("mipsel-sony-psx", mipsel_sony_psx),
1730    ("mipsel-unknown-none", mipsel_unknown_none),
1731    ("mips-mti-none-elf", mips_mti_none_elf),
1732    ("mipsel-mti-none-elf", mipsel_mti_none_elf),
1733    ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1734    ("armv4t-none-eabi", armv4t_none_eabi),
1735    ("thumbv5te-none-eabi", thumbv5te_none_eabi),
1736    ("armv5te-none-eabi", armv5te_none_eabi),
1737
1738    ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1739    ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1740    ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1741
1742    ("bpfeb-unknown-none", bpfeb_unknown_none),
1743    ("bpfel-unknown-none", bpfel_unknown_none),
1744
1745    ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1746
1747    ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1748
1749    ("armv7-sony-vita-newlibeabihf", armv7_sony_vita_newlibeabihf),
1750
1751    ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1752    ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1753
1754    ("x86_64-unknown-none", x86_64_unknown_none),
1755
1756    ("aarch64-unknown-teeos", aarch64_unknown_teeos),
1757
1758    ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1759
1760    ("aarch64-unknown-nto-qnx700", aarch64_unknown_nto_qnx700),
1761    ("aarch64-unknown-nto-qnx710", aarch64_unknown_nto_qnx710),
1762    ("aarch64-unknown-nto-qnx710_iosock", aarch64_unknown_nto_qnx710_iosock),
1763    ("aarch64-unknown-nto-qnx800", aarch64_unknown_nto_qnx800),
1764    ("x86_64-pc-nto-qnx710", x86_64_pc_nto_qnx710),
1765    ("x86_64-pc-nto-qnx710_iosock", x86_64_pc_nto_qnx710_iosock),
1766    ("x86_64-pc-nto-qnx800", x86_64_pc_nto_qnx800),
1767    ("i686-pc-nto-qnx700", i686_pc_nto_qnx700),
1768
1769    ("aarch64-unknown-linux-ohos", aarch64_unknown_linux_ohos),
1770    ("armv7-unknown-linux-ohos", armv7_unknown_linux_ohos),
1771    ("loongarch64-unknown-linux-ohos", loongarch64_unknown_linux_ohos),
1772    ("x86_64-unknown-linux-ohos", x86_64_unknown_linux_ohos),
1773
1774    ("x86_64-unknown-linux-none", x86_64_unknown_linux_none),
1775
1776    ("thumbv6m-nuttx-eabi", thumbv6m_nuttx_eabi),
1777    ("thumbv7a-nuttx-eabi", thumbv7a_nuttx_eabi),
1778    ("thumbv7a-nuttx-eabihf", thumbv7a_nuttx_eabihf),
1779    ("thumbv7m-nuttx-eabi", thumbv7m_nuttx_eabi),
1780    ("thumbv7em-nuttx-eabi", thumbv7em_nuttx_eabi),
1781    ("thumbv7em-nuttx-eabihf", thumbv7em_nuttx_eabihf),
1782    ("thumbv8m.base-nuttx-eabi", thumbv8m_base_nuttx_eabi),
1783    ("thumbv8m.main-nuttx-eabi", thumbv8m_main_nuttx_eabi),
1784    ("thumbv8m.main-nuttx-eabihf", thumbv8m_main_nuttx_eabihf),
1785    ("riscv32imc-unknown-nuttx-elf", riscv32imc_unknown_nuttx_elf),
1786    ("riscv32imac-unknown-nuttx-elf", riscv32imac_unknown_nuttx_elf),
1787    ("riscv32imafc-unknown-nuttx-elf", riscv32imafc_unknown_nuttx_elf),
1788    ("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf),
1789    ("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf),
1790    ("x86_64-lynx-lynxos178", x86_64_lynx_lynxos178),
1791
1792    ("x86_64-pc-cygwin", x86_64_pc_cygwin),
1793}
1794
1795macro_rules! cvs {
1797    () => {
1798        ::std::borrow::Cow::Borrowed(&[])
1799    };
1800    ($($x:expr),+ $(,)?) => {
1801        ::std::borrow::Cow::Borrowed(&[
1802            $(
1803                ::std::borrow::Cow::Borrowed($x),
1804            )*
1805        ])
1806    };
1807}
1808
1809pub(crate) use cvs;
1810
1811#[derive(Debug, PartialEq)]
1815pub struct TargetWarnings {
1816    unused_fields: Vec<String>,
1817}
1818
1819impl TargetWarnings {
1820    pub fn empty() -> Self {
1821        Self { unused_fields: Vec::new() }
1822    }
1823
1824    pub fn warning_messages(&self) -> Vec<String> {
1825        let mut warnings = vec![];
1826        if !self.unused_fields.is_empty() {
1827            warnings.push(format!(
1828                "target json file contains unused fields: {}",
1829                self.unused_fields.join(", ")
1830            ));
1831        }
1832        warnings
1833    }
1834}
1835
1836#[derive(Copy, Clone, Debug, PartialEq)]
1839enum TargetKind {
1840    Json,
1841    Builtin,
1842}
1843
1844#[derive(PartialEq, Clone, Debug)]
1848pub struct Target {
1849    pub llvm_target: StaticCow<str>,
1856    pub metadata: TargetMetadata,
1859    pub pointer_width: u16,
1861    pub arch: StaticCow<str>,
1864    pub data_layout: StaticCow<str>,
1866    pub options: TargetOptions,
1868}
1869
1870#[derive(Default, PartialEq, Clone, Debug)]
1874pub struct TargetMetadata {
1875    pub description: Option<StaticCow<str>>,
1878    pub tier: Option<u64>,
1880    pub host_tools: Option<bool>,
1882    pub std: Option<bool>,
1885}
1886
1887impl Target {
1888    pub fn parse_data_layout(&self) -> Result<TargetDataLayout, TargetDataLayoutErrors<'_>> {
1889        let mut dl = TargetDataLayout::parse_from_llvm_datalayout_string(
1890            &self.data_layout,
1891            self.options.default_address_space,
1892        )?;
1893
1894        if dl.endian != self.endian {
1896            return Err(TargetDataLayoutErrors::InconsistentTargetArchitecture {
1897                dl: dl.endian.as_str(),
1898                target: self.endian.as_str(),
1899            });
1900        }
1901
1902        let target_pointer_width: u64 = self.pointer_width.into();
1903        let dl_pointer_size: u64 = dl.pointer_size().bits();
1904        if dl_pointer_size != target_pointer_width {
1905            return Err(TargetDataLayoutErrors::InconsistentTargetPointerWidth {
1906                pointer_size: dl_pointer_size,
1907                target: self.pointer_width,
1908            });
1909        }
1910
1911        dl.c_enum_min_size = Integer::from_size(Size::from_bits(
1912            self.c_enum_min_bits.unwrap_or(self.c_int_width as _),
1913        ))
1914        .map_err(|err| TargetDataLayoutErrors::InvalidBitsSize { err })?;
1915
1916        Ok(dl)
1917    }
1918}
1919
1920pub trait HasTargetSpec {
1921    fn target_spec(&self) -> &Target;
1922}
1923
1924impl HasTargetSpec for Target {
1925    #[inline]
1926    fn target_spec(&self) -> &Target {
1927        self
1928    }
1929}
1930
1931#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1933pub struct X86Abi {
1934    pub regparm: Option<u32>,
1937    pub reg_struct_return: bool,
1939}
1940
1941pub trait HasX86AbiOpt {
1942    fn x86_abi_opt(&self) -> X86Abi;
1943}
1944
1945type StaticCow<T> = Cow<'static, T>;
1946
1947#[derive(PartialEq, Clone, Debug)]
1956pub struct TargetOptions {
1957    pub endian: Endian,
1959    pub c_int_width: u16,
1961    pub os: StaticCow<str>,
1966    pub env: StaticCow<str>,
1968    pub abi: StaticCow<str>,
1973    pub vendor: StaticCow<str>,
1975
1976    pub linker: Option<StaticCow<str>>,
1978    pub linker_flavor: LinkerFlavor,
1981    linker_flavor_json: LinkerFlavorCli,
1982    lld_flavor_json: LldFlavor,
1983    linker_is_gnu_json: bool,
1984
1985    pub pre_link_objects: CrtObjects,
1987    pub post_link_objects: CrtObjects,
1988    pub pre_link_objects_self_contained: CrtObjects,
1990    pub post_link_objects_self_contained: CrtObjects,
1991    pub link_self_contained: LinkSelfContainedDefault,
1994
1995    pub pre_link_args: LinkArgs,
1997    pre_link_args_json: LinkArgsCli,
1998    pub late_link_args: LinkArgs,
2002    late_link_args_json: LinkArgsCli,
2003    pub late_link_args_dynamic: LinkArgs,
2006    late_link_args_dynamic_json: LinkArgsCli,
2007    pub late_link_args_static: LinkArgs,
2010    late_link_args_static_json: LinkArgsCli,
2011    pub post_link_args: LinkArgs,
2014    post_link_args_json: LinkArgsCli,
2015
2016    pub link_script: Option<StaticCow<str>>,
2020    pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
2022    pub link_env_remove: StaticCow<[StaticCow<str>]>,
2024
2025    pub asm_args: StaticCow<[StaticCow<str>]>,
2027
2028    pub cpu: StaticCow<str>,
2031    pub need_explicit_cpu: bool,
2034    pub features: StaticCow<str>,
2043    pub direct_access_external_data: Option<bool>,
2045    pub dynamic_linking: bool,
2047    pub dll_tls_export: bool,
2049    pub only_cdylib: bool,
2051    pub executables: bool,
2053    pub relocation_model: RelocModel,
2056    pub code_model: Option<CodeModel>,
2059    pub tls_model: TlsModel,
2062    pub disable_redzone: bool,
2064    pub frame_pointer: FramePointer,
2066    pub function_sections: bool,
2068    pub dll_prefix: StaticCow<str>,
2070    pub dll_suffix: StaticCow<str>,
2072    pub exe_suffix: StaticCow<str>,
2074    pub staticlib_prefix: StaticCow<str>,
2076    pub staticlib_suffix: StaticCow<str>,
2078    pub families: StaticCow<[StaticCow<str>]>,
2084    pub abi_return_struct_as_int: bool,
2086    pub is_like_aix: bool,
2089    pub is_like_darwin: bool,
2094    pub is_like_solaris: bool,
2098    pub is_like_windows: bool,
2106    pub is_like_msvc: bool,
2116    pub is_like_wasm: bool,
2118    pub is_like_android: bool,
2120    pub is_like_vexos: bool,
2122    pub binary_format: BinaryFormat,
2124    pub default_dwarf_version: u32,
2127    pub allows_weak_linkage: bool,
2134    pub has_rpath: bool,
2136    pub no_default_libraries: bool,
2139    pub position_independent_executables: bool,
2145    pub static_position_independent_executables: bool,
2147    pub plt_by_default: bool,
2150    pub relro_level: RelroLevel,
2154    pub archive_format: StaticCow<str>,
2159    pub allow_asm: bool,
2161    pub main_needs_argc_argv: bool,
2164
2165    pub has_thread_local: bool,
2167    pub obj_is_bitcode: bool,
2171
2172    pub min_atomic_width: Option<u64>,
2174
2175    pub max_atomic_width: Option<u64>,
2177
2178    pub atomic_cas: bool,
2180
2181    pub panic_strategy: PanicStrategy,
2183
2184    pub crt_static_allows_dylibs: bool,
2186    pub crt_static_default: bool,
2188    pub crt_static_respected: bool,
2190
2191    pub stack_probes: StackProbeType,
2193
2194    pub min_global_align: Option<Align>,
2196
2197    pub default_codegen_units: Option<u64>,
2199
2200    pub default_codegen_backend: Option<StaticCow<str>>,
2210
2211    pub trap_unreachable: bool,
2214
2215    pub requires_lto: bool,
2218
2219    pub singlethread: bool,
2221
2222    pub no_builtins: bool,
2225
2226    pub default_visibility: Option<SymbolVisibility>,
2232
2233    pub emit_debug_gdb_scripts: bool,
2235
2236    pub requires_uwtable: bool,
2240
2241    pub default_uwtable: bool,
2244
2245    pub simd_types_indirect: bool,
2250
2251    pub limit_rdylib_exports: bool,
2253
2254    pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
2257
2258    pub merge_functions: MergeFunctions,
2265
2266    pub mcount: StaticCow<str>,
2268
2269    pub llvm_mcount_intrinsic: Option<StaticCow<str>>,
2271
2272    pub llvm_abiname: StaticCow<str>,
2275
2276    pub llvm_floatabi: Option<FloatAbi>,
2283
2284    pub rustc_abi: Option<RustcAbi>,
2289
2290    pub relax_elf_relocations: bool,
2292
2293    pub llvm_args: StaticCow<[StaticCow<str>]>,
2295
2296    pub use_ctors_section: bool,
2299
2300    pub eh_frame_header: bool,
2304
2305    pub has_thumb_interworking: bool,
2308
2309    pub debuginfo_kind: DebuginfoKind,
2311    pub split_debuginfo: SplitDebuginfo,
2314    pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
2316
2317    pub supported_sanitizers: SanitizerSet,
2323
2324    pub c_enum_min_bits: Option<u64>,
2326
2327    pub generate_arange_section: bool,
2329
2330    pub supports_stack_protector: bool,
2333
2334    pub entry_name: StaticCow<str>,
2337
2338    pub entry_abi: CanonAbi,
2341
2342    pub supports_xray: bool,
2344
2345    pub default_address_space: rustc_abi::AddressSpace,
2349
2350    small_data_threshold_support: SmallDataThresholdSupport,
2352}
2353
2354fn add_link_args_iter(
2357    link_args: &mut LinkArgs,
2358    flavor: LinkerFlavor,
2359    args: impl Iterator<Item = StaticCow<str>> + Clone,
2360) {
2361    let mut insert = |flavor| link_args.entry(flavor).or_default().extend(args.clone());
2362    insert(flavor);
2363    match flavor {
2364        LinkerFlavor::Gnu(cc, lld) => {
2365            assert_eq!(lld, Lld::No);
2366            insert(LinkerFlavor::Gnu(cc, Lld::Yes));
2367        }
2368        LinkerFlavor::Darwin(cc, lld) => {
2369            assert_eq!(lld, Lld::No);
2370            insert(LinkerFlavor::Darwin(cc, Lld::Yes));
2371        }
2372        LinkerFlavor::Msvc(lld) => {
2373            assert_eq!(lld, Lld::No);
2374            insert(LinkerFlavor::Msvc(Lld::Yes));
2375        }
2376        LinkerFlavor::WasmLld(..)
2377        | LinkerFlavor::Unix(..)
2378        | LinkerFlavor::EmCc
2379        | LinkerFlavor::Bpf
2380        | LinkerFlavor::Llbc
2381        | LinkerFlavor::Ptx => {}
2382    }
2383}
2384
2385fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
2386    add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
2387}
2388
2389impl TargetOptions {
2390    pub fn supports_comdat(&self) -> bool {
2391        !self.is_like_aix && !self.is_like_darwin
2393    }
2394}
2395
2396impl TargetOptions {
2397    fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
2398        let mut link_args = LinkArgs::new();
2399        add_link_args(&mut link_args, flavor, args);
2400        link_args
2401    }
2402
2403    fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
2404        add_link_args(&mut self.pre_link_args, flavor, args);
2405    }
2406
2407    fn update_from_cli(&mut self) {
2408        self.linker_flavor = LinkerFlavor::from_cli_json(
2409            self.linker_flavor_json,
2410            self.lld_flavor_json,
2411            self.linker_is_gnu_json,
2412        );
2413        for (args, args_json) in [
2414            (&mut self.pre_link_args, &self.pre_link_args_json),
2415            (&mut self.late_link_args, &self.late_link_args_json),
2416            (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
2417            (&mut self.late_link_args_static, &self.late_link_args_static_json),
2418            (&mut self.post_link_args, &self.post_link_args_json),
2419        ] {
2420            args.clear();
2421            for (flavor, args_json) in args_json {
2422                let linker_flavor = self.linker_flavor.with_cli_hints(*flavor);
2423                let linker_flavor = match linker_flavor {
2425                    LinkerFlavor::Gnu(cc, _) => LinkerFlavor::Gnu(cc, Lld::No),
2426                    LinkerFlavor::Darwin(cc, _) => LinkerFlavor::Darwin(cc, Lld::No),
2427                    LinkerFlavor::Msvc(_) => LinkerFlavor::Msvc(Lld::No),
2428                    _ => linker_flavor,
2429                };
2430                if !args.contains_key(&linker_flavor) {
2431                    add_link_args_iter(args, linker_flavor, args_json.iter().cloned());
2432                }
2433            }
2434        }
2435    }
2436
2437    fn update_to_cli(&mut self) {
2438        self.linker_flavor_json = self.linker_flavor.to_cli_counterpart();
2439        self.lld_flavor_json = self.linker_flavor.lld_flavor();
2440        self.linker_is_gnu_json = self.linker_flavor.is_gnu();
2441        for (args, args_json) in [
2442            (&self.pre_link_args, &mut self.pre_link_args_json),
2443            (&self.late_link_args, &mut self.late_link_args_json),
2444            (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
2445            (&self.late_link_args_static, &mut self.late_link_args_static_json),
2446            (&self.post_link_args, &mut self.post_link_args_json),
2447        ] {
2448            *args_json = args
2449                .iter()
2450                .map(|(flavor, args)| (flavor.to_cli_counterpart(), args.clone()))
2451                .collect();
2452        }
2453    }
2454}
2455
2456impl Default for TargetOptions {
2457    fn default() -> TargetOptions {
2460        TargetOptions {
2461            endian: Endian::Little,
2462            c_int_width: 32,
2463            os: "none".into(),
2464            env: "".into(),
2465            abi: "".into(),
2466            vendor: "unknown".into(),
2467            linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
2468            linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
2469            linker_flavor_json: LinkerFlavorCli::Gcc,
2470            lld_flavor_json: LldFlavor::Ld,
2471            linker_is_gnu_json: true,
2472            link_script: None,
2473            asm_args: cvs![],
2474            cpu: "generic".into(),
2475            need_explicit_cpu: false,
2476            features: "".into(),
2477            direct_access_external_data: None,
2478            dynamic_linking: false,
2479            dll_tls_export: true,
2480            only_cdylib: false,
2481            executables: true,
2482            relocation_model: RelocModel::Pic,
2483            code_model: None,
2484            tls_model: TlsModel::GeneralDynamic,
2485            disable_redzone: false,
2486            frame_pointer: FramePointer::MayOmit,
2487            function_sections: true,
2488            dll_prefix: "lib".into(),
2489            dll_suffix: ".so".into(),
2490            exe_suffix: "".into(),
2491            staticlib_prefix: "lib".into(),
2492            staticlib_suffix: ".a".into(),
2493            families: cvs![],
2494            abi_return_struct_as_int: false,
2495            is_like_aix: false,
2496            is_like_darwin: false,
2497            is_like_solaris: false,
2498            is_like_windows: false,
2499            is_like_msvc: false,
2500            is_like_wasm: false,
2501            is_like_android: false,
2502            is_like_vexos: false,
2503            binary_format: BinaryFormat::Elf,
2504            default_dwarf_version: 4,
2505            allows_weak_linkage: true,
2506            has_rpath: false,
2507            no_default_libraries: true,
2508            position_independent_executables: false,
2509            static_position_independent_executables: false,
2510            plt_by_default: true,
2511            relro_level: RelroLevel::None,
2512            pre_link_objects: Default::default(),
2513            post_link_objects: Default::default(),
2514            pre_link_objects_self_contained: Default::default(),
2515            post_link_objects_self_contained: Default::default(),
2516            link_self_contained: LinkSelfContainedDefault::False,
2517            pre_link_args: LinkArgs::new(),
2518            pre_link_args_json: LinkArgsCli::new(),
2519            late_link_args: LinkArgs::new(),
2520            late_link_args_json: LinkArgsCli::new(),
2521            late_link_args_dynamic: LinkArgs::new(),
2522            late_link_args_dynamic_json: LinkArgsCli::new(),
2523            late_link_args_static: LinkArgs::new(),
2524            late_link_args_static_json: LinkArgsCli::new(),
2525            post_link_args: LinkArgs::new(),
2526            post_link_args_json: LinkArgsCli::new(),
2527            link_env: cvs![],
2528            link_env_remove: cvs![],
2529            archive_format: "gnu".into(),
2530            main_needs_argc_argv: true,
2531            allow_asm: true,
2532            has_thread_local: false,
2533            obj_is_bitcode: false,
2534            min_atomic_width: None,
2535            max_atomic_width: None,
2536            atomic_cas: true,
2537            panic_strategy: PanicStrategy::Unwind,
2538            crt_static_allows_dylibs: false,
2539            crt_static_default: false,
2540            crt_static_respected: false,
2541            stack_probes: StackProbeType::None,
2542            min_global_align: None,
2543            default_codegen_units: None,
2544            default_codegen_backend: None,
2545            trap_unreachable: true,
2546            requires_lto: false,
2547            singlethread: false,
2548            no_builtins: false,
2549            default_visibility: None,
2550            emit_debug_gdb_scripts: true,
2551            requires_uwtable: false,
2552            default_uwtable: false,
2553            simd_types_indirect: true,
2554            limit_rdylib_exports: true,
2555            override_export_symbols: None,
2556            merge_functions: MergeFunctions::Aliases,
2557            mcount: "mcount".into(),
2558            llvm_mcount_intrinsic: None,
2559            llvm_abiname: "".into(),
2560            llvm_floatabi: None,
2561            rustc_abi: None,
2562            relax_elf_relocations: false,
2563            llvm_args: cvs![],
2564            use_ctors_section: false,
2565            eh_frame_header: true,
2566            has_thumb_interworking: false,
2567            debuginfo_kind: Default::default(),
2568            split_debuginfo: Default::default(),
2569            supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
2571            supported_sanitizers: SanitizerSet::empty(),
2572            c_enum_min_bits: None,
2573            generate_arange_section: true,
2574            supports_stack_protector: true,
2575            entry_name: "main".into(),
2576            entry_abi: CanonAbi::C,
2577            supports_xray: false,
2578            default_address_space: rustc_abi::AddressSpace::ZERO,
2579            small_data_threshold_support: SmallDataThresholdSupport::DefaultForArch,
2580        }
2581    }
2582}
2583
2584impl Deref for Target {
2588    type Target = TargetOptions;
2589
2590    #[inline]
2591    fn deref(&self) -> &Self::Target {
2592        &self.options
2593    }
2594}
2595impl DerefMut for Target {
2596    #[inline]
2597    fn deref_mut(&mut self) -> &mut Self::Target {
2598        &mut self.options
2599    }
2600}
2601
2602impl Target {
2603    pub fn is_abi_supported(&self, abi: ExternAbi) -> bool {
2604        let abi_map = AbiMap::from_target(self);
2605        abi_map.canonize_abi(abi, false).is_mapped()
2606    }
2607
2608    pub fn min_atomic_width(&self) -> u64 {
2611        self.min_atomic_width.unwrap_or(8)
2612    }
2613
2614    pub fn max_atomic_width(&self) -> u64 {
2617        self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
2618    }
2619
2620    fn check_consistency(&self, kind: TargetKind) -> Result<(), String> {
2623        macro_rules! check {
2624            ($b:expr, $($msg:tt)*) => {
2625                if !$b {
2626                    return Err(format!($($msg)*));
2627                }
2628            }
2629        }
2630        macro_rules! check_eq {
2631            ($left:expr, $right:expr, $($msg:tt)*) => {
2632                if ($left) != ($right) {
2633                    return Err(format!($($msg)*));
2634                }
2635            }
2636        }
2637        macro_rules! check_ne {
2638            ($left:expr, $right:expr, $($msg:tt)*) => {
2639                if ($left) == ($right) {
2640                    return Err(format!($($msg)*));
2641                }
2642            }
2643        }
2644        macro_rules! check_matches {
2645            ($left:expr, $right:pat, $($msg:tt)*) => {
2646                if !matches!($left, $right) {
2647                    return Err(format!($($msg)*));
2648                }
2649            }
2650        }
2651
2652        check_eq!(
2653            self.is_like_darwin,
2654            self.vendor == "apple",
2655            "`is_like_darwin` must be set if and only if `vendor` is `apple`"
2656        );
2657        check_eq!(
2658            self.is_like_solaris,
2659            self.os == "solaris" || self.os == "illumos",
2660            "`is_like_solaris` must be set if and only if `os` is `solaris` or `illumos`"
2661        );
2662        check_eq!(
2663            self.is_like_windows,
2664            self.os == "windows" || self.os == "uefi" || self.os == "cygwin",
2665            "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`"
2666        );
2667        check_eq!(
2668            self.is_like_wasm,
2669            self.arch == "wasm32" || self.arch == "wasm64",
2670            "`is_like_wasm` must be set if and only if `arch` is `wasm32` or `wasm64`"
2671        );
2672        if self.is_like_msvc {
2673            check!(self.is_like_windows, "if `is_like_msvc` is set, `is_like_windows` must be set");
2674        }
2675        if self.os == "emscripten" {
2676            check!(self.is_like_wasm, "the `emcscripten` os only makes sense on wasm-like targets");
2677        }
2678
2679        check_eq!(
2681            self.is_like_darwin,
2682            matches!(self.linker_flavor, LinkerFlavor::Darwin(..)),
2683            "`linker_flavor` must be `darwin` if and only if `is_like_darwin` is set"
2684        );
2685        check_eq!(
2686            self.is_like_msvc,
2687            matches!(self.linker_flavor, LinkerFlavor::Msvc(..)),
2688            "`linker_flavor` must be `msvc` if and only if `is_like_msvc` is set"
2689        );
2690        check_eq!(
2691            self.is_like_wasm && self.os != "emscripten",
2692            matches!(self.linker_flavor, LinkerFlavor::WasmLld(..)),
2693            "`linker_flavor` must be `wasm-lld` if and only if `is_like_wasm` is set and the `os` is not `emscripten`",
2694        );
2695        check_eq!(
2696            self.os == "emscripten",
2697            matches!(self.linker_flavor, LinkerFlavor::EmCc),
2698            "`linker_flavor` must be `em-cc` if and only if `os` is `emscripten`"
2699        );
2700        check_eq!(
2701            self.arch == "bpf",
2702            matches!(self.linker_flavor, LinkerFlavor::Bpf),
2703            "`linker_flavor` must be `bpf` if and only if `arch` is `bpf`"
2704        );
2705        check_eq!(
2706            self.arch == "nvptx64",
2707            matches!(self.linker_flavor, LinkerFlavor::Ptx),
2708            "`linker_flavor` must be `ptc` if and only if `arch` is `nvptx64`"
2709        );
2710
2711        for args in [
2712            &self.pre_link_args,
2713            &self.late_link_args,
2714            &self.late_link_args_dynamic,
2715            &self.late_link_args_static,
2716            &self.post_link_args,
2717        ] {
2718            for (&flavor, flavor_args) in args {
2719                check!(
2720                    !flavor_args.is_empty() || self.arch == "avr",
2721                    "linker flavor args must not be empty"
2722                );
2723                match self.linker_flavor {
2725                    LinkerFlavor::Gnu(..) => {
2726                        check_matches!(
2727                            flavor,
2728                            LinkerFlavor::Gnu(..),
2729                            "mixing GNU and non-GNU linker flavors"
2730                        );
2731                    }
2732                    LinkerFlavor::Darwin(..) => {
2733                        check_matches!(
2734                            flavor,
2735                            LinkerFlavor::Darwin(..),
2736                            "mixing Darwin and non-Darwin linker flavors"
2737                        )
2738                    }
2739                    LinkerFlavor::WasmLld(..) => {
2740                        check_matches!(
2741                            flavor,
2742                            LinkerFlavor::WasmLld(..),
2743                            "mixing wasm and non-wasm linker flavors"
2744                        )
2745                    }
2746                    LinkerFlavor::Unix(..) => {
2747                        check_matches!(
2748                            flavor,
2749                            LinkerFlavor::Unix(..),
2750                            "mixing unix and non-unix linker flavors"
2751                        );
2752                    }
2753                    LinkerFlavor::Msvc(..) => {
2754                        check_matches!(
2755                            flavor,
2756                            LinkerFlavor::Msvc(..),
2757                            "mixing MSVC and non-MSVC linker flavors"
2758                        );
2759                    }
2760                    LinkerFlavor::EmCc
2761                    | LinkerFlavor::Bpf
2762                    | LinkerFlavor::Ptx
2763                    | LinkerFlavor::Llbc => {
2764                        check_eq!(flavor, self.linker_flavor, "mixing different linker flavors")
2765                    }
2766                }
2767
2768                let check_noncc = |noncc_flavor| -> Result<(), String> {
2770                    if let Some(noncc_args) = args.get(&noncc_flavor) {
2771                        for arg in flavor_args {
2772                            if let Some(suffix) = arg.strip_prefix("-Wl,") {
2773                                check!(
2774                                    noncc_args.iter().any(|a| a == suffix),
2775                                    " link args for cc and non-cc versions of flavors are not consistent"
2776                                );
2777                            }
2778                        }
2779                    }
2780                    Ok(())
2781                };
2782
2783                match self.linker_flavor {
2784                    LinkerFlavor::Gnu(Cc::Yes, lld) => check_noncc(LinkerFlavor::Gnu(Cc::No, lld))?,
2785                    LinkerFlavor::WasmLld(Cc::Yes) => check_noncc(LinkerFlavor::WasmLld(Cc::No))?,
2786                    LinkerFlavor::Unix(Cc::Yes) => check_noncc(LinkerFlavor::Unix(Cc::No))?,
2787                    _ => {}
2788                }
2789            }
2790
2791            for cc in [Cc::No, Cc::Yes] {
2793                check_eq!(
2794                    args.get(&LinkerFlavor::Gnu(cc, Lld::No)),
2795                    args.get(&LinkerFlavor::Gnu(cc, Lld::Yes)),
2796                    "link args for lld and non-lld versions of flavors are not consistent",
2797                );
2798                check_eq!(
2799                    args.get(&LinkerFlavor::Darwin(cc, Lld::No)),
2800                    args.get(&LinkerFlavor::Darwin(cc, Lld::Yes)),
2801                    "link args for lld and non-lld versions of flavors are not consistent",
2802                );
2803            }
2804            check_eq!(
2805                args.get(&LinkerFlavor::Msvc(Lld::No)),
2806                args.get(&LinkerFlavor::Msvc(Lld::Yes)),
2807                "link args for lld and non-lld versions of flavors are not consistent",
2808            );
2809        }
2810
2811        if self.link_self_contained.is_disabled() {
2812            check!(
2813                self.pre_link_objects_self_contained.is_empty()
2814                    && self.post_link_objects_self_contained.is_empty(),
2815                "if `link_self_contained` is disabled, then `pre_link_objects_self_contained` and `post_link_objects_self_contained` must be empty",
2816            );
2817        }
2818
2819        check_ne!(self.vendor, "", "`vendor` cannot be empty");
2823        check_ne!(self.os, "", "`os` cannot be empty");
2824        if !self.can_use_os_unknown() {
2825            check_ne!(
2827                self.os,
2828                "unknown",
2829                "`unknown` os can only be used on particular targets; use `none` for bare-metal targets"
2830            );
2831        }
2832
2833        if kind == TargetKind::Builtin {
2839            if self.os == "none"
2843                && (self.arch != "bpf"
2844                    && self.arch != "hexagon"
2845                    && self.arch != "wasm32"
2846                    && self.arch != "wasm64")
2847            {
2848                check!(
2849                    !self.dynamic_linking,
2850                    "dynamic linking is not supported on this OS/architecture"
2851                );
2852            }
2853            if self.only_cdylib
2854                || self.crt_static_allows_dylibs
2855                || !self.late_link_args_dynamic.is_empty()
2856            {
2857                check!(
2858                    self.dynamic_linking,
2859                    "dynamic linking must be allowed when `only_cdylib` or `crt_static_allows_dylibs` or `late_link_args_dynamic` are set"
2860                );
2861            }
2862            if self.dynamic_linking && !self.is_like_wasm {
2864                check_eq!(
2865                    self.relocation_model,
2866                    RelocModel::Pic,
2867                    "targets that support dynamic linking must use the `pic` relocation model"
2868                );
2869            }
2870            if self.position_independent_executables {
2871                check_eq!(
2872                    self.relocation_model,
2873                    RelocModel::Pic,
2874                    "targets that support position-independent executables must use the `pic` relocation model"
2875                );
2876            }
2877            if self.relocation_model == RelocModel::Pic && (self.os != "uefi") {
2879                check!(
2880                    self.dynamic_linking || self.position_independent_executables,
2881                    "when the relocation model is `pic`, the target must support dynamic linking or use position-independent executables. \
2882                Set the relocation model to `static` to avoid this requirement"
2883                );
2884            }
2885            if self.static_position_independent_executables {
2886                check!(
2887                    self.position_independent_executables,
2888                    "if `static_position_independent_executables` is set, then `position_independent_executables` must be set"
2889                );
2890            }
2891            if self.position_independent_executables {
2892                check!(
2893                    self.executables,
2894                    "if `position_independent_executables` is set then `executables` must be set"
2895                );
2896            }
2897        }
2898
2899        if self.crt_static_default || self.crt_static_allows_dylibs {
2901            check!(
2902                self.crt_static_respected,
2903                "static CRT can be enabled but `crt_static_respected` is not set"
2904            );
2905        }
2906
2907        match &*self.arch {
2910            "riscv32" => {
2911                check_matches!(
2912                    &*self.llvm_abiname,
2913                    "ilp32" | "ilp32f" | "ilp32d" | "ilp32e",
2914                    "invalid RISC-V ABI name: {}",
2915                    self.llvm_abiname,
2916                );
2917            }
2918            "riscv64" => {
2919                check_matches!(
2921                    &*self.llvm_abiname,
2922                    "lp64" | "lp64f" | "lp64d" | "lp64e",
2923                    "invalid RISC-V ABI name: {}",
2924                    self.llvm_abiname,
2925                );
2926            }
2927            "arm" => {
2928                check!(
2929                    self.llvm_floatabi.is_some(),
2930                    "ARM targets must set `llvm-floatabi` to `hard` or `soft`",
2931                )
2932            }
2933            _ => {}
2934        }
2935
2936        if let Some(rust_abi) = self.rustc_abi {
2938            match rust_abi {
2939                RustcAbi::X86Sse2 => check_matches!(
2940                    &*self.arch,
2941                    "x86",
2942                    "`x86-sse2` ABI is only valid for x86-32 targets"
2943                ),
2944                RustcAbi::X86Softfloat => check_matches!(
2945                    &*self.arch,
2946                    "x86" | "x86_64",
2947                    "`x86-softfloat` ABI is only valid for x86 targets"
2948                ),
2949            }
2950        }
2951
2952        if !self.features.is_empty() {
2954            let mut features_enabled = FxHashSet::default();
2955            let mut features_disabled = FxHashSet::default();
2956            for feat in self.features.split(',') {
2957                if let Some(feat) = feat.strip_prefix("+") {
2958                    features_enabled.insert(feat);
2959                    if features_disabled.contains(feat) {
2960                        return Err(format!(
2961                            "target feature `{feat}` is both enabled and disabled"
2962                        ));
2963                    }
2964                } else if let Some(feat) = feat.strip_prefix("-") {
2965                    features_disabled.insert(feat);
2966                    if features_enabled.contains(feat) {
2967                        return Err(format!(
2968                            "target feature `{feat}` is both enabled and disabled"
2969                        ));
2970                    }
2971                } else {
2972                    return Err(format!(
2973                        "target feature `{feat}` is invalid, must start with `+` or `-`"
2974                    ));
2975                }
2976            }
2977            let abi_feature_constraints = self.abi_required_features();
2979            for feat in abi_feature_constraints.required {
2980                if features_disabled.contains(feat) {
2983                    return Err(format!(
2984                        "target feature `{feat}` is required by the ABI but gets disabled in target spec"
2985                    ));
2986                }
2987            }
2988            for feat in abi_feature_constraints.incompatible {
2989                if features_enabled.contains(feat) {
2992                    return Err(format!(
2993                        "target feature `{feat}` is incompatible with the ABI but gets enabled in target spec"
2994                    ));
2995                }
2996            }
2997        }
2998
2999        Ok(())
3000    }
3001
3002    #[cfg(test)]
3004    fn test_target(mut self) {
3005        let recycled_target =
3006            Target::from_json(&serde_json::to_string(&self.to_json()).unwrap()).map(|(j, _)| j);
3007        self.update_to_cli();
3008        self.check_consistency(TargetKind::Builtin).unwrap();
3009        assert_eq!(recycled_target, Ok(self));
3010    }
3011
3012    fn can_use_os_unknown(&self) -> bool {
3015        self.llvm_target == "wasm32-unknown-unknown"
3016            || self.llvm_target == "wasm64-unknown-unknown"
3017            || (self.env == "sgx" && self.vendor == "fortanix")
3018    }
3019
3020    pub fn expect_builtin(target_tuple: &TargetTuple) -> Target {
3022        match *target_tuple {
3023            TargetTuple::TargetTuple(ref target_tuple) => {
3024                load_builtin(target_tuple).expect("built-in target")
3025            }
3026            TargetTuple::TargetJson { .. } => {
3027                panic!("built-in targets doesn't support target-paths")
3028            }
3029        }
3030    }
3031
3032    pub fn builtins() -> impl Iterator<Item = Target> {
3034        load_all_builtins()
3035    }
3036
3037    pub fn search(
3047        target_tuple: &TargetTuple,
3048        sysroot: &Path,
3049    ) -> Result<(Target, TargetWarnings), String> {
3050        use std::{env, fs};
3051
3052        fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
3053            let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
3054            Target::from_json(&contents)
3055        }
3056
3057        match *target_tuple {
3058            TargetTuple::TargetTuple(ref target_tuple) => {
3059                if let Some(t) = load_builtin(target_tuple) {
3061                    return Ok((t, TargetWarnings::empty()));
3062                }
3063
3064                let path = {
3066                    let mut target = target_tuple.to_string();
3067                    target.push_str(".json");
3068                    PathBuf::from(target)
3069                };
3070
3071                let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
3072
3073                for dir in env::split_paths(&target_path) {
3074                    let p = dir.join(&path);
3075                    if p.is_file() {
3076                        return load_file(&p);
3077                    }
3078                }
3079
3080                let rustlib_path = crate::relative_target_rustlib_path(sysroot, target_tuple);
3083                let p = PathBuf::from_iter([
3084                    Path::new(sysroot),
3085                    Path::new(&rustlib_path),
3086                    Path::new("target.json"),
3087                ]);
3088                if p.is_file() {
3089                    return load_file(&p);
3090                }
3091
3092                if target_tuple == "i586-pc-windows-msvc" {
3096                    Err("the `i586-pc-windows-msvc` target has been removed. Use the `i686-pc-windows-msvc` target instead.\n\
3097                        Windows 10 (the minimum required OS version) requires a CPU baseline of at least i686 so you can safely switch".into())
3098                } else {
3099                    Err(format!("could not find specification for target {target_tuple:?}"))
3100                }
3101            }
3102            TargetTuple::TargetJson { ref contents, .. } => Target::from_json(contents),
3103        }
3104    }
3105
3106    pub fn small_data_threshold_support(&self) -> SmallDataThresholdSupport {
3109        match &self.options.small_data_threshold_support {
3110            SmallDataThresholdSupport::DefaultForArch => match self.arch.as_ref() {
3114                "mips" | "mips64" | "mips32r6" => {
3115                    SmallDataThresholdSupport::LlvmArg("mips-ssection-threshold".into())
3116                }
3117                "hexagon" => {
3118                    SmallDataThresholdSupport::LlvmArg("hexagon-small-data-threshold".into())
3119                }
3120                "m68k" => SmallDataThresholdSupport::LlvmArg("m68k-ssection-threshold".into()),
3121                "riscv32" | "riscv64" => {
3122                    SmallDataThresholdSupport::LlvmModuleFlag("SmallDataLimit".into())
3123                }
3124                _ => SmallDataThresholdSupport::None,
3125            },
3126            s => s.clone(),
3127        }
3128    }
3129
3130    pub fn object_architecture(
3131        &self,
3132        unstable_target_features: &FxIndexSet<Symbol>,
3133    ) -> Option<(object::Architecture, Option<object::SubArchitecture>)> {
3134        use object::Architecture;
3135        Some(match self.arch.as_ref() {
3136            "arm" => (Architecture::Arm, None),
3137            "aarch64" => (
3138                if self.pointer_width == 32 {
3139                    Architecture::Aarch64_Ilp32
3140                } else {
3141                    Architecture::Aarch64
3142                },
3143                None,
3144            ),
3145            "x86" => (Architecture::I386, None),
3146            "s390x" => (Architecture::S390x, None),
3147            "m68k" => (Architecture::M68k, None),
3148            "mips" | "mips32r6" => (Architecture::Mips, None),
3149            "mips64" | "mips64r6" => (
3150                if self.options.llvm_abiname.as_ref() == "n32" {
3156                    Architecture::Mips64_N32
3157                } else {
3158                    Architecture::Mips64
3159                },
3160                None,
3161            ),
3162            "x86_64" => (
3163                if self.pointer_width == 32 {
3164                    Architecture::X86_64_X32
3165                } else {
3166                    Architecture::X86_64
3167                },
3168                None,
3169            ),
3170            "powerpc" => (Architecture::PowerPc, None),
3171            "powerpc64" => (Architecture::PowerPc64, None),
3172            "riscv32" => (Architecture::Riscv32, None),
3173            "riscv64" => (Architecture::Riscv64, None),
3174            "sparc" => {
3175                if unstable_target_features.contains(&sym::v8plus) {
3176                    (Architecture::Sparc32Plus, None)
3178                } else {
3179                    (Architecture::Sparc, None)
3181                }
3182            }
3183            "sparc64" => (Architecture::Sparc64, None),
3184            "avr" => (Architecture::Avr, None),
3185            "msp430" => (Architecture::Msp430, None),
3186            "hexagon" => (Architecture::Hexagon, None),
3187            "xtensa" => (Architecture::Xtensa, None),
3188            "bpf" => (Architecture::Bpf, None),
3189            "loongarch32" => (Architecture::LoongArch32, None),
3190            "loongarch64" => (Architecture::LoongArch64, None),
3191            "csky" => (Architecture::Csky, None),
3192            "arm64ec" => (Architecture::Aarch64, Some(object::SubArchitecture::Arm64EC)),
3193            _ => return None,
3195        })
3196    }
3197
3198    pub fn max_reliable_alignment(&self) -> Align {
3207        if self.is_like_windows && self.arch == "x86" {
3211            Align::from_bytes(4).unwrap()
3212        } else {
3213            Align::MAX
3214        }
3215    }
3216}
3217
3218#[derive(Clone, Debug)]
3220pub enum TargetTuple {
3221    TargetTuple(String),
3222    TargetJson {
3223        path_for_rustdoc: PathBuf,
3226        tuple: String,
3227        contents: String,
3228    },
3229}
3230
3231impl PartialEq for TargetTuple {
3233    fn eq(&self, other: &Self) -> bool {
3234        match (self, other) {
3235            (Self::TargetTuple(l0), Self::TargetTuple(r0)) => l0 == r0,
3236            (
3237                Self::TargetJson { path_for_rustdoc: _, tuple: l_tuple, contents: l_contents },
3238                Self::TargetJson { path_for_rustdoc: _, tuple: r_tuple, contents: r_contents },
3239            ) => l_tuple == r_tuple && l_contents == r_contents,
3240            _ => false,
3241        }
3242    }
3243}
3244
3245impl Hash for TargetTuple {
3247    fn hash<H: Hasher>(&self, state: &mut H) -> () {
3248        match self {
3249            TargetTuple::TargetTuple(tuple) => {
3250                0u8.hash(state);
3251                tuple.hash(state)
3252            }
3253            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3254                1u8.hash(state);
3255                tuple.hash(state);
3256                contents.hash(state)
3257            }
3258        }
3259    }
3260}
3261
3262impl<S: Encoder> Encodable<S> for TargetTuple {
3264    fn encode(&self, s: &mut S) {
3265        match self {
3266            TargetTuple::TargetTuple(tuple) => {
3267                s.emit_u8(0);
3268                s.emit_str(tuple);
3269            }
3270            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3271                s.emit_u8(1);
3272                s.emit_str(tuple);
3273                s.emit_str(contents);
3274            }
3275        }
3276    }
3277}
3278
3279impl<D: Decoder> Decodable<D> for TargetTuple {
3280    fn decode(d: &mut D) -> Self {
3281        match d.read_u8() {
3282            0 => TargetTuple::TargetTuple(d.read_str().to_owned()),
3283            1 => TargetTuple::TargetJson {
3284                path_for_rustdoc: PathBuf::new(),
3285                tuple: d.read_str().to_owned(),
3286                contents: d.read_str().to_owned(),
3287            },
3288            _ => {
3289                panic!("invalid enum variant tag while decoding `TargetTuple`, expected 0..2");
3290            }
3291        }
3292    }
3293}
3294
3295impl TargetTuple {
3296    pub fn from_tuple(tuple: &str) -> Self {
3298        TargetTuple::TargetTuple(tuple.into())
3299    }
3300
3301    pub fn from_path(path: &Path) -> Result<Self, io::Error> {
3303        let canonicalized_path = try_canonicalize(path)?;
3304        let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
3305            io::Error::new(
3306                io::ErrorKind::InvalidInput,
3307                format!("target path {canonicalized_path:?} is not a valid file: {err}"),
3308            )
3309        })?;
3310        let tuple = canonicalized_path
3311            .file_stem()
3312            .expect("target path must not be empty")
3313            .to_str()
3314            .expect("target path must be valid unicode")
3315            .to_owned();
3316        Ok(TargetTuple::TargetJson { path_for_rustdoc: canonicalized_path, tuple, contents })
3317    }
3318
3319    pub fn tuple(&self) -> &str {
3323        match *self {
3324            TargetTuple::TargetTuple(ref tuple) | TargetTuple::TargetJson { ref tuple, .. } => {
3325                tuple
3326            }
3327        }
3328    }
3329
3330    pub fn debug_tuple(&self) -> String {
3335        use std::hash::DefaultHasher;
3336
3337        match self {
3338            TargetTuple::TargetTuple(tuple) => tuple.to_owned(),
3339            TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents: content } => {
3340                let mut hasher = DefaultHasher::new();
3341                content.hash(&mut hasher);
3342                let hash = hasher.finish();
3343                format!("{tuple}-{hash}")
3344            }
3345        }
3346    }
3347}
3348
3349impl fmt::Display for TargetTuple {
3350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3351        write!(f, "{}", self.debug_tuple())
3352    }
3353}
3354
3355into_diag_arg_using_display!(&TargetTuple);