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