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