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