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