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