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