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