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