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;
79 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
80 RustcEncodable, RustcDecodable)]
81 pub enum LinkerFlavor {
89 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
90 RustcEncodable, RustcDecodable)]
99 fn from_str(s: &str) -> Option<Self> {
101 "darwin" => LldFlavor::Ld64,
102 "gnu" => LldFlavor::Ld,
103 "link" => LldFlavor::Link,
104 "wasm" => LldFlavor::Wasm,
110 impl ToJson for LldFlavor {
111 fn to_json(&self) -> Json {
113 LldFlavor::Ld64 => "darwin",
114 LldFlavor::Ld => "gnu",
115 LldFlavor::Link => "link",
116 LldFlavor::Wasm => "wasm",
121 impl ToJson for LinkerFlavor {
122 fn to_json(&self) -> Json {
123 self.desc().to_json()
126 macro_rules! flavor_mappings {
127 ($((($($flavor:tt)*), $string:expr),)*) => (
129 pub const fn one_of() -> &'static str {
130 concat!("one of: ", $($string, " ",)+)
133 pub fn from_str(s: &str) -> Option<Self> {
135 $($string => $($flavor)*,)+
140 pub fn desc(&self) -> &str {
142 $($($flavor)* => $string,)+
151 ((LinkerFlavor::Em), "em"),
152 ((LinkerFlavor::Gcc), "gcc"),
153 ((LinkerFlavor::Ld), "ld"),
154 ((LinkerFlavor::Msvc), "msvc"),
155 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
156 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
157 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
158 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
161 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
162 pub enum PanicStrategy {
168 pub fn desc(&self) -> &str {
170 PanicStrategy::Unwind => "unwind",
171 PanicStrategy::Abort => "abort",
176 impl ToJson for PanicStrategy {
177 fn to_json(&self) -> Json {
179 PanicStrategy::Abort => "abort".to_json(),
180 PanicStrategy::Unwind => "unwind".to_json(),
185 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
186 pub enum RelroLevel {
194 pub fn desc(&self) -> &str {
196 RelroLevel::Full => "full",
197 RelroLevel::Partial => "partial",
198 RelroLevel::Off => "off",
199 RelroLevel::None => "none",
204 impl FromStr for RelroLevel {
207 fn from_str(s: &str) -> Result<RelroLevel, ()> {
209 "full" => Ok(RelroLevel::Full),
210 "partial" => Ok(RelroLevel::Partial),
211 "off" => Ok(RelroLevel::Off),
212 "none" => Ok(RelroLevel::None),
218 impl ToJson for RelroLevel {
219 fn to_json(&self) -> Json {
221 RelroLevel::Full => "full".to_json(),
222 RelroLevel::Partial => "partial".to_json(),
223 RelroLevel::Off => "off".to_json(),
224 RelroLevel::None => "None".to_json(),
229 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
230 pub type TargetResult = Result<Target, String>;
232 macro_rules! supported_targets {
233 ( $(($triple:expr, $module:ident),)+ ) => (
236 /// List of supported targets
237 const TARGETS: &'static [&'static str] = &[$($triple),*];
239 fn load_specific(target: &str) -> TargetResult {
243 let mut t = $module::target()?;
244 t.options.is_builtin = true;
246 // round-trip through the JSON parser to ensure at
247 // run-time that the parser works correctly
248 t = Target::from_json(t.to_json())?;
249 debug!("Got builtin target: {:?}", t);
253 _ => Err(format!("Unable to find target: {}", target))
257 pub fn get_targets() -> Box<dyn Iterator<Item=String>> {
258 Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
260 .and(Ok(t.to_string()))
266 mod test_json_encode_decode {
267 use serialize::json::ToJson;
269 $(use super::$module;)*
274 // Grab the TargetResult struct. If we successfully retrieved
275 // a Target, then the test JSON encoding/decoding can run for this
276 // Target on this testing platform (i.e., checking the iOS targets
277 // only on a Mac test platform).
278 let _ = $module::target().map(|original| {
279 let as_json = original.to_json();
280 let parsed = Target::from_json(as_json).unwrap();
281 assert_eq!(original, parsed);
290 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
291 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
292 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
293 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
294 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
295 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
296 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
297 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
298 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
299 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
300 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
301 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
302 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
303 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
304 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
305 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
306 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
307 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
308 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
309 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
310 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
311 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
312 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
313 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
314 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
315 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
317 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
318 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
319 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
320 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
321 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
322 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
324 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
325 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
327 ("i686-linux-android", i686_linux_android),
328 ("x86_64-linux-android", x86_64_linux_android),
329 ("arm-linux-androideabi", arm_linux_androideabi),
330 ("armv7-linux-androideabi", armv7_linux_androideabi),
331 ("aarch64-linux-android", aarch64_linux_android),
333 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
334 ("i686-unknown-freebsd", i686_unknown_freebsd),
335 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
337 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
338 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
340 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
342 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
343 ("i686-unknown-openbsd", i686_unknown_openbsd),
344 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
346 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
347 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
348 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
349 ("i686-unknown-netbsd", i686_unknown_netbsd),
350 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
351 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
352 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
353 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
355 ("i686-unknown-haiku", i686_unknown_haiku),
356 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
358 ("x86_64-apple-darwin", x86_64_apple_darwin),
359 ("i686-apple-darwin", i686_apple_darwin),
361 ("aarch64-fuchsia", aarch64_fuchsia),
362 ("x86_64-fuchsia", x86_64_fuchsia),
364 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
366 ("x86_64-unknown-redox", x86_64_unknown_redox),
368 ("i386-apple-ios", i386_apple_ios),
369 ("x86_64-apple-ios", x86_64_apple_ios),
370 ("aarch64-apple-ios", aarch64_apple_ios),
371 ("armv7-apple-ios", armv7_apple_ios),
372 ("armv7s-apple-ios", armv7s_apple_ios),
374 ("armebv7r-none-eabi", armebv7r_none_eabi),
375 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
376 ("armv7r-none-eabi", armv7r_none_eabi),
377 ("armv7r-none-eabihf", armv7r_none_eabihf),
379 ("x86_64-sun-solaris", x86_64_sun_solaris),
380 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
382 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
383 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
385 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
386 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
387 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
388 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
389 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
391 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
392 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
393 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
394 ("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
396 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
397 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
398 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
399 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
401 ("msp430-none-elf", msp430_none_elf),
403 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
404 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
405 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
406 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
408 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
409 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
411 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
412 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
414 ("aarch64-unknown-none", aarch64_unknown_none),
416 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
419 /// Everything `rustc` knows about how to compile for a specific target.
421 /// Every field here must be specified, and has no default value.
422 #[derive(PartialEq, Clone, Debug)]
424 /// Target triple to pass to LLVM.
425 pub llvm_target: String,
426 /// String to use as the `target_endian` `cfg` variable.
427 pub target_endian: String,
428 /// String to use as the `target_pointer_width` `cfg` variable.
429 pub target_pointer_width: String,
430 /// Width of c_int type
431 pub target_c_int_width: String,
432 /// OS name to use for conditional compilation.
433 pub target_os: String,
434 /// Environment name to use for conditional compilation.
435 pub target_env: String,
436 /// Vendor name to use for conditional compilation.
437 pub target_vendor: String,
438 /// Architecture to use for ABI considerations. Valid options: "x86",
439 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
441 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
442 pub data_layout: String,
444 pub linker_flavor: LinkerFlavor,
445 /// Optional settings with defaults.
446 pub options: TargetOptions,
449 pub trait HasTargetSpec {
450 fn target_spec(&self) -> &Target;
453 impl HasTargetSpec for Target {
454 fn target_spec(&self) -> &Target {
459 /// Optional aspects of a target specification.
461 /// This has an implementation of `Default`, see each field for what the default is. In general,
462 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
463 #[derive(PartialEq, Clone, Debug)]
464 pub struct TargetOptions {
465 /// Whether the target is built-in or loaded from a custom target specification.
466 pub is_builtin: bool,
469 pub linker: Option<String>,
472 pub lld_flavor: LldFlavor,
474 /// Linker arguments that are passed *before* any user-defined libraries.
475 pub pre_link_args: LinkArgs, // ... unconditionally
476 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
477 /// Objects to link before all others, always found within the
479 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
480 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
481 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
482 /// Linker arguments that are unconditionally passed after any
483 /// user-defined but before post_link_objects. Standard platform
484 /// libraries that should be always be linked to, usually go here.
485 pub late_link_args: LinkArgs,
486 /// Objects to link after all others, always found within the
488 pub post_link_objects: Vec<String>, // ... unconditionally
489 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
490 /// Linker arguments that are unconditionally passed *after* any
491 /// user-defined libraries.
492 pub post_link_args: LinkArgs,
494 /// Environment variables to be set before invoking the linker.
495 pub link_env: Vec<(String, String)>,
497 /// Extra arguments to pass to the external assembler (when used)
498 pub asm_args: Vec<String>,
500 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
503 /// Default target features to pass to LLVM. These features will *always* be
504 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
505 /// -mattr=$features`.
506 pub features: String,
507 /// Whether dynamic linking is available on this target. Defaults to false.
508 pub dynamic_linking: bool,
509 /// If dynamic linking is available, whether only cdylibs are supported.
510 pub only_cdylib: bool,
511 /// Whether executables are available on this target. iOS, for example, only allows static
512 /// libraries. Defaults to false.
513 pub executables: bool,
514 /// Relocation model to use in object file. Corresponds to `llc
515 /// -relocation-model=$relocation_model`. Defaults to "pic".
516 pub relocation_model: String,
517 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
518 pub code_model: Option<String>,
519 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
520 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
521 pub tls_model: String,
522 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
523 pub disable_redzone: bool,
524 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
525 pub eliminate_frame_pointer: bool,
526 /// Emit each function in its own section. Defaults to true.
527 pub function_sections: bool,
528 /// String to prepend to the name of every dynamic library. Defaults to "lib".
529 pub dll_prefix: String,
530 /// String to append to the name of every dynamic library. Defaults to ".so".
531 pub dll_suffix: String,
532 /// String to append to the name of every executable.
533 pub exe_suffix: String,
534 /// String to prepend to the name of every static library. Defaults to "lib".
535 pub staticlib_prefix: String,
536 /// String to append to the name of every static library. Defaults to ".a".
537 pub staticlib_suffix: String,
538 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
539 pub target_family: Option<String>,
540 /// Whether the target toolchain's ABI supports returning small structs as an integer.
541 pub abi_return_struct_as_int: bool,
542 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
543 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
544 pub is_like_osx: bool,
545 /// Whether the target toolchain is like Solaris's.
546 /// Only useful for compiling against Illumos/Solaris,
547 /// as they have a different set of linker flags. Defaults to false.
548 pub is_like_solaris: bool,
549 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
550 /// only really used for figuring out how to find libraries, since Windows uses its own
551 /// library naming convention. Defaults to false.
552 pub is_like_windows: bool,
553 pub is_like_msvc: bool,
554 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
555 /// Defaults to false.
556 pub is_like_android: bool,
557 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
558 /// Emscripten toolchain.
559 /// Defaults to false.
560 pub is_like_emscripten: bool,
561 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
562 pub linker_is_gnu: bool,
563 /// The MinGW toolchain has a known issue that prevents it from correctly
564 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
565 /// symbol needs its own COMDAT section, weak linkage implies a large
566 /// number sections that easily exceeds the given limit for larger
567 /// codebases. Consequently we want a way to disallow weak linkage on some
569 pub allows_weak_linkage: bool,
570 /// Whether the linker support rpaths or not. Defaults to false.
572 /// Whether to disable linking to the default libraries, typically corresponds
573 /// to `-nodefaultlibs`. Defaults to true.
574 pub no_default_libraries: bool,
575 /// Dynamically linked executables can be compiled as position independent
576 /// if the default relocation model of position independent code is not
577 /// changed. This is a requirement to take advantage of ASLR, as otherwise
578 /// the functions in the executable are not randomized and can be used
579 /// during an exploit of a vulnerability in any code.
580 pub position_independent_executables: bool,
581 /// Determines if the target always requires using the PLT for indirect
582 /// library calls or not. This controls the default value of the `-Z plt` flag.
584 /// Either partial, full, or off. Full RELRO makes the dynamic linker
585 /// resolve all symbols at startup and marks the GOT read-only before
586 /// starting the program, preventing overwriting the GOT.
587 pub relro_level: RelroLevel,
588 /// Format that archives should be emitted in. This affects whether we use
589 /// LLVM to assemble an archive or fall back to the system linker, and
590 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
591 /// the system linker to be used.
592 pub archive_format: String,
593 /// Is asm!() allowed? Defaults to true.
595 /// Whether the target uses a custom unwind resumption routine.
596 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
597 /// defined in libgcc. If this option is enabled, the target must provide
598 /// `eh_unwind_resume` lang item.
599 pub custom_unwind_resume: bool,
601 /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
603 pub has_elf_tls: bool,
604 // This is mainly for easy compatibility with emscripten.
605 // If we give emcc .o files that are actually .bc files it
607 pub obj_is_bitcode: bool,
609 // LLVM can't produce object files for this target. Instead, we'll make LLVM
610 // emit assembly and then use `gcc` to turn that assembly into an object
612 pub no_integrated_as: bool,
614 /// Don't use this field; instead use the `.min_atomic_width()` method.
615 pub min_atomic_width: Option<u64>,
617 /// Don't use this field; instead use the `.max_atomic_width()` method.
618 pub max_atomic_width: Option<u64>,
620 /// Whether the target supports atomic CAS operations natively
621 pub atomic_cas: bool,
623 /// Panic strategy: "unwind" or "abort"
624 pub panic_strategy: PanicStrategy,
626 /// A blacklist of ABIs unsupported by the current target. Note that generic
627 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
628 pub abi_blacklist: Vec<Abi>,
630 /// Whether or not linking dylibs to a static CRT is allowed.
631 pub crt_static_allows_dylibs: bool,
632 /// Whether or not the CRT is statically linked by default.
633 pub crt_static_default: bool,
634 /// Whether or not crt-static is respected by the compiler (or is a no-op).
635 pub crt_static_respected: bool,
637 /// Whether or not stack probes (__rust_probestack) are enabled
638 pub stack_probes: bool,
640 /// The minimum alignment for global symbols.
641 pub min_global_align: Option<u64>,
643 /// Default number of codegen units to use in debug mode
644 pub default_codegen_units: Option<u64>,
646 /// Whether to generate trap instructions in places where optimization would
647 /// otherwise produce control flow that falls through into unrelated memory.
648 pub trap_unreachable: bool,
650 /// This target requires everything to be compiled with LTO to emit a final
651 /// executable, aka there is no native linker for this target.
652 pub requires_lto: bool,
654 /// This target has no support for threads.
655 pub singlethread: bool,
657 /// Whether library functions call lowering/optimization is disabled in LLVM
658 /// for this target unconditionally.
659 pub no_builtins: bool,
661 /// Whether to lower 128-bit operations to compiler_builtins calls. Use if
662 /// your backend only supports 64-bit and smaller math.
663 pub i128_lowering: bool,
665 /// The codegen backend to use for this target, typically "llvm"
666 pub codegen_backend: String,
668 /// The default visibility for symbols in this target should be "hidden"
669 /// rather than "default"
670 pub default_hidden_visibility: bool,
672 /// Whether or not bitcode is embedded in object files
673 pub embed_bitcode: bool,
675 /// Whether a .debug_gdb_scripts section will be added to the output object file
676 pub emit_debug_gdb_scripts: bool,
678 /// Whether or not to unconditionally `uwtable` attributes on functions,
679 /// typically because the platform needs to unwind for things like stack
681 pub requires_uwtable: bool,
683 /// Whether or not SIMD types are passed by reference in the Rust ABI,
684 /// typically required if a target can be compiled with a mixed set of
685 /// target features. This is `true` by default, and `false` for targets like
686 /// wasm32 where the whole program either has simd or not.
687 pub simd_types_indirect: bool,
689 /// If set, have the linker export exactly these symbols, instead of using
690 /// the usual logic to figure this out from the crate itself.
691 pub override_export_symbols: Option<Vec<String>>
694 impl Default for TargetOptions {
695 /// Create a set of "sane defaults" for any target. This is still
696 /// incomplete, and if used for compilation, will certainly not work.
697 fn default() -> TargetOptions {
700 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
701 lld_flavor: LldFlavor::Ld,
702 pre_link_args: LinkArgs::new(),
703 pre_link_args_crt: LinkArgs::new(),
704 post_link_args: LinkArgs::new(),
705 asm_args: Vec::new(),
706 cpu: "generic".to_string(),
707 features: String::new(),
708 dynamic_linking: false,
711 relocation_model: "pic".to_string(),
713 tls_model: "global-dynamic".to_string(),
714 disable_redzone: false,
715 eliminate_frame_pointer: true,
716 function_sections: true,
717 dll_prefix: "lib".to_string(),
718 dll_suffix: ".so".to_string(),
719 exe_suffix: String::new(),
720 staticlib_prefix: "lib".to_string(),
721 staticlib_suffix: ".a".to_string(),
723 abi_return_struct_as_int: false,
725 is_like_solaris: false,
726 is_like_windows: false,
727 is_like_android: false,
728 is_like_emscripten: false,
730 linker_is_gnu: false,
731 allows_weak_linkage: true,
733 no_default_libraries: true,
734 position_independent_executables: false,
736 relro_level: RelroLevel::None,
737 pre_link_objects_exe: Vec::new(),
738 pre_link_objects_exe_crt: Vec::new(),
739 pre_link_objects_dll: Vec::new(),
740 post_link_objects: Vec::new(),
741 post_link_objects_crt: Vec::new(),
742 late_link_args: LinkArgs::new(),
743 link_env: Vec::new(),
744 archive_format: "gnu".to_string(),
745 custom_unwind_resume: false,
748 obj_is_bitcode: false,
749 no_integrated_as: false,
750 min_atomic_width: None,
751 max_atomic_width: None,
753 panic_strategy: PanicStrategy::Unwind,
754 abi_blacklist: vec![],
755 crt_static_allows_dylibs: false,
756 crt_static_default: false,
757 crt_static_respected: false,
759 min_global_align: None,
760 default_codegen_units: None,
761 trap_unreachable: true,
765 i128_lowering: false,
766 codegen_backend: "llvm".to_string(),
767 default_hidden_visibility: false,
768 embed_bitcode: false,
769 emit_debug_gdb_scripts: true,
770 requires_uwtable: false,
771 simd_types_indirect: true,
772 override_export_symbols: None,
778 /// Given a function ABI, turn it into the correct ABI for this target.
779 pub fn adjust_abi(&self, abi: Abi) -> Abi {
782 if self.options.is_like_windows && self.arch == "x86" {
788 // These ABI kinds are ignored on non-x86 Windows targets.
789 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
790 // and the individual pages for __stdcall et al.
791 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
792 if self.options.is_like_windows && self.arch != "x86" {
802 /// Minimum integer size in bits that this target can perform atomic
804 pub fn min_atomic_width(&self) -> u64 {
805 self.options.min_atomic_width.unwrap_or(8)
808 /// Maximum integer size in bits that this target can perform atomic
810 pub fn max_atomic_width(&self) -> u64 {
811 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
814 pub fn is_abi_supported(&self, abi: Abi) -> bool {
815 abi.generic() || !self.options.abi_blacklist.contains(&abi)
818 /// Load a target descriptor from a JSON object.
819 pub fn from_json(obj: Json) -> TargetResult {
820 // While ugly, this code must remain this way to retain
821 // compatibility with existing JSON fields and the internal
822 // expected naming of the Target and TargetOptions structs.
823 // To ensure compatibility is retained, the built-in targets
824 // are round-tripped through this code to catch cases where
825 // the JSON parser is not updated to match the structs.
827 let get_req_field = |name: &str| {
829 .map(|s| s.as_string())
830 .and_then(|os| os.map(|s| s.to_string()))
831 .ok_or_else(|| format!("Field {} in target specification is required", name))
834 let get_opt_field = |name: &str, default: &str| {
835 obj.find(name).and_then(|s| s.as_string())
836 .map(|s| s.to_string())
837 .unwrap_or_else(|| default.to_string())
840 let mut base = Target {
841 llvm_target: get_req_field("llvm-target")?,
842 target_endian: get_req_field("target-endian")?,
843 target_pointer_width: get_req_field("target-pointer-width")?,
844 target_c_int_width: get_req_field("target-c-int-width")?,
845 data_layout: get_req_field("data-layout")?,
846 arch: get_req_field("arch")?,
847 target_os: get_req_field("os")?,
848 target_env: get_opt_field("env", ""),
849 target_vendor: get_opt_field("vendor", "unknown"),
850 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
852 format!("linker flavor must be {}", LinkerFlavor::one_of())
854 options: Default::default(),
858 ($key_name:ident) => ( {
859 let name = (stringify!($key_name)).replace("_", "-");
860 obj.find(&name[..]).map(|o| o.as_string()
861 .map(|s| base.options.$key_name = s.to_string()));
863 ($key_name:ident, bool) => ( {
864 let name = (stringify!($key_name)).replace("_", "-");
866 .map(|o| o.as_boolean()
867 .map(|s| base.options.$key_name = s));
869 ($key_name:ident, Option<u64>) => ( {
870 let name = (stringify!($key_name)).replace("_", "-");
873 .map(|s| base.options.$key_name = Some(s)));
875 ($key_name:ident, PanicStrategy) => ( {
876 let name = (stringify!($key_name)).replace("_", "-");
877 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
879 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
880 "abort" => base.options.$key_name = PanicStrategy::Abort,
881 _ => return Some(Err(format!("'{}' is not a valid value for \
882 panic-strategy. Use 'unwind' or 'abort'.",
886 })).unwrap_or(Ok(()))
888 ($key_name:ident, RelroLevel) => ( {
889 let name = (stringify!($key_name)).replace("_", "-");
890 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
891 match s.parse::<RelroLevel>() {
892 Ok(level) => base.options.$key_name = level,
893 _ => return Some(Err(format!("'{}' is not a valid value for \
894 relro-level. Use 'full', 'partial, or 'off'.",
898 })).unwrap_or(Ok(()))
900 ($key_name:ident, list) => ( {
901 let name = (stringify!($key_name)).replace("_", "-");
902 obj.find(&name[..]).map(|o| o.as_array()
903 .map(|v| base.options.$key_name = v.iter()
904 .map(|a| a.as_string().unwrap().to_string()).collect()
908 ($key_name:ident, opt_list) => ( {
909 let name = (stringify!($key_name)).replace("_", "-");
910 obj.find(&name[..]).map(|o| o.as_array()
911 .map(|v| base.options.$key_name = Some(v.iter()
912 .map(|a| a.as_string().unwrap().to_string()).collect())
916 ($key_name:ident, optional) => ( {
917 let name = (stringify!($key_name)).replace("_", "-");
918 if let Some(o) = obj.find(&name[..]) {
919 base.options.$key_name = o
921 .map(|s| s.to_string() );
924 ($key_name:ident, LldFlavor) => ( {
925 let name = (stringify!($key_name)).replace("_", "-");
926 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
927 if let Some(flavor) = LldFlavor::from_str(&s) {
928 base.options.$key_name = flavor;
930 return Some(Err(format!(
931 "'{}' is not a valid value for lld-flavor. \
932 Use 'darwin', 'gnu', 'link' or 'wasm.",
936 })).unwrap_or(Ok(()))
938 ($key_name:ident, LinkerFlavor) => ( {
939 let name = (stringify!($key_name)).replace("_", "-");
940 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
941 LinkerFlavor::from_str(&s).ok_or_else(|| {
942 Err(format!("'{}' is not a valid value for linker-flavor. \
943 Use 'em', 'gcc', 'ld' or 'msvc.", s))
945 })).unwrap_or(Ok(()))
947 ($key_name:ident, link_args) => ( {
948 let name = (stringify!($key_name)).replace("_", "-");
949 if let Some(val) = obj.find(&name[..]) {
950 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
951 JSON object with fields per linker-flavor.", name))?;
952 let mut args = LinkArgs::new();
954 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
955 format!("{}: '{}' is not a valid value for linker-flavor. \
956 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
959 let v = v.as_array().ok_or_else(||
960 format!("{}.{}: expected a JSON array", name, k)
961 )?.iter().enumerate()
963 let s = s.as_string().ok_or_else(||
964 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
967 .collect::<Result<Vec<_>, String>>()?;
969 args.insert(flavor, v);
971 base.options.$key_name = args;
974 ($key_name:ident, env) => ( {
975 let name = (stringify!($key_name)).replace("_", "-");
976 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
978 if let Some(s) = o.as_string() {
979 let p = s.split('=').collect::<Vec<_>>();
981 let k = p[0].to_string();
982 let v = p[1].to_string();
983 base.options.$key_name.push((k, v));
991 key!(is_builtin, bool);
992 key!(linker, optional);
993 try!(key!(lld_flavor, LldFlavor));
994 key!(pre_link_args, link_args);
995 key!(pre_link_args_crt, link_args);
996 key!(pre_link_objects_exe, list);
997 key!(pre_link_objects_exe_crt, list);
998 key!(pre_link_objects_dll, list);
999 key!(late_link_args, link_args);
1000 key!(post_link_objects, list);
1001 key!(post_link_objects_crt, list);
1002 key!(post_link_args, link_args);
1003 key!(link_env, env);
1004 key!(asm_args, list);
1007 key!(dynamic_linking, bool);
1008 key!(only_cdylib, bool);
1009 key!(executables, bool);
1010 key!(relocation_model);
1011 key!(code_model, optional);
1013 key!(disable_redzone, bool);
1014 key!(eliminate_frame_pointer, bool);
1015 key!(function_sections, bool);
1019 key!(staticlib_prefix);
1020 key!(staticlib_suffix);
1021 key!(target_family, optional);
1022 key!(abi_return_struct_as_int, bool);
1023 key!(is_like_osx, bool);
1024 key!(is_like_solaris, bool);
1025 key!(is_like_windows, bool);
1026 key!(is_like_msvc, bool);
1027 key!(is_like_emscripten, bool);
1028 key!(is_like_android, bool);
1029 key!(linker_is_gnu, bool);
1030 key!(allows_weak_linkage, bool);
1031 key!(has_rpath, bool);
1032 key!(no_default_libraries, bool);
1033 key!(position_independent_executables, bool);
1034 key!(needs_plt, bool);
1035 try!(key!(relro_level, RelroLevel));
1036 key!(archive_format);
1037 key!(allow_asm, bool);
1038 key!(custom_unwind_resume, bool);
1039 key!(has_elf_tls, bool);
1040 key!(obj_is_bitcode, bool);
1041 key!(no_integrated_as, bool);
1042 key!(max_atomic_width, Option<u64>);
1043 key!(min_atomic_width, Option<u64>);
1044 key!(atomic_cas, bool);
1045 try!(key!(panic_strategy, PanicStrategy));
1046 key!(crt_static_allows_dylibs, bool);
1047 key!(crt_static_default, bool);
1048 key!(crt_static_respected, bool);
1049 key!(stack_probes, bool);
1050 key!(min_global_align, Option<u64>);
1051 key!(default_codegen_units, Option<u64>);
1052 key!(trap_unreachable, bool);
1053 key!(requires_lto, bool);
1054 key!(singlethread, bool);
1055 key!(no_builtins, bool);
1056 key!(codegen_backend);
1057 key!(default_hidden_visibility, bool);
1058 key!(embed_bitcode, bool);
1059 key!(emit_debug_gdb_scripts, bool);
1060 key!(requires_uwtable, bool);
1061 key!(simd_types_indirect, bool);
1062 key!(override_export_symbols, opt_list);
1064 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1065 for name in array.iter().filter_map(|abi| abi.as_string()) {
1066 match lookup_abi(name) {
1069 return Err(format!("The ABI \"{}\" is considered to be supported on \
1070 all targets and cannot be blacklisted", abi))
1073 base.options.abi_blacklist.push(abi)
1075 None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
1083 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1084 /// triple. Note that it could also just be a bare filename already, so also
1085 /// check for that. If one of the hardcoded targets we know about, just
1086 /// return it directly.
1088 /// The error string could come from any of the APIs called, including
1089 /// filesystem access and JSON decoding.
1090 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1093 use serialize::json;
1095 fn load_file(path: &Path) -> Result<Target, String> {
1096 let contents = fs::read(path).map_err(|e| e.to_string())?;
1097 let obj = json::from_reader(&mut &contents[..])
1098 .map_err(|e| e.to_string())?;
1099 Target::from_json(obj)
1102 match *target_triple {
1103 TargetTriple::TargetTriple(ref target_triple) => {
1104 // check if triple is in list of supported targets
1105 if let Ok(t) = load_specific(target_triple) {
1109 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1111 let mut target = target_triple.to_string();
1112 target.push_str(".json");
1113 PathBuf::from(target)
1116 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1118 // FIXME 16351: add a sane default search path?
1120 for dir in env::split_paths(&target_path) {
1121 let p = dir.join(&path);
1123 return load_file(&p);
1126 Err(format!("Could not find specification for target {:?}", target_triple))
1128 TargetTriple::TargetPath(ref target_path) => {
1129 if target_path.is_file() {
1130 return load_file(&target_path);
1132 Err(format!("Target path {:?} is not a valid file", target_path))
1138 impl ToJson for Target {
1139 fn to_json(&self) -> Json {
1140 let mut d = BTreeMap::new();
1141 let default: TargetOptions = Default::default();
1143 macro_rules! target_val {
1144 ($attr:ident) => ( {
1145 let name = (stringify!($attr)).replace("_", "-");
1146 d.insert(name, self.$attr.to_json());
1148 ($attr:ident, $key_name:expr) => ( {
1149 let name = $key_name;
1150 d.insert(name.to_string(), self.$attr.to_json());
1154 macro_rules! target_option_val {
1155 ($attr:ident) => ( {
1156 let name = (stringify!($attr)).replace("_", "-");
1157 if default.$attr != self.options.$attr {
1158 d.insert(name, self.options.$attr.to_json());
1161 ($attr:ident, $key_name:expr) => ( {
1162 let name = $key_name;
1163 if default.$attr != self.options.$attr {
1164 d.insert(name.to_string(), self.options.$attr.to_json());
1167 (link_args - $attr:ident) => ( {
1168 let name = (stringify!($attr)).replace("_", "-");
1169 if default.$attr != self.options.$attr {
1170 let obj = self.options.$attr
1172 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1173 .collect::<BTreeMap<_, _>>();
1174 d.insert(name, obj.to_json());
1177 (env - $attr:ident) => ( {
1178 let name = (stringify!($attr)).replace("_", "-");
1179 if default.$attr != self.options.$attr {
1180 let obj = self.options.$attr
1182 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1183 .collect::<Vec<_>>();
1184 d.insert(name, obj.to_json());
1190 target_val!(llvm_target);
1191 target_val!(target_endian);
1192 target_val!(target_pointer_width);
1193 target_val!(target_c_int_width);
1195 target_val!(target_os, "os");
1196 target_val!(target_env, "env");
1197 target_val!(target_vendor, "vendor");
1198 target_val!(data_layout);
1199 target_val!(linker_flavor);
1201 target_option_val!(is_builtin);
1202 target_option_val!(linker);
1203 target_option_val!(lld_flavor);
1204 target_option_val!(link_args - pre_link_args);
1205 target_option_val!(link_args - pre_link_args_crt);
1206 target_option_val!(pre_link_objects_exe);
1207 target_option_val!(pre_link_objects_exe_crt);
1208 target_option_val!(pre_link_objects_dll);
1209 target_option_val!(link_args - late_link_args);
1210 target_option_val!(post_link_objects);
1211 target_option_val!(post_link_objects_crt);
1212 target_option_val!(link_args - post_link_args);
1213 target_option_val!(env - link_env);
1214 target_option_val!(asm_args);
1215 target_option_val!(cpu);
1216 target_option_val!(features);
1217 target_option_val!(dynamic_linking);
1218 target_option_val!(only_cdylib);
1219 target_option_val!(executables);
1220 target_option_val!(relocation_model);
1221 target_option_val!(code_model);
1222 target_option_val!(tls_model);
1223 target_option_val!(disable_redzone);
1224 target_option_val!(eliminate_frame_pointer);
1225 target_option_val!(function_sections);
1226 target_option_val!(dll_prefix);
1227 target_option_val!(dll_suffix);
1228 target_option_val!(exe_suffix);
1229 target_option_val!(staticlib_prefix);
1230 target_option_val!(staticlib_suffix);
1231 target_option_val!(target_family);
1232 target_option_val!(abi_return_struct_as_int);
1233 target_option_val!(is_like_osx);
1234 target_option_val!(is_like_solaris);
1235 target_option_val!(is_like_windows);
1236 target_option_val!(is_like_msvc);
1237 target_option_val!(is_like_emscripten);
1238 target_option_val!(is_like_android);
1239 target_option_val!(linker_is_gnu);
1240 target_option_val!(allows_weak_linkage);
1241 target_option_val!(has_rpath);
1242 target_option_val!(no_default_libraries);
1243 target_option_val!(position_independent_executables);
1244 target_option_val!(needs_plt);
1245 target_option_val!(relro_level);
1246 target_option_val!(archive_format);
1247 target_option_val!(allow_asm);
1248 target_option_val!(custom_unwind_resume);
1249 target_option_val!(has_elf_tls);
1250 target_option_val!(obj_is_bitcode);
1251 target_option_val!(no_integrated_as);
1252 target_option_val!(min_atomic_width);
1253 target_option_val!(max_atomic_width);
1254 target_option_val!(atomic_cas);
1255 target_option_val!(panic_strategy);
1256 target_option_val!(crt_static_allows_dylibs);
1257 target_option_val!(crt_static_default);
1258 target_option_val!(crt_static_respected);
1259 target_option_val!(stack_probes);
1260 target_option_val!(min_global_align);
1261 target_option_val!(default_codegen_units);
1262 target_option_val!(trap_unreachable);
1263 target_option_val!(requires_lto);
1264 target_option_val!(singlethread);
1265 target_option_val!(no_builtins);
1266 target_option_val!(codegen_backend);
1267 target_option_val!(default_hidden_visibility);
1268 target_option_val!(embed_bitcode);
1269 target_option_val!(emit_debug_gdb_scripts);
1270 target_option_val!(requires_uwtable);
1271 target_option_val!(simd_types_indirect);
1272 target_option_val!(override_export_symbols);
1274 if default.abi_blacklist != self.options.abi_blacklist {
1275 d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1276 .map(|&name| Abi::name(name).to_json())
1277 .collect::<Vec<_>>().to_json());
1284 /// Either a target triple string or a path to a JSON file.
1285 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1286 pub enum TargetTriple {
1287 TargetTriple(String),
1288 TargetPath(PathBuf),
1292 /// Creates a target triple from the passed target triple string.
1293 pub fn from_triple(triple: &str) -> Self {
1294 TargetTriple::TargetTriple(triple.to_string())
1297 /// Creates a target triple from the passed target path.
1298 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1299 let canonicalized_path = path.canonicalize()?;
1300 Ok(TargetTriple::TargetPath(canonicalized_path))
1303 /// Returns a string triple for this target.
1305 /// If this target is a path, the file name (without extension) is returned.
1306 pub fn triple(&self) -> &str {
1308 TargetTriple::TargetTriple(ref triple) => triple,
1309 TargetTriple::TargetPath(ref path) => {
1310 path.file_stem().expect("target path must not be empty").to_str()
1311 .expect("target path must be valid unicode")
1316 /// Returns an extended string triple for this target.
1318 /// If this target is a path, a hash of the path is appended to the triple returned
1320 pub fn debug_triple(&self) -> String {
1321 use std::hash::{Hash, Hasher};
1322 use std::collections::hash_map::DefaultHasher;
1324 let triple = self.triple();
1325 if let TargetTriple::TargetPath(ref path) = *self {
1326 let mut hasher = DefaultHasher::new();
1327 path.hash(&mut hasher);
1328 let hash = hasher.finish();
1329 format!("{}-{}", triple, hash)
1336 impl fmt::Display for TargetTriple {
1337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338 write!(f, "{}", self.debug_triple())