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