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