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 serialize::json::{Json, ToJson};
38 use std::collections::BTreeMap;
39 use std::default::Default;
41 use std::path::{Path, PathBuf};
42 use std::str::FromStr;
43 use crate::spec::abi::{Abi, lookup as lookup_abi};
62 mod windows_msvc_base;
71 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
72 RustcEncodable, RustcDecodable)]
73 pub enum LinkerFlavor {
82 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
83 RustcEncodable, RustcDecodable)]
92 fn from_str(s: &str) -> Option<Self> {
94 "darwin" => LldFlavor::Ld64,
95 "gnu" => LldFlavor::Ld,
96 "link" => LldFlavor::Link,
97 "wasm" => LldFlavor::Wasm,
103 impl ToJson for LldFlavor {
104 fn to_json(&self) -> Json {
106 LldFlavor::Ld64 => "darwin",
107 LldFlavor::Ld => "gnu",
108 LldFlavor::Link => "link",
109 LldFlavor::Wasm => "wasm",
114 impl ToJson for LinkerFlavor {
115 fn to_json(&self) -> Json {
116 self.desc().to_json()
119 macro_rules! flavor_mappings {
120 ($((($($flavor:tt)*), $string:expr),)*) => (
122 pub const fn one_of() -> &'static str {
123 concat!("one of: ", $($string, " ",)*)
126 pub fn from_str(s: &str) -> Option<Self> {
128 $($string => $($flavor)*,)*
133 pub fn desc(&self) -> &str {
135 $($($flavor)* => $string,)*
144 ((LinkerFlavor::Em), "em"),
145 ((LinkerFlavor::Gcc), "gcc"),
146 ((LinkerFlavor::Ld), "ld"),
147 ((LinkerFlavor::Msvc), "msvc"),
148 ((LinkerFlavor::PtxLinker), "ptx-linker"),
149 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
150 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
151 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
152 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
155 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
156 pub enum PanicStrategy {
162 pub fn desc(&self) -> &str {
164 PanicStrategy::Unwind => "unwind",
165 PanicStrategy::Abort => "abort",
170 impl ToJson for PanicStrategy {
171 fn to_json(&self) -> Json {
173 PanicStrategy::Abort => "abort".to_json(),
174 PanicStrategy::Unwind => "unwind".to_json(),
179 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
180 pub enum RelroLevel {
188 pub fn desc(&self) -> &str {
190 RelroLevel::Full => "full",
191 RelroLevel::Partial => "partial",
192 RelroLevel::Off => "off",
193 RelroLevel::None => "none",
198 impl FromStr for RelroLevel {
201 fn from_str(s: &str) -> Result<RelroLevel, ()> {
203 "full" => Ok(RelroLevel::Full),
204 "partial" => Ok(RelroLevel::Partial),
205 "off" => Ok(RelroLevel::Off),
206 "none" => Ok(RelroLevel::None),
212 impl ToJson for RelroLevel {
213 fn to_json(&self) -> Json {
215 RelroLevel::Full => "full".to_json(),
216 RelroLevel::Partial => "partial".to_json(),
217 RelroLevel::Off => "off".to_json(),
218 RelroLevel::None => "None".to_json(),
223 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
224 pub enum MergeFunctions {
230 impl MergeFunctions {
231 pub fn desc(&self) -> &str {
233 MergeFunctions::Disabled => "disabled",
234 MergeFunctions::Trampolines => "trampolines",
235 MergeFunctions::Aliases => "aliases",
240 impl FromStr for MergeFunctions {
243 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
245 "disabled" => Ok(MergeFunctions::Disabled),
246 "trampolines" => Ok(MergeFunctions::Trampolines),
247 "aliases" => Ok(MergeFunctions::Aliases),
253 impl ToJson for MergeFunctions {
254 fn to_json(&self) -> Json {
256 MergeFunctions::Disabled => "disabled".to_json(),
257 MergeFunctions::Trampolines => "trampolines".to_json(),
258 MergeFunctions::Aliases => "aliases".to_json(),
263 pub enum LoadTargetError {
264 BuiltinTargetNotFound(String),
268 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
269 pub type TargetResult = Result<Target, String>;
271 macro_rules! supported_targets {
272 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
275 /// List of supported targets
276 const TARGETS: &[&str] = &[$($($triple),+),+];
278 fn load_specific(target: &str) -> Result<Target, LoadTargetError> {
282 let mut t = $module::target()
283 .map_err(LoadTargetError::Other)?;
284 t.options.is_builtin = true;
286 // round-trip through the JSON parser to ensure at
287 // run-time that the parser works correctly
288 t = Target::from_json(t.to_json())
289 .map_err(LoadTargetError::Other)?;
290 debug!("Got builtin target: {:?}", t);
294 _ => Err(LoadTargetError::BuiltinTargetNotFound(
295 format!("Unable to find target: {}", target)))
299 pub fn get_targets() -> impl Iterator<Item = String> {
300 TARGETS.iter().filter_map(|t| -> Option<String> {
302 .and(Ok(t.to_string()))
308 mod test_json_encode_decode {
309 use serialize::json::ToJson;
311 $(use super::$module;)+
316 // Grab the TargetResult struct. If we successfully retrieved
317 // a Target, then the test JSON encoding/decoding can run for this
318 // Target on this testing platform (i.e., checking the iOS targets
319 // only on a Mac test platform).
320 let _ = $module::target().map(|original| {
321 let as_json = original.to_json();
322 let parsed = Target::from_json(as_json).unwrap();
323 assert_eq!(original, parsed);
332 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
333 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
334 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
335 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
336 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
337 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
338 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
339 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
340 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
341 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
342 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
343 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
344 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
345 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
346 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
347 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
348 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
349 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
350 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
351 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
352 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
353 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
354 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
355 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
356 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
357 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
358 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
359 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
360 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
361 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
362 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
363 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
364 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
365 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
366 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
367 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
368 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
369 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
370 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
372 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
373 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
375 ("i686-linux-android", i686_linux_android),
376 ("x86_64-linux-android", x86_64_linux_android),
377 ("arm-linux-androideabi", arm_linux_androideabi),
378 ("armv7-linux-androideabi", armv7_linux_androideabi),
379 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
380 ("aarch64-linux-android", aarch64_linux_android),
382 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
383 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
384 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
385 ("i686-unknown-freebsd", i686_unknown_freebsd),
386 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
387 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
389 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
390 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
392 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
393 ("i686-unknown-openbsd", i686_unknown_openbsd),
394 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
396 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
397 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
398 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
399 ("i686-unknown-netbsd", i686_unknown_netbsd),
400 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
401 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
402 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
403 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
405 ("i686-unknown-haiku", i686_unknown_haiku),
406 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
408 ("x86_64-apple-darwin", x86_64_apple_darwin),
409 ("i686-apple-darwin", i686_apple_darwin),
411 ("aarch64-fuchsia", aarch64_fuchsia),
412 ("x86_64-fuchsia", x86_64_fuchsia),
414 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
416 ("x86_64-unknown-redox", x86_64_unknown_redox),
418 ("i386-apple-ios", i386_apple_ios),
419 ("x86_64-apple-ios", x86_64_apple_ios),
420 ("aarch64-apple-ios", aarch64_apple_ios),
421 ("armv7-apple-ios", armv7_apple_ios),
422 ("armv7s-apple-ios", armv7s_apple_ios),
424 ("armebv7r-none-eabi", armebv7r_none_eabi),
425 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
426 ("armv7r-none-eabi", armv7r_none_eabi),
427 ("armv7r-none-eabihf", armv7r_none_eabihf),
429 // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
430 // (See <https://github.com/rust-lang/rust/issues/40531>.)
431 ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris),
432 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
434 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
435 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
437 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
438 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
439 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
440 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
441 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
443 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
444 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
445 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
446 ("wasm32-wasi", wasm32_wasi),
447 ("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
449 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
450 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
451 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
452 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
453 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
454 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
455 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
457 ("msp430-none-elf", msp430_none_elf),
459 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
460 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
461 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
462 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
464 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
465 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
467 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
468 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
469 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
470 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
472 ("aarch64-unknown-none", aarch64_unknown_none),
474 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
476 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
478 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
480 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
481 ("i686-wrs-vxworks", i686_wrs_vxworks),
482 ("i586-wrs-vxworks", i586_wrs_vxworks),
483 ("armv7-wrs-vxworks", armv7_wrs_vxworks),
484 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
485 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
486 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
487 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
490 /// Everything `rustc` knows about how to compile for a specific target.
492 /// Every field here must be specified, and has no default value.
493 #[derive(PartialEq, Clone, Debug)]
495 /// Target triple to pass to LLVM.
496 pub llvm_target: String,
497 /// String to use as the `target_endian` `cfg` variable.
498 pub target_endian: String,
499 /// String to use as the `target_pointer_width` `cfg` variable.
500 pub target_pointer_width: String,
501 /// Width of c_int type
502 pub target_c_int_width: String,
503 /// OS name to use for conditional compilation.
504 pub target_os: String,
505 /// Environment name to use for conditional compilation.
506 pub target_env: String,
507 /// Vendor name to use for conditional compilation.
508 pub target_vendor: String,
509 /// Architecture to use for ABI considerations. Valid options include: "x86",
510 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
512 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
513 pub data_layout: String,
515 pub linker_flavor: LinkerFlavor,
516 /// Optional settings with defaults.
517 pub options: TargetOptions,
520 pub trait HasTargetSpec {
521 fn target_spec(&self) -> &Target;
524 impl HasTargetSpec for Target {
525 fn target_spec(&self) -> &Target {
530 /// Optional aspects of a target specification.
532 /// This has an implementation of `Default`, see each field for what the default is. In general,
533 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
534 #[derive(PartialEq, Clone, Debug)]
535 pub struct TargetOptions {
536 /// Whether the target is built-in or loaded from a custom target specification.
537 pub is_builtin: bool,
540 pub linker: Option<String>,
543 pub lld_flavor: LldFlavor,
545 /// Linker arguments that are passed *before* any user-defined libraries.
546 pub pre_link_args: LinkArgs, // ... unconditionally
547 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
548 /// Objects to link before all others, always found within the
550 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
551 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
552 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
553 /// Linker arguments that are unconditionally passed after any
554 /// user-defined but before post_link_objects. Standard platform
555 /// libraries that should be always be linked to, usually go here.
556 pub late_link_args: LinkArgs,
557 /// Objects to link after all others, always found within the
559 pub post_link_objects: Vec<String>, // ... unconditionally
560 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
561 /// Linker arguments that are unconditionally passed *after* any
562 /// user-defined libraries.
563 pub post_link_args: LinkArgs,
565 /// Environment variables to be set before invoking the linker.
566 pub link_env: Vec<(String, String)>,
568 /// Extra arguments to pass to the external assembler (when used)
569 pub asm_args: Vec<String>,
571 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
574 /// Default target features to pass to LLVM. These features will *always* be
575 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
576 /// -mattr=$features`.
577 pub features: String,
578 /// Whether dynamic linking is available on this target. Defaults to false.
579 pub dynamic_linking: bool,
580 /// If dynamic linking is available, whether only cdylibs are supported.
581 pub only_cdylib: bool,
582 /// Whether executables are available on this target. iOS, for example, only allows static
583 /// libraries. Defaults to false.
584 pub executables: bool,
585 /// Relocation model to use in object file. Corresponds to `llc
586 /// -relocation-model=$relocation_model`. Defaults to "pic".
587 pub relocation_model: String,
588 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
589 pub code_model: Option<String>,
590 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
591 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
592 pub tls_model: String,
593 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
594 pub disable_redzone: bool,
595 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
596 pub eliminate_frame_pointer: bool,
597 /// Emit each function in its own section. Defaults to true.
598 pub function_sections: bool,
599 /// String to prepend to the name of every dynamic library. Defaults to "lib".
600 pub dll_prefix: String,
601 /// String to append to the name of every dynamic library. Defaults to ".so".
602 pub dll_suffix: String,
603 /// String to append to the name of every executable.
604 pub exe_suffix: String,
605 /// String to prepend to the name of every static library. Defaults to "lib".
606 pub staticlib_prefix: String,
607 /// String to append to the name of every static library. Defaults to ".a".
608 pub staticlib_suffix: String,
609 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
610 pub target_family: Option<String>,
611 /// Whether the target toolchain's ABI supports returning small structs as an integer.
612 pub abi_return_struct_as_int: bool,
613 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
614 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
615 pub is_like_osx: bool,
616 /// Whether the target toolchain is like Solaris's.
617 /// Only useful for compiling against Illumos/Solaris,
618 /// as they have a different set of linker flags. Defaults to false.
619 pub is_like_solaris: bool,
620 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
621 /// only really used for figuring out how to find libraries, since Windows uses its own
622 /// library naming convention. Defaults to false.
623 pub is_like_windows: bool,
624 pub is_like_msvc: bool,
625 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
626 /// Defaults to false.
627 pub is_like_android: bool,
628 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
629 /// Emscripten toolchain.
630 /// Defaults to false.
631 pub is_like_emscripten: bool,
632 /// Whether the target toolchain is like Fuchsia's.
633 pub is_like_fuchsia: bool,
634 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
635 pub linker_is_gnu: bool,
636 /// The MinGW toolchain has a known issue that prevents it from correctly
637 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
638 /// symbol needs its own COMDAT section, weak linkage implies a large
639 /// number sections that easily exceeds the given limit for larger
640 /// codebases. Consequently we want a way to disallow weak linkage on some
642 pub allows_weak_linkage: bool,
643 /// Whether the linker support rpaths or not. Defaults to false.
645 /// Whether to disable linking to the default libraries, typically corresponds
646 /// to `-nodefaultlibs`. Defaults to true.
647 pub no_default_libraries: bool,
648 /// Dynamically linked executables can be compiled as position independent
649 /// if the default relocation model of position independent code is not
650 /// changed. This is a requirement to take advantage of ASLR, as otherwise
651 /// the functions in the executable are not randomized and can be used
652 /// during an exploit of a vulnerability in any code.
653 pub position_independent_executables: bool,
654 /// Determines if the target always requires using the PLT for indirect
655 /// library calls or not. This controls the default value of the `-Z plt` flag.
657 /// Either partial, full, or off. Full RELRO makes the dynamic linker
658 /// resolve all symbols at startup and marks the GOT read-only before
659 /// starting the program, preventing overwriting the GOT.
660 pub relro_level: RelroLevel,
661 /// Format that archives should be emitted in. This affects whether we use
662 /// LLVM to assemble an archive or fall back to the system linker, and
663 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
664 /// the system linker to be used.
665 pub archive_format: String,
666 /// Is asm!() allowed? Defaults to true.
668 /// Whether the target uses a custom unwind resumption routine.
669 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
670 /// defined in libgcc. If this option is enabled, the target must provide
671 /// `eh_unwind_resume` lang item.
672 pub custom_unwind_resume: bool,
674 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
676 pub has_elf_tls: bool,
677 // This is mainly for easy compatibility with emscripten.
678 // If we give emcc .o files that are actually .bc files it
680 pub obj_is_bitcode: bool,
682 // LLVM can't produce object files for this target. Instead, we'll make LLVM
683 // emit assembly and then use `gcc` to turn that assembly into an object
685 pub no_integrated_as: bool,
687 /// Don't use this field; instead use the `.min_atomic_width()` method.
688 pub min_atomic_width: Option<u64>,
690 /// Don't use this field; instead use the `.max_atomic_width()` method.
691 pub max_atomic_width: Option<u64>,
693 /// Whether the target supports atomic CAS operations natively
694 pub atomic_cas: bool,
696 /// Panic strategy: "unwind" or "abort"
697 pub panic_strategy: PanicStrategy,
699 /// A blacklist of ABIs unsupported by the current target. Note that generic
700 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
701 pub abi_blacklist: Vec<Abi>,
703 /// Whether or not linking dylibs to a static CRT is allowed.
704 pub crt_static_allows_dylibs: bool,
705 /// Whether or not the CRT is statically linked by default.
706 pub crt_static_default: bool,
707 /// Whether or not crt-static is respected by the compiler (or is a no-op).
708 pub crt_static_respected: bool,
710 /// Whether or not stack probes (__rust_probestack) are enabled
711 pub stack_probes: bool,
713 /// The minimum alignment for global symbols.
714 pub min_global_align: Option<u64>,
716 /// Default number of codegen units to use in debug mode
717 pub default_codegen_units: Option<u64>,
719 /// Whether to generate trap instructions in places where optimization would
720 /// otherwise produce control flow that falls through into unrelated memory.
721 pub trap_unreachable: bool,
723 /// This target requires everything to be compiled with LTO to emit a final
724 /// executable, aka there is no native linker for this target.
725 pub requires_lto: bool,
727 /// This target has no support for threads.
728 pub singlethread: bool,
730 /// Whether library functions call lowering/optimization is disabled in LLVM
731 /// for this target unconditionally.
732 pub no_builtins: bool,
734 /// Whether to lower 128-bit operations to compiler_builtins calls. Use if
735 /// your backend only supports 64-bit and smaller math.
736 pub i128_lowering: bool,
738 /// The codegen backend to use for this target, typically "llvm"
739 pub codegen_backend: String,
741 /// The default visibility for symbols in this target should be "hidden"
742 /// rather than "default"
743 pub default_hidden_visibility: bool,
745 /// Whether or not bitcode is embedded in object files
746 pub embed_bitcode: bool,
748 /// Whether a .debug_gdb_scripts section will be added to the output object file
749 pub emit_debug_gdb_scripts: bool,
751 /// Whether or not to unconditionally `uwtable` attributes on functions,
752 /// typically because the platform needs to unwind for things like stack
754 pub requires_uwtable: bool,
756 /// Whether or not SIMD types are passed by reference in the Rust ABI,
757 /// typically required if a target can be compiled with a mixed set of
758 /// target features. This is `true` by default, and `false` for targets like
759 /// wasm32 where the whole program either has simd or not.
760 pub simd_types_indirect: bool,
762 /// Pass a list of symbol which should be exported in the dylib to the linker.
763 pub limit_rdylib_exports: bool,
765 /// If set, have the linker export exactly these symbols, instead of using
766 /// the usual logic to figure this out from the crate itself.
767 pub override_export_symbols: Option<Vec<String>>,
769 /// Determines how or whether the MergeFunctions LLVM pass should run for
770 /// this target. Either "disabled", "trampolines", or "aliases".
771 /// The MergeFunctions pass is generally useful, but some targets may need
772 /// to opt out. The default is "aliases".
774 /// Workaround for: https://github.com/rust-lang/rust/issues/57356
775 pub merge_functions: MergeFunctions,
777 /// Use platform dependent mcount function
778 pub target_mcount: String
781 impl Default for TargetOptions {
782 /// Creates a set of "sane defaults" for any target. This is still
783 /// incomplete, and if used for compilation, will certainly not work.
784 fn default() -> TargetOptions {
787 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
788 lld_flavor: LldFlavor::Ld,
789 pre_link_args: LinkArgs::new(),
790 pre_link_args_crt: LinkArgs::new(),
791 post_link_args: LinkArgs::new(),
792 asm_args: Vec::new(),
793 cpu: "generic".to_string(),
794 features: String::new(),
795 dynamic_linking: false,
798 relocation_model: "pic".to_string(),
800 tls_model: "global-dynamic".to_string(),
801 disable_redzone: false,
802 eliminate_frame_pointer: true,
803 function_sections: true,
804 dll_prefix: "lib".to_string(),
805 dll_suffix: ".so".to_string(),
806 exe_suffix: String::new(),
807 staticlib_prefix: "lib".to_string(),
808 staticlib_suffix: ".a".to_string(),
810 abi_return_struct_as_int: false,
812 is_like_solaris: false,
813 is_like_windows: false,
814 is_like_android: false,
815 is_like_emscripten: false,
817 is_like_fuchsia: false,
818 linker_is_gnu: false,
819 allows_weak_linkage: true,
821 no_default_libraries: true,
822 position_independent_executables: false,
824 relro_level: RelroLevel::None,
825 pre_link_objects_exe: Vec::new(),
826 pre_link_objects_exe_crt: Vec::new(),
827 pre_link_objects_dll: Vec::new(),
828 post_link_objects: Vec::new(),
829 post_link_objects_crt: Vec::new(),
830 late_link_args: LinkArgs::new(),
831 link_env: Vec::new(),
832 archive_format: "gnu".to_string(),
833 custom_unwind_resume: false,
836 obj_is_bitcode: false,
837 no_integrated_as: false,
838 min_atomic_width: None,
839 max_atomic_width: None,
841 panic_strategy: PanicStrategy::Unwind,
842 abi_blacklist: vec![],
843 crt_static_allows_dylibs: false,
844 crt_static_default: false,
845 crt_static_respected: false,
847 min_global_align: None,
848 default_codegen_units: None,
849 trap_unreachable: true,
853 i128_lowering: false,
854 codegen_backend: "llvm".to_string(),
855 default_hidden_visibility: false,
856 embed_bitcode: false,
857 emit_debug_gdb_scripts: true,
858 requires_uwtable: false,
859 simd_types_indirect: true,
860 limit_rdylib_exports: true,
861 override_export_symbols: None,
862 merge_functions: MergeFunctions::Aliases,
863 target_mcount: "mcount".to_string(),
869 /// Given a function ABI, turn it into the correct ABI for this target.
870 pub fn adjust_abi(&self, abi: Abi) -> Abi {
873 if self.options.is_like_windows && self.arch == "x86" {
879 // These ABI kinds are ignored on non-x86 Windows targets.
880 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
881 // and the individual pages for __stdcall et al.
882 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
883 if self.options.is_like_windows && self.arch != "x86" {
893 /// Minimum integer size in bits that this target can perform atomic
895 pub fn min_atomic_width(&self) -> u64 {
896 self.options.min_atomic_width.unwrap_or(8)
899 /// Maximum integer size in bits that this target can perform atomic
901 pub fn max_atomic_width(&self) -> u64 {
902 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
905 pub fn is_abi_supported(&self, abi: Abi) -> bool {
906 abi.generic() || !self.options.abi_blacklist.contains(&abi)
909 /// Loads a target descriptor from a JSON object.
910 pub fn from_json(obj: Json) -> TargetResult {
911 // While ugly, this code must remain this way to retain
912 // compatibility with existing JSON fields and the internal
913 // expected naming of the Target and TargetOptions structs.
914 // To ensure compatibility is retained, the built-in targets
915 // are round-tripped through this code to catch cases where
916 // the JSON parser is not updated to match the structs.
918 let get_req_field = |name: &str| {
920 .map(|s| s.as_string())
921 .and_then(|os| os.map(|s| s.to_string()))
922 .ok_or_else(|| format!("Field {} in target specification is required", name))
925 let get_opt_field = |name: &str, default: &str| {
926 obj.find(name).and_then(|s| s.as_string())
927 .map(|s| s.to_string())
928 .unwrap_or_else(|| default.to_string())
931 let mut base = Target {
932 llvm_target: get_req_field("llvm-target")?,
933 target_endian: get_req_field("target-endian")?,
934 target_pointer_width: get_req_field("target-pointer-width")?,
935 target_c_int_width: get_req_field("target-c-int-width")?,
936 data_layout: get_req_field("data-layout")?,
937 arch: get_req_field("arch")?,
938 target_os: get_req_field("os")?,
939 target_env: get_opt_field("env", ""),
940 target_vendor: get_opt_field("vendor", "unknown"),
941 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
943 format!("linker flavor must be {}", LinkerFlavor::one_of())
945 options: Default::default(),
949 ($key_name:ident) => ( {
950 let name = (stringify!($key_name)).replace("_", "-");
951 obj.find(&name[..]).map(|o| o.as_string()
952 .map(|s| base.options.$key_name = s.to_string()));
954 ($key_name:ident, bool) => ( {
955 let name = (stringify!($key_name)).replace("_", "-");
957 .map(|o| o.as_boolean()
958 .map(|s| base.options.$key_name = s));
960 ($key_name:ident, Option<u64>) => ( {
961 let name = (stringify!($key_name)).replace("_", "-");
964 .map(|s| base.options.$key_name = Some(s)));
966 ($key_name:ident, MergeFunctions) => ( {
967 let name = (stringify!($key_name)).replace("_", "-");
968 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
969 match s.parse::<MergeFunctions>() {
970 Ok(mergefunc) => base.options.$key_name = mergefunc,
971 _ => return Some(Err(format!("'{}' is not a valid value for \
972 merge-functions. Use 'disabled', \
973 'trampolines', or 'aliases'.",
977 })).unwrap_or(Ok(()))
979 ($key_name:ident, PanicStrategy) => ( {
980 let name = (stringify!($key_name)).replace("_", "-");
981 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
983 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
984 "abort" => base.options.$key_name = PanicStrategy::Abort,
985 _ => return Some(Err(format!("'{}' is not a valid value for \
986 panic-strategy. Use 'unwind' or 'abort'.",
990 })).unwrap_or(Ok(()))
992 ($key_name:ident, RelroLevel) => ( {
993 let name = (stringify!($key_name)).replace("_", "-");
994 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
995 match s.parse::<RelroLevel>() {
996 Ok(level) => base.options.$key_name = level,
997 _ => return Some(Err(format!("'{}' is not a valid value for \
998 relro-level. Use 'full', 'partial, or 'off'.",
1002 })).unwrap_or(Ok(()))
1004 ($key_name:ident, list) => ( {
1005 let name = (stringify!($key_name)).replace("_", "-");
1006 obj.find(&name[..]).map(|o| o.as_array()
1007 .map(|v| base.options.$key_name = v.iter()
1008 .map(|a| a.as_string().unwrap().to_string()).collect()
1012 ($key_name:ident, opt_list) => ( {
1013 let name = (stringify!($key_name)).replace("_", "-");
1014 obj.find(&name[..]).map(|o| o.as_array()
1015 .map(|v| base.options.$key_name = Some(v.iter()
1016 .map(|a| a.as_string().unwrap().to_string()).collect())
1020 ($key_name:ident, optional) => ( {
1021 let name = (stringify!($key_name)).replace("_", "-");
1022 if let Some(o) = obj.find(&name[..]) {
1023 base.options.$key_name = o
1025 .map(|s| s.to_string() );
1028 ($key_name:ident, LldFlavor) => ( {
1029 let name = (stringify!($key_name)).replace("_", "-");
1030 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1031 if let Some(flavor) = LldFlavor::from_str(&s) {
1032 base.options.$key_name = flavor;
1034 return Some(Err(format!(
1035 "'{}' is not a valid value for lld-flavor. \
1036 Use 'darwin', 'gnu', 'link' or 'wasm.",
1040 })).unwrap_or(Ok(()))
1042 ($key_name:ident, LinkerFlavor) => ( {
1043 let name = (stringify!($key_name)).replace("_", "-");
1044 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
1045 LinkerFlavor::from_str(&s).ok_or_else(|| {
1046 Err(format!("'{}' is not a valid value for linker-flavor. \
1047 Use 'em', 'gcc', 'ld' or 'msvc.", s))
1049 })).unwrap_or(Ok(()))
1051 ($key_name:ident, link_args) => ( {
1052 let name = (stringify!($key_name)).replace("_", "-");
1053 if let Some(val) = obj.find(&name[..]) {
1054 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1055 JSON object with fields per linker-flavor.", name))?;
1056 let mut args = LinkArgs::new();
1058 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1059 format!("{}: '{}' is not a valid value for linker-flavor. \
1060 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1063 let v = v.as_array().ok_or_else(||
1064 format!("{}.{}: expected a JSON array", name, k)
1065 )?.iter().enumerate()
1067 let s = s.as_string().ok_or_else(||
1068 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1071 .collect::<Result<Vec<_>, String>>()?;
1073 args.insert(flavor, v);
1075 base.options.$key_name = args;
1078 ($key_name:ident, env) => ( {
1079 let name = (stringify!($key_name)).replace("_", "-");
1080 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1082 if let Some(s) = o.as_string() {
1083 let p = s.split('=').collect::<Vec<_>>();
1085 let k = p[0].to_string();
1086 let v = p[1].to_string();
1087 base.options.$key_name.push((k, v));
1095 key!(is_builtin, bool);
1096 key!(linker, optional);
1097 key!(lld_flavor, LldFlavor)?;
1098 key!(pre_link_args, link_args);
1099 key!(pre_link_args_crt, link_args);
1100 key!(pre_link_objects_exe, list);
1101 key!(pre_link_objects_exe_crt, list);
1102 key!(pre_link_objects_dll, list);
1103 key!(late_link_args, link_args);
1104 key!(post_link_objects, list);
1105 key!(post_link_objects_crt, list);
1106 key!(post_link_args, link_args);
1107 key!(link_env, env);
1108 key!(asm_args, list);
1111 key!(dynamic_linking, bool);
1112 key!(only_cdylib, bool);
1113 key!(executables, bool);
1114 key!(relocation_model);
1115 key!(code_model, optional);
1117 key!(disable_redzone, bool);
1118 key!(eliminate_frame_pointer, bool);
1119 key!(function_sections, bool);
1123 key!(staticlib_prefix);
1124 key!(staticlib_suffix);
1125 key!(target_family, optional);
1126 key!(abi_return_struct_as_int, bool);
1127 key!(is_like_osx, bool);
1128 key!(is_like_solaris, bool);
1129 key!(is_like_windows, bool);
1130 key!(is_like_msvc, bool);
1131 key!(is_like_emscripten, bool);
1132 key!(is_like_android, bool);
1133 key!(is_like_fuchsia, bool);
1134 key!(linker_is_gnu, bool);
1135 key!(allows_weak_linkage, bool);
1136 key!(has_rpath, bool);
1137 key!(no_default_libraries, bool);
1138 key!(position_independent_executables, bool);
1139 key!(needs_plt, bool);
1140 key!(relro_level, RelroLevel)?;
1141 key!(archive_format);
1142 key!(allow_asm, bool);
1143 key!(custom_unwind_resume, bool);
1144 key!(has_elf_tls, bool);
1145 key!(obj_is_bitcode, bool);
1146 key!(no_integrated_as, bool);
1147 key!(max_atomic_width, Option<u64>);
1148 key!(min_atomic_width, Option<u64>);
1149 key!(atomic_cas, bool);
1150 key!(panic_strategy, PanicStrategy)?;
1151 key!(crt_static_allows_dylibs, bool);
1152 key!(crt_static_default, bool);
1153 key!(crt_static_respected, bool);
1154 key!(stack_probes, bool);
1155 key!(min_global_align, Option<u64>);
1156 key!(default_codegen_units, Option<u64>);
1157 key!(trap_unreachable, bool);
1158 key!(requires_lto, bool);
1159 key!(singlethread, bool);
1160 key!(no_builtins, bool);
1161 key!(codegen_backend);
1162 key!(default_hidden_visibility, bool);
1163 key!(embed_bitcode, bool);
1164 key!(emit_debug_gdb_scripts, bool);
1165 key!(requires_uwtable, bool);
1166 key!(simd_types_indirect, bool);
1167 key!(limit_rdylib_exports, bool);
1168 key!(override_export_symbols, opt_list);
1169 key!(merge_functions, MergeFunctions)?;
1170 key!(target_mcount);
1172 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1173 for name in array.iter().filter_map(|abi| abi.as_string()) {
1174 match lookup_abi(name) {
1177 return Err(format!("The ABI \"{}\" is considered to be supported on \
1178 all targets and cannot be blacklisted", abi))
1181 base.options.abi_blacklist.push(abi)
1183 None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
1191 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1192 /// triple. Note that it could also just be a bare filename already, so also
1193 /// check for that. If one of the hardcoded targets we know about, just
1194 /// return it directly.
1196 /// The error string could come from any of the APIs called, including
1197 /// filesystem access and JSON decoding.
1198 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1201 use serialize::json;
1203 fn load_file(path: &Path) -> Result<Target, String> {
1204 let contents = fs::read(path).map_err(|e| e.to_string())?;
1205 let obj = json::from_reader(&mut &contents[..])
1206 .map_err(|e| e.to_string())?;
1207 Target::from_json(obj)
1210 match *target_triple {
1211 TargetTriple::TargetTriple(ref target_triple) => {
1212 // check if triple is in list of supported targets
1213 match load_specific(target_triple) {
1214 Ok(t) => return Ok(t),
1215 Err(LoadTargetError::BuiltinTargetNotFound(_)) => (),
1216 Err(LoadTargetError::Other(e)) => return Err(e),
1219 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1221 let mut target = target_triple.to_string();
1222 target.push_str(".json");
1223 PathBuf::from(target)
1226 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1228 // FIXME 16351: add a sane default search path?
1230 for dir in env::split_paths(&target_path) {
1231 let p = dir.join(&path);
1233 return load_file(&p);
1236 Err(format!("Could not find specification for target {:?}", target_triple))
1238 TargetTriple::TargetPath(ref target_path) => {
1239 if target_path.is_file() {
1240 return load_file(&target_path);
1242 Err(format!("Target path {:?} is not a valid file", target_path))
1248 impl ToJson for Target {
1249 fn to_json(&self) -> Json {
1250 let mut d = BTreeMap::new();
1251 let default: TargetOptions = Default::default();
1253 macro_rules! target_val {
1254 ($attr:ident) => ( {
1255 let name = (stringify!($attr)).replace("_", "-");
1256 d.insert(name, self.$attr.to_json());
1258 ($attr:ident, $key_name:expr) => ( {
1259 let name = $key_name;
1260 d.insert(name.to_string(), self.$attr.to_json());
1264 macro_rules! target_option_val {
1265 ($attr:ident) => ( {
1266 let name = (stringify!($attr)).replace("_", "-");
1267 if default.$attr != self.options.$attr {
1268 d.insert(name, self.options.$attr.to_json());
1271 ($attr:ident, $key_name:expr) => ( {
1272 let name = $key_name;
1273 if default.$attr != self.options.$attr {
1274 d.insert(name.to_string(), self.options.$attr.to_json());
1277 (link_args - $attr:ident) => ( {
1278 let name = (stringify!($attr)).replace("_", "-");
1279 if default.$attr != self.options.$attr {
1280 let obj = self.options.$attr
1282 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1283 .collect::<BTreeMap<_, _>>();
1284 d.insert(name, obj.to_json());
1287 (env - $attr:ident) => ( {
1288 let name = (stringify!($attr)).replace("_", "-");
1289 if default.$attr != self.options.$attr {
1290 let obj = self.options.$attr
1292 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1293 .collect::<Vec<_>>();
1294 d.insert(name, obj.to_json());
1300 target_val!(llvm_target);
1301 target_val!(target_endian);
1302 target_val!(target_pointer_width);
1303 target_val!(target_c_int_width);
1305 target_val!(target_os, "os");
1306 target_val!(target_env, "env");
1307 target_val!(target_vendor, "vendor");
1308 target_val!(data_layout);
1309 target_val!(linker_flavor);
1311 target_option_val!(is_builtin);
1312 target_option_val!(linker);
1313 target_option_val!(lld_flavor);
1314 target_option_val!(link_args - pre_link_args);
1315 target_option_val!(link_args - pre_link_args_crt);
1316 target_option_val!(pre_link_objects_exe);
1317 target_option_val!(pre_link_objects_exe_crt);
1318 target_option_val!(pre_link_objects_dll);
1319 target_option_val!(link_args - late_link_args);
1320 target_option_val!(post_link_objects);
1321 target_option_val!(post_link_objects_crt);
1322 target_option_val!(link_args - post_link_args);
1323 target_option_val!(env - link_env);
1324 target_option_val!(asm_args);
1325 target_option_val!(cpu);
1326 target_option_val!(features);
1327 target_option_val!(dynamic_linking);
1328 target_option_val!(only_cdylib);
1329 target_option_val!(executables);
1330 target_option_val!(relocation_model);
1331 target_option_val!(code_model);
1332 target_option_val!(tls_model);
1333 target_option_val!(disable_redzone);
1334 target_option_val!(eliminate_frame_pointer);
1335 target_option_val!(function_sections);
1336 target_option_val!(dll_prefix);
1337 target_option_val!(dll_suffix);
1338 target_option_val!(exe_suffix);
1339 target_option_val!(staticlib_prefix);
1340 target_option_val!(staticlib_suffix);
1341 target_option_val!(target_family);
1342 target_option_val!(abi_return_struct_as_int);
1343 target_option_val!(is_like_osx);
1344 target_option_val!(is_like_solaris);
1345 target_option_val!(is_like_windows);
1346 target_option_val!(is_like_msvc);
1347 target_option_val!(is_like_emscripten);
1348 target_option_val!(is_like_android);
1349 target_option_val!(is_like_fuchsia);
1350 target_option_val!(linker_is_gnu);
1351 target_option_val!(allows_weak_linkage);
1352 target_option_val!(has_rpath);
1353 target_option_val!(no_default_libraries);
1354 target_option_val!(position_independent_executables);
1355 target_option_val!(needs_plt);
1356 target_option_val!(relro_level);
1357 target_option_val!(archive_format);
1358 target_option_val!(allow_asm);
1359 target_option_val!(custom_unwind_resume);
1360 target_option_val!(has_elf_tls);
1361 target_option_val!(obj_is_bitcode);
1362 target_option_val!(no_integrated_as);
1363 target_option_val!(min_atomic_width);
1364 target_option_val!(max_atomic_width);
1365 target_option_val!(atomic_cas);
1366 target_option_val!(panic_strategy);
1367 target_option_val!(crt_static_allows_dylibs);
1368 target_option_val!(crt_static_default);
1369 target_option_val!(crt_static_respected);
1370 target_option_val!(stack_probes);
1371 target_option_val!(min_global_align);
1372 target_option_val!(default_codegen_units);
1373 target_option_val!(trap_unreachable);
1374 target_option_val!(requires_lto);
1375 target_option_val!(singlethread);
1376 target_option_val!(no_builtins);
1377 target_option_val!(codegen_backend);
1378 target_option_val!(default_hidden_visibility);
1379 target_option_val!(embed_bitcode);
1380 target_option_val!(emit_debug_gdb_scripts);
1381 target_option_val!(requires_uwtable);
1382 target_option_val!(simd_types_indirect);
1383 target_option_val!(limit_rdylib_exports);
1384 target_option_val!(override_export_symbols);
1385 target_option_val!(merge_functions);
1386 target_option_val!(target_mcount);
1388 if default.abi_blacklist != self.options.abi_blacklist {
1389 d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1390 .map(|&name| Abi::name(name).to_json())
1391 .collect::<Vec<_>>().to_json());
1398 /// Either a target triple string or a path to a JSON file.
1399 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1400 pub enum TargetTriple {
1401 TargetTriple(String),
1402 TargetPath(PathBuf),
1406 /// Creates a target triple from the passed target triple string.
1407 pub fn from_triple(triple: &str) -> Self {
1408 TargetTriple::TargetTriple(triple.to_string())
1411 /// Creates a target triple from the passed target path.
1412 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1413 let canonicalized_path = path.canonicalize()?;
1414 Ok(TargetTriple::TargetPath(canonicalized_path))
1417 /// Returns a string triple for this target.
1419 /// If this target is a path, the file name (without extension) is returned.
1420 pub fn triple(&self) -> &str {
1422 TargetTriple::TargetTriple(ref triple) => triple,
1423 TargetTriple::TargetPath(ref path) => {
1424 path.file_stem().expect("target path must not be empty").to_str()
1425 .expect("target path must be valid unicode")
1430 /// Returns an extended string triple for this target.
1432 /// If this target is a path, a hash of the path is appended to the triple returned
1434 pub fn debug_triple(&self) -> String {
1435 use std::hash::{Hash, Hasher};
1436 use std::collections::hash_map::DefaultHasher;
1438 let triple = self.triple();
1439 if let TargetTriple::TargetPath(ref path) = *self {
1440 let mut hasher = DefaultHasher::new();
1441 path.hash(&mut hasher);
1442 let hash = hasher.finish();
1443 format!("{}-{}", triple, hash)
1450 impl fmt::Display for TargetTriple {
1451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1452 write!(f, "{}", self.debug_triple())