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