]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
Rollup merge of #39426 - jakllsch:netbsd-c, r=alexcrichton
[rust.git] / src / librustc_back / target / 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::io::prelude::*;
51 use syntax::abi::{Abi, lookup as lookup_abi};
52
53 use PanicStrategy;
54
55 mod android_base;
56 mod apple_base;
57 mod apple_ios_base;
58 mod arm_base;
59 mod bitrig_base;
60 mod dragonfly_base;
61 mod emscripten_base;
62 mod freebsd_base;
63 mod haiku_base;
64 mod linux_base;
65 mod linux_musl_base;
66 mod openbsd_base;
67 mod netbsd_base;
68 mod solaris_base;
69 mod windows_base;
70 mod windows_msvc_base;
71 mod thumb_base;
72 mod fuchsia_base;
73 mod redox_base;
74
75 pub type TargetResult = Result<Target, String>;
76
77 macro_rules! supported_targets {
78     ( $(($triple:expr, $module:ident),)+ ) => (
79         $(mod $module;)*
80
81         /// List of supported targets
82         const TARGETS: &'static [&'static str] = &[$($triple),*];
83
84         fn load_specific(target: &str) -> TargetResult {
85             match target {
86                 $(
87                     $triple => {
88                         let mut t = $module::target()?;
89                         t.options.is_builtin = true;
90
91                         // round-trip through the JSON parser to ensure at
92                         // run-time that the parser works correctly
93                         t = Target::from_json(t.to_json())?;
94                         debug!("Got builtin target: {:?}", t);
95                         Ok(t)
96                     },
97                 )+
98                 _ => Err(format!("Unable to find target: {}", target))
99             }
100         }
101
102         pub fn get_targets() -> Box<Iterator<Item=String>> {
103             Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
104                 load_specific(t)
105                     .and(Ok(t.to_string()))
106                     .ok()
107             }))
108         }
109
110         #[cfg(test)]
111         mod test_json_encode_decode {
112             use serialize::json::ToJson;
113             use super::Target;
114             $(use super::$module;)*
115
116             $(
117                 #[test]
118                 fn $module() {
119                     // Grab the TargetResult struct. If we successfully retrieved
120                     // a Target, then the test JSON encoding/decoding can run for this
121                     // Target on this testing platform (i.e., checking the iOS targets
122                     // only on a Mac test platform).
123                     let _ = $module::target().map(|original| {
124                         let as_json = original.to_json();
125                         let parsed = Target::from_json(as_json).unwrap();
126                         assert_eq!(original, parsed);
127                     });
128                 }
129             )*
130         }
131     )
132 }
133
134 supported_targets! {
135     ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
136     ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
137     ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
138     ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
139     ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
140     ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
141     ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
142     ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
143     ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
144     ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
145     ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
146     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
147     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
148     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
149     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
150     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
151     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
152     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
153     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
154     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
155     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
156     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
157     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
158     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
159     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
160
161     ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
162
163     ("i686-linux-android", i686_linux_android),
164     ("arm-linux-androideabi", arm_linux_androideabi),
165     ("armv7-linux-androideabi", armv7_linux_androideabi),
166     ("aarch64-linux-android", aarch64_linux_android),
167
168     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
169     ("i686-unknown-freebsd", i686_unknown_freebsd),
170     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
171
172     ("i686-unknown-dragonfly", i686_unknown_dragonfly),
173     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
174
175     ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
176
177     ("i686-unknown-openbsd", i686_unknown_openbsd),
178     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
179
180     ("i686-unknown-netbsd", i686_unknown_netbsd),
181     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
182     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
183     ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
184
185     ("i686-unknown-haiku", i686_unknown_haiku),
186     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
187
188     ("x86_64-apple-darwin", x86_64_apple_darwin),
189     ("i686-apple-darwin", i686_apple_darwin),
190
191     ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia),
192     ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
193
194     ("x86_64-unknown-redox", x86_64_unknown_redox),
195
196     ("i386-apple-ios", i386_apple_ios),
197     ("x86_64-apple-ios", x86_64_apple_ios),
198     ("aarch64-apple-ios", aarch64_apple_ios),
199     ("armv7-apple-ios", armv7_apple_ios),
200     ("armv7s-apple-ios", armv7s_apple_ios),
201
202     ("x86_64-sun-solaris", x86_64_sun_solaris),
203
204     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
205     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
206
207     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
208     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
209     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
210
211     ("le32-unknown-nacl", le32_unknown_nacl),
212     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
213     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
214
215     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
216     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
217     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
218     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
219 }
220
221 /// Everything `rustc` knows about how to compile for a specific target.
222 ///
223 /// Every field here must be specified, and has no default value.
224 #[derive(PartialEq, Clone, Debug)]
225 pub struct Target {
226     /// Target triple to pass to LLVM.
227     pub llvm_target: String,
228     /// String to use as the `target_endian` `cfg` variable.
229     pub target_endian: String,
230     /// String to use as the `target_pointer_width` `cfg` variable.
231     pub target_pointer_width: String,
232     /// OS name to use for conditional compilation.
233     pub target_os: String,
234     /// Environment name to use for conditional compilation.
235     pub target_env: String,
236     /// Vendor name to use for conditional compilation.
237     pub target_vendor: String,
238     /// Architecture to use for ABI considerations. Valid options: "x86",
239     /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
240     pub arch: String,
241     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
242     pub data_layout: String,
243     /// Optional settings with defaults.
244     pub options: TargetOptions,
245 }
246
247 /// Optional aspects of a target specification.
248 ///
249 /// This has an implementation of `Default`, see each field for what the default is. In general,
250 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
251 #[derive(PartialEq, Clone, Debug)]
252 pub struct TargetOptions {
253     /// Whether the target is built-in or loaded from a custom target specification.
254     pub is_builtin: bool,
255
256     /// Linker to invoke. Defaults to "cc".
257     pub linker: String,
258     /// Archive utility to use when managing archives. Defaults to "ar".
259     pub ar: String,
260
261     /// Linker arguments that are unconditionally passed *before* any
262     /// user-defined libraries.
263     pub pre_link_args: Vec<String>,
264     /// Objects to link before all others, always found within the
265     /// sysroot folder.
266     pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
267     pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
268     /// Linker arguments that are unconditionally passed after any
269     /// user-defined but before post_link_objects.  Standard platform
270     /// libraries that should be always be linked to, usually go here.
271     pub late_link_args: Vec<String>,
272     /// Objects to link after all others, always found within the
273     /// sysroot folder.
274     pub post_link_objects: Vec<String>,
275     /// Linker arguments that are unconditionally passed *after* any
276     /// user-defined libraries.
277     pub post_link_args: Vec<String>,
278
279     /// Extra arguments to pass to the external assembler (when used)
280     pub asm_args: Vec<String>,
281
282     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
283     /// to "generic".
284     pub cpu: String,
285     /// Default target features to pass to LLVM. These features will *always* be
286     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
287     /// -mattr=$features`.
288     pub features: String,
289     /// Whether dynamic linking is available on this target. Defaults to false.
290     pub dynamic_linking: bool,
291     /// Whether executables are available on this target. iOS, for example, only allows static
292     /// libraries. Defaults to false.
293     pub executables: bool,
294     /// Relocation model to use in object file. Corresponds to `llc
295     /// -relocation-model=$relocation_model`. Defaults to "pic".
296     pub relocation_model: String,
297     /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
298     pub code_model: String,
299     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
300     pub disable_redzone: bool,
301     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
302     pub eliminate_frame_pointer: bool,
303     /// Emit each function in its own section. Defaults to true.
304     pub function_sections: bool,
305     /// String to prepend to the name of every dynamic library. Defaults to "lib".
306     pub dll_prefix: String,
307     /// String to append to the name of every dynamic library. Defaults to ".so".
308     pub dll_suffix: String,
309     /// String to append to the name of every executable.
310     pub exe_suffix: String,
311     /// String to prepend to the name of every static library. Defaults to "lib".
312     pub staticlib_prefix: String,
313     /// String to append to the name of every static library. Defaults to ".a".
314     pub staticlib_suffix: String,
315     /// OS family to use for conditional compilation. Valid options: "unix", "windows".
316     pub target_family: Option<String>,
317     /// Whether the target toolchain is like OpenBSD's.
318     /// Only useful for compiling against OpenBSD, for configuring abi when returning a struct.
319     pub is_like_openbsd: bool,
320     /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
321     /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
322     pub is_like_osx: bool,
323     /// Whether the target toolchain is like Solaris's.
324     /// Only useful for compiling against Illumos/Solaris,
325     /// as they have a different set of linker flags. Defaults to false.
326     pub is_like_solaris: bool,
327     /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
328     /// only really used for figuring out how to find libraries, since Windows uses its own
329     /// library naming convention. Defaults to false.
330     pub is_like_windows: bool,
331     pub is_like_msvc: bool,
332     /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
333     /// Defaults to false.
334     pub is_like_android: bool,
335     /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
336     /// Emscripten toolchain.
337     /// Defaults to false.
338     pub is_like_emscripten: bool,
339     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
340     pub linker_is_gnu: bool,
341     /// The MinGW toolchain has a known issue that prevents it from correctly
342     /// handling COFF object files with more than 2^15 sections. Since each weak
343     /// symbol needs its own COMDAT section, weak linkage implies a large
344     /// number sections that easily exceeds the given limit for larger
345     /// codebases. Consequently we want a way to disallow weak linkage on some
346     /// platforms.
347     pub allows_weak_linkage: bool,
348     /// Whether the linker support rpaths or not. Defaults to false.
349     pub has_rpath: bool,
350     /// Whether to disable linking to the default libraries, typically corresponds
351     /// to `-nodefaultlibs`. Defaults to true.
352     pub no_default_libraries: bool,
353     /// Dynamically linked executables can be compiled as position independent
354     /// if the default relocation model of position independent code is not
355     /// changed. This is a requirement to take advantage of ASLR, as otherwise
356     /// the functions in the executable are not randomized and can be used
357     /// during an exploit of a vulnerability in any code.
358     pub position_independent_executables: bool,
359     /// Format that archives should be emitted in. This affects whether we use
360     /// LLVM to assemble an archive or fall back to the system linker, and
361     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
362     /// the system linker to be used.
363     pub archive_format: String,
364     /// Is asm!() allowed? Defaults to true.
365     pub allow_asm: bool,
366     /// Whether the target uses a custom unwind resumption routine.
367     /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
368     /// defined in libgcc.  If this option is enabled, the target must provide
369     /// `eh_unwind_resume` lang item.
370     pub custom_unwind_resume: bool,
371
372     /// Default crate for allocation symbols to link against
373     pub lib_allocation_crate: String,
374     pub exe_allocation_crate: String,
375
376     /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
377     /// this target.
378     pub has_elf_tls: bool,
379     // This is mainly for easy compatibility with emscripten.
380     // If we give emcc .o files that are actually .bc files it
381     // will 'just work'.
382     pub obj_is_bitcode: bool,
383
384     // LLVM can't produce object files for this target. Instead, we'll make LLVM
385     // emit assembly and then use `gcc` to turn that assembly into an object
386     // file
387     pub no_integrated_as: bool,
388
389     /// Don't use this field; instead use the `.min_atomic_width()` method.
390     pub min_atomic_width: Option<u64>,
391
392     /// Don't use this field; instead use the `.max_atomic_width()` method.
393     pub max_atomic_width: Option<u64>,
394
395     /// Panic strategy: "unwind" or "abort"
396     pub panic_strategy: PanicStrategy,
397
398     /// A blacklist of ABIs unsupported by the current target. Note that generic
399     /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
400     pub abi_blacklist: Vec<Abi>,
401
402     /// Whether or not the CRT is statically linked by default.
403     pub crt_static_default: bool,
404 }
405
406 impl Default for TargetOptions {
407     /// Create a set of "sane defaults" for any target. This is still
408     /// incomplete, and if used for compilation, will certainly not work.
409     fn default() -> TargetOptions {
410         TargetOptions {
411             is_builtin: false,
412             linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
413             ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
414             pre_link_args: Vec::new(),
415             post_link_args: Vec::new(),
416             asm_args: Vec::new(),
417             cpu: "generic".to_string(),
418             features: "".to_string(),
419             dynamic_linking: false,
420             executables: false,
421             relocation_model: "pic".to_string(),
422             code_model: "default".to_string(),
423             disable_redzone: false,
424             eliminate_frame_pointer: true,
425             function_sections: true,
426             dll_prefix: "lib".to_string(),
427             dll_suffix: ".so".to_string(),
428             exe_suffix: "".to_string(),
429             staticlib_prefix: "lib".to_string(),
430             staticlib_suffix: ".a".to_string(),
431             target_family: None,
432             is_like_openbsd: false,
433             is_like_osx: false,
434             is_like_solaris: false,
435             is_like_windows: false,
436             is_like_android: false,
437             is_like_emscripten: false,
438             is_like_msvc: false,
439             linker_is_gnu: false,
440             allows_weak_linkage: true,
441             has_rpath: false,
442             no_default_libraries: true,
443             position_independent_executables: false,
444             pre_link_objects_exe: Vec::new(),
445             pre_link_objects_dll: Vec::new(),
446             post_link_objects: Vec::new(),
447             late_link_args: Vec::new(),
448             archive_format: "gnu".to_string(),
449             custom_unwind_resume: false,
450             lib_allocation_crate: "alloc_system".to_string(),
451             exe_allocation_crate: "alloc_system".to_string(),
452             allow_asm: true,
453             has_elf_tls: false,
454             obj_is_bitcode: false,
455             no_integrated_as: false,
456             min_atomic_width: None,
457             max_atomic_width: None,
458             panic_strategy: PanicStrategy::Unwind,
459             abi_blacklist: vec![],
460             crt_static_default: false,
461         }
462     }
463 }
464
465 impl Target {
466     /// Given a function ABI, turn "System" into the correct ABI for this target.
467     pub fn adjust_abi(&self, abi: Abi) -> Abi {
468         match abi {
469             Abi::System => {
470                 if self.options.is_like_windows && self.arch == "x86" {
471                     Abi::Stdcall
472                 } else {
473                     Abi::C
474                 }
475             },
476             abi => abi
477         }
478     }
479
480     /// Minimum integer size in bits that this target can perform atomic
481     /// operations on.
482     pub fn min_atomic_width(&self) -> u64 {
483         self.options.min_atomic_width.unwrap_or(8)
484     }
485
486     /// Maximum integer size in bits that this target can perform atomic
487     /// operations on.
488     pub fn max_atomic_width(&self) -> u64 {
489         self.options.max_atomic_width.unwrap_or(self.target_pointer_width.parse().unwrap())
490     }
491
492     pub fn is_abi_supported(&self, abi: Abi) -> bool {
493         abi.generic() || !self.options.abi_blacklist.contains(&abi)
494     }
495
496     /// Load a target descriptor from a JSON object.
497     pub fn from_json(obj: Json) -> TargetResult {
498         // While ugly, this code must remain this way to retain
499         // compatibility with existing JSON fields and the internal
500         // expected naming of the Target and TargetOptions structs.
501         // To ensure compatibility is retained, the built-in targets
502         // are round-tripped through this code to catch cases where
503         // the JSON parser is not updated to match the structs.
504
505         let get_req_field = |name: &str| {
506             match obj.find(name)
507                      .map(|s| s.as_string())
508                      .and_then(|os| os.map(|s| s.to_string())) {
509                 Some(val) => Ok(val),
510                 None => {
511                     return Err(format!("Field {} in target specification is required", name))
512                 }
513             }
514         };
515
516         let get_opt_field = |name: &str, default: &str| {
517             obj.find(name).and_then(|s| s.as_string())
518                .map(|s| s.to_string())
519                .unwrap_or(default.to_string())
520         };
521
522         let mut base = Target {
523             llvm_target: get_req_field("llvm-target")?,
524             target_endian: get_req_field("target-endian")?,
525             target_pointer_width: get_req_field("target-pointer-width")?,
526             data_layout: get_req_field("data-layout")?,
527             arch: get_req_field("arch")?,
528             target_os: get_req_field("os")?,
529             target_env: get_opt_field("env", ""),
530             target_vendor: get_opt_field("vendor", "unknown"),
531             options: Default::default(),
532         };
533
534         macro_rules! key {
535             ($key_name:ident) => ( {
536                 let name = (stringify!($key_name)).replace("_", "-");
537                 obj.find(&name[..]).map(|o| o.as_string()
538                                     .map(|s| base.options.$key_name = s.to_string()));
539             } );
540             ($key_name:ident, bool) => ( {
541                 let name = (stringify!($key_name)).replace("_", "-");
542                 obj.find(&name[..])
543                     .map(|o| o.as_boolean()
544                          .map(|s| base.options.$key_name = s));
545             } );
546             ($key_name:ident, Option<u64>) => ( {
547                 let name = (stringify!($key_name)).replace("_", "-");
548                 obj.find(&name[..])
549                     .map(|o| o.as_u64()
550                          .map(|s| base.options.$key_name = Some(s)));
551             } );
552             ($key_name:ident, PanicStrategy) => ( {
553                 let name = (stringify!($key_name)).replace("_", "-");
554                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
555                     match s {
556                         "unwind" => base.options.$key_name = PanicStrategy::Unwind,
557                         "abort" => base.options.$key_name = PanicStrategy::Abort,
558                         _ => return Some(Err(format!("'{}' is not a valid value for \
559                                                       panic-strategy. Use 'unwind' or 'abort'.",
560                                                      s))),
561                 }
562                 Some(Ok(()))
563             })).unwrap_or(Ok(()))
564             } );
565             ($key_name:ident, list) => ( {
566                 let name = (stringify!($key_name)).replace("_", "-");
567                 obj.find(&name[..]).map(|o| o.as_array()
568                     .map(|v| base.options.$key_name = v.iter()
569                         .map(|a| a.as_string().unwrap().to_string()).collect()
570                         )
571                     );
572             } );
573             ($key_name:ident, optional) => ( {
574                 let name = (stringify!($key_name)).replace("_", "-");
575                 if let Some(o) = obj.find(&name[..]) {
576                     base.options.$key_name = o
577                         .as_string()
578                         .map(|s| s.to_string() );
579                 }
580             } );
581         }
582
583         key!(is_builtin, bool);
584         key!(linker);
585         key!(ar);
586         key!(pre_link_args, list);
587         key!(pre_link_objects_exe, list);
588         key!(pre_link_objects_dll, list);
589         key!(late_link_args, list);
590         key!(post_link_objects, list);
591         key!(post_link_args, list);
592         key!(asm_args, list);
593         key!(cpu);
594         key!(features);
595         key!(dynamic_linking, bool);
596         key!(executables, bool);
597         key!(relocation_model);
598         key!(code_model);
599         key!(disable_redzone, bool);
600         key!(eliminate_frame_pointer, bool);
601         key!(function_sections, bool);
602         key!(dll_prefix);
603         key!(dll_suffix);
604         key!(exe_suffix);
605         key!(staticlib_prefix);
606         key!(staticlib_suffix);
607         key!(target_family, optional);
608         key!(is_like_openbsd, bool);
609         key!(is_like_osx, bool);
610         key!(is_like_solaris, bool);
611         key!(is_like_windows, bool);
612         key!(is_like_msvc, bool);
613         key!(is_like_emscripten, bool);
614         key!(is_like_android, bool);
615         key!(linker_is_gnu, bool);
616         key!(allows_weak_linkage, bool);
617         key!(has_rpath, bool);
618         key!(no_default_libraries, bool);
619         key!(position_independent_executables, bool);
620         key!(archive_format);
621         key!(allow_asm, bool);
622         key!(custom_unwind_resume, bool);
623         key!(lib_allocation_crate);
624         key!(exe_allocation_crate);
625         key!(has_elf_tls, bool);
626         key!(obj_is_bitcode, bool);
627         key!(no_integrated_as, bool);
628         key!(max_atomic_width, Option<u64>);
629         key!(min_atomic_width, Option<u64>);
630         try!(key!(panic_strategy, PanicStrategy));
631         key!(crt_static_default, bool);
632
633         if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
634             for name in array.iter().filter_map(|abi| abi.as_string()) {
635                 match lookup_abi(name) {
636                     Some(abi) => {
637                         if abi.generic() {
638                             return Err(format!("The ABI \"{}\" is considered to be supported on \
639                                                 all targets and cannot be blacklisted", abi))
640                         }
641
642                         base.options.abi_blacklist.push(abi)
643                     }
644                     None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
645                 }
646             }
647         }
648
649         Ok(base)
650     }
651
652     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
653     /// triple. Note that it could also just be a bare filename already, so also
654     /// check for that. If one of the hardcoded targets we know about, just
655     /// return it directly.
656     ///
657     /// The error string could come from any of the APIs called, including
658     /// filesystem access and JSON decoding.
659     pub fn search(target: &str) -> Result<Target, String> {
660         use std::env;
661         use std::ffi::OsString;
662         use std::fs::File;
663         use std::path::{Path, PathBuf};
664         use serialize::json;
665
666         fn load_file(path: &Path) -> Result<Target, String> {
667             let mut f = File::open(path).map_err(|e| e.to_string())?;
668             let mut contents = Vec::new();
669             f.read_to_end(&mut contents).map_err(|e| e.to_string())?;
670             let obj = json::from_reader(&mut &contents[..])
671                            .map_err(|e| e.to_string())?;
672             Target::from_json(obj)
673         }
674
675         if let Ok(t) = load_specific(target) {
676             return Ok(t)
677         }
678
679         let path = Path::new(target);
680
681         if path.is_file() {
682             return load_file(&path);
683         }
684
685         let path = {
686             let mut target = target.to_string();
687             target.push_str(".json");
688             PathBuf::from(target)
689         };
690
691         let target_path = env::var_os("RUST_TARGET_PATH")
692                               .unwrap_or(OsString::new());
693
694         // FIXME 16351: add a sane default search path?
695
696         for dir in env::split_paths(&target_path) {
697             let p =  dir.join(&path);
698             if p.is_file() {
699                 return load_file(&p);
700             }
701         }
702
703         Err(format!("Could not find specification for target {:?}", target))
704     }
705 }
706
707 impl ToJson for Target {
708     fn to_json(&self) -> Json {
709         let mut d = BTreeMap::new();
710         let default: TargetOptions = Default::default();
711
712         macro_rules! target_val {
713             ($attr:ident) => ( {
714                 let name = (stringify!($attr)).replace("_", "-");
715                 d.insert(name.to_string(), self.$attr.to_json());
716             } );
717             ($attr:ident, $key_name:expr) => ( {
718                 let name = $key_name;
719                 d.insert(name.to_string(), self.$attr.to_json());
720             } );
721         }
722
723         macro_rules! target_option_val {
724             ($attr:ident) => ( {
725                 let name = (stringify!($attr)).replace("_", "-");
726                 if default.$attr != self.options.$attr {
727                     d.insert(name.to_string(), self.options.$attr.to_json());
728                 }
729             } );
730             ($attr:ident, $key_name:expr) => ( {
731                 let name = $key_name;
732                 if default.$attr != self.options.$attr {
733                     d.insert(name.to_string(), self.options.$attr.to_json());
734                 }
735             } );
736         }
737
738         target_val!(llvm_target);
739         target_val!(target_endian);
740         target_val!(target_pointer_width);
741         target_val!(arch);
742         target_val!(target_os, "os");
743         target_val!(target_env, "env");
744         target_val!(target_vendor, "vendor");
745         target_val!(arch);
746         target_val!(data_layout);
747
748         target_option_val!(is_builtin);
749         target_option_val!(linker);
750         target_option_val!(ar);
751         target_option_val!(pre_link_args);
752         target_option_val!(pre_link_objects_exe);
753         target_option_val!(pre_link_objects_dll);
754         target_option_val!(late_link_args);
755         target_option_val!(post_link_objects);
756         target_option_val!(post_link_args);
757         target_option_val!(asm_args);
758         target_option_val!(cpu);
759         target_option_val!(features);
760         target_option_val!(dynamic_linking);
761         target_option_val!(executables);
762         target_option_val!(relocation_model);
763         target_option_val!(code_model);
764         target_option_val!(disable_redzone);
765         target_option_val!(eliminate_frame_pointer);
766         target_option_val!(function_sections);
767         target_option_val!(dll_prefix);
768         target_option_val!(dll_suffix);
769         target_option_val!(exe_suffix);
770         target_option_val!(staticlib_prefix);
771         target_option_val!(staticlib_suffix);
772         target_option_val!(target_family);
773         target_option_val!(is_like_openbsd);
774         target_option_val!(is_like_osx);
775         target_option_val!(is_like_solaris);
776         target_option_val!(is_like_windows);
777         target_option_val!(is_like_msvc);
778         target_option_val!(is_like_emscripten);
779         target_option_val!(is_like_android);
780         target_option_val!(linker_is_gnu);
781         target_option_val!(allows_weak_linkage);
782         target_option_val!(has_rpath);
783         target_option_val!(no_default_libraries);
784         target_option_val!(position_independent_executables);
785         target_option_val!(archive_format);
786         target_option_val!(allow_asm);
787         target_option_val!(custom_unwind_resume);
788         target_option_val!(lib_allocation_crate);
789         target_option_val!(exe_allocation_crate);
790         target_option_val!(has_elf_tls);
791         target_option_val!(obj_is_bitcode);
792         target_option_val!(no_integrated_as);
793         target_option_val!(min_atomic_width);
794         target_option_val!(max_atomic_width);
795         target_option_val!(panic_strategy);
796         target_option_val!(crt_static_default);
797
798         if default.abi_blacklist != self.options.abi_blacklist {
799             d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
800                 .map(Abi::name).map(|name| name.to_json())
801                 .collect::<Vec<_>>().to_json());
802         }
803
804         Json::Object(d)
805     }
806 }
807
808 fn maybe_jemalloc() -> String {
809     if cfg!(feature = "jemalloc") {
810         "alloc_jemalloc".to_string()
811     } else {
812         "alloc_system".to_string()
813     }
814 }