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