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