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