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