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