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