]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Rollup merge of #101057 - cjgillot:one-fn-sig, r=compiler-errors
[rust.git] / compiler / rustc_target / src / spec / mod.rs
1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
2 //!
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
8 //!
9 //! # Using custom targets
10 //!
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
20 //! will be given.
21 //!
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
25 //!
26 //! # Defining a new target
27 //!
28 //! Targets are defined using [JSON](https://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
36
37 use crate::abi::Endian;
38 use crate::json::{Json, ToJson};
39 use crate::spec::abi::{lookup as lookup_abi, Abi};
40 use crate::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
41 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
42 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
43 use rustc_span::symbol::{sym, Symbol};
44 use serde_json::Value;
45 use std::borrow::Cow;
46 use std::collections::BTreeMap;
47 use std::convert::TryFrom;
48 use std::hash::{Hash, Hasher};
49 use std::iter::FromIterator;
50 use std::ops::{Deref, DerefMut};
51 use std::path::{Path, PathBuf};
52 use std::str::FromStr;
53 use std::{fmt, io};
54
55 use rustc_macros::HashStable_Generic;
56
57 pub mod abi;
58 pub mod crt_objects;
59
60 mod android_base;
61 mod apple_base;
62 mod apple_sdk_base;
63 mod avr_gnu_base;
64 mod bpf_base;
65 mod dragonfly_base;
66 mod freebsd_base;
67 mod fuchsia_base;
68 mod haiku_base;
69 mod hermit_base;
70 mod illumos_base;
71 mod l4re_base;
72 mod linux_base;
73 mod linux_gnu_base;
74 mod linux_kernel_base;
75 mod linux_musl_base;
76 mod linux_uclibc_base;
77 mod msvc_base;
78 mod netbsd_base;
79 mod openbsd_base;
80 mod redox_base;
81 mod solaris_base;
82 mod solid_base;
83 mod thumb_base;
84 mod uefi_msvc_base;
85 mod vxworks_base;
86 mod wasm_base;
87 mod windows_gnu_base;
88 mod windows_gnullvm_base;
89 mod windows_msvc_base;
90 mod windows_uwp_gnu_base;
91 mod windows_uwp_msvc_base;
92
93 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
94 pub enum LinkerFlavor {
95     Em,
96     Gcc,
97     L4Bender,
98     Ld,
99     Msvc,
100     Lld(LldFlavor),
101     PtxLinker,
102     BpfLinker,
103 }
104
105 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
106 pub enum LldFlavor {
107     Wasm,
108     Ld64,
109     Ld,
110     Link,
111 }
112
113 impl LldFlavor {
114     pub fn as_str(&self) -> &'static str {
115         match self {
116             LldFlavor::Wasm => "wasm",
117             LldFlavor::Ld64 => "darwin",
118             LldFlavor::Ld => "gnu",
119             LldFlavor::Link => "link",
120         }
121     }
122
123     fn from_str(s: &str) -> Option<Self> {
124         Some(match s {
125             "darwin" => LldFlavor::Ld64,
126             "gnu" => LldFlavor::Ld,
127             "link" => LldFlavor::Link,
128             "wasm" => LldFlavor::Wasm,
129             _ => return None,
130         })
131     }
132 }
133
134 impl ToJson for LldFlavor {
135     fn to_json(&self) -> Json {
136         self.as_str().to_json()
137     }
138 }
139
140 impl ToJson for LinkerFlavor {
141     fn to_json(&self) -> Json {
142         self.desc().to_json()
143     }
144 }
145 macro_rules! flavor_mappings {
146     ($((($($flavor:tt)*), $string:expr),)*) => (
147         impl LinkerFlavor {
148             pub const fn one_of() -> &'static str {
149                 concat!("one of: ", $($string, " ",)*)
150             }
151
152             pub fn from_str(s: &str) -> Option<Self> {
153                 Some(match s {
154                     $($string => $($flavor)*,)*
155                     _ => return None,
156                 })
157             }
158
159             pub fn desc(&self) -> &str {
160                 match *self {
161                     $($($flavor)* => $string,)*
162                 }
163             }
164         }
165     )
166 }
167
168 flavor_mappings! {
169     ((LinkerFlavor::Em), "em"),
170     ((LinkerFlavor::Gcc), "gcc"),
171     ((LinkerFlavor::L4Bender), "l4-bender"),
172     ((LinkerFlavor::Ld), "ld"),
173     ((LinkerFlavor::Msvc), "msvc"),
174     ((LinkerFlavor::PtxLinker), "ptx-linker"),
175     ((LinkerFlavor::BpfLinker), "bpf-linker"),
176     ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
177     ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
178     ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
179     ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
180 }
181
182 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
183 pub enum PanicStrategy {
184     Unwind,
185     Abort,
186 }
187
188 impl PanicStrategy {
189     pub fn desc(&self) -> &str {
190         match *self {
191             PanicStrategy::Unwind => "unwind",
192             PanicStrategy::Abort => "abort",
193         }
194     }
195
196     pub const fn desc_symbol(&self) -> Symbol {
197         match *self {
198             PanicStrategy::Unwind => sym::unwind,
199             PanicStrategy::Abort => sym::abort,
200         }
201     }
202
203     pub const fn all() -> [Symbol; 2] {
204         [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
205     }
206 }
207
208 impl ToJson for PanicStrategy {
209     fn to_json(&self) -> Json {
210         match *self {
211             PanicStrategy::Abort => "abort".to_json(),
212             PanicStrategy::Unwind => "unwind".to_json(),
213         }
214     }
215 }
216
217 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
218 pub enum RelroLevel {
219     Full,
220     Partial,
221     Off,
222     None,
223 }
224
225 impl RelroLevel {
226     pub fn desc(&self) -> &str {
227         match *self {
228             RelroLevel::Full => "full",
229             RelroLevel::Partial => "partial",
230             RelroLevel::Off => "off",
231             RelroLevel::None => "none",
232         }
233     }
234 }
235
236 impl FromStr for RelroLevel {
237     type Err = ();
238
239     fn from_str(s: &str) -> Result<RelroLevel, ()> {
240         match s {
241             "full" => Ok(RelroLevel::Full),
242             "partial" => Ok(RelroLevel::Partial),
243             "off" => Ok(RelroLevel::Off),
244             "none" => Ok(RelroLevel::None),
245             _ => Err(()),
246         }
247     }
248 }
249
250 impl ToJson for RelroLevel {
251     fn to_json(&self) -> Json {
252         match *self {
253             RelroLevel::Full => "full".to_json(),
254             RelroLevel::Partial => "partial".to_json(),
255             RelroLevel::Off => "off".to_json(),
256             RelroLevel::None => "None".to_json(),
257         }
258     }
259 }
260
261 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
262 pub enum MergeFunctions {
263     Disabled,
264     Trampolines,
265     Aliases,
266 }
267
268 impl MergeFunctions {
269     pub fn desc(&self) -> &str {
270         match *self {
271             MergeFunctions::Disabled => "disabled",
272             MergeFunctions::Trampolines => "trampolines",
273             MergeFunctions::Aliases => "aliases",
274         }
275     }
276 }
277
278 impl FromStr for MergeFunctions {
279     type Err = ();
280
281     fn from_str(s: &str) -> Result<MergeFunctions, ()> {
282         match s {
283             "disabled" => Ok(MergeFunctions::Disabled),
284             "trampolines" => Ok(MergeFunctions::Trampolines),
285             "aliases" => Ok(MergeFunctions::Aliases),
286             _ => Err(()),
287         }
288     }
289 }
290
291 impl ToJson for MergeFunctions {
292     fn to_json(&self) -> Json {
293         match *self {
294             MergeFunctions::Disabled => "disabled".to_json(),
295             MergeFunctions::Trampolines => "trampolines".to_json(),
296             MergeFunctions::Aliases => "aliases".to_json(),
297         }
298     }
299 }
300
301 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
302 pub enum RelocModel {
303     Static,
304     Pic,
305     Pie,
306     DynamicNoPic,
307     Ropi,
308     Rwpi,
309     RopiRwpi,
310 }
311
312 impl FromStr for RelocModel {
313     type Err = ();
314
315     fn from_str(s: &str) -> Result<RelocModel, ()> {
316         Ok(match s {
317             "static" => RelocModel::Static,
318             "pic" => RelocModel::Pic,
319             "pie" => RelocModel::Pie,
320             "dynamic-no-pic" => RelocModel::DynamicNoPic,
321             "ropi" => RelocModel::Ropi,
322             "rwpi" => RelocModel::Rwpi,
323             "ropi-rwpi" => RelocModel::RopiRwpi,
324             _ => return Err(()),
325         })
326     }
327 }
328
329 impl ToJson for RelocModel {
330     fn to_json(&self) -> Json {
331         match *self {
332             RelocModel::Static => "static",
333             RelocModel::Pic => "pic",
334             RelocModel::Pie => "pie",
335             RelocModel::DynamicNoPic => "dynamic-no-pic",
336             RelocModel::Ropi => "ropi",
337             RelocModel::Rwpi => "rwpi",
338             RelocModel::RopiRwpi => "ropi-rwpi",
339         }
340         .to_json()
341     }
342 }
343
344 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
345 pub enum CodeModel {
346     Tiny,
347     Small,
348     Kernel,
349     Medium,
350     Large,
351 }
352
353 impl FromStr for CodeModel {
354     type Err = ();
355
356     fn from_str(s: &str) -> Result<CodeModel, ()> {
357         Ok(match s {
358             "tiny" => CodeModel::Tiny,
359             "small" => CodeModel::Small,
360             "kernel" => CodeModel::Kernel,
361             "medium" => CodeModel::Medium,
362             "large" => CodeModel::Large,
363             _ => return Err(()),
364         })
365     }
366 }
367
368 impl ToJson for CodeModel {
369     fn to_json(&self) -> Json {
370         match *self {
371             CodeModel::Tiny => "tiny",
372             CodeModel::Small => "small",
373             CodeModel::Kernel => "kernel",
374             CodeModel::Medium => "medium",
375             CodeModel::Large => "large",
376         }
377         .to_json()
378     }
379 }
380
381 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
382 pub enum TlsModel {
383     GeneralDynamic,
384     LocalDynamic,
385     InitialExec,
386     LocalExec,
387 }
388
389 impl FromStr for TlsModel {
390     type Err = ();
391
392     fn from_str(s: &str) -> Result<TlsModel, ()> {
393         Ok(match s {
394             // Note the difference "general" vs "global" difference. The model name is "general",
395             // but the user-facing option name is "global" for consistency with other compilers.
396             "global-dynamic" => TlsModel::GeneralDynamic,
397             "local-dynamic" => TlsModel::LocalDynamic,
398             "initial-exec" => TlsModel::InitialExec,
399             "local-exec" => TlsModel::LocalExec,
400             _ => return Err(()),
401         })
402     }
403 }
404
405 impl ToJson for TlsModel {
406     fn to_json(&self) -> Json {
407         match *self {
408             TlsModel::GeneralDynamic => "global-dynamic",
409             TlsModel::LocalDynamic => "local-dynamic",
410             TlsModel::InitialExec => "initial-exec",
411             TlsModel::LocalExec => "local-exec",
412         }
413         .to_json()
414     }
415 }
416
417 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
418 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
419 pub enum LinkOutputKind {
420     /// Dynamically linked non position-independent executable.
421     DynamicNoPicExe,
422     /// Dynamically linked position-independent executable.
423     DynamicPicExe,
424     /// Statically linked non position-independent executable.
425     StaticNoPicExe,
426     /// Statically linked position-independent executable.
427     StaticPicExe,
428     /// Regular dynamic library ("dynamically linked").
429     DynamicDylib,
430     /// Dynamic library with bundled libc ("statically linked").
431     StaticDylib,
432     /// WASI module with a lifetime past the _initialize entry point
433     WasiReactorExe,
434 }
435
436 impl LinkOutputKind {
437     fn as_str(&self) -> &'static str {
438         match self {
439             LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
440             LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
441             LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
442             LinkOutputKind::StaticPicExe => "static-pic-exe",
443             LinkOutputKind::DynamicDylib => "dynamic-dylib",
444             LinkOutputKind::StaticDylib => "static-dylib",
445             LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
446         }
447     }
448
449     pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
450         Some(match s {
451             "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
452             "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
453             "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
454             "static-pic-exe" => LinkOutputKind::StaticPicExe,
455             "dynamic-dylib" => LinkOutputKind::DynamicDylib,
456             "static-dylib" => LinkOutputKind::StaticDylib,
457             "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
458             _ => return None,
459         })
460     }
461 }
462
463 impl fmt::Display for LinkOutputKind {
464     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465         f.write_str(self.as_str())
466     }
467 }
468
469 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
470
471 /// Which kind of debuginfo does the target use?
472 ///
473 /// Useful in determining whether a target supports Split DWARF (a target with
474 /// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example).
475 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
476 pub enum DebuginfoKind {
477     /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`).
478     #[default]
479     Dwarf,
480     /// DWARF debuginfo in dSYM files (such as on Apple platforms).
481     DwarfDsym,
482     /// Program database files (such as on Windows).
483     Pdb,
484 }
485
486 impl DebuginfoKind {
487     fn as_str(&self) -> &'static str {
488         match self {
489             DebuginfoKind::Dwarf => "dwarf",
490             DebuginfoKind::DwarfDsym => "dwarf-dsym",
491             DebuginfoKind::Pdb => "pdb",
492         }
493     }
494 }
495
496 impl FromStr for DebuginfoKind {
497     type Err = ();
498
499     fn from_str(s: &str) -> Result<Self, ()> {
500         Ok(match s {
501             "dwarf" => DebuginfoKind::Dwarf,
502             "dwarf-dsym" => DebuginfoKind::DwarfDsym,
503             "pdb" => DebuginfoKind::Pdb,
504             _ => return Err(()),
505         })
506     }
507 }
508
509 impl ToJson for DebuginfoKind {
510     fn to_json(&self) -> Json {
511         self.as_str().to_json()
512     }
513 }
514
515 impl fmt::Display for DebuginfoKind {
516     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517         f.write_str(self.as_str())
518     }
519 }
520
521 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
522 pub enum SplitDebuginfo {
523     /// Split debug-information is disabled, meaning that on supported platforms
524     /// you can find all debug information in the executable itself. This is
525     /// only supported for ELF effectively.
526     ///
527     /// * Windows - not supported
528     /// * macOS - don't run `dsymutil`
529     /// * ELF - `.debug_*` sections
530     #[default]
531     Off,
532
533     /// Split debug-information can be found in a "packed" location separate
534     /// from the final artifact. This is supported on all platforms.
535     ///
536     /// * Windows - `*.pdb`
537     /// * macOS - `*.dSYM` (run `dsymutil`)
538     /// * ELF - `*.dwp` (run `thorin`)
539     Packed,
540
541     /// Split debug-information can be found in individual object files on the
542     /// filesystem. The main executable may point to the object files.
543     ///
544     /// * Windows - not supported
545     /// * macOS - supported, scattered object files
546     /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
547     Unpacked,
548 }
549
550 impl SplitDebuginfo {
551     fn as_str(&self) -> &'static str {
552         match self {
553             SplitDebuginfo::Off => "off",
554             SplitDebuginfo::Packed => "packed",
555             SplitDebuginfo::Unpacked => "unpacked",
556         }
557     }
558 }
559
560 impl FromStr for SplitDebuginfo {
561     type Err = ();
562
563     fn from_str(s: &str) -> Result<Self, ()> {
564         Ok(match s {
565             "off" => SplitDebuginfo::Off,
566             "unpacked" => SplitDebuginfo::Unpacked,
567             "packed" => SplitDebuginfo::Packed,
568             _ => return Err(()),
569         })
570     }
571 }
572
573 impl ToJson for SplitDebuginfo {
574     fn to_json(&self) -> Json {
575         self.as_str().to_json()
576     }
577 }
578
579 impl fmt::Display for SplitDebuginfo {
580     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581         f.write_str(self.as_str())
582     }
583 }
584
585 #[derive(Clone, Debug, PartialEq, Eq)]
586 pub enum StackProbeType {
587     /// Don't emit any stack probes.
588     None,
589     /// It is harmless to use this option even on targets that do not have backend support for
590     /// stack probes as the failure mode is the same as if no stack-probe option was specified in
591     /// the first place.
592     Inline,
593     /// Call `__rust_probestack` whenever stack needs to be probed.
594     Call,
595     /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
596     /// and call `__rust_probestack` otherwise.
597     InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
598 }
599
600 impl StackProbeType {
601     fn from_json(json: &Json) -> Result<Self, String> {
602         let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
603         let kind = object
604             .get("kind")
605             .and_then(|o| o.as_str())
606             .ok_or_else(|| "expected `kind` to be a string")?;
607         match kind {
608             "none" => Ok(StackProbeType::None),
609             "inline" => Ok(StackProbeType::Inline),
610             "call" => Ok(StackProbeType::Call),
611             "inline-or-call" => {
612                 let min_version = object
613                     .get("min-llvm-version-for-inline")
614                     .and_then(|o| o.as_array())
615                     .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
616                 let mut iter = min_version.into_iter().map(|v| {
617                     let int = v.as_u64().ok_or_else(
618                         || "expected `min-llvm-version-for-inline` values to be integers",
619                     )?;
620                     u32::try_from(int)
621                         .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
622                 });
623                 let min_llvm_version_for_inline = (
624                     iter.next().unwrap_or(Ok(11))?,
625                     iter.next().unwrap_or(Ok(0))?,
626                     iter.next().unwrap_or(Ok(0))?,
627                 );
628                 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
629             }
630             _ => Err(String::from(
631                 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
632             )),
633         }
634     }
635 }
636
637 impl ToJson for StackProbeType {
638     fn to_json(&self) -> Json {
639         Json::Object(match self {
640             StackProbeType::None => {
641                 [(String::from("kind"), "none".to_json())].into_iter().collect()
642             }
643             StackProbeType::Inline => {
644                 [(String::from("kind"), "inline".to_json())].into_iter().collect()
645             }
646             StackProbeType::Call => {
647                 [(String::from("kind"), "call".to_json())].into_iter().collect()
648             }
649             StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
650                 (String::from("kind"), "inline-or-call".to_json()),
651                 (
652                     String::from("min-llvm-version-for-inline"),
653                     Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
654                 ),
655             ]
656             .into_iter()
657             .collect(),
658         })
659     }
660 }
661
662 bitflags::bitflags! {
663     #[derive(Default, Encodable, Decodable)]
664     pub struct SanitizerSet: u8 {
665         const ADDRESS = 1 << 0;
666         const LEAK    = 1 << 1;
667         const MEMORY  = 1 << 2;
668         const THREAD  = 1 << 3;
669         const HWADDRESS = 1 << 4;
670         const CFI     = 1 << 5;
671         const MEMTAG  = 1 << 6;
672         const SHADOWCALLSTACK = 1 << 7;
673     }
674 }
675
676 impl SanitizerSet {
677     /// Return sanitizer's name
678     ///
679     /// Returns none if the flags is a set of sanitizers numbering not exactly one.
680     pub fn as_str(self) -> Option<&'static str> {
681         Some(match self {
682             SanitizerSet::ADDRESS => "address",
683             SanitizerSet::CFI => "cfi",
684             SanitizerSet::LEAK => "leak",
685             SanitizerSet::MEMORY => "memory",
686             SanitizerSet::MEMTAG => "memtag",
687             SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
688             SanitizerSet::THREAD => "thread",
689             SanitizerSet::HWADDRESS => "hwaddress",
690             _ => return None,
691         })
692     }
693 }
694
695 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
696 impl fmt::Display for SanitizerSet {
697     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698         let mut first = true;
699         for s in *self {
700             let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
701             if !first {
702                 f.write_str(", ")?;
703             }
704             f.write_str(name)?;
705             first = false;
706         }
707         Ok(())
708     }
709 }
710
711 impl IntoIterator for SanitizerSet {
712     type Item = SanitizerSet;
713     type IntoIter = std::vec::IntoIter<SanitizerSet>;
714
715     fn into_iter(self) -> Self::IntoIter {
716         [
717             SanitizerSet::ADDRESS,
718             SanitizerSet::CFI,
719             SanitizerSet::LEAK,
720             SanitizerSet::MEMORY,
721             SanitizerSet::MEMTAG,
722             SanitizerSet::SHADOWCALLSTACK,
723             SanitizerSet::THREAD,
724             SanitizerSet::HWADDRESS,
725         ]
726         .iter()
727         .copied()
728         .filter(|&s| self.contains(s))
729         .collect::<Vec<_>>()
730         .into_iter()
731     }
732 }
733
734 impl<CTX> HashStable<CTX> for SanitizerSet {
735     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
736         self.bits().hash_stable(ctx, hasher);
737     }
738 }
739
740 impl ToJson for SanitizerSet {
741     fn to_json(&self) -> Json {
742         self.into_iter()
743             .map(|v| Some(v.as_str()?.to_json()))
744             .collect::<Option<Vec<_>>>()
745             .unwrap_or_default()
746             .to_json()
747     }
748 }
749
750 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
751 pub enum FramePointer {
752     /// Forces the machine code generator to always preserve the frame pointers.
753     Always,
754     /// Forces the machine code generator to preserve the frame pointers except for the leaf
755     /// functions (i.e. those that don't call other functions).
756     NonLeaf,
757     /// Allows the machine code generator to omit the frame pointers.
758     ///
759     /// This option does not guarantee that the frame pointers will be omitted.
760     MayOmit,
761 }
762
763 impl FromStr for FramePointer {
764     type Err = ();
765     fn from_str(s: &str) -> Result<Self, ()> {
766         Ok(match s {
767             "always" => Self::Always,
768             "non-leaf" => Self::NonLeaf,
769             "may-omit" => Self::MayOmit,
770             _ => return Err(()),
771         })
772     }
773 }
774
775 impl ToJson for FramePointer {
776     fn to_json(&self) -> Json {
777         match *self {
778             Self::Always => "always",
779             Self::NonLeaf => "non-leaf",
780             Self::MayOmit => "may-omit",
781         }
782         .to_json()
783     }
784 }
785
786 /// Controls use of stack canaries.
787 #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
788 pub enum StackProtector {
789     /// Disable stack canary generation.
790     None,
791
792     /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
793     /// llvm/docs/LangRef.rst). This triggers stack canary generation in
794     /// functions which contain an array of a byte-sized type with more than
795     /// eight elements.
796     Basic,
797
798     /// On LLVM, mark all generated LLVM functions with the `sspstrong`
799     /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
800     /// generation in functions which either contain an array, or which take
801     /// the address of a local variable.
802     Strong,
803
804     /// Generate stack canaries in all functions.
805     All,
806 }
807
808 impl StackProtector {
809     fn as_str(&self) -> &'static str {
810         match self {
811             StackProtector::None => "none",
812             StackProtector::Basic => "basic",
813             StackProtector::Strong => "strong",
814             StackProtector::All => "all",
815         }
816     }
817 }
818
819 impl FromStr for StackProtector {
820     type Err = ();
821
822     fn from_str(s: &str) -> Result<StackProtector, ()> {
823         Ok(match s {
824             "none" => StackProtector::None,
825             "basic" => StackProtector::Basic,
826             "strong" => StackProtector::Strong,
827             "all" => StackProtector::All,
828             _ => return Err(()),
829         })
830     }
831 }
832
833 impl fmt::Display for StackProtector {
834     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835         f.write_str(self.as_str())
836     }
837 }
838
839 macro_rules! supported_targets {
840     ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
841         $(mod $module;)+
842
843         /// List of supported targets
844         pub const TARGETS: &[&str] = &[$($($triple),+),+];
845
846         fn load_builtin(target: &str) -> Option<Target> {
847             let mut t = match target {
848                 $( $($triple)|+ => $module::target(), )+
849                 _ => return None,
850             };
851             t.is_builtin = true;
852             debug!("got builtin target: {:?}", t);
853             Some(t)
854         }
855
856         #[cfg(test)]
857         mod tests {
858             mod tests_impl;
859
860             // Cannot put this into a separate file without duplication, make an exception.
861             $(
862                 #[test] // `#[test]`
863                 fn $module() {
864                     tests_impl::test_target(super::$module::target());
865                 }
866             )+
867         }
868     };
869 }
870
871 supported_targets! {
872     ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
873     ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
874     ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
875     ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
876     ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
877     ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
878     ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
879     ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
880     ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
881     ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
882     ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
883     ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
884     ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
885     ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
886     ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
887     ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
888     ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
889     ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
890     ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
891     ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
892     ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
893     ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
894     ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
895     ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
896     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
897     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
898     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
899     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
900     ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
901     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
902     ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
903     ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
904     ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
905     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
906     ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
907     ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
908     ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
909     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
910     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
911     ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
912     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
913     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
914     ("i586-unknown-linux-musl", i586_unknown_linux_musl),
915     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
916     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
917     ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
918     ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
919     ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
920
921     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
922     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
923
924     ("i686-linux-android", i686_linux_android),
925     ("x86_64-linux-android", x86_64_linux_android),
926     ("arm-linux-androideabi", arm_linux_androideabi),
927     ("armv7-linux-androideabi", armv7_linux_androideabi),
928     ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
929     ("aarch64-linux-android", aarch64_linux_android),
930
931     ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
932
933     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
934     ("armv6-unknown-freebsd", armv6_unknown_freebsd),
935     ("armv7-unknown-freebsd", armv7_unknown_freebsd),
936     ("i686-unknown-freebsd", i686_unknown_freebsd),
937     ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
938     ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
939     ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
940     ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
941     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
942
943     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
944
945     ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
946     ("i686-unknown-openbsd", i686_unknown_openbsd),
947     ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
948     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
949     ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
950
951     ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
952     ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
953     ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
954     ("i686-unknown-netbsd", i686_unknown_netbsd),
955     ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
956     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
957     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
958
959     ("i686-unknown-haiku", i686_unknown_haiku),
960     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
961
962     ("aarch64-apple-darwin", aarch64_apple_darwin),
963     ("x86_64-apple-darwin", x86_64_apple_darwin),
964     ("i686-apple-darwin", i686_apple_darwin),
965
966     ("aarch64-fuchsia", aarch64_fuchsia),
967     ("x86_64-fuchsia", x86_64_fuchsia),
968
969     ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
970
971     ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
972
973     ("aarch64-unknown-redox", aarch64_unknown_redox),
974     ("x86_64-unknown-redox", x86_64_unknown_redox),
975
976     ("i386-apple-ios", i386_apple_ios),
977     ("x86_64-apple-ios", x86_64_apple_ios),
978     ("aarch64-apple-ios", aarch64_apple_ios),
979     ("armv7-apple-ios", armv7_apple_ios),
980     ("armv7s-apple-ios", armv7s_apple_ios),
981     ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
982     ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
983     ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
984     ("aarch64-apple-tvos", aarch64_apple_tvos),
985     ("x86_64-apple-tvos", x86_64_apple_tvos),
986
987     ("armv7k-apple-watchos", armv7k_apple_watchos),
988     ("arm64_32-apple-watchos", arm64_32_apple_watchos),
989     ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
990     ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
991
992     ("armebv7r-none-eabi", armebv7r_none_eabi),
993     ("armebv7r-none-eabihf", armebv7r_none_eabihf),
994     ("armv7r-none-eabi", armv7r_none_eabi),
995     ("armv7r-none-eabihf", armv7r_none_eabihf),
996
997     ("x86_64-pc-solaris", x86_64_pc_solaris),
998     ("x86_64-sun-solaris", x86_64_sun_solaris),
999     ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1000
1001     ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1002
1003     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1004     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1005     ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1006     ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1007
1008     ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1009     ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1010
1011     ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1012     ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1013     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1014     ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1015     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1016     ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1017     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
1018     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1019     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1020
1021     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
1022     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1023     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1024     ("wasm32-wasi", wasm32_wasi),
1025     ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1026
1027     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1028     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1029     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1030     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1031     ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1032     ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1033     ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1034
1035     ("armv7a-none-eabi", armv7a_none_eabi),
1036     ("armv7a-none-eabihf", armv7a_none_eabihf),
1037
1038     ("msp430-none-elf", msp430_none_elf),
1039
1040     ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1041     ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1042
1043     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1044     ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1045     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1046     ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1047     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1048     ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1049     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1050     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1051     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1052     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1053     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1054     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1055
1056     ("aarch64-unknown-none", aarch64_unknown_none),
1057     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1058
1059     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1060
1061     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1062     ("i686-unknown-uefi", i686_unknown_uefi),
1063     ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1064
1065     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1066
1067     ("i686-wrs-vxworks", i686_wrs_vxworks),
1068     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1069     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1070     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1071     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1072     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1073     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1074
1075     ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1076     ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1077     ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1078
1079     ("mipsel-sony-psp", mipsel_sony_psp),
1080     ("mipsel-unknown-none", mipsel_unknown_none),
1081     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1082     ("armv4t-none-eabi", armv4t_none_eabi),
1083
1084     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1085     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1086     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1087
1088     ("bpfeb-unknown-none", bpfeb_unknown_none),
1089     ("bpfel-unknown-none", bpfel_unknown_none),
1090
1091     ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1092
1093     ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1094
1095     ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1096     ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1097
1098     ("x86_64-unknown-none", x86_64_unknown_none),
1099
1100     ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1101 }
1102
1103 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1104 macro_rules! cvs {
1105     () => {
1106         ::std::borrow::Cow::Borrowed(&[])
1107     };
1108     ($($x:expr),+ $(,)?) => {
1109         ::std::borrow::Cow::Borrowed(&[
1110             $(
1111                 ::std::borrow::Cow::Borrowed($x),
1112             )*
1113         ])
1114     };
1115 }
1116
1117 pub(crate) use cvs;
1118
1119 /// Warnings encountered when parsing the target `json`.
1120 ///
1121 /// Includes fields that weren't recognized and fields that don't have the expected type.
1122 #[derive(Debug, PartialEq)]
1123 pub struct TargetWarnings {
1124     unused_fields: Vec<String>,
1125     incorrect_type: Vec<String>,
1126 }
1127
1128 impl TargetWarnings {
1129     pub fn empty() -> Self {
1130         Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1131     }
1132
1133     pub fn warning_messages(&self) -> Vec<String> {
1134         let mut warnings = vec![];
1135         if !self.unused_fields.is_empty() {
1136             warnings.push(format!(
1137                 "target json file contains unused fields: {}",
1138                 self.unused_fields.join(", ")
1139             ));
1140         }
1141         if !self.incorrect_type.is_empty() {
1142             warnings.push(format!(
1143                 "target json file contains fields whose value doesn't have the correct json type: {}",
1144                 self.incorrect_type.join(", ")
1145             ));
1146         }
1147         warnings
1148     }
1149 }
1150
1151 /// Everything `rustc` knows about how to compile for a specific target.
1152 ///
1153 /// Every field here must be specified, and has no default value.
1154 #[derive(PartialEq, Clone, Debug)]
1155 pub struct Target {
1156     /// Target triple to pass to LLVM.
1157     pub llvm_target: StaticCow<str>,
1158     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1159     pub pointer_width: u32,
1160     /// Architecture to use for ABI considerations. Valid options include: "x86",
1161     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1162     pub arch: StaticCow<str>,
1163     /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1164     pub data_layout: StaticCow<str>,
1165     /// Optional settings with defaults.
1166     pub options: TargetOptions,
1167 }
1168
1169 pub trait HasTargetSpec {
1170     fn target_spec(&self) -> &Target;
1171 }
1172
1173 impl HasTargetSpec for Target {
1174     #[inline]
1175     fn target_spec(&self) -> &Target {
1176         self
1177     }
1178 }
1179
1180 type StaticCow<T> = Cow<'static, T>;
1181
1182 /// Optional aspects of a target specification.
1183 ///
1184 /// This has an implementation of `Default`, see each field for what the default is. In general,
1185 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1186 ///
1187 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1188 /// construction, all its fields logically belong to `Target` and available from `Target`
1189 /// through `Deref` impls.
1190 #[derive(PartialEq, Clone, Debug)]
1191 pub struct TargetOptions {
1192     /// Whether the target is built-in or loaded from a custom target specification.
1193     pub is_builtin: bool,
1194
1195     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1196     pub endian: Endian,
1197     /// Width of c_int type. Defaults to "32".
1198     pub c_int_width: StaticCow<str>,
1199     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1200     /// "none" implies a bare metal target without `std` library.
1201     /// A couple of targets having `std` also use "unknown" as an `os` value,
1202     /// but they are exceptions.
1203     pub os: StaticCow<str>,
1204     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1205     pub env: StaticCow<str>,
1206     /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1207     /// or `"eabihf"`. Defaults to "".
1208     pub abi: StaticCow<str>,
1209     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1210     pub vendor: StaticCow<str>,
1211     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1212     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1213     pub linker_flavor: LinkerFlavor,
1214
1215     /// Linker to invoke
1216     pub linker: Option<StaticCow<str>>,
1217
1218     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1219     /// without clarifying its flavor in any way.
1220     pub lld_flavor: LldFlavor,
1221
1222     /// Linker arguments that are passed *before* any user-defined libraries.
1223     pub pre_link_args: LinkArgs,
1224     /// Objects to link before and after all other object code.
1225     pub pre_link_objects: CrtObjects,
1226     pub post_link_objects: CrtObjects,
1227     /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1228     pub pre_link_objects_self_contained: CrtObjects,
1229     pub post_link_objects_self_contained: CrtObjects,
1230     pub link_self_contained: LinkSelfContainedDefault,
1231
1232     /// Linker arguments that are unconditionally passed after any
1233     /// user-defined but before post-link objects. Standard platform
1234     /// libraries that should be always be linked to, usually go here.
1235     pub late_link_args: LinkArgs,
1236     /// Linker arguments used in addition to `late_link_args` if at least one
1237     /// Rust dependency is dynamically linked.
1238     pub late_link_args_dynamic: LinkArgs,
1239     /// Linker arguments used in addition to `late_link_args` if all Rust
1240     /// dependencies are statically linked.
1241     pub late_link_args_static: LinkArgs,
1242     /// Linker arguments that are unconditionally passed *after* any
1243     /// user-defined libraries.
1244     pub post_link_args: LinkArgs,
1245     /// Optional link script applied to `dylib` and `executable` crate types.
1246     /// This is a string containing the script, not a path. Can only be applied
1247     /// to linkers where `linker_is_gnu` is true.
1248     pub link_script: Option<StaticCow<str>>,
1249
1250     /// Environment variables to be set for the linker invocation.
1251     pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1252     /// Environment variables to be removed for the linker invocation.
1253     pub link_env_remove: StaticCow<[StaticCow<str>]>,
1254
1255     /// Extra arguments to pass to the external assembler (when used)
1256     pub asm_args: StaticCow<[StaticCow<str>]>,
1257
1258     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1259     /// to "generic".
1260     pub cpu: StaticCow<str>,
1261     /// Default target features to pass to LLVM. These features will *always* be
1262     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1263     /// -mattr=$features`.
1264     pub features: StaticCow<str>,
1265     /// Whether dynamic linking is available on this target. Defaults to false.
1266     pub dynamic_linking: bool,
1267     /// If dynamic linking is available, whether only cdylibs are supported.
1268     pub only_cdylib: bool,
1269     /// Whether executables are available on this target. Defaults to true.
1270     pub executables: bool,
1271     /// Relocation model to use in object file. Corresponds to `llc
1272     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1273     pub relocation_model: RelocModel,
1274     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1275     /// Defaults to `None` which means "inherited from the base LLVM target".
1276     pub code_model: Option<CodeModel>,
1277     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1278     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1279     pub tls_model: TlsModel,
1280     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1281     pub disable_redzone: bool,
1282     /// Frame pointer mode for this target. Defaults to `MayOmit`.
1283     pub frame_pointer: FramePointer,
1284     /// Emit each function in its own section. Defaults to true.
1285     pub function_sections: bool,
1286     /// String to prepend to the name of every dynamic library. Defaults to "lib".
1287     pub dll_prefix: StaticCow<str>,
1288     /// String to append to the name of every dynamic library. Defaults to ".so".
1289     pub dll_suffix: StaticCow<str>,
1290     /// String to append to the name of every executable.
1291     pub exe_suffix: StaticCow<str>,
1292     /// String to prepend to the name of every static library. Defaults to "lib".
1293     pub staticlib_prefix: StaticCow<str>,
1294     /// String to append to the name of every static library. Defaults to ".a".
1295     pub staticlib_suffix: StaticCow<str>,
1296     /// Values of the `target_family` cfg set for this target.
1297     ///
1298     /// Common options are: "unix", "windows". Defaults to no families.
1299     ///
1300     /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1301     pub families: StaticCow<[StaticCow<str>]>,
1302     /// Whether the target toolchain's ABI supports returning small structs as an integer.
1303     pub abi_return_struct_as_int: bool,
1304     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1305     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1306     pub is_like_osx: bool,
1307     /// Whether the target toolchain is like Solaris's.
1308     /// Only useful for compiling against Illumos/Solaris,
1309     /// as they have a different set of linker flags. Defaults to false.
1310     pub is_like_solaris: bool,
1311     /// Whether the target is like Windows.
1312     /// This is a combination of several more specific properties represented as a single flag:
1313     ///   - The target uses a Windows ABI,
1314     ///   - uses PE/COFF as a format for object code,
1315     ///   - uses Windows-style dllexport/dllimport for shared libraries,
1316     ///   - uses import libraries and .def files for symbol exports,
1317     ///   - executables support setting a subsystem.
1318     pub is_like_windows: bool,
1319     /// Whether the target is like MSVC.
1320     /// This is a combination of several more specific properties represented as a single flag:
1321     ///   - The target has all the properties from `is_like_windows`
1322     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
1323     ///   - has some MSVC-specific Windows ABI properties,
1324     ///   - uses a link.exe-like linker,
1325     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
1326     ///   - uses SEH-based unwinding,
1327     ///   - supports control flow guard mechanism.
1328     pub is_like_msvc: bool,
1329     /// Whether a target toolchain is like WASM.
1330     pub is_like_wasm: bool,
1331     /// Default supported version of DWARF on this platform.
1332     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1333     pub default_dwarf_version: u32,
1334     /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1335     pub linker_is_gnu: bool,
1336     /// The MinGW toolchain has a known issue that prevents it from correctly
1337     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1338     /// symbol needs its own COMDAT section, weak linkage implies a large
1339     /// number sections that easily exceeds the given limit for larger
1340     /// codebases. Consequently we want a way to disallow weak linkage on some
1341     /// platforms.
1342     pub allows_weak_linkage: bool,
1343     /// Whether the linker support rpaths or not. Defaults to false.
1344     pub has_rpath: bool,
1345     /// Whether to disable linking to the default libraries, typically corresponds
1346     /// to `-nodefaultlibs`. Defaults to true.
1347     pub no_default_libraries: bool,
1348     /// Dynamically linked executables can be compiled as position independent
1349     /// if the default relocation model of position independent code is not
1350     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1351     /// the functions in the executable are not randomized and can be used
1352     /// during an exploit of a vulnerability in any code.
1353     pub position_independent_executables: bool,
1354     /// Executables that are both statically linked and position-independent are supported.
1355     pub static_position_independent_executables: bool,
1356     /// Determines if the target always requires using the PLT for indirect
1357     /// library calls or not. This controls the default value of the `-Z plt` flag.
1358     pub needs_plt: bool,
1359     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1360     /// resolve all symbols at startup and marks the GOT read-only before
1361     /// starting the program, preventing overwriting the GOT.
1362     pub relro_level: RelroLevel,
1363     /// Format that archives should be emitted in. This affects whether we use
1364     /// LLVM to assemble an archive or fall back to the system linker, and
1365     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1366     /// the system linker to be used.
1367     pub archive_format: StaticCow<str>,
1368     /// Is asm!() allowed? Defaults to true.
1369     pub allow_asm: bool,
1370     /// Whether the runtime startup code requires the `main` function be passed
1371     /// `argc` and `argv` values.
1372     pub main_needs_argc_argv: bool,
1373
1374     /// Flag indicating whether #[thread_local] is available for this target.
1375     pub has_thread_local: bool,
1376     // This is mainly for easy compatibility with emscripten.
1377     // If we give emcc .o files that are actually .bc files it
1378     // will 'just work'.
1379     pub obj_is_bitcode: bool,
1380     /// Whether the target requires that emitted object code includes bitcode.
1381     pub forces_embed_bitcode: bool,
1382     /// Content of the LLVM cmdline section associated with embedded bitcode.
1383     pub bitcode_llvm_cmdline: StaticCow<str>,
1384
1385     /// Don't use this field; instead use the `.min_atomic_width()` method.
1386     pub min_atomic_width: Option<u64>,
1387
1388     /// Don't use this field; instead use the `.max_atomic_width()` method.
1389     pub max_atomic_width: Option<u64>,
1390
1391     /// Whether the target supports atomic CAS operations natively
1392     pub atomic_cas: bool,
1393
1394     /// Panic strategy: "unwind" or "abort"
1395     pub panic_strategy: PanicStrategy,
1396
1397     /// Whether or not linking dylibs to a static CRT is allowed.
1398     pub crt_static_allows_dylibs: bool,
1399     /// Whether or not the CRT is statically linked by default.
1400     pub crt_static_default: bool,
1401     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1402     pub crt_static_respected: bool,
1403
1404     /// The implementation of stack probes to use.
1405     pub stack_probes: StackProbeType,
1406
1407     /// The minimum alignment for global symbols.
1408     pub min_global_align: Option<u64>,
1409
1410     /// Default number of codegen units to use in debug mode
1411     pub default_codegen_units: Option<u64>,
1412
1413     /// Whether to generate trap instructions in places where optimization would
1414     /// otherwise produce control flow that falls through into unrelated memory.
1415     pub trap_unreachable: bool,
1416
1417     /// This target requires everything to be compiled with LTO to emit a final
1418     /// executable, aka there is no native linker for this target.
1419     pub requires_lto: bool,
1420
1421     /// This target has no support for threads.
1422     pub singlethread: bool,
1423
1424     /// Whether library functions call lowering/optimization is disabled in LLVM
1425     /// for this target unconditionally.
1426     pub no_builtins: bool,
1427
1428     /// The default visibility for symbols in this target should be "hidden"
1429     /// rather than "default"
1430     pub default_hidden_visibility: bool,
1431
1432     /// Whether a .debug_gdb_scripts section will be added to the output object file
1433     pub emit_debug_gdb_scripts: bool,
1434
1435     /// Whether or not to unconditionally `uwtable` attributes on functions,
1436     /// typically because the platform needs to unwind for things like stack
1437     /// unwinders.
1438     pub requires_uwtable: bool,
1439
1440     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1441     /// is not specified and `uwtable` is not required on this target.
1442     pub default_uwtable: bool,
1443
1444     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1445     /// typically required if a target can be compiled with a mixed set of
1446     /// target features. This is `true` by default, and `false` for targets like
1447     /// wasm32 where the whole program either has simd or not.
1448     pub simd_types_indirect: bool,
1449
1450     /// Pass a list of symbol which should be exported in the dylib to the linker.
1451     pub limit_rdylib_exports: bool,
1452
1453     /// If set, have the linker export exactly these symbols, instead of using
1454     /// the usual logic to figure this out from the crate itself.
1455     pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1456
1457     /// Determines how or whether the MergeFunctions LLVM pass should run for
1458     /// this target. Either "disabled", "trampolines", or "aliases".
1459     /// The MergeFunctions pass is generally useful, but some targets may need
1460     /// to opt out. The default is "aliases".
1461     ///
1462     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1463     pub merge_functions: MergeFunctions,
1464
1465     /// Use platform dependent mcount function
1466     pub mcount: StaticCow<str>,
1467
1468     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1469     pub llvm_abiname: StaticCow<str>,
1470
1471     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1472     pub relax_elf_relocations: bool,
1473
1474     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1475     pub llvm_args: StaticCow<[StaticCow<str>]>,
1476
1477     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1478     /// to false (uses .init_array).
1479     pub use_ctors_section: bool,
1480
1481     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1482     /// used to locate unwinding information is passed
1483     /// (only has effect if the linker is `ld`-like).
1484     pub eh_frame_header: bool,
1485
1486     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1487     /// thumb and arm interworking.
1488     pub has_thumb_interworking: bool,
1489
1490     /// Which kind of debuginfo is used by this target?
1491     pub debuginfo_kind: DebuginfoKind,
1492     /// How to handle split debug information, if at all. Specifying `None` has
1493     /// target-specific meaning.
1494     pub split_debuginfo: SplitDebuginfo,
1495     /// Which kinds of split debuginfo are supported by the target?
1496     pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
1497
1498     /// The sanitizers supported by this target
1499     ///
1500     /// Note that the support here is at a codegen level. If the machine code with sanitizer
1501     /// enabled can generated on this target, but the necessary supporting libraries are not
1502     /// distributed with the target, the sanitizer should still appear in this list for the target.
1503     pub supported_sanitizers: SanitizerSet,
1504
1505     /// If present it's a default value to use for adjusting the C ABI.
1506     pub default_adjusted_cabi: Option<Abi>,
1507
1508     /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1509     pub c_enum_min_bits: u64,
1510
1511     /// Whether or not the DWARF `.debug_aranges` section should be generated.
1512     pub generate_arange_section: bool,
1513
1514     /// Whether the target supports stack canary checks. `true` by default,
1515     /// since this is most common among tier 1 and tier 2 targets.
1516     pub supports_stack_protector: bool,
1517 }
1518
1519 /// Add arguments for the given flavor and also for its "twin" flavors
1520 /// that have a compatible command line interface.
1521 fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
1522     let mut insert = |flavor| {
1523         link_args.entry(flavor).or_default().extend(args.iter().copied().map(Cow::Borrowed))
1524     };
1525     insert(flavor);
1526     match flavor {
1527         LinkerFlavor::Ld => insert(LinkerFlavor::Lld(LldFlavor::Ld)),
1528         LinkerFlavor::Msvc => insert(LinkerFlavor::Lld(LldFlavor::Link)),
1529         LinkerFlavor::Lld(LldFlavor::Wasm) => {}
1530         LinkerFlavor::Lld(lld_flavor) => {
1531             panic!("add_link_args: use non-LLD flavor for {:?}", lld_flavor)
1532         }
1533         LinkerFlavor::Gcc
1534         | LinkerFlavor::Em
1535         | LinkerFlavor::L4Bender
1536         | LinkerFlavor::BpfLinker
1537         | LinkerFlavor::PtxLinker => {}
1538     }
1539 }
1540
1541 impl TargetOptions {
1542     fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
1543         let mut link_args = LinkArgs::new();
1544         add_link_args(&mut link_args, flavor, args);
1545         link_args
1546     }
1547
1548     fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1549         add_link_args(&mut self.pre_link_args, flavor, args);
1550     }
1551
1552     fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1553         add_link_args(&mut self.post_link_args, flavor, args);
1554     }
1555 }
1556
1557 impl Default for TargetOptions {
1558     /// Creates a set of "sane defaults" for any target. This is still
1559     /// incomplete, and if used for compilation, will certainly not work.
1560     fn default() -> TargetOptions {
1561         TargetOptions {
1562             is_builtin: false,
1563             endian: Endian::Little,
1564             c_int_width: "32".into(),
1565             os: "none".into(),
1566             env: "".into(),
1567             abi: "".into(),
1568             vendor: "unknown".into(),
1569             linker_flavor: LinkerFlavor::Gcc,
1570             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1571             lld_flavor: LldFlavor::Ld,
1572             pre_link_args: LinkArgs::new(),
1573             post_link_args: LinkArgs::new(),
1574             link_script: None,
1575             asm_args: cvs![],
1576             cpu: "generic".into(),
1577             features: "".into(),
1578             dynamic_linking: false,
1579             only_cdylib: false,
1580             executables: true,
1581             relocation_model: RelocModel::Pic,
1582             code_model: None,
1583             tls_model: TlsModel::GeneralDynamic,
1584             disable_redzone: false,
1585             frame_pointer: FramePointer::MayOmit,
1586             function_sections: true,
1587             dll_prefix: "lib".into(),
1588             dll_suffix: ".so".into(),
1589             exe_suffix: "".into(),
1590             staticlib_prefix: "lib".into(),
1591             staticlib_suffix: ".a".into(),
1592             families: cvs![],
1593             abi_return_struct_as_int: false,
1594             is_like_osx: false,
1595             is_like_solaris: false,
1596             is_like_windows: false,
1597             is_like_msvc: false,
1598             is_like_wasm: false,
1599             default_dwarf_version: 4,
1600             linker_is_gnu: true,
1601             allows_weak_linkage: true,
1602             has_rpath: false,
1603             no_default_libraries: true,
1604             position_independent_executables: false,
1605             static_position_independent_executables: false,
1606             needs_plt: false,
1607             relro_level: RelroLevel::None,
1608             pre_link_objects: Default::default(),
1609             post_link_objects: Default::default(),
1610             pre_link_objects_self_contained: Default::default(),
1611             post_link_objects_self_contained: Default::default(),
1612             link_self_contained: LinkSelfContainedDefault::False,
1613             late_link_args: LinkArgs::new(),
1614             late_link_args_dynamic: LinkArgs::new(),
1615             late_link_args_static: LinkArgs::new(),
1616             link_env: cvs![],
1617             link_env_remove: cvs![],
1618             archive_format: "gnu".into(),
1619             main_needs_argc_argv: true,
1620             allow_asm: true,
1621             has_thread_local: false,
1622             obj_is_bitcode: false,
1623             forces_embed_bitcode: false,
1624             bitcode_llvm_cmdline: "".into(),
1625             min_atomic_width: None,
1626             max_atomic_width: None,
1627             atomic_cas: true,
1628             panic_strategy: PanicStrategy::Unwind,
1629             crt_static_allows_dylibs: false,
1630             crt_static_default: false,
1631             crt_static_respected: false,
1632             stack_probes: StackProbeType::None,
1633             min_global_align: None,
1634             default_codegen_units: None,
1635             trap_unreachable: true,
1636             requires_lto: false,
1637             singlethread: false,
1638             no_builtins: false,
1639             default_hidden_visibility: false,
1640             emit_debug_gdb_scripts: true,
1641             requires_uwtable: false,
1642             default_uwtable: false,
1643             simd_types_indirect: true,
1644             limit_rdylib_exports: true,
1645             override_export_symbols: None,
1646             merge_functions: MergeFunctions::Aliases,
1647             mcount: "mcount".into(),
1648             llvm_abiname: "".into(),
1649             relax_elf_relocations: false,
1650             llvm_args: cvs![],
1651             use_ctors_section: false,
1652             eh_frame_header: true,
1653             has_thumb_interworking: false,
1654             debuginfo_kind: Default::default(),
1655             split_debuginfo: Default::default(),
1656             // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
1657             supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
1658             supported_sanitizers: SanitizerSet::empty(),
1659             default_adjusted_cabi: None,
1660             c_enum_min_bits: 32,
1661             generate_arange_section: true,
1662             supports_stack_protector: true,
1663         }
1664     }
1665 }
1666
1667 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1668 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1669 /// this `Deref` implementation is no longer necessary.
1670 impl Deref for Target {
1671     type Target = TargetOptions;
1672
1673     #[inline]
1674     fn deref(&self) -> &Self::Target {
1675         &self.options
1676     }
1677 }
1678 impl DerefMut for Target {
1679     #[inline]
1680     fn deref_mut(&mut self) -> &mut Self::Target {
1681         &mut self.options
1682     }
1683 }
1684
1685 impl Target {
1686     /// Given a function ABI, turn it into the correct ABI for this target.
1687     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1688         match abi {
1689             Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1690             Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1691                 Abi::Stdcall { unwind }
1692             }
1693             Abi::System { unwind } => Abi::C { unwind },
1694             Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1695             Abi::EfiApi => Abi::C { unwind: false },
1696
1697             // See commentary in `is_abi_supported`.
1698             Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1699             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1700             Abi::Fastcall { .. } if self.arch == "x86" => abi,
1701             Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1702             Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1703
1704             abi => abi,
1705         }
1706     }
1707
1708     /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1709     pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1710         use Abi::*;
1711         Some(match abi {
1712             Rust
1713             | C { .. }
1714             | System { .. }
1715             | RustIntrinsic
1716             | RustCall
1717             | PlatformIntrinsic
1718             | Unadjusted
1719             | Cdecl { .. }
1720             | EfiApi
1721             | RustCold => true,
1722             X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1723             Aapcs { .. } => "arm" == self.arch,
1724             CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1725             Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1726             PtxKernel => self.arch == "nvptx64",
1727             Msp430Interrupt => self.arch == "msp430",
1728             AmdGpuKernel => self.arch == "amdgcn",
1729             AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1730             Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1731             Thiscall { .. } => self.arch == "x86",
1732             // On windows these fall-back to platform native calling convention (C) when the
1733             // architecture is not supported.
1734             //
1735             // This is I believe a historical accident that has occurred as part of Microsoft
1736             // striving to allow most of the code to "just" compile when support for 64-bit x86
1737             // was added and then later again, when support for ARM architectures was added.
1738             //
1739             // This is well documented across MSDN. Support for this in Rust has been added in
1740             // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1741             // Rust, but there isn't much leeway remaining here to change it back at the time this
1742             // comment has been written.
1743             //
1744             // Following are the relevant excerpts from the MSDN documentation.
1745             //
1746             // > The __vectorcall calling convention is only supported in native code on x86 and
1747             // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1748             // > ...
1749             // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1750             //
1751             // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1752             //
1753             // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1754             //
1755             // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1756             //
1757             // > In most cases, keywords or compiler switches that specify an unsupported
1758             // > convention on a particular platform are ignored, and the platform default
1759             // > convention is used.
1760             //
1761             // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1762             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1763             // Outside of Windows we want to only support these calling conventions for the
1764             // architectures for which these calling conventions are actually well defined.
1765             Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1766             Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1767             // Return a `None` for other cases so that we know to emit a future compat lint.
1768             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1769         })
1770     }
1771
1772     /// Minimum integer size in bits that this target can perform atomic
1773     /// operations on.
1774     pub fn min_atomic_width(&self) -> u64 {
1775         self.min_atomic_width.unwrap_or(8)
1776     }
1777
1778     /// Maximum integer size in bits that this target can perform atomic
1779     /// operations on.
1780     pub fn max_atomic_width(&self) -> u64 {
1781         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1782     }
1783
1784     /// Loads a target descriptor from a JSON object.
1785     pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
1786         // While ugly, this code must remain this way to retain
1787         // compatibility with existing JSON fields and the internal
1788         // expected naming of the Target and TargetOptions structs.
1789         // To ensure compatibility is retained, the built-in targets
1790         // are round-tripped through this code to catch cases where
1791         // the JSON parser is not updated to match the structs.
1792
1793         let mut obj = match obj {
1794             Value::Object(obj) => obj,
1795             _ => return Err("Expected JSON object for target")?,
1796         };
1797
1798         let mut get_req_field = |name: &str| {
1799             obj.remove(name)
1800                 .and_then(|j| j.as_str().map(str::to_string))
1801                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1802         };
1803
1804         let mut base = Target {
1805             llvm_target: get_req_field("llvm-target")?.into(),
1806             pointer_width: get_req_field("target-pointer-width")?
1807                 .parse::<u32>()
1808                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1809             data_layout: get_req_field("data-layout")?.into(),
1810             arch: get_req_field("arch")?.into(),
1811             options: Default::default(),
1812         };
1813
1814         let mut incorrect_type = vec![];
1815
1816         macro_rules! key {
1817             ($key_name:ident) => ( {
1818                 let name = (stringify!($key_name)).replace("_", "-");
1819                 if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1820                     base.$key_name = s;
1821                 }
1822             } );
1823             ($key_name:ident = $json_name:expr) => ( {
1824                 let name = $json_name;
1825                 if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1826                     base.$key_name = s;
1827                 }
1828             } );
1829             ($key_name:ident, bool) => ( {
1830                 let name = (stringify!($key_name)).replace("_", "-");
1831                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
1832                     base.$key_name = s;
1833                 }
1834             } );
1835             ($key_name:ident, u64) => ( {
1836                 let name = (stringify!($key_name)).replace("_", "-");
1837                 if let Some(s) = obj.remove(&name).and_then(|j| Json::as_u64(&j)) {
1838                     base.$key_name = s;
1839                 }
1840             } );
1841             ($key_name:ident, u32) => ( {
1842                 let name = (stringify!($key_name)).replace("_", "-");
1843                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1844                     if s < 1 || s > 5 {
1845                         return Err("Not a valid DWARF version number".into());
1846                     }
1847                     base.$key_name = s as u32;
1848                 }
1849             } );
1850             ($key_name:ident, Option<u64>) => ( {
1851                 let name = (stringify!($key_name)).replace("_", "-");
1852                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1853                     base.$key_name = Some(s);
1854                 }
1855             } );
1856             ($key_name:ident, MergeFunctions) => ( {
1857                 let name = (stringify!($key_name)).replace("_", "-");
1858                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1859                     match s.parse::<MergeFunctions>() {
1860                         Ok(mergefunc) => base.$key_name = mergefunc,
1861                         _ => return Some(Err(format!("'{}' is not a valid value for \
1862                                                       merge-functions. Use 'disabled', \
1863                                                       'trampolines', or 'aliases'.",
1864                                                       s))),
1865                     }
1866                     Some(Ok(()))
1867                 })).unwrap_or(Ok(()))
1868             } );
1869             ($key_name:ident, RelocModel) => ( {
1870                 let name = (stringify!($key_name)).replace("_", "-");
1871                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1872                     match s.parse::<RelocModel>() {
1873                         Ok(relocation_model) => base.$key_name = relocation_model,
1874                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1875                                                       Run `rustc --print relocation-models` to \
1876                                                       see the list of supported values.", s))),
1877                     }
1878                     Some(Ok(()))
1879                 })).unwrap_or(Ok(()))
1880             } );
1881             ($key_name:ident, CodeModel) => ( {
1882                 let name = (stringify!($key_name)).replace("_", "-");
1883                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1884                     match s.parse::<CodeModel>() {
1885                         Ok(code_model) => base.$key_name = Some(code_model),
1886                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1887                                                       Run `rustc --print code-models` to \
1888                                                       see the list of supported values.", s))),
1889                     }
1890                     Some(Ok(()))
1891                 })).unwrap_or(Ok(()))
1892             } );
1893             ($key_name:ident, TlsModel) => ( {
1894                 let name = (stringify!($key_name)).replace("_", "-");
1895                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1896                     match s.parse::<TlsModel>() {
1897                         Ok(tls_model) => base.$key_name = tls_model,
1898                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1899                                                       Run `rustc --print tls-models` to \
1900                                                       see the list of supported values.", s))),
1901                     }
1902                     Some(Ok(()))
1903                 })).unwrap_or(Ok(()))
1904             } );
1905             ($key_name:ident, PanicStrategy) => ( {
1906                 let name = (stringify!($key_name)).replace("_", "-");
1907                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1908                     match s {
1909                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1910                         "abort" => base.$key_name = PanicStrategy::Abort,
1911                         _ => return Some(Err(format!("'{}' is not a valid value for \
1912                                                       panic-strategy. Use 'unwind' or 'abort'.",
1913                                                      s))),
1914                 }
1915                 Some(Ok(()))
1916             })).unwrap_or(Ok(()))
1917             } );
1918             ($key_name:ident, RelroLevel) => ( {
1919                 let name = (stringify!($key_name)).replace("_", "-");
1920                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1921                     match s.parse::<RelroLevel>() {
1922                         Ok(level) => base.$key_name = level,
1923                         _ => return Some(Err(format!("'{}' is not a valid value for \
1924                                                       relro-level. Use 'full', 'partial, or 'off'.",
1925                                                       s))),
1926                     }
1927                     Some(Ok(()))
1928                 })).unwrap_or(Ok(()))
1929             } );
1930             ($key_name:ident, DebuginfoKind) => ( {
1931                 let name = (stringify!($key_name)).replace("_", "-");
1932                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1933                     match s.parse::<DebuginfoKind>() {
1934                         Ok(level) => base.$key_name = level,
1935                         _ => return Some(Err(
1936                             format!("'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
1937                                   'dwarf-dsym' or 'pdb'.")
1938                         )),
1939                     }
1940                     Some(Ok(()))
1941                 })).unwrap_or(Ok(()))
1942             } );
1943             ($key_name:ident, SplitDebuginfo) => ( {
1944                 let name = (stringify!($key_name)).replace("_", "-");
1945                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1946                     match s.parse::<SplitDebuginfo>() {
1947                         Ok(level) => base.$key_name = level,
1948                         _ => return Some(Err(format!("'{}' is not a valid value for \
1949                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
1950                                                       s))),
1951                     }
1952                     Some(Ok(()))
1953                 })).unwrap_or(Ok(()))
1954             } );
1955             ($key_name:ident, list) => ( {
1956                 let name = (stringify!($key_name)).replace("_", "-");
1957                 if let Some(j) = obj.remove(&name) {
1958                     if let Some(v) = j.as_array() {
1959                         base.$key_name = v.iter()
1960                             .map(|a| a.as_str().unwrap().to_string().into())
1961                             .collect();
1962                     } else {
1963                         incorrect_type.push(name)
1964                     }
1965                 }
1966             } );
1967             ($key_name:ident, opt_list) => ( {
1968                 let name = (stringify!($key_name)).replace("_", "-");
1969                 if let Some(j) = obj.remove(&name) {
1970                     if let Some(v) = j.as_array() {
1971                         base.$key_name = Some(v.iter()
1972                             .map(|a| a.as_str().unwrap().to_string().into())
1973                             .collect());
1974                     } else {
1975                         incorrect_type.push(name)
1976                     }
1977                 }
1978             } );
1979             ($key_name:ident, falliable_list) => ( {
1980                 let name = (stringify!($key_name)).replace("_", "-");
1981                 obj.remove(&name).and_then(|j| {
1982                     if let Some(v) = j.as_array() {
1983                         match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() {
1984                             Ok(l) => { base.$key_name = l },
1985                             // FIXME: `falliable_list` can't re-use the `key!` macro for list
1986                             // elements and the error messages from that macro, so it has a bad
1987                             // generic message instead
1988                             Err(_) => return Some(Err(
1989                                 format!("`{:?}` is not a valid value for `{}`", j, name)
1990                             )),
1991                         }
1992                     } else {
1993                         incorrect_type.push(name)
1994                     }
1995                     Some(Ok(()))
1996                 }).unwrap_or(Ok(()))
1997             } );
1998             ($key_name:ident, optional) => ( {
1999                 let name = (stringify!($key_name)).replace("_", "-");
2000                 if let Some(o) = obj.remove(&name) {
2001                     base.$key_name = o
2002                         .as_str()
2003                         .map(|s| s.to_string().into());
2004                 }
2005             } );
2006             ($key_name:ident, LldFlavor) => ( {
2007                 let name = (stringify!($key_name)).replace("_", "-");
2008                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2009                     if let Some(flavor) = LldFlavor::from_str(&s) {
2010                         base.$key_name = flavor;
2011                     } else {
2012                         return Some(Err(format!(
2013                             "'{}' is not a valid value for lld-flavor. \
2014                              Use 'darwin', 'gnu', 'link' or 'wasm.",
2015                             s)))
2016                     }
2017                     Some(Ok(()))
2018                 })).unwrap_or(Ok(()))
2019             } );
2020             ($key_name:ident, LinkerFlavor) => ( {
2021                 let name = (stringify!($key_name)).replace("_", "-");
2022                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2023                     match LinkerFlavor::from_str(s) {
2024                         Some(linker_flavor) => base.$key_name = linker_flavor,
2025                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
2026                                                       Use {}", s, LinkerFlavor::one_of()))),
2027                     }
2028                     Some(Ok(()))
2029                 })).unwrap_or(Ok(()))
2030             } );
2031             ($key_name:ident, StackProbeType) => ( {
2032                 let name = (stringify!($key_name)).replace("_", "-");
2033                 obj.remove(&name).and_then(|o| match StackProbeType::from_json(&o) {
2034                     Ok(v) => {
2035                         base.$key_name = v;
2036                         Some(Ok(()))
2037                     },
2038                     Err(s) => Some(Err(
2039                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
2040                     )),
2041                 }).unwrap_or(Ok(()))
2042             } );
2043             ($key_name:ident, SanitizerSet) => ( {
2044                 let name = (stringify!($key_name)).replace("_", "-");
2045                 if let Some(o) = obj.remove(&name) {
2046                     if let Some(a) = o.as_array() {
2047                         for s in a {
2048                             base.$key_name |= match s.as_str() {
2049                                 Some("address") => SanitizerSet::ADDRESS,
2050                                 Some("cfi") => SanitizerSet::CFI,
2051                                 Some("leak") => SanitizerSet::LEAK,
2052                                 Some("memory") => SanitizerSet::MEMORY,
2053                                 Some("memtag") => SanitizerSet::MEMTAG,
2054                                 Some("shadow-call-stack") => SanitizerSet::SHADOWCALLSTACK,
2055                                 Some("thread") => SanitizerSet::THREAD,
2056                                 Some("hwaddress") => SanitizerSet::HWADDRESS,
2057                                 Some(s) => return Err(format!("unknown sanitizer {}", s)),
2058                                 _ => return Err(format!("not a string: {:?}", s)),
2059                             };
2060                         }
2061                     } else {
2062                         incorrect_type.push(name)
2063                     }
2064                 }
2065                 Ok::<(), String>(())
2066             } );
2067
2068             ($key_name:ident = $json_name:expr, link_self_contained) => ( {
2069                 let name = $json_name;
2070                 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2071                     match s.parse::<LinkSelfContainedDefault>() {
2072                         Ok(lsc_default) => base.$key_name = lsc_default,
2073                         _ => return Some(Err(format!("'{}' is not a valid `-Clink-self-contained` default. \
2074                                                       Use 'false', 'true', 'musl' or 'mingw'", s))),
2075                     }
2076                     Some(Ok(()))
2077                 })).unwrap_or(Ok(()))
2078             } );
2079             ($key_name:ident = $json_name:expr, link_objects) => ( {
2080                 let name = $json_name;
2081                 if let Some(val) = obj.remove(name) {
2082                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2083                         JSON object with fields per CRT object kind.", name))?;
2084                     let mut args = CrtObjects::new();
2085                     for (k, v) in obj {
2086                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
2087                             format!("{}: '{}' is not a valid value for CRT object kind. \
2088                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
2089                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
2090                         })?;
2091
2092                         let v = v.as_array().ok_or_else(||
2093                             format!("{}.{}: expected a JSON array", name, k)
2094                         )?.iter().enumerate()
2095                             .map(|(i,s)| {
2096                                 let s = s.as_str().ok_or_else(||
2097                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2098                                 Ok(s.to_string().into())
2099                             })
2100                             .collect::<Result<Vec<_>, String>>()?;
2101
2102                         args.insert(kind, v);
2103                     }
2104                     base.$key_name = args;
2105                 }
2106             } );
2107             ($key_name:ident, link_args) => ( {
2108                 let name = (stringify!($key_name)).replace("_", "-");
2109                 if let Some(val) = obj.remove(&name) {
2110                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2111                         JSON object with fields per linker-flavor.", name))?;
2112                     let mut args = LinkArgs::new();
2113                     for (k, v) in obj {
2114                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
2115                             format!("{}: '{}' is not a valid value for linker-flavor. \
2116                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
2117                         })?;
2118
2119                         let v = v.as_array().ok_or_else(||
2120                             format!("{}.{}: expected a JSON array", name, k)
2121                         )?.iter().enumerate()
2122                             .map(|(i,s)| {
2123                                 let s = s.as_str().ok_or_else(||
2124                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2125                                 Ok(s.to_string().into())
2126                             })
2127                             .collect::<Result<Vec<_>, String>>()?;
2128
2129                         args.insert(flavor, v);
2130                     }
2131                     base.$key_name = args;
2132                 }
2133             } );
2134             ($key_name:ident, env) => ( {
2135                 let name = (stringify!($key_name)).replace("_", "-");
2136                 if let Some(o) = obj.remove(&name) {
2137                     if let Some(a) = o.as_array() {
2138                         for o in a {
2139                             if let Some(s) = o.as_str() {
2140                                 let p = s.split('=').collect::<Vec<_>>();
2141                                 if p.len() == 2 {
2142                                     let k = p[0].to_string();
2143                                     let v = p[1].to_string();
2144                                     base.$key_name.to_mut().push((k.into(), v.into()));
2145                                 }
2146                             }
2147                         }
2148                     } else {
2149                         incorrect_type.push(name)
2150                     }
2151                 }
2152             } );
2153             ($key_name:ident, Option<Abi>) => ( {
2154                 let name = (stringify!($key_name)).replace("_", "-");
2155                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2156                     match lookup_abi(s) {
2157                         Some(abi) => base.$key_name = Some(abi),
2158                         _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2159                     }
2160                     Some(Ok(()))
2161                 })).unwrap_or(Ok(()))
2162             } );
2163             ($key_name:ident, TargetFamilies) => ( {
2164                 if let Some(value) = obj.remove("target-family") {
2165                     if let Some(v) = value.as_array() {
2166                         base.$key_name = v.iter()
2167                             .map(|a| a.as_str().unwrap().to_string().into())
2168                             .collect();
2169                     } else if let Some(v) = value.as_str() {
2170                         base.$key_name = vec![v.to_string().into()].into();
2171                     }
2172                 }
2173             } );
2174         }
2175
2176         if let Some(j) = obj.remove("target-endian") {
2177             if let Some(s) = j.as_str() {
2178                 base.endian = s.parse()?;
2179             } else {
2180                 incorrect_type.push("target-endian".into())
2181             }
2182         }
2183
2184         if let Some(fp) = obj.remove("frame-pointer") {
2185             if let Some(s) = fp.as_str() {
2186                 base.frame_pointer = s
2187                     .parse()
2188                     .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2189             } else {
2190                 incorrect_type.push("frame-pointer".into())
2191             }
2192         }
2193
2194         key!(is_builtin, bool);
2195         key!(c_int_width = "target-c-int-width");
2196         key!(os);
2197         key!(env);
2198         key!(abi);
2199         key!(vendor);
2200         key!(linker_flavor, LinkerFlavor)?;
2201         key!(linker, optional);
2202         key!(lld_flavor, LldFlavor)?;
2203         key!(pre_link_objects = "pre-link-objects", link_objects);
2204         key!(post_link_objects = "post-link-objects", link_objects);
2205         key!(pre_link_objects_self_contained = "pre-link-objects-fallback", link_objects);
2206         key!(post_link_objects_self_contained = "post-link-objects-fallback", link_objects);
2207         key!(link_self_contained = "crt-objects-fallback", link_self_contained)?;
2208         key!(pre_link_args, link_args);
2209         key!(late_link_args, link_args);
2210         key!(late_link_args_dynamic, link_args);
2211         key!(late_link_args_static, link_args);
2212         key!(post_link_args, link_args);
2213         key!(link_script, optional);
2214         key!(link_env, env);
2215         key!(link_env_remove, list);
2216         key!(asm_args, list);
2217         key!(cpu);
2218         key!(features);
2219         key!(dynamic_linking, bool);
2220         key!(only_cdylib, bool);
2221         key!(executables, bool);
2222         key!(relocation_model, RelocModel)?;
2223         key!(code_model, CodeModel)?;
2224         key!(tls_model, TlsModel)?;
2225         key!(disable_redzone, bool);
2226         key!(function_sections, bool);
2227         key!(dll_prefix);
2228         key!(dll_suffix);
2229         key!(exe_suffix);
2230         key!(staticlib_prefix);
2231         key!(staticlib_suffix);
2232         key!(families, TargetFamilies);
2233         key!(abi_return_struct_as_int, bool);
2234         key!(is_like_osx, bool);
2235         key!(is_like_solaris, bool);
2236         key!(is_like_windows, bool);
2237         key!(is_like_msvc, bool);
2238         key!(is_like_wasm, bool);
2239         key!(default_dwarf_version, u32);
2240         key!(linker_is_gnu, bool);
2241         key!(allows_weak_linkage, bool);
2242         key!(has_rpath, bool);
2243         key!(no_default_libraries, bool);
2244         key!(position_independent_executables, bool);
2245         key!(static_position_independent_executables, bool);
2246         key!(needs_plt, bool);
2247         key!(relro_level, RelroLevel)?;
2248         key!(archive_format);
2249         key!(allow_asm, bool);
2250         key!(main_needs_argc_argv, bool);
2251         key!(has_thread_local, bool);
2252         key!(obj_is_bitcode, bool);
2253         key!(forces_embed_bitcode, bool);
2254         key!(bitcode_llvm_cmdline);
2255         key!(max_atomic_width, Option<u64>);
2256         key!(min_atomic_width, Option<u64>);
2257         key!(atomic_cas, bool);
2258         key!(panic_strategy, PanicStrategy)?;
2259         key!(crt_static_allows_dylibs, bool);
2260         key!(crt_static_default, bool);
2261         key!(crt_static_respected, bool);
2262         key!(stack_probes, StackProbeType)?;
2263         key!(min_global_align, Option<u64>);
2264         key!(default_codegen_units, Option<u64>);
2265         key!(trap_unreachable, bool);
2266         key!(requires_lto, bool);
2267         key!(singlethread, bool);
2268         key!(no_builtins, bool);
2269         key!(default_hidden_visibility, bool);
2270         key!(emit_debug_gdb_scripts, bool);
2271         key!(requires_uwtable, bool);
2272         key!(default_uwtable, bool);
2273         key!(simd_types_indirect, bool);
2274         key!(limit_rdylib_exports, bool);
2275         key!(override_export_symbols, opt_list);
2276         key!(merge_functions, MergeFunctions)?;
2277         key!(mcount = "target-mcount");
2278         key!(llvm_abiname);
2279         key!(relax_elf_relocations, bool);
2280         key!(llvm_args, list);
2281         key!(use_ctors_section, bool);
2282         key!(eh_frame_header, bool);
2283         key!(has_thumb_interworking, bool);
2284         key!(debuginfo_kind, DebuginfoKind)?;
2285         key!(split_debuginfo, SplitDebuginfo)?;
2286         key!(supported_split_debuginfo, falliable_list)?;
2287         key!(supported_sanitizers, SanitizerSet)?;
2288         key!(default_adjusted_cabi, Option<Abi>)?;
2289         key!(c_enum_min_bits, u64);
2290         key!(generate_arange_section, bool);
2291         key!(supports_stack_protector, bool);
2292
2293         if base.is_builtin {
2294             // This can cause unfortunate ICEs later down the line.
2295             return Err("may not set is_builtin for targets not built-in".into());
2296         }
2297         // Each field should have been read using `Json::remove` so any keys remaining are unused.
2298         let remaining_keys = obj.keys();
2299         Ok((
2300             base,
2301             TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2302         ))
2303     }
2304
2305     /// Load a built-in target
2306     pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2307         match *target_triple {
2308             TargetTriple::TargetTriple(ref target_triple) => {
2309                 load_builtin(target_triple).expect("built-in target")
2310             }
2311             TargetTriple::TargetJson { .. } => {
2312                 panic!("built-in targets doens't support target-paths")
2313             }
2314         }
2315     }
2316
2317     /// Search for a JSON file specifying the given target triple.
2318     ///
2319     /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2320     /// sysroot under the target-triple's `rustlib` directory.  Note that it could also just be a
2321     /// bare filename already, so also check for that. If one of the hardcoded targets we know
2322     /// about, just return it directly.
2323     ///
2324     /// The error string could come from any of the APIs called, including filesystem access and
2325     /// JSON decoding.
2326     pub fn search(
2327         target_triple: &TargetTriple,
2328         sysroot: &Path,
2329     ) -> Result<(Target, TargetWarnings), String> {
2330         use std::env;
2331         use std::fs;
2332
2333         fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2334             let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2335             let obj = serde_json::from_str(&contents).map_err(|e| e.to_string())?;
2336             Target::from_json(obj)
2337         }
2338
2339         match *target_triple {
2340             TargetTriple::TargetTriple(ref target_triple) => {
2341                 // check if triple is in list of built-in targets
2342                 if let Some(t) = load_builtin(target_triple) {
2343                     return Ok((t, TargetWarnings::empty()));
2344                 }
2345
2346                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2347                 let path = {
2348                     let mut target = target_triple.to_string();
2349                     target.push_str(".json");
2350                     PathBuf::from(target)
2351                 };
2352
2353                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2354
2355                 for dir in env::split_paths(&target_path) {
2356                     let p = dir.join(&path);
2357                     if p.is_file() {
2358                         return load_file(&p);
2359                     }
2360                 }
2361
2362                 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2363                 // as a fallback.
2364                 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2365                 let p = PathBuf::from_iter([
2366                     Path::new(sysroot),
2367                     Path::new(&rustlib_path),
2368                     Path::new("target.json"),
2369                 ]);
2370                 if p.is_file() {
2371                     return load_file(&p);
2372                 }
2373
2374                 Err(format!("Could not find specification for target {:?}", target_triple))
2375             }
2376             TargetTriple::TargetJson { ref contents, .. } => {
2377                 let obj = serde_json::from_str(contents).map_err(|e| e.to_string())?;
2378                 Target::from_json(obj)
2379             }
2380         }
2381     }
2382 }
2383
2384 impl ToJson for Target {
2385     fn to_json(&self) -> Json {
2386         let mut d = serde_json::Map::new();
2387         let default: TargetOptions = Default::default();
2388
2389         macro_rules! target_val {
2390             ($attr:ident) => {{
2391                 let name = (stringify!($attr)).replace("_", "-");
2392                 d.insert(name, self.$attr.to_json());
2393             }};
2394         }
2395
2396         macro_rules! target_option_val {
2397             ($attr:ident) => {{
2398                 let name = (stringify!($attr)).replace("_", "-");
2399                 if default.$attr != self.$attr {
2400                     d.insert(name, self.$attr.to_json());
2401                 }
2402             }};
2403             ($attr:ident, $key_name:expr) => {{
2404                 let name = $key_name;
2405                 if default.$attr != self.$attr {
2406                     d.insert(name.into(), self.$attr.to_json());
2407                 }
2408             }};
2409             (link_args - $attr:ident) => {{
2410                 let name = (stringify!($attr)).replace("_", "-");
2411                 if default.$attr != self.$attr {
2412                     let obj = self
2413                         .$attr
2414                         .iter()
2415                         .map(|(k, v)| (k.desc().to_string(), v.clone()))
2416                         .collect::<BTreeMap<_, _>>();
2417                     d.insert(name, obj.to_json());
2418                 }
2419             }};
2420             (env - $attr:ident) => {{
2421                 let name = (stringify!($attr)).replace("_", "-");
2422                 if default.$attr != self.$attr {
2423                     let obj = self
2424                         .$attr
2425                         .iter()
2426                         .map(|&(ref k, ref v)| format!("{k}={v}"))
2427                         .collect::<Vec<_>>();
2428                     d.insert(name, obj.to_json());
2429                 }
2430             }};
2431         }
2432
2433         target_val!(llvm_target);
2434         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2435         target_val!(arch);
2436         target_val!(data_layout);
2437
2438         target_option_val!(is_builtin);
2439         target_option_val!(endian, "target-endian");
2440         target_option_val!(c_int_width, "target-c-int-width");
2441         target_option_val!(os);
2442         target_option_val!(env);
2443         target_option_val!(abi);
2444         target_option_val!(vendor);
2445         target_option_val!(linker_flavor);
2446         target_option_val!(linker);
2447         target_option_val!(lld_flavor);
2448         target_option_val!(pre_link_objects);
2449         target_option_val!(post_link_objects);
2450         target_option_val!(pre_link_objects_self_contained, "pre-link-objects-fallback");
2451         target_option_val!(post_link_objects_self_contained, "post-link-objects-fallback");
2452         target_option_val!(link_self_contained, "crt-objects-fallback");
2453         target_option_val!(link_args - pre_link_args);
2454         target_option_val!(link_args - late_link_args);
2455         target_option_val!(link_args - late_link_args_dynamic);
2456         target_option_val!(link_args - late_link_args_static);
2457         target_option_val!(link_args - post_link_args);
2458         target_option_val!(link_script);
2459         target_option_val!(env - link_env);
2460         target_option_val!(link_env_remove);
2461         target_option_val!(asm_args);
2462         target_option_val!(cpu);
2463         target_option_val!(features);
2464         target_option_val!(dynamic_linking);
2465         target_option_val!(only_cdylib);
2466         target_option_val!(executables);
2467         target_option_val!(relocation_model);
2468         target_option_val!(code_model);
2469         target_option_val!(tls_model);
2470         target_option_val!(disable_redzone);
2471         target_option_val!(frame_pointer);
2472         target_option_val!(function_sections);
2473         target_option_val!(dll_prefix);
2474         target_option_val!(dll_suffix);
2475         target_option_val!(exe_suffix);
2476         target_option_val!(staticlib_prefix);
2477         target_option_val!(staticlib_suffix);
2478         target_option_val!(families, "target-family");
2479         target_option_val!(abi_return_struct_as_int);
2480         target_option_val!(is_like_osx);
2481         target_option_val!(is_like_solaris);
2482         target_option_val!(is_like_windows);
2483         target_option_val!(is_like_msvc);
2484         target_option_val!(is_like_wasm);
2485         target_option_val!(default_dwarf_version);
2486         target_option_val!(linker_is_gnu);
2487         target_option_val!(allows_weak_linkage);
2488         target_option_val!(has_rpath);
2489         target_option_val!(no_default_libraries);
2490         target_option_val!(position_independent_executables);
2491         target_option_val!(static_position_independent_executables);
2492         target_option_val!(needs_plt);
2493         target_option_val!(relro_level);
2494         target_option_val!(archive_format);
2495         target_option_val!(allow_asm);
2496         target_option_val!(main_needs_argc_argv);
2497         target_option_val!(has_thread_local);
2498         target_option_val!(obj_is_bitcode);
2499         target_option_val!(forces_embed_bitcode);
2500         target_option_val!(bitcode_llvm_cmdline);
2501         target_option_val!(min_atomic_width);
2502         target_option_val!(max_atomic_width);
2503         target_option_val!(atomic_cas);
2504         target_option_val!(panic_strategy);
2505         target_option_val!(crt_static_allows_dylibs);
2506         target_option_val!(crt_static_default);
2507         target_option_val!(crt_static_respected);
2508         target_option_val!(stack_probes);
2509         target_option_val!(min_global_align);
2510         target_option_val!(default_codegen_units);
2511         target_option_val!(trap_unreachable);
2512         target_option_val!(requires_lto);
2513         target_option_val!(singlethread);
2514         target_option_val!(no_builtins);
2515         target_option_val!(default_hidden_visibility);
2516         target_option_val!(emit_debug_gdb_scripts);
2517         target_option_val!(requires_uwtable);
2518         target_option_val!(default_uwtable);
2519         target_option_val!(simd_types_indirect);
2520         target_option_val!(limit_rdylib_exports);
2521         target_option_val!(override_export_symbols);
2522         target_option_val!(merge_functions);
2523         target_option_val!(mcount, "target-mcount");
2524         target_option_val!(llvm_abiname);
2525         target_option_val!(relax_elf_relocations);
2526         target_option_val!(llvm_args);
2527         target_option_val!(use_ctors_section);
2528         target_option_val!(eh_frame_header);
2529         target_option_val!(has_thumb_interworking);
2530         target_option_val!(debuginfo_kind);
2531         target_option_val!(split_debuginfo);
2532         target_option_val!(supported_split_debuginfo);
2533         target_option_val!(supported_sanitizers);
2534         target_option_val!(c_enum_min_bits);
2535         target_option_val!(generate_arange_section);
2536         target_option_val!(supports_stack_protector);
2537
2538         if let Some(abi) = self.default_adjusted_cabi {
2539             d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2540         }
2541
2542         Json::Object(d)
2543     }
2544 }
2545
2546 /// Either a target triple string or a path to a JSON file.
2547 #[derive(Clone, Debug)]
2548 pub enum TargetTriple {
2549     TargetTriple(String),
2550     TargetJson {
2551         /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
2552         /// inconsistencies as it is discarded during serialization.
2553         path_for_rustdoc: PathBuf,
2554         triple: String,
2555         contents: String,
2556     },
2557 }
2558
2559 // Use a manual implementation to ignore the path field
2560 impl PartialEq for TargetTriple {
2561     fn eq(&self, other: &Self) -> bool {
2562         match (self, other) {
2563             (Self::TargetTriple(l0), Self::TargetTriple(r0)) => l0 == r0,
2564             (
2565                 Self::TargetJson { path_for_rustdoc: _, triple: l_triple, contents: l_contents },
2566                 Self::TargetJson { path_for_rustdoc: _, triple: r_triple, contents: r_contents },
2567             ) => l_triple == r_triple && l_contents == r_contents,
2568             _ => false,
2569         }
2570     }
2571 }
2572
2573 // Use a manual implementation to ignore the path field
2574 impl Hash for TargetTriple {
2575     fn hash<H: Hasher>(&self, state: &mut H) -> () {
2576         match self {
2577             TargetTriple::TargetTriple(triple) => {
2578                 0u8.hash(state);
2579                 triple.hash(state)
2580             }
2581             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => {
2582                 1u8.hash(state);
2583                 triple.hash(state);
2584                 contents.hash(state)
2585             }
2586         }
2587     }
2588 }
2589
2590 // Use a manual implementation to prevent encoding the target json file path in the crate metadata
2591 impl<S: Encoder> Encodable<S> for TargetTriple {
2592     fn encode(&self, s: &mut S) {
2593         match self {
2594             TargetTriple::TargetTriple(triple) => s.emit_enum_variant(0, |s| s.emit_str(triple)),
2595             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => s
2596                 .emit_enum_variant(1, |s| {
2597                     s.emit_str(triple);
2598                     s.emit_str(contents)
2599                 }),
2600         }
2601     }
2602 }
2603
2604 impl<D: Decoder> Decodable<D> for TargetTriple {
2605     fn decode(d: &mut D) -> Self {
2606         match d.read_usize() {
2607             0 => TargetTriple::TargetTriple(d.read_str().to_owned()),
2608             1 => TargetTriple::TargetJson {
2609                 path_for_rustdoc: PathBuf::new(),
2610                 triple: d.read_str().to_owned(),
2611                 contents: d.read_str().to_owned(),
2612             },
2613             _ => {
2614                 panic!("invalid enum variant tag while decoding `TargetTriple`, expected 0..2");
2615             }
2616         }
2617     }
2618 }
2619
2620 impl TargetTriple {
2621     /// Creates a target triple from the passed target triple string.
2622     pub fn from_triple(triple: &str) -> Self {
2623         TargetTriple::TargetTriple(triple.into())
2624     }
2625
2626     /// Creates a target triple from the passed target path.
2627     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2628         let canonicalized_path = path.canonicalize()?;
2629         let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
2630             io::Error::new(
2631                 io::ErrorKind::InvalidInput,
2632                 format!("target path {:?} is not a valid file: {}", canonicalized_path, err),
2633             )
2634         })?;
2635         let triple = canonicalized_path
2636             .file_stem()
2637             .expect("target path must not be empty")
2638             .to_str()
2639             .expect("target path must be valid unicode")
2640             .to_owned();
2641         Ok(TargetTriple::TargetJson { path_for_rustdoc: canonicalized_path, triple, contents })
2642     }
2643
2644     /// Returns a string triple for this target.
2645     ///
2646     /// If this target is a path, the file name (without extension) is returned.
2647     pub fn triple(&self) -> &str {
2648         match *self {
2649             TargetTriple::TargetTriple(ref triple)
2650             | TargetTriple::TargetJson { ref triple, .. } => triple,
2651         }
2652     }
2653
2654     /// Returns an extended string triple for this target.
2655     ///
2656     /// If this target is a path, a hash of the path is appended to the triple returned
2657     /// by `triple()`.
2658     pub fn debug_triple(&self) -> String {
2659         use std::collections::hash_map::DefaultHasher;
2660
2661         match self {
2662             TargetTriple::TargetTriple(triple) => triple.to_owned(),
2663             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents: content } => {
2664                 let mut hasher = DefaultHasher::new();
2665                 content.hash(&mut hasher);
2666                 let hash = hasher.finish();
2667                 format!("{}-{}", triple, hash)
2668             }
2669         }
2670     }
2671 }
2672
2673 impl fmt::Display for TargetTriple {
2674     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2675         write!(f, "{}", self.debug_triple())
2676     }
2677 }