]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Add support for powerpc64le-unknown-freebsd.
[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 `none`, `inline`, `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     ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
645     ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
646     ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
647     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
648     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
649     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
650     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
651     ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
652     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
653     ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
654     ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
655     ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
656     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
657     ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
658     ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
659     ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
660     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
661     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
662     ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
663     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
664     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
665     ("i586-unknown-linux-musl", i586_unknown_linux_musl),
666     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
667     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
668     ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
669     ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
670     ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
671
672     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
673     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
674
675     ("i686-linux-android", i686_linux_android),
676     ("x86_64-linux-android", x86_64_linux_android),
677     ("arm-linux-androideabi", arm_linux_androideabi),
678     ("armv7-linux-androideabi", armv7_linux_androideabi),
679     ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
680     ("aarch64-linux-android", aarch64_linux_android),
681
682     ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
683
684     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
685     ("armv6-unknown-freebsd", armv6_unknown_freebsd),
686     ("armv7-unknown-freebsd", armv7_unknown_freebsd),
687     ("i686-unknown-freebsd", i686_unknown_freebsd),
688     ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
689     ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
690     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
691
692     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
693
694     ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
695     ("i686-unknown-openbsd", i686_unknown_openbsd),
696     ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
697     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
698     ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
699
700     ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
701     ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
702     ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
703     ("i686-unknown-netbsd", i686_unknown_netbsd),
704     ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
705     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
706     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
707
708     ("i686-unknown-haiku", i686_unknown_haiku),
709     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
710
711     ("aarch64-apple-darwin", aarch64_apple_darwin),
712     ("x86_64-apple-darwin", x86_64_apple_darwin),
713     ("i686-apple-darwin", i686_apple_darwin),
714
715     ("aarch64-fuchsia", aarch64_fuchsia),
716     ("x86_64-fuchsia", x86_64_fuchsia),
717
718     ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
719
720     ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
721
722     ("aarch64-unknown-redox", aarch64_unknown_redox),
723     ("x86_64-unknown-redox", x86_64_unknown_redox),
724
725     ("i386-apple-ios", i386_apple_ios),
726     ("x86_64-apple-ios", x86_64_apple_ios),
727     ("aarch64-apple-ios", aarch64_apple_ios),
728     ("armv7-apple-ios", armv7_apple_ios),
729     ("armv7s-apple-ios", armv7s_apple_ios),
730     ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
731     ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
732     ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
733     ("aarch64-apple-tvos", aarch64_apple_tvos),
734     ("x86_64-apple-tvos", x86_64_apple_tvos),
735
736     ("armebv7r-none-eabi", armebv7r_none_eabi),
737     ("armebv7r-none-eabihf", armebv7r_none_eabihf),
738     ("armv7r-none-eabi", armv7r_none_eabi),
739     ("armv7r-none-eabihf", armv7r_none_eabihf),
740
741     ("x86_64-pc-solaris", x86_64_pc_solaris),
742     ("x86_64-sun-solaris", x86_64_sun_solaris),
743     ("sparcv9-sun-solaris", sparcv9_sun_solaris),
744
745     ("x86_64-unknown-illumos", x86_64_unknown_illumos),
746
747     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
748     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
749     ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
750     ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
751
752     ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
753     ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
754     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
755     ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
756     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
757     ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
758     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
759     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
760     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
761
762     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
763     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
764     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
765     ("wasm32-wasi", wasm32_wasi),
766
767     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
768     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
769     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
770     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
771     ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
772     ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
773     ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
774
775     ("armv7a-none-eabi", armv7a_none_eabi),
776     ("armv7a-none-eabihf", armv7a_none_eabihf),
777
778     ("msp430-none-elf", msp430_none_elf),
779
780     ("aarch64-unknown-hermit", aarch64_unknown_hermit),
781     ("x86_64-unknown-hermit", x86_64_unknown_hermit),
782
783     ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
784
785     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
786     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
787     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
788     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
789     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
790     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
791     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
792     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
793     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
794
795     ("aarch64-unknown-none", aarch64_unknown_none),
796     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
797
798     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
799
800     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
801     ("i686-unknown-uefi", i686_unknown_uefi),
802
803     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
804
805     ("i686-wrs-vxworks", i686_wrs_vxworks),
806     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
807     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
808     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
809     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
810     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
811     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
812
813     ("mipsel-sony-psp", mipsel_sony_psp),
814     ("mipsel-unknown-none", mipsel_unknown_none),
815     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
816
817     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
818     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
819     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
820 }
821
822 /// Everything `rustc` knows about how to compile for a specific target.
823 ///
824 /// Every field here must be specified, and has no default value.
825 #[derive(PartialEq, Clone, Debug)]
826 pub struct Target {
827     /// Target triple to pass to LLVM.
828     pub llvm_target: String,
829     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
830     pub pointer_width: u32,
831     /// Architecture to use for ABI considerations. Valid options include: "x86",
832     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
833     pub arch: String,
834     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
835     pub data_layout: String,
836     /// Optional settings with defaults.
837     pub options: TargetOptions,
838 }
839
840 pub trait HasTargetSpec {
841     fn target_spec(&self) -> &Target;
842 }
843
844 impl HasTargetSpec for Target {
845     fn target_spec(&self) -> &Target {
846         self
847     }
848 }
849
850 /// Optional aspects of a target specification.
851 ///
852 /// This has an implementation of `Default`, see each field for what the default is. In general,
853 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
854 ///
855 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
856 /// construction, all its fields logically belong to `Target` and available from `Target`
857 /// through `Deref` impls.
858 #[derive(PartialEq, Clone, Debug)]
859 pub struct TargetOptions {
860     /// Whether the target is built-in or loaded from a custom target specification.
861     pub is_builtin: bool,
862
863     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
864     pub endian: Endian,
865     /// Width of c_int type. Defaults to "32".
866     pub c_int_width: String,
867     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
868     /// "none" implies a bare metal target without `std` library.
869     /// A couple of targets having `std` also use "unknown" as an `os` value,
870     /// but they are exceptions.
871     pub os: String,
872     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
873     pub env: String,
874     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
875     pub vendor: String,
876     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
877     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
878     pub linker_flavor: LinkerFlavor,
879
880     /// Linker to invoke
881     pub linker: Option<String>,
882
883     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
884     /// without clarifying its flavor in any way.
885     pub lld_flavor: LldFlavor,
886
887     /// Linker arguments that are passed *before* any user-defined libraries.
888     pub pre_link_args: LinkArgs,
889     /// Objects to link before and after all other object code.
890     pub pre_link_objects: CrtObjects,
891     pub post_link_objects: CrtObjects,
892     /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
893     /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
894     /// See `crt_objects.rs` for some more detailed documentation.
895     pub pre_link_objects_fallback: CrtObjects,
896     pub post_link_objects_fallback: CrtObjects,
897     /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
898     pub crt_objects_fallback: Option<CrtObjectsFallback>,
899
900     /// Linker arguments that are unconditionally passed after any
901     /// user-defined but before post-link objects. Standard platform
902     /// libraries that should be always be linked to, usually go here.
903     pub late_link_args: LinkArgs,
904     /// Linker arguments used in addition to `late_link_args` if at least one
905     /// Rust dependency is dynamically linked.
906     pub late_link_args_dynamic: LinkArgs,
907     /// Linker arguments used in addition to `late_link_args` if aall Rust
908     /// dependencies are statically linked.
909     pub late_link_args_static: LinkArgs,
910     /// Linker arguments that are unconditionally passed *after* any
911     /// user-defined libraries.
912     pub post_link_args: LinkArgs,
913     /// Optional link script applied to `dylib` and `executable` crate types.
914     /// This is a string containing the script, not a path. Can only be applied
915     /// to linkers where `linker_is_gnu` is true.
916     pub link_script: Option<String>,
917
918     /// Environment variables to be set for the linker invocation.
919     pub link_env: Vec<(String, String)>,
920     /// Environment variables to be removed for the linker invocation.
921     pub link_env_remove: Vec<String>,
922
923     /// Extra arguments to pass to the external assembler (when used)
924     pub asm_args: Vec<String>,
925
926     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
927     /// to "generic".
928     pub cpu: String,
929     /// Default target features to pass to LLVM. These features will *always* be
930     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
931     /// -mattr=$features`.
932     pub features: String,
933     /// Whether dynamic linking is available on this target. Defaults to false.
934     pub dynamic_linking: bool,
935     /// If dynamic linking is available, whether only cdylibs are supported.
936     pub only_cdylib: bool,
937     /// Whether executables are available on this target. iOS, for example, only allows static
938     /// libraries. Defaults to false.
939     pub executables: bool,
940     /// Relocation model to use in object file. Corresponds to `llc
941     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
942     pub relocation_model: RelocModel,
943     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
944     /// Defaults to `None` which means "inherited from the base LLVM target".
945     pub code_model: Option<CodeModel>,
946     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
947     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
948     pub tls_model: TlsModel,
949     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
950     pub disable_redzone: bool,
951     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
952     pub eliminate_frame_pointer: bool,
953     /// Emit each function in its own section. Defaults to true.
954     pub function_sections: bool,
955     /// String to prepend to the name of every dynamic library. Defaults to "lib".
956     pub dll_prefix: String,
957     /// String to append to the name of every dynamic library. Defaults to ".so".
958     pub dll_suffix: String,
959     /// String to append to the name of every executable.
960     pub exe_suffix: String,
961     /// String to prepend to the name of every static library. Defaults to "lib".
962     pub staticlib_prefix: String,
963     /// String to append to the name of every static library. Defaults to ".a".
964     pub staticlib_suffix: String,
965     /// OS family to use for conditional compilation. Valid options: "unix", "windows".
966     pub os_family: Option<String>,
967     /// Whether the target toolchain's ABI supports returning small structs as an integer.
968     pub abi_return_struct_as_int: bool,
969     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
970     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
971     pub is_like_osx: bool,
972     /// Whether the target toolchain is like Solaris's.
973     /// Only useful for compiling against Illumos/Solaris,
974     /// as they have a different set of linker flags. Defaults to false.
975     pub is_like_solaris: bool,
976     /// Whether the target is like Windows.
977     /// This is a combination of several more specific properties represented as a single flag:
978     ///   - The target uses a Windows ABI,
979     ///   - uses PE/COFF as a format for object code,
980     ///   - uses Windows-style dllexport/dllimport for shared libraries,
981     ///   - uses import libraries and .def files for symbol exports,
982     ///   - executables support setting a subsystem.
983     pub is_like_windows: bool,
984     /// Whether the target is like MSVC.
985     /// This is a combination of several more specific properties represented as a single flag:
986     ///   - The target has all the properties from `is_like_windows`
987     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
988     ///   - has some MSVC-specific Windows ABI properties,
989     ///   - uses a link.exe-like linker,
990     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
991     ///   - uses SEH-based unwinding,
992     ///   - supports control flow guard mechanism.
993     pub is_like_msvc: bool,
994     /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
995     /// Emscripten toolchain.
996     /// Defaults to false.
997     pub is_like_emscripten: bool,
998     /// Whether the target toolchain is like Fuchsia's.
999     pub is_like_fuchsia: bool,
1000     /// Version of DWARF to use if not using the default.
1001     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1002     pub dwarf_version: Option<u32>,
1003     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
1004     pub linker_is_gnu: bool,
1005     /// The MinGW toolchain has a known issue that prevents it from correctly
1006     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1007     /// symbol needs its own COMDAT section, weak linkage implies a large
1008     /// number sections that easily exceeds the given limit for larger
1009     /// codebases. Consequently we want a way to disallow weak linkage on some
1010     /// platforms.
1011     pub allows_weak_linkage: bool,
1012     /// Whether the linker support rpaths or not. Defaults to false.
1013     pub has_rpath: bool,
1014     /// Whether to disable linking to the default libraries, typically corresponds
1015     /// to `-nodefaultlibs`. Defaults to true.
1016     pub no_default_libraries: bool,
1017     /// Dynamically linked executables can be compiled as position independent
1018     /// if the default relocation model of position independent code is not
1019     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1020     /// the functions in the executable are not randomized and can be used
1021     /// during an exploit of a vulnerability in any code.
1022     pub position_independent_executables: bool,
1023     /// Executables that are both statically linked and position-independent are supported.
1024     pub static_position_independent_executables: bool,
1025     /// Determines if the target always requires using the PLT for indirect
1026     /// library calls or not. This controls the default value of the `-Z plt` flag.
1027     pub needs_plt: bool,
1028     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1029     /// resolve all symbols at startup and marks the GOT read-only before
1030     /// starting the program, preventing overwriting the GOT.
1031     pub relro_level: RelroLevel,
1032     /// Format that archives should be emitted in. This affects whether we use
1033     /// LLVM to assemble an archive or fall back to the system linker, and
1034     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1035     /// the system linker to be used.
1036     pub archive_format: String,
1037     /// Is asm!() allowed? Defaults to true.
1038     pub allow_asm: bool,
1039     /// Whether the runtime startup code requires the `main` function be passed
1040     /// `argc` and `argv` values.
1041     pub main_needs_argc_argv: bool,
1042
1043     /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
1044     /// this target.
1045     pub has_elf_tls: bool,
1046     // This is mainly for easy compatibility with emscripten.
1047     // If we give emcc .o files that are actually .bc files it
1048     // will 'just work'.
1049     pub obj_is_bitcode: bool,
1050     /// Whether the target requires that emitted object code includes bitcode.
1051     pub forces_embed_bitcode: bool,
1052     /// Content of the LLVM cmdline section associated with embedded bitcode.
1053     pub bitcode_llvm_cmdline: String,
1054
1055     /// Don't use this field; instead use the `.min_atomic_width()` method.
1056     pub min_atomic_width: Option<u64>,
1057
1058     /// Don't use this field; instead use the `.max_atomic_width()` method.
1059     pub max_atomic_width: Option<u64>,
1060
1061     /// Whether the target supports atomic CAS operations natively
1062     pub atomic_cas: bool,
1063
1064     /// Panic strategy: "unwind" or "abort"
1065     pub panic_strategy: PanicStrategy,
1066
1067     /// A list of ABIs unsupported by the current target. Note that generic ABIs
1068     /// are considered to be supported on all platforms and cannot be marked
1069     /// unsupported.
1070     pub unsupported_abis: Vec<Abi>,
1071
1072     /// Whether or not linking dylibs to a static CRT is allowed.
1073     pub crt_static_allows_dylibs: bool,
1074     /// Whether or not the CRT is statically linked by default.
1075     pub crt_static_default: bool,
1076     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1077     pub crt_static_respected: bool,
1078
1079     /// The implementation of stack probes to use.
1080     pub stack_probes: StackProbeType,
1081
1082     /// The minimum alignment for global symbols.
1083     pub min_global_align: Option<u64>,
1084
1085     /// Default number of codegen units to use in debug mode
1086     pub default_codegen_units: Option<u64>,
1087
1088     /// Whether to generate trap instructions in places where optimization would
1089     /// otherwise produce control flow that falls through into unrelated memory.
1090     pub trap_unreachable: bool,
1091
1092     /// This target requires everything to be compiled with LTO to emit a final
1093     /// executable, aka there is no native linker for this target.
1094     pub requires_lto: bool,
1095
1096     /// This target has no support for threads.
1097     pub singlethread: bool,
1098
1099     /// Whether library functions call lowering/optimization is disabled in LLVM
1100     /// for this target unconditionally.
1101     pub no_builtins: bool,
1102
1103     /// The default visibility for symbols in this target should be "hidden"
1104     /// rather than "default"
1105     pub default_hidden_visibility: bool,
1106
1107     /// Whether a .debug_gdb_scripts section will be added to the output object file
1108     pub emit_debug_gdb_scripts: bool,
1109
1110     /// Whether or not to unconditionally `uwtable` attributes on functions,
1111     /// typically because the platform needs to unwind for things like stack
1112     /// unwinders.
1113     pub requires_uwtable: bool,
1114
1115     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1116     /// is not specified and `uwtable` is not required on this target.
1117     pub default_uwtable: bool,
1118
1119     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1120     /// typically required if a target can be compiled with a mixed set of
1121     /// target features. This is `true` by default, and `false` for targets like
1122     /// wasm32 where the whole program either has simd or not.
1123     pub simd_types_indirect: bool,
1124
1125     /// Pass a list of symbol which should be exported in the dylib to the linker.
1126     pub limit_rdylib_exports: bool,
1127
1128     /// If set, have the linker export exactly these symbols, instead of using
1129     /// the usual logic to figure this out from the crate itself.
1130     pub override_export_symbols: Option<Vec<String>>,
1131
1132     /// Determines how or whether the MergeFunctions LLVM pass should run for
1133     /// this target. Either "disabled", "trampolines", or "aliases".
1134     /// The MergeFunctions pass is generally useful, but some targets may need
1135     /// to opt out. The default is "aliases".
1136     ///
1137     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1138     pub merge_functions: MergeFunctions,
1139
1140     /// Use platform dependent mcount function
1141     pub mcount: String,
1142
1143     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1144     pub llvm_abiname: String,
1145
1146     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1147     pub relax_elf_relocations: bool,
1148
1149     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1150     pub llvm_args: Vec<String>,
1151
1152     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1153     /// to false (uses .init_array).
1154     pub use_ctors_section: bool,
1155
1156     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1157     /// used to locate unwinding information is passed
1158     /// (only has effect if the linker is `ld`-like).
1159     pub eh_frame_header: bool,
1160
1161     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1162     /// thumb and arm interworking.
1163     pub has_thumb_interworking: bool,
1164
1165     /// How to handle split debug information, if at all. Specifying `None` has
1166     /// target-specific meaning.
1167     pub split_debuginfo: SplitDebuginfo,
1168 }
1169
1170 impl Default for TargetOptions {
1171     /// Creates a set of "sane defaults" for any target. This is still
1172     /// incomplete, and if used for compilation, will certainly not work.
1173     fn default() -> TargetOptions {
1174         TargetOptions {
1175             is_builtin: false,
1176             endian: Endian::Little,
1177             c_int_width: "32".to_string(),
1178             os: "none".to_string(),
1179             env: String::new(),
1180             vendor: "unknown".to_string(),
1181             linker_flavor: LinkerFlavor::Gcc,
1182             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1183             lld_flavor: LldFlavor::Ld,
1184             pre_link_args: LinkArgs::new(),
1185             post_link_args: LinkArgs::new(),
1186             link_script: None,
1187             asm_args: Vec::new(),
1188             cpu: "generic".to_string(),
1189             features: String::new(),
1190             dynamic_linking: false,
1191             only_cdylib: false,
1192             executables: false,
1193             relocation_model: RelocModel::Pic,
1194             code_model: None,
1195             tls_model: TlsModel::GeneralDynamic,
1196             disable_redzone: false,
1197             eliminate_frame_pointer: true,
1198             function_sections: true,
1199             dll_prefix: "lib".to_string(),
1200             dll_suffix: ".so".to_string(),
1201             exe_suffix: String::new(),
1202             staticlib_prefix: "lib".to_string(),
1203             staticlib_suffix: ".a".to_string(),
1204             os_family: None,
1205             abi_return_struct_as_int: false,
1206             is_like_osx: false,
1207             is_like_solaris: false,
1208             is_like_windows: false,
1209             is_like_emscripten: false,
1210             is_like_msvc: false,
1211             is_like_fuchsia: false,
1212             dwarf_version: None,
1213             linker_is_gnu: false,
1214             allows_weak_linkage: true,
1215             has_rpath: false,
1216             no_default_libraries: true,
1217             position_independent_executables: false,
1218             static_position_independent_executables: false,
1219             needs_plt: false,
1220             relro_level: RelroLevel::None,
1221             pre_link_objects: Default::default(),
1222             post_link_objects: Default::default(),
1223             pre_link_objects_fallback: Default::default(),
1224             post_link_objects_fallback: Default::default(),
1225             crt_objects_fallback: None,
1226             late_link_args: LinkArgs::new(),
1227             late_link_args_dynamic: LinkArgs::new(),
1228             late_link_args_static: LinkArgs::new(),
1229             link_env: Vec::new(),
1230             link_env_remove: Vec::new(),
1231             archive_format: "gnu".to_string(),
1232             main_needs_argc_argv: true,
1233             allow_asm: true,
1234             has_elf_tls: false,
1235             obj_is_bitcode: false,
1236             forces_embed_bitcode: false,
1237             bitcode_llvm_cmdline: String::new(),
1238             min_atomic_width: None,
1239             max_atomic_width: None,
1240             atomic_cas: true,
1241             panic_strategy: PanicStrategy::Unwind,
1242             unsupported_abis: vec![],
1243             crt_static_allows_dylibs: false,
1244             crt_static_default: false,
1245             crt_static_respected: false,
1246             stack_probes: StackProbeType::None,
1247             min_global_align: None,
1248             default_codegen_units: None,
1249             trap_unreachable: true,
1250             requires_lto: false,
1251             singlethread: false,
1252             no_builtins: false,
1253             default_hidden_visibility: false,
1254             emit_debug_gdb_scripts: true,
1255             requires_uwtable: false,
1256             default_uwtable: false,
1257             simd_types_indirect: true,
1258             limit_rdylib_exports: true,
1259             override_export_symbols: None,
1260             merge_functions: MergeFunctions::Aliases,
1261             mcount: "mcount".to_string(),
1262             llvm_abiname: "".to_string(),
1263             relax_elf_relocations: false,
1264             llvm_args: vec![],
1265             use_ctors_section: false,
1266             eh_frame_header: true,
1267             has_thumb_interworking: false,
1268             split_debuginfo: SplitDebuginfo::Off,
1269         }
1270     }
1271 }
1272
1273 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1274 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1275 /// this `Deref` implementation is no longer necessary.
1276 impl Deref for Target {
1277     type Target = TargetOptions;
1278
1279     fn deref(&self) -> &Self::Target {
1280         &self.options
1281     }
1282 }
1283 impl DerefMut for Target {
1284     fn deref_mut(&mut self) -> &mut Self::Target {
1285         &mut self.options
1286     }
1287 }
1288
1289 impl Target {
1290     /// Given a function ABI, turn it into the correct ABI for this target.
1291     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1292         match abi {
1293             Abi::System { unwind } => {
1294                 if self.is_like_windows && self.arch == "x86" {
1295                     Abi::Stdcall { unwind }
1296                 } else {
1297                     Abi::C { unwind }
1298                 }
1299             }
1300             // These ABI kinds are ignored on non-x86 Windows targets.
1301             // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1302             // and the individual pages for __stdcall et al.
1303             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => {
1304                 if self.is_like_windows && self.arch != "x86" { Abi::C { unwind } } else { abi }
1305             }
1306             Abi::Fastcall | Abi::Vectorcall => {
1307                 if self.is_like_windows && self.arch != "x86" {
1308                     Abi::C { unwind: false }
1309                 } else {
1310                     abi
1311                 }
1312             }
1313             Abi::EfiApi => {
1314                 if self.arch == "x86_64" {
1315                     Abi::Win64
1316                 } else {
1317                     Abi::C { unwind: false }
1318                 }
1319             }
1320             abi => abi,
1321         }
1322     }
1323
1324     /// Minimum integer size in bits that this target can perform atomic
1325     /// operations on.
1326     pub fn min_atomic_width(&self) -> u64 {
1327         self.min_atomic_width.unwrap_or(8)
1328     }
1329
1330     /// Maximum integer size in bits that this target can perform atomic
1331     /// operations on.
1332     pub fn max_atomic_width(&self) -> u64 {
1333         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1334     }
1335
1336     pub fn is_abi_supported(&self, abi: Abi) -> bool {
1337         abi.generic() || !self.unsupported_abis.contains(&abi)
1338     }
1339
1340     /// Loads a target descriptor from a JSON object.
1341     pub fn from_json(obj: Json) -> Result<Target, String> {
1342         // While ugly, this code must remain this way to retain
1343         // compatibility with existing JSON fields and the internal
1344         // expected naming of the Target and TargetOptions structs.
1345         // To ensure compatibility is retained, the built-in targets
1346         // are round-tripped through this code to catch cases where
1347         // the JSON parser is not updated to match the structs.
1348
1349         let get_req_field = |name: &str| {
1350             obj.find(name)
1351                 .map(|s| s.as_string())
1352                 .and_then(|os| os.map(|s| s.to_string()))
1353                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1354         };
1355
1356         let mut base = Target {
1357             llvm_target: get_req_field("llvm-target")?,
1358             pointer_width: get_req_field("target-pointer-width")?
1359                 .parse::<u32>()
1360                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1361             data_layout: get_req_field("data-layout")?,
1362             arch: get_req_field("arch")?,
1363             options: Default::default(),
1364         };
1365
1366         macro_rules! key {
1367             ($key_name:ident) => ( {
1368                 let name = (stringify!($key_name)).replace("_", "-");
1369                 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1370                     base.$key_name = s.to_string();
1371                 }
1372             } );
1373             ($key_name:ident = $json_name:expr) => ( {
1374                 let name = $json_name;
1375                 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1376                     base.$key_name = s.to_string();
1377                 }
1378             } );
1379             ($key_name:ident, bool) => ( {
1380                 let name = (stringify!($key_name)).replace("_", "-");
1381                 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
1382                     base.$key_name = s;
1383                 }
1384             } );
1385             ($key_name:ident, Option<u32>) => ( {
1386                 let name = (stringify!($key_name)).replace("_", "-");
1387                 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1388                     if s < 1 || s > 5 {
1389                         return Err("Not a valid DWARF version number".to_string());
1390                     }
1391                     base.$key_name = Some(s as u32);
1392                 }
1393             } );
1394             ($key_name:ident, Option<u64>) => ( {
1395                 let name = (stringify!($key_name)).replace("_", "-");
1396                 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1397                     base.$key_name = Some(s);
1398                 }
1399             } );
1400             ($key_name:ident, MergeFunctions) => ( {
1401                 let name = (stringify!($key_name)).replace("_", "-");
1402                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1403                     match s.parse::<MergeFunctions>() {
1404                         Ok(mergefunc) => base.$key_name = mergefunc,
1405                         _ => return Some(Err(format!("'{}' is not a valid value for \
1406                                                       merge-functions. Use 'disabled', \
1407                                                       'trampolines', or 'aliases'.",
1408                                                       s))),
1409                     }
1410                     Some(Ok(()))
1411                 })).unwrap_or(Ok(()))
1412             } );
1413             ($key_name:ident, RelocModel) => ( {
1414                 let name = (stringify!($key_name)).replace("_", "-");
1415                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1416                     match s.parse::<RelocModel>() {
1417                         Ok(relocation_model) => base.$key_name = relocation_model,
1418                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1419                                                       Run `rustc --print relocation-models` to \
1420                                                       see the list of supported values.", s))),
1421                     }
1422                     Some(Ok(()))
1423                 })).unwrap_or(Ok(()))
1424             } );
1425             ($key_name:ident, CodeModel) => ( {
1426                 let name = (stringify!($key_name)).replace("_", "-");
1427                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1428                     match s.parse::<CodeModel>() {
1429                         Ok(code_model) => base.$key_name = Some(code_model),
1430                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1431                                                       Run `rustc --print code-models` to \
1432                                                       see the list of supported values.", s))),
1433                     }
1434                     Some(Ok(()))
1435                 })).unwrap_or(Ok(()))
1436             } );
1437             ($key_name:ident, TlsModel) => ( {
1438                 let name = (stringify!($key_name)).replace("_", "-");
1439                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1440                     match s.parse::<TlsModel>() {
1441                         Ok(tls_model) => base.$key_name = tls_model,
1442                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1443                                                       Run `rustc --print tls-models` to \
1444                                                       see the list of supported values.", s))),
1445                     }
1446                     Some(Ok(()))
1447                 })).unwrap_or(Ok(()))
1448             } );
1449             ($key_name:ident, PanicStrategy) => ( {
1450                 let name = (stringify!($key_name)).replace("_", "-");
1451                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1452                     match s {
1453                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1454                         "abort" => base.$key_name = PanicStrategy::Abort,
1455                         _ => return Some(Err(format!("'{}' is not a valid value for \
1456                                                       panic-strategy. Use 'unwind' or 'abort'.",
1457                                                      s))),
1458                 }
1459                 Some(Ok(()))
1460             })).unwrap_or(Ok(()))
1461             } );
1462             ($key_name:ident, RelroLevel) => ( {
1463                 let name = (stringify!($key_name)).replace("_", "-");
1464                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1465                     match s.parse::<RelroLevel>() {
1466                         Ok(level) => base.$key_name = level,
1467                         _ => return Some(Err(format!("'{}' is not a valid value for \
1468                                                       relro-level. Use 'full', 'partial, or 'off'.",
1469                                                       s))),
1470                     }
1471                     Some(Ok(()))
1472                 })).unwrap_or(Ok(()))
1473             } );
1474             ($key_name:ident, SplitDebuginfo) => ( {
1475                 let name = (stringify!($key_name)).replace("_", "-");
1476                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1477                     match s.parse::<SplitDebuginfo>() {
1478                         Ok(level) => base.$key_name = level,
1479                         _ => return Some(Err(format!("'{}' is not a valid value for \
1480                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
1481                                                       s))),
1482                     }
1483                     Some(Ok(()))
1484                 })).unwrap_or(Ok(()))
1485             } );
1486             ($key_name:ident, list) => ( {
1487                 let name = (stringify!($key_name)).replace("_", "-");
1488                 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1489                     base.$key_name = v.iter()
1490                         .map(|a| a.as_string().unwrap().to_string())
1491                         .collect();
1492                 }
1493             } );
1494             ($key_name:ident, opt_list) => ( {
1495                 let name = (stringify!($key_name)).replace("_", "-");
1496                 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1497                     base.$key_name = Some(v.iter()
1498                         .map(|a| a.as_string().unwrap().to_string())
1499                         .collect());
1500                 }
1501             } );
1502             ($key_name:ident, optional) => ( {
1503                 let name = (stringify!($key_name)).replace("_", "-");
1504                 if let Some(o) = obj.find(&name[..]) {
1505                     base.$key_name = o
1506                         .as_string()
1507                         .map(|s| s.to_string() );
1508                 }
1509             } );
1510             ($key_name:ident = $json_name:expr, optional) => ( {
1511                 let name = $json_name;
1512                 if let Some(o) = obj.find(name) {
1513                     base.$key_name = o
1514                         .as_string()
1515                         .map(|s| s.to_string() );
1516                 }
1517             } );
1518             ($key_name:ident, LldFlavor) => ( {
1519                 let name = (stringify!($key_name)).replace("_", "-");
1520                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1521                     if let Some(flavor) = LldFlavor::from_str(&s) {
1522                         base.$key_name = flavor;
1523                     } else {
1524                         return Some(Err(format!(
1525                             "'{}' is not a valid value for lld-flavor. \
1526                              Use 'darwin', 'gnu', 'link' or 'wasm.",
1527                             s)))
1528                     }
1529                     Some(Ok(()))
1530                 })).unwrap_or(Ok(()))
1531             } );
1532             ($key_name:ident, LinkerFlavor) => ( {
1533                 let name = (stringify!($key_name)).replace("_", "-");
1534                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1535                     match LinkerFlavor::from_str(s) {
1536                         Some(linker_flavor) => base.$key_name = linker_flavor,
1537                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1538                                                       Use {}", s, LinkerFlavor::one_of()))),
1539                     }
1540                     Some(Ok(()))
1541                 })).unwrap_or(Ok(()))
1542             } );
1543             ($key_name:ident, StackProbeType) => ( {
1544                 let name = (stringify!($key_name)).replace("_", "-");
1545                 obj.find(&name[..]).and_then(|o| match StackProbeType::from_json(o) {
1546                     Ok(v) => {
1547                         base.$key_name = v;
1548                         Some(Ok(()))
1549                     },
1550                     Err(s) => Some(Err(
1551                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1552                     )),
1553                 }).unwrap_or(Ok(()))
1554             } );
1555             ($key_name:ident, crt_objects_fallback) => ( {
1556                 let name = (stringify!($key_name)).replace("_", "-");
1557                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1558                     match s.parse::<CrtObjectsFallback>() {
1559                         Ok(fallback) => base.$key_name = Some(fallback),
1560                         _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1561                                                       Use 'musl', 'mingw' or 'wasm'", s))),
1562                     }
1563                     Some(Ok(()))
1564                 })).unwrap_or(Ok(()))
1565             } );
1566             ($key_name:ident, link_objects) => ( {
1567                 let name = (stringify!($key_name)).replace("_", "-");
1568                 if let Some(val) = obj.find(&name[..]) {
1569                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1570                         JSON object with fields per CRT object kind.", name))?;
1571                     let mut args = CrtObjects::new();
1572                     for (k, v) in obj {
1573                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1574                             format!("{}: '{}' is not a valid value for CRT object kind. \
1575                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
1576                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1577                         })?;
1578
1579                         let v = v.as_array().ok_or_else(||
1580                             format!("{}.{}: expected a JSON array", name, k)
1581                         )?.iter().enumerate()
1582                             .map(|(i,s)| {
1583                                 let s = s.as_string().ok_or_else(||
1584                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1585                                 Ok(s.to_owned())
1586                             })
1587                             .collect::<Result<Vec<_>, String>>()?;
1588
1589                         args.insert(kind, v);
1590                     }
1591                     base.$key_name = args;
1592                 }
1593             } );
1594             ($key_name:ident, link_args) => ( {
1595                 let name = (stringify!($key_name)).replace("_", "-");
1596                 if let Some(val) = obj.find(&name[..]) {
1597                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1598                         JSON object with fields per linker-flavor.", name))?;
1599                     let mut args = LinkArgs::new();
1600                     for (k, v) in obj {
1601                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1602                             format!("{}: '{}' is not a valid value for linker-flavor. \
1603                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1604                         })?;
1605
1606                         let v = v.as_array().ok_or_else(||
1607                             format!("{}.{}: expected a JSON array", name, k)
1608                         )?.iter().enumerate()
1609                             .map(|(i,s)| {
1610                                 let s = s.as_string().ok_or_else(||
1611                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1612                                 Ok(s.to_owned())
1613                             })
1614                             .collect::<Result<Vec<_>, String>>()?;
1615
1616                         args.insert(flavor, v);
1617                     }
1618                     base.$key_name = args;
1619                 }
1620             } );
1621             ($key_name:ident, env) => ( {
1622                 let name = (stringify!($key_name)).replace("_", "-");
1623                 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1624                     for o in a {
1625                         if let Some(s) = o.as_string() {
1626                             let p = s.split('=').collect::<Vec<_>>();
1627                             if p.len() == 2 {
1628                                 let k = p[0].to_string();
1629                                 let v = p[1].to_string();
1630                                 base.$key_name.push((k, v));
1631                             }
1632                         }
1633                     }
1634                 }
1635             } );
1636         }
1637
1638         if let Some(s) = obj.find("target-endian").and_then(Json::as_string) {
1639             base.endian = s.parse()?;
1640         }
1641         key!(is_builtin, bool);
1642         key!(c_int_width = "target-c-int-width");
1643         key!(os);
1644         key!(env);
1645         key!(vendor);
1646         key!(linker_flavor, LinkerFlavor)?;
1647         key!(linker, optional);
1648         key!(lld_flavor, LldFlavor)?;
1649         key!(pre_link_objects, link_objects);
1650         key!(post_link_objects, link_objects);
1651         key!(pre_link_objects_fallback, link_objects);
1652         key!(post_link_objects_fallback, link_objects);
1653         key!(crt_objects_fallback, crt_objects_fallback)?;
1654         key!(pre_link_args, link_args);
1655         key!(late_link_args, link_args);
1656         key!(late_link_args_dynamic, link_args);
1657         key!(late_link_args_static, link_args);
1658         key!(post_link_args, link_args);
1659         key!(link_script, optional);
1660         key!(link_env, env);
1661         key!(link_env_remove, list);
1662         key!(asm_args, list);
1663         key!(cpu);
1664         key!(features);
1665         key!(dynamic_linking, bool);
1666         key!(only_cdylib, bool);
1667         key!(executables, bool);
1668         key!(relocation_model, RelocModel)?;
1669         key!(code_model, CodeModel)?;
1670         key!(tls_model, TlsModel)?;
1671         key!(disable_redzone, bool);
1672         key!(eliminate_frame_pointer, bool);
1673         key!(function_sections, bool);
1674         key!(dll_prefix);
1675         key!(dll_suffix);
1676         key!(exe_suffix);
1677         key!(staticlib_prefix);
1678         key!(staticlib_suffix);
1679         key!(os_family = "target-family", optional);
1680         key!(abi_return_struct_as_int, bool);
1681         key!(is_like_osx, bool);
1682         key!(is_like_solaris, bool);
1683         key!(is_like_windows, bool);
1684         key!(is_like_msvc, bool);
1685         key!(is_like_emscripten, bool);
1686         key!(is_like_fuchsia, bool);
1687         key!(dwarf_version, Option<u32>);
1688         key!(linker_is_gnu, bool);
1689         key!(allows_weak_linkage, bool);
1690         key!(has_rpath, bool);
1691         key!(no_default_libraries, bool);
1692         key!(position_independent_executables, bool);
1693         key!(static_position_independent_executables, bool);
1694         key!(needs_plt, bool);
1695         key!(relro_level, RelroLevel)?;
1696         key!(archive_format);
1697         key!(allow_asm, bool);
1698         key!(main_needs_argc_argv, bool);
1699         key!(has_elf_tls, bool);
1700         key!(obj_is_bitcode, bool);
1701         key!(forces_embed_bitcode, bool);
1702         key!(bitcode_llvm_cmdline);
1703         key!(max_atomic_width, Option<u64>);
1704         key!(min_atomic_width, Option<u64>);
1705         key!(atomic_cas, bool);
1706         key!(panic_strategy, PanicStrategy)?;
1707         key!(crt_static_allows_dylibs, bool);
1708         key!(crt_static_default, bool);
1709         key!(crt_static_respected, bool);
1710         key!(stack_probes, StackProbeType)?;
1711         key!(min_global_align, Option<u64>);
1712         key!(default_codegen_units, Option<u64>);
1713         key!(trap_unreachable, bool);
1714         key!(requires_lto, bool);
1715         key!(singlethread, bool);
1716         key!(no_builtins, bool);
1717         key!(default_hidden_visibility, bool);
1718         key!(emit_debug_gdb_scripts, bool);
1719         key!(requires_uwtable, bool);
1720         key!(default_uwtable, bool);
1721         key!(simd_types_indirect, bool);
1722         key!(limit_rdylib_exports, bool);
1723         key!(override_export_symbols, opt_list);
1724         key!(merge_functions, MergeFunctions)?;
1725         key!(mcount = "target-mcount");
1726         key!(llvm_abiname);
1727         key!(relax_elf_relocations, bool);
1728         key!(llvm_args, list);
1729         key!(use_ctors_section, bool);
1730         key!(eh_frame_header, bool);
1731         key!(has_thumb_interworking, bool);
1732         key!(split_debuginfo, SplitDebuginfo)?;
1733
1734         // NB: The old name is deprecated, but support for it is retained for
1735         // compatibility.
1736         for name in ["abi-blacklist", "unsupported-abis"].iter() {
1737             if let Some(array) = obj.find(name).and_then(Json::as_array) {
1738                 for name in array.iter().filter_map(|abi| abi.as_string()) {
1739                     match lookup_abi(name) {
1740                         Some(abi) => {
1741                             if abi.generic() {
1742                                 return Err(format!(
1743                                     "The ABI \"{}\" is considered to be supported on all \
1744                                     targets and cannot be marked unsupported",
1745                                     abi
1746                                 ));
1747                             }
1748
1749                             base.unsupported_abis.push(abi)
1750                         }
1751                         None => {
1752                             return Err(format!(
1753                                 "Unknown ABI \"{}\" in target specification",
1754                                 name
1755                             ));
1756                         }
1757                     }
1758                 }
1759             }
1760         }
1761
1762         Ok(base)
1763     }
1764
1765     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1766     /// triple. Note that it could also just be a bare filename already, so also
1767     /// check for that. If one of the hardcoded targets we know about, just
1768     /// return it directly.
1769     ///
1770     /// The error string could come from any of the APIs called, including
1771     /// filesystem access and JSON decoding.
1772     pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1773         use rustc_serialize::json;
1774         use std::env;
1775         use std::fs;
1776
1777         fn load_file(path: &Path) -> Result<Target, String> {
1778             let contents = fs::read(path).map_err(|e| e.to_string())?;
1779             let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1780             Target::from_json(obj)
1781         }
1782
1783         match *target_triple {
1784             TargetTriple::TargetTriple(ref target_triple) => {
1785                 // check if triple is in list of built-in targets
1786                 if let Some(t) = load_builtin(target_triple) {
1787                     return Ok(t);
1788                 }
1789
1790                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1791                 let path = {
1792                     let mut target = target_triple.to_string();
1793                     target.push_str(".json");
1794                     PathBuf::from(target)
1795                 };
1796
1797                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1798
1799                 // FIXME 16351: add a sane default search path?
1800
1801                 for dir in env::split_paths(&target_path) {
1802                     let p = dir.join(&path);
1803                     if p.is_file() {
1804                         return load_file(&p);
1805                     }
1806                 }
1807                 Err(format!("Could not find specification for target {:?}", target_triple))
1808             }
1809             TargetTriple::TargetPath(ref target_path) => {
1810                 if target_path.is_file() {
1811                     return load_file(&target_path);
1812                 }
1813                 Err(format!("Target path {:?} is not a valid file", target_path))
1814             }
1815         }
1816     }
1817 }
1818
1819 impl ToJson for Target {
1820     fn to_json(&self) -> Json {
1821         let mut d = BTreeMap::new();
1822         let default: TargetOptions = Default::default();
1823
1824         macro_rules! target_val {
1825             ($attr:ident) => {{
1826                 let name = (stringify!($attr)).replace("_", "-");
1827                 d.insert(name, self.$attr.to_json());
1828             }};
1829             ($attr:ident, $key_name:expr) => {{
1830                 let name = $key_name;
1831                 d.insert(name.to_string(), self.$attr.to_json());
1832             }};
1833         }
1834
1835         macro_rules! target_option_val {
1836             ($attr:ident) => {{
1837                 let name = (stringify!($attr)).replace("_", "-");
1838                 if default.$attr != self.$attr {
1839                     d.insert(name, self.$attr.to_json());
1840                 }
1841             }};
1842             ($attr:ident, $key_name:expr) => {{
1843                 let name = $key_name;
1844                 if default.$attr != self.$attr {
1845                     d.insert(name.to_string(), self.$attr.to_json());
1846                 }
1847             }};
1848             (link_args - $attr:ident) => {{
1849                 let name = (stringify!($attr)).replace("_", "-");
1850                 if default.$attr != self.$attr {
1851                     let obj = self
1852                         .$attr
1853                         .iter()
1854                         .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1855                         .collect::<BTreeMap<_, _>>();
1856                     d.insert(name, obj.to_json());
1857                 }
1858             }};
1859             (env - $attr:ident) => {{
1860                 let name = (stringify!($attr)).replace("_", "-");
1861                 if default.$attr != self.$attr {
1862                     let obj = self
1863                         .$attr
1864                         .iter()
1865                         .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1866                         .collect::<Vec<_>>();
1867                     d.insert(name, obj.to_json());
1868                 }
1869             }};
1870         }
1871
1872         target_val!(llvm_target);
1873         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
1874         target_val!(arch);
1875         target_val!(data_layout);
1876
1877         target_option_val!(is_builtin);
1878         target_option_val!(endian, "target-endian");
1879         target_option_val!(c_int_width, "target-c-int-width");
1880         target_option_val!(os);
1881         target_option_val!(env);
1882         target_option_val!(vendor);
1883         target_option_val!(linker_flavor);
1884         target_option_val!(linker);
1885         target_option_val!(lld_flavor);
1886         target_option_val!(pre_link_objects);
1887         target_option_val!(post_link_objects);
1888         target_option_val!(pre_link_objects_fallback);
1889         target_option_val!(post_link_objects_fallback);
1890         target_option_val!(crt_objects_fallback);
1891         target_option_val!(link_args - pre_link_args);
1892         target_option_val!(link_args - late_link_args);
1893         target_option_val!(link_args - late_link_args_dynamic);
1894         target_option_val!(link_args - late_link_args_static);
1895         target_option_val!(link_args - post_link_args);
1896         target_option_val!(link_script);
1897         target_option_val!(env - link_env);
1898         target_option_val!(link_env_remove);
1899         target_option_val!(asm_args);
1900         target_option_val!(cpu);
1901         target_option_val!(features);
1902         target_option_val!(dynamic_linking);
1903         target_option_val!(only_cdylib);
1904         target_option_val!(executables);
1905         target_option_val!(relocation_model);
1906         target_option_val!(code_model);
1907         target_option_val!(tls_model);
1908         target_option_val!(disable_redzone);
1909         target_option_val!(eliminate_frame_pointer);
1910         target_option_val!(function_sections);
1911         target_option_val!(dll_prefix);
1912         target_option_val!(dll_suffix);
1913         target_option_val!(exe_suffix);
1914         target_option_val!(staticlib_prefix);
1915         target_option_val!(staticlib_suffix);
1916         target_option_val!(os_family, "target-family");
1917         target_option_val!(abi_return_struct_as_int);
1918         target_option_val!(is_like_osx);
1919         target_option_val!(is_like_solaris);
1920         target_option_val!(is_like_windows);
1921         target_option_val!(is_like_msvc);
1922         target_option_val!(is_like_emscripten);
1923         target_option_val!(is_like_fuchsia);
1924         target_option_val!(dwarf_version);
1925         target_option_val!(linker_is_gnu);
1926         target_option_val!(allows_weak_linkage);
1927         target_option_val!(has_rpath);
1928         target_option_val!(no_default_libraries);
1929         target_option_val!(position_independent_executables);
1930         target_option_val!(static_position_independent_executables);
1931         target_option_val!(needs_plt);
1932         target_option_val!(relro_level);
1933         target_option_val!(archive_format);
1934         target_option_val!(allow_asm);
1935         target_option_val!(main_needs_argc_argv);
1936         target_option_val!(has_elf_tls);
1937         target_option_val!(obj_is_bitcode);
1938         target_option_val!(forces_embed_bitcode);
1939         target_option_val!(bitcode_llvm_cmdline);
1940         target_option_val!(min_atomic_width);
1941         target_option_val!(max_atomic_width);
1942         target_option_val!(atomic_cas);
1943         target_option_val!(panic_strategy);
1944         target_option_val!(crt_static_allows_dylibs);
1945         target_option_val!(crt_static_default);
1946         target_option_val!(crt_static_respected);
1947         target_option_val!(stack_probes);
1948         target_option_val!(min_global_align);
1949         target_option_val!(default_codegen_units);
1950         target_option_val!(trap_unreachable);
1951         target_option_val!(requires_lto);
1952         target_option_val!(singlethread);
1953         target_option_val!(no_builtins);
1954         target_option_val!(default_hidden_visibility);
1955         target_option_val!(emit_debug_gdb_scripts);
1956         target_option_val!(requires_uwtable);
1957         target_option_val!(default_uwtable);
1958         target_option_val!(simd_types_indirect);
1959         target_option_val!(limit_rdylib_exports);
1960         target_option_val!(override_export_symbols);
1961         target_option_val!(merge_functions);
1962         target_option_val!(mcount, "target-mcount");
1963         target_option_val!(llvm_abiname);
1964         target_option_val!(relax_elf_relocations);
1965         target_option_val!(llvm_args);
1966         target_option_val!(use_ctors_section);
1967         target_option_val!(eh_frame_header);
1968         target_option_val!(has_thumb_interworking);
1969         target_option_val!(split_debuginfo);
1970
1971         if default.unsupported_abis != self.unsupported_abis {
1972             d.insert(
1973                 "unsupported-abis".to_string(),
1974                 self.unsupported_abis
1975                     .iter()
1976                     .map(|&name| Abi::name(name).to_json())
1977                     .collect::<Vec<_>>()
1978                     .to_json(),
1979             );
1980         }
1981
1982         Json::Object(d)
1983     }
1984 }
1985
1986 /// Either a target triple string or a path to a JSON file.
1987 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
1988 pub enum TargetTriple {
1989     TargetTriple(String),
1990     TargetPath(PathBuf),
1991 }
1992
1993 impl TargetTriple {
1994     /// Creates a target triple from the passed target triple string.
1995     pub fn from_triple(triple: &str) -> Self {
1996         TargetTriple::TargetTriple(triple.to_string())
1997     }
1998
1999     /// Creates a target triple from the passed target path.
2000     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2001         let canonicalized_path = path.canonicalize()?;
2002         Ok(TargetTriple::TargetPath(canonicalized_path))
2003     }
2004
2005     /// Returns a string triple for this target.
2006     ///
2007     /// If this target is a path, the file name (without extension) is returned.
2008     pub fn triple(&self) -> &str {
2009         match *self {
2010             TargetTriple::TargetTriple(ref triple) => triple,
2011             TargetTriple::TargetPath(ref path) => path
2012                 .file_stem()
2013                 .expect("target path must not be empty")
2014                 .to_str()
2015                 .expect("target path must be valid unicode"),
2016         }
2017     }
2018
2019     /// Returns an extended string triple for this target.
2020     ///
2021     /// If this target is a path, a hash of the path is appended to the triple returned
2022     /// by `triple()`.
2023     pub fn debug_triple(&self) -> String {
2024         use std::collections::hash_map::DefaultHasher;
2025         use std::hash::{Hash, Hasher};
2026
2027         let triple = self.triple();
2028         if let TargetTriple::TargetPath(ref path) = *self {
2029             let mut hasher = DefaultHasher::new();
2030             path.hash(&mut hasher);
2031             let hash = hasher.finish();
2032             format!("{}-{}", triple, hash)
2033         } else {
2034             triple.to_owned()
2035         }
2036     }
2037 }
2038
2039 impl fmt::Display for TargetTriple {
2040     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2041         write!(f, "{}", self.debug_triple())
2042     }
2043 }