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