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};
72 mod windows_msvc_base;
78 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
79 RustcEncodable, RustcDecodable)]
80 pub enum LinkerFlavor {
88 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
89 RustcEncodable, RustcDecodable)]
98 fn from_str(s: &str) -> Option<Self> {
100 "darwin" => LldFlavor::Ld64,
101 "gnu" => LldFlavor::Ld,
102 "link" => LldFlavor::Link,
103 "wasm" => LldFlavor::Wasm,
109 impl ToJson for LldFlavor {
110 fn to_json(&self) -> Json {
112 LldFlavor::Ld64 => "darwin",
113 LldFlavor::Ld => "gnu",
114 LldFlavor::Link => "link",
115 LldFlavor::Wasm => "wasm",
120 impl ToJson for LinkerFlavor {
121 fn to_json(&self) -> Json {
122 self.desc().to_json()
125 macro_rules! flavor_mappings {
126 ($((($($flavor:tt)*), $string:expr),)*) => (
128 pub const fn one_of() -> &'static str {
129 concat!("one of: ", $($string, " ",)+)
132 pub fn from_str(s: &str) -> Option<Self> {
134 $($string => $($flavor)*,)+
139 pub fn desc(&self) -> &str {
141 $($($flavor)* => $string,)+
150 ((LinkerFlavor::Em), "em"),
151 ((LinkerFlavor::Gcc), "gcc"),
152 ((LinkerFlavor::Ld), "ld"),
153 ((LinkerFlavor::Msvc), "msvc"),
154 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
155 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
156 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
157 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
160 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
161 pub enum PanicStrategy {
167 pub fn desc(&self) -> &str {
169 PanicStrategy::Unwind => "unwind",
170 PanicStrategy::Abort => "abort",
175 impl ToJson for PanicStrategy {
176 fn to_json(&self) -> Json {
178 PanicStrategy::Abort => "abort".to_json(),
179 PanicStrategy::Unwind => "unwind".to_json(),
184 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
185 pub enum RelroLevel {
193 pub fn desc(&self) -> &str {
195 RelroLevel::Full => "full",
196 RelroLevel::Partial => "partial",
197 RelroLevel::Off => "off",
198 RelroLevel::None => "none",
203 impl FromStr for RelroLevel {
206 fn from_str(s: &str) -> Result<RelroLevel, ()> {
208 "full" => Ok(RelroLevel::Full),
209 "partial" => Ok(RelroLevel::Partial),
210 "off" => Ok(RelroLevel::Off),
211 "none" => Ok(RelroLevel::None),
217 impl ToJson for RelroLevel {
218 fn to_json(&self) -> Json {
220 RelroLevel::Full => "full".to_json(),
221 RelroLevel::Partial => "partial".to_json(),
222 RelroLevel::Off => "off".to_json(),
223 RelroLevel::None => "None".to_json(),
228 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
229 pub type TargetResult = Result<Target, String>;
231 macro_rules! supported_targets {
232 ( $(($triple:expr, $module:ident),)+ ) => (
235 /// List of supported targets
236 const TARGETS: &'static [&'static str] = &[$($triple),*];
238 fn load_specific(target: &str) -> TargetResult {
242 let mut t = $module::target()?;
243 t.options.is_builtin = true;
245 // round-trip through the JSON parser to ensure at
246 // run-time that the parser works correctly
247 t = Target::from_json(t.to_json())?;
248 debug!("Got builtin target: {:?}", t);
252 _ => Err(format!("Unable to find target: {}", target))
256 pub fn get_targets() -> Box<dyn Iterator<Item=String>> {
257 Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
259 .and(Ok(t.to_string()))
265 mod test_json_encode_decode {
266 use serialize::json::ToJson;
268 $(use super::$module;)*
273 // Grab the TargetResult struct. If we successfully retrieved
274 // a Target, then the test JSON encoding/decoding can run for this
275 // Target on this testing platform (i.e., checking the iOS targets
276 // only on a Mac test platform).
277 let _ = $module::target().map(|original| {
278 let as_json = original.to_json();
279 let parsed = Target::from_json(as_json).unwrap();
280 assert_eq!(original, parsed);
289 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
290 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
291 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
292 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
293 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
294 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
295 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
296 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
297 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
298 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
299 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
300 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
301 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
302 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
303 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
304 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
305 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
306 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
307 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
308 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
309 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
310 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
311 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
312 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
313 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
314 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
316 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
317 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
318 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
319 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
320 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
321 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
323 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
324 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
326 ("i686-linux-android", i686_linux_android),
327 ("x86_64-linux-android", x86_64_linux_android),
328 ("arm-linux-androideabi", arm_linux_androideabi),
329 ("armv7-linux-androideabi", armv7_linux_androideabi),
330 ("aarch64-linux-android", aarch64_linux_android),
332 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
333 ("i686-unknown-freebsd", i686_unknown_freebsd),
334 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
336 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
337 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
339 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
341 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
342 ("i686-unknown-openbsd", i686_unknown_openbsd),
343 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
345 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
346 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
347 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
348 ("i686-unknown-netbsd", i686_unknown_netbsd),
349 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
350 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
351 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
352 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
354 ("i686-unknown-haiku", i686_unknown_haiku),
355 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
357 ("x86_64-apple-darwin", x86_64_apple_darwin),
358 ("i686-apple-darwin", i686_apple_darwin),
360 ("aarch64-fuchsia", aarch64_fuchsia),
361 ("x86_64-fuchsia", x86_64_fuchsia),
363 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
365 ("x86_64-unknown-redox", x86_64_unknown_redox),
367 ("i386-apple-ios", i386_apple_ios),
368 ("x86_64-apple-ios", x86_64_apple_ios),
369 ("aarch64-apple-ios", aarch64_apple_ios),
370 ("armv7-apple-ios", armv7_apple_ios),
371 ("armv7s-apple-ios", armv7s_apple_ios),
373 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
374 ("armv7r-none-eabihf", armv7r_none_eabihf),
376 ("x86_64-sun-solaris", x86_64_sun_solaris),
377 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
379 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
380 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
382 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
383 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
384 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
385 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
387 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
388 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
389 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
390 ("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
392 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
393 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
394 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
395 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
397 ("msp430-none-elf", msp430_none_elf),
399 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
400 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
401 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
402 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
404 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
405 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
407 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
409 ("aarch64-unknown-none", aarch64_unknown_none),
412 /// Everything `rustc` knows about how to compile for a specific target.
414 /// Every field here must be specified, and has no default value.
415 #[derive(PartialEq, Clone, Debug)]
417 /// Target triple to pass to LLVM.
418 pub llvm_target: String,
419 /// String to use as the `target_endian` `cfg` variable.
420 pub target_endian: String,
421 /// String to use as the `target_pointer_width` `cfg` variable.
422 pub target_pointer_width: String,
423 /// Width of c_int type
424 pub target_c_int_width: String,
425 /// OS name to use for conditional compilation.
426 pub target_os: String,
427 /// Environment name to use for conditional compilation.
428 pub target_env: String,
429 /// Vendor name to use for conditional compilation.
430 pub target_vendor: String,
431 /// Architecture to use for ABI considerations. Valid options: "x86",
432 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
434 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
435 pub data_layout: String,
437 pub linker_flavor: LinkerFlavor,
438 /// Optional settings with defaults.
439 pub options: TargetOptions,
442 pub trait HasTargetSpec: Copy {
443 fn target_spec(&self) -> &Target;
446 impl<'a> HasTargetSpec for &'a Target {
447 fn target_spec(&self) -> &Target {
452 /// Optional aspects of a target specification.
454 /// This has an implementation of `Default`, see each field for what the default is. In general,
455 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
456 #[derive(PartialEq, Clone, Debug)]
457 pub struct TargetOptions {
458 /// Whether the target is built-in or loaded from a custom target specification.
459 pub is_builtin: bool,
462 pub linker: Option<String>,
465 pub lld_flavor: LldFlavor,
467 /// Linker arguments that are passed *before* any user-defined libraries.
468 pub pre_link_args: LinkArgs, // ... unconditionally
469 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
470 /// Objects to link before all others, always found within the
472 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
473 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
474 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
475 /// Linker arguments that are unconditionally passed after any
476 /// user-defined but before post_link_objects. Standard platform
477 /// libraries that should be always be linked to, usually go here.
478 pub late_link_args: LinkArgs,
479 /// Objects to link after all others, always found within the
481 pub post_link_objects: Vec<String>, // ... unconditionally
482 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
483 /// Linker arguments that are unconditionally passed *after* any
484 /// user-defined libraries.
485 pub post_link_args: LinkArgs,
487 /// Environment variables to be set before invoking the linker.
488 pub link_env: Vec<(String, String)>,
490 /// Extra arguments to pass to the external assembler (when used)
491 pub asm_args: Vec<String>,
493 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
496 /// Default target features to pass to LLVM. These features will *always* be
497 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
498 /// -mattr=$features`.
499 pub features: String,
500 /// Whether dynamic linking is available on this target. Defaults to false.
501 pub dynamic_linking: bool,
502 /// If dynamic linking is available, whether only cdylibs are supported.
503 pub only_cdylib: bool,
504 /// Whether executables are available on this target. iOS, for example, only allows static
505 /// libraries. Defaults to false.
506 pub executables: bool,
507 /// Relocation model to use in object file. Corresponds to `llc
508 /// -relocation-model=$relocation_model`. Defaults to "pic".
509 pub relocation_model: String,
510 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
511 pub code_model: Option<String>,
512 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
513 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
514 pub tls_model: String,
515 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
516 pub disable_redzone: bool,
517 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
518 pub eliminate_frame_pointer: bool,
519 /// Emit each function in its own section. Defaults to true.
520 pub function_sections: bool,
521 /// String to prepend to the name of every dynamic library. Defaults to "lib".
522 pub dll_prefix: String,
523 /// String to append to the name of every dynamic library. Defaults to ".so".
524 pub dll_suffix: String,
525 /// String to append to the name of every executable.
526 pub exe_suffix: String,
527 /// String to prepend to the name of every static library. Defaults to "lib".
528 pub staticlib_prefix: String,
529 /// String to append to the name of every static library. Defaults to ".a".
530 pub staticlib_suffix: String,
531 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
532 pub target_family: Option<String>,
533 /// Whether the target toolchain's ABI supports returning small structs as an integer.
534 pub abi_return_struct_as_int: bool,
535 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
536 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
537 pub is_like_osx: bool,
538 /// Whether the target toolchain is like Solaris's.
539 /// Only useful for compiling against Illumos/Solaris,
540 /// as they have a different set of linker flags. Defaults to false.
541 pub is_like_solaris: bool,
542 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
543 /// only really used for figuring out how to find libraries, since Windows uses its own
544 /// library naming convention. Defaults to false.
545 pub is_like_windows: bool,
546 pub is_like_msvc: bool,
547 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
548 /// Defaults to false.
549 pub is_like_android: bool,
550 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
551 /// Emscripten toolchain.
552 /// Defaults to false.
553 pub is_like_emscripten: bool,
554 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
555 pub linker_is_gnu: bool,
556 /// The MinGW toolchain has a known issue that prevents it from correctly
557 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
558 /// symbol needs its own COMDAT section, weak linkage implies a large
559 /// number sections that easily exceeds the given limit for larger
560 /// codebases. Consequently we want a way to disallow weak linkage on some
562 pub allows_weak_linkage: bool,
563 /// Whether the linker support rpaths or not. Defaults to false.
565 /// Whether to disable linking to the default libraries, typically corresponds
566 /// to `-nodefaultlibs`. Defaults to true.
567 pub no_default_libraries: bool,
568 /// Dynamically linked executables can be compiled as position independent
569 /// if the default relocation model of position independent code is not
570 /// changed. This is a requirement to take advantage of ASLR, as otherwise
571 /// the functions in the executable are not randomized and can be used
572 /// during an exploit of a vulnerability in any code.
573 pub position_independent_executables: bool,
574 /// Either partial, full, or off. Full RELRO makes the dynamic linker
575 /// resolve all symbols at startup and marks the GOT read-only before
576 /// starting the program, preventing overwriting the GOT.
577 pub relro_level: RelroLevel,
578 /// Format that archives should be emitted in. This affects whether we use
579 /// LLVM to assemble an archive or fall back to the system linker, and
580 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
581 /// the system linker to be used.
582 pub archive_format: String,
583 /// Is asm!() allowed? Defaults to true.
585 /// Whether the target uses a custom unwind resumption routine.
586 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
587 /// defined in libgcc. If this option is enabled, the target must provide
588 /// `eh_unwind_resume` lang item.
589 pub custom_unwind_resume: bool,
591 /// If necessary, a different crate to link exe allocators by default
592 pub exe_allocation_crate: Option<String>,
594 /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
596 pub has_elf_tls: bool,
597 // This is mainly for easy compatibility with emscripten.
598 // If we give emcc .o files that are actually .bc files it
600 pub obj_is_bitcode: bool,
602 // LLVM can't produce object files for this target. Instead, we'll make LLVM
603 // emit assembly and then use `gcc` to turn that assembly into an object
605 pub no_integrated_as: bool,
607 /// Don't use this field; instead use the `.min_atomic_width()` method.
608 pub min_atomic_width: Option<u64>,
610 /// Don't use this field; instead use the `.max_atomic_width()` method.
611 pub max_atomic_width: Option<u64>,
613 /// Whether the target supports atomic CAS operations natively
614 pub atomic_cas: bool,
616 /// Panic strategy: "unwind" or "abort"
617 pub panic_strategy: PanicStrategy,
619 /// A blacklist of ABIs unsupported by the current target. Note that generic
620 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
621 pub abi_blacklist: Vec<Abi>,
623 /// Whether or not linking dylibs to a static CRT is allowed.
624 pub crt_static_allows_dylibs: bool,
625 /// Whether or not the CRT is statically linked by default.
626 pub crt_static_default: bool,
627 /// Whether or not crt-static is respected by the compiler (or is a no-op).
628 pub crt_static_respected: bool,
630 /// Whether or not stack probes (__rust_probestack) are enabled
631 pub stack_probes: bool,
633 /// The minimum alignment for global symbols.
634 pub min_global_align: Option<u64>,
636 /// Default number of codegen units to use in debug mode
637 pub default_codegen_units: Option<u64>,
639 /// Whether to generate trap instructions in places where optimization would
640 /// otherwise produce control flow that falls through into unrelated memory.
641 pub trap_unreachable: bool,
643 /// This target requires everything to be compiled with LTO to emit a final
644 /// executable, aka there is no native linker for this target.
645 pub requires_lto: bool,
647 /// This target has no support for threads.
648 pub singlethread: bool,
650 /// Whether library functions call lowering/optimization is disabled in LLVM
651 /// for this target unconditionally.
652 pub no_builtins: bool,
654 /// Whether to lower 128-bit operations to compiler_builtins calls. Use if
655 /// your backend only supports 64-bit and smaller math.
656 pub i128_lowering: bool,
658 /// The codegen backend to use for this target, typically "llvm"
659 pub codegen_backend: String,
661 /// The default visibility for symbols in this target should be "hidden"
662 /// rather than "default"
663 pub default_hidden_visibility: bool,
665 /// Whether or not bitcode is embedded in object files
666 pub embed_bitcode: bool,
668 /// Whether a .debug_gdb_scripts section will be added to the output object file
669 pub emit_debug_gdb_scripts: bool,
671 /// Whether or not to unconditionally `uwtable` attributes on functions,
672 /// typically because the platform needs to unwind for things like stack
674 pub requires_uwtable: bool,
677 impl Default for TargetOptions {
678 /// Create a set of "sane defaults" for any target. This is still
679 /// incomplete, and if used for compilation, will certainly not work.
680 fn default() -> TargetOptions {
683 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
684 lld_flavor: LldFlavor::Ld,
685 pre_link_args: LinkArgs::new(),
686 pre_link_args_crt: LinkArgs::new(),
687 post_link_args: LinkArgs::new(),
688 asm_args: Vec::new(),
689 cpu: "generic".to_string(),
690 features: String::new(),
691 dynamic_linking: false,
694 relocation_model: "pic".to_string(),
696 tls_model: "global-dynamic".to_string(),
697 disable_redzone: false,
698 eliminate_frame_pointer: true,
699 function_sections: true,
700 dll_prefix: "lib".to_string(),
701 dll_suffix: ".so".to_string(),
702 exe_suffix: String::new(),
703 staticlib_prefix: "lib".to_string(),
704 staticlib_suffix: ".a".to_string(),
706 abi_return_struct_as_int: false,
708 is_like_solaris: false,
709 is_like_windows: false,
710 is_like_android: false,
711 is_like_emscripten: false,
713 linker_is_gnu: false,
714 allows_weak_linkage: true,
716 no_default_libraries: true,
717 position_independent_executables: false,
718 relro_level: RelroLevel::None,
719 pre_link_objects_exe: Vec::new(),
720 pre_link_objects_exe_crt: Vec::new(),
721 pre_link_objects_dll: Vec::new(),
722 post_link_objects: Vec::new(),
723 post_link_objects_crt: Vec::new(),
724 late_link_args: LinkArgs::new(),
725 link_env: Vec::new(),
726 archive_format: "gnu".to_string(),
727 custom_unwind_resume: false,
728 exe_allocation_crate: None,
731 obj_is_bitcode: false,
732 no_integrated_as: false,
733 min_atomic_width: None,
734 max_atomic_width: None,
736 panic_strategy: PanicStrategy::Unwind,
737 abi_blacklist: vec![],
738 crt_static_allows_dylibs: false,
739 crt_static_default: false,
740 crt_static_respected: false,
742 min_global_align: None,
743 default_codegen_units: None,
744 trap_unreachable: true,
748 i128_lowering: false,
749 codegen_backend: "llvm".to_string(),
750 default_hidden_visibility: false,
751 embed_bitcode: false,
752 emit_debug_gdb_scripts: true,
753 requires_uwtable: false,
759 /// Given a function ABI, turn "System" into the correct ABI for this target.
760 pub fn adjust_abi(&self, abi: Abi) -> Abi {
763 if self.options.is_like_windows && self.arch == "x86" {
773 /// Minimum integer size in bits that this target can perform atomic
775 pub fn min_atomic_width(&self) -> u64 {
776 self.options.min_atomic_width.unwrap_or(8)
779 /// Maximum integer size in bits that this target can perform atomic
781 pub fn max_atomic_width(&self) -> u64 {
782 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
785 pub fn is_abi_supported(&self, abi: Abi) -> bool {
786 abi.generic() || !self.options.abi_blacklist.contains(&abi)
789 /// Load a target descriptor from a JSON object.
790 pub fn from_json(obj: Json) -> TargetResult {
791 // While ugly, this code must remain this way to retain
792 // compatibility with existing JSON fields and the internal
793 // expected naming of the Target and TargetOptions structs.
794 // To ensure compatibility is retained, the built-in targets
795 // are round-tripped through this code to catch cases where
796 // the JSON parser is not updated to match the structs.
798 let get_req_field = |name: &str| {
800 .map(|s| s.as_string())
801 .and_then(|os| os.map(|s| s.to_string()))
802 .ok_or_else(|| format!("Field {} in target specification is required", name))
805 let get_opt_field = |name: &str, default: &str| {
806 obj.find(name).and_then(|s| s.as_string())
807 .map(|s| s.to_string())
808 .unwrap_or_else(|| default.to_string())
811 let mut base = Target {
812 llvm_target: get_req_field("llvm-target")?,
813 target_endian: get_req_field("target-endian")?,
814 target_pointer_width: get_req_field("target-pointer-width")?,
815 target_c_int_width: get_req_field("target-c-int-width")?,
816 data_layout: get_req_field("data-layout")?,
817 arch: get_req_field("arch")?,
818 target_os: get_req_field("os")?,
819 target_env: get_opt_field("env", ""),
820 target_vendor: get_opt_field("vendor", "unknown"),
821 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
823 format!("linker flavor must be {}", LinkerFlavor::one_of())
825 options: Default::default(),
829 ($key_name:ident) => ( {
830 let name = (stringify!($key_name)).replace("_", "-");
831 obj.find(&name[..]).map(|o| o.as_string()
832 .map(|s| base.options.$key_name = s.to_string()));
834 ($key_name:ident, bool) => ( {
835 let name = (stringify!($key_name)).replace("_", "-");
837 .map(|o| o.as_boolean()
838 .map(|s| base.options.$key_name = s));
840 ($key_name:ident, Option<u64>) => ( {
841 let name = (stringify!($key_name)).replace("_", "-");
844 .map(|s| base.options.$key_name = Some(s)));
846 ($key_name:ident, PanicStrategy) => ( {
847 let name = (stringify!($key_name)).replace("_", "-");
848 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
850 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
851 "abort" => base.options.$key_name = PanicStrategy::Abort,
852 _ => return Some(Err(format!("'{}' is not a valid value for \
853 panic-strategy. Use 'unwind' or 'abort'.",
857 })).unwrap_or(Ok(()))
859 ($key_name:ident, RelroLevel) => ( {
860 let name = (stringify!($key_name)).replace("_", "-");
861 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
862 match s.parse::<RelroLevel>() {
863 Ok(level) => base.options.$key_name = level,
864 _ => return Some(Err(format!("'{}' is not a valid value for \
865 relro-level. Use 'full', 'partial, or 'off'.",
869 })).unwrap_or(Ok(()))
871 ($key_name:ident, list) => ( {
872 let name = (stringify!($key_name)).replace("_", "-");
873 obj.find(&name[..]).map(|o| o.as_array()
874 .map(|v| base.options.$key_name = v.iter()
875 .map(|a| a.as_string().unwrap().to_string()).collect()
879 ($key_name:ident, optional) => ( {
880 let name = (stringify!($key_name)).replace("_", "-");
881 if let Some(o) = obj.find(&name[..]) {
882 base.options.$key_name = o
884 .map(|s| s.to_string() );
887 ($key_name:ident, LldFlavor) => ( {
888 let name = (stringify!($key_name)).replace("_", "-");
889 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
890 if let Some(flavor) = LldFlavor::from_str(&s) {
891 base.options.$key_name = flavor;
893 return Some(Err(format!(
894 "'{}' is not a valid value for lld-flavor. \
895 Use 'darwin', 'gnu', 'link' or 'wasm.",
899 })).unwrap_or(Ok(()))
901 ($key_name:ident, LinkerFlavor) => ( {
902 let name = (stringify!($key_name)).replace("_", "-");
903 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
904 LinkerFlavor::from_str(&s).ok_or_else(|| {
905 Err(format!("'{}' is not a valid value for linker-flavor. \
906 Use 'em', 'gcc', 'ld' or 'msvc.", s))
908 })).unwrap_or(Ok(()))
910 ($key_name:ident, link_args) => ( {
911 let name = (stringify!($key_name)).replace("_", "-");
912 if let Some(val) = obj.find(&name[..]) {
913 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
914 JSON object with fields per linker-flavor.", name))?;
915 let mut args = LinkArgs::new();
917 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
918 format!("{}: '{}' is not a valid value for linker-flavor. \
919 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
922 let v = v.as_array().ok_or_else(||
923 format!("{}.{}: expected a JSON array", name, k)
924 )?.iter().enumerate()
926 let s = s.as_string().ok_or_else(||
927 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
930 .collect::<Result<Vec<_>, String>>()?;
932 args.insert(flavor, v);
934 base.options.$key_name = args;
937 ($key_name:ident, env) => ( {
938 let name = (stringify!($key_name)).replace("_", "-");
939 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
941 if let Some(s) = o.as_string() {
942 let p = s.split('=').collect::<Vec<_>>();
944 let k = p[0].to_string();
945 let v = p[1].to_string();
946 base.options.$key_name.push((k, v));
954 key!(is_builtin, bool);
955 key!(linker, optional);
956 try!(key!(lld_flavor, LldFlavor));
957 key!(pre_link_args, link_args);
958 key!(pre_link_args_crt, link_args);
959 key!(pre_link_objects_exe, list);
960 key!(pre_link_objects_exe_crt, list);
961 key!(pre_link_objects_dll, list);
962 key!(late_link_args, link_args);
963 key!(post_link_objects, list);
964 key!(post_link_objects_crt, list);
965 key!(post_link_args, link_args);
967 key!(asm_args, list);
970 key!(dynamic_linking, bool);
971 key!(only_cdylib, bool);
972 key!(executables, bool);
973 key!(relocation_model);
974 key!(code_model, optional);
976 key!(disable_redzone, bool);
977 key!(eliminate_frame_pointer, bool);
978 key!(function_sections, bool);
982 key!(staticlib_prefix);
983 key!(staticlib_suffix);
984 key!(target_family, optional);
985 key!(abi_return_struct_as_int, bool);
986 key!(is_like_osx, bool);
987 key!(is_like_solaris, bool);
988 key!(is_like_windows, bool);
989 key!(is_like_msvc, bool);
990 key!(is_like_emscripten, bool);
991 key!(is_like_android, bool);
992 key!(linker_is_gnu, bool);
993 key!(allows_weak_linkage, bool);
994 key!(has_rpath, bool);
995 key!(no_default_libraries, bool);
996 key!(position_independent_executables, bool);
997 try!(key!(relro_level, RelroLevel));
998 key!(archive_format);
999 key!(allow_asm, bool);
1000 key!(custom_unwind_resume, bool);
1001 key!(exe_allocation_crate, optional);
1002 key!(has_elf_tls, bool);
1003 key!(obj_is_bitcode, bool);
1004 key!(no_integrated_as, bool);
1005 key!(max_atomic_width, Option<u64>);
1006 key!(min_atomic_width, Option<u64>);
1007 key!(atomic_cas, bool);
1008 try!(key!(panic_strategy, PanicStrategy));
1009 key!(crt_static_allows_dylibs, bool);
1010 key!(crt_static_default, bool);
1011 key!(crt_static_respected, bool);
1012 key!(stack_probes, bool);
1013 key!(min_global_align, Option<u64>);
1014 key!(default_codegen_units, Option<u64>);
1015 key!(trap_unreachable, bool);
1016 key!(requires_lto, bool);
1017 key!(singlethread, bool);
1018 key!(no_builtins, bool);
1019 key!(codegen_backend);
1020 key!(default_hidden_visibility, bool);
1021 key!(embed_bitcode, bool);
1022 key!(emit_debug_gdb_scripts, bool);
1023 key!(requires_uwtable, bool);
1025 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1026 for name in array.iter().filter_map(|abi| abi.as_string()) {
1027 match lookup_abi(name) {
1030 return Err(format!("The ABI \"{}\" is considered to be supported on \
1031 all targets and cannot be blacklisted", abi))
1034 base.options.abi_blacklist.push(abi)
1036 None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
1044 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1045 /// triple. Note that it could also just be a bare filename already, so also
1046 /// check for that. If one of the hardcoded targets we know about, just
1047 /// return it directly.
1049 /// The error string could come from any of the APIs called, including
1050 /// filesystem access and JSON decoding.
1051 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1054 use serialize::json;
1056 fn load_file(path: &Path) -> Result<Target, String> {
1057 let contents = fs::read(path).map_err(|e| e.to_string())?;
1058 let obj = json::from_reader(&mut &contents[..])
1059 .map_err(|e| e.to_string())?;
1060 Target::from_json(obj)
1063 match *target_triple {
1064 TargetTriple::TargetTriple(ref target_triple) => {
1065 // check if triple is in list of supported targets
1066 if let Ok(t) = load_specific(target_triple) {
1070 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1072 let mut target = target_triple.to_string();
1073 target.push_str(".json");
1074 PathBuf::from(target)
1077 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1079 // FIXME 16351: add a sane default search path?
1081 for dir in env::split_paths(&target_path) {
1082 let p = dir.join(&path);
1084 return load_file(&p);
1087 Err(format!("Could not find specification for target {:?}", target_triple))
1089 TargetTriple::TargetPath(ref target_path) => {
1090 if target_path.is_file() {
1091 return load_file(&target_path);
1093 Err(format!("Target path {:?} is not a valid file", target_path))
1099 impl ToJson for Target {
1100 fn to_json(&self) -> Json {
1101 let mut d = BTreeMap::new();
1102 let default: TargetOptions = Default::default();
1104 macro_rules! target_val {
1105 ($attr:ident) => ( {
1106 let name = (stringify!($attr)).replace("_", "-");
1107 d.insert(name.to_string(), self.$attr.to_json());
1109 ($attr:ident, $key_name:expr) => ( {
1110 let name = $key_name;
1111 d.insert(name.to_string(), self.$attr.to_json());
1115 macro_rules! target_option_val {
1116 ($attr:ident) => ( {
1117 let name = (stringify!($attr)).replace("_", "-");
1118 if default.$attr != self.options.$attr {
1119 d.insert(name.to_string(), self.options.$attr.to_json());
1122 ($attr:ident, $key_name:expr) => ( {
1123 let name = $key_name;
1124 if default.$attr != self.options.$attr {
1125 d.insert(name.to_string(), self.options.$attr.to_json());
1128 (link_args - $attr:ident) => ( {
1129 let name = (stringify!($attr)).replace("_", "-");
1130 if default.$attr != self.options.$attr {
1131 let obj = self.options.$attr
1133 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1134 .collect::<BTreeMap<_, _>>();
1135 d.insert(name.to_string(), obj.to_json());
1138 (env - $attr:ident) => ( {
1139 let name = (stringify!($attr)).replace("_", "-");
1140 if default.$attr != self.options.$attr {
1141 let obj = self.options.$attr
1143 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1144 .collect::<Vec<_>>();
1145 d.insert(name.to_string(), obj.to_json());
1151 target_val!(llvm_target);
1152 target_val!(target_endian);
1153 target_val!(target_pointer_width);
1154 target_val!(target_c_int_width);
1156 target_val!(target_os, "os");
1157 target_val!(target_env, "env");
1158 target_val!(target_vendor, "vendor");
1159 target_val!(data_layout);
1160 target_val!(linker_flavor);
1162 target_option_val!(is_builtin);
1163 target_option_val!(linker);
1164 target_option_val!(lld_flavor);
1165 target_option_val!(link_args - pre_link_args);
1166 target_option_val!(link_args - pre_link_args_crt);
1167 target_option_val!(pre_link_objects_exe);
1168 target_option_val!(pre_link_objects_exe_crt);
1169 target_option_val!(pre_link_objects_dll);
1170 target_option_val!(link_args - late_link_args);
1171 target_option_val!(post_link_objects);
1172 target_option_val!(post_link_objects_crt);
1173 target_option_val!(link_args - post_link_args);
1174 target_option_val!(env - link_env);
1175 target_option_val!(asm_args);
1176 target_option_val!(cpu);
1177 target_option_val!(features);
1178 target_option_val!(dynamic_linking);
1179 target_option_val!(only_cdylib);
1180 target_option_val!(executables);
1181 target_option_val!(relocation_model);
1182 target_option_val!(code_model);
1183 target_option_val!(tls_model);
1184 target_option_val!(disable_redzone);
1185 target_option_val!(eliminate_frame_pointer);
1186 target_option_val!(function_sections);
1187 target_option_val!(dll_prefix);
1188 target_option_val!(dll_suffix);
1189 target_option_val!(exe_suffix);
1190 target_option_val!(staticlib_prefix);
1191 target_option_val!(staticlib_suffix);
1192 target_option_val!(target_family);
1193 target_option_val!(abi_return_struct_as_int);
1194 target_option_val!(is_like_osx);
1195 target_option_val!(is_like_solaris);
1196 target_option_val!(is_like_windows);
1197 target_option_val!(is_like_msvc);
1198 target_option_val!(is_like_emscripten);
1199 target_option_val!(is_like_android);
1200 target_option_val!(linker_is_gnu);
1201 target_option_val!(allows_weak_linkage);
1202 target_option_val!(has_rpath);
1203 target_option_val!(no_default_libraries);
1204 target_option_val!(position_independent_executables);
1205 target_option_val!(relro_level);
1206 target_option_val!(archive_format);
1207 target_option_val!(allow_asm);
1208 target_option_val!(custom_unwind_resume);
1209 target_option_val!(exe_allocation_crate);
1210 target_option_val!(has_elf_tls);
1211 target_option_val!(obj_is_bitcode);
1212 target_option_val!(no_integrated_as);
1213 target_option_val!(min_atomic_width);
1214 target_option_val!(max_atomic_width);
1215 target_option_val!(atomic_cas);
1216 target_option_val!(panic_strategy);
1217 target_option_val!(crt_static_allows_dylibs);
1218 target_option_val!(crt_static_default);
1219 target_option_val!(crt_static_respected);
1220 target_option_val!(stack_probes);
1221 target_option_val!(min_global_align);
1222 target_option_val!(default_codegen_units);
1223 target_option_val!(trap_unreachable);
1224 target_option_val!(requires_lto);
1225 target_option_val!(singlethread);
1226 target_option_val!(no_builtins);
1227 target_option_val!(codegen_backend);
1228 target_option_val!(default_hidden_visibility);
1229 target_option_val!(embed_bitcode);
1230 target_option_val!(emit_debug_gdb_scripts);
1231 target_option_val!(requires_uwtable);
1233 if default.abi_blacklist != self.options.abi_blacklist {
1234 d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1235 .map(|&name| Abi::name(name).to_json())
1236 .collect::<Vec<_>>().to_json());
1243 fn maybe_jemalloc() -> Option<String> {
1244 if cfg!(feature = "jemalloc") {
1245 Some("alloc_jemalloc".to_string())
1251 /// Either a target triple string or a path to a JSON file.
1252 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1253 pub enum TargetTriple {
1254 TargetTriple(String),
1255 TargetPath(PathBuf),
1259 /// Creates a target triple from the passed target triple string.
1260 pub fn from_triple(triple: &str) -> Self {
1261 TargetTriple::TargetTriple(triple.to_string())
1264 /// Creates a target triple from the passed target path.
1265 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1266 let canonicalized_path = path.canonicalize()?;
1267 Ok(TargetTriple::TargetPath(canonicalized_path))
1270 /// Returns a string triple for this target.
1272 /// If this target is a path, the file name (without extension) is returned.
1273 pub fn triple(&self) -> &str {
1275 TargetTriple::TargetTriple(ref triple) => triple,
1276 TargetTriple::TargetPath(ref path) => {
1277 path.file_stem().expect("target path must not be empty").to_str()
1278 .expect("target path must be valid unicode")
1283 /// Returns an extended string triple for this target.
1285 /// If this target is a path, a hash of the path is appended to the triple returned
1287 pub fn debug_triple(&self) -> String {
1288 use std::hash::{Hash, Hasher};
1289 use std::collections::hash_map::DefaultHasher;
1291 let triple = self.triple();
1292 if let TargetTriple::TargetPath(ref path) = *self {
1293 let mut hasher = DefaultHasher::new();
1294 path.hash(&mut hasher);
1295 let hash = hasher.finish();
1296 format!("{}-{}", triple, hash)
1303 impl fmt::Display for TargetTriple {
1304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1305 write!(f, "{}", self.debug_triple())