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