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};
63 mod windows_msvc_base;
70 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
71 RustcEncodable, RustcDecodable)]
72 pub enum LinkerFlavor {
81 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
82 RustcEncodable, RustcDecodable)]
91 fn from_str(s: &str) -> Option<Self> {
93 "darwin" => LldFlavor::Ld64,
94 "gnu" => LldFlavor::Ld,
95 "link" => LldFlavor::Link,
96 "wasm" => LldFlavor::Wasm,
102 impl ToJson for LldFlavor {
103 fn to_json(&self) -> Json {
105 LldFlavor::Ld64 => "darwin",
106 LldFlavor::Ld => "gnu",
107 LldFlavor::Link => "link",
108 LldFlavor::Wasm => "wasm",
113 impl ToJson for LinkerFlavor {
114 fn to_json(&self) -> Json {
115 self.desc().to_json()
118 macro_rules! flavor_mappings {
119 ($((($($flavor:tt)*), $string:expr),)*) => (
121 pub const fn one_of() -> &'static str {
122 concat!("one of: ", $($string, " ",)+)
125 pub fn from_str(s: &str) -> Option<Self> {
127 $($string => $($flavor)*,)+
132 pub fn desc(&self) -> &str {
134 $($($flavor)* => $string,)+
143 ((LinkerFlavor::Em), "em"),
144 ((LinkerFlavor::Gcc), "gcc"),
145 ((LinkerFlavor::Ld), "ld"),
146 ((LinkerFlavor::Msvc), "msvc"),
147 ((LinkerFlavor::PtxLinker), "ptx-linker"),
148 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
149 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
150 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
151 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
154 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
155 pub enum PanicStrategy {
161 pub fn desc(&self) -> &str {
163 PanicStrategy::Unwind => "unwind",
164 PanicStrategy::Abort => "abort",
169 impl ToJson for PanicStrategy {
170 fn to_json(&self) -> Json {
172 PanicStrategy::Abort => "abort".to_json(),
173 PanicStrategy::Unwind => "unwind".to_json(),
178 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
179 pub enum RelroLevel {
187 pub fn desc(&self) -> &str {
189 RelroLevel::Full => "full",
190 RelroLevel::Partial => "partial",
191 RelroLevel::Off => "off",
192 RelroLevel::None => "none",
197 impl FromStr for RelroLevel {
200 fn from_str(s: &str) -> Result<RelroLevel, ()> {
202 "full" => Ok(RelroLevel::Full),
203 "partial" => Ok(RelroLevel::Partial),
204 "off" => Ok(RelroLevel::Off),
205 "none" => Ok(RelroLevel::None),
211 impl ToJson for RelroLevel {
212 fn to_json(&self) -> Json {
214 RelroLevel::Full => "full".to_json(),
215 RelroLevel::Partial => "partial".to_json(),
216 RelroLevel::Off => "off".to_json(),
217 RelroLevel::None => "None".to_json(),
222 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
223 pub enum MergeFunctions {
229 impl MergeFunctions {
230 pub fn desc(&self) -> &str {
232 MergeFunctions::Disabled => "disabled",
233 MergeFunctions::Trampolines => "trampolines",
234 MergeFunctions::Aliases => "aliases",
239 impl FromStr for MergeFunctions {
242 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
244 "disabled" => Ok(MergeFunctions::Disabled),
245 "trampolines" => Ok(MergeFunctions::Trampolines),
246 "aliases" => Ok(MergeFunctions::Aliases),
252 impl ToJson for MergeFunctions {
253 fn to_json(&self) -> Json {
255 MergeFunctions::Disabled => "disabled".to_json(),
256 MergeFunctions::Trampolines => "trampolines".to_json(),
257 MergeFunctions::Aliases => "aliases".to_json(),
262 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
263 pub type TargetResult = Result<Target, String>;
265 macro_rules! supported_targets {
266 ( $(($triple:expr, $module:ident),)+ ) => (
269 /// List of supported targets
270 const TARGETS: &[&str] = &[$($triple),*];
272 fn load_specific(target: &str) -> TargetResult {
276 let mut t = $module::target()?;
277 t.options.is_builtin = true;
279 // round-trip through the JSON parser to ensure at
280 // run-time that the parser works correctly
281 t = Target::from_json(t.to_json())?;
282 debug!("Got builtin target: {:?}", t);
286 _ => Err(format!("Unable to find target: {}", target))
290 pub fn get_targets() -> impl Iterator<Item = String> {
291 TARGETS.iter().filter_map(|t| -> Option<String> {
293 .and(Ok(t.to_string()))
299 mod test_json_encode_decode {
300 use serialize::json::ToJson;
302 $(use super::$module;)*
307 // Grab the TargetResult struct. If we successfully retrieved
308 // a Target, then the test JSON encoding/decoding can run for this
309 // Target on this testing platform (i.e., checking the iOS targets
310 // only on a Mac test platform).
311 let _ = $module::target().map(|original| {
312 let as_json = original.to_json();
313 let parsed = Target::from_json(as_json).unwrap();
314 assert_eq!(original, parsed);
323 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
324 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
325 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
326 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
327 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
328 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
329 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
330 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
331 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
332 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
333 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
334 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
335 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
336 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
337 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
338 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
339 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
340 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
341 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
342 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
343 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
344 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
345 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
346 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
347 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
348 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
349 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
350 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
351 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
353 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
354 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
355 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
356 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
357 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
358 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
360 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
361 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
363 ("i686-linux-android", i686_linux_android),
364 ("x86_64-linux-android", x86_64_linux_android),
365 ("arm-linux-androideabi", arm_linux_androideabi),
366 ("armv7-linux-androideabi", armv7_linux_androideabi),
367 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
368 ("aarch64-linux-android", aarch64_linux_android),
370 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
371 ("i686-unknown-freebsd", i686_unknown_freebsd),
372 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
373 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
375 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
376 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
378 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
380 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
381 ("i686-unknown-openbsd", i686_unknown_openbsd),
382 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
384 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
385 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
386 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
387 ("i686-unknown-netbsd", i686_unknown_netbsd),
388 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
389 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
390 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
391 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
393 ("i686-unknown-haiku", i686_unknown_haiku),
394 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
396 ("x86_64-apple-darwin", x86_64_apple_darwin),
397 ("i686-apple-darwin", i686_apple_darwin),
399 ("aarch64-fuchsia", aarch64_fuchsia),
400 ("x86_64-fuchsia", x86_64_fuchsia),
402 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
404 ("x86_64-unknown-redox", x86_64_unknown_redox),
406 ("i386-apple-ios", i386_apple_ios),
407 ("x86_64-apple-ios", x86_64_apple_ios),
408 ("aarch64-apple-ios", aarch64_apple_ios),
409 ("armv7-apple-ios", armv7_apple_ios),
410 ("armv7s-apple-ios", armv7s_apple_ios),
412 ("armebv7r-none-eabi", armebv7r_none_eabi),
413 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
414 ("armv7r-none-eabi", armv7r_none_eabi),
415 ("armv7r-none-eabihf", armv7r_none_eabihf),
417 ("x86_64-sun-solaris", x86_64_sun_solaris),
418 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
420 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
421 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
423 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
424 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
425 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
426 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
427 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
429 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
430 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
431 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
432 ("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
434 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
435 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
436 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
437 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
438 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
439 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
440 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
442 ("msp430-none-elf", msp430_none_elf),
444 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
445 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
446 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
447 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
449 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
450 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
452 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
453 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
454 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
455 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
457 ("aarch64-unknown-none", aarch64_unknown_none),
459 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
461 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
463 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
466 /// Everything `rustc` knows about how to compile for a specific target.
468 /// Every field here must be specified, and has no default value.
469 #[derive(PartialEq, Clone, Debug)]
471 /// Target triple to pass to LLVM.
472 pub llvm_target: String,
473 /// String to use as the `target_endian` `cfg` variable.
474 pub target_endian: String,
475 /// String to use as the `target_pointer_width` `cfg` variable.
476 pub target_pointer_width: String,
477 /// Width of c_int type
478 pub target_c_int_width: String,
479 /// OS name to use for conditional compilation.
480 pub target_os: String,
481 /// Environment name to use for conditional compilation.
482 pub target_env: String,
483 /// Vendor name to use for conditional compilation.
484 pub target_vendor: String,
485 /// Architecture to use for ABI considerations. Valid options: "x86",
486 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
488 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
489 pub data_layout: String,
491 pub linker_flavor: LinkerFlavor,
492 /// Optional settings with defaults.
493 pub options: TargetOptions,
496 pub trait HasTargetSpec {
497 fn target_spec(&self) -> &Target;
500 impl HasTargetSpec for Target {
501 fn target_spec(&self) -> &Target {
506 /// Optional aspects of a target specification.
508 /// This has an implementation of `Default`, see each field for what the default is. In general,
509 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
510 #[derive(PartialEq, Clone, Debug)]
511 pub struct TargetOptions {
512 /// Whether the target is built-in or loaded from a custom target specification.
513 pub is_builtin: bool,
516 pub linker: Option<String>,
519 pub lld_flavor: LldFlavor,
521 /// Linker arguments that are passed *before* any user-defined libraries.
522 pub pre_link_args: LinkArgs, // ... unconditionally
523 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
524 /// Objects to link before all others, always found within the
526 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
527 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
528 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
529 /// Linker arguments that are unconditionally passed after any
530 /// user-defined but before post_link_objects. Standard platform
531 /// libraries that should be always be linked to, usually go here.
532 pub late_link_args: LinkArgs,
533 /// Objects to link after all others, always found within the
535 pub post_link_objects: Vec<String>, // ... unconditionally
536 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
537 /// Linker arguments that are unconditionally passed *after* any
538 /// user-defined libraries.
539 pub post_link_args: LinkArgs,
541 /// Environment variables to be set before invoking the linker.
542 pub link_env: Vec<(String, String)>,
544 /// Extra arguments to pass to the external assembler (when used)
545 pub asm_args: Vec<String>,
547 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
550 /// Default target features to pass to LLVM. These features will *always* be
551 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
552 /// -mattr=$features`.
553 pub features: String,
554 /// Whether dynamic linking is available on this target. Defaults to false.
555 pub dynamic_linking: bool,
556 /// If dynamic linking is available, whether only cdylibs are supported.
557 pub only_cdylib: bool,
558 /// Whether executables are available on this target. iOS, for example, only allows static
559 /// libraries. Defaults to false.
560 pub executables: bool,
561 /// Relocation model to use in object file. Corresponds to `llc
562 /// -relocation-model=$relocation_model`. Defaults to "pic".
563 pub relocation_model: String,
564 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
565 pub code_model: Option<String>,
566 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
567 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
568 pub tls_model: String,
569 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
570 pub disable_redzone: bool,
571 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
572 pub eliminate_frame_pointer: bool,
573 /// Emit each function in its own section. Defaults to true.
574 pub function_sections: bool,
575 /// String to prepend to the name of every dynamic library. Defaults to "lib".
576 pub dll_prefix: String,
577 /// String to append to the name of every dynamic library. Defaults to ".so".
578 pub dll_suffix: String,
579 /// String to append to the name of every executable.
580 pub exe_suffix: String,
581 /// String to prepend to the name of every static library. Defaults to "lib".
582 pub staticlib_prefix: String,
583 /// String to append to the name of every static library. Defaults to ".a".
584 pub staticlib_suffix: String,
585 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
586 pub target_family: Option<String>,
587 /// Whether the target toolchain's ABI supports returning small structs as an integer.
588 pub abi_return_struct_as_int: bool,
589 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
590 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
591 pub is_like_osx: bool,
592 /// Whether the target toolchain is like Solaris's.
593 /// Only useful for compiling against Illumos/Solaris,
594 /// as they have a different set of linker flags. Defaults to false.
595 pub is_like_solaris: bool,
596 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
597 /// only really used for figuring out how to find libraries, since Windows uses its own
598 /// library naming convention. Defaults to false.
599 pub is_like_windows: bool,
600 pub is_like_msvc: bool,
601 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
602 /// Defaults to false.
603 pub is_like_android: bool,
604 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
605 /// Emscripten toolchain.
606 /// Defaults to false.
607 pub is_like_emscripten: bool,
608 /// Whether the target toolchain is like Fuchsia's.
609 pub is_like_fuchsia: bool,
610 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
611 pub linker_is_gnu: bool,
612 /// The MinGW toolchain has a known issue that prevents it from correctly
613 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
614 /// symbol needs its own COMDAT section, weak linkage implies a large
615 /// number sections that easily exceeds the given limit for larger
616 /// codebases. Consequently we want a way to disallow weak linkage on some
618 pub allows_weak_linkage: bool,
619 /// Whether the linker support rpaths or not. Defaults to false.
621 /// Whether to disable linking to the default libraries, typically corresponds
622 /// to `-nodefaultlibs`. Defaults to true.
623 pub no_default_libraries: bool,
624 /// Dynamically linked executables can be compiled as position independent
625 /// if the default relocation model of position independent code is not
626 /// changed. This is a requirement to take advantage of ASLR, as otherwise
627 /// the functions in the executable are not randomized and can be used
628 /// during an exploit of a vulnerability in any code.
629 pub position_independent_executables: bool,
630 /// Determines if the target always requires using the PLT for indirect
631 /// library calls or not. This controls the default value of the `-Z plt` flag.
633 /// Either partial, full, or off. Full RELRO makes the dynamic linker
634 /// resolve all symbols at startup and marks the GOT read-only before
635 /// starting the program, preventing overwriting the GOT.
636 pub relro_level: RelroLevel,
637 /// Format that archives should be emitted in. This affects whether we use
638 /// LLVM to assemble an archive or fall back to the system linker, and
639 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
640 /// the system linker to be used.
641 pub archive_format: String,
642 /// Is asm!() allowed? Defaults to true.
644 /// Whether the target uses a custom unwind resumption routine.
645 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
646 /// defined in libgcc. If this option is enabled, the target must provide
647 /// `eh_unwind_resume` lang item.
648 pub custom_unwind_resume: bool,
650 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
652 pub has_elf_tls: bool,
653 // This is mainly for easy compatibility with emscripten.
654 // If we give emcc .o files that are actually .bc files it
656 pub obj_is_bitcode: bool,
658 // LLVM can't produce object files for this target. Instead, we'll make LLVM
659 // emit assembly and then use `gcc` to turn that assembly into an object
661 pub no_integrated_as: bool,
663 /// Don't use this field; instead use the `.min_atomic_width()` method.
664 pub min_atomic_width: Option<u64>,
666 /// Don't use this field; instead use the `.max_atomic_width()` method.
667 pub max_atomic_width: Option<u64>,
669 /// Whether the target supports atomic CAS operations natively
670 pub atomic_cas: bool,
672 /// Panic strategy: "unwind" or "abort"
673 pub panic_strategy: PanicStrategy,
675 /// A blacklist of ABIs unsupported by the current target. Note that generic
676 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
677 pub abi_blacklist: Vec<Abi>,
679 /// Whether or not linking dylibs to a static CRT is allowed.
680 pub crt_static_allows_dylibs: bool,
681 /// Whether or not the CRT is statically linked by default.
682 pub crt_static_default: bool,
683 /// Whether or not crt-static is respected by the compiler (or is a no-op).
684 pub crt_static_respected: bool,
686 /// Whether or not stack probes (__rust_probestack) are enabled
687 pub stack_probes: bool,
689 /// The minimum alignment for global symbols.
690 pub min_global_align: Option<u64>,
692 /// Default number of codegen units to use in debug mode
693 pub default_codegen_units: Option<u64>,
695 /// Whether to generate trap instructions in places where optimization would
696 /// otherwise produce control flow that falls through into unrelated memory.
697 pub trap_unreachable: bool,
699 /// This target requires everything to be compiled with LTO to emit a final
700 /// executable, aka there is no native linker for this target.
701 pub requires_lto: bool,
703 /// This target has no support for threads.
704 pub singlethread: bool,
706 /// Whether library functions call lowering/optimization is disabled in LLVM
707 /// for this target unconditionally.
708 pub no_builtins: bool,
710 /// Whether to lower 128-bit operations to compiler_builtins calls. Use if
711 /// your backend only supports 64-bit and smaller math.
712 pub i128_lowering: bool,
714 /// The codegen backend to use for this target, typically "llvm"
715 pub codegen_backend: String,
717 /// The default visibility for symbols in this target should be "hidden"
718 /// rather than "default"
719 pub default_hidden_visibility: bool,
721 /// Whether or not bitcode is embedded in object files
722 pub embed_bitcode: bool,
724 /// Whether a .debug_gdb_scripts section will be added to the output object file
725 pub emit_debug_gdb_scripts: bool,
727 /// Whether or not to unconditionally `uwtable` attributes on functions,
728 /// typically because the platform needs to unwind for things like stack
730 pub requires_uwtable: bool,
732 /// Whether or not SIMD types are passed by reference in the Rust ABI,
733 /// typically required if a target can be compiled with a mixed set of
734 /// target features. This is `true` by default, and `false` for targets like
735 /// wasm32 where the whole program either has simd or not.
736 pub simd_types_indirect: bool,
738 /// If set, have the linker export exactly these symbols, instead of using
739 /// the usual logic to figure this out from the crate itself.
740 pub override_export_symbols: Option<Vec<String>>,
742 /// Determines how or whether the MergeFunctions LLVM pass should run for
743 /// this target. Either "disabled", "trampolines", or "aliases".
744 /// The MergeFunctions pass is generally useful, but some targets may need
745 /// to opt out. The default is "aliases".
747 /// Workaround for: https://github.com/rust-lang/rust/issues/57356
748 pub merge_functions: MergeFunctions
751 impl Default for TargetOptions {
752 /// Creates a set of "sane defaults" for any target. This is still
753 /// incomplete, and if used for compilation, will certainly not work.
754 fn default() -> TargetOptions {
757 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
758 lld_flavor: LldFlavor::Ld,
759 pre_link_args: LinkArgs::new(),
760 pre_link_args_crt: LinkArgs::new(),
761 post_link_args: LinkArgs::new(),
762 asm_args: Vec::new(),
763 cpu: "generic".to_string(),
764 features: String::new(),
765 dynamic_linking: false,
768 relocation_model: "pic".to_string(),
770 tls_model: "global-dynamic".to_string(),
771 disable_redzone: false,
772 eliminate_frame_pointer: true,
773 function_sections: true,
774 dll_prefix: "lib".to_string(),
775 dll_suffix: ".so".to_string(),
776 exe_suffix: String::new(),
777 staticlib_prefix: "lib".to_string(),
778 staticlib_suffix: ".a".to_string(),
780 abi_return_struct_as_int: false,
782 is_like_solaris: false,
783 is_like_windows: false,
784 is_like_android: false,
785 is_like_emscripten: false,
787 is_like_fuchsia: false,
788 linker_is_gnu: false,
789 allows_weak_linkage: true,
791 no_default_libraries: true,
792 position_independent_executables: false,
794 relro_level: RelroLevel::None,
795 pre_link_objects_exe: Vec::new(),
796 pre_link_objects_exe_crt: Vec::new(),
797 pre_link_objects_dll: Vec::new(),
798 post_link_objects: Vec::new(),
799 post_link_objects_crt: Vec::new(),
800 late_link_args: LinkArgs::new(),
801 link_env: Vec::new(),
802 archive_format: "gnu".to_string(),
803 custom_unwind_resume: false,
806 obj_is_bitcode: false,
807 no_integrated_as: false,
808 min_atomic_width: None,
809 max_atomic_width: None,
811 panic_strategy: PanicStrategy::Unwind,
812 abi_blacklist: vec![],
813 crt_static_allows_dylibs: false,
814 crt_static_default: false,
815 crt_static_respected: false,
817 min_global_align: None,
818 default_codegen_units: None,
819 trap_unreachable: true,
823 i128_lowering: false,
824 codegen_backend: "llvm".to_string(),
825 default_hidden_visibility: false,
826 embed_bitcode: false,
827 emit_debug_gdb_scripts: true,
828 requires_uwtable: false,
829 simd_types_indirect: true,
830 override_export_symbols: None,
831 merge_functions: MergeFunctions::Aliases,
837 /// Given a function ABI, turn it into the correct ABI for this target.
838 pub fn adjust_abi(&self, abi: Abi) -> Abi {
841 if self.options.is_like_windows && self.arch == "x86" {
847 // These ABI kinds are ignored on non-x86 Windows targets.
848 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
849 // and the individual pages for __stdcall et al.
850 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
851 if self.options.is_like_windows && self.arch != "x86" {
861 /// Minimum integer size in bits that this target can perform atomic
863 pub fn min_atomic_width(&self) -> u64 {
864 self.options.min_atomic_width.unwrap_or(8)
867 /// Maximum integer size in bits that this target can perform atomic
869 pub fn max_atomic_width(&self) -> u64 {
870 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
873 pub fn is_abi_supported(&self, abi: Abi) -> bool {
874 abi.generic() || !self.options.abi_blacklist.contains(&abi)
877 /// Loads a target descriptor from a JSON object.
878 pub fn from_json(obj: Json) -> TargetResult {
879 // While ugly, this code must remain this way to retain
880 // compatibility with existing JSON fields and the internal
881 // expected naming of the Target and TargetOptions structs.
882 // To ensure compatibility is retained, the built-in targets
883 // are round-tripped through this code to catch cases where
884 // the JSON parser is not updated to match the structs.
886 let get_req_field = |name: &str| {
888 .map(|s| s.as_string())
889 .and_then(|os| os.map(|s| s.to_string()))
890 .ok_or_else(|| format!("Field {} in target specification is required", name))
893 let get_opt_field = |name: &str, default: &str| {
894 obj.find(name).and_then(|s| s.as_string())
895 .map(|s| s.to_string())
896 .unwrap_or_else(|| default.to_string())
899 let mut base = Target {
900 llvm_target: get_req_field("llvm-target")?,
901 target_endian: get_req_field("target-endian")?,
902 target_pointer_width: get_req_field("target-pointer-width")?,
903 target_c_int_width: get_req_field("target-c-int-width")?,
904 data_layout: get_req_field("data-layout")?,
905 arch: get_req_field("arch")?,
906 target_os: get_req_field("os")?,
907 target_env: get_opt_field("env", ""),
908 target_vendor: get_opt_field("vendor", "unknown"),
909 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
911 format!("linker flavor must be {}", LinkerFlavor::one_of())
913 options: Default::default(),
917 ($key_name:ident) => ( {
918 let name = (stringify!($key_name)).replace("_", "-");
919 obj.find(&name[..]).map(|o| o.as_string()
920 .map(|s| base.options.$key_name = s.to_string()));
922 ($key_name:ident, bool) => ( {
923 let name = (stringify!($key_name)).replace("_", "-");
925 .map(|o| o.as_boolean()
926 .map(|s| base.options.$key_name = s));
928 ($key_name:ident, Option<u64>) => ( {
929 let name = (stringify!($key_name)).replace("_", "-");
932 .map(|s| base.options.$key_name = Some(s)));
934 ($key_name:ident, MergeFunctions) => ( {
935 let name = (stringify!($key_name)).replace("_", "-");
936 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
937 match s.parse::<MergeFunctions>() {
938 Ok(mergefunc) => base.options.$key_name = mergefunc,
939 _ => return Some(Err(format!("'{}' is not a valid value for \
940 merge-functions. Use 'disabled', \
941 'trampolines', or 'aliases'.",
945 })).unwrap_or(Ok(()))
947 ($key_name:ident, PanicStrategy) => ( {
948 let name = (stringify!($key_name)).replace("_", "-");
949 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
951 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
952 "abort" => base.options.$key_name = PanicStrategy::Abort,
953 _ => return Some(Err(format!("'{}' is not a valid value for \
954 panic-strategy. Use 'unwind' or 'abort'.",
958 })).unwrap_or(Ok(()))
960 ($key_name:ident, RelroLevel) => ( {
961 let name = (stringify!($key_name)).replace("_", "-");
962 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
963 match s.parse::<RelroLevel>() {
964 Ok(level) => base.options.$key_name = level,
965 _ => return Some(Err(format!("'{}' is not a valid value for \
966 relro-level. Use 'full', 'partial, or 'off'.",
970 })).unwrap_or(Ok(()))
972 ($key_name:ident, list) => ( {
973 let name = (stringify!($key_name)).replace("_", "-");
974 obj.find(&name[..]).map(|o| o.as_array()
975 .map(|v| base.options.$key_name = v.iter()
976 .map(|a| a.as_string().unwrap().to_string()).collect()
980 ($key_name:ident, opt_list) => ( {
981 let name = (stringify!($key_name)).replace("_", "-");
982 obj.find(&name[..]).map(|o| o.as_array()
983 .map(|v| base.options.$key_name = Some(v.iter()
984 .map(|a| a.as_string().unwrap().to_string()).collect())
988 ($key_name:ident, optional) => ( {
989 let name = (stringify!($key_name)).replace("_", "-");
990 if let Some(o) = obj.find(&name[..]) {
991 base.options.$key_name = o
993 .map(|s| s.to_string() );
996 ($key_name:ident, LldFlavor) => ( {
997 let name = (stringify!($key_name)).replace("_", "-");
998 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
999 if let Some(flavor) = LldFlavor::from_str(&s) {
1000 base.options.$key_name = flavor;
1002 return Some(Err(format!(
1003 "'{}' is not a valid value for lld-flavor. \
1004 Use 'darwin', 'gnu', 'link' or 'wasm.",
1008 })).unwrap_or(Ok(()))
1010 ($key_name:ident, LinkerFlavor) => ( {
1011 let name = (stringify!($key_name)).replace("_", "-");
1012 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
1013 LinkerFlavor::from_str(&s).ok_or_else(|| {
1014 Err(format!("'{}' is not a valid value for linker-flavor. \
1015 Use 'em', 'gcc', 'ld' or 'msvc.", s))
1017 })).unwrap_or(Ok(()))
1019 ($key_name:ident, link_args) => ( {
1020 let name = (stringify!($key_name)).replace("_", "-");
1021 if let Some(val) = obj.find(&name[..]) {
1022 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1023 JSON object with fields per linker-flavor.", name))?;
1024 let mut args = LinkArgs::new();
1026 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1027 format!("{}: '{}' is not a valid value for linker-flavor. \
1028 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1031 let v = v.as_array().ok_or_else(||
1032 format!("{}.{}: expected a JSON array", name, k)
1033 )?.iter().enumerate()
1035 let s = s.as_string().ok_or_else(||
1036 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1039 .collect::<Result<Vec<_>, String>>()?;
1041 args.insert(flavor, v);
1043 base.options.$key_name = args;
1046 ($key_name:ident, env) => ( {
1047 let name = (stringify!($key_name)).replace("_", "-");
1048 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1050 if let Some(s) = o.as_string() {
1051 let p = s.split('=').collect::<Vec<_>>();
1053 let k = p[0].to_string();
1054 let v = p[1].to_string();
1055 base.options.$key_name.push((k, v));
1063 key!(is_builtin, bool);
1064 key!(linker, optional);
1065 key!(lld_flavor, LldFlavor)?;
1066 key!(pre_link_args, link_args);
1067 key!(pre_link_args_crt, link_args);
1068 key!(pre_link_objects_exe, list);
1069 key!(pre_link_objects_exe_crt, list);
1070 key!(pre_link_objects_dll, list);
1071 key!(late_link_args, link_args);
1072 key!(post_link_objects, list);
1073 key!(post_link_objects_crt, list);
1074 key!(post_link_args, link_args);
1075 key!(link_env, env);
1076 key!(asm_args, list);
1079 key!(dynamic_linking, bool);
1080 key!(only_cdylib, bool);
1081 key!(executables, bool);
1082 key!(relocation_model);
1083 key!(code_model, optional);
1085 key!(disable_redzone, bool);
1086 key!(eliminate_frame_pointer, bool);
1087 key!(function_sections, bool);
1091 key!(staticlib_prefix);
1092 key!(staticlib_suffix);
1093 key!(target_family, optional);
1094 key!(abi_return_struct_as_int, bool);
1095 key!(is_like_osx, bool);
1096 key!(is_like_solaris, bool);
1097 key!(is_like_windows, bool);
1098 key!(is_like_msvc, bool);
1099 key!(is_like_emscripten, bool);
1100 key!(is_like_android, bool);
1101 key!(is_like_fuchsia, bool);
1102 key!(linker_is_gnu, bool);
1103 key!(allows_weak_linkage, bool);
1104 key!(has_rpath, bool);
1105 key!(no_default_libraries, bool);
1106 key!(position_independent_executables, bool);
1107 key!(needs_plt, bool);
1108 key!(relro_level, RelroLevel)?;
1109 key!(archive_format);
1110 key!(allow_asm, bool);
1111 key!(custom_unwind_resume, bool);
1112 key!(has_elf_tls, bool);
1113 key!(obj_is_bitcode, bool);
1114 key!(no_integrated_as, bool);
1115 key!(max_atomic_width, Option<u64>);
1116 key!(min_atomic_width, Option<u64>);
1117 key!(atomic_cas, bool);
1118 key!(panic_strategy, PanicStrategy)?;
1119 key!(crt_static_allows_dylibs, bool);
1120 key!(crt_static_default, bool);
1121 key!(crt_static_respected, bool);
1122 key!(stack_probes, bool);
1123 key!(min_global_align, Option<u64>);
1124 key!(default_codegen_units, Option<u64>);
1125 key!(trap_unreachable, bool);
1126 key!(requires_lto, bool);
1127 key!(singlethread, bool);
1128 key!(no_builtins, bool);
1129 key!(codegen_backend);
1130 key!(default_hidden_visibility, bool);
1131 key!(embed_bitcode, bool);
1132 key!(emit_debug_gdb_scripts, bool);
1133 key!(requires_uwtable, bool);
1134 key!(simd_types_indirect, bool);
1135 key!(override_export_symbols, opt_list);
1136 key!(merge_functions, MergeFunctions)?;
1138 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1139 for name in array.iter().filter_map(|abi| abi.as_string()) {
1140 match lookup_abi(name) {
1143 return Err(format!("The ABI \"{}\" is considered to be supported on \
1144 all targets and cannot be blacklisted", abi))
1147 base.options.abi_blacklist.push(abi)
1149 None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
1157 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1158 /// triple. Note that it could also just be a bare filename already, so also
1159 /// check for that. If one of the hardcoded targets we know about, just
1160 /// return it directly.
1162 /// The error string could come from any of the APIs called, including
1163 /// filesystem access and JSON decoding.
1164 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1167 use serialize::json;
1169 fn load_file(path: &Path) -> Result<Target, String> {
1170 let contents = fs::read(path).map_err(|e| e.to_string())?;
1171 let obj = json::from_reader(&mut &contents[..])
1172 .map_err(|e| e.to_string())?;
1173 Target::from_json(obj)
1176 match *target_triple {
1177 TargetTriple::TargetTriple(ref target_triple) => {
1178 // check if triple is in list of supported targets
1179 if let Ok(t) = load_specific(target_triple) {
1183 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1185 let mut target = target_triple.to_string();
1186 target.push_str(".json");
1187 PathBuf::from(target)
1190 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1192 // FIXME 16351: add a sane default search path?
1194 for dir in env::split_paths(&target_path) {
1195 let p = dir.join(&path);
1197 return load_file(&p);
1200 Err(format!("Could not find specification for target {:?}", target_triple))
1202 TargetTriple::TargetPath(ref target_path) => {
1203 if target_path.is_file() {
1204 return load_file(&target_path);
1206 Err(format!("Target path {:?} is not a valid file", target_path))
1212 impl ToJson for Target {
1213 fn to_json(&self) -> Json {
1214 let mut d = BTreeMap::new();
1215 let default: TargetOptions = Default::default();
1217 macro_rules! target_val {
1218 ($attr:ident) => ( {
1219 let name = (stringify!($attr)).replace("_", "-");
1220 d.insert(name, self.$attr.to_json());
1222 ($attr:ident, $key_name:expr) => ( {
1223 let name = $key_name;
1224 d.insert(name.to_string(), self.$attr.to_json());
1228 macro_rules! target_option_val {
1229 ($attr:ident) => ( {
1230 let name = (stringify!($attr)).replace("_", "-");
1231 if default.$attr != self.options.$attr {
1232 d.insert(name, self.options.$attr.to_json());
1235 ($attr:ident, $key_name:expr) => ( {
1236 let name = $key_name;
1237 if default.$attr != self.options.$attr {
1238 d.insert(name.to_string(), self.options.$attr.to_json());
1241 (link_args - $attr:ident) => ( {
1242 let name = (stringify!($attr)).replace("_", "-");
1243 if default.$attr != self.options.$attr {
1244 let obj = self.options.$attr
1246 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1247 .collect::<BTreeMap<_, _>>();
1248 d.insert(name, obj.to_json());
1251 (env - $attr:ident) => ( {
1252 let name = (stringify!($attr)).replace("_", "-");
1253 if default.$attr != self.options.$attr {
1254 let obj = self.options.$attr
1256 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1257 .collect::<Vec<_>>();
1258 d.insert(name, obj.to_json());
1264 target_val!(llvm_target);
1265 target_val!(target_endian);
1266 target_val!(target_pointer_width);
1267 target_val!(target_c_int_width);
1269 target_val!(target_os, "os");
1270 target_val!(target_env, "env");
1271 target_val!(target_vendor, "vendor");
1272 target_val!(data_layout);
1273 target_val!(linker_flavor);
1275 target_option_val!(is_builtin);
1276 target_option_val!(linker);
1277 target_option_val!(lld_flavor);
1278 target_option_val!(link_args - pre_link_args);
1279 target_option_val!(link_args - pre_link_args_crt);
1280 target_option_val!(pre_link_objects_exe);
1281 target_option_val!(pre_link_objects_exe_crt);
1282 target_option_val!(pre_link_objects_dll);
1283 target_option_val!(link_args - late_link_args);
1284 target_option_val!(post_link_objects);
1285 target_option_val!(post_link_objects_crt);
1286 target_option_val!(link_args - post_link_args);
1287 target_option_val!(env - link_env);
1288 target_option_val!(asm_args);
1289 target_option_val!(cpu);
1290 target_option_val!(features);
1291 target_option_val!(dynamic_linking);
1292 target_option_val!(only_cdylib);
1293 target_option_val!(executables);
1294 target_option_val!(relocation_model);
1295 target_option_val!(code_model);
1296 target_option_val!(tls_model);
1297 target_option_val!(disable_redzone);
1298 target_option_val!(eliminate_frame_pointer);
1299 target_option_val!(function_sections);
1300 target_option_val!(dll_prefix);
1301 target_option_val!(dll_suffix);
1302 target_option_val!(exe_suffix);
1303 target_option_val!(staticlib_prefix);
1304 target_option_val!(staticlib_suffix);
1305 target_option_val!(target_family);
1306 target_option_val!(abi_return_struct_as_int);
1307 target_option_val!(is_like_osx);
1308 target_option_val!(is_like_solaris);
1309 target_option_val!(is_like_windows);
1310 target_option_val!(is_like_msvc);
1311 target_option_val!(is_like_emscripten);
1312 target_option_val!(is_like_android);
1313 target_option_val!(is_like_fuchsia);
1314 target_option_val!(linker_is_gnu);
1315 target_option_val!(allows_weak_linkage);
1316 target_option_val!(has_rpath);
1317 target_option_val!(no_default_libraries);
1318 target_option_val!(position_independent_executables);
1319 target_option_val!(needs_plt);
1320 target_option_val!(relro_level);
1321 target_option_val!(archive_format);
1322 target_option_val!(allow_asm);
1323 target_option_val!(custom_unwind_resume);
1324 target_option_val!(has_elf_tls);
1325 target_option_val!(obj_is_bitcode);
1326 target_option_val!(no_integrated_as);
1327 target_option_val!(min_atomic_width);
1328 target_option_val!(max_atomic_width);
1329 target_option_val!(atomic_cas);
1330 target_option_val!(panic_strategy);
1331 target_option_val!(crt_static_allows_dylibs);
1332 target_option_val!(crt_static_default);
1333 target_option_val!(crt_static_respected);
1334 target_option_val!(stack_probes);
1335 target_option_val!(min_global_align);
1336 target_option_val!(default_codegen_units);
1337 target_option_val!(trap_unreachable);
1338 target_option_val!(requires_lto);
1339 target_option_val!(singlethread);
1340 target_option_val!(no_builtins);
1341 target_option_val!(codegen_backend);
1342 target_option_val!(default_hidden_visibility);
1343 target_option_val!(embed_bitcode);
1344 target_option_val!(emit_debug_gdb_scripts);
1345 target_option_val!(requires_uwtable);
1346 target_option_val!(simd_types_indirect);
1347 target_option_val!(override_export_symbols);
1348 target_option_val!(merge_functions);
1350 if default.abi_blacklist != self.options.abi_blacklist {
1351 d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1352 .map(|&name| Abi::name(name).to_json())
1353 .collect::<Vec<_>>().to_json());
1360 /// Either a target triple string or a path to a JSON file.
1361 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1362 pub enum TargetTriple {
1363 TargetTriple(String),
1364 TargetPath(PathBuf),
1368 /// Creates a target triple from the passed target triple string.
1369 pub fn from_triple(triple: &str) -> Self {
1370 TargetTriple::TargetTriple(triple.to_string())
1373 /// Creates a target triple from the passed target path.
1374 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1375 let canonicalized_path = path.canonicalize()?;
1376 Ok(TargetTriple::TargetPath(canonicalized_path))
1379 /// Returns a string triple for this target.
1381 /// If this target is a path, the file name (without extension) is returned.
1382 pub fn triple(&self) -> &str {
1384 TargetTriple::TargetTriple(ref triple) => triple,
1385 TargetTriple::TargetPath(ref path) => {
1386 path.file_stem().expect("target path must not be empty").to_str()
1387 .expect("target path must be valid unicode")
1392 /// Returns an extended string triple for this target.
1394 /// If this target is a path, a hash of the path is appended to the triple returned
1396 pub fn debug_triple(&self) -> String {
1397 use std::hash::{Hash, Hasher};
1398 use std::collections::hash_map::DefaultHasher;
1400 let triple = self.triple();
1401 if let TargetTriple::TargetPath(ref path) = *self {
1402 let mut hasher = DefaultHasher::new();
1403 path.hash(&mut hasher);
1404 let hash = hasher.finish();
1405 format!("{}-{}", triple, hash)
1412 impl fmt::Display for TargetTriple {
1413 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1414 write!(f, "{}", self.debug_triple())