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