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