]> git.lizzy.rs Git - rust.git/blob - src/librustc_target/spec/mod.rs
Rollup merge of #71657 - Daniel-Worrall:24949, r=estebank
[rust.git] / src / librustc_target / 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::spec::abi::{lookup as lookup_abi, Abi};
38 use rustc_serialize::json::{Json, ToJson};
39 use std::collections::BTreeMap;
40 use std::path::{Path, PathBuf};
41 use std::str::FromStr;
42 use std::{fmt, io};
43
44 use rustc_macros::HashStable_Generic;
45
46 pub mod abi;
47 mod android_base;
48 mod apple_base;
49 mod apple_sdk_base;
50 mod arm_base;
51 mod cloudabi_base;
52 mod dragonfly_base;
53 mod freebsd_base;
54 mod fuchsia_base;
55 mod haiku_base;
56 mod hermit_base;
57 mod hermit_kernel_base;
58 mod illumos_base;
59 mod l4re_base;
60 mod linux_base;
61 mod linux_kernel_base;
62 mod linux_musl_base;
63 mod msvc_base;
64 mod netbsd_base;
65 mod openbsd_base;
66 mod redox_base;
67 mod riscv_base;
68 mod solaris_base;
69 mod thumb_base;
70 mod uefi_msvc_base;
71 mod vxworks_base;
72 mod wasm32_base;
73 mod windows_gnu_base;
74 mod windows_msvc_base;
75 mod windows_uwp_gnu_base;
76 mod windows_uwp_msvc_base;
77
78 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
79 pub enum LinkerFlavor {
80     Em,
81     Gcc,
82     Ld,
83     Msvc,
84     Lld(LldFlavor),
85     PtxLinker,
86 }
87
88 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
89 pub enum LldFlavor {
90     Wasm,
91     Ld64,
92     Ld,
93     Link,
94 }
95
96 impl LldFlavor {
97     fn from_str(s: &str) -> Option<Self> {
98         Some(match s {
99             "darwin" => LldFlavor::Ld64,
100             "gnu" => LldFlavor::Ld,
101             "link" => LldFlavor::Link,
102             "wasm" => LldFlavor::Wasm,
103             _ => return None,
104         })
105     }
106 }
107
108 impl ToJson for LldFlavor {
109     fn to_json(&self) -> Json {
110         match *self {
111             LldFlavor::Ld64 => "darwin",
112             LldFlavor::Ld => "gnu",
113             LldFlavor::Link => "link",
114             LldFlavor::Wasm => "wasm",
115         }
116         .to_json()
117     }
118 }
119
120 impl ToJson for LinkerFlavor {
121     fn to_json(&self) -> Json {
122         self.desc().to_json()
123     }
124 }
125 macro_rules! flavor_mappings {
126     ($((($($flavor:tt)*), $string:expr),)*) => (
127         impl LinkerFlavor {
128             pub const fn one_of() -> &'static str {
129                 concat!("one of: ", $($string, " ",)*)
130             }
131
132             pub fn from_str(s: &str) -> Option<Self> {
133                 Some(match s {
134                     $($string => $($flavor)*,)*
135                     _ => return None,
136                 })
137             }
138
139             pub fn desc(&self) -> &str {
140                 match *self {
141                     $($($flavor)* => $string,)*
142                 }
143             }
144         }
145     )
146 }
147
148 flavor_mappings! {
149     ((LinkerFlavor::Em), "em"),
150     ((LinkerFlavor::Gcc), "gcc"),
151     ((LinkerFlavor::Ld), "ld"),
152     ((LinkerFlavor::Msvc), "msvc"),
153     ((LinkerFlavor::PtxLinker), "ptx-linker"),
154     ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
155     ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
156     ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
157     ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
158 }
159
160 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable, HashStable_Generic)]
161 pub enum PanicStrategy {
162     Unwind,
163     Abort,
164 }
165
166 impl PanicStrategy {
167     pub fn desc(&self) -> &str {
168         match *self {
169             PanicStrategy::Unwind => "unwind",
170             PanicStrategy::Abort => "abort",
171         }
172     }
173 }
174
175 impl ToJson for PanicStrategy {
176     fn to_json(&self) -> Json {
177         match *self {
178             PanicStrategy::Abort => "abort".to_json(),
179             PanicStrategy::Unwind => "unwind".to_json(),
180         }
181     }
182 }
183
184 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
185 pub enum RelroLevel {
186     Full,
187     Partial,
188     Off,
189     None,
190 }
191
192 impl RelroLevel {
193     pub fn desc(&self) -> &str {
194         match *self {
195             RelroLevel::Full => "full",
196             RelroLevel::Partial => "partial",
197             RelroLevel::Off => "off",
198             RelroLevel::None => "none",
199         }
200     }
201 }
202
203 impl FromStr for RelroLevel {
204     type Err = ();
205
206     fn from_str(s: &str) -> Result<RelroLevel, ()> {
207         match s {
208             "full" => Ok(RelroLevel::Full),
209             "partial" => Ok(RelroLevel::Partial),
210             "off" => Ok(RelroLevel::Off),
211             "none" => Ok(RelroLevel::None),
212             _ => Err(()),
213         }
214     }
215 }
216
217 impl ToJson for RelroLevel {
218     fn to_json(&self) -> Json {
219         match *self {
220             RelroLevel::Full => "full".to_json(),
221             RelroLevel::Partial => "partial".to_json(),
222             RelroLevel::Off => "off".to_json(),
223             RelroLevel::None => "None".to_json(),
224         }
225     }
226 }
227
228 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
229 pub enum MergeFunctions {
230     Disabled,
231     Trampolines,
232     Aliases,
233 }
234
235 impl MergeFunctions {
236     pub fn desc(&self) -> &str {
237         match *self {
238             MergeFunctions::Disabled => "disabled",
239             MergeFunctions::Trampolines => "trampolines",
240             MergeFunctions::Aliases => "aliases",
241         }
242     }
243 }
244
245 impl FromStr for MergeFunctions {
246     type Err = ();
247
248     fn from_str(s: &str) -> Result<MergeFunctions, ()> {
249         match s {
250             "disabled" => Ok(MergeFunctions::Disabled),
251             "trampolines" => Ok(MergeFunctions::Trampolines),
252             "aliases" => Ok(MergeFunctions::Aliases),
253             _ => Err(()),
254         }
255     }
256 }
257
258 impl ToJson for MergeFunctions {
259     fn to_json(&self) -> Json {
260         match *self {
261             MergeFunctions::Disabled => "disabled".to_json(),
262             MergeFunctions::Trampolines => "trampolines".to_json(),
263             MergeFunctions::Aliases => "aliases".to_json(),
264         }
265     }
266 }
267
268 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
269 pub enum RelocModel {
270     Static,
271     Pic,
272     DynamicNoPic,
273     Ropi,
274     Rwpi,
275     RopiRwpi,
276 }
277
278 impl FromStr for RelocModel {
279     type Err = ();
280
281     fn from_str(s: &str) -> Result<RelocModel, ()> {
282         Ok(match s {
283             "static" => RelocModel::Static,
284             "pic" => RelocModel::Pic,
285             "dynamic-no-pic" => RelocModel::DynamicNoPic,
286             "ropi" => RelocModel::Ropi,
287             "rwpi" => RelocModel::Rwpi,
288             "ropi-rwpi" => RelocModel::RopiRwpi,
289             _ => return Err(()),
290         })
291     }
292 }
293
294 impl ToJson for RelocModel {
295     fn to_json(&self) -> Json {
296         match *self {
297             RelocModel::Static => "static",
298             RelocModel::Pic => "pic",
299             RelocModel::DynamicNoPic => "dynamic-no-pic",
300             RelocModel::Ropi => "ropi",
301             RelocModel::Rwpi => "rwpi",
302             RelocModel::RopiRwpi => "ropi-rwpi",
303         }
304         .to_json()
305     }
306 }
307
308 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
309 pub enum TlsModel {
310     GeneralDynamic,
311     LocalDynamic,
312     InitialExec,
313     LocalExec,
314 }
315
316 impl FromStr for TlsModel {
317     type Err = ();
318
319     fn from_str(s: &str) -> Result<TlsModel, ()> {
320         Ok(match s {
321             // Note the difference "general" vs "global" difference. The model name is "general",
322             // but the user-facing option name is "global" for consistency with other compilers.
323             "global-dynamic" => TlsModel::GeneralDynamic,
324             "local-dynamic" => TlsModel::LocalDynamic,
325             "initial-exec" => TlsModel::InitialExec,
326             "local-exec" => TlsModel::LocalExec,
327             _ => return Err(()),
328         })
329     }
330 }
331
332 impl ToJson for TlsModel {
333     fn to_json(&self) -> Json {
334         match *self {
335             TlsModel::GeneralDynamic => "global-dynamic",
336             TlsModel::LocalDynamic => "local-dynamic",
337             TlsModel::InitialExec => "initial-exec",
338             TlsModel::LocalExec => "local-exec",
339         }
340         .to_json()
341     }
342 }
343
344 pub enum LoadTargetError {
345     BuiltinTargetNotFound(String),
346     Other(String),
347 }
348
349 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
350 pub type TargetResult = Result<Target, String>;
351
352 macro_rules! supported_targets {
353     ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
354         $(mod $module;)+
355
356         /// List of supported targets
357         const TARGETS: &[&str] = &[$($($triple),+),+];
358
359         fn load_specific(target: &str) -> Result<Target, LoadTargetError> {
360             match target {
361                 $(
362                     $($triple)|+ => {
363                         let mut t = $module::target()
364                             .map_err(LoadTargetError::Other)?;
365                         t.options.is_builtin = true;
366
367                         // round-trip through the JSON parser to ensure at
368                         // run-time that the parser works correctly
369                         t = Target::from_json(t.to_json())
370                             .map_err(LoadTargetError::Other)?;
371                         debug!("got builtin target: {:?}", t);
372                         Ok(t)
373                     },
374                 )+
375                     _ => Err(LoadTargetError::BuiltinTargetNotFound(
376                         format!("Unable to find target: {}", target)))
377             }
378         }
379
380         pub fn get_targets() -> impl Iterator<Item = String> {
381             TARGETS.iter().filter_map(|t| -> Option<String> {
382                 load_specific(t)
383                     .and(Ok(t.to_string()))
384                     .ok()
385             })
386         }
387
388         #[cfg(test)]
389         mod tests {
390             mod tests_impl;
391
392             // Cannot put this into a separate file without duplication, make an exception.
393             $(
394                 #[test] // `#[test]`
395                 fn $module() {
396                     tests_impl::test_target(super::$module::target());
397                 }
398             )+
399         }
400     };
401 }
402
403 supported_targets! {
404     ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
405     ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
406     ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
407     ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
408     ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
409     ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
410     ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
411     ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
412     ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
413     ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
414     ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
415     ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
416     ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
417     ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
418     ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
419     ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
420     ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
421     ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
422     ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
423     ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
424     ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
425     ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
426     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
427     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
428     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
429     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
430     ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
431     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
432     ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
433     ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
434     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
435     ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
436     ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
437     ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
438     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
439     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
440     ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
441     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
442     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
443     ("i586-unknown-linux-musl", i586_unknown_linux_musl),
444     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
445     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
446     ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
447     ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
448     ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
449
450     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
451     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
452
453     ("i686-linux-android", i686_linux_android),
454     ("x86_64-linux-android", x86_64_linux_android),
455     ("arm-linux-androideabi", arm_linux_androideabi),
456     ("armv7-linux-androideabi", armv7_linux_androideabi),
457     ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
458     ("aarch64-linux-android", aarch64_linux_android),
459
460     ("x86_64-linux-kernel", x86_64_linux_kernel),
461
462     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
463     ("armv6-unknown-freebsd", armv6_unknown_freebsd),
464     ("armv7-unknown-freebsd", armv7_unknown_freebsd),
465     ("i686-unknown-freebsd", i686_unknown_freebsd),
466     ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
467     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
468
469     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
470
471     ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
472     ("i686-unknown-openbsd", i686_unknown_openbsd),
473     ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
474     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
475
476     ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
477     ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
478     ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
479     ("i686-unknown-netbsd", i686_unknown_netbsd),
480     ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
481     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
482     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
483     ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
484
485     ("i686-unknown-haiku", i686_unknown_haiku),
486     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
487
488     ("x86_64-apple-darwin", x86_64_apple_darwin),
489     ("i686-apple-darwin", i686_apple_darwin),
490
491     ("aarch64-fuchsia", aarch64_fuchsia),
492     ("x86_64-fuchsia", x86_64_fuchsia),
493
494     ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
495
496     ("aarch64-unknown-redox", aarch64_unknown_redox),
497     ("x86_64-unknown-redox", x86_64_unknown_redox),
498
499     ("i386-apple-ios", i386_apple_ios),
500     ("x86_64-apple-ios", x86_64_apple_ios),
501     ("aarch64-apple-ios", aarch64_apple_ios),
502     ("armv7-apple-ios", armv7_apple_ios),
503     ("armv7s-apple-ios", armv7s_apple_ios),
504     ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
505     ("aarch64-apple-tvos", aarch64_apple_tvos),
506     ("x86_64-apple-tvos", x86_64_apple_tvos),
507
508     ("armebv7r-none-eabi", armebv7r_none_eabi),
509     ("armebv7r-none-eabihf", armebv7r_none_eabihf),
510     ("armv7r-none-eabi", armv7r_none_eabi),
511     ("armv7r-none-eabihf", armv7r_none_eabihf),
512
513     // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
514     // (See <https://github.com/rust-lang/rust/issues/40531>.)
515     ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris),
516     ("sparcv9-sun-solaris", sparcv9_sun_solaris),
517
518     ("x86_64-unknown-illumos", x86_64_unknown_illumos),
519
520     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
521     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
522     ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
523     ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
524
525     ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
526     ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
527     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
528     ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
529     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
530     ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
531     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
532     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
533
534     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
535     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
536     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
537     ("wasm32-wasi", wasm32_wasi),
538
539     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
540     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
541     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
542     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
543     ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
544     ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
545     ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
546
547     ("armv7a-none-eabi", armv7a_none_eabi),
548     ("armv7a-none-eabihf", armv7a_none_eabihf),
549
550     ("msp430-none-elf", msp430_none_elf),
551
552     ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
553     ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
554     ("i686-unknown-cloudabi", i686_unknown_cloudabi),
555     ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
556
557     ("aarch64-unknown-hermit", aarch64_unknown_hermit),
558     ("x86_64-unknown-hermit", x86_64_unknown_hermit),
559     ("x86_64-unknown-hermit-kernel", x86_64_unknown_hermit_kernel),
560
561     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
562     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
563     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
564     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
565     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
566     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
567
568     ("aarch64-unknown-none", aarch64_unknown_none),
569     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
570
571     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
572
573     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
574     ("i686-unknown-uefi", i686_unknown_uefi),
575
576     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
577
578     ("i686-wrs-vxworks", i686_wrs_vxworks),
579     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
580     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
581     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
582     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
583     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
584     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
585 }
586
587 /// Everything `rustc` knows about how to compile for a specific target.
588 ///
589 /// Every field here must be specified, and has no default value.
590 #[derive(PartialEq, Clone, Debug)]
591 pub struct Target {
592     /// Target triple to pass to LLVM.
593     pub llvm_target: String,
594     /// String to use as the `target_endian` `cfg` variable.
595     pub target_endian: String,
596     /// String to use as the `target_pointer_width` `cfg` variable.
597     pub target_pointer_width: String,
598     /// Width of c_int type
599     pub target_c_int_width: String,
600     /// OS name to use for conditional compilation.
601     pub target_os: String,
602     /// Environment name to use for conditional compilation.
603     pub target_env: String,
604     /// Vendor name to use for conditional compilation.
605     pub target_vendor: String,
606     /// Architecture to use for ABI considerations. Valid options include: "x86",
607     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
608     pub arch: String,
609     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
610     pub data_layout: String,
611     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
612     /// on the command line.
613     pub linker_flavor: LinkerFlavor,
614     /// Optional settings with defaults.
615     pub options: TargetOptions,
616 }
617
618 pub trait HasTargetSpec {
619     fn target_spec(&self) -> &Target;
620 }
621
622 impl HasTargetSpec for Target {
623     fn target_spec(&self) -> &Target {
624         self
625     }
626 }
627
628 /// Optional aspects of a target specification.
629 ///
630 /// This has an implementation of `Default`, see each field for what the default is. In general,
631 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
632 #[derive(PartialEq, Clone, Debug)]
633 pub struct TargetOptions {
634     /// Whether the target is built-in or loaded from a custom target specification.
635     pub is_builtin: bool,
636
637     /// Linker to invoke
638     pub linker: Option<String>,
639
640     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
641     /// without clarifying its flavor in any way.
642     pub lld_flavor: LldFlavor,
643
644     /// Linker arguments that are passed *before* any user-defined libraries.
645     pub pre_link_args: LinkArgs, // ... unconditionally
646     pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
647     /// Objects to link before all others, always found within the
648     /// sysroot folder.
649     pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
650     pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
651     pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
652     /// Linker arguments that are unconditionally passed after any
653     /// user-defined but before post_link_objects. Standard platform
654     /// libraries that should be always be linked to, usually go here.
655     pub late_link_args: LinkArgs,
656     /// Linker arguments used in addition to `late_link_args` if at least one
657     /// Rust dependency is dynamically linked.
658     pub late_link_args_dynamic: LinkArgs,
659     /// Linker arguments used in addition to `late_link_args` if aall Rust
660     /// dependencies are statically linked.
661     pub late_link_args_static: LinkArgs,
662     /// Objects to link after all others, always found within the
663     /// sysroot folder.
664     pub post_link_objects: Vec<String>, // ... unconditionally
665     pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
666     /// Linker arguments that are unconditionally passed *after* any
667     /// user-defined libraries.
668     pub post_link_args: LinkArgs,
669
670     /// Environment variables to be set for the linker invocation.
671     pub link_env: Vec<(String, String)>,
672     /// Environment variables to be removed for the linker invocation.
673     pub link_env_remove: Vec<String>,
674
675     /// Extra arguments to pass to the external assembler (when used)
676     pub asm_args: Vec<String>,
677
678     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
679     /// to "generic".
680     pub cpu: String,
681     /// Default target features to pass to LLVM. These features will *always* be
682     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
683     /// -mattr=$features`.
684     pub features: String,
685     /// Whether dynamic linking is available on this target. Defaults to false.
686     pub dynamic_linking: bool,
687     /// If dynamic linking is available, whether only cdylibs are supported.
688     pub only_cdylib: bool,
689     /// Whether executables are available on this target. iOS, for example, only allows static
690     /// libraries. Defaults to false.
691     pub executables: bool,
692     /// Relocation model to use in object file. Corresponds to `llc
693     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
694     pub relocation_model: RelocModel,
695     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
696     pub code_model: Option<String>,
697     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
698     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
699     pub tls_model: TlsModel,
700     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
701     pub disable_redzone: bool,
702     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
703     pub eliminate_frame_pointer: bool,
704     /// Emit each function in its own section. Defaults to true.
705     pub function_sections: bool,
706     /// String to prepend to the name of every dynamic library. Defaults to "lib".
707     pub dll_prefix: String,
708     /// String to append to the name of every dynamic library. Defaults to ".so".
709     pub dll_suffix: String,
710     /// String to append to the name of every executable.
711     pub exe_suffix: String,
712     /// String to prepend to the name of every static library. Defaults to "lib".
713     pub staticlib_prefix: String,
714     /// String to append to the name of every static library. Defaults to ".a".
715     pub staticlib_suffix: String,
716     /// OS family to use for conditional compilation. Valid options: "unix", "windows".
717     pub target_family: Option<String>,
718     /// Whether the target toolchain's ABI supports returning small structs as an integer.
719     pub abi_return_struct_as_int: bool,
720     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
721     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
722     pub is_like_osx: bool,
723     /// Whether the target toolchain is like Solaris's.
724     /// Only useful for compiling against Illumos/Solaris,
725     /// as they have a different set of linker flags. Defaults to false.
726     pub is_like_solaris: bool,
727     /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
728     /// only really used for figuring out how to find libraries, since Windows uses its own
729     /// library naming convention. Defaults to false.
730     pub is_like_windows: bool,
731     pub is_like_msvc: bool,
732     /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
733     /// Defaults to false.
734     pub is_like_android: bool,
735     /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
736     /// Emscripten toolchain.
737     /// Defaults to false.
738     pub is_like_emscripten: bool,
739     /// Whether the target toolchain is like Fuchsia's.
740     pub is_like_fuchsia: bool,
741     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
742     pub linker_is_gnu: bool,
743     /// The MinGW toolchain has a known issue that prevents it from correctly
744     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
745     /// symbol needs its own COMDAT section, weak linkage implies a large
746     /// number sections that easily exceeds the given limit for larger
747     /// codebases. Consequently we want a way to disallow weak linkage on some
748     /// platforms.
749     pub allows_weak_linkage: bool,
750     /// Whether the linker support rpaths or not. Defaults to false.
751     pub has_rpath: bool,
752     /// Whether to disable linking to the default libraries, typically corresponds
753     /// to `-nodefaultlibs`. Defaults to true.
754     pub no_default_libraries: bool,
755     /// Dynamically linked executables can be compiled as position independent
756     /// if the default relocation model of position independent code is not
757     /// changed. This is a requirement to take advantage of ASLR, as otherwise
758     /// the functions in the executable are not randomized and can be used
759     /// during an exploit of a vulnerability in any code.
760     pub position_independent_executables: bool,
761     /// Determines if the target always requires using the PLT for indirect
762     /// library calls or not. This controls the default value of the `-Z plt` flag.
763     pub needs_plt: bool,
764     /// Either partial, full, or off. Full RELRO makes the dynamic linker
765     /// resolve all symbols at startup and marks the GOT read-only before
766     /// starting the program, preventing overwriting the GOT.
767     pub relro_level: RelroLevel,
768     /// Format that archives should be emitted in. This affects whether we use
769     /// LLVM to assemble an archive or fall back to the system linker, and
770     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
771     /// the system linker to be used.
772     pub archive_format: String,
773     /// Is asm!() allowed? Defaults to true.
774     pub allow_asm: bool,
775     /// Whether the runtime startup code requires the `main` function be passed
776     /// `argc` and `argv` values.
777     pub main_needs_argc_argv: bool,
778
779     /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
780     /// this target.
781     pub has_elf_tls: bool,
782     // This is mainly for easy compatibility with emscripten.
783     // If we give emcc .o files that are actually .bc files it
784     // will 'just work'.
785     pub obj_is_bitcode: bool,
786
787     /// Don't use this field; instead use the `.min_atomic_width()` method.
788     pub min_atomic_width: Option<u64>,
789
790     /// Don't use this field; instead use the `.max_atomic_width()` method.
791     pub max_atomic_width: Option<u64>,
792
793     /// Whether the target supports atomic CAS operations natively
794     pub atomic_cas: bool,
795
796     /// Panic strategy: "unwind" or "abort"
797     pub panic_strategy: PanicStrategy,
798
799     /// A blacklist of ABIs unsupported by the current target. Note that generic
800     /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
801     pub abi_blacklist: Vec<Abi>,
802
803     /// Whether or not linking dylibs to a static CRT is allowed.
804     pub crt_static_allows_dylibs: bool,
805     /// Whether or not the CRT is statically linked by default.
806     pub crt_static_default: bool,
807     /// Whether or not crt-static is respected by the compiler (or is a no-op).
808     pub crt_static_respected: bool,
809
810     /// Whether or not stack probes (__rust_probestack) are enabled
811     pub stack_probes: bool,
812
813     /// The minimum alignment for global symbols.
814     pub min_global_align: Option<u64>,
815
816     /// Default number of codegen units to use in debug mode
817     pub default_codegen_units: Option<u64>,
818
819     /// Whether to generate trap instructions in places where optimization would
820     /// otherwise produce control flow that falls through into unrelated memory.
821     pub trap_unreachable: bool,
822
823     /// This target requires everything to be compiled with LTO to emit a final
824     /// executable, aka there is no native linker for this target.
825     pub requires_lto: bool,
826
827     /// This target has no support for threads.
828     pub singlethread: bool,
829
830     /// Whether library functions call lowering/optimization is disabled in LLVM
831     /// for this target unconditionally.
832     pub no_builtins: bool,
833
834     /// The codegen backend to use for this target, typically "llvm"
835     pub codegen_backend: String,
836
837     /// The default visibility for symbols in this target should be "hidden"
838     /// rather than "default"
839     pub default_hidden_visibility: bool,
840
841     /// Whether a .debug_gdb_scripts section will be added to the output object file
842     pub emit_debug_gdb_scripts: bool,
843
844     /// Whether or not to unconditionally `uwtable` attributes on functions,
845     /// typically because the platform needs to unwind for things like stack
846     /// unwinders.
847     pub requires_uwtable: bool,
848
849     /// Whether or not SIMD types are passed by reference in the Rust ABI,
850     /// typically required if a target can be compiled with a mixed set of
851     /// target features. This is `true` by default, and `false` for targets like
852     /// wasm32 where the whole program either has simd or not.
853     pub simd_types_indirect: bool,
854
855     /// Pass a list of symbol which should be exported in the dylib to the linker.
856     pub limit_rdylib_exports: bool,
857
858     /// If set, have the linker export exactly these symbols, instead of using
859     /// the usual logic to figure this out from the crate itself.
860     pub override_export_symbols: Option<Vec<String>>,
861
862     /// Determines how or whether the MergeFunctions LLVM pass should run for
863     /// this target. Either "disabled", "trampolines", or "aliases".
864     /// The MergeFunctions pass is generally useful, but some targets may need
865     /// to opt out. The default is "aliases".
866     ///
867     /// Workaround for: https://github.com/rust-lang/rust/issues/57356
868     pub merge_functions: MergeFunctions,
869
870     /// Use platform dependent mcount function
871     pub target_mcount: String,
872
873     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
874     pub llvm_abiname: String,
875
876     /// Whether or not RelaxElfRelocation flag will be passed to the linker
877     pub relax_elf_relocations: bool,
878
879     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
880     pub llvm_args: Vec<String>,
881 }
882
883 impl Default for TargetOptions {
884     /// Creates a set of "sane defaults" for any target. This is still
885     /// incomplete, and if used for compilation, will certainly not work.
886     fn default() -> TargetOptions {
887         TargetOptions {
888             is_builtin: false,
889             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
890             lld_flavor: LldFlavor::Ld,
891             pre_link_args: LinkArgs::new(),
892             pre_link_args_crt: LinkArgs::new(),
893             post_link_args: LinkArgs::new(),
894             asm_args: Vec::new(),
895             cpu: "generic".to_string(),
896             features: String::new(),
897             dynamic_linking: false,
898             only_cdylib: false,
899             executables: false,
900             relocation_model: RelocModel::Pic,
901             code_model: None,
902             tls_model: TlsModel::GeneralDynamic,
903             disable_redzone: false,
904             eliminate_frame_pointer: true,
905             function_sections: true,
906             dll_prefix: "lib".to_string(),
907             dll_suffix: ".so".to_string(),
908             exe_suffix: String::new(),
909             staticlib_prefix: "lib".to_string(),
910             staticlib_suffix: ".a".to_string(),
911             target_family: None,
912             abi_return_struct_as_int: false,
913             is_like_osx: false,
914             is_like_solaris: false,
915             is_like_windows: false,
916             is_like_android: false,
917             is_like_emscripten: false,
918             is_like_msvc: false,
919             is_like_fuchsia: false,
920             linker_is_gnu: false,
921             allows_weak_linkage: true,
922             has_rpath: false,
923             no_default_libraries: true,
924             position_independent_executables: false,
925             needs_plt: false,
926             relro_level: RelroLevel::None,
927             pre_link_objects_exe: Vec::new(),
928             pre_link_objects_exe_crt: Vec::new(),
929             pre_link_objects_dll: Vec::new(),
930             post_link_objects: Vec::new(),
931             post_link_objects_crt: Vec::new(),
932             late_link_args: LinkArgs::new(),
933             late_link_args_dynamic: LinkArgs::new(),
934             late_link_args_static: LinkArgs::new(),
935             link_env: Vec::new(),
936             link_env_remove: Vec::new(),
937             archive_format: "gnu".to_string(),
938             main_needs_argc_argv: true,
939             allow_asm: true,
940             has_elf_tls: false,
941             obj_is_bitcode: false,
942             min_atomic_width: None,
943             max_atomic_width: None,
944             atomic_cas: true,
945             panic_strategy: PanicStrategy::Unwind,
946             abi_blacklist: vec![],
947             crt_static_allows_dylibs: false,
948             crt_static_default: false,
949             crt_static_respected: false,
950             stack_probes: false,
951             min_global_align: None,
952             default_codegen_units: None,
953             trap_unreachable: true,
954             requires_lto: false,
955             singlethread: false,
956             no_builtins: false,
957             codegen_backend: "llvm".to_string(),
958             default_hidden_visibility: false,
959             emit_debug_gdb_scripts: true,
960             requires_uwtable: false,
961             simd_types_indirect: true,
962             limit_rdylib_exports: true,
963             override_export_symbols: None,
964             merge_functions: MergeFunctions::Aliases,
965             target_mcount: "mcount".to_string(),
966             llvm_abiname: "".to_string(),
967             relax_elf_relocations: false,
968             llvm_args: vec![],
969         }
970     }
971 }
972
973 impl Target {
974     /// Given a function ABI, turn it into the correct ABI for this target.
975     pub fn adjust_abi(&self, abi: Abi) -> Abi {
976         match abi {
977             Abi::System => {
978                 if self.options.is_like_windows && self.arch == "x86" {
979                     Abi::Stdcall
980                 } else {
981                     Abi::C
982                 }
983             }
984             // These ABI kinds are ignored on non-x86 Windows targets.
985             // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
986             // and the individual pages for __stdcall et al.
987             Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
988                 if self.options.is_like_windows && self.arch != "x86" { Abi::C } else { abi }
989             }
990             Abi::EfiApi => {
991                 if self.arch == "x86_64" {
992                     Abi::Win64
993                 } else {
994                     Abi::C
995                 }
996             }
997             abi => abi,
998         }
999     }
1000
1001     /// Minimum integer size in bits that this target can perform atomic
1002     /// operations on.
1003     pub fn min_atomic_width(&self) -> u64 {
1004         self.options.min_atomic_width.unwrap_or(8)
1005     }
1006
1007     /// Maximum integer size in bits that this target can perform atomic
1008     /// operations on.
1009     pub fn max_atomic_width(&self) -> u64 {
1010         self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
1011     }
1012
1013     pub fn is_abi_supported(&self, abi: Abi) -> bool {
1014         abi.generic() || !self.options.abi_blacklist.contains(&abi)
1015     }
1016
1017     /// Loads a target descriptor from a JSON object.
1018     pub fn from_json(obj: Json) -> TargetResult {
1019         // While ugly, this code must remain this way to retain
1020         // compatibility with existing JSON fields and the internal
1021         // expected naming of the Target and TargetOptions structs.
1022         // To ensure compatibility is retained, the built-in targets
1023         // are round-tripped through this code to catch cases where
1024         // the JSON parser is not updated to match the structs.
1025
1026         let get_req_field = |name: &str| {
1027             obj.find(name)
1028                 .map(|s| s.as_string())
1029                 .and_then(|os| os.map(|s| s.to_string()))
1030                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1031         };
1032
1033         let get_opt_field = |name: &str, default: &str| {
1034             obj.find(name)
1035                 .and_then(|s| s.as_string())
1036                 .map(|s| s.to_string())
1037                 .unwrap_or_else(|| default.to_string())
1038         };
1039
1040         let mut base = Target {
1041             llvm_target: get_req_field("llvm-target")?,
1042             target_endian: get_req_field("target-endian")?,
1043             target_pointer_width: get_req_field("target-pointer-width")?,
1044             target_c_int_width: get_req_field("target-c-int-width")?,
1045             data_layout: get_req_field("data-layout")?,
1046             arch: get_req_field("arch")?,
1047             target_os: get_req_field("os")?,
1048             target_env: get_opt_field("env", ""),
1049             target_vendor: get_opt_field("vendor", "unknown"),
1050             linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
1051                 .ok_or_else(|| format!("linker flavor must be {}", LinkerFlavor::one_of()))?,
1052             options: Default::default(),
1053         };
1054
1055         macro_rules! key {
1056             ($key_name:ident) => ( {
1057                 let name = (stringify!($key_name)).replace("_", "-");
1058                 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1059                     base.options.$key_name = s.to_string();
1060                 }
1061             } );
1062             ($key_name:ident, bool) => ( {
1063                 let name = (stringify!($key_name)).replace("_", "-");
1064                 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
1065                     base.options.$key_name = s;
1066                 }
1067             } );
1068             ($key_name:ident, Option<u64>) => ( {
1069                 let name = (stringify!($key_name)).replace("_", "-");
1070                 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1071                     base.options.$key_name = Some(s);
1072                 }
1073             } );
1074             ($key_name:ident, MergeFunctions) => ( {
1075                 let name = (stringify!($key_name)).replace("_", "-");
1076                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1077                     match s.parse::<MergeFunctions>() {
1078                         Ok(mergefunc) => base.options.$key_name = mergefunc,
1079                         _ => return Some(Err(format!("'{}' is not a valid value for \
1080                                                       merge-functions. Use 'disabled', \
1081                                                       'trampolines', or 'aliases'.",
1082                                                       s))),
1083                     }
1084                     Some(Ok(()))
1085                 })).unwrap_or(Ok(()))
1086             } );
1087             ($key_name:ident, RelocModel) => ( {
1088                 let name = (stringify!($key_name)).replace("_", "-");
1089                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1090                     match s.parse::<RelocModel>() {
1091                         Ok(relocation_model) => base.options.$key_name = relocation_model,
1092                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1093                                                       Run `rustc --print relocation-models` to \
1094                                                       see the list of supported values.", s))),
1095                     }
1096                     Some(Ok(()))
1097                 })).unwrap_or(Ok(()))
1098             } );
1099             ($key_name:ident, TlsModel) => ( {
1100                 let name = (stringify!($key_name)).replace("_", "-");
1101                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1102                     match s.parse::<TlsModel>() {
1103                         Ok(tls_model) => base.options.$key_name = tls_model,
1104                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1105                                                       Run `rustc --print tls-models` to \
1106                                                       see the list of supported values.", s))),
1107                     }
1108                     Some(Ok(()))
1109                 })).unwrap_or(Ok(()))
1110             } );
1111             ($key_name:ident, PanicStrategy) => ( {
1112                 let name = (stringify!($key_name)).replace("_", "-");
1113                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1114                     match s {
1115                         "unwind" => base.options.$key_name = PanicStrategy::Unwind,
1116                         "abort" => base.options.$key_name = PanicStrategy::Abort,
1117                         _ => return Some(Err(format!("'{}' is not a valid value for \
1118                                                       panic-strategy. Use 'unwind' or 'abort'.",
1119                                                      s))),
1120                 }
1121                 Some(Ok(()))
1122             })).unwrap_or(Ok(()))
1123             } );
1124             ($key_name:ident, RelroLevel) => ( {
1125                 let name = (stringify!($key_name)).replace("_", "-");
1126                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1127                     match s.parse::<RelroLevel>() {
1128                         Ok(level) => base.options.$key_name = level,
1129                         _ => return Some(Err(format!("'{}' is not a valid value for \
1130                                                       relro-level. Use 'full', 'partial, or 'off'.",
1131                                                       s))),
1132                     }
1133                     Some(Ok(()))
1134                 })).unwrap_or(Ok(()))
1135             } );
1136             ($key_name:ident, list) => ( {
1137                 let name = (stringify!($key_name)).replace("_", "-");
1138                 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1139                     base.options.$key_name = v.iter()
1140                         .map(|a| a.as_string().unwrap().to_string())
1141                         .collect();
1142                 }
1143             } );
1144             ($key_name:ident, opt_list) => ( {
1145                 let name = (stringify!($key_name)).replace("_", "-");
1146                 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1147                     base.options.$key_name = Some(v.iter()
1148                         .map(|a| a.as_string().unwrap().to_string())
1149                         .collect());
1150                 }
1151             } );
1152             ($key_name:ident, optional) => ( {
1153                 let name = (stringify!($key_name)).replace("_", "-");
1154                 if let Some(o) = obj.find(&name[..]) {
1155                     base.options.$key_name = o
1156                         .as_string()
1157                         .map(|s| s.to_string() );
1158                 }
1159             } );
1160             ($key_name:ident, LldFlavor) => ( {
1161                 let name = (stringify!($key_name)).replace("_", "-");
1162                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1163                     if let Some(flavor) = LldFlavor::from_str(&s) {
1164                         base.options.$key_name = flavor;
1165                     } else {
1166                         return Some(Err(format!(
1167                             "'{}' is not a valid value for lld-flavor. \
1168                              Use 'darwin', 'gnu', 'link' or 'wasm.",
1169                             s)))
1170                     }
1171                     Some(Ok(()))
1172                 })).unwrap_or(Ok(()))
1173             } );
1174             ($key_name:ident, LinkerFlavor) => ( {
1175                 let name = (stringify!($key_name)).replace("_", "-");
1176                 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
1177                     LinkerFlavor::from_str(&s).ok_or_else(|| {
1178                         Err(format!("'{}' is not a valid value for linker-flavor. \
1179                                      Use 'em', 'gcc', 'ld' or 'msvc.", s))
1180                     })
1181                 })).unwrap_or(Ok(()))
1182             } );
1183             ($key_name:ident, link_args) => ( {
1184                 let name = (stringify!($key_name)).replace("_", "-");
1185                 if let Some(val) = obj.find(&name[..]) {
1186                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1187                         JSON object with fields per linker-flavor.", name))?;
1188                     let mut args = LinkArgs::new();
1189                     for (k, v) in obj {
1190                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1191                             format!("{}: '{}' is not a valid value for linker-flavor. \
1192                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1193                         })?;
1194
1195                         let v = v.as_array().ok_or_else(||
1196                             format!("{}.{}: expected a JSON array", name, k)
1197                         )?.iter().enumerate()
1198                             .map(|(i,s)| {
1199                                 let s = s.as_string().ok_or_else(||
1200                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1201                                 Ok(s.to_owned())
1202                             })
1203                             .collect::<Result<Vec<_>, String>>()?;
1204
1205                         args.insert(flavor, v);
1206                     }
1207                     base.options.$key_name = args;
1208                 }
1209             } );
1210             ($key_name:ident, env) => ( {
1211                 let name = (stringify!($key_name)).replace("_", "-");
1212                 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1213                     for o in a {
1214                         if let Some(s) = o.as_string() {
1215                             let p = s.split('=').collect::<Vec<_>>();
1216                             if p.len() == 2 {
1217                                 let k = p[0].to_string();
1218                                 let v = p[1].to_string();
1219                                 base.options.$key_name.push((k, v));
1220                             }
1221                         }
1222                     }
1223                 }
1224             } );
1225         }
1226
1227         key!(is_builtin, bool);
1228         key!(linker, optional);
1229         key!(lld_flavor, LldFlavor)?;
1230         key!(pre_link_args, link_args);
1231         key!(pre_link_args_crt, link_args);
1232         key!(pre_link_objects_exe, list);
1233         key!(pre_link_objects_exe_crt, list);
1234         key!(pre_link_objects_dll, list);
1235         key!(late_link_args, link_args);
1236         key!(late_link_args_dynamic, link_args);
1237         key!(late_link_args_static, link_args);
1238         key!(post_link_objects, list);
1239         key!(post_link_objects_crt, list);
1240         key!(post_link_args, link_args);
1241         key!(link_env, env);
1242         key!(link_env_remove, list);
1243         key!(asm_args, list);
1244         key!(cpu);
1245         key!(features);
1246         key!(dynamic_linking, bool);
1247         key!(only_cdylib, bool);
1248         key!(executables, bool);
1249         key!(relocation_model, RelocModel)?;
1250         key!(code_model, optional);
1251         key!(tls_model, TlsModel)?;
1252         key!(disable_redzone, bool);
1253         key!(eliminate_frame_pointer, bool);
1254         key!(function_sections, bool);
1255         key!(dll_prefix);
1256         key!(dll_suffix);
1257         key!(exe_suffix);
1258         key!(staticlib_prefix);
1259         key!(staticlib_suffix);
1260         key!(target_family, optional);
1261         key!(abi_return_struct_as_int, bool);
1262         key!(is_like_osx, bool);
1263         key!(is_like_solaris, bool);
1264         key!(is_like_windows, bool);
1265         key!(is_like_msvc, bool);
1266         key!(is_like_emscripten, bool);
1267         key!(is_like_android, bool);
1268         key!(is_like_fuchsia, bool);
1269         key!(linker_is_gnu, bool);
1270         key!(allows_weak_linkage, bool);
1271         key!(has_rpath, bool);
1272         key!(no_default_libraries, bool);
1273         key!(position_independent_executables, bool);
1274         key!(needs_plt, bool);
1275         key!(relro_level, RelroLevel)?;
1276         key!(archive_format);
1277         key!(allow_asm, bool);
1278         key!(main_needs_argc_argv, bool);
1279         key!(has_elf_tls, bool);
1280         key!(obj_is_bitcode, bool);
1281         key!(max_atomic_width, Option<u64>);
1282         key!(min_atomic_width, Option<u64>);
1283         key!(atomic_cas, bool);
1284         key!(panic_strategy, PanicStrategy)?;
1285         key!(crt_static_allows_dylibs, bool);
1286         key!(crt_static_default, bool);
1287         key!(crt_static_respected, bool);
1288         key!(stack_probes, bool);
1289         key!(min_global_align, Option<u64>);
1290         key!(default_codegen_units, Option<u64>);
1291         key!(trap_unreachable, bool);
1292         key!(requires_lto, bool);
1293         key!(singlethread, bool);
1294         key!(no_builtins, bool);
1295         key!(codegen_backend);
1296         key!(default_hidden_visibility, bool);
1297         key!(emit_debug_gdb_scripts, bool);
1298         key!(requires_uwtable, bool);
1299         key!(simd_types_indirect, bool);
1300         key!(limit_rdylib_exports, bool);
1301         key!(override_export_symbols, opt_list);
1302         key!(merge_functions, MergeFunctions)?;
1303         key!(target_mcount);
1304         key!(llvm_abiname);
1305         key!(relax_elf_relocations, bool);
1306         key!(llvm_args, list);
1307
1308         if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1309             for name in array.iter().filter_map(|abi| abi.as_string()) {
1310                 match lookup_abi(name) {
1311                     Some(abi) => {
1312                         if abi.generic() {
1313                             return Err(format!(
1314                                 "The ABI \"{}\" is considered to be supported on \
1315                                                 all targets and cannot be blacklisted",
1316                                 abi
1317                             ));
1318                         }
1319
1320                         base.options.abi_blacklist.push(abi)
1321                     }
1322                     None => {
1323                         return Err(format!("Unknown ABI \"{}\" in target specification", name));
1324                     }
1325                 }
1326             }
1327         }
1328
1329         Ok(base)
1330     }
1331
1332     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1333     /// triple. Note that it could also just be a bare filename already, so also
1334     /// check for that. If one of the hardcoded targets we know about, just
1335     /// return it directly.
1336     ///
1337     /// The error string could come from any of the APIs called, including
1338     /// filesystem access and JSON decoding.
1339     pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1340         use rustc_serialize::json;
1341         use std::env;
1342         use std::fs;
1343
1344         fn load_file(path: &Path) -> Result<Target, String> {
1345             let contents = fs::read(path).map_err(|e| e.to_string())?;
1346             let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1347             Target::from_json(obj)
1348         }
1349
1350         match *target_triple {
1351             TargetTriple::TargetTriple(ref target_triple) => {
1352                 // check if triple is in list of supported targets
1353                 match load_specific(target_triple) {
1354                     Ok(t) => return Ok(t),
1355                     Err(LoadTargetError::BuiltinTargetNotFound(_)) => (),
1356                     Err(LoadTargetError::Other(e)) => return Err(e),
1357                 }
1358
1359                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1360                 let path = {
1361                     let mut target = target_triple.to_string();
1362                     target.push_str(".json");
1363                     PathBuf::from(target)
1364                 };
1365
1366                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1367
1368                 // FIXME 16351: add a sane default search path?
1369
1370                 for dir in env::split_paths(&target_path) {
1371                     let p = dir.join(&path);
1372                     if p.is_file() {
1373                         return load_file(&p);
1374                     }
1375                 }
1376                 Err(format!("Could not find specification for target {:?}", target_triple))
1377             }
1378             TargetTriple::TargetPath(ref target_path) => {
1379                 if target_path.is_file() {
1380                     return load_file(&target_path);
1381                 }
1382                 Err(format!("Target path {:?} is not a valid file", target_path))
1383             }
1384         }
1385     }
1386 }
1387
1388 impl ToJson for Target {
1389     fn to_json(&self) -> Json {
1390         let mut d = BTreeMap::new();
1391         let default: TargetOptions = Default::default();
1392
1393         macro_rules! target_val {
1394             ($attr:ident) => {{
1395                 let name = (stringify!($attr)).replace("_", "-");
1396                 d.insert(name, self.$attr.to_json());
1397             }};
1398             ($attr:ident, $key_name:expr) => {{
1399                 let name = $key_name;
1400                 d.insert(name.to_string(), self.$attr.to_json());
1401             }};
1402         }
1403
1404         macro_rules! target_option_val {
1405             ($attr:ident) => {{
1406                 let name = (stringify!($attr)).replace("_", "-");
1407                 if default.$attr != self.options.$attr {
1408                     d.insert(name, self.options.$attr.to_json());
1409                 }
1410             }};
1411             ($attr:ident, $key_name:expr) => {{
1412                 let name = $key_name;
1413                 if default.$attr != self.options.$attr {
1414                     d.insert(name.to_string(), self.options.$attr.to_json());
1415                 }
1416             }};
1417             (link_args - $attr:ident) => {{
1418                 let name = (stringify!($attr)).replace("_", "-");
1419                 if default.$attr != self.options.$attr {
1420                     let obj = self
1421                         .options
1422                         .$attr
1423                         .iter()
1424                         .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1425                         .collect::<BTreeMap<_, _>>();
1426                     d.insert(name, obj.to_json());
1427                 }
1428             }};
1429             (env - $attr:ident) => {{
1430                 let name = (stringify!($attr)).replace("_", "-");
1431                 if default.$attr != self.options.$attr {
1432                     let obj = self
1433                         .options
1434                         .$attr
1435                         .iter()
1436                         .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1437                         .collect::<Vec<_>>();
1438                     d.insert(name, obj.to_json());
1439                 }
1440             }};
1441         }
1442
1443         target_val!(llvm_target);
1444         target_val!(target_endian);
1445         target_val!(target_pointer_width);
1446         target_val!(target_c_int_width);
1447         target_val!(arch);
1448         target_val!(target_os, "os");
1449         target_val!(target_env, "env");
1450         target_val!(target_vendor, "vendor");
1451         target_val!(data_layout);
1452         target_val!(linker_flavor);
1453
1454         target_option_val!(is_builtin);
1455         target_option_val!(linker);
1456         target_option_val!(lld_flavor);
1457         target_option_val!(link_args - pre_link_args);
1458         target_option_val!(link_args - pre_link_args_crt);
1459         target_option_val!(pre_link_objects_exe);
1460         target_option_val!(pre_link_objects_exe_crt);
1461         target_option_val!(pre_link_objects_dll);
1462         target_option_val!(link_args - late_link_args);
1463         target_option_val!(link_args - late_link_args_dynamic);
1464         target_option_val!(link_args - late_link_args_static);
1465         target_option_val!(post_link_objects);
1466         target_option_val!(post_link_objects_crt);
1467         target_option_val!(link_args - post_link_args);
1468         target_option_val!(env - link_env);
1469         target_option_val!(link_env_remove);
1470         target_option_val!(asm_args);
1471         target_option_val!(cpu);
1472         target_option_val!(features);
1473         target_option_val!(dynamic_linking);
1474         target_option_val!(only_cdylib);
1475         target_option_val!(executables);
1476         target_option_val!(relocation_model);
1477         target_option_val!(code_model);
1478         target_option_val!(tls_model);
1479         target_option_val!(disable_redzone);
1480         target_option_val!(eliminate_frame_pointer);
1481         target_option_val!(function_sections);
1482         target_option_val!(dll_prefix);
1483         target_option_val!(dll_suffix);
1484         target_option_val!(exe_suffix);
1485         target_option_val!(staticlib_prefix);
1486         target_option_val!(staticlib_suffix);
1487         target_option_val!(target_family);
1488         target_option_val!(abi_return_struct_as_int);
1489         target_option_val!(is_like_osx);
1490         target_option_val!(is_like_solaris);
1491         target_option_val!(is_like_windows);
1492         target_option_val!(is_like_msvc);
1493         target_option_val!(is_like_emscripten);
1494         target_option_val!(is_like_android);
1495         target_option_val!(is_like_fuchsia);
1496         target_option_val!(linker_is_gnu);
1497         target_option_val!(allows_weak_linkage);
1498         target_option_val!(has_rpath);
1499         target_option_val!(no_default_libraries);
1500         target_option_val!(position_independent_executables);
1501         target_option_val!(needs_plt);
1502         target_option_val!(relro_level);
1503         target_option_val!(archive_format);
1504         target_option_val!(allow_asm);
1505         target_option_val!(main_needs_argc_argv);
1506         target_option_val!(has_elf_tls);
1507         target_option_val!(obj_is_bitcode);
1508         target_option_val!(min_atomic_width);
1509         target_option_val!(max_atomic_width);
1510         target_option_val!(atomic_cas);
1511         target_option_val!(panic_strategy);
1512         target_option_val!(crt_static_allows_dylibs);
1513         target_option_val!(crt_static_default);
1514         target_option_val!(crt_static_respected);
1515         target_option_val!(stack_probes);
1516         target_option_val!(min_global_align);
1517         target_option_val!(default_codegen_units);
1518         target_option_val!(trap_unreachable);
1519         target_option_val!(requires_lto);
1520         target_option_val!(singlethread);
1521         target_option_val!(no_builtins);
1522         target_option_val!(codegen_backend);
1523         target_option_val!(default_hidden_visibility);
1524         target_option_val!(emit_debug_gdb_scripts);
1525         target_option_val!(requires_uwtable);
1526         target_option_val!(simd_types_indirect);
1527         target_option_val!(limit_rdylib_exports);
1528         target_option_val!(override_export_symbols);
1529         target_option_val!(merge_functions);
1530         target_option_val!(target_mcount);
1531         target_option_val!(llvm_abiname);
1532         target_option_val!(relax_elf_relocations);
1533         target_option_val!(llvm_args);
1534
1535         if default.abi_blacklist != self.options.abi_blacklist {
1536             d.insert(
1537                 "abi-blacklist".to_string(),
1538                 self.options
1539                     .abi_blacklist
1540                     .iter()
1541                     .map(|&name| Abi::name(name).to_json())
1542                     .collect::<Vec<_>>()
1543                     .to_json(),
1544             );
1545         }
1546
1547         Json::Object(d)
1548     }
1549 }
1550
1551 /// Either a target triple string or a path to a JSON file.
1552 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1553 pub enum TargetTriple {
1554     TargetTriple(String),
1555     TargetPath(PathBuf),
1556 }
1557
1558 impl TargetTriple {
1559     /// Creates a target triple from the passed target triple string.
1560     pub fn from_triple(triple: &str) -> Self {
1561         TargetTriple::TargetTriple(triple.to_string())
1562     }
1563
1564     /// Creates a target triple from the passed target path.
1565     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1566         let canonicalized_path = path.canonicalize()?;
1567         Ok(TargetTriple::TargetPath(canonicalized_path))
1568     }
1569
1570     /// Returns a string triple for this target.
1571     ///
1572     /// If this target is a path, the file name (without extension) is returned.
1573     pub fn triple(&self) -> &str {
1574         match *self {
1575             TargetTriple::TargetTriple(ref triple) => triple,
1576             TargetTriple::TargetPath(ref path) => path
1577                 .file_stem()
1578                 .expect("target path must not be empty")
1579                 .to_str()
1580                 .expect("target path must be valid unicode"),
1581         }
1582     }
1583
1584     /// Returns an extended string triple for this target.
1585     ///
1586     /// If this target is a path, a hash of the path is appended to the triple returned
1587     /// by `triple()`.
1588     pub fn debug_triple(&self) -> String {
1589         use std::collections::hash_map::DefaultHasher;
1590         use std::hash::{Hash, Hasher};
1591
1592         let triple = self.triple();
1593         if let TargetTriple::TargetPath(ref path) = *self {
1594             let mut hasher = DefaultHasher::new();
1595             path.hash(&mut hasher);
1596             let hash = hasher.finish();
1597             format!("{}-{}", triple, hash)
1598         } else {
1599             triple.to_owned()
1600         }
1601     }
1602 }
1603
1604 impl fmt::Display for TargetTriple {
1605     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606         write!(f, "{}", self.debug_triple())
1607     }
1608 }