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