]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Move `{core,std}::stream::Stream` to `{core,std}::async_iter::AsyncIterator`.
[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     ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
968
969     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
970     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
971     ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
972     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
973     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
974     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
975     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
976     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
977     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
978     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
979
980     ("aarch64-unknown-none", aarch64_unknown_none),
981     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
982
983     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
984
985     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
986     ("i686-unknown-uefi", i686_unknown_uefi),
987     ("aarch64-unknown-uefi", aarch64_unknown_uefi),
988
989     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
990
991     ("i686-wrs-vxworks", i686_wrs_vxworks),
992     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
993     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
994     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
995     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
996     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
997     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
998
999     ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1000     ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1001     ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1002
1003     ("mipsel-sony-psp", mipsel_sony_psp),
1004     ("mipsel-unknown-none", mipsel_unknown_none),
1005     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1006
1007     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1008     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1009     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1010
1011     ("bpfeb-unknown-none", bpfeb_unknown_none),
1012     ("bpfel-unknown-none", bpfel_unknown_none),
1013
1014     ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1015
1016     ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1017
1018     ("x86_64-unknown-none", x86_64_unknown_none),
1019 }
1020
1021 /// Warnings encountered when parsing the target `json`.
1022 ///
1023 /// Includes fields that weren't recognized and fields that don't have the expected type.
1024 #[derive(Debug, PartialEq)]
1025 pub struct TargetWarnings {
1026     unused_fields: Vec<String>,
1027     incorrect_type: Vec<String>,
1028 }
1029
1030 impl TargetWarnings {
1031     pub fn empty() -> Self {
1032         Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1033     }
1034
1035     pub fn warning_messages(&self) -> Vec<String> {
1036         let mut warnings = vec![];
1037         if !self.unused_fields.is_empty() {
1038             warnings.push(format!(
1039                 "target json file contains unused fields: {}",
1040                 self.unused_fields.join(", ")
1041             ));
1042         }
1043         if !self.incorrect_type.is_empty() {
1044             warnings.push(format!(
1045                 "target json file contains fields whose value doesn't have the correct json type: {}",
1046                 self.incorrect_type.join(", ")
1047             ));
1048         }
1049         warnings
1050     }
1051 }
1052
1053 /// Everything `rustc` knows about how to compile for a specific target.
1054 ///
1055 /// Every field here must be specified, and has no default value.
1056 #[derive(PartialEq, Clone, Debug)]
1057 pub struct Target {
1058     /// Target triple to pass to LLVM.
1059     pub llvm_target: String,
1060     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1061     pub pointer_width: u32,
1062     /// Architecture to use for ABI considerations. Valid options include: "x86",
1063     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1064     pub arch: String,
1065     /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1066     pub data_layout: String,
1067     /// Optional settings with defaults.
1068     pub options: TargetOptions,
1069 }
1070
1071 pub trait HasTargetSpec {
1072     fn target_spec(&self) -> &Target;
1073 }
1074
1075 impl HasTargetSpec for Target {
1076     #[inline]
1077     fn target_spec(&self) -> &Target {
1078         self
1079     }
1080 }
1081
1082 /// Optional aspects of a target specification.
1083 ///
1084 /// This has an implementation of `Default`, see each field for what the default is. In general,
1085 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1086 ///
1087 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1088 /// construction, all its fields logically belong to `Target` and available from `Target`
1089 /// through `Deref` impls.
1090 #[derive(PartialEq, Clone, Debug)]
1091 pub struct TargetOptions {
1092     /// Whether the target is built-in or loaded from a custom target specification.
1093     pub is_builtin: bool,
1094
1095     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1096     pub endian: Endian,
1097     /// Width of c_int type. Defaults to "32".
1098     pub c_int_width: String,
1099     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1100     /// "none" implies a bare metal target without `std` library.
1101     /// A couple of targets having `std` also use "unknown" as an `os` value,
1102     /// but they are exceptions.
1103     pub os: String,
1104     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1105     pub env: String,
1106     /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1107     /// or `"eabihf"`. Defaults to "".
1108     pub abi: String,
1109     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1110     pub vendor: String,
1111     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1112     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1113     pub linker_flavor: LinkerFlavor,
1114
1115     /// Linker to invoke
1116     pub linker: Option<String>,
1117
1118     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1119     /// without clarifying its flavor in any way.
1120     pub lld_flavor: LldFlavor,
1121
1122     /// Linker arguments that are passed *before* any user-defined libraries.
1123     pub pre_link_args: LinkArgs,
1124     /// Objects to link before and after all other object code.
1125     pub pre_link_objects: CrtObjects,
1126     pub post_link_objects: CrtObjects,
1127     /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
1128     /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
1129     /// See `crt_objects.rs` for some more detailed documentation.
1130     pub pre_link_objects_fallback: CrtObjects,
1131     pub post_link_objects_fallback: CrtObjects,
1132     /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
1133     pub crt_objects_fallback: Option<CrtObjectsFallback>,
1134
1135     /// Linker arguments that are unconditionally passed after any
1136     /// user-defined but before post-link objects. Standard platform
1137     /// libraries that should be always be linked to, usually go here.
1138     pub late_link_args: LinkArgs,
1139     /// Linker arguments used in addition to `late_link_args` if at least one
1140     /// Rust dependency is dynamically linked.
1141     pub late_link_args_dynamic: LinkArgs,
1142     /// Linker arguments used in addition to `late_link_args` if aall Rust
1143     /// dependencies are statically linked.
1144     pub late_link_args_static: LinkArgs,
1145     /// Linker arguments that are unconditionally passed *after* any
1146     /// user-defined libraries.
1147     pub post_link_args: LinkArgs,
1148     /// Optional link script applied to `dylib` and `executable` crate types.
1149     /// This is a string containing the script, not a path. Can only be applied
1150     /// to linkers where `linker_is_gnu` is true.
1151     pub link_script: Option<String>,
1152
1153     /// Environment variables to be set for the linker invocation.
1154     pub link_env: Vec<(String, String)>,
1155     /// Environment variables to be removed for the linker invocation.
1156     pub link_env_remove: Vec<String>,
1157
1158     /// Extra arguments to pass to the external assembler (when used)
1159     pub asm_args: Vec<String>,
1160
1161     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1162     /// to "generic".
1163     pub cpu: String,
1164     /// Default target features to pass to LLVM. These features will *always* be
1165     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1166     /// -mattr=$features`.
1167     pub features: String,
1168     /// Whether dynamic linking is available on this target. Defaults to false.
1169     pub dynamic_linking: bool,
1170     /// If dynamic linking is available, whether only cdylibs are supported.
1171     pub only_cdylib: bool,
1172     /// Whether executables are available on this target. iOS, for example, only allows static
1173     /// libraries. Defaults to false.
1174     pub executables: bool,
1175     /// Relocation model to use in object file. Corresponds to `llc
1176     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1177     pub relocation_model: RelocModel,
1178     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1179     /// Defaults to `None` which means "inherited from the base LLVM target".
1180     pub code_model: Option<CodeModel>,
1181     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1182     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1183     pub tls_model: TlsModel,
1184     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1185     pub disable_redzone: bool,
1186     /// Frame pointer mode for this target. Defaults to `MayOmit`.
1187     pub frame_pointer: FramePointer,
1188     /// Emit each function in its own section. Defaults to true.
1189     pub function_sections: bool,
1190     /// String to prepend to the name of every dynamic library. Defaults to "lib".
1191     pub dll_prefix: String,
1192     /// String to append to the name of every dynamic library. Defaults to ".so".
1193     pub dll_suffix: String,
1194     /// String to append to the name of every executable.
1195     pub exe_suffix: String,
1196     /// String to prepend to the name of every static library. Defaults to "lib".
1197     pub staticlib_prefix: String,
1198     /// String to append to the name of every static library. Defaults to ".a".
1199     pub staticlib_suffix: String,
1200     /// Values of the `target_family` cfg set for this target.
1201     ///
1202     /// Common options are: "unix", "windows". Defaults to no families.
1203     ///
1204     /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1205     pub families: Vec<String>,
1206     /// Whether the target toolchain's ABI supports returning small structs as an integer.
1207     pub abi_return_struct_as_int: bool,
1208     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1209     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1210     pub is_like_osx: bool,
1211     /// Whether the target toolchain is like Solaris's.
1212     /// Only useful for compiling against Illumos/Solaris,
1213     /// as they have a different set of linker flags. Defaults to false.
1214     pub is_like_solaris: bool,
1215     /// Whether the target is like Windows.
1216     /// This is a combination of several more specific properties represented as a single flag:
1217     ///   - The target uses a Windows ABI,
1218     ///   - uses PE/COFF as a format for object code,
1219     ///   - uses Windows-style dllexport/dllimport for shared libraries,
1220     ///   - uses import libraries and .def files for symbol exports,
1221     ///   - executables support setting a subsystem.
1222     pub is_like_windows: bool,
1223     /// Whether the target is like MSVC.
1224     /// This is a combination of several more specific properties represented as a single flag:
1225     ///   - The target has all the properties from `is_like_windows`
1226     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
1227     ///   - has some MSVC-specific Windows ABI properties,
1228     ///   - uses a link.exe-like linker,
1229     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
1230     ///   - uses SEH-based unwinding,
1231     ///   - supports control flow guard mechanism.
1232     pub is_like_msvc: bool,
1233     /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1234     /// Emscripten toolchain.
1235     /// Defaults to false.
1236     pub is_like_emscripten: bool,
1237     /// Whether the target toolchain is like Fuchsia's.
1238     pub is_like_fuchsia: bool,
1239     /// Whether a target toolchain is like WASM.
1240     pub is_like_wasm: bool,
1241     /// Version of DWARF to use if not using the default.
1242     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1243     pub dwarf_version: Option<u32>,
1244     /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1245     pub linker_is_gnu: bool,
1246     /// The MinGW toolchain has a known issue that prevents it from correctly
1247     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1248     /// symbol needs its own COMDAT section, weak linkage implies a large
1249     /// number sections that easily exceeds the given limit for larger
1250     /// codebases. Consequently we want a way to disallow weak linkage on some
1251     /// platforms.
1252     pub allows_weak_linkage: bool,
1253     /// Whether the linker support rpaths or not. Defaults to false.
1254     pub has_rpath: bool,
1255     /// Whether to disable linking to the default libraries, typically corresponds
1256     /// to `-nodefaultlibs`. Defaults to true.
1257     pub no_default_libraries: bool,
1258     /// Dynamically linked executables can be compiled as position independent
1259     /// if the default relocation model of position independent code is not
1260     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1261     /// the functions in the executable are not randomized and can be used
1262     /// during an exploit of a vulnerability in any code.
1263     pub position_independent_executables: bool,
1264     /// Executables that are both statically linked and position-independent are supported.
1265     pub static_position_independent_executables: bool,
1266     /// Determines if the target always requires using the PLT for indirect
1267     /// library calls or not. This controls the default value of the `-Z plt` flag.
1268     pub needs_plt: bool,
1269     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1270     /// resolve all symbols at startup and marks the GOT read-only before
1271     /// starting the program, preventing overwriting the GOT.
1272     pub relro_level: RelroLevel,
1273     /// Format that archives should be emitted in. This affects whether we use
1274     /// LLVM to assemble an archive or fall back to the system linker, and
1275     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1276     /// the system linker to be used.
1277     pub archive_format: String,
1278     /// Is asm!() allowed? Defaults to true.
1279     pub allow_asm: bool,
1280     /// Whether the runtime startup code requires the `main` function be passed
1281     /// `argc` and `argv` values.
1282     pub main_needs_argc_argv: bool,
1283
1284     /// Flag indicating whether #[thread_local] is available for this target.
1285     pub has_thread_local: bool,
1286     // This is mainly for easy compatibility with emscripten.
1287     // If we give emcc .o files that are actually .bc files it
1288     // will 'just work'.
1289     pub obj_is_bitcode: bool,
1290     /// Whether the target requires that emitted object code includes bitcode.
1291     pub forces_embed_bitcode: bool,
1292     /// Content of the LLVM cmdline section associated with embedded bitcode.
1293     pub bitcode_llvm_cmdline: String,
1294
1295     /// Don't use this field; instead use the `.min_atomic_width()` method.
1296     pub min_atomic_width: Option<u64>,
1297
1298     /// Don't use this field; instead use the `.max_atomic_width()` method.
1299     pub max_atomic_width: Option<u64>,
1300
1301     /// Whether the target supports atomic CAS operations natively
1302     pub atomic_cas: bool,
1303
1304     /// Panic strategy: "unwind" or "abort"
1305     pub panic_strategy: PanicStrategy,
1306
1307     /// Whether or not linking dylibs to a static CRT is allowed.
1308     pub crt_static_allows_dylibs: bool,
1309     /// Whether or not the CRT is statically linked by default.
1310     pub crt_static_default: bool,
1311     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1312     pub crt_static_respected: bool,
1313
1314     /// The implementation of stack probes to use.
1315     pub stack_probes: StackProbeType,
1316
1317     /// The minimum alignment for global symbols.
1318     pub min_global_align: Option<u64>,
1319
1320     /// Default number of codegen units to use in debug mode
1321     pub default_codegen_units: Option<u64>,
1322
1323     /// Whether to generate trap instructions in places where optimization would
1324     /// otherwise produce control flow that falls through into unrelated memory.
1325     pub trap_unreachable: bool,
1326
1327     /// This target requires everything to be compiled with LTO to emit a final
1328     /// executable, aka there is no native linker for this target.
1329     pub requires_lto: bool,
1330
1331     /// This target has no support for threads.
1332     pub singlethread: bool,
1333
1334     /// Whether library functions call lowering/optimization is disabled in LLVM
1335     /// for this target unconditionally.
1336     pub no_builtins: bool,
1337
1338     /// The default visibility for symbols in this target should be "hidden"
1339     /// rather than "default"
1340     pub default_hidden_visibility: bool,
1341
1342     /// Whether a .debug_gdb_scripts section will be added to the output object file
1343     pub emit_debug_gdb_scripts: bool,
1344
1345     /// Whether or not to unconditionally `uwtable` attributes on functions,
1346     /// typically because the platform needs to unwind for things like stack
1347     /// unwinders.
1348     pub requires_uwtable: bool,
1349
1350     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1351     /// is not specified and `uwtable` is not required on this target.
1352     pub default_uwtable: bool,
1353
1354     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1355     /// typically required if a target can be compiled with a mixed set of
1356     /// target features. This is `true` by default, and `false` for targets like
1357     /// wasm32 where the whole program either has simd or not.
1358     pub simd_types_indirect: bool,
1359
1360     /// Pass a list of symbol which should be exported in the dylib to the linker.
1361     pub limit_rdylib_exports: bool,
1362
1363     /// If set, have the linker export exactly these symbols, instead of using
1364     /// the usual logic to figure this out from the crate itself.
1365     pub override_export_symbols: Option<Vec<String>>,
1366
1367     /// Determines how or whether the MergeFunctions LLVM pass should run for
1368     /// this target. Either "disabled", "trampolines", or "aliases".
1369     /// The MergeFunctions pass is generally useful, but some targets may need
1370     /// to opt out. The default is "aliases".
1371     ///
1372     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1373     pub merge_functions: MergeFunctions,
1374
1375     /// Use platform dependent mcount function
1376     pub mcount: String,
1377
1378     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1379     pub llvm_abiname: String,
1380
1381     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1382     pub relax_elf_relocations: bool,
1383
1384     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1385     pub llvm_args: Vec<String>,
1386
1387     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1388     /// to false (uses .init_array).
1389     pub use_ctors_section: bool,
1390
1391     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1392     /// used to locate unwinding information is passed
1393     /// (only has effect if the linker is `ld`-like).
1394     pub eh_frame_header: bool,
1395
1396     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1397     /// thumb and arm interworking.
1398     pub has_thumb_interworking: bool,
1399
1400     /// How to handle split debug information, if at all. Specifying `None` has
1401     /// target-specific meaning.
1402     pub split_debuginfo: SplitDebuginfo,
1403
1404     /// The sanitizers supported by this target
1405     ///
1406     /// Note that the support here is at a codegen level. If the machine code with sanitizer
1407     /// enabled can generated on this target, but the necessary supporting libraries are not
1408     /// distributed with the target, the sanitizer should still appear in this list for the target.
1409     pub supported_sanitizers: SanitizerSet,
1410
1411     /// If present it's a default value to use for adjusting the C ABI.
1412     pub default_adjusted_cabi: Option<Abi>,
1413
1414     /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1415     pub c_enum_min_bits: u64,
1416
1417     /// Whether or not the DWARF `.debug_aranges` section should be generated.
1418     pub generate_arange_section: bool,
1419
1420     /// Whether the target supports stack canary checks. `true` by default,
1421     /// since this is most common among tier 1 and tier 2 targets.
1422     pub supports_stack_protector: bool,
1423 }
1424
1425 impl Default for TargetOptions {
1426     /// Creates a set of "sane defaults" for any target. This is still
1427     /// incomplete, and if used for compilation, will certainly not work.
1428     fn default() -> TargetOptions {
1429         TargetOptions {
1430             is_builtin: false,
1431             endian: Endian::Little,
1432             c_int_width: "32".to_string(),
1433             os: "none".to_string(),
1434             env: String::new(),
1435             abi: String::new(),
1436             vendor: "unknown".to_string(),
1437             linker_flavor: LinkerFlavor::Gcc,
1438             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1439             lld_flavor: LldFlavor::Ld,
1440             pre_link_args: LinkArgs::new(),
1441             post_link_args: LinkArgs::new(),
1442             link_script: None,
1443             asm_args: Vec::new(),
1444             cpu: "generic".to_string(),
1445             features: String::new(),
1446             dynamic_linking: false,
1447             only_cdylib: false,
1448             executables: false,
1449             relocation_model: RelocModel::Pic,
1450             code_model: None,
1451             tls_model: TlsModel::GeneralDynamic,
1452             disable_redzone: false,
1453             frame_pointer: FramePointer::MayOmit,
1454             function_sections: true,
1455             dll_prefix: "lib".to_string(),
1456             dll_suffix: ".so".to_string(),
1457             exe_suffix: String::new(),
1458             staticlib_prefix: "lib".to_string(),
1459             staticlib_suffix: ".a".to_string(),
1460             families: Vec::new(),
1461             abi_return_struct_as_int: false,
1462             is_like_osx: false,
1463             is_like_solaris: false,
1464             is_like_windows: false,
1465             is_like_emscripten: false,
1466             is_like_msvc: false,
1467             is_like_fuchsia: false,
1468             is_like_wasm: false,
1469             dwarf_version: None,
1470             linker_is_gnu: true,
1471             allows_weak_linkage: true,
1472             has_rpath: false,
1473             no_default_libraries: true,
1474             position_independent_executables: false,
1475             static_position_independent_executables: false,
1476             needs_plt: false,
1477             relro_level: RelroLevel::None,
1478             pre_link_objects: Default::default(),
1479             post_link_objects: Default::default(),
1480             pre_link_objects_fallback: Default::default(),
1481             post_link_objects_fallback: Default::default(),
1482             crt_objects_fallback: None,
1483             late_link_args: LinkArgs::new(),
1484             late_link_args_dynamic: LinkArgs::new(),
1485             late_link_args_static: LinkArgs::new(),
1486             link_env: Vec::new(),
1487             link_env_remove: Vec::new(),
1488             archive_format: "gnu".to_string(),
1489             main_needs_argc_argv: true,
1490             allow_asm: true,
1491             has_thread_local: false,
1492             obj_is_bitcode: false,
1493             forces_embed_bitcode: false,
1494             bitcode_llvm_cmdline: String::new(),
1495             min_atomic_width: None,
1496             max_atomic_width: None,
1497             atomic_cas: true,
1498             panic_strategy: PanicStrategy::Unwind,
1499             crt_static_allows_dylibs: false,
1500             crt_static_default: false,
1501             crt_static_respected: false,
1502             stack_probes: StackProbeType::None,
1503             min_global_align: None,
1504             default_codegen_units: None,
1505             trap_unreachable: true,
1506             requires_lto: false,
1507             singlethread: false,
1508             no_builtins: false,
1509             default_hidden_visibility: false,
1510             emit_debug_gdb_scripts: true,
1511             requires_uwtable: false,
1512             default_uwtable: false,
1513             simd_types_indirect: true,
1514             limit_rdylib_exports: true,
1515             override_export_symbols: None,
1516             merge_functions: MergeFunctions::Aliases,
1517             mcount: "mcount".to_string(),
1518             llvm_abiname: "".to_string(),
1519             relax_elf_relocations: false,
1520             llvm_args: vec![],
1521             use_ctors_section: false,
1522             eh_frame_header: true,
1523             has_thumb_interworking: false,
1524             split_debuginfo: SplitDebuginfo::Off,
1525             supported_sanitizers: SanitizerSet::empty(),
1526             default_adjusted_cabi: None,
1527             c_enum_min_bits: 32,
1528             generate_arange_section: true,
1529             supports_stack_protector: true,
1530         }
1531     }
1532 }
1533
1534 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1535 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1536 /// this `Deref` implementation is no longer necessary.
1537 impl Deref for Target {
1538     type Target = TargetOptions;
1539
1540     fn deref(&self) -> &Self::Target {
1541         &self.options
1542     }
1543 }
1544 impl DerefMut for Target {
1545     fn deref_mut(&mut self) -> &mut Self::Target {
1546         &mut self.options
1547     }
1548 }
1549
1550 impl Target {
1551     /// Given a function ABI, turn it into the correct ABI for this target.
1552     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1553         match abi {
1554             Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1555             Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1556                 Abi::Stdcall { unwind }
1557             }
1558             Abi::System { unwind } => Abi::C { unwind },
1559             Abi::EfiApi if self.arch == "x86_64" => Abi::Win64,
1560             Abi::EfiApi => Abi::C { unwind: false },
1561
1562             // See commentary in `is_abi_supported`.
1563             Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1564             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1565             Abi::Fastcall if self.arch == "x86" => abi,
1566             Abi::Vectorcall if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1567             Abi::Fastcall | Abi::Vectorcall => Abi::C { unwind: false },
1568
1569             abi => abi,
1570         }
1571     }
1572
1573     /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1574     pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1575         use Abi::*;
1576         Some(match abi {
1577             Rust
1578             | C { .. }
1579             | System { .. }
1580             | RustIntrinsic
1581             | RustCall
1582             | PlatformIntrinsic
1583             | Unadjusted
1584             | Cdecl
1585             | EfiApi => true,
1586             X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1587             Aapcs => "arm" == self.arch,
1588             CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1589             Win64 | SysV64 => self.arch == "x86_64",
1590             PtxKernel => self.arch == "nvptx64",
1591             Msp430Interrupt => self.arch == "msp430",
1592             AmdGpuKernel => self.arch == "amdgcn",
1593             AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1594             Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1595             Thiscall { .. } => self.arch == "x86",
1596             // On windows these fall-back to platform native calling convention (C) when the
1597             // architecture is not supported.
1598             //
1599             // This is I believe a historical accident that has occurred as part of Microsoft
1600             // striving to allow most of the code to "just" compile when support for 64-bit x86
1601             // was added and then later again, when support for ARM architectures was added.
1602             //
1603             // This is well documented across MSDN. Support for this in Rust has been added in
1604             // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1605             // Rust, but there isn't much leeway remaining here to change it back at the time this
1606             // comment has been written.
1607             //
1608             // Following are the relevant excerpts from the MSDN documentation.
1609             //
1610             // > The __vectorcall calling convention is only supported in native code on x86 and
1611             // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1612             // > ...
1613             // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1614             //
1615             // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1616             //
1617             // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1618             //
1619             // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1620             //
1621             // > In most cases, keywords or compiler switches that specify an unsupported
1622             // > convention on a particular platform are ignored, and the platform default
1623             // > convention is used.
1624             //
1625             // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1626             Stdcall { .. } | Fastcall | Vectorcall if self.is_like_windows => true,
1627             // Outside of Windows we want to only support these calling conventions for the
1628             // architectures for which these calling conventions are actually well defined.
1629             Stdcall { .. } | Fastcall if self.arch == "x86" => true,
1630             Vectorcall if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1631             // Return a `None` for other cases so that we know to emit a future compat lint.
1632             Stdcall { .. } | Fastcall | Vectorcall => return None,
1633         })
1634     }
1635
1636     /// Minimum integer size in bits that this target can perform atomic
1637     /// operations on.
1638     pub fn min_atomic_width(&self) -> u64 {
1639         self.min_atomic_width.unwrap_or(8)
1640     }
1641
1642     /// Maximum integer size in bits that this target can perform atomic
1643     /// operations on.
1644     pub fn max_atomic_width(&self) -> u64 {
1645         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1646     }
1647
1648     /// Loads a target descriptor from a JSON object.
1649     pub fn from_json(mut obj: Json) -> Result<(Target, TargetWarnings), String> {
1650         // While ugly, this code must remain this way to retain
1651         // compatibility with existing JSON fields and the internal
1652         // expected naming of the Target and TargetOptions structs.
1653         // To ensure compatibility is retained, the built-in targets
1654         // are round-tripped through this code to catch cases where
1655         // the JSON parser is not updated to match the structs.
1656
1657         let mut get_req_field = |name: &str| {
1658             obj.remove_key(name)
1659                 .and_then(|j| Json::as_string(&j).map(str::to_string))
1660                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1661         };
1662
1663         let mut base = Target {
1664             llvm_target: get_req_field("llvm-target")?,
1665             pointer_width: get_req_field("target-pointer-width")?
1666                 .parse::<u32>()
1667                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1668             data_layout: get_req_field("data-layout")?,
1669             arch: get_req_field("arch")?,
1670             options: Default::default(),
1671         };
1672
1673         let mut incorrect_type = vec![];
1674
1675         macro_rules! key {
1676             ($key_name:ident) => ( {
1677                 let name = (stringify!($key_name)).replace("_", "-");
1678                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1679                     base.$key_name = s;
1680                 }
1681             } );
1682             ($key_name:ident = $json_name:expr) => ( {
1683                 let name = $json_name;
1684                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_string(&j).map(str::to_string)) {
1685                     base.$key_name = s;
1686                 }
1687             } );
1688             ($key_name:ident, bool) => ( {
1689                 let name = (stringify!($key_name)).replace("_", "-");
1690                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_boolean(&j)) {
1691                     base.$key_name = s;
1692                 }
1693             } );
1694             ($key_name:ident, u64) => ( {
1695                 let name = (stringify!($key_name)).replace("_", "-");
1696                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1697                     base.$key_name = s;
1698                 }
1699             } );
1700             ($key_name:ident, Option<u32>) => ( {
1701                 let name = (stringify!($key_name)).replace("_", "-");
1702                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1703                     if s < 1 || s > 5 {
1704                         return Err("Not a valid DWARF version number".to_string());
1705                     }
1706                     base.$key_name = Some(s as u32);
1707                 }
1708             } );
1709             ($key_name:ident, Option<u64>) => ( {
1710                 let name = (stringify!($key_name)).replace("_", "-");
1711                 if let Some(s) = obj.remove_key(&name).and_then(|j| Json::as_u64(&j)) {
1712                     base.$key_name = Some(s);
1713                 }
1714             } );
1715             ($key_name:ident, MergeFunctions) => ( {
1716                 let name = (stringify!($key_name)).replace("_", "-");
1717                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1718                     match s.parse::<MergeFunctions>() {
1719                         Ok(mergefunc) => base.$key_name = mergefunc,
1720                         _ => return Some(Err(format!("'{}' is not a valid value for \
1721                                                       merge-functions. Use 'disabled', \
1722                                                       'trampolines', or 'aliases'.",
1723                                                       s))),
1724                     }
1725                     Some(Ok(()))
1726                 })).unwrap_or(Ok(()))
1727             } );
1728             ($key_name:ident, RelocModel) => ( {
1729                 let name = (stringify!($key_name)).replace("_", "-");
1730                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1731                     match s.parse::<RelocModel>() {
1732                         Ok(relocation_model) => base.$key_name = relocation_model,
1733                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1734                                                       Run `rustc --print relocation-models` to \
1735                                                       see the list of supported values.", s))),
1736                     }
1737                     Some(Ok(()))
1738                 })).unwrap_or(Ok(()))
1739             } );
1740             ($key_name:ident, CodeModel) => ( {
1741                 let name = (stringify!($key_name)).replace("_", "-");
1742                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1743                     match s.parse::<CodeModel>() {
1744                         Ok(code_model) => base.$key_name = Some(code_model),
1745                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1746                                                       Run `rustc --print code-models` to \
1747                                                       see the list of supported values.", s))),
1748                     }
1749                     Some(Ok(()))
1750                 })).unwrap_or(Ok(()))
1751             } );
1752             ($key_name:ident, TlsModel) => ( {
1753                 let name = (stringify!($key_name)).replace("_", "-");
1754                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1755                     match s.parse::<TlsModel>() {
1756                         Ok(tls_model) => base.$key_name = tls_model,
1757                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1758                                                       Run `rustc --print tls-models` to \
1759                                                       see the list of supported values.", s))),
1760                     }
1761                     Some(Ok(()))
1762                 })).unwrap_or(Ok(()))
1763             } );
1764             ($key_name:ident, PanicStrategy) => ( {
1765                 let name = (stringify!($key_name)).replace("_", "-");
1766                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1767                     match s {
1768                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1769                         "abort" => base.$key_name = PanicStrategy::Abort,
1770                         _ => return Some(Err(format!("'{}' is not a valid value for \
1771                                                       panic-strategy. Use 'unwind' or 'abort'.",
1772                                                      s))),
1773                 }
1774                 Some(Ok(()))
1775             })).unwrap_or(Ok(()))
1776             } );
1777             ($key_name:ident, RelroLevel) => ( {
1778                 let name = (stringify!($key_name)).replace("_", "-");
1779                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1780                     match s.parse::<RelroLevel>() {
1781                         Ok(level) => base.$key_name = level,
1782                         _ => return Some(Err(format!("'{}' is not a valid value for \
1783                                                       relro-level. Use 'full', 'partial, or 'off'.",
1784                                                       s))),
1785                     }
1786                     Some(Ok(()))
1787                 })).unwrap_or(Ok(()))
1788             } );
1789             ($key_name:ident, SplitDebuginfo) => ( {
1790                 let name = (stringify!($key_name)).replace("_", "-");
1791                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1792                     match s.parse::<SplitDebuginfo>() {
1793                         Ok(level) => base.$key_name = level,
1794                         _ => return Some(Err(format!("'{}' is not a valid value for \
1795                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
1796                                                       s))),
1797                     }
1798                     Some(Ok(()))
1799                 })).unwrap_or(Ok(()))
1800             } );
1801             ($key_name:ident, list) => ( {
1802                 let name = (stringify!($key_name)).replace("_", "-");
1803                 if let Some(j) = obj.remove_key(&name){
1804                     if let Some(v) = Json::as_array(&j) {
1805                         base.$key_name = v.iter()
1806                             .map(|a| a.as_string().unwrap().to_string())
1807                             .collect();
1808                     } else {
1809                         incorrect_type.push(name)
1810                     }
1811                 }
1812             } );
1813             ($key_name:ident, opt_list) => ( {
1814                 let name = (stringify!($key_name)).replace("_", "-");
1815                 if let Some(j) = obj.remove_key(&name) {
1816                     if let Some(v) = Json::as_array(&j) {
1817                         base.$key_name = Some(v.iter()
1818                             .map(|a| a.as_string().unwrap().to_string())
1819                             .collect());
1820                     } else {
1821                         incorrect_type.push(name)
1822                     }
1823                 }
1824             } );
1825             ($key_name:ident, optional) => ( {
1826                 let name = (stringify!($key_name)).replace("_", "-");
1827                 if let Some(o) = obj.remove_key(&name[..]) {
1828                     base.$key_name = o
1829                         .as_string()
1830                         .map(|s| s.to_string() );
1831                 }
1832             } );
1833             ($key_name:ident, LldFlavor) => ( {
1834                 let name = (stringify!($key_name)).replace("_", "-");
1835                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1836                     if let Some(flavor) = LldFlavor::from_str(&s) {
1837                         base.$key_name = flavor;
1838                     } else {
1839                         return Some(Err(format!(
1840                             "'{}' is not a valid value for lld-flavor. \
1841                              Use 'darwin', 'gnu', 'link' or 'wasm.",
1842                             s)))
1843                     }
1844                     Some(Ok(()))
1845                 })).unwrap_or(Ok(()))
1846             } );
1847             ($key_name:ident, LinkerFlavor) => ( {
1848                 let name = (stringify!($key_name)).replace("_", "-");
1849                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1850                     match LinkerFlavor::from_str(s) {
1851                         Some(linker_flavor) => base.$key_name = linker_flavor,
1852                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1853                                                       Use {}", s, LinkerFlavor::one_of()))),
1854                     }
1855                     Some(Ok(()))
1856                 })).unwrap_or(Ok(()))
1857             } );
1858             ($key_name:ident, StackProbeType) => ( {
1859                 let name = (stringify!($key_name)).replace("_", "-");
1860                 obj.remove_key(&name[..]).and_then(|o| match StackProbeType::from_json(&o) {
1861                     Ok(v) => {
1862                         base.$key_name = v;
1863                         Some(Ok(()))
1864                     },
1865                     Err(s) => Some(Err(
1866                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1867                     )),
1868                 }).unwrap_or(Ok(()))
1869             } );
1870             ($key_name:ident, SanitizerSet) => ( {
1871                 let name = (stringify!($key_name)).replace("_", "-");
1872                 if let Some(o) = obj.remove_key(&name[..]) {
1873                     if let Some(a) = o.as_array() {
1874                         for s in a {
1875                             base.$key_name |= match s.as_string() {
1876                                 Some("address") => SanitizerSet::ADDRESS,
1877                                 Some("cfi") => SanitizerSet::CFI,
1878                                 Some("leak") => SanitizerSet::LEAK,
1879                                 Some("memory") => SanitizerSet::MEMORY,
1880                                 Some("thread") => SanitizerSet::THREAD,
1881                                 Some("hwaddress") => SanitizerSet::HWADDRESS,
1882                                 Some(s) => return Err(format!("unknown sanitizer {}", s)),
1883                                 _ => return Err(format!("not a string: {:?}", s)),
1884                             };
1885                         }
1886                     } else {
1887                         incorrect_type.push(name)
1888                     }
1889                 }
1890                 Ok::<(), String>(())
1891             } );
1892
1893             ($key_name:ident, crt_objects_fallback) => ( {
1894                 let name = (stringify!($key_name)).replace("_", "-");
1895                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1896                     match s.parse::<CrtObjectsFallback>() {
1897                         Ok(fallback) => base.$key_name = Some(fallback),
1898                         _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1899                                                       Use 'musl', 'mingw' or 'wasm'", s))),
1900                     }
1901                     Some(Ok(()))
1902                 })).unwrap_or(Ok(()))
1903             } );
1904             ($key_name:ident, link_objects) => ( {
1905                 let name = (stringify!($key_name)).replace("_", "-");
1906                 if let Some(val) = obj.remove_key(&name[..]) {
1907                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1908                         JSON object with fields per CRT object kind.", name))?;
1909                     let mut args = CrtObjects::new();
1910                     for (k, v) in obj {
1911                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1912                             format!("{}: '{}' is not a valid value for CRT object kind. \
1913                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
1914                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1915                         })?;
1916
1917                         let v = v.as_array().ok_or_else(||
1918                             format!("{}.{}: expected a JSON array", name, k)
1919                         )?.iter().enumerate()
1920                             .map(|(i,s)| {
1921                                 let s = s.as_string().ok_or_else(||
1922                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1923                                 Ok(s.to_owned())
1924                             })
1925                             .collect::<Result<Vec<_>, String>>()?;
1926
1927                         args.insert(kind, v);
1928                     }
1929                     base.$key_name = args;
1930                 }
1931             } );
1932             ($key_name:ident, link_args) => ( {
1933                 let name = (stringify!($key_name)).replace("_", "-");
1934                 if let Some(val) = obj.remove_key(&name[..]) {
1935                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1936                         JSON object with fields per linker-flavor.", name))?;
1937                     let mut args = LinkArgs::new();
1938                     for (k, v) in obj {
1939                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1940                             format!("{}: '{}' is not a valid value for linker-flavor. \
1941                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1942                         })?;
1943
1944                         let v = v.as_array().ok_or_else(||
1945                             format!("{}.{}: expected a JSON array", name, k)
1946                         )?.iter().enumerate()
1947                             .map(|(i,s)| {
1948                                 let s = s.as_string().ok_or_else(||
1949                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1950                                 Ok(s.to_owned())
1951                             })
1952                             .collect::<Result<Vec<_>, String>>()?;
1953
1954                         args.insert(flavor, v);
1955                     }
1956                     base.$key_name = args;
1957                 }
1958             } );
1959             ($key_name:ident, env) => ( {
1960                 let name = (stringify!($key_name)).replace("_", "-");
1961                 if let Some(o) = obj.remove_key(&name[..]) {
1962                     if let Some(a) = o.as_array() {
1963                         for o in a {
1964                             if let Some(s) = o.as_string() {
1965                                 let p = s.split('=').collect::<Vec<_>>();
1966                                 if p.len() == 2 {
1967                                     let k = p[0].to_string();
1968                                     let v = p[1].to_string();
1969                                     base.$key_name.push((k, v));
1970                                 }
1971                             }
1972                         }
1973                     } else {
1974                         incorrect_type.push(name)
1975                     }
1976                 }
1977             } );
1978             ($key_name:ident, Option<Abi>) => ( {
1979                 let name = (stringify!($key_name)).replace("_", "-");
1980                 obj.remove_key(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1981                     match lookup_abi(s) {
1982                         Some(abi) => base.$key_name = Some(abi),
1983                         _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
1984                     }
1985                     Some(Ok(()))
1986                 })).unwrap_or(Ok(()))
1987             } );
1988             ($key_name:ident, TargetFamilies) => ( {
1989                 if let Some(value) = obj.remove_key("target-family") {
1990                     if let Some(v) = Json::as_array(&value) {
1991                         base.$key_name = v.iter()
1992                             .map(|a| a.as_string().unwrap().to_string())
1993                             .collect();
1994                     } else if let Some(v) = Json::as_string(&value) {
1995                         base.$key_name = vec![v.to_string()];
1996                     }
1997                 }
1998             } );
1999         }
2000
2001         if let Some(j) = obj.remove_key("target-endian") {
2002             if let Some(s) = Json::as_string(&j) {
2003                 base.endian = s.parse()?;
2004             } else {
2005                 incorrect_type.push("target-endian".to_string())
2006             }
2007         }
2008
2009         if let Some(fp) = obj.remove_key("frame-pointer") {
2010             if let Some(s) = Json::as_string(&fp) {
2011                 base.frame_pointer = s
2012                     .parse()
2013                     .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2014             } else {
2015                 incorrect_type.push("frame-pointer".to_string())
2016             }
2017         }
2018
2019         key!(is_builtin, bool);
2020         key!(c_int_width = "target-c-int-width");
2021         key!(os);
2022         key!(env);
2023         key!(abi);
2024         key!(vendor);
2025         key!(linker_flavor, LinkerFlavor)?;
2026         key!(linker, optional);
2027         key!(lld_flavor, LldFlavor)?;
2028         key!(pre_link_objects, link_objects);
2029         key!(post_link_objects, link_objects);
2030         key!(pre_link_objects_fallback, link_objects);
2031         key!(post_link_objects_fallback, link_objects);
2032         key!(crt_objects_fallback, crt_objects_fallback)?;
2033         key!(pre_link_args, link_args);
2034         key!(late_link_args, link_args);
2035         key!(late_link_args_dynamic, link_args);
2036         key!(late_link_args_static, link_args);
2037         key!(post_link_args, link_args);
2038         key!(link_script, optional);
2039         key!(link_env, env);
2040         key!(link_env_remove, list);
2041         key!(asm_args, list);
2042         key!(cpu);
2043         key!(features);
2044         key!(dynamic_linking, bool);
2045         key!(only_cdylib, bool);
2046         key!(executables, bool);
2047         key!(relocation_model, RelocModel)?;
2048         key!(code_model, CodeModel)?;
2049         key!(tls_model, TlsModel)?;
2050         key!(disable_redzone, bool);
2051         key!(function_sections, bool);
2052         key!(dll_prefix);
2053         key!(dll_suffix);
2054         key!(exe_suffix);
2055         key!(staticlib_prefix);
2056         key!(staticlib_suffix);
2057         key!(families, TargetFamilies);
2058         key!(abi_return_struct_as_int, bool);
2059         key!(is_like_osx, bool);
2060         key!(is_like_solaris, bool);
2061         key!(is_like_windows, bool);
2062         key!(is_like_msvc, bool);
2063         key!(is_like_emscripten, bool);
2064         key!(is_like_fuchsia, bool);
2065         key!(is_like_wasm, bool);
2066         key!(dwarf_version, Option<u32>);
2067         key!(linker_is_gnu, bool);
2068         key!(allows_weak_linkage, bool);
2069         key!(has_rpath, bool);
2070         key!(no_default_libraries, bool);
2071         key!(position_independent_executables, bool);
2072         key!(static_position_independent_executables, bool);
2073         key!(needs_plt, bool);
2074         key!(relro_level, RelroLevel)?;
2075         key!(archive_format);
2076         key!(allow_asm, bool);
2077         key!(main_needs_argc_argv, bool);
2078         key!(has_thread_local, bool);
2079         key!(obj_is_bitcode, bool);
2080         key!(forces_embed_bitcode, bool);
2081         key!(bitcode_llvm_cmdline);
2082         key!(max_atomic_width, Option<u64>);
2083         key!(min_atomic_width, Option<u64>);
2084         key!(atomic_cas, bool);
2085         key!(panic_strategy, PanicStrategy)?;
2086         key!(crt_static_allows_dylibs, bool);
2087         key!(crt_static_default, bool);
2088         key!(crt_static_respected, bool);
2089         key!(stack_probes, StackProbeType)?;
2090         key!(min_global_align, Option<u64>);
2091         key!(default_codegen_units, Option<u64>);
2092         key!(trap_unreachable, bool);
2093         key!(requires_lto, bool);
2094         key!(singlethread, bool);
2095         key!(no_builtins, bool);
2096         key!(default_hidden_visibility, bool);
2097         key!(emit_debug_gdb_scripts, bool);
2098         key!(requires_uwtable, bool);
2099         key!(default_uwtable, bool);
2100         key!(simd_types_indirect, bool);
2101         key!(limit_rdylib_exports, bool);
2102         key!(override_export_symbols, opt_list);
2103         key!(merge_functions, MergeFunctions)?;
2104         key!(mcount = "target-mcount");
2105         key!(llvm_abiname);
2106         key!(relax_elf_relocations, bool);
2107         key!(llvm_args, list);
2108         key!(use_ctors_section, bool);
2109         key!(eh_frame_header, bool);
2110         key!(has_thumb_interworking, bool);
2111         key!(split_debuginfo, SplitDebuginfo)?;
2112         key!(supported_sanitizers, SanitizerSet)?;
2113         key!(default_adjusted_cabi, Option<Abi>)?;
2114         key!(c_enum_min_bits, u64);
2115         key!(generate_arange_section, bool);
2116         key!(supports_stack_protector, bool);
2117
2118         if base.is_builtin {
2119             // This can cause unfortunate ICEs later down the line.
2120             return Err("may not set is_builtin for targets not built-in".to_string());
2121         }
2122         // Each field should have been read using `Json::remove_key` so any keys remaining are unused.
2123         let remaining_keys = obj.as_object().ok_or("Expected JSON object for target")?.keys();
2124         Ok((
2125             base,
2126             TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2127         ))
2128     }
2129
2130     /// Search for a JSON file specifying the given target triple.
2131     ///
2132     /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2133     /// sysroot under the target-triple's `rustlib` directory.  Note that it could also just be a
2134     /// bare filename already, so also check for that. If one of the hardcoded targets we know
2135     /// about, just return it directly.
2136     ///
2137     /// The error string could come from any of the APIs called, including filesystem access and
2138     /// JSON decoding.
2139     pub fn search(
2140         target_triple: &TargetTriple,
2141         sysroot: &Path,
2142     ) -> Result<(Target, TargetWarnings), String> {
2143         use rustc_serialize::json;
2144         use std::env;
2145         use std::fs;
2146
2147         fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2148             let contents = fs::read(path).map_err(|e| e.to_string())?;
2149             let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
2150             Target::from_json(obj)
2151         }
2152
2153         match *target_triple {
2154             TargetTriple::TargetTriple(ref target_triple) => {
2155                 // check if triple is in list of built-in targets
2156                 if let Some(t) = load_builtin(target_triple) {
2157                     return Ok((t, TargetWarnings::empty()));
2158                 }
2159
2160                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2161                 let path = {
2162                     let mut target = target_triple.to_string();
2163                     target.push_str(".json");
2164                     PathBuf::from(target)
2165                 };
2166
2167                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2168
2169                 for dir in env::split_paths(&target_path) {
2170                     let p = dir.join(&path);
2171                     if p.is_file() {
2172                         return load_file(&p);
2173                     }
2174                 }
2175
2176                 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2177                 // as a fallback.
2178                 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2179                 let p = PathBuf::from_iter([
2180                     Path::new(sysroot),
2181                     Path::new(&rustlib_path),
2182                     Path::new("target.json"),
2183                 ]);
2184                 if p.is_file() {
2185                     return load_file(&p);
2186                 }
2187
2188                 Err(format!("Could not find specification for target {:?}", target_triple))
2189             }
2190             TargetTriple::TargetPath(ref target_path) => {
2191                 if target_path.is_file() {
2192                     return load_file(&target_path);
2193                 }
2194                 Err(format!("Target path {:?} is not a valid file", target_path))
2195             }
2196         }
2197     }
2198 }
2199
2200 impl ToJson for Target {
2201     fn to_json(&self) -> Json {
2202         let mut d = BTreeMap::new();
2203         let default: TargetOptions = Default::default();
2204
2205         macro_rules! target_val {
2206             ($attr:ident) => {{
2207                 let name = (stringify!($attr)).replace("_", "-");
2208                 d.insert(name, self.$attr.to_json());
2209             }};
2210             ($attr:ident, $key_name:expr) => {{
2211                 let name = $key_name;
2212                 d.insert(name.to_string(), self.$attr.to_json());
2213             }};
2214         }
2215
2216         macro_rules! target_option_val {
2217             ($attr:ident) => {{
2218                 let name = (stringify!($attr)).replace("_", "-");
2219                 if default.$attr != self.$attr {
2220                     d.insert(name, self.$attr.to_json());
2221                 }
2222             }};
2223             ($attr:ident, $key_name:expr) => {{
2224                 let name = $key_name;
2225                 if default.$attr != self.$attr {
2226                     d.insert(name.to_string(), self.$attr.to_json());
2227                 }
2228             }};
2229             (link_args - $attr:ident) => {{
2230                 let name = (stringify!($attr)).replace("_", "-");
2231                 if default.$attr != self.$attr {
2232                     let obj = self
2233                         .$attr
2234                         .iter()
2235                         .map(|(k, v)| (k.desc().to_owned(), v.clone()))
2236                         .collect::<BTreeMap<_, _>>();
2237                     d.insert(name, obj.to_json());
2238                 }
2239             }};
2240             (env - $attr:ident) => {{
2241                 let name = (stringify!($attr)).replace("_", "-");
2242                 if default.$attr != self.$attr {
2243                     let obj = self
2244                         .$attr
2245                         .iter()
2246                         .map(|&(ref k, ref v)| k.clone() + "=" + &v)
2247                         .collect::<Vec<_>>();
2248                     d.insert(name, obj.to_json());
2249                 }
2250             }};
2251         }
2252
2253         target_val!(llvm_target);
2254         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2255         target_val!(arch);
2256         target_val!(data_layout);
2257
2258         target_option_val!(is_builtin);
2259         target_option_val!(endian, "target-endian");
2260         target_option_val!(c_int_width, "target-c-int-width");
2261         target_option_val!(os);
2262         target_option_val!(env);
2263         target_option_val!(abi);
2264         target_option_val!(vendor);
2265         target_option_val!(linker_flavor);
2266         target_option_val!(linker);
2267         target_option_val!(lld_flavor);
2268         target_option_val!(pre_link_objects);
2269         target_option_val!(post_link_objects);
2270         target_option_val!(pre_link_objects_fallback);
2271         target_option_val!(post_link_objects_fallback);
2272         target_option_val!(crt_objects_fallback);
2273         target_option_val!(link_args - pre_link_args);
2274         target_option_val!(link_args - late_link_args);
2275         target_option_val!(link_args - late_link_args_dynamic);
2276         target_option_val!(link_args - late_link_args_static);
2277         target_option_val!(link_args - post_link_args);
2278         target_option_val!(link_script);
2279         target_option_val!(env - link_env);
2280         target_option_val!(link_env_remove);
2281         target_option_val!(asm_args);
2282         target_option_val!(cpu);
2283         target_option_val!(features);
2284         target_option_val!(dynamic_linking);
2285         target_option_val!(only_cdylib);
2286         target_option_val!(executables);
2287         target_option_val!(relocation_model);
2288         target_option_val!(code_model);
2289         target_option_val!(tls_model);
2290         target_option_val!(disable_redzone);
2291         target_option_val!(frame_pointer);
2292         target_option_val!(function_sections);
2293         target_option_val!(dll_prefix);
2294         target_option_val!(dll_suffix);
2295         target_option_val!(exe_suffix);
2296         target_option_val!(staticlib_prefix);
2297         target_option_val!(staticlib_suffix);
2298         target_option_val!(families, "target-family");
2299         target_option_val!(abi_return_struct_as_int);
2300         target_option_val!(is_like_osx);
2301         target_option_val!(is_like_solaris);
2302         target_option_val!(is_like_windows);
2303         target_option_val!(is_like_msvc);
2304         target_option_val!(is_like_emscripten);
2305         target_option_val!(is_like_fuchsia);
2306         target_option_val!(is_like_wasm);
2307         target_option_val!(dwarf_version);
2308         target_option_val!(linker_is_gnu);
2309         target_option_val!(allows_weak_linkage);
2310         target_option_val!(has_rpath);
2311         target_option_val!(no_default_libraries);
2312         target_option_val!(position_independent_executables);
2313         target_option_val!(static_position_independent_executables);
2314         target_option_val!(needs_plt);
2315         target_option_val!(relro_level);
2316         target_option_val!(archive_format);
2317         target_option_val!(allow_asm);
2318         target_option_val!(main_needs_argc_argv);
2319         target_option_val!(has_thread_local);
2320         target_option_val!(obj_is_bitcode);
2321         target_option_val!(forces_embed_bitcode);
2322         target_option_val!(bitcode_llvm_cmdline);
2323         target_option_val!(min_atomic_width);
2324         target_option_val!(max_atomic_width);
2325         target_option_val!(atomic_cas);
2326         target_option_val!(panic_strategy);
2327         target_option_val!(crt_static_allows_dylibs);
2328         target_option_val!(crt_static_default);
2329         target_option_val!(crt_static_respected);
2330         target_option_val!(stack_probes);
2331         target_option_val!(min_global_align);
2332         target_option_val!(default_codegen_units);
2333         target_option_val!(trap_unreachable);
2334         target_option_val!(requires_lto);
2335         target_option_val!(singlethread);
2336         target_option_val!(no_builtins);
2337         target_option_val!(default_hidden_visibility);
2338         target_option_val!(emit_debug_gdb_scripts);
2339         target_option_val!(requires_uwtable);
2340         target_option_val!(default_uwtable);
2341         target_option_val!(simd_types_indirect);
2342         target_option_val!(limit_rdylib_exports);
2343         target_option_val!(override_export_symbols);
2344         target_option_val!(merge_functions);
2345         target_option_val!(mcount, "target-mcount");
2346         target_option_val!(llvm_abiname);
2347         target_option_val!(relax_elf_relocations);
2348         target_option_val!(llvm_args);
2349         target_option_val!(use_ctors_section);
2350         target_option_val!(eh_frame_header);
2351         target_option_val!(has_thumb_interworking);
2352         target_option_val!(split_debuginfo);
2353         target_option_val!(supported_sanitizers);
2354         target_option_val!(c_enum_min_bits);
2355         target_option_val!(generate_arange_section);
2356         target_option_val!(supports_stack_protector);
2357
2358         if let Some(abi) = self.default_adjusted_cabi {
2359             d.insert("default-adjusted-cabi".to_string(), Abi::name(abi).to_json());
2360         }
2361
2362         Json::Object(d)
2363     }
2364 }
2365
2366 /// Either a target triple string or a path to a JSON file.
2367 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2368 pub enum TargetTriple {
2369     TargetTriple(String),
2370     TargetPath(PathBuf),
2371 }
2372
2373 impl TargetTriple {
2374     /// Creates a target triple from the passed target triple string.
2375     pub fn from_triple(triple: &str) -> Self {
2376         TargetTriple::TargetTriple(triple.to_string())
2377     }
2378
2379     /// Creates a target triple from the passed target path.
2380     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2381         let canonicalized_path = path.canonicalize()?;
2382         Ok(TargetTriple::TargetPath(canonicalized_path))
2383     }
2384
2385     /// Returns a string triple for this target.
2386     ///
2387     /// If this target is a path, the file name (without extension) is returned.
2388     pub fn triple(&self) -> &str {
2389         match *self {
2390             TargetTriple::TargetTriple(ref triple) => triple,
2391             TargetTriple::TargetPath(ref path) => path
2392                 .file_stem()
2393                 .expect("target path must not be empty")
2394                 .to_str()
2395                 .expect("target path must be valid unicode"),
2396         }
2397     }
2398
2399     /// Returns an extended string triple for this target.
2400     ///
2401     /// If this target is a path, a hash of the path is appended to the triple returned
2402     /// by `triple()`.
2403     pub fn debug_triple(&self) -> String {
2404         use std::collections::hash_map::DefaultHasher;
2405         use std::hash::{Hash, Hasher};
2406
2407         let triple = self.triple();
2408         if let TargetTriple::TargetPath(ref path) = *self {
2409             let mut hasher = DefaultHasher::new();
2410             path.hash(&mut hasher);
2411             let hash = hasher.finish();
2412             format!("{}-{}", triple, hash)
2413         } else {
2414             triple.to_owned()
2415         }
2416     }
2417 }
2418
2419 impl fmt::Display for TargetTriple {
2420     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2421         write!(f, "{}", self.debug_triple())
2422     }
2423 }