]> git.lizzy.rs Git - rust.git/blob - src/librustc_target/spec/mod.rs
Rollup merge of #55711 - kngwyu:btreemap-rangemut-doc, r=Mark-Simulacrum
[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
688 impl Default for TargetOptions {
689     /// Create a set of "sane defaults" for any target. This is still
690     /// incomplete, and if used for compilation, will certainly not work.
691     fn default() -> TargetOptions {
692         TargetOptions {
693             is_builtin: false,
694             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
695             lld_flavor: LldFlavor::Ld,
696             pre_link_args: LinkArgs::new(),
697             pre_link_args_crt: LinkArgs::new(),
698             post_link_args: LinkArgs::new(),
699             asm_args: Vec::new(),
700             cpu: "generic".to_string(),
701             features: String::new(),
702             dynamic_linking: false,
703             only_cdylib: false,
704             executables: false,
705             relocation_model: "pic".to_string(),
706             code_model: None,
707             tls_model: "global-dynamic".to_string(),
708             disable_redzone: false,
709             eliminate_frame_pointer: true,
710             function_sections: true,
711             dll_prefix: "lib".to_string(),
712             dll_suffix: ".so".to_string(),
713             exe_suffix: String::new(),
714             staticlib_prefix: "lib".to_string(),
715             staticlib_suffix: ".a".to_string(),
716             target_family: None,
717             abi_return_struct_as_int: false,
718             is_like_osx: false,
719             is_like_solaris: false,
720             is_like_windows: false,
721             is_like_android: false,
722             is_like_emscripten: false,
723             is_like_msvc: false,
724             linker_is_gnu: false,
725             allows_weak_linkage: true,
726             has_rpath: false,
727             no_default_libraries: true,
728             position_independent_executables: false,
729             needs_plt: false,
730             relro_level: RelroLevel::None,
731             pre_link_objects_exe: Vec::new(),
732             pre_link_objects_exe_crt: Vec::new(),
733             pre_link_objects_dll: Vec::new(),
734             post_link_objects: Vec::new(),
735             post_link_objects_crt: Vec::new(),
736             late_link_args: LinkArgs::new(),
737             link_env: Vec::new(),
738             archive_format: "gnu".to_string(),
739             custom_unwind_resume: false,
740             allow_asm: true,
741             has_elf_tls: false,
742             obj_is_bitcode: false,
743             no_integrated_as: false,
744             min_atomic_width: None,
745             max_atomic_width: None,
746             atomic_cas: true,
747             panic_strategy: PanicStrategy::Unwind,
748             abi_blacklist: vec![],
749             crt_static_allows_dylibs: false,
750             crt_static_default: false,
751             crt_static_respected: false,
752             stack_probes: false,
753             min_global_align: None,
754             default_codegen_units: None,
755             trap_unreachable: true,
756             requires_lto: false,
757             singlethread: false,
758             no_builtins: false,
759             i128_lowering: false,
760             codegen_backend: "llvm".to_string(),
761             default_hidden_visibility: false,
762             embed_bitcode: false,
763             emit_debug_gdb_scripts: true,
764             requires_uwtable: false,
765             simd_types_indirect: true,
766         }
767     }
768 }
769
770 impl Target {
771     /// Given a function ABI, turn it into the correct ABI for this target.
772     pub fn adjust_abi(&self, abi: Abi) -> Abi {
773         match abi {
774             Abi::System => {
775                 if self.options.is_like_windows && self.arch == "x86" {
776                     Abi::Stdcall
777                 } else {
778                     Abi::C
779                 }
780             },
781             // These ABI kinds are ignored on non-x86 Windows targets.
782             // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
783             // and the individual pages for __stdcall et al.
784             Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
785                 if self.options.is_like_windows && self.arch != "x86" {
786                     Abi::C
787                 } else {
788                     abi
789                 }
790             },
791             abi => abi
792         }
793     }
794
795     /// Minimum integer size in bits that this target can perform atomic
796     /// operations on.
797     pub fn min_atomic_width(&self) -> u64 {
798         self.options.min_atomic_width.unwrap_or(8)
799     }
800
801     /// Maximum integer size in bits that this target can perform atomic
802     /// operations on.
803     pub fn max_atomic_width(&self) -> u64 {
804         self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
805     }
806
807     pub fn is_abi_supported(&self, abi: Abi) -> bool {
808         abi.generic() || !self.options.abi_blacklist.contains(&abi)
809     }
810
811     /// Load a target descriptor from a JSON object.
812     pub fn from_json(obj: Json) -> TargetResult {
813         // While ugly, this code must remain this way to retain
814         // compatibility with existing JSON fields and the internal
815         // expected naming of the Target and TargetOptions structs.
816         // To ensure compatibility is retained, the built-in targets
817         // are round-tripped through this code to catch cases where
818         // the JSON parser is not updated to match the structs.
819
820         let get_req_field = |name: &str| {
821             obj.find(name)
822                .map(|s| s.as_string())
823                .and_then(|os| os.map(|s| s.to_string()))
824                .ok_or_else(|| format!("Field {} in target specification is required", name))
825         };
826
827         let get_opt_field = |name: &str, default: &str| {
828             obj.find(name).and_then(|s| s.as_string())
829                .map(|s| s.to_string())
830                .unwrap_or_else(|| default.to_string())
831         };
832
833         let mut base = Target {
834             llvm_target: get_req_field("llvm-target")?,
835             target_endian: get_req_field("target-endian")?,
836             target_pointer_width: get_req_field("target-pointer-width")?,
837             target_c_int_width: get_req_field("target-c-int-width")?,
838             data_layout: get_req_field("data-layout")?,
839             arch: get_req_field("arch")?,
840             target_os: get_req_field("os")?,
841             target_env: get_opt_field("env", ""),
842             target_vendor: get_opt_field("vendor", "unknown"),
843             linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
844                 .ok_or_else(|| {
845                     format!("linker flavor must be {}", LinkerFlavor::one_of())
846                 })?,
847             options: Default::default(),
848         };
849
850         macro_rules! key {
851             ($key_name:ident) => ( {
852                 let name = (stringify!($key_name)).replace("_", "-");
853                 obj.find(&name[..]).map(|o| o.as_string()
854                                     .map(|s| base.options.$key_name = s.to_string()));
855             } );
856             ($key_name:ident, bool) => ( {
857                 let name = (stringify!($key_name)).replace("_", "-");
858                 obj.find(&name[..])
859                     .map(|o| o.as_boolean()
860                          .map(|s| base.options.$key_name = s));
861             } );
862             ($key_name:ident, Option<u64>) => ( {
863                 let name = (stringify!($key_name)).replace("_", "-");
864                 obj.find(&name[..])
865                     .map(|o| o.as_u64()
866                          .map(|s| base.options.$key_name = Some(s)));
867             } );
868             ($key_name:ident, PanicStrategy) => ( {
869                 let name = (stringify!($key_name)).replace("_", "-");
870                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
871                     match s {
872                         "unwind" => base.options.$key_name = PanicStrategy::Unwind,
873                         "abort" => base.options.$key_name = PanicStrategy::Abort,
874                         _ => return Some(Err(format!("'{}' is not a valid value for \
875                                                       panic-strategy. Use 'unwind' or 'abort'.",
876                                                      s))),
877                 }
878                 Some(Ok(()))
879             })).unwrap_or(Ok(()))
880             } );
881             ($key_name:ident, RelroLevel) => ( {
882                 let name = (stringify!($key_name)).replace("_", "-");
883                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
884                     match s.parse::<RelroLevel>() {
885                         Ok(level) => base.options.$key_name = level,
886                         _ => return Some(Err(format!("'{}' is not a valid value for \
887                                                       relro-level. Use 'full', 'partial, or 'off'.",
888                                                       s))),
889                     }
890                     Some(Ok(()))
891                 })).unwrap_or(Ok(()))
892             } );
893             ($key_name:ident, list) => ( {
894                 let name = (stringify!($key_name)).replace("_", "-");
895                 obj.find(&name[..]).map(|o| o.as_array()
896                     .map(|v| base.options.$key_name = v.iter()
897                         .map(|a| a.as_string().unwrap().to_string()).collect()
898                         )
899                     );
900             } );
901             ($key_name:ident, optional) => ( {
902                 let name = (stringify!($key_name)).replace("_", "-");
903                 if let Some(o) = obj.find(&name[..]) {
904                     base.options.$key_name = o
905                         .as_string()
906                         .map(|s| s.to_string() );
907                 }
908             } );
909             ($key_name:ident, LldFlavor) => ( {
910                 let name = (stringify!($key_name)).replace("_", "-");
911                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
912                     if let Some(flavor) = LldFlavor::from_str(&s) {
913                         base.options.$key_name = flavor;
914                     } else {
915                         return Some(Err(format!(
916                             "'{}' is not a valid value for lld-flavor. \
917                              Use 'darwin', 'gnu', 'link' or 'wasm.",
918                             s)))
919                     }
920                     Some(Ok(()))
921                 })).unwrap_or(Ok(()))
922             } );
923             ($key_name:ident, LinkerFlavor) => ( {
924                 let name = (stringify!($key_name)).replace("_", "-");
925                 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
926                     LinkerFlavor::from_str(&s).ok_or_else(|| {
927                         Err(format!("'{}' is not a valid value for linker-flavor. \
928                                      Use 'em', 'gcc', 'ld' or 'msvc.", s))
929                     })
930                 })).unwrap_or(Ok(()))
931             } );
932             ($key_name:ident, link_args) => ( {
933                 let name = (stringify!($key_name)).replace("_", "-");
934                 if let Some(val) = obj.find(&name[..]) {
935                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
936                         JSON object with fields per linker-flavor.", name))?;
937                     let mut args = LinkArgs::new();
938                     for (k, v) in obj {
939                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
940                             format!("{}: '{}' is not a valid value for linker-flavor. \
941                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
942                         })?;
943
944                         let v = v.as_array().ok_or_else(||
945                             format!("{}.{}: expected a JSON array", name, k)
946                         )?.iter().enumerate()
947                             .map(|(i,s)| {
948                                 let s = s.as_string().ok_or_else(||
949                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
950                                 Ok(s.to_owned())
951                             })
952                             .collect::<Result<Vec<_>, String>>()?;
953
954                         args.insert(flavor, v);
955                     }
956                     base.options.$key_name = args;
957                 }
958             } );
959             ($key_name:ident, env) => ( {
960                 let name = (stringify!($key_name)).replace("_", "-");
961                 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
962                     for o in a {
963                         if let Some(s) = o.as_string() {
964                             let p = s.split('=').collect::<Vec<_>>();
965                             if p.len() == 2 {
966                                 let k = p[0].to_string();
967                                 let v = p[1].to_string();
968                                 base.options.$key_name.push((k, v));
969                             }
970                         }
971                     }
972                 }
973             } );
974         }
975
976         key!(is_builtin, bool);
977         key!(linker, optional);
978         try!(key!(lld_flavor, LldFlavor));
979         key!(pre_link_args, link_args);
980         key!(pre_link_args_crt, link_args);
981         key!(pre_link_objects_exe, list);
982         key!(pre_link_objects_exe_crt, list);
983         key!(pre_link_objects_dll, list);
984         key!(late_link_args, link_args);
985         key!(post_link_objects, list);
986         key!(post_link_objects_crt, list);
987         key!(post_link_args, link_args);
988         key!(link_env, env);
989         key!(asm_args, list);
990         key!(cpu);
991         key!(features);
992         key!(dynamic_linking, bool);
993         key!(only_cdylib, bool);
994         key!(executables, bool);
995         key!(relocation_model);
996         key!(code_model, optional);
997         key!(tls_model);
998         key!(disable_redzone, bool);
999         key!(eliminate_frame_pointer, bool);
1000         key!(function_sections, bool);
1001         key!(dll_prefix);
1002         key!(dll_suffix);
1003         key!(exe_suffix);
1004         key!(staticlib_prefix);
1005         key!(staticlib_suffix);
1006         key!(target_family, optional);
1007         key!(abi_return_struct_as_int, bool);
1008         key!(is_like_osx, bool);
1009         key!(is_like_solaris, bool);
1010         key!(is_like_windows, bool);
1011         key!(is_like_msvc, bool);
1012         key!(is_like_emscripten, bool);
1013         key!(is_like_android, bool);
1014         key!(linker_is_gnu, bool);
1015         key!(allows_weak_linkage, bool);
1016         key!(has_rpath, bool);
1017         key!(no_default_libraries, bool);
1018         key!(position_independent_executables, bool);
1019         key!(needs_plt, bool);
1020         try!(key!(relro_level, RelroLevel));
1021         key!(archive_format);
1022         key!(allow_asm, bool);
1023         key!(custom_unwind_resume, bool);
1024         key!(has_elf_tls, bool);
1025         key!(obj_is_bitcode, bool);
1026         key!(no_integrated_as, bool);
1027         key!(max_atomic_width, Option<u64>);
1028         key!(min_atomic_width, Option<u64>);
1029         key!(atomic_cas, bool);
1030         try!(key!(panic_strategy, PanicStrategy));
1031         key!(crt_static_allows_dylibs, bool);
1032         key!(crt_static_default, bool);
1033         key!(crt_static_respected, bool);
1034         key!(stack_probes, bool);
1035         key!(min_global_align, Option<u64>);
1036         key!(default_codegen_units, Option<u64>);
1037         key!(trap_unreachable, bool);
1038         key!(requires_lto, bool);
1039         key!(singlethread, bool);
1040         key!(no_builtins, bool);
1041         key!(codegen_backend);
1042         key!(default_hidden_visibility, bool);
1043         key!(embed_bitcode, bool);
1044         key!(emit_debug_gdb_scripts, bool);
1045         key!(requires_uwtable, bool);
1046         key!(simd_types_indirect, bool);
1047
1048         if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1049             for name in array.iter().filter_map(|abi| abi.as_string()) {
1050                 match lookup_abi(name) {
1051                     Some(abi) => {
1052                         if abi.generic() {
1053                             return Err(format!("The ABI \"{}\" is considered to be supported on \
1054                                                 all targets and cannot be blacklisted", abi))
1055                         }
1056
1057                         base.options.abi_blacklist.push(abi)
1058                     }
1059                     None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
1060                 }
1061             }
1062         }
1063
1064         Ok(base)
1065     }
1066
1067     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1068     /// triple. Note that it could also just be a bare filename already, so also
1069     /// check for that. If one of the hardcoded targets we know about, just
1070     /// return it directly.
1071     ///
1072     /// The error string could come from any of the APIs called, including
1073     /// filesystem access and JSON decoding.
1074     pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1075         use std::env;
1076         use std::fs;
1077         use serialize::json;
1078
1079         fn load_file(path: &Path) -> Result<Target, String> {
1080             let contents = fs::read(path).map_err(|e| e.to_string())?;
1081             let obj = json::from_reader(&mut &contents[..])
1082                            .map_err(|e| e.to_string())?;
1083             Target::from_json(obj)
1084         }
1085
1086         match *target_triple {
1087             TargetTriple::TargetTriple(ref target_triple) => {
1088                 // check if triple is in list of supported targets
1089                 if let Ok(t) = load_specific(target_triple) {
1090                     return Ok(t)
1091                 }
1092
1093                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1094                 let path = {
1095                     let mut target = target_triple.to_string();
1096                     target.push_str(".json");
1097                     PathBuf::from(target)
1098                 };
1099
1100                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1101
1102                 // FIXME 16351: add a sane default search path?
1103
1104                 for dir in env::split_paths(&target_path) {
1105                     let p =  dir.join(&path);
1106                     if p.is_file() {
1107                         return load_file(&p);
1108                     }
1109                 }
1110                 Err(format!("Could not find specification for target {:?}", target_triple))
1111             }
1112             TargetTriple::TargetPath(ref target_path) => {
1113                 if target_path.is_file() {
1114                     return load_file(&target_path);
1115                 }
1116                 Err(format!("Target path {:?} is not a valid file", target_path))
1117             }
1118         }
1119     }
1120 }
1121
1122 impl ToJson for Target {
1123     fn to_json(&self) -> Json {
1124         let mut d = BTreeMap::new();
1125         let default: TargetOptions = Default::default();
1126
1127         macro_rules! target_val {
1128             ($attr:ident) => ( {
1129                 let name = (stringify!($attr)).replace("_", "-");
1130                 d.insert(name, self.$attr.to_json());
1131             } );
1132             ($attr:ident, $key_name:expr) => ( {
1133                 let name = $key_name;
1134                 d.insert(name.to_string(), self.$attr.to_json());
1135             } );
1136         }
1137
1138         macro_rules! target_option_val {
1139             ($attr:ident) => ( {
1140                 let name = (stringify!($attr)).replace("_", "-");
1141                 if default.$attr != self.options.$attr {
1142                     d.insert(name, self.options.$attr.to_json());
1143                 }
1144             } );
1145             ($attr:ident, $key_name:expr) => ( {
1146                 let name = $key_name;
1147                 if default.$attr != self.options.$attr {
1148                     d.insert(name.to_string(), self.options.$attr.to_json());
1149                 }
1150             } );
1151             (link_args - $attr:ident) => ( {
1152                 let name = (stringify!($attr)).replace("_", "-");
1153                 if default.$attr != self.options.$attr {
1154                     let obj = self.options.$attr
1155                         .iter()
1156                         .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1157                         .collect::<BTreeMap<_, _>>();
1158                     d.insert(name, obj.to_json());
1159                 }
1160             } );
1161             (env - $attr:ident) => ( {
1162                 let name = (stringify!($attr)).replace("_", "-");
1163                 if default.$attr != self.options.$attr {
1164                     let obj = self.options.$attr
1165                         .iter()
1166                         .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1167                         .collect::<Vec<_>>();
1168                     d.insert(name, obj.to_json());
1169                 }
1170             } );
1171
1172         }
1173
1174         target_val!(llvm_target);
1175         target_val!(target_endian);
1176         target_val!(target_pointer_width);
1177         target_val!(target_c_int_width);
1178         target_val!(arch);
1179         target_val!(target_os, "os");
1180         target_val!(target_env, "env");
1181         target_val!(target_vendor, "vendor");
1182         target_val!(data_layout);
1183         target_val!(linker_flavor);
1184
1185         target_option_val!(is_builtin);
1186         target_option_val!(linker);
1187         target_option_val!(lld_flavor);
1188         target_option_val!(link_args - pre_link_args);
1189         target_option_val!(link_args - pre_link_args_crt);
1190         target_option_val!(pre_link_objects_exe);
1191         target_option_val!(pre_link_objects_exe_crt);
1192         target_option_val!(pre_link_objects_dll);
1193         target_option_val!(link_args - late_link_args);
1194         target_option_val!(post_link_objects);
1195         target_option_val!(post_link_objects_crt);
1196         target_option_val!(link_args - post_link_args);
1197         target_option_val!(env - link_env);
1198         target_option_val!(asm_args);
1199         target_option_val!(cpu);
1200         target_option_val!(features);
1201         target_option_val!(dynamic_linking);
1202         target_option_val!(only_cdylib);
1203         target_option_val!(executables);
1204         target_option_val!(relocation_model);
1205         target_option_val!(code_model);
1206         target_option_val!(tls_model);
1207         target_option_val!(disable_redzone);
1208         target_option_val!(eliminate_frame_pointer);
1209         target_option_val!(function_sections);
1210         target_option_val!(dll_prefix);
1211         target_option_val!(dll_suffix);
1212         target_option_val!(exe_suffix);
1213         target_option_val!(staticlib_prefix);
1214         target_option_val!(staticlib_suffix);
1215         target_option_val!(target_family);
1216         target_option_val!(abi_return_struct_as_int);
1217         target_option_val!(is_like_osx);
1218         target_option_val!(is_like_solaris);
1219         target_option_val!(is_like_windows);
1220         target_option_val!(is_like_msvc);
1221         target_option_val!(is_like_emscripten);
1222         target_option_val!(is_like_android);
1223         target_option_val!(linker_is_gnu);
1224         target_option_val!(allows_weak_linkage);
1225         target_option_val!(has_rpath);
1226         target_option_val!(no_default_libraries);
1227         target_option_val!(position_independent_executables);
1228         target_option_val!(needs_plt);
1229         target_option_val!(relro_level);
1230         target_option_val!(archive_format);
1231         target_option_val!(allow_asm);
1232         target_option_val!(custom_unwind_resume);
1233         target_option_val!(has_elf_tls);
1234         target_option_val!(obj_is_bitcode);
1235         target_option_val!(no_integrated_as);
1236         target_option_val!(min_atomic_width);
1237         target_option_val!(max_atomic_width);
1238         target_option_val!(atomic_cas);
1239         target_option_val!(panic_strategy);
1240         target_option_val!(crt_static_allows_dylibs);
1241         target_option_val!(crt_static_default);
1242         target_option_val!(crt_static_respected);
1243         target_option_val!(stack_probes);
1244         target_option_val!(min_global_align);
1245         target_option_val!(default_codegen_units);
1246         target_option_val!(trap_unreachable);
1247         target_option_val!(requires_lto);
1248         target_option_val!(singlethread);
1249         target_option_val!(no_builtins);
1250         target_option_val!(codegen_backend);
1251         target_option_val!(default_hidden_visibility);
1252         target_option_val!(embed_bitcode);
1253         target_option_val!(emit_debug_gdb_scripts);
1254         target_option_val!(requires_uwtable);
1255         target_option_val!(simd_types_indirect);
1256
1257         if default.abi_blacklist != self.options.abi_blacklist {
1258             d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1259                 .map(|&name| Abi::name(name).to_json())
1260                 .collect::<Vec<_>>().to_json());
1261         }
1262
1263         Json::Object(d)
1264     }
1265 }
1266
1267 /// Either a target triple string or a path to a JSON file.
1268 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1269 pub enum TargetTriple {
1270     TargetTriple(String),
1271     TargetPath(PathBuf),
1272 }
1273
1274 impl TargetTriple {
1275     /// Creates a target triple from the passed target triple string.
1276     pub fn from_triple(triple: &str) -> Self {
1277         TargetTriple::TargetTriple(triple.to_string())
1278     }
1279
1280     /// Creates a target triple from the passed target path.
1281     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1282         let canonicalized_path = path.canonicalize()?;
1283         Ok(TargetTriple::TargetPath(canonicalized_path))
1284     }
1285
1286     /// Returns a string triple for this target.
1287     ///
1288     /// If this target is a path, the file name (without extension) is returned.
1289     pub fn triple(&self) -> &str {
1290         match *self {
1291             TargetTriple::TargetTriple(ref triple) => triple,
1292             TargetTriple::TargetPath(ref path) => {
1293                 path.file_stem().expect("target path must not be empty").to_str()
1294                     .expect("target path must be valid unicode")
1295             }
1296         }
1297     }
1298
1299     /// Returns an extended string triple for this target.
1300     ///
1301     /// If this target is a path, a hash of the path is appended to the triple returned
1302     /// by `triple()`.
1303     pub fn debug_triple(&self) -> String {
1304         use std::hash::{Hash, Hasher};
1305         use std::collections::hash_map::DefaultHasher;
1306
1307         let triple = self.triple();
1308         if let TargetTriple::TargetPath(ref path) = *self {
1309             let mut hasher = DefaultHasher::new();
1310             path.hash(&mut hasher);
1311             let hash = hasher.finish();
1312             format!("{}-{}", triple, hash)
1313         } else {
1314             triple.to_owned()
1315         }
1316     }
1317 }
1318
1319 impl fmt::Display for TargetTriple {
1320     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1321         write!(f, "{}", self.debug_triple())
1322     }
1323 }