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