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