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