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;
51 use std::path::{Path, PathBuf};
52 use std::str::FromStr;
53 use spec::abi::{Abi, lookup as lookup_abi};
71 mod windows_msvc_base;
77 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
78 RustcEncodable, RustcDecodable)]
79 pub enum LinkerFlavor {
87 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
88 RustcEncodable, RustcDecodable)]
96 impl ToJson for LinkerFlavor {
97 fn to_json(&self) -> Json {
101 macro_rules! flavor_mappings {
102 ($((($($flavor:tt)*), $string:expr),)*) => (
104 pub const fn one_of() -> &'static str {
105 concat!("one of: ", $($string, " ",)+)
108 pub fn from_str(s: &str) -> Option<Self> {
110 $($string => $($flavor)*,)+
115 pub fn desc(&self) -> &str {
117 $($($flavor)* => $string,)+
126 ((LinkerFlavor::Em), "em"),
127 ((LinkerFlavor::Gcc), "gcc"),
128 ((LinkerFlavor::Ld), "ld"),
129 ((LinkerFlavor::Msvc), "msvc"),
130 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
131 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
132 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
133 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
136 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
137 pub enum PanicStrategy {
143 pub fn desc(&self) -> &str {
145 PanicStrategy::Unwind => "unwind",
146 PanicStrategy::Abort => "abort",
151 impl ToJson for PanicStrategy {
152 fn to_json(&self) -> Json {
154 PanicStrategy::Abort => "abort".to_json(),
155 PanicStrategy::Unwind => "unwind".to_json(),
160 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
161 pub enum RelroLevel {
169 pub fn desc(&self) -> &str {
171 RelroLevel::Full => "full",
172 RelroLevel::Partial => "partial",
173 RelroLevel::Off => "off",
174 RelroLevel::None => "none",
179 impl FromStr for RelroLevel {
182 fn from_str(s: &str) -> Result<RelroLevel, ()> {
184 "full" => Ok(RelroLevel::Full),
185 "partial" => Ok(RelroLevel::Partial),
186 "off" => Ok(RelroLevel::Off),
187 "none" => Ok(RelroLevel::None),
193 impl ToJson for RelroLevel {
194 fn to_json(&self) -> Json {
196 RelroLevel::Full => "full".to_json(),
197 RelroLevel::Partial => "partial".to_json(),
198 RelroLevel::Off => "off".to_json(),
199 RelroLevel::None => "None".to_json(),
204 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
205 pub type TargetResult = Result<Target, String>;
207 macro_rules! supported_targets {
208 ( $(($triple:expr, $module:ident),)+ ) => (
211 /// List of supported targets
212 const TARGETS: &'static [&'static str] = &[$($triple),*];
214 fn load_specific(target: &str) -> TargetResult {
218 let mut t = $module::target()?;
219 t.options.is_builtin = true;
221 // round-trip through the JSON parser to ensure at
222 // run-time that the parser works correctly
223 t = Target::from_json(t.to_json())?;
224 debug!("Got builtin target: {:?}", t);
228 _ => Err(format!("Unable to find target: {}", target))
232 pub fn get_targets() -> Box<Iterator<Item=String>> {
233 Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
235 .and(Ok(t.to_string()))
241 mod test_json_encode_decode {
242 use serialize::json::ToJson;
244 $(use super::$module;)*
249 // Grab the TargetResult struct. If we successfully retrieved
250 // a Target, then the test JSON encoding/decoding can run for this
251 // Target on this testing platform (i.e., checking the iOS targets
252 // only on a Mac test platform).
253 let _ = $module::target().map(|original| {
254 let as_json = original.to_json();
255 let parsed = Target::from_json(as_json).unwrap();
256 assert_eq!(original, parsed);
265 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
266 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
267 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
268 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
269 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
270 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
271 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
272 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
273 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
274 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
275 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
276 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
277 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
278 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
279 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
280 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
281 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
282 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
283 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
284 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
285 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
286 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
287 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
288 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
289 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
291 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
292 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
293 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
294 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
295 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
296 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
298 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
299 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
301 ("i686-linux-android", i686_linux_android),
302 ("x86_64-linux-android", x86_64_linux_android),
303 ("arm-linux-androideabi", arm_linux_androideabi),
304 ("armv7-linux-androideabi", armv7_linux_androideabi),
305 ("aarch64-linux-android", aarch64_linux_android),
307 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
308 ("i686-unknown-freebsd", i686_unknown_freebsd),
309 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
311 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
312 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
314 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
316 ("i686-unknown-openbsd", i686_unknown_openbsd),
317 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
319 ("i686-unknown-netbsd", i686_unknown_netbsd),
320 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
321 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
322 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
323 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
325 ("i686-unknown-haiku", i686_unknown_haiku),
326 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
328 ("x86_64-apple-darwin", x86_64_apple_darwin),
329 ("i686-apple-darwin", i686_apple_darwin),
331 ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia),
332 ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
334 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
336 ("x86_64-unknown-redox", x86_64_unknown_redox),
338 ("i386-apple-ios", i386_apple_ios),
339 ("x86_64-apple-ios", x86_64_apple_ios),
340 ("aarch64-apple-ios", aarch64_apple_ios),
341 ("armv7-apple-ios", armv7_apple_ios),
342 ("armv7s-apple-ios", armv7s_apple_ios),
344 ("x86_64-sun-solaris", x86_64_sun_solaris),
345 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
347 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
348 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
350 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
351 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
352 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
354 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
355 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
356 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
357 ("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
359 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
360 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
361 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
362 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
364 ("msp430-none-elf", msp430_none_elf),
366 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
367 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
368 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
369 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
372 /// Everything `rustc` knows about how to compile for a specific target.
374 /// Every field here must be specified, and has no default value.
375 #[derive(PartialEq, Clone, Debug)]
377 /// Target triple to pass to LLVM.
378 pub llvm_target: String,
379 /// String to use as the `target_endian` `cfg` variable.
380 pub target_endian: String,
381 /// String to use as the `target_pointer_width` `cfg` variable.
382 pub target_pointer_width: String,
383 /// Width of c_int type
384 pub target_c_int_width: String,
385 /// OS name to use for conditional compilation.
386 pub target_os: String,
387 /// Environment name to use for conditional compilation.
388 pub target_env: String,
389 /// Vendor name to use for conditional compilation.
390 pub target_vendor: String,
391 /// Architecture to use for ABI considerations. Valid options: "x86",
392 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
394 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
395 pub data_layout: String,
397 pub linker_flavor: LinkerFlavor,
398 /// Optional settings with defaults.
399 pub options: TargetOptions,
402 pub trait HasTargetSpec: Copy {
403 fn target_spec(&self) -> &Target;
406 impl<'a> HasTargetSpec for &'a Target {
407 fn target_spec(&self) -> &Target {
412 /// Optional aspects of a target specification.
414 /// This has an implementation of `Default`, see each field for what the default is. In general,
415 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
416 #[derive(PartialEq, Clone, Debug)]
417 pub struct TargetOptions {
418 /// Whether the target is built-in or loaded from a custom target specification.
419 pub is_builtin: bool,
422 pub linker: Option<String>,
424 /// Linker arguments that are unconditionally passed *before* any
425 /// user-defined libraries.
426 pub pre_link_args: LinkArgs,
427 /// Objects to link before all others, always found within the
429 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
430 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
431 /// Linker arguments that are unconditionally passed after any
432 /// user-defined but before post_link_objects. Standard platform
433 /// libraries that should be always be linked to, usually go here.
434 pub late_link_args: LinkArgs,
435 /// Objects to link after all others, always found within the
437 pub post_link_objects: Vec<String>,
438 /// Linker arguments that are unconditionally passed *after* any
439 /// user-defined libraries.
440 pub post_link_args: LinkArgs,
442 /// Environment variables to be set before invoking the linker.
443 pub link_env: Vec<(String, String)>,
445 /// Extra arguments to pass to the external assembler (when used)
446 pub asm_args: Vec<String>,
448 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
451 /// Default target features to pass to LLVM. These features will *always* be
452 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
453 /// -mattr=$features`.
454 pub features: String,
455 /// Whether dynamic linking is available on this target. Defaults to false.
456 pub dynamic_linking: bool,
457 /// If dynamic linking is available, whether only cdylibs are supported.
458 pub only_cdylib: bool,
459 /// Whether executables are available on this target. iOS, for example, only allows static
460 /// libraries. Defaults to false.
461 pub executables: bool,
462 /// Relocation model to use in object file. Corresponds to `llc
463 /// -relocation-model=$relocation_model`. Defaults to "pic".
464 pub relocation_model: String,
465 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
466 pub code_model: Option<String>,
467 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
468 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
469 pub tls_model: String,
470 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
471 pub disable_redzone: bool,
472 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
473 pub eliminate_frame_pointer: bool,
474 /// Emit each function in its own section. Defaults to true.
475 pub function_sections: bool,
476 /// String to prepend to the name of every dynamic library. Defaults to "lib".
477 pub dll_prefix: String,
478 /// String to append to the name of every dynamic library. Defaults to ".so".
479 pub dll_suffix: String,
480 /// String to append to the name of every executable.
481 pub exe_suffix: String,
482 /// String to prepend to the name of every static library. Defaults to "lib".
483 pub staticlib_prefix: String,
484 /// String to append to the name of every static library. Defaults to ".a".
485 pub staticlib_suffix: String,
486 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
487 pub target_family: Option<String>,
488 /// Whether the target toolchain's ABI supports returning small structs as an integer.
489 pub abi_return_struct_as_int: bool,
490 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
491 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
492 pub is_like_osx: bool,
493 /// Whether the target toolchain is like Solaris's.
494 /// Only useful for compiling against Illumos/Solaris,
495 /// as they have a different set of linker flags. Defaults to false.
496 pub is_like_solaris: bool,
497 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
498 /// only really used for figuring out how to find libraries, since Windows uses its own
499 /// library naming convention. Defaults to false.
500 pub is_like_windows: bool,
501 pub is_like_msvc: bool,
502 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
503 /// Defaults to false.
504 pub is_like_android: bool,
505 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
506 /// Emscripten toolchain.
507 /// Defaults to false.
508 pub is_like_emscripten: bool,
509 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
510 pub linker_is_gnu: bool,
511 /// The MinGW toolchain has a known issue that prevents it from correctly
512 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
513 /// symbol needs its own COMDAT section, weak linkage implies a large
514 /// number sections that easily exceeds the given limit for larger
515 /// codebases. Consequently we want a way to disallow weak linkage on some
517 pub allows_weak_linkage: bool,
518 /// Whether the linker support rpaths or not. Defaults to false.
520 /// Whether to disable linking to the default libraries, typically corresponds
521 /// to `-nodefaultlibs`. Defaults to true.
522 pub no_default_libraries: bool,
523 /// Dynamically linked executables can be compiled as position independent
524 /// if the default relocation model of position independent code is not
525 /// changed. This is a requirement to take advantage of ASLR, as otherwise
526 /// the functions in the executable are not randomized and can be used
527 /// during an exploit of a vulnerability in any code.
528 pub position_independent_executables: bool,
529 /// Either partial, full, or off. Full RELRO makes the dynamic linker
530 /// resolve all symbols at startup and marks the GOT read-only before
531 /// starting the program, preventing overwriting the GOT.
532 pub relro_level: RelroLevel,
533 /// Format that archives should be emitted in. This affects whether we use
534 /// LLVM to assemble an archive or fall back to the system linker, and
535 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
536 /// the system linker to be used.
537 pub archive_format: String,
538 /// Is asm!() allowed? Defaults to true.
540 /// Whether the target uses a custom unwind resumption routine.
541 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
542 /// defined in libgcc. If this option is enabled, the target must provide
543 /// `eh_unwind_resume` lang item.
544 pub custom_unwind_resume: bool,
546 /// If necessary, a different crate to link exe allocators by default
547 pub exe_allocation_crate: Option<String>,
549 /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
551 pub has_elf_tls: bool,
552 // This is mainly for easy compatibility with emscripten.
553 // If we give emcc .o files that are actually .bc files it
555 pub obj_is_bitcode: bool,
557 // LLVM can't produce object files for this target. Instead, we'll make LLVM
558 // emit assembly and then use `gcc` to turn that assembly into an object
560 pub no_integrated_as: bool,
562 /// Don't use this field; instead use the `.min_atomic_width()` method.
563 pub min_atomic_width: Option<u64>,
565 /// Don't use this field; instead use the `.max_atomic_width()` method.
566 pub max_atomic_width: Option<u64>,
568 /// Panic strategy: "unwind" or "abort"
569 pub panic_strategy: PanicStrategy,
571 /// A blacklist of ABIs unsupported by the current target. Note that generic
572 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
573 pub abi_blacklist: Vec<Abi>,
575 /// Whether or not linking dylibs to a static CRT is allowed.
576 pub crt_static_allows_dylibs: bool,
577 /// Whether or not the CRT is statically linked by default.
578 pub crt_static_default: bool,
579 /// Whether or not crt-static is respected by the compiler (or is a no-op).
580 pub crt_static_respected: bool,
582 /// Whether or not stack probes (__rust_probestack) are enabled
583 pub stack_probes: bool,
585 /// The minimum alignment for global symbols.
586 pub min_global_align: Option<u64>,
588 /// Default number of codegen units to use in debug mode
589 pub default_codegen_units: Option<u64>,
591 /// Whether to generate trap instructions in places where optimization would
592 /// otherwise produce control flow that falls through into unrelated memory.
593 pub trap_unreachable: bool,
595 /// This target requires everything to be compiled with LTO to emit a final
596 /// executable, aka there is no native linker for this target.
597 pub requires_lto: bool,
599 /// This target has no support for threads.
600 pub singlethread: bool,
602 /// Whether library functions call lowering/optimization is disabled in LLVM
603 /// for this target unconditionally.
604 pub no_builtins: bool,
606 /// Whether to lower 128-bit operations to compiler_builtins calls. Use if
607 /// your backend only supports 64-bit and smaller math.
608 pub i128_lowering: bool,
610 /// The codegen backend to use for this target, typically "llvm"
611 pub codegen_backend: String,
613 /// The default visibility for symbols in this target should be "hidden"
614 /// rather than "default"
615 pub default_hidden_visibility: bool,
617 /// Whether or not bitcode is embedded in object files
618 pub embed_bitcode: bool,
620 /// Whether a .debug_gdb_scripts section will be added to the output object file
621 pub emit_debug_gdb_scripts: bool,
623 /// Whether or not to unconditionally `uwtable` attributes on functions,
624 /// typically because the platform needs to unwind for things like stack
626 pub requires_uwtable: bool,
629 impl Default for TargetOptions {
630 /// Create a set of "sane defaults" for any target. This is still
631 /// incomplete, and if used for compilation, will certainly not work.
632 fn default() -> TargetOptions {
635 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
636 pre_link_args: LinkArgs::new(),
637 post_link_args: LinkArgs::new(),
638 asm_args: Vec::new(),
639 cpu: "generic".to_string(),
640 features: "".to_string(),
641 dynamic_linking: false,
644 relocation_model: "pic".to_string(),
646 tls_model: "global-dynamic".to_string(),
647 disable_redzone: false,
648 eliminate_frame_pointer: true,
649 function_sections: true,
650 dll_prefix: "lib".to_string(),
651 dll_suffix: ".so".to_string(),
652 exe_suffix: "".to_string(),
653 staticlib_prefix: "lib".to_string(),
654 staticlib_suffix: ".a".to_string(),
656 abi_return_struct_as_int: false,
658 is_like_solaris: false,
659 is_like_windows: false,
660 is_like_android: false,
661 is_like_emscripten: false,
663 linker_is_gnu: false,
664 allows_weak_linkage: true,
666 no_default_libraries: true,
667 position_independent_executables: false,
668 relro_level: RelroLevel::None,
669 pre_link_objects_exe: Vec::new(),
670 pre_link_objects_dll: Vec::new(),
671 post_link_objects: Vec::new(),
672 late_link_args: LinkArgs::new(),
673 link_env: Vec::new(),
674 archive_format: "gnu".to_string(),
675 custom_unwind_resume: false,
676 exe_allocation_crate: None,
679 obj_is_bitcode: false,
680 no_integrated_as: false,
681 min_atomic_width: None,
682 max_atomic_width: None,
683 panic_strategy: PanicStrategy::Unwind,
684 abi_blacklist: vec![],
685 crt_static_allows_dylibs: false,
686 crt_static_default: false,
687 crt_static_respected: false,
689 min_global_align: None,
690 default_codegen_units: None,
691 trap_unreachable: true,
695 i128_lowering: false,
696 codegen_backend: "llvm".to_string(),
697 default_hidden_visibility: false,
698 embed_bitcode: false,
699 emit_debug_gdb_scripts: true,
700 requires_uwtable: false,
706 /// Given a function ABI, turn "System" into the correct ABI for this target.
707 pub fn adjust_abi(&self, abi: Abi) -> Abi {
710 if self.options.is_like_windows && self.arch == "x86" {
720 /// Minimum integer size in bits that this target can perform atomic
722 pub fn min_atomic_width(&self) -> u64 {
723 self.options.min_atomic_width.unwrap_or(8)
726 /// Maximum integer size in bits that this target can perform atomic
728 pub fn max_atomic_width(&self) -> u64 {
729 self.options.max_atomic_width.unwrap_or(self.target_pointer_width.parse().unwrap())
732 pub fn is_abi_supported(&self, abi: Abi) -> bool {
733 abi.generic() || !self.options.abi_blacklist.contains(&abi)
736 /// Load a target descriptor from a JSON object.
737 pub fn from_json(obj: Json) -> TargetResult {
738 // While ugly, this code must remain this way to retain
739 // compatibility with existing JSON fields and the internal
740 // expected naming of the Target and TargetOptions structs.
741 // To ensure compatibility is retained, the built-in targets
742 // are round-tripped through this code to catch cases where
743 // the JSON parser is not updated to match the structs.
745 let get_req_field = |name: &str| {
747 .map(|s| s.as_string())
748 .and_then(|os| os.map(|s| s.to_string())) {
749 Some(val) => Ok(val),
751 return Err(format!("Field {} in target specification is required", name))
756 let get_opt_field = |name: &str, default: &str| {
757 obj.find(name).and_then(|s| s.as_string())
758 .map(|s| s.to_string())
759 .unwrap_or(default.to_string())
762 let mut base = Target {
763 llvm_target: get_req_field("llvm-target")?,
764 target_endian: get_req_field("target-endian")?,
765 target_pointer_width: get_req_field("target-pointer-width")?,
766 target_c_int_width: get_req_field("target-c-int-width")?,
767 data_layout: get_req_field("data-layout")?,
768 arch: get_req_field("arch")?,
769 target_os: get_req_field("os")?,
770 target_env: get_opt_field("env", ""),
771 target_vendor: get_opt_field("vendor", "unknown"),
772 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
774 format!("linker flavor must be {}", LinkerFlavor::one_of())
776 options: Default::default(),
780 ($key_name:ident) => ( {
781 let name = (stringify!($key_name)).replace("_", "-");
782 obj.find(&name[..]).map(|o| o.as_string()
783 .map(|s| base.options.$key_name = s.to_string()));
785 ($key_name:ident, bool) => ( {
786 let name = (stringify!($key_name)).replace("_", "-");
788 .map(|o| o.as_boolean()
789 .map(|s| base.options.$key_name = s));
791 ($key_name:ident, Option<u64>) => ( {
792 let name = (stringify!($key_name)).replace("_", "-");
795 .map(|s| base.options.$key_name = Some(s)));
797 ($key_name:ident, PanicStrategy) => ( {
798 let name = (stringify!($key_name)).replace("_", "-");
799 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
801 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
802 "abort" => base.options.$key_name = PanicStrategy::Abort,
803 _ => return Some(Err(format!("'{}' is not a valid value for \
804 panic-strategy. Use 'unwind' or 'abort'.",
808 })).unwrap_or(Ok(()))
810 ($key_name:ident, RelroLevel) => ( {
811 let name = (stringify!($key_name)).replace("_", "-");
812 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
813 match s.parse::<RelroLevel>() {
814 Ok(level) => base.options.$key_name = level,
815 _ => return Some(Err(format!("'{}' is not a valid value for \
816 relro-level. Use 'full', 'partial, or 'off'.",
820 })).unwrap_or(Ok(()))
822 ($key_name:ident, list) => ( {
823 let name = (stringify!($key_name)).replace("_", "-");
824 obj.find(&name[..]).map(|o| o.as_array()
825 .map(|v| base.options.$key_name = v.iter()
826 .map(|a| a.as_string().unwrap().to_string()).collect()
830 ($key_name:ident, optional) => ( {
831 let name = (stringify!($key_name)).replace("_", "-");
832 if let Some(o) = obj.find(&name[..]) {
833 base.options.$key_name = o
835 .map(|s| s.to_string() );
838 ($key_name:ident, LinkerFlavor) => ( {
839 let name = (stringify!($key_name)).replace("_", "-");
840 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
841 LinkerFlavor::from_str(&s).ok_or_else(|| {
842 Err(format!("'{}' is not a valid value for linker-flavor. \
843 Use 'em', 'gcc', 'ld' or 'msvc.", s))
845 })).unwrap_or(Ok(()))
847 ($key_name:ident, link_args) => ( {
848 let name = (stringify!($key_name)).replace("_", "-");
849 if let Some(obj) = obj.find(&name[..]).and_then(|o| o.as_object()) {
850 let mut args = LinkArgs::new();
852 let k = LinkerFlavor::from_str(&k).ok_or_else(|| {
853 format!("{}: '{}' is not a valid value for linker-flavor. \
854 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
857 let v = v.as_array().map(|a| {
860 .filter_map(|o| o.as_string())
861 .map(|s| s.to_owned())
863 }).unwrap_or(vec![]);
867 base.options.$key_name = args;
870 ($key_name:ident, env) => ( {
871 let name = (stringify!($key_name)).replace("_", "-");
872 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
874 if let Some(s) = o.as_string() {
875 let p = s.split('=').collect::<Vec<_>>();
877 let k = p[0].to_string();
878 let v = p[1].to_string();
879 base.options.$key_name.push((k, v));
887 key!(is_builtin, bool);
888 key!(linker, optional);
889 key!(pre_link_args, link_args);
890 key!(pre_link_objects_exe, list);
891 key!(pre_link_objects_dll, list);
892 key!(late_link_args, link_args);
893 key!(post_link_objects, list);
894 key!(post_link_args, link_args);
896 key!(asm_args, list);
899 key!(dynamic_linking, bool);
900 key!(only_cdylib, bool);
901 key!(executables, bool);
902 key!(relocation_model);
903 key!(code_model, optional);
905 key!(disable_redzone, bool);
906 key!(eliminate_frame_pointer, bool);
907 key!(function_sections, bool);
911 key!(staticlib_prefix);
912 key!(staticlib_suffix);
913 key!(target_family, optional);
914 key!(abi_return_struct_as_int, bool);
915 key!(is_like_osx, bool);
916 key!(is_like_solaris, bool);
917 key!(is_like_windows, bool);
918 key!(is_like_msvc, bool);
919 key!(is_like_emscripten, bool);
920 key!(is_like_android, bool);
921 key!(linker_is_gnu, bool);
922 key!(allows_weak_linkage, bool);
923 key!(has_rpath, bool);
924 key!(no_default_libraries, bool);
925 key!(position_independent_executables, bool);
926 try!(key!(relro_level, RelroLevel));
927 key!(archive_format);
928 key!(allow_asm, bool);
929 key!(custom_unwind_resume, bool);
930 key!(exe_allocation_crate, optional);
931 key!(has_elf_tls, bool);
932 key!(obj_is_bitcode, bool);
933 key!(no_integrated_as, bool);
934 key!(max_atomic_width, Option<u64>);
935 key!(min_atomic_width, Option<u64>);
936 try!(key!(panic_strategy, PanicStrategy));
937 key!(crt_static_allows_dylibs, bool);
938 key!(crt_static_default, bool);
939 key!(crt_static_respected, bool);
940 key!(stack_probes, bool);
941 key!(min_global_align, Option<u64>);
942 key!(default_codegen_units, Option<u64>);
943 key!(trap_unreachable, bool);
944 key!(requires_lto, bool);
945 key!(singlethread, bool);
946 key!(no_builtins, bool);
947 key!(codegen_backend);
948 key!(default_hidden_visibility, bool);
949 key!(embed_bitcode, bool);
950 key!(emit_debug_gdb_scripts, bool);
951 key!(requires_uwtable, bool);
953 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
954 for name in array.iter().filter_map(|abi| abi.as_string()) {
955 match lookup_abi(name) {
958 return Err(format!("The ABI \"{}\" is considered to be supported on \
959 all targets and cannot be blacklisted", abi))
962 base.options.abi_blacklist.push(abi)
964 None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
972 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
973 /// triple. Note that it could also just be a bare filename already, so also
974 /// check for that. If one of the hardcoded targets we know about, just
975 /// return it directly.
977 /// The error string could come from any of the APIs called, including
978 /// filesystem access and JSON decoding.
979 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
981 use std::ffi::OsString;
985 fn load_file(path: &Path) -> Result<Target, String> {
986 let contents = fs::read(path).map_err(|e| e.to_string())?;
987 let obj = json::from_reader(&mut &contents[..])
988 .map_err(|e| e.to_string())?;
989 Target::from_json(obj)
992 match target_triple {
993 &TargetTriple::TargetTriple(ref target_triple) => {
994 // check if triple is in list of supported targets
995 if let Ok(t) = load_specific(target_triple) {
999 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1001 let mut target = target_triple.to_string();
1002 target.push_str(".json");
1003 PathBuf::from(target)
1006 let target_path = env::var_os("RUST_TARGET_PATH")
1007 .unwrap_or(OsString::new());
1009 // FIXME 16351: add a sane default search path?
1011 for dir in env::split_paths(&target_path) {
1012 let p = dir.join(&path);
1014 return load_file(&p);
1017 Err(format!("Could not find specification for target {:?}", target_triple))
1019 &TargetTriple::TargetPath(ref target_path) => {
1020 if target_path.is_file() {
1021 return load_file(&target_path);
1023 Err(format!("Target path {:?} is not a valid file", target_path))
1029 impl ToJson for Target {
1030 fn to_json(&self) -> Json {
1031 let mut d = BTreeMap::new();
1032 let default: TargetOptions = Default::default();
1034 macro_rules! target_val {
1035 ($attr:ident) => ( {
1036 let name = (stringify!($attr)).replace("_", "-");
1037 d.insert(name.to_string(), self.$attr.to_json());
1039 ($attr:ident, $key_name:expr) => ( {
1040 let name = $key_name;
1041 d.insert(name.to_string(), self.$attr.to_json());
1045 macro_rules! target_option_val {
1046 ($attr:ident) => ( {
1047 let name = (stringify!($attr)).replace("_", "-");
1048 if default.$attr != self.options.$attr {
1049 d.insert(name.to_string(), self.options.$attr.to_json());
1052 ($attr:ident, $key_name:expr) => ( {
1053 let name = $key_name;
1054 if default.$attr != self.options.$attr {
1055 d.insert(name.to_string(), self.options.$attr.to_json());
1058 (link_args - $attr:ident) => ( {
1059 let name = (stringify!($attr)).replace("_", "-");
1060 if default.$attr != self.options.$attr {
1061 let obj = self.options.$attr
1063 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1064 .collect::<BTreeMap<_, _>>();
1065 d.insert(name.to_string(), obj.to_json());
1068 (env - $attr:ident) => ( {
1069 let name = (stringify!($attr)).replace("_", "-");
1070 if default.$attr != self.options.$attr {
1071 let obj = self.options.$attr
1073 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1074 .collect::<Vec<_>>();
1075 d.insert(name.to_string(), obj.to_json());
1081 target_val!(llvm_target);
1082 target_val!(target_endian);
1083 target_val!(target_pointer_width);
1084 target_val!(target_c_int_width);
1086 target_val!(target_os, "os");
1087 target_val!(target_env, "env");
1088 target_val!(target_vendor, "vendor");
1089 target_val!(data_layout);
1090 target_val!(linker_flavor);
1092 target_option_val!(is_builtin);
1093 target_option_val!(linker);
1094 target_option_val!(link_args - pre_link_args);
1095 target_option_val!(pre_link_objects_exe);
1096 target_option_val!(pre_link_objects_dll);
1097 target_option_val!(link_args - late_link_args);
1098 target_option_val!(post_link_objects);
1099 target_option_val!(link_args - post_link_args);
1100 target_option_val!(env - link_env);
1101 target_option_val!(asm_args);
1102 target_option_val!(cpu);
1103 target_option_val!(features);
1104 target_option_val!(dynamic_linking);
1105 target_option_val!(only_cdylib);
1106 target_option_val!(executables);
1107 target_option_val!(relocation_model);
1108 target_option_val!(code_model);
1109 target_option_val!(tls_model);
1110 target_option_val!(disable_redzone);
1111 target_option_val!(eliminate_frame_pointer);
1112 target_option_val!(function_sections);
1113 target_option_val!(dll_prefix);
1114 target_option_val!(dll_suffix);
1115 target_option_val!(exe_suffix);
1116 target_option_val!(staticlib_prefix);
1117 target_option_val!(staticlib_suffix);
1118 target_option_val!(target_family);
1119 target_option_val!(abi_return_struct_as_int);
1120 target_option_val!(is_like_osx);
1121 target_option_val!(is_like_solaris);
1122 target_option_val!(is_like_windows);
1123 target_option_val!(is_like_msvc);
1124 target_option_val!(is_like_emscripten);
1125 target_option_val!(is_like_android);
1126 target_option_val!(linker_is_gnu);
1127 target_option_val!(allows_weak_linkage);
1128 target_option_val!(has_rpath);
1129 target_option_val!(no_default_libraries);
1130 target_option_val!(position_independent_executables);
1131 target_option_val!(relro_level);
1132 target_option_val!(archive_format);
1133 target_option_val!(allow_asm);
1134 target_option_val!(custom_unwind_resume);
1135 target_option_val!(exe_allocation_crate);
1136 target_option_val!(has_elf_tls);
1137 target_option_val!(obj_is_bitcode);
1138 target_option_val!(no_integrated_as);
1139 target_option_val!(min_atomic_width);
1140 target_option_val!(max_atomic_width);
1141 target_option_val!(panic_strategy);
1142 target_option_val!(crt_static_allows_dylibs);
1143 target_option_val!(crt_static_default);
1144 target_option_val!(crt_static_respected);
1145 target_option_val!(stack_probes);
1146 target_option_val!(min_global_align);
1147 target_option_val!(default_codegen_units);
1148 target_option_val!(trap_unreachable);
1149 target_option_val!(requires_lto);
1150 target_option_val!(singlethread);
1151 target_option_val!(no_builtins);
1152 target_option_val!(codegen_backend);
1153 target_option_val!(default_hidden_visibility);
1154 target_option_val!(embed_bitcode);
1155 target_option_val!(emit_debug_gdb_scripts);
1156 target_option_val!(requires_uwtable);
1158 if default.abi_blacklist != self.options.abi_blacklist {
1159 d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1160 .map(Abi::name).map(|name| name.to_json())
1161 .collect::<Vec<_>>().to_json());
1168 fn maybe_jemalloc() -> Option<String> {
1169 if cfg!(feature = "jemalloc") {
1170 Some("alloc_jemalloc".to_string())
1176 /// Either a target triple string or a path to a JSON file.
1177 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1178 pub enum TargetTriple {
1179 TargetTriple(String),
1180 TargetPath(PathBuf),
1184 /// Creates a target triple from the passed target triple string.
1185 pub fn from_triple(triple: &str) -> Self {
1186 TargetTriple::TargetTriple(triple.to_string())
1189 /// Creates a target triple from the passed target path.
1190 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1191 let canonicalized_path = path.canonicalize()?;
1192 Ok(TargetTriple::TargetPath(canonicalized_path))
1195 /// Returns a string triple for this target.
1197 /// If this target is a path, the file name (without extension) is returned.
1198 pub fn triple(&self) -> &str {
1200 &TargetTriple::TargetTriple(ref triple) => triple,
1201 &TargetTriple::TargetPath(ref path) => {
1202 path.file_stem().expect("target path must not be empty").to_str()
1203 .expect("target path must be valid unicode")
1208 /// Returns an extended string triple for this target.
1210 /// If this target is a path, a hash of the path is appended to the triple returned
1212 pub fn debug_triple(&self) -> String {
1213 use std::hash::{Hash, Hasher};
1214 use std::collections::hash_map::DefaultHasher;
1216 let triple = self.triple();
1217 if let &TargetTriple::TargetPath(ref path) = self {
1218 let mut hasher = DefaultHasher::new();
1219 path.hash(&mut hasher);
1220 let hash = hasher.finish();
1221 format!("{}-{}", triple, hash)
1228 impl fmt::Display for TargetTriple {
1229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1230 write!(f, "{}", self.debug_triple())