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