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