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