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