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