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