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