]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Rollup merge of #93057 - frengor:iter_collect_into, r=m-ou-se
[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::collections::BTreeMap;
44 use std::convert::TryFrom;
45 use std::iter::FromIterator;
46 use std::ops::{Deref, DerefMut};
47 use std::path::{Path, PathBuf};
48 use std::str::FromStr;
49 use std::{fmt, io};
50
51 use rustc_macros::HashStable_Generic;
52
53 pub mod abi;
54 pub mod crt_objects;
55
56 mod android_base;
57 mod apple_base;
58 mod apple_sdk_base;
59 mod avr_gnu_base;
60 mod bpf_base;
61 mod dragonfly_base;
62 mod freebsd_base;
63 mod fuchsia_base;
64 mod haiku_base;
65 mod hermit_base;
66 mod hermit_kernel_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<String>>;
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     ("aarch64-unknown-none-hermitkernel", aarch64_unknown_none_hermitkernel),
975     ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
976
977     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
978     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
979     ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
980     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
981     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
982     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
983     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
984     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
985     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
986     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
987
988     ("aarch64-unknown-none", aarch64_unknown_none),
989     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
990
991     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
992
993     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
994     ("i686-unknown-uefi", i686_unknown_uefi),
995     ("aarch64-unknown-uefi", aarch64_unknown_uefi),
996
997     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
998
999     ("i686-wrs-vxworks", i686_wrs_vxworks),
1000     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1001     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1002     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1003     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1004     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1005     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1006
1007     ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1008     ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1009     ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1010
1011     ("mipsel-sony-psp", mipsel_sony_psp),
1012     ("mipsel-unknown-none", mipsel_unknown_none),
1013     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1014
1015     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1016     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1017     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1018
1019     ("bpfeb-unknown-none", bpfeb_unknown_none),
1020     ("bpfel-unknown-none", bpfel_unknown_none),
1021
1022     ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1023
1024     ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1025     ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1026
1027     ("x86_64-unknown-none", x86_64_unknown_none),
1028
1029     ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1030 }
1031
1032 /// Warnings encountered when parsing the target `json`.
1033 ///
1034 /// Includes fields that weren't recognized and fields that don't have the expected type.
1035 #[derive(Debug, PartialEq)]
1036 pub struct TargetWarnings {
1037     unused_fields: Vec<String>,
1038     incorrect_type: Vec<String>,
1039 }
1040
1041 impl TargetWarnings {
1042     pub fn empty() -> Self {
1043         Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1044     }
1045
1046     pub fn warning_messages(&self) -> Vec<String> {
1047         let mut warnings = vec![];
1048         if !self.unused_fields.is_empty() {
1049             warnings.push(format!(
1050                 "target json file contains unused fields: {}",
1051                 self.unused_fields.join(", ")
1052             ));
1053         }
1054         if !self.incorrect_type.is_empty() {
1055             warnings.push(format!(
1056                 "target json file contains fields whose value doesn't have the correct json type: {}",
1057                 self.incorrect_type.join(", ")
1058             ));
1059         }
1060         warnings
1061     }
1062 }
1063
1064 /// Everything `rustc` knows about how to compile for a specific target.
1065 ///
1066 /// Every field here must be specified, and has no default value.
1067 #[derive(PartialEq, Clone, Debug)]
1068 pub struct Target {
1069     /// Target triple to pass to LLVM.
1070     pub llvm_target: String,
1071     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1072     pub pointer_width: u32,
1073     /// Architecture to use for ABI considerations. Valid options include: "x86",
1074     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1075     pub arch: String,
1076     /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1077     pub data_layout: String,
1078     /// Optional settings with defaults.
1079     pub options: TargetOptions,
1080 }
1081
1082 pub trait HasTargetSpec {
1083     fn target_spec(&self) -> &Target;
1084 }
1085
1086 impl HasTargetSpec for Target {
1087     #[inline]
1088     fn target_spec(&self) -> &Target {
1089         self
1090     }
1091 }
1092
1093 /// Optional aspects of a target specification.
1094 ///
1095 /// This has an implementation of `Default`, see each field for what the default is. In general,
1096 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1097 ///
1098 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1099 /// construction, all its fields logically belong to `Target` and available from `Target`
1100 /// through `Deref` impls.
1101 #[derive(PartialEq, Clone, Debug)]
1102 pub struct TargetOptions {
1103     /// Whether the target is built-in or loaded from a custom target specification.
1104     pub is_builtin: bool,
1105
1106     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1107     pub endian: Endian,
1108     /// Width of c_int type. Defaults to "32".
1109     pub c_int_width: String,
1110     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1111     /// "none" implies a bare metal target without `std` library.
1112     /// A couple of targets having `std` also use "unknown" as an `os` value,
1113     /// but they are exceptions.
1114     pub os: String,
1115     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1116     pub env: String,
1117     /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1118     /// or `"eabihf"`. Defaults to "".
1119     pub abi: String,
1120     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1121     pub vendor: String,
1122     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1123     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1124     pub linker_flavor: LinkerFlavor,
1125
1126     /// Linker to invoke
1127     pub linker: Option<String>,
1128
1129     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1130     /// without clarifying its flavor in any way.
1131     pub lld_flavor: LldFlavor,
1132
1133     /// Linker arguments that are passed *before* any user-defined libraries.
1134     pub pre_link_args: LinkArgs,
1135     /// Objects to link before and after all other object code.
1136     pub pre_link_objects: CrtObjects,
1137     pub post_link_objects: CrtObjects,
1138     /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
1139     /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
1140     /// See `crt_objects.rs` for some more detailed documentation.
1141     pub pre_link_objects_fallback: CrtObjects,
1142     pub post_link_objects_fallback: CrtObjects,
1143     /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
1144     pub crt_objects_fallback: Option<CrtObjectsFallback>,
1145
1146     /// Linker arguments that are unconditionally passed after any
1147     /// user-defined but before post-link objects. Standard platform
1148     /// libraries that should be always be linked to, usually go here.
1149     pub late_link_args: LinkArgs,
1150     /// Linker arguments used in addition to `late_link_args` if at least one
1151     /// Rust dependency is dynamically linked.
1152     pub late_link_args_dynamic: LinkArgs,
1153     /// Linker arguments used in addition to `late_link_args` if aall Rust
1154     /// dependencies are statically linked.
1155     pub late_link_args_static: LinkArgs,
1156     /// Linker arguments that are unconditionally passed *after* any
1157     /// user-defined libraries.
1158     pub post_link_args: LinkArgs,
1159     /// Optional link script applied to `dylib` and `executable` crate types.
1160     /// This is a string containing the script, not a path. Can only be applied
1161     /// to linkers where `linker_is_gnu` is true.
1162     pub link_script: Option<String>,
1163
1164     /// Environment variables to be set for the linker invocation.
1165     pub link_env: Vec<(String, String)>,
1166     /// Environment variables to be removed for the linker invocation.
1167     pub link_env_remove: Vec<String>,
1168
1169     /// Extra arguments to pass to the external assembler (when used)
1170     pub asm_args: Vec<String>,
1171
1172     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1173     /// to "generic".
1174     pub cpu: String,
1175     /// Default target features to pass to LLVM. These features will *always* be
1176     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1177     /// -mattr=$features`.
1178     pub features: String,
1179     /// Whether dynamic linking is available on this target. Defaults to false.
1180     pub dynamic_linking: bool,
1181     /// If dynamic linking is available, whether only cdylibs are supported.
1182     pub only_cdylib: bool,
1183     /// Whether executables are available on this target. iOS, for example, only allows static
1184     /// libraries. Defaults to false.
1185     pub executables: bool,
1186     /// Relocation model to use in object file. Corresponds to `llc
1187     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1188     pub relocation_model: RelocModel,
1189     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1190     /// Defaults to `None` which means "inherited from the base LLVM target".
1191     pub code_model: Option<CodeModel>,
1192     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1193     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1194     pub tls_model: TlsModel,
1195     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1196     pub disable_redzone: bool,
1197     /// Frame pointer mode for this target. Defaults to `MayOmit`.
1198     pub frame_pointer: FramePointer,
1199     /// Emit each function in its own section. Defaults to true.
1200     pub function_sections: bool,
1201     /// String to prepend to the name of every dynamic library. Defaults to "lib".
1202     pub dll_prefix: String,
1203     /// String to append to the name of every dynamic library. Defaults to ".so".
1204     pub dll_suffix: String,
1205     /// String to append to the name of every executable.
1206     pub exe_suffix: String,
1207     /// String to prepend to the name of every static library. Defaults to "lib".
1208     pub staticlib_prefix: String,
1209     /// String to append to the name of every static library. Defaults to ".a".
1210     pub staticlib_suffix: String,
1211     /// Values of the `target_family` cfg set for this target.
1212     ///
1213     /// Common options are: "unix", "windows". Defaults to no families.
1214     ///
1215     /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1216     pub families: Vec<String>,
1217     /// Whether the target toolchain's ABI supports returning small structs as an integer.
1218     pub abi_return_struct_as_int: bool,
1219     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1220     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1221     pub is_like_osx: bool,
1222     /// Whether the target toolchain is like Solaris's.
1223     /// Only useful for compiling against Illumos/Solaris,
1224     /// as they have a different set of linker flags. Defaults to false.
1225     pub is_like_solaris: bool,
1226     /// Whether the target is like Windows.
1227     /// This is a combination of several more specific properties represented as a single flag:
1228     ///   - The target uses a Windows ABI,
1229     ///   - uses PE/COFF as a format for object code,
1230     ///   - uses Windows-style dllexport/dllimport for shared libraries,
1231     ///   - uses import libraries and .def files for symbol exports,
1232     ///   - executables support setting a subsystem.
1233     pub is_like_windows: bool,
1234     /// Whether the target is like MSVC.
1235     /// This is a combination of several more specific properties represented as a single flag:
1236     ///   - The target has all the properties from `is_like_windows`
1237     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
1238     ///   - has some MSVC-specific Windows ABI properties,
1239     ///   - uses a link.exe-like linker,
1240     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
1241     ///   - uses SEH-based unwinding,
1242     ///   - supports control flow guard mechanism.
1243     pub is_like_msvc: bool,
1244     /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1245     /// Emscripten toolchain.
1246     /// Defaults to false.
1247     pub is_like_emscripten: bool,
1248     /// Whether the target toolchain is like Fuchsia's.
1249     pub is_like_fuchsia: bool,
1250     /// Whether a target toolchain is like WASM.
1251     pub is_like_wasm: bool,
1252     /// Version of DWARF to use if not using the default.
1253     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1254     pub dwarf_version: Option<u32>,
1255     /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1256     pub linker_is_gnu: bool,
1257     /// The MinGW toolchain has a known issue that prevents it from correctly
1258     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1259     /// symbol needs its own COMDAT section, weak linkage implies a large
1260     /// number sections that easily exceeds the given limit for larger
1261     /// codebases. Consequently we want a way to disallow weak linkage on some
1262     /// platforms.
1263     pub allows_weak_linkage: bool,
1264     /// Whether the linker support rpaths or not. Defaults to false.
1265     pub has_rpath: bool,
1266     /// Whether to disable linking to the default libraries, typically corresponds
1267     /// to `-nodefaultlibs`. Defaults to true.
1268     pub no_default_libraries: bool,
1269     /// Dynamically linked executables can be compiled as position independent
1270     /// if the default relocation model of position independent code is not
1271     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1272     /// the functions in the executable are not randomized and can be used
1273     /// during an exploit of a vulnerability in any code.
1274     pub position_independent_executables: bool,
1275     /// Executables that are both statically linked and position-independent are supported.
1276     pub static_position_independent_executables: bool,
1277     /// Determines if the target always requires using the PLT for indirect
1278     /// library calls or not. This controls the default value of the `-Z plt` flag.
1279     pub needs_plt: bool,
1280     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1281     /// resolve all symbols at startup and marks the GOT read-only before
1282     /// starting the program, preventing overwriting the GOT.
1283     pub relro_level: RelroLevel,
1284     /// Format that archives should be emitted in. This affects whether we use
1285     /// LLVM to assemble an archive or fall back to the system linker, and
1286     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1287     /// the system linker to be used.
1288     pub archive_format: String,
1289     /// Is asm!() allowed? Defaults to true.
1290     pub allow_asm: bool,
1291     /// Whether the runtime startup code requires the `main` function be passed
1292     /// `argc` and `argv` values.
1293     pub main_needs_argc_argv: bool,
1294
1295     /// Flag indicating whether #[thread_local] is available for this target.
1296     pub has_thread_local: bool,
1297     // This is mainly for easy compatibility with emscripten.
1298     // If we give emcc .o files that are actually .bc files it
1299     // will 'just work'.
1300     pub obj_is_bitcode: bool,
1301     /// Whether the target requires that emitted object code includes bitcode.
1302     pub forces_embed_bitcode: bool,
1303     /// Content of the LLVM cmdline section associated with embedded bitcode.
1304     pub bitcode_llvm_cmdline: String,
1305
1306     /// Don't use this field; instead use the `.min_atomic_width()` method.
1307     pub min_atomic_width: Option<u64>,
1308
1309     /// Don't use this field; instead use the `.max_atomic_width()` method.
1310     pub max_atomic_width: Option<u64>,
1311
1312     /// Whether the target supports atomic CAS operations natively
1313     pub atomic_cas: bool,
1314
1315     /// Panic strategy: "unwind" or "abort"
1316     pub panic_strategy: PanicStrategy,
1317
1318     /// Whether or not linking dylibs to a static CRT is allowed.
1319     pub crt_static_allows_dylibs: bool,
1320     /// Whether or not the CRT is statically linked by default.
1321     pub crt_static_default: bool,
1322     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1323     pub crt_static_respected: bool,
1324
1325     /// The implementation of stack probes to use.
1326     pub stack_probes: StackProbeType,
1327
1328     /// The minimum alignment for global symbols.
1329     pub min_global_align: Option<u64>,
1330
1331     /// Default number of codegen units to use in debug mode
1332     pub default_codegen_units: Option<u64>,
1333
1334     /// Whether to generate trap instructions in places where optimization would
1335     /// otherwise produce control flow that falls through into unrelated memory.
1336     pub trap_unreachable: bool,
1337
1338     /// This target requires everything to be compiled with LTO to emit a final
1339     /// executable, aka there is no native linker for this target.
1340     pub requires_lto: bool,
1341
1342     /// This target has no support for threads.
1343     pub singlethread: bool,
1344
1345     /// Whether library functions call lowering/optimization is disabled in LLVM
1346     /// for this target unconditionally.
1347     pub no_builtins: bool,
1348
1349     /// The default visibility for symbols in this target should be "hidden"
1350     /// rather than "default"
1351     pub default_hidden_visibility: bool,
1352
1353     /// Whether a .debug_gdb_scripts section will be added to the output object file
1354     pub emit_debug_gdb_scripts: bool,
1355
1356     /// Whether or not to unconditionally `uwtable` attributes on functions,
1357     /// typically because the platform needs to unwind for things like stack
1358     /// unwinders.
1359     pub requires_uwtable: bool,
1360
1361     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1362     /// is not specified and `uwtable` is not required on this target.
1363     pub default_uwtable: bool,
1364
1365     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1366     /// typically required if a target can be compiled with a mixed set of
1367     /// target features. This is `true` by default, and `false` for targets like
1368     /// wasm32 where the whole program either has simd or not.
1369     pub simd_types_indirect: bool,
1370
1371     /// Pass a list of symbol which should be exported in the dylib to the linker.
1372     pub limit_rdylib_exports: bool,
1373
1374     /// If set, have the linker export exactly these symbols, instead of using
1375     /// the usual logic to figure this out from the crate itself.
1376     pub override_export_symbols: Option<Vec<String>>,
1377
1378     /// Determines how or whether the MergeFunctions LLVM pass should run for
1379     /// this target. Either "disabled", "trampolines", or "aliases".
1380     /// The MergeFunctions pass is generally useful, but some targets may need
1381     /// to opt out. The default is "aliases".
1382     ///
1383     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1384     pub merge_functions: MergeFunctions,
1385
1386     /// Use platform dependent mcount function
1387     pub mcount: String,
1388
1389     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1390     pub llvm_abiname: String,
1391
1392     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1393     pub relax_elf_relocations: bool,
1394
1395     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1396     pub llvm_args: Vec<String>,
1397
1398     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1399     /// to false (uses .init_array).
1400     pub use_ctors_section: bool,
1401
1402     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1403     /// used to locate unwinding information is passed
1404     /// (only has effect if the linker is `ld`-like).
1405     pub eh_frame_header: bool,
1406
1407     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1408     /// thumb and arm interworking.
1409     pub has_thumb_interworking: bool,
1410
1411     /// How to handle split debug information, if at all. Specifying `None` has
1412     /// target-specific meaning.
1413     pub split_debuginfo: SplitDebuginfo,
1414
1415     /// The sanitizers supported by this target
1416     ///
1417     /// Note that the support here is at a codegen level. If the machine code with sanitizer
1418     /// enabled can generated on this target, but the necessary supporting libraries are not
1419     /// distributed with the target, the sanitizer should still appear in this list for the target.
1420     pub supported_sanitizers: SanitizerSet,
1421
1422     /// If present it's a default value to use for adjusting the C ABI.
1423     pub default_adjusted_cabi: Option<Abi>,
1424
1425     /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1426     pub c_enum_min_bits: u64,
1427
1428     /// Whether or not the DWARF `.debug_aranges` section should be generated.
1429     pub generate_arange_section: bool,
1430
1431     /// Whether the target supports stack canary checks. `true` by default,
1432     /// since this is most common among tier 1 and tier 2 targets.
1433     pub supports_stack_protector: bool,
1434 }
1435
1436 impl Default for TargetOptions {
1437     /// Creates a set of "sane defaults" for any target. This is still
1438     /// incomplete, and if used for compilation, will certainly not work.
1439     fn default() -> TargetOptions {
1440         TargetOptions {
1441             is_builtin: false,
1442             endian: Endian::Little,
1443             c_int_width: "32".to_string(),
1444             os: "none".to_string(),
1445             env: String::new(),
1446             abi: String::new(),
1447             vendor: "unknown".to_string(),
1448             linker_flavor: LinkerFlavor::Gcc,
1449             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1450             lld_flavor: LldFlavor::Ld,
1451             pre_link_args: LinkArgs::new(),
1452             post_link_args: LinkArgs::new(),
1453             link_script: None,
1454             asm_args: Vec::new(),
1455             cpu: "generic".to_string(),
1456             features: String::new(),
1457             dynamic_linking: false,
1458             only_cdylib: false,
1459             executables: false,
1460             relocation_model: RelocModel::Pic,
1461             code_model: None,
1462             tls_model: TlsModel::GeneralDynamic,
1463             disable_redzone: false,
1464             frame_pointer: FramePointer::MayOmit,
1465             function_sections: true,
1466             dll_prefix: "lib".to_string(),
1467             dll_suffix: ".so".to_string(),
1468             exe_suffix: String::new(),
1469             staticlib_prefix: "lib".to_string(),
1470             staticlib_suffix: ".a".to_string(),
1471             families: Vec::new(),
1472             abi_return_struct_as_int: false,
1473             is_like_osx: false,
1474             is_like_solaris: false,
1475             is_like_windows: false,
1476             is_like_emscripten: false,
1477             is_like_msvc: false,
1478             is_like_fuchsia: false,
1479             is_like_wasm: false,
1480             dwarf_version: None,
1481             linker_is_gnu: true,
1482             allows_weak_linkage: true,
1483             has_rpath: false,
1484             no_default_libraries: true,
1485             position_independent_executables: false,
1486             static_position_independent_executables: false,
1487             needs_plt: false,
1488             relro_level: RelroLevel::None,
1489             pre_link_objects: Default::default(),
1490             post_link_objects: Default::default(),
1491             pre_link_objects_fallback: Default::default(),
1492             post_link_objects_fallback: Default::default(),
1493             crt_objects_fallback: None,
1494             late_link_args: LinkArgs::new(),
1495             late_link_args_dynamic: LinkArgs::new(),
1496             late_link_args_static: LinkArgs::new(),
1497             link_env: Vec::new(),
1498             link_env_remove: Vec::new(),
1499             archive_format: "gnu".to_string(),
1500             main_needs_argc_argv: true,
1501             allow_asm: true,
1502             has_thread_local: false,
1503             obj_is_bitcode: false,
1504             forces_embed_bitcode: false,
1505             bitcode_llvm_cmdline: String::new(),
1506             min_atomic_width: None,
1507             max_atomic_width: None,
1508             atomic_cas: true,
1509             panic_strategy: PanicStrategy::Unwind,
1510             crt_static_allows_dylibs: false,
1511             crt_static_default: false,
1512             crt_static_respected: false,
1513             stack_probes: StackProbeType::None,
1514             min_global_align: None,
1515             default_codegen_units: None,
1516             trap_unreachable: true,
1517             requires_lto: false,
1518             singlethread: false,
1519             no_builtins: false,
1520             default_hidden_visibility: false,
1521             emit_debug_gdb_scripts: true,
1522             requires_uwtable: false,
1523             default_uwtable: false,
1524             simd_types_indirect: true,
1525             limit_rdylib_exports: true,
1526             override_export_symbols: None,
1527             merge_functions: MergeFunctions::Aliases,
1528             mcount: "mcount".to_string(),
1529             llvm_abiname: "".to_string(),
1530             relax_elf_relocations: false,
1531             llvm_args: vec![],
1532             use_ctors_section: false,
1533             eh_frame_header: true,
1534             has_thumb_interworking: false,
1535             split_debuginfo: SplitDebuginfo::Off,
1536             supported_sanitizers: SanitizerSet::empty(),
1537             default_adjusted_cabi: None,
1538             c_enum_min_bits: 32,
1539             generate_arange_section: true,
1540             supports_stack_protector: true,
1541         }
1542     }
1543 }
1544
1545 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1546 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1547 /// this `Deref` implementation is no longer necessary.
1548 impl Deref for Target {
1549     type Target = TargetOptions;
1550
1551     #[inline]
1552     fn deref(&self) -> &Self::Target {
1553         &self.options
1554     }
1555 }
1556 impl DerefMut for Target {
1557     #[inline]
1558     fn deref_mut(&mut self) -> &mut Self::Target {
1559         &mut self.options
1560     }
1561 }
1562
1563 impl Target {
1564     /// Given a function ABI, turn it into the correct ABI for this target.
1565     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1566         match abi {
1567             Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1568             Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1569                 Abi::Stdcall { unwind }
1570             }
1571             Abi::System { unwind } => Abi::C { unwind },
1572             Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1573             Abi::EfiApi => Abi::C { unwind: false },
1574
1575             // See commentary in `is_abi_supported`.
1576             Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1577             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1578             Abi::Fastcall { .. } if self.arch == "x86" => abi,
1579             Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1580             Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1581
1582             abi => abi,
1583         }
1584     }
1585
1586     /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1587     pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1588         use Abi::*;
1589         Some(match abi {
1590             Rust
1591             | C { .. }
1592             | System { .. }
1593             | RustIntrinsic
1594             | RustCall
1595             | PlatformIntrinsic
1596             | Unadjusted
1597             | Cdecl { .. }
1598             | EfiApi => true,
1599             X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1600             Aapcs { .. } => "arm" == self.arch,
1601             CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1602             Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1603             PtxKernel => self.arch == "nvptx64",
1604             Msp430Interrupt => self.arch == "msp430",
1605             AmdGpuKernel => self.arch == "amdgcn",
1606             AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1607             Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1608             Thiscall { .. } => self.arch == "x86",
1609             // On windows these fall-back to platform native calling convention (C) when the
1610             // architecture is not supported.
1611             //
1612             // This is I believe a historical accident that has occurred as part of Microsoft
1613             // striving to allow most of the code to "just" compile when support for 64-bit x86
1614             // was added and then later again, when support for ARM architectures was added.
1615             //
1616             // This is well documented across MSDN. Support for this in Rust has been added in
1617             // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1618             // Rust, but there isn't much leeway remaining here to change it back at the time this
1619             // comment has been written.
1620             //
1621             // Following are the relevant excerpts from the MSDN documentation.
1622             //
1623             // > The __vectorcall calling convention is only supported in native code on x86 and
1624             // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1625             // > ...
1626             // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1627             //
1628             // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1629             //
1630             // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1631             //
1632             // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1633             //
1634             // > In most cases, keywords or compiler switches that specify an unsupported
1635             // > convention on a particular platform are ignored, and the platform default
1636             // > convention is used.
1637             //
1638             // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1639             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1640             // Outside of Windows we want to only support these calling conventions for the
1641             // architectures for which these calling conventions are actually well defined.
1642             Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1643             Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1644             // Return a `None` for other cases so that we know to emit a future compat lint.
1645             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1646         })
1647     }
1648
1649     /// Minimum integer size in bits that this target can perform atomic
1650     /// operations on.
1651     pub fn min_atomic_width(&self) -> u64 {
1652         self.min_atomic_width.unwrap_or(8)
1653     }
1654
1655     /// Maximum integer size in bits that this target can perform atomic
1656     /// operations on.
1657     pub fn max_atomic_width(&self) -> u64 {
1658         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1659     }
1660
1661     /// Loads a target descriptor from a JSON object.
1662     pub fn from_json(mut obj: Json) -> Result<(Target, TargetWarnings), String> {
1663         // While ugly, this code must remain this way to retain
1664         // compatibility with existing JSON fields and the internal
1665         // expected naming of the Target and TargetOptions structs.
1666         // To ensure compatibility is retained, the built-in targets
1667         // are round-tripped through this code to catch cases where
1668         // the JSON parser is not updated to match the structs.
1669
1670         let mut get_req_field = |name: &str| {
1671             obj.remove_key(name)
1672                 .and_then(|j| Json::as_string(&j).map(str::to_string))
1673                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1674         };
1675
1676         let mut base = Target {
1677             llvm_target: get_req_field("llvm-target")?,
1678             pointer_width: get_req_field("target-pointer-width")?
1679                 .parse::<u32>()
1680                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1681             data_layout: get_req_field("data-layout")?,
1682             arch: get_req_field("arch")?,
1683             options: Default::default(),
1684         };
1685
1686         let mut incorrect_type = vec![];
1687
1688         macro_rules! key {
1689             ($key_name:ident) => ( {
1690                 let name = (stringify!($key_name)).replace("_", "-");
1691                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1692                     base.$key_name = s;
1693                 }
1694             } );
1695             ($key_name:ident = $json_name:expr) => ( {
1696                 let name = $json_name;
1697                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1698                     base.$key_name = s;
1699                 }
1700             } );
1701             ($key_name:ident, bool) => ( {
1702                 let name = (stringify!($key_name)).replace("_", "-");
1703                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_boolean(&j)) {
1704                     base.$key_name = s;
1705                 }
1706             } );
1707             ($key_name:ident, u64) => ( {
1708                 let name = (stringify!($key_name)).replace("_", "-");
1709                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1710                     base.$key_name = s;
1711                 }
1712             } );
1713             ($key_name:ident, Option<u32>) => ( {
1714                 let name = (stringify!($key_name)).replace("_", "-");
1715                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1716                     if s < 1 || s > 5 {
1717                         return Err("Not a valid DWARF version number".to_string());
1718                     }
1719                     base.$key_name = Some(s as u32);
1720                 }
1721             } );
1722             ($key_name:ident, Option<u64>) => ( {
1723                 let name = (stringify!($key_name)).replace("_", "-");
1724                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1725                     base.$key_name = Some(s);
1726                 }
1727             } );
1728             ($key_name:ident, MergeFunctions) => ( {
1729                 let name = (stringify!($key_name)).replace("_", "-");
1730                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1731                     match s.parse::<MergeFunctions>() {
1732                         Ok(mergefunc) => base.$key_name = mergefunc,
1733                         _ => return Some(Err(format!("'{}' is not a valid value for \
1734                                                       merge-functions. Use 'disabled', \
1735                                                       'trampolines', or 'aliases'.",
1736                                                       s))),
1737                     }
1738                     Some(Ok(()))
1739                 })).unwrap_or(Ok(()))
1740             } );
1741             ($key_name:ident, RelocModel) => ( {
1742                 let name = (stringify!($key_name)).replace("_", "-");
1743                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1744                     match s.parse::<RelocModel>() {
1745                         Ok(relocation_model) => base.$key_name = relocation_model,
1746                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1747                                                       Run `rustc --print relocation-models` to \
1748                                                       see the list of supported values.", s))),
1749                     }
1750                     Some(Ok(()))
1751                 })).unwrap_or(Ok(()))
1752             } );
1753             ($key_name:ident, CodeModel) => ( {
1754                 let name = (stringify!($key_name)).replace("_", "-");
1755                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1756                     match s.parse::<CodeModel>() {
1757                         Ok(code_model) => base.$key_name = Some(code_model),
1758                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1759                                                       Run `rustc --print code-models` to \
1760                                                       see the list of supported values.", s))),
1761                     }
1762                     Some(Ok(()))
1763                 })).unwrap_or(Ok(()))
1764             } );
1765             ($key_name:ident, TlsModel) => ( {
1766                 let name = (stringify!($key_name)).replace("_", "-");
1767                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1768                     match s.parse::<TlsModel>() {
1769                         Ok(tls_model) => base.$key_name = tls_model,
1770                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1771                                                       Run `rustc --print tls-models` to \
1772                                                       see the list of supported values.", s))),
1773                     }
1774                     Some(Ok(()))
1775                 })).unwrap_or(Ok(()))
1776             } );
1777             ($key_name:ident, PanicStrategy) => ( {
1778                 let name = (stringify!($key_name)).replace("_", "-");
1779                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1780                     match s {
1781                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1782                         "abort" => base.$key_name = PanicStrategy::Abort,
1783                         _ => return Some(Err(format!("'{}' is not a valid value for \
1784                                                       panic-strategy. Use 'unwind' or 'abort'.",
1785                                                      s))),
1786                 }
1787                 Some(Ok(()))
1788             })).unwrap_or(Ok(()))
1789             } );
1790             ($key_name:ident, RelroLevel) => ( {
1791                 let name = (stringify!($key_name)).replace("_", "-");
1792                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1793                     match s.parse::<RelroLevel>() {
1794                         Ok(level) => base.$key_name = level,
1795                         _ => return Some(Err(format!("'{}' is not a valid value for \
1796                                                       relro-level. Use 'full', 'partial, or 'off'.",
1797                                                       s))),
1798                     }
1799                     Some(Ok(()))
1800                 })).unwrap_or(Ok(()))
1801             } );
1802             ($key_name:ident, SplitDebuginfo) => ( {
1803                 let name = (stringify!($key_name)).replace("_", "-");
1804                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1805                     match s.parse::<SplitDebuginfo>() {
1806                         Ok(level) => base.$key_name = level,
1807                         _ => return Some(Err(format!("'{}' is not a valid value for \
1808                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
1809                                                       s))),
1810                     }
1811                     Some(Ok(()))
1812                 })).unwrap_or(Ok(()))
1813             } );
1814             ($key_name:ident, list) => ( {
1815                 let name = (stringify!($key_name)).replace("_", "-");
1816                 if let Some(j) = obj.remove_key(&name){
1817                     if let Some(v) = Json::as_array(&j) {
1818                         base.$key_name = v.iter()
1819                             .map(|a| a.as_string().unwrap().to_string())
1820                             .collect();
1821                     } else {
1822                         incorrect_type.push(name)
1823                     }
1824                 }
1825             } );
1826             ($key_name:ident, opt_list) => ( {
1827                 let name = (stringify!($key_name)).replace("_", "-");
1828                 if let Some(j) = obj.remove_key(&name) {
1829                     if let Some(v) = Json::as_array(&j) {
1830                         base.$key_name = Some(v.iter()
1831                             .map(|a| a.as_string().unwrap().to_string())
1832                             .collect());
1833                     } else {
1834                         incorrect_type.push(name)
1835                     }
1836                 }
1837             } );
1838             ($key_name:ident, optional) => ( {
1839                 let name = (stringify!($key_name)).replace("_", "-");
1840                 if let Some(o) = obj.remove_key(&name[..]) {
1841                     base.$key_name = o
1842                         .as_string()
1843                         .map(|s| s.to_string() );
1844                 }
1845             } );
1846             ($key_name:ident, LldFlavor) => ( {
1847                 let name = (stringify!($key_name)).replace("_", "-");
1848                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1849                     if let Some(flavor) = LldFlavor::from_str(&s) {
1850                         base.$key_name = flavor;
1851                     } else {
1852                         return Some(Err(format!(
1853                             "'{}' is not a valid value for lld-flavor. \
1854                              Use 'darwin', 'gnu', 'link' or 'wasm.",
1855                             s)))
1856                     }
1857                     Some(Ok(()))
1858                 })).unwrap_or(Ok(()))
1859             } );
1860             ($key_name:ident, LinkerFlavor) => ( {
1861                 let name = (stringify!($key_name)).replace("_", "-");
1862                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1863                     match LinkerFlavor::from_str(s) {
1864                         Some(linker_flavor) => base.$key_name = linker_flavor,
1865                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1866                                                       Use {}", s, LinkerFlavor::one_of()))),
1867                     }
1868                     Some(Ok(()))
1869                 })).unwrap_or(Ok(()))
1870             } );
1871             ($key_name:ident, StackProbeType) => ( {
1872                 let name = (stringify!($key_name)).replace("_", "-");
1873                 obj.remove_key(&name[..]).and_then(|o| match StackProbeType::from_json(&o) {
1874                     Ok(v) => {
1875                         base.$key_name = v;
1876                         Some(Ok(()))
1877                     },
1878                     Err(s) => Some(Err(
1879                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1880                     )),
1881                 }).unwrap_or(Ok(()))
1882             } );
1883             ($key_name:ident, SanitizerSet) => ( {
1884                 let name = (stringify!($key_name)).replace("_", "-");
1885                 if let Some(o) = obj.remove_key(&name[..]) {
1886                     if let Some(a) = o.as_array() {
1887                         for s in a {
1888                             base.$key_name |= match s.as_string() {
1889                                 Some("address") => SanitizerSet::ADDRESS,
1890                                 Some("cfi") => SanitizerSet::CFI,
1891                                 Some("leak") => SanitizerSet::LEAK,
1892                                 Some("memory") => SanitizerSet::MEMORY,
1893                                 Some("memtag") => SanitizerSet::MEMTAG,
1894                                 Some("thread") => SanitizerSet::THREAD,
1895                                 Some("hwaddress") => SanitizerSet::HWADDRESS,
1896                                 Some(s) => return Err(format!("unknown sanitizer {}", s)),
1897                                 _ => return Err(format!("not a string: {:?}", s)),
1898                             };
1899                         }
1900                     } else {
1901                         incorrect_type.push(name)
1902                     }
1903                 }
1904                 Ok::<(), String>(())
1905             } );
1906
1907             ($key_name:ident, crt_objects_fallback) => ( {
1908                 let name = (stringify!($key_name)).replace("_", "-");
1909                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1910                     match s.parse::<CrtObjectsFallback>() {
1911                         Ok(fallback) => base.$key_name = Some(fallback),
1912                         _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1913                                                       Use 'musl', 'mingw' or 'wasm'", s))),
1914                     }
1915                     Some(Ok(()))
1916                 })).unwrap_or(Ok(()))
1917             } );
1918             ($key_name:ident, link_objects) => ( {
1919                 let name = (stringify!($key_name)).replace("_", "-");
1920                 if let Some(val) = obj.remove_key(&name[..]) {
1921                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1922                         JSON object with fields per CRT object kind.", name))?;
1923                     let mut args = CrtObjects::new();
1924                     for (k, v) in obj {
1925                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1926                             format!("{}: '{}' is not a valid value for CRT object kind. \
1927                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
1928                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1929                         })?;
1930
1931                         let v = v.as_array().ok_or_else(||
1932                             format!("{}.{}: expected a JSON array", name, k)
1933                         )?.iter().enumerate()
1934                             .map(|(i,s)| {
1935                                 let s = s.as_string().ok_or_else(||
1936                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1937                                 Ok(s.to_owned())
1938                             })
1939                             .collect::<Result<Vec<_>, String>>()?;
1940
1941                         args.insert(kind, v);
1942                     }
1943                     base.$key_name = args;
1944                 }
1945             } );
1946             ($key_name:ident, link_args) => ( {
1947                 let name = (stringify!($key_name)).replace("_", "-");
1948                 if let Some(val) = obj.remove_key(&name[..]) {
1949                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1950                         JSON object with fields per linker-flavor.", name))?;
1951                     let mut args = LinkArgs::new();
1952                     for (k, v) in obj {
1953                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1954                             format!("{}: '{}' is not a valid value for linker-flavor. \
1955                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1956                         })?;
1957
1958                         let v = v.as_array().ok_or_else(||
1959                             format!("{}.{}: expected a JSON array", name, k)
1960                         )?.iter().enumerate()
1961                             .map(|(i,s)| {
1962                                 let s = s.as_string().ok_or_else(||
1963                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1964                                 Ok(s.to_owned())
1965                             })
1966                             .collect::<Result<Vec<_>, String>>()?;
1967
1968                         args.insert(flavor, v);
1969                     }
1970                     base.$key_name = args;
1971                 }
1972             } );
1973             ($key_name:ident, env) => ( {
1974                 let name = (stringify!($key_name)).replace("_", "-");
1975                 if let Some(o) = obj.remove_key(&name[..]) {
1976                     if let Some(a) = o.as_array() {
1977                         for o in a {
1978                             if let Some(s) = o.as_string() {
1979                                 let p = s.split('=').collect::<Vec<_>>();
1980                                 if p.len() == 2 {
1981                                     let k = p[0].to_string();
1982                                     let v = p[1].to_string();
1983                                     base.$key_name.push((k, v));
1984                                 }
1985                             }
1986                         }
1987                     } else {
1988                         incorrect_type.push(name)
1989                     }
1990                 }
1991             } );
1992             ($key_name:ident, Option<Abi>) => ( {
1993                 let name = (stringify!($key_name)).replace("_", "-");
1994                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1995                     match lookup_abi(s) {
1996                         Some(abi) => base.$key_name = Some(abi),
1997                         _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
1998                     }
1999                     Some(Ok(()))
2000                 })).unwrap_or(Ok(()))
2001             } );
2002             ($key_name:ident, TargetFamilies) => ( {
2003                 if let Some(value) = obj.remove_key("target-family") {
2004                     if let Some(v) = Json::as_array(&value) {
2005                         base.$key_name = v.iter()
2006                             .map(|a| a.as_string().unwrap().to_string())
2007                             .collect();
2008                     } else if let Some(v) = Json::as_string(&value) {
2009                         base.$key_name = vec![v.to_string()];
2010                     }
2011                 }
2012             } );
2013         }
2014
2015         if let Some(j) = obj.remove_key("target-endian") {
2016             if let Some(s) = Json::as_string(&j) {
2017                 base.endian = s.parse()?;
2018             } else {
2019                 incorrect_type.push("target-endian".to_string())
2020             }
2021         }
2022
2023         if let Some(fp) = obj.remove_key("frame-pointer") {
2024             if let Some(s) = Json::as_string(&fp) {
2025                 base.frame_pointer = s
2026                     .parse()
2027                     .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2028             } else {
2029                 incorrect_type.push("frame-pointer".to_string())
2030             }
2031         }
2032
2033         key!(is_builtin, bool);
2034         key!(c_int_width = "target-c-int-width");
2035         key!(os);
2036         key!(env);
2037         key!(abi);
2038         key!(vendor);
2039         key!(linker_flavor, LinkerFlavor)?;
2040         key!(linker, optional);
2041         key!(lld_flavor, LldFlavor)?;
2042         key!(pre_link_objects, link_objects);
2043         key!(post_link_objects, link_objects);
2044         key!(pre_link_objects_fallback, link_objects);
2045         key!(post_link_objects_fallback, link_objects);
2046         key!(crt_objects_fallback, crt_objects_fallback)?;
2047         key!(pre_link_args, link_args);
2048         key!(late_link_args, link_args);
2049         key!(late_link_args_dynamic, link_args);
2050         key!(late_link_args_static, link_args);
2051         key!(post_link_args, link_args);
2052         key!(link_script, optional);
2053         key!(link_env, env);
2054         key!(link_env_remove, list);
2055         key!(asm_args, list);
2056         key!(cpu);
2057         key!(features);
2058         key!(dynamic_linking, bool);
2059         key!(only_cdylib, bool);
2060         key!(executables, bool);
2061         key!(relocation_model, RelocModel)?;
2062         key!(code_model, CodeModel)?;
2063         key!(tls_model, TlsModel)?;
2064         key!(disable_redzone, bool);
2065         key!(function_sections, bool);
2066         key!(dll_prefix);
2067         key!(dll_suffix);
2068         key!(exe_suffix);
2069         key!(staticlib_prefix);
2070         key!(staticlib_suffix);
2071         key!(families, TargetFamilies);
2072         key!(abi_return_struct_as_int, bool);
2073         key!(is_like_osx, bool);
2074         key!(is_like_solaris, bool);
2075         key!(is_like_windows, bool);
2076         key!(is_like_msvc, bool);
2077         key!(is_like_emscripten, bool);
2078         key!(is_like_fuchsia, bool);
2079         key!(is_like_wasm, bool);
2080         key!(dwarf_version, Option<u32>);
2081         key!(linker_is_gnu, bool);
2082         key!(allows_weak_linkage, bool);
2083         key!(has_rpath, bool);
2084         key!(no_default_libraries, bool);
2085         key!(position_independent_executables, bool);
2086         key!(static_position_independent_executables, bool);
2087         key!(needs_plt, bool);
2088         key!(relro_level, RelroLevel)?;
2089         key!(archive_format);
2090         key!(allow_asm, bool);
2091         key!(main_needs_argc_argv, bool);
2092         key!(has_thread_local, bool);
2093         key!(obj_is_bitcode, bool);
2094         key!(forces_embed_bitcode, bool);
2095         key!(bitcode_llvm_cmdline);
2096         key!(max_atomic_width, Option<u64>);
2097         key!(min_atomic_width, Option<u64>);
2098         key!(atomic_cas, bool);
2099         key!(panic_strategy, PanicStrategy)?;
2100         key!(crt_static_allows_dylibs, bool);
2101         key!(crt_static_default, bool);
2102         key!(crt_static_respected, bool);
2103         key!(stack_probes, StackProbeType)?;
2104         key!(min_global_align, Option<u64>);
2105         key!(default_codegen_units, Option<u64>);
2106         key!(trap_unreachable, bool);
2107         key!(requires_lto, bool);
2108         key!(singlethread, bool);
2109         key!(no_builtins, bool);
2110         key!(default_hidden_visibility, bool);
2111         key!(emit_debug_gdb_scripts, bool);
2112         key!(requires_uwtable, bool);
2113         key!(default_uwtable, bool);
2114         key!(simd_types_indirect, bool);
2115         key!(limit_rdylib_exports, bool);
2116         key!(override_export_symbols, opt_list);
2117         key!(merge_functions, MergeFunctions)?;
2118         key!(mcount = "target-mcount");
2119         key!(llvm_abiname);
2120         key!(relax_elf_relocations, bool);
2121         key!(llvm_args, list);
2122         key!(use_ctors_section, bool);
2123         key!(eh_frame_header, bool);
2124         key!(has_thumb_interworking, bool);
2125         key!(split_debuginfo, SplitDebuginfo)?;
2126         key!(supported_sanitizers, SanitizerSet)?;
2127         key!(default_adjusted_cabi, Option<Abi>)?;
2128         key!(c_enum_min_bits, u64);
2129         key!(generate_arange_section, bool);
2130         key!(supports_stack_protector, bool);
2131
2132         if base.is_builtin {
2133             // This can cause unfortunate ICEs later down the line.
2134             return Err("may not set is_builtin for targets not built-in".to_string());
2135         }
2136         // Each field should have been read using `Json::remove_key` so any keys remaining are unused.
2137         let remaining_keys = obj.as_object().ok_or("Expected JSON object for target")?.keys();
2138         Ok((
2139             base,
2140             TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2141         ))
2142     }
2143
2144     /// Load a built-in target
2145     pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2146         match *target_triple {
2147             TargetTriple::TargetTriple(ref target_triple) => {
2148                 load_builtin(target_triple).expect("built-in target")
2149             }
2150             TargetTriple::TargetPath(..) => {
2151                 panic!("built-in targets doens't support target-paths")
2152             }
2153         }
2154     }
2155
2156     /// Search for a JSON file specifying the given target triple.
2157     ///
2158     /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2159     /// sysroot under the target-triple's `rustlib` directory.  Note that it could also just be a
2160     /// bare filename already, so also check for that. If one of the hardcoded targets we know
2161     /// about, just return it directly.
2162     ///
2163     /// The error string could come from any of the APIs called, including filesystem access and
2164     /// JSON decoding.
2165     pub fn search(
2166         target_triple: &TargetTriple,
2167         sysroot: &Path,
2168     ) -> Result<(Target, TargetWarnings), String> {
2169         use rustc_serialize::json;
2170         use std::env;
2171         use std::fs;
2172
2173         fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2174             let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2175             let obj = json::from_str(&contents).map_err(|e| e.to_string())?;
2176             Target::from_json(obj)
2177         }
2178
2179         match *target_triple {
2180             TargetTriple::TargetTriple(ref target_triple) => {
2181                 // check if triple is in list of built-in targets
2182                 if let Some(t) = load_builtin(target_triple) {
2183                     return Ok((t, TargetWarnings::empty()));
2184                 }
2185
2186                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2187                 let path = {
2188                     let mut target = target_triple.to_string();
2189                     target.push_str(".json");
2190                     PathBuf::from(target)
2191                 };
2192
2193                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2194
2195                 for dir in env::split_paths(&target_path) {
2196                     let p = dir.join(&path);
2197                     if p.is_file() {
2198                         return load_file(&p);
2199                     }
2200                 }
2201
2202                 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2203                 // as a fallback.
2204                 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2205                 let p = PathBuf::from_iter([
2206                     Path::new(sysroot),
2207                     Path::new(&rustlib_path),
2208                     Path::new("target.json"),
2209                 ]);
2210                 if p.is_file() {
2211                     return load_file(&p);
2212                 }
2213
2214                 Err(format!("Could not find specification for target {:?}", target_triple))
2215             }
2216             TargetTriple::TargetPath(ref target_path) => {
2217                 if target_path.is_file() {
2218                     return load_file(&target_path);
2219                 }
2220                 Err(format!("Target path {:?} is not a valid file", target_path))
2221             }
2222         }
2223     }
2224 }
2225
2226 impl ToJson for Target {
2227     fn to_json(&self) -> Json {
2228         let mut d = BTreeMap::new();
2229         let default: TargetOptions = Default::default();
2230
2231         macro_rules! target_val {
2232             ($attr:ident) => {{
2233                 let name = (stringify!($attr)).replace("_", "-");
2234                 d.insert(name, self.$attr.to_json());
2235             }};
2236             ($attr:ident, $key_name:expr) => {{
2237                 let name = $key_name;
2238                 d.insert(name.to_string(), self.$attr.to_json());
2239             }};
2240         }
2241
2242         macro_rules! target_option_val {
2243             ($attr:ident) => {{
2244                 let name = (stringify!($attr)).replace("_", "-");
2245                 if default.$attr != self.$attr {
2246                     d.insert(name, self.$attr.to_json());
2247                 }
2248             }};
2249             ($attr:ident, $key_name:expr) => {{
2250                 let name = $key_name;
2251                 if default.$attr != self.$attr {
2252                     d.insert(name.to_string(), self.$attr.to_json());
2253                 }
2254             }};
2255             (link_args - $attr:ident) => {{
2256                 let name = (stringify!($attr)).replace("_", "-");
2257                 if default.$attr != self.$attr {
2258                     let obj = self
2259                         .$attr
2260                         .iter()
2261                         .map(|(k, v)| (k.desc().to_owned(), v.clone()))
2262                         .collect::<BTreeMap<_, _>>();
2263                     d.insert(name, obj.to_json());
2264                 }
2265             }};
2266             (env - $attr:ident) => {{
2267                 let name = (stringify!($attr)).replace("_", "-");
2268                 if default.$attr != self.$attr {
2269                     let obj = self
2270                         .$attr
2271                         .iter()
2272                         .map(|&(ref k, ref v)| k.clone() + "=" + &v)
2273                         .collect::<Vec<_>>();
2274                     d.insert(name, obj.to_json());
2275                 }
2276             }};
2277         }
2278
2279         target_val!(llvm_target);
2280         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2281         target_val!(arch);
2282         target_val!(data_layout);
2283
2284         target_option_val!(is_builtin);
2285         target_option_val!(endian, "target-endian");
2286         target_option_val!(c_int_width, "target-c-int-width");
2287         target_option_val!(os);
2288         target_option_val!(env);
2289         target_option_val!(abi);
2290         target_option_val!(vendor);
2291         target_option_val!(linker_flavor);
2292         target_option_val!(linker);
2293         target_option_val!(lld_flavor);
2294         target_option_val!(pre_link_objects);
2295         target_option_val!(post_link_objects);
2296         target_option_val!(pre_link_objects_fallback);
2297         target_option_val!(post_link_objects_fallback);
2298         target_option_val!(crt_objects_fallback);
2299         target_option_val!(link_args - pre_link_args);
2300         target_option_val!(link_args - late_link_args);
2301         target_option_val!(link_args - late_link_args_dynamic);
2302         target_option_val!(link_args - late_link_args_static);
2303         target_option_val!(link_args - post_link_args);
2304         target_option_val!(link_script);
2305         target_option_val!(env - link_env);
2306         target_option_val!(link_env_remove);
2307         target_option_val!(asm_args);
2308         target_option_val!(cpu);
2309         target_option_val!(features);
2310         target_option_val!(dynamic_linking);
2311         target_option_val!(only_cdylib);
2312         target_option_val!(executables);
2313         target_option_val!(relocation_model);
2314         target_option_val!(code_model);
2315         target_option_val!(tls_model);
2316         target_option_val!(disable_redzone);
2317         target_option_val!(frame_pointer);
2318         target_option_val!(function_sections);
2319         target_option_val!(dll_prefix);
2320         target_option_val!(dll_suffix);
2321         target_option_val!(exe_suffix);
2322         target_option_val!(staticlib_prefix);
2323         target_option_val!(staticlib_suffix);
2324         target_option_val!(families, "target-family");
2325         target_option_val!(abi_return_struct_as_int);
2326         target_option_val!(is_like_osx);
2327         target_option_val!(is_like_solaris);
2328         target_option_val!(is_like_windows);
2329         target_option_val!(is_like_msvc);
2330         target_option_val!(is_like_emscripten);
2331         target_option_val!(is_like_fuchsia);
2332         target_option_val!(is_like_wasm);
2333         target_option_val!(dwarf_version);
2334         target_option_val!(linker_is_gnu);
2335         target_option_val!(allows_weak_linkage);
2336         target_option_val!(has_rpath);
2337         target_option_val!(no_default_libraries);
2338         target_option_val!(position_independent_executables);
2339         target_option_val!(static_position_independent_executables);
2340         target_option_val!(needs_plt);
2341         target_option_val!(relro_level);
2342         target_option_val!(archive_format);
2343         target_option_val!(allow_asm);
2344         target_option_val!(main_needs_argc_argv);
2345         target_option_val!(has_thread_local);
2346         target_option_val!(obj_is_bitcode);
2347         target_option_val!(forces_embed_bitcode);
2348         target_option_val!(bitcode_llvm_cmdline);
2349         target_option_val!(min_atomic_width);
2350         target_option_val!(max_atomic_width);
2351         target_option_val!(atomic_cas);
2352         target_option_val!(panic_strategy);
2353         target_option_val!(crt_static_allows_dylibs);
2354         target_option_val!(crt_static_default);
2355         target_option_val!(crt_static_respected);
2356         target_option_val!(stack_probes);
2357         target_option_val!(min_global_align);
2358         target_option_val!(default_codegen_units);
2359         target_option_val!(trap_unreachable);
2360         target_option_val!(requires_lto);
2361         target_option_val!(singlethread);
2362         target_option_val!(no_builtins);
2363         target_option_val!(default_hidden_visibility);
2364         target_option_val!(emit_debug_gdb_scripts);
2365         target_option_val!(requires_uwtable);
2366         target_option_val!(default_uwtable);
2367         target_option_val!(simd_types_indirect);
2368         target_option_val!(limit_rdylib_exports);
2369         target_option_val!(override_export_symbols);
2370         target_option_val!(merge_functions);
2371         target_option_val!(mcount, "target-mcount");
2372         target_option_val!(llvm_abiname);
2373         target_option_val!(relax_elf_relocations);
2374         target_option_val!(llvm_args);
2375         target_option_val!(use_ctors_section);
2376         target_option_val!(eh_frame_header);
2377         target_option_val!(has_thumb_interworking);
2378         target_option_val!(split_debuginfo);
2379         target_option_val!(supported_sanitizers);
2380         target_option_val!(c_enum_min_bits);
2381         target_option_val!(generate_arange_section);
2382         target_option_val!(supports_stack_protector);
2383
2384         if let Some(abi) = self.default_adjusted_cabi {
2385             d.insert("default-adjusted-cabi".to_string(), Abi::name(abi).to_json());
2386         }
2387
2388         Json::Object(d)
2389     }
2390 }
2391
2392 /// Either a target triple string or a path to a JSON file.
2393 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2394 pub enum TargetTriple {
2395     TargetTriple(String),
2396     TargetPath(PathBuf),
2397 }
2398
2399 impl TargetTriple {
2400     /// Creates a target triple from the passed target triple string.
2401     pub fn from_triple(triple: &str) -> Self {
2402         TargetTriple::TargetTriple(triple.to_string())
2403     }
2404
2405     /// Creates a target triple from the passed target path.
2406     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2407         let canonicalized_path = path.canonicalize()?;
2408         Ok(TargetTriple::TargetPath(canonicalized_path))
2409     }
2410
2411     /// Returns a string triple for this target.
2412     ///
2413     /// If this target is a path, the file name (without extension) is returned.
2414     pub fn triple(&self) -> &str {
2415         match *self {
2416             TargetTriple::TargetTriple(ref triple) => triple,
2417             TargetTriple::TargetPath(ref path) => path
2418                 .file_stem()
2419                 .expect("target path must not be empty")
2420                 .to_str()
2421                 .expect("target path must be valid unicode"),
2422         }
2423     }
2424
2425     /// Returns an extended string triple for this target.
2426     ///
2427     /// If this target is a path, a hash of the path is appended to the triple returned
2428     /// by `triple()`.
2429     pub fn debug_triple(&self) -> String {
2430         use std::collections::hash_map::DefaultHasher;
2431         use std::hash::{Hash, Hasher};
2432
2433         let triple = self.triple();
2434         if let TargetTriple::TargetPath(ref path) = *self {
2435             let mut hasher = DefaultHasher::new();
2436             path.hash(&mut hasher);
2437             let hash = hasher.finish();
2438             format!("{}-{}", triple, hash)
2439         } else {
2440             triple.to_owned()
2441         }
2442     }
2443 }
2444
2445 impl fmt::Display for TargetTriple {
2446     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2447         write!(f, "{}", self.debug_triple())
2448     }
2449 }