1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
9 //! # Using custom targets
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
26 //! # Defining a new target
28 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
37 use crate::spec::abi::{lookup as lookup_abi, Abi};
38 use rustc_serialize::json::{Json, ToJson};
39 use std::collections::BTreeMap;
40 use std::path::{Path, PathBuf};
41 use std::str::FromStr;
44 use rustc_macros::HashStable_Generic;
57 mod hermit_kernel_base;
61 mod linux_kernel_base;
74 mod windows_msvc_base;
75 mod windows_uwp_gnu_base;
76 mod windows_uwp_msvc_base;
78 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
79 pub enum LinkerFlavor {
88 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
97 fn from_str(s: &str) -> Option<Self> {
99 "darwin" => LldFlavor::Ld64,
100 "gnu" => LldFlavor::Ld,
101 "link" => LldFlavor::Link,
102 "wasm" => LldFlavor::Wasm,
108 impl ToJson for LldFlavor {
109 fn to_json(&self) -> Json {
111 LldFlavor::Ld64 => "darwin",
112 LldFlavor::Ld => "gnu",
113 LldFlavor::Link => "link",
114 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,)*
149 ((LinkerFlavor::Em), "em"),
150 ((LinkerFlavor::Gcc), "gcc"),
151 ((LinkerFlavor::Ld), "ld"),
152 ((LinkerFlavor::Msvc), "msvc"),
153 ((LinkerFlavor::PtxLinker), "ptx-linker"),
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, HashStable_Generic)]
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 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
229 pub enum MergeFunctions {
235 impl MergeFunctions {
236 pub fn desc(&self) -> &str {
238 MergeFunctions::Disabled => "disabled",
239 MergeFunctions::Trampolines => "trampolines",
240 MergeFunctions::Aliases => "aliases",
245 impl FromStr for MergeFunctions {
248 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
250 "disabled" => Ok(MergeFunctions::Disabled),
251 "trampolines" => Ok(MergeFunctions::Trampolines),
252 "aliases" => Ok(MergeFunctions::Aliases),
258 impl ToJson for MergeFunctions {
259 fn to_json(&self) -> Json {
261 MergeFunctions::Disabled => "disabled".to_json(),
262 MergeFunctions::Trampolines => "trampolines".to_json(),
263 MergeFunctions::Aliases => "aliases".to_json(),
268 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
269 pub enum RelocModel {
278 impl FromStr for RelocModel {
281 fn from_str(s: &str) -> Result<RelocModel, ()> {
283 "static" => RelocModel::Static,
284 "pic" => RelocModel::Pic,
285 "dynamic-no-pic" => RelocModel::DynamicNoPic,
286 "ropi" => RelocModel::Ropi,
287 "rwpi" => RelocModel::Rwpi,
288 "ropi-rwpi" => RelocModel::RopiRwpi,
294 impl ToJson for RelocModel {
295 fn to_json(&self) -> Json {
297 RelocModel::Static => "static",
298 RelocModel::Pic => "pic",
299 RelocModel::DynamicNoPic => "dynamic-no-pic",
300 RelocModel::Ropi => "ropi",
301 RelocModel::Rwpi => "rwpi",
302 RelocModel::RopiRwpi => "ropi-rwpi",
308 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
316 impl FromStr for TlsModel {
319 fn from_str(s: &str) -> Result<TlsModel, ()> {
321 // Note the difference "general" vs "global" difference. The model name is "general",
322 // but the user-facing option name is "global" for consistency with other compilers.
323 "global-dynamic" => TlsModel::GeneralDynamic,
324 "local-dynamic" => TlsModel::LocalDynamic,
325 "initial-exec" => TlsModel::InitialExec,
326 "local-exec" => TlsModel::LocalExec,
332 impl ToJson for TlsModel {
333 fn to_json(&self) -> Json {
335 TlsModel::GeneralDynamic => "global-dynamic",
336 TlsModel::LocalDynamic => "local-dynamic",
337 TlsModel::InitialExec => "initial-exec",
338 TlsModel::LocalExec => "local-exec",
344 pub enum LoadTargetError {
345 BuiltinTargetNotFound(String),
349 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
350 pub type TargetResult = Result<Target, String>;
352 macro_rules! supported_targets {
353 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
356 /// List of supported targets
357 const TARGETS: &[&str] = &[$($($triple),+),+];
359 fn load_specific(target: &str) -> Result<Target, LoadTargetError> {
363 let mut t = $module::target()
364 .map_err(LoadTargetError::Other)?;
365 t.options.is_builtin = true;
367 // round-trip through the JSON parser to ensure at
368 // run-time that the parser works correctly
369 t = Target::from_json(t.to_json())
370 .map_err(LoadTargetError::Other)?;
371 debug!("got builtin target: {:?}", t);
375 _ => Err(LoadTargetError::BuiltinTargetNotFound(
376 format!("Unable to find target: {}", target)))
380 pub fn get_targets() -> impl Iterator<Item = String> {
381 TARGETS.iter().filter_map(|t| -> Option<String> {
383 .and(Ok(t.to_string()))
392 // Cannot put this into a separate file without duplication, make an exception.
396 tests_impl::test_target(super::$module::target());
404 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
405 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
406 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
407 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
408 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
409 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
410 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
411 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
412 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
413 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
414 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
415 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
416 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
417 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
418 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
419 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
420 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
421 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
422 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
423 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
424 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
425 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
426 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
427 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
428 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
429 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
430 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
431 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
432 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
433 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
434 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
435 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
436 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
437 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
438 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
439 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
440 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
441 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
442 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
443 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
444 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
445 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
446 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
447 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
448 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
450 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
451 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
453 ("i686-linux-android", i686_linux_android),
454 ("x86_64-linux-android", x86_64_linux_android),
455 ("arm-linux-androideabi", arm_linux_androideabi),
456 ("armv7-linux-androideabi", armv7_linux_androideabi),
457 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
458 ("aarch64-linux-android", aarch64_linux_android),
460 ("x86_64-linux-kernel", x86_64_linux_kernel),
462 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
463 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
464 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
465 ("i686-unknown-freebsd", i686_unknown_freebsd),
466 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
467 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
469 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
471 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
472 ("i686-unknown-openbsd", i686_unknown_openbsd),
473 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
474 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
476 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
477 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
478 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
479 ("i686-unknown-netbsd", i686_unknown_netbsd),
480 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
481 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
482 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
483 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
485 ("i686-unknown-haiku", i686_unknown_haiku),
486 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
488 ("x86_64-apple-darwin", x86_64_apple_darwin),
489 ("i686-apple-darwin", i686_apple_darwin),
491 ("aarch64-fuchsia", aarch64_fuchsia),
492 ("x86_64-fuchsia", x86_64_fuchsia),
494 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
496 ("aarch64-unknown-redox", aarch64_unknown_redox),
497 ("x86_64-unknown-redox", x86_64_unknown_redox),
499 ("i386-apple-ios", i386_apple_ios),
500 ("x86_64-apple-ios", x86_64_apple_ios),
501 ("aarch64-apple-ios", aarch64_apple_ios),
502 ("armv7-apple-ios", armv7_apple_ios),
503 ("armv7s-apple-ios", armv7s_apple_ios),
504 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
505 ("aarch64-apple-tvos", aarch64_apple_tvos),
506 ("x86_64-apple-tvos", x86_64_apple_tvos),
508 ("armebv7r-none-eabi", armebv7r_none_eabi),
509 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
510 ("armv7r-none-eabi", armv7r_none_eabi),
511 ("armv7r-none-eabihf", armv7r_none_eabihf),
513 // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
514 // (See <https://github.com/rust-lang/rust/issues/40531>.)
515 ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris),
516 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
518 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
520 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
521 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
522 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
523 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
525 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
526 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
527 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
528 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
529 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
530 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
531 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
532 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
534 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
535 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
536 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
537 ("wasm32-wasi", wasm32_wasi),
539 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
540 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
541 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
542 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
543 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
544 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
545 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
547 ("armv7a-none-eabi", armv7a_none_eabi),
548 ("armv7a-none-eabihf", armv7a_none_eabihf),
550 ("msp430-none-elf", msp430_none_elf),
552 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
553 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
554 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
555 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
557 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
558 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
559 ("x86_64-unknown-hermit-kernel", x86_64_unknown_hermit_kernel),
561 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
562 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
563 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
564 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
565 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
566 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
568 ("aarch64-unknown-none", aarch64_unknown_none),
569 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
571 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
573 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
574 ("i686-unknown-uefi", i686_unknown_uefi),
576 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
578 ("i686-wrs-vxworks", i686_wrs_vxworks),
579 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
580 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
581 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
582 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
583 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
584 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
587 /// Everything `rustc` knows about how to compile for a specific target.
589 /// Every field here must be specified, and has no default value.
590 #[derive(PartialEq, Clone, Debug)]
592 /// Target triple to pass to LLVM.
593 pub llvm_target: String,
594 /// String to use as the `target_endian` `cfg` variable.
595 pub target_endian: String,
596 /// String to use as the `target_pointer_width` `cfg` variable.
597 pub target_pointer_width: String,
598 /// Width of c_int type
599 pub target_c_int_width: String,
600 /// OS name to use for conditional compilation.
601 pub target_os: String,
602 /// Environment name to use for conditional compilation.
603 pub target_env: String,
604 /// Vendor name to use for conditional compilation.
605 pub target_vendor: String,
606 /// Architecture to use for ABI considerations. Valid options include: "x86",
607 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
609 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
610 pub data_layout: String,
611 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
612 /// on the command line.
613 pub linker_flavor: LinkerFlavor,
614 /// Optional settings with defaults.
615 pub options: TargetOptions,
618 pub trait HasTargetSpec {
619 fn target_spec(&self) -> &Target;
622 impl HasTargetSpec for Target {
623 fn target_spec(&self) -> &Target {
628 /// Optional aspects of a target specification.
630 /// This has an implementation of `Default`, see each field for what the default is. In general,
631 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
632 #[derive(PartialEq, Clone, Debug)]
633 pub struct TargetOptions {
634 /// Whether the target is built-in or loaded from a custom target specification.
635 pub is_builtin: bool,
638 pub linker: Option<String>,
640 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
641 /// without clarifying its flavor in any way.
642 pub lld_flavor: LldFlavor,
644 /// Linker arguments that are passed *before* any user-defined libraries.
645 pub pre_link_args: LinkArgs, // ... unconditionally
646 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
647 /// Objects to link before all others, always found within the
649 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
650 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
651 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
652 /// Linker arguments that are unconditionally passed after any
653 /// user-defined but before post_link_objects. Standard platform
654 /// libraries that should be always be linked to, usually go here.
655 pub late_link_args: LinkArgs,
656 /// Linker arguments used in addition to `late_link_args` if at least one
657 /// Rust dependency is dynamically linked.
658 pub late_link_args_dynamic: LinkArgs,
659 /// Linker arguments used in addition to `late_link_args` if aall Rust
660 /// dependencies are statically linked.
661 pub late_link_args_static: LinkArgs,
662 /// Objects to link after all others, always found within the
664 pub post_link_objects: Vec<String>, // ... unconditionally
665 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
666 /// Linker arguments that are unconditionally passed *after* any
667 /// user-defined libraries.
668 pub post_link_args: LinkArgs,
670 /// Environment variables to be set for the linker invocation.
671 pub link_env: Vec<(String, String)>,
672 /// Environment variables to be removed for the linker invocation.
673 pub link_env_remove: Vec<String>,
675 /// Extra arguments to pass to the external assembler (when used)
676 pub asm_args: Vec<String>,
678 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
681 /// Default target features to pass to LLVM. These features will *always* be
682 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
683 /// -mattr=$features`.
684 pub features: String,
685 /// Whether dynamic linking is available on this target. Defaults to false.
686 pub dynamic_linking: bool,
687 /// If dynamic linking is available, whether only cdylibs are supported.
688 pub only_cdylib: bool,
689 /// Whether executables are available on this target. iOS, for example, only allows static
690 /// libraries. Defaults to false.
691 pub executables: bool,
692 /// Relocation model to use in object file. Corresponds to `llc
693 /// -relocation-model=$relocation_model`. Defaults to `Pic`.
694 pub relocation_model: RelocModel,
695 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
696 pub code_model: Option<String>,
697 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
698 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
699 pub tls_model: TlsModel,
700 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
701 pub disable_redzone: bool,
702 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
703 pub eliminate_frame_pointer: bool,
704 /// Emit each function in its own section. Defaults to true.
705 pub function_sections: bool,
706 /// String to prepend to the name of every dynamic library. Defaults to "lib".
707 pub dll_prefix: String,
708 /// String to append to the name of every dynamic library. Defaults to ".so".
709 pub dll_suffix: String,
710 /// String to append to the name of every executable.
711 pub exe_suffix: String,
712 /// String to prepend to the name of every static library. Defaults to "lib".
713 pub staticlib_prefix: String,
714 /// String to append to the name of every static library. Defaults to ".a".
715 pub staticlib_suffix: String,
716 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
717 pub target_family: Option<String>,
718 /// Whether the target toolchain's ABI supports returning small structs as an integer.
719 pub abi_return_struct_as_int: bool,
720 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
721 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
722 pub is_like_osx: bool,
723 /// Whether the target toolchain is like Solaris's.
724 /// Only useful for compiling against Illumos/Solaris,
725 /// as they have a different set of linker flags. Defaults to false.
726 pub is_like_solaris: bool,
727 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
728 /// only really used for figuring out how to find libraries, since Windows uses its own
729 /// library naming convention. Defaults to false.
730 pub is_like_windows: bool,
731 pub is_like_msvc: bool,
732 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
733 /// Defaults to false.
734 pub is_like_android: bool,
735 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
736 /// Emscripten toolchain.
737 /// Defaults to false.
738 pub is_like_emscripten: bool,
739 /// Whether the target toolchain is like Fuchsia's.
740 pub is_like_fuchsia: bool,
741 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
742 pub linker_is_gnu: bool,
743 /// The MinGW toolchain has a known issue that prevents it from correctly
744 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
745 /// symbol needs its own COMDAT section, weak linkage implies a large
746 /// number sections that easily exceeds the given limit for larger
747 /// codebases. Consequently we want a way to disallow weak linkage on some
749 pub allows_weak_linkage: bool,
750 /// Whether the linker support rpaths or not. Defaults to false.
752 /// Whether to disable linking to the default libraries, typically corresponds
753 /// to `-nodefaultlibs`. Defaults to true.
754 pub no_default_libraries: bool,
755 /// Dynamically linked executables can be compiled as position independent
756 /// if the default relocation model of position independent code is not
757 /// changed. This is a requirement to take advantage of ASLR, as otherwise
758 /// the functions in the executable are not randomized and can be used
759 /// during an exploit of a vulnerability in any code.
760 pub position_independent_executables: bool,
761 /// Determines if the target always requires using the PLT for indirect
762 /// library calls or not. This controls the default value of the `-Z plt` flag.
764 /// Either partial, full, or off. Full RELRO makes the dynamic linker
765 /// resolve all symbols at startup and marks the GOT read-only before
766 /// starting the program, preventing overwriting the GOT.
767 pub relro_level: RelroLevel,
768 /// Format that archives should be emitted in. This affects whether we use
769 /// LLVM to assemble an archive or fall back to the system linker, and
770 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
771 /// the system linker to be used.
772 pub archive_format: String,
773 /// Is asm!() allowed? Defaults to true.
775 /// Whether the runtime startup code requires the `main` function be passed
776 /// `argc` and `argv` values.
777 pub main_needs_argc_argv: bool,
779 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
781 pub has_elf_tls: bool,
782 // This is mainly for easy compatibility with emscripten.
783 // If we give emcc .o files that are actually .bc files it
785 pub obj_is_bitcode: bool,
786 /// Whether the target requires that emitted object code includes bitcode.
787 pub forces_embed_bitcode: bool,
788 /// Content of the LLVM cmdline section associated with embedded bitcode.
789 pub bitcode_llvm_cmdline: String,
791 /// Don't use this field; instead use the `.min_atomic_width()` method.
792 pub min_atomic_width: Option<u64>,
794 /// Don't use this field; instead use the `.max_atomic_width()` method.
795 pub max_atomic_width: Option<u64>,
797 /// Whether the target supports atomic CAS operations natively
798 pub atomic_cas: bool,
800 /// Panic strategy: "unwind" or "abort"
801 pub panic_strategy: PanicStrategy,
803 /// A blacklist of ABIs unsupported by the current target. Note that generic
804 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
805 pub abi_blacklist: Vec<Abi>,
807 /// Whether or not linking dylibs to a static CRT is allowed.
808 pub crt_static_allows_dylibs: bool,
809 /// Whether or not the CRT is statically linked by default.
810 pub crt_static_default: bool,
811 /// Whether or not crt-static is respected by the compiler (or is a no-op).
812 pub crt_static_respected: bool,
814 /// Whether or not stack probes (__rust_probestack) are enabled
815 pub stack_probes: bool,
817 /// The minimum alignment for global symbols.
818 pub min_global_align: Option<u64>,
820 /// Default number of codegen units to use in debug mode
821 pub default_codegen_units: Option<u64>,
823 /// Whether to generate trap instructions in places where optimization would
824 /// otherwise produce control flow that falls through into unrelated memory.
825 pub trap_unreachable: bool,
827 /// This target requires everything to be compiled with LTO to emit a final
828 /// executable, aka there is no native linker for this target.
829 pub requires_lto: bool,
831 /// This target has no support for threads.
832 pub singlethread: bool,
834 /// Whether library functions call lowering/optimization is disabled in LLVM
835 /// for this target unconditionally.
836 pub no_builtins: bool,
838 /// The codegen backend to use for this target, typically "llvm"
839 pub codegen_backend: String,
841 /// The default visibility for symbols in this target should be "hidden"
842 /// rather than "default"
843 pub default_hidden_visibility: bool,
845 /// Whether a .debug_gdb_scripts section will be added to the output object file
846 pub emit_debug_gdb_scripts: bool,
848 /// Whether or not to unconditionally `uwtable` attributes on functions,
849 /// typically because the platform needs to unwind for things like stack
851 pub requires_uwtable: bool,
853 /// Whether or not SIMD types are passed by reference in the Rust ABI,
854 /// typically required if a target can be compiled with a mixed set of
855 /// target features. This is `true` by default, and `false` for targets like
856 /// wasm32 where the whole program either has simd or not.
857 pub simd_types_indirect: bool,
859 /// Pass a list of symbol which should be exported in the dylib to the linker.
860 pub limit_rdylib_exports: bool,
862 /// If set, have the linker export exactly these symbols, instead of using
863 /// the usual logic to figure this out from the crate itself.
864 pub override_export_symbols: Option<Vec<String>>,
866 /// Determines how or whether the MergeFunctions LLVM pass should run for
867 /// this target. Either "disabled", "trampolines", or "aliases".
868 /// The MergeFunctions pass is generally useful, but some targets may need
869 /// to opt out. The default is "aliases".
871 /// Workaround for: https://github.com/rust-lang/rust/issues/57356
872 pub merge_functions: MergeFunctions,
874 /// Use platform dependent mcount function
875 pub target_mcount: String,
877 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
878 pub llvm_abiname: String,
880 /// Whether or not RelaxElfRelocation flag will be passed to the linker
881 pub relax_elf_relocations: bool,
883 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
884 pub llvm_args: Vec<String>,
887 impl Default for TargetOptions {
888 /// Creates a set of "sane defaults" for any target. This is still
889 /// incomplete, and if used for compilation, will certainly not work.
890 fn default() -> TargetOptions {
893 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
894 lld_flavor: LldFlavor::Ld,
895 pre_link_args: LinkArgs::new(),
896 pre_link_args_crt: LinkArgs::new(),
897 post_link_args: LinkArgs::new(),
898 asm_args: Vec::new(),
899 cpu: "generic".to_string(),
900 features: String::new(),
901 dynamic_linking: false,
904 relocation_model: RelocModel::Pic,
906 tls_model: TlsModel::GeneralDynamic,
907 disable_redzone: false,
908 eliminate_frame_pointer: true,
909 function_sections: true,
910 dll_prefix: "lib".to_string(),
911 dll_suffix: ".so".to_string(),
912 exe_suffix: String::new(),
913 staticlib_prefix: "lib".to_string(),
914 staticlib_suffix: ".a".to_string(),
916 abi_return_struct_as_int: false,
918 is_like_solaris: false,
919 is_like_windows: false,
920 is_like_android: false,
921 is_like_emscripten: false,
923 is_like_fuchsia: false,
924 linker_is_gnu: false,
925 allows_weak_linkage: true,
927 no_default_libraries: true,
928 position_independent_executables: false,
930 relro_level: RelroLevel::None,
931 pre_link_objects_exe: Vec::new(),
932 pre_link_objects_exe_crt: Vec::new(),
933 pre_link_objects_dll: Vec::new(),
934 post_link_objects: Vec::new(),
935 post_link_objects_crt: Vec::new(),
936 late_link_args: LinkArgs::new(),
937 late_link_args_dynamic: LinkArgs::new(),
938 late_link_args_static: LinkArgs::new(),
939 link_env: Vec::new(),
940 link_env_remove: Vec::new(),
941 archive_format: "gnu".to_string(),
942 main_needs_argc_argv: true,
945 obj_is_bitcode: false,
946 forces_embed_bitcode: false,
947 bitcode_llvm_cmdline: String::new(),
948 min_atomic_width: None,
949 max_atomic_width: None,
951 panic_strategy: PanicStrategy::Unwind,
952 abi_blacklist: vec![],
953 crt_static_allows_dylibs: false,
954 crt_static_default: false,
955 crt_static_respected: false,
957 min_global_align: None,
958 default_codegen_units: None,
959 trap_unreachable: true,
963 codegen_backend: "llvm".to_string(),
964 default_hidden_visibility: false,
965 emit_debug_gdb_scripts: true,
966 requires_uwtable: false,
967 simd_types_indirect: true,
968 limit_rdylib_exports: true,
969 override_export_symbols: None,
970 merge_functions: MergeFunctions::Aliases,
971 target_mcount: "mcount".to_string(),
972 llvm_abiname: "".to_string(),
973 relax_elf_relocations: false,
980 /// Given a function ABI, turn it into the correct ABI for this target.
981 pub fn adjust_abi(&self, abi: Abi) -> Abi {
984 if self.options.is_like_windows && self.arch == "x86" {
990 // These ABI kinds are ignored on non-x86 Windows targets.
991 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
992 // and the individual pages for __stdcall et al.
993 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
994 if self.options.is_like_windows && self.arch != "x86" { Abi::C } else { abi }
997 if self.arch == "x86_64" {
1007 /// Minimum integer size in bits that this target can perform atomic
1009 pub fn min_atomic_width(&self) -> u64 {
1010 self.options.min_atomic_width.unwrap_or(8)
1013 /// Maximum integer size in bits that this target can perform atomic
1015 pub fn max_atomic_width(&self) -> u64 {
1016 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
1019 pub fn is_abi_supported(&self, abi: Abi) -> bool {
1020 abi.generic() || !self.options.abi_blacklist.contains(&abi)
1023 /// Loads a target descriptor from a JSON object.
1024 pub fn from_json(obj: Json) -> TargetResult {
1025 // While ugly, this code must remain this way to retain
1026 // compatibility with existing JSON fields and the internal
1027 // expected naming of the Target and TargetOptions structs.
1028 // To ensure compatibility is retained, the built-in targets
1029 // are round-tripped through this code to catch cases where
1030 // the JSON parser is not updated to match the structs.
1032 let get_req_field = |name: &str| {
1034 .map(|s| s.as_string())
1035 .and_then(|os| os.map(|s| s.to_string()))
1036 .ok_or_else(|| format!("Field {} in target specification is required", name))
1039 let get_opt_field = |name: &str, default: &str| {
1041 .and_then(|s| s.as_string())
1042 .map(|s| s.to_string())
1043 .unwrap_or_else(|| default.to_string())
1046 let mut base = Target {
1047 llvm_target: get_req_field("llvm-target")?,
1048 target_endian: get_req_field("target-endian")?,
1049 target_pointer_width: get_req_field("target-pointer-width")?,
1050 target_c_int_width: get_req_field("target-c-int-width")?,
1051 data_layout: get_req_field("data-layout")?,
1052 arch: get_req_field("arch")?,
1053 target_os: get_req_field("os")?,
1054 target_env: get_opt_field("env", ""),
1055 target_vendor: get_opt_field("vendor", "unknown"),
1056 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
1057 .ok_or_else(|| format!("linker flavor must be {}", LinkerFlavor::one_of()))?,
1058 options: Default::default(),
1062 ($key_name:ident) => ( {
1063 let name = (stringify!($key_name)).replace("_", "-");
1064 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1065 base.options.$key_name = s.to_string();
1068 ($key_name:ident, bool) => ( {
1069 let name = (stringify!($key_name)).replace("_", "-");
1070 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
1071 base.options.$key_name = s;
1074 ($key_name:ident, Option<u64>) => ( {
1075 let name = (stringify!($key_name)).replace("_", "-");
1076 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1077 base.options.$key_name = Some(s);
1080 ($key_name:ident, MergeFunctions) => ( {
1081 let name = (stringify!($key_name)).replace("_", "-");
1082 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1083 match s.parse::<MergeFunctions>() {
1084 Ok(mergefunc) => base.options.$key_name = mergefunc,
1085 _ => return Some(Err(format!("'{}' is not a valid value for \
1086 merge-functions. Use 'disabled', \
1087 'trampolines', or 'aliases'.",
1091 })).unwrap_or(Ok(()))
1093 ($key_name:ident, RelocModel) => ( {
1094 let name = (stringify!($key_name)).replace("_", "-");
1095 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1096 match s.parse::<RelocModel>() {
1097 Ok(relocation_model) => base.options.$key_name = relocation_model,
1098 _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1099 Run `rustc --print relocation-models` to \
1100 see the list of supported values.", s))),
1103 })).unwrap_or(Ok(()))
1105 ($key_name:ident, TlsModel) => ( {
1106 let name = (stringify!($key_name)).replace("_", "-");
1107 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1108 match s.parse::<TlsModel>() {
1109 Ok(tls_model) => base.options.$key_name = tls_model,
1110 _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1111 Run `rustc --print tls-models` to \
1112 see the list of supported values.", s))),
1115 })).unwrap_or(Ok(()))
1117 ($key_name:ident, PanicStrategy) => ( {
1118 let name = (stringify!($key_name)).replace("_", "-");
1119 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1121 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
1122 "abort" => base.options.$key_name = PanicStrategy::Abort,
1123 _ => return Some(Err(format!("'{}' is not a valid value for \
1124 panic-strategy. Use 'unwind' or 'abort'.",
1128 })).unwrap_or(Ok(()))
1130 ($key_name:ident, RelroLevel) => ( {
1131 let name = (stringify!($key_name)).replace("_", "-");
1132 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1133 match s.parse::<RelroLevel>() {
1134 Ok(level) => base.options.$key_name = level,
1135 _ => return Some(Err(format!("'{}' is not a valid value for \
1136 relro-level. Use 'full', 'partial, or 'off'.",
1140 })).unwrap_or(Ok(()))
1142 ($key_name:ident, list) => ( {
1143 let name = (stringify!($key_name)).replace("_", "-");
1144 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1145 base.options.$key_name = v.iter()
1146 .map(|a| a.as_string().unwrap().to_string())
1150 ($key_name:ident, opt_list) => ( {
1151 let name = (stringify!($key_name)).replace("_", "-");
1152 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1153 base.options.$key_name = Some(v.iter()
1154 .map(|a| a.as_string().unwrap().to_string())
1158 ($key_name:ident, optional) => ( {
1159 let name = (stringify!($key_name)).replace("_", "-");
1160 if let Some(o) = obj.find(&name[..]) {
1161 base.options.$key_name = o
1163 .map(|s| s.to_string() );
1166 ($key_name:ident, LldFlavor) => ( {
1167 let name = (stringify!($key_name)).replace("_", "-");
1168 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1169 if let Some(flavor) = LldFlavor::from_str(&s) {
1170 base.options.$key_name = flavor;
1172 return Some(Err(format!(
1173 "'{}' is not a valid value for lld-flavor. \
1174 Use 'darwin', 'gnu', 'link' or 'wasm.",
1178 })).unwrap_or(Ok(()))
1180 ($key_name:ident, LinkerFlavor) => ( {
1181 let name = (stringify!($key_name)).replace("_", "-");
1182 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
1183 LinkerFlavor::from_str(&s).ok_or_else(|| {
1184 Err(format!("'{}' is not a valid value for linker-flavor. \
1185 Use 'em', 'gcc', 'ld' or 'msvc.", s))
1187 })).unwrap_or(Ok(()))
1189 ($key_name:ident, link_args) => ( {
1190 let name = (stringify!($key_name)).replace("_", "-");
1191 if let Some(val) = obj.find(&name[..]) {
1192 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1193 JSON object with fields per linker-flavor.", name))?;
1194 let mut args = LinkArgs::new();
1196 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1197 format!("{}: '{}' is not a valid value for linker-flavor. \
1198 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1201 let v = v.as_array().ok_or_else(||
1202 format!("{}.{}: expected a JSON array", name, k)
1203 )?.iter().enumerate()
1205 let s = s.as_string().ok_or_else(||
1206 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1209 .collect::<Result<Vec<_>, String>>()?;
1211 args.insert(flavor, v);
1213 base.options.$key_name = args;
1216 ($key_name:ident, env) => ( {
1217 let name = (stringify!($key_name)).replace("_", "-");
1218 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1220 if let Some(s) = o.as_string() {
1221 let p = s.split('=').collect::<Vec<_>>();
1223 let k = p[0].to_string();
1224 let v = p[1].to_string();
1225 base.options.$key_name.push((k, v));
1233 key!(is_builtin, bool);
1234 key!(linker, optional);
1235 key!(lld_flavor, LldFlavor)?;
1236 key!(pre_link_args, link_args);
1237 key!(pre_link_args_crt, link_args);
1238 key!(pre_link_objects_exe, list);
1239 key!(pre_link_objects_exe_crt, list);
1240 key!(pre_link_objects_dll, list);
1241 key!(late_link_args, link_args);
1242 key!(late_link_args_dynamic, link_args);
1243 key!(late_link_args_static, link_args);
1244 key!(post_link_objects, list);
1245 key!(post_link_objects_crt, list);
1246 key!(post_link_args, link_args);
1247 key!(link_env, env);
1248 key!(link_env_remove, list);
1249 key!(asm_args, list);
1252 key!(dynamic_linking, bool);
1253 key!(only_cdylib, bool);
1254 key!(executables, bool);
1255 key!(relocation_model, RelocModel)?;
1256 key!(code_model, optional);
1257 key!(tls_model, TlsModel)?;
1258 key!(disable_redzone, bool);
1259 key!(eliminate_frame_pointer, bool);
1260 key!(function_sections, bool);
1264 key!(staticlib_prefix);
1265 key!(staticlib_suffix);
1266 key!(target_family, optional);
1267 key!(abi_return_struct_as_int, bool);
1268 key!(is_like_osx, bool);
1269 key!(is_like_solaris, bool);
1270 key!(is_like_windows, bool);
1271 key!(is_like_msvc, bool);
1272 key!(is_like_emscripten, bool);
1273 key!(is_like_android, bool);
1274 key!(is_like_fuchsia, bool);
1275 key!(linker_is_gnu, bool);
1276 key!(allows_weak_linkage, bool);
1277 key!(has_rpath, bool);
1278 key!(no_default_libraries, bool);
1279 key!(position_independent_executables, bool);
1280 key!(needs_plt, bool);
1281 key!(relro_level, RelroLevel)?;
1282 key!(archive_format);
1283 key!(allow_asm, bool);
1284 key!(main_needs_argc_argv, bool);
1285 key!(has_elf_tls, bool);
1286 key!(obj_is_bitcode, bool);
1287 key!(forces_embed_bitcode, bool);
1288 key!(bitcode_llvm_cmdline);
1289 key!(max_atomic_width, Option<u64>);
1290 key!(min_atomic_width, Option<u64>);
1291 key!(atomic_cas, bool);
1292 key!(panic_strategy, PanicStrategy)?;
1293 key!(crt_static_allows_dylibs, bool);
1294 key!(crt_static_default, bool);
1295 key!(crt_static_respected, bool);
1296 key!(stack_probes, bool);
1297 key!(min_global_align, Option<u64>);
1298 key!(default_codegen_units, Option<u64>);
1299 key!(trap_unreachable, bool);
1300 key!(requires_lto, bool);
1301 key!(singlethread, bool);
1302 key!(no_builtins, bool);
1303 key!(codegen_backend);
1304 key!(default_hidden_visibility, bool);
1305 key!(emit_debug_gdb_scripts, bool);
1306 key!(requires_uwtable, bool);
1307 key!(simd_types_indirect, bool);
1308 key!(limit_rdylib_exports, bool);
1309 key!(override_export_symbols, opt_list);
1310 key!(merge_functions, MergeFunctions)?;
1311 key!(target_mcount);
1313 key!(relax_elf_relocations, bool);
1314 key!(llvm_args, list);
1316 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1317 for name in array.iter().filter_map(|abi| abi.as_string()) {
1318 match lookup_abi(name) {
1322 "The ABI \"{}\" is considered to be supported on \
1323 all targets and cannot be blacklisted",
1328 base.options.abi_blacklist.push(abi)
1331 return Err(format!("Unknown ABI \"{}\" in target specification", name));
1340 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1341 /// triple. Note that it could also just be a bare filename already, so also
1342 /// check for that. If one of the hardcoded targets we know about, just
1343 /// return it directly.
1345 /// The error string could come from any of the APIs called, including
1346 /// filesystem access and JSON decoding.
1347 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1348 use rustc_serialize::json;
1352 fn load_file(path: &Path) -> Result<Target, String> {
1353 let contents = fs::read(path).map_err(|e| e.to_string())?;
1354 let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1355 Target::from_json(obj)
1358 match *target_triple {
1359 TargetTriple::TargetTriple(ref target_triple) => {
1360 // check if triple is in list of supported targets
1361 match load_specific(target_triple) {
1362 Ok(t) => return Ok(t),
1363 Err(LoadTargetError::BuiltinTargetNotFound(_)) => (),
1364 Err(LoadTargetError::Other(e)) => return Err(e),
1367 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1369 let mut target = target_triple.to_string();
1370 target.push_str(".json");
1371 PathBuf::from(target)
1374 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1376 // FIXME 16351: add a sane default search path?
1378 for dir in env::split_paths(&target_path) {
1379 let p = dir.join(&path);
1381 return load_file(&p);
1384 Err(format!("Could not find specification for target {:?}", target_triple))
1386 TargetTriple::TargetPath(ref target_path) => {
1387 if target_path.is_file() {
1388 return load_file(&target_path);
1390 Err(format!("Target path {:?} is not a valid file", target_path))
1396 impl ToJson for Target {
1397 fn to_json(&self) -> Json {
1398 let mut d = BTreeMap::new();
1399 let default: TargetOptions = Default::default();
1401 macro_rules! target_val {
1403 let name = (stringify!($attr)).replace("_", "-");
1404 d.insert(name, self.$attr.to_json());
1406 ($attr:ident, $key_name:expr) => {{
1407 let name = $key_name;
1408 d.insert(name.to_string(), self.$attr.to_json());
1412 macro_rules! target_option_val {
1414 let name = (stringify!($attr)).replace("_", "-");
1415 if default.$attr != self.options.$attr {
1416 d.insert(name, self.options.$attr.to_json());
1419 ($attr:ident, $key_name:expr) => {{
1420 let name = $key_name;
1421 if default.$attr != self.options.$attr {
1422 d.insert(name.to_string(), self.options.$attr.to_json());
1425 (link_args - $attr:ident) => {{
1426 let name = (stringify!($attr)).replace("_", "-");
1427 if default.$attr != self.options.$attr {
1432 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1433 .collect::<BTreeMap<_, _>>();
1434 d.insert(name, obj.to_json());
1437 (env - $attr:ident) => {{
1438 let name = (stringify!($attr)).replace("_", "-");
1439 if default.$attr != self.options.$attr {
1444 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1445 .collect::<Vec<_>>();
1446 d.insert(name, obj.to_json());
1451 target_val!(llvm_target);
1452 target_val!(target_endian);
1453 target_val!(target_pointer_width);
1454 target_val!(target_c_int_width);
1456 target_val!(target_os, "os");
1457 target_val!(target_env, "env");
1458 target_val!(target_vendor, "vendor");
1459 target_val!(data_layout);
1460 target_val!(linker_flavor);
1462 target_option_val!(is_builtin);
1463 target_option_val!(linker);
1464 target_option_val!(lld_flavor);
1465 target_option_val!(link_args - pre_link_args);
1466 target_option_val!(link_args - pre_link_args_crt);
1467 target_option_val!(pre_link_objects_exe);
1468 target_option_val!(pre_link_objects_exe_crt);
1469 target_option_val!(pre_link_objects_dll);
1470 target_option_val!(link_args - late_link_args);
1471 target_option_val!(link_args - late_link_args_dynamic);
1472 target_option_val!(link_args - late_link_args_static);
1473 target_option_val!(post_link_objects);
1474 target_option_val!(post_link_objects_crt);
1475 target_option_val!(link_args - post_link_args);
1476 target_option_val!(env - link_env);
1477 target_option_val!(link_env_remove);
1478 target_option_val!(asm_args);
1479 target_option_val!(cpu);
1480 target_option_val!(features);
1481 target_option_val!(dynamic_linking);
1482 target_option_val!(only_cdylib);
1483 target_option_val!(executables);
1484 target_option_val!(relocation_model);
1485 target_option_val!(code_model);
1486 target_option_val!(tls_model);
1487 target_option_val!(disable_redzone);
1488 target_option_val!(eliminate_frame_pointer);
1489 target_option_val!(function_sections);
1490 target_option_val!(dll_prefix);
1491 target_option_val!(dll_suffix);
1492 target_option_val!(exe_suffix);
1493 target_option_val!(staticlib_prefix);
1494 target_option_val!(staticlib_suffix);
1495 target_option_val!(target_family);
1496 target_option_val!(abi_return_struct_as_int);
1497 target_option_val!(is_like_osx);
1498 target_option_val!(is_like_solaris);
1499 target_option_val!(is_like_windows);
1500 target_option_val!(is_like_msvc);
1501 target_option_val!(is_like_emscripten);
1502 target_option_val!(is_like_android);
1503 target_option_val!(is_like_fuchsia);
1504 target_option_val!(linker_is_gnu);
1505 target_option_val!(allows_weak_linkage);
1506 target_option_val!(has_rpath);
1507 target_option_val!(no_default_libraries);
1508 target_option_val!(position_independent_executables);
1509 target_option_val!(needs_plt);
1510 target_option_val!(relro_level);
1511 target_option_val!(archive_format);
1512 target_option_val!(allow_asm);
1513 target_option_val!(main_needs_argc_argv);
1514 target_option_val!(has_elf_tls);
1515 target_option_val!(obj_is_bitcode);
1516 target_option_val!(forces_embed_bitcode);
1517 target_option_val!(bitcode_llvm_cmdline);
1518 target_option_val!(min_atomic_width);
1519 target_option_val!(max_atomic_width);
1520 target_option_val!(atomic_cas);
1521 target_option_val!(panic_strategy);
1522 target_option_val!(crt_static_allows_dylibs);
1523 target_option_val!(crt_static_default);
1524 target_option_val!(crt_static_respected);
1525 target_option_val!(stack_probes);
1526 target_option_val!(min_global_align);
1527 target_option_val!(default_codegen_units);
1528 target_option_val!(trap_unreachable);
1529 target_option_val!(requires_lto);
1530 target_option_val!(singlethread);
1531 target_option_val!(no_builtins);
1532 target_option_val!(codegen_backend);
1533 target_option_val!(default_hidden_visibility);
1534 target_option_val!(emit_debug_gdb_scripts);
1535 target_option_val!(requires_uwtable);
1536 target_option_val!(simd_types_indirect);
1537 target_option_val!(limit_rdylib_exports);
1538 target_option_val!(override_export_symbols);
1539 target_option_val!(merge_functions);
1540 target_option_val!(target_mcount);
1541 target_option_val!(llvm_abiname);
1542 target_option_val!(relax_elf_relocations);
1543 target_option_val!(llvm_args);
1545 if default.abi_blacklist != self.options.abi_blacklist {
1547 "abi-blacklist".to_string(),
1551 .map(|&name| Abi::name(name).to_json())
1552 .collect::<Vec<_>>()
1561 /// Either a target triple string or a path to a JSON file.
1562 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1563 pub enum TargetTriple {
1564 TargetTriple(String),
1565 TargetPath(PathBuf),
1569 /// Creates a target triple from the passed target triple string.
1570 pub fn from_triple(triple: &str) -> Self {
1571 TargetTriple::TargetTriple(triple.to_string())
1574 /// Creates a target triple from the passed target path.
1575 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1576 let canonicalized_path = path.canonicalize()?;
1577 Ok(TargetTriple::TargetPath(canonicalized_path))
1580 /// Returns a string triple for this target.
1582 /// If this target is a path, the file name (without extension) is returned.
1583 pub fn triple(&self) -> &str {
1585 TargetTriple::TargetTriple(ref triple) => triple,
1586 TargetTriple::TargetPath(ref path) => path
1588 .expect("target path must not be empty")
1590 .expect("target path must be valid unicode"),
1594 /// Returns an extended string triple for this target.
1596 /// If this target is a path, a hash of the path is appended to the triple returned
1598 pub fn debug_triple(&self) -> String {
1599 use std::collections::hash_map::DefaultHasher;
1600 use std::hash::{Hash, Hasher};
1602 let triple = self.triple();
1603 if let TargetTriple::TargetPath(ref path) = *self {
1604 let mut hasher = DefaultHasher::new();
1605 path.hash(&mut hasher);
1606 let hash = hasher.finish();
1607 format!("{}-{}", triple, hash)
1614 impl fmt::Display for TargetTriple {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 write!(f, "{}", self.debug_triple())