1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
9 //! # Using custom targets
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
26 //! # Defining a new target
28 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
37 use crate::spec::abi::{lookup as lookup_abi, Abi};
38 use rustc_serialize::json::{Json, ToJson};
39 use std::collections::BTreeMap;
40 use std::default::Default;
41 use std::path::{Path, PathBuf};
42 use std::str::FromStr;
45 use rustc_macros::HashStable_Generic;
58 mod hermit_kernel_base;
61 mod linux_kernel_base;
73 mod windows_msvc_base;
75 mod windows_uwp_msvc_base;
77 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
78 pub enum LinkerFlavor {
87 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
96 fn from_str(s: &str) -> Option<Self> {
98 "darwin" => LldFlavor::Ld64,
99 "gnu" => LldFlavor::Ld,
100 "link" => LldFlavor::Link,
101 "wasm" => LldFlavor::Wasm,
107 impl ToJson for LldFlavor {
108 fn to_json(&self) -> Json {
110 LldFlavor::Ld64 => "darwin",
111 LldFlavor::Ld => "gnu",
112 LldFlavor::Link => "link",
113 LldFlavor::Wasm => "wasm",
119 impl ToJson for LinkerFlavor {
120 fn to_json(&self) -> Json {
121 self.desc().to_json()
124 macro_rules! flavor_mappings {
125 ($((($($flavor:tt)*), $string:expr),)*) => (
127 pub const fn one_of() -> &'static str {
128 concat!("one of: ", $($string, " ",)*)
131 pub fn from_str(s: &str) -> Option<Self> {
133 $($string => $($flavor)*,)*
138 pub fn desc(&self) -> &str {
140 $($($flavor)* => $string,)*
148 ((LinkerFlavor::Em), "em"),
149 ((LinkerFlavor::Gcc), "gcc"),
150 ((LinkerFlavor::Ld), "ld"),
151 ((LinkerFlavor::Msvc), "msvc"),
152 ((LinkerFlavor::PtxLinker), "ptx-linker"),
153 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
154 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
155 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
156 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
159 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable, HashStable_Generic)]
160 pub enum PanicStrategy {
166 pub fn desc(&self) -> &str {
168 PanicStrategy::Unwind => "unwind",
169 PanicStrategy::Abort => "abort",
174 impl ToJson for PanicStrategy {
175 fn to_json(&self) -> Json {
177 PanicStrategy::Abort => "abort".to_json(),
178 PanicStrategy::Unwind => "unwind".to_json(),
183 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
184 pub enum RelroLevel {
192 pub fn desc(&self) -> &str {
194 RelroLevel::Full => "full",
195 RelroLevel::Partial => "partial",
196 RelroLevel::Off => "off",
197 RelroLevel::None => "none",
202 impl FromStr for RelroLevel {
205 fn from_str(s: &str) -> Result<RelroLevel, ()> {
207 "full" => Ok(RelroLevel::Full),
208 "partial" => Ok(RelroLevel::Partial),
209 "off" => Ok(RelroLevel::Off),
210 "none" => Ok(RelroLevel::None),
216 impl ToJson for RelroLevel {
217 fn to_json(&self) -> Json {
219 RelroLevel::Full => "full".to_json(),
220 RelroLevel::Partial => "partial".to_json(),
221 RelroLevel::Off => "off".to_json(),
222 RelroLevel::None => "None".to_json(),
227 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
228 pub enum MergeFunctions {
234 impl MergeFunctions {
235 pub fn desc(&self) -> &str {
237 MergeFunctions::Disabled => "disabled",
238 MergeFunctions::Trampolines => "trampolines",
239 MergeFunctions::Aliases => "aliases",
244 impl FromStr for MergeFunctions {
247 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
249 "disabled" => Ok(MergeFunctions::Disabled),
250 "trampolines" => Ok(MergeFunctions::Trampolines),
251 "aliases" => Ok(MergeFunctions::Aliases),
257 impl ToJson for MergeFunctions {
258 fn to_json(&self) -> Json {
260 MergeFunctions::Disabled => "disabled".to_json(),
261 MergeFunctions::Trampolines => "trampolines".to_json(),
262 MergeFunctions::Aliases => "aliases".to_json(),
267 pub enum LoadTargetError {
268 BuiltinTargetNotFound(String),
272 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
273 pub type TargetResult = Result<Target, String>;
275 macro_rules! supported_targets {
276 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
279 /// List of supported targets
280 const TARGETS: &[&str] = &[$($($triple),+),+];
282 fn load_specific(target: &str) -> Result<Target, LoadTargetError> {
286 let mut t = $module::target()
287 .map_err(LoadTargetError::Other)?;
288 t.options.is_builtin = true;
290 // round-trip through the JSON parser to ensure at
291 // run-time that the parser works correctly
292 t = Target::from_json(t.to_json())
293 .map_err(LoadTargetError::Other)?;
294 debug!("got builtin target: {:?}", t);
298 _ => Err(LoadTargetError::BuiltinTargetNotFound(
299 format!("Unable to find target: {}", target)))
303 pub fn get_targets() -> impl Iterator<Item = String> {
304 TARGETS.iter().filter_map(|t| -> Option<String> {
306 .and(Ok(t.to_string()))
312 mod test_json_encode_decode {
313 use rustc_serialize::json::ToJson;
315 $(use super::$module;)+
318 #[test] // `#[test]` - this is hard to put into a separate file, make an exception
320 // Grab the TargetResult struct. If we successfully retrieved
321 // a Target, then the test JSON encoding/decoding can run for this
322 // Target on this testing platform (i.e., checking the iOS targets
323 // only on a Mac test platform).
324 let _ = $module::target().map(|original| {
325 original.check_consistency();
326 let as_json = original.to_json();
327 let parsed = Target::from_json(as_json).unwrap();
328 assert_eq!(original, parsed);
337 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
338 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
339 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
340 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
341 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
342 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
343 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
344 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
345 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
346 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
347 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
348 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
349 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
350 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
351 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
352 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
353 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
354 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
355 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
356 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
357 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
358 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
359 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
360 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
361 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
362 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
363 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
364 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
365 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
366 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
367 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
368 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
369 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
370 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
371 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
372 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
373 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
374 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
375 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
376 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
377 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
378 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
379 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
380 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
381 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
383 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
384 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
386 ("i686-linux-android", i686_linux_android),
387 ("x86_64-linux-android", x86_64_linux_android),
388 ("arm-linux-androideabi", arm_linux_androideabi),
389 ("armv7-linux-androideabi", armv7_linux_androideabi),
390 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
391 ("aarch64-linux-android", aarch64_linux_android),
393 ("x86_64-linux-kernel", x86_64_linux_kernel),
395 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
396 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
397 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
398 ("i686-unknown-freebsd", i686_unknown_freebsd),
399 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
400 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
402 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
404 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
405 ("i686-unknown-openbsd", i686_unknown_openbsd),
406 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
407 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
409 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
410 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
411 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
412 ("i686-unknown-netbsd", i686_unknown_netbsd),
413 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
414 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
415 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
416 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
418 ("i686-unknown-haiku", i686_unknown_haiku),
419 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
421 ("x86_64-apple-darwin", x86_64_apple_darwin),
422 ("i686-apple-darwin", i686_apple_darwin),
424 ("aarch64-fuchsia", aarch64_fuchsia),
425 ("x86_64-fuchsia", x86_64_fuchsia),
427 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
429 ("aarch64-unknown-redox", aarch64_unknown_redox),
430 ("x86_64-unknown-redox", x86_64_unknown_redox),
432 ("i386-apple-ios", i386_apple_ios),
433 ("x86_64-apple-ios", x86_64_apple_ios),
434 ("aarch64-apple-ios", aarch64_apple_ios),
435 ("armv7-apple-ios", armv7_apple_ios),
436 ("armv7s-apple-ios", armv7s_apple_ios),
437 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
438 ("aarch64-apple-tvos", aarch64_apple_tvos),
439 ("x86_64-apple-tvos", x86_64_apple_tvos),
441 ("armebv7r-none-eabi", armebv7r_none_eabi),
442 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
443 ("armv7r-none-eabi", armv7r_none_eabi),
444 ("armv7r-none-eabihf", armv7r_none_eabihf),
446 // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
447 // (See <https://github.com/rust-lang/rust/issues/40531>.)
448 ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris),
449 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
451 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
452 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
453 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
454 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
456 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
457 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
458 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
459 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
460 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
461 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
462 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
463 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
465 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
466 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
467 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
468 ("wasm32-wasi", wasm32_wasi),
470 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
471 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
472 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
473 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
474 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
475 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
476 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
478 ("armv7a-none-eabi", armv7a_none_eabi),
479 ("armv7a-none-eabihf", armv7a_none_eabihf),
481 ("msp430-none-elf", msp430_none_elf),
483 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
484 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
485 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
486 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
488 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
489 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
490 ("x86_64-unknown-hermit-kernel", x86_64_unknown_hermit_kernel),
492 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
493 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
494 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
495 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
496 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
497 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
499 ("aarch64-unknown-none", aarch64_unknown_none),
500 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
502 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
504 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
505 ("i686-unknown-uefi", i686_unknown_uefi),
507 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
509 ("i686-wrs-vxworks", i686_wrs_vxworks),
510 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
511 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
512 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
513 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
514 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
515 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
518 /// Everything `rustc` knows about how to compile for a specific target.
520 /// Every field here must be specified, and has no default value.
521 #[derive(PartialEq, Clone, Debug)]
523 /// Target triple to pass to LLVM.
524 pub llvm_target: String,
525 /// String to use as the `target_endian` `cfg` variable.
526 pub target_endian: String,
527 /// String to use as the `target_pointer_width` `cfg` variable.
528 pub target_pointer_width: String,
529 /// Width of c_int type
530 pub target_c_int_width: String,
531 /// OS name to use for conditional compilation.
532 pub target_os: String,
533 /// Environment name to use for conditional compilation.
534 pub target_env: String,
535 /// Vendor name to use for conditional compilation.
536 pub target_vendor: String,
537 /// Architecture to use for ABI considerations. Valid options include: "x86",
538 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
540 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
541 pub data_layout: String,
542 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
543 /// on the command line.
544 pub linker_flavor: LinkerFlavor,
545 /// Optional settings with defaults.
546 pub options: TargetOptions,
549 pub trait HasTargetSpec {
550 fn target_spec(&self) -> &Target;
553 impl HasTargetSpec for Target {
554 fn target_spec(&self) -> &Target {
559 /// Optional aspects of a target specification.
561 /// This has an implementation of `Default`, see each field for what the default is. In general,
562 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
563 #[derive(PartialEq, Clone, Debug)]
564 pub struct TargetOptions {
565 /// Whether the target is built-in or loaded from a custom target specification.
566 pub is_builtin: bool,
569 pub linker: Option<String>,
571 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
572 /// without clarifying its flavor in any way.
573 pub lld_flavor: LldFlavor,
575 /// Linker arguments that are passed *before* any user-defined libraries.
576 pub pre_link_args: LinkArgs, // ... unconditionally
577 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
578 /// Objects to link before all others, always found within the
580 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
581 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
582 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
583 /// Linker arguments that are unconditionally passed after any
584 /// user-defined but before post_link_objects. Standard platform
585 /// libraries that should be always be linked to, usually go here.
586 pub late_link_args: LinkArgs,
587 /// Linker arguments used in addition to `late_link_args` if at least one
588 /// Rust dependency is dynamically linked.
589 pub late_link_args_dynamic: LinkArgs,
590 /// Linker arguments used in addition to `late_link_args` if aall Rust
591 /// dependencies are statically linked.
592 pub late_link_args_static: LinkArgs,
593 /// Objects to link after all others, always found within the
595 pub post_link_objects: Vec<String>, // ... unconditionally
596 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
597 /// Linker arguments that are unconditionally passed *after* any
598 /// user-defined libraries.
599 pub post_link_args: LinkArgs,
601 /// Environment variables to be set for the linker invocation.
602 pub link_env: Vec<(String, String)>,
603 /// Environment variables to be removed for the linker invocation.
604 pub link_env_remove: Vec<String>,
606 /// Extra arguments to pass to the external assembler (when used)
607 pub asm_args: Vec<String>,
609 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
612 /// Default target features to pass to LLVM. These features will *always* be
613 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
614 /// -mattr=$features`.
615 pub features: String,
616 /// Whether dynamic linking is available on this target. Defaults to false.
617 pub dynamic_linking: bool,
618 /// If dynamic linking is available, whether only cdylibs are supported.
619 pub only_cdylib: bool,
620 /// Whether executables are available on this target. iOS, for example, only allows static
621 /// libraries. Defaults to false.
622 pub executables: bool,
623 /// Relocation model to use in object file. Corresponds to `llc
624 /// -relocation-model=$relocation_model`. Defaults to "pic".
625 pub relocation_model: String,
626 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
627 pub code_model: Option<String>,
628 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
629 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
630 pub tls_model: String,
631 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
632 pub disable_redzone: bool,
633 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
634 pub eliminate_frame_pointer: bool,
635 /// Emit each function in its own section. Defaults to true.
636 pub function_sections: bool,
637 /// String to prepend to the name of every dynamic library. Defaults to "lib".
638 pub dll_prefix: String,
639 /// String to append to the name of every dynamic library. Defaults to ".so".
640 pub dll_suffix: String,
641 /// String to append to the name of every executable.
642 pub exe_suffix: String,
643 /// String to prepend to the name of every static library. Defaults to "lib".
644 pub staticlib_prefix: String,
645 /// String to append to the name of every static library. Defaults to ".a".
646 pub staticlib_suffix: String,
647 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
648 pub target_family: Option<String>,
649 /// Whether the target toolchain's ABI supports returning small structs as an integer.
650 pub abi_return_struct_as_int: bool,
651 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
652 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
653 pub is_like_osx: bool,
654 /// Whether the target toolchain is like Solaris's.
655 /// Only useful for compiling against Illumos/Solaris,
656 /// as they have a different set of linker flags. Defaults to false.
657 pub is_like_solaris: bool,
658 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
659 /// only really used for figuring out how to find libraries, since Windows uses its own
660 /// library naming convention. Defaults to false.
661 pub is_like_windows: bool,
662 pub is_like_msvc: bool,
663 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
664 /// Defaults to false.
665 pub is_like_android: bool,
666 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
667 /// Emscripten toolchain.
668 /// Defaults to false.
669 pub is_like_emscripten: bool,
670 /// Whether the target toolchain is like Fuchsia's.
671 pub is_like_fuchsia: bool,
672 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
673 pub linker_is_gnu: bool,
674 /// The MinGW toolchain has a known issue that prevents it from correctly
675 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
676 /// symbol needs its own COMDAT section, weak linkage implies a large
677 /// number sections that easily exceeds the given limit for larger
678 /// codebases. Consequently we want a way to disallow weak linkage on some
680 pub allows_weak_linkage: bool,
681 /// Whether the linker support rpaths or not. Defaults to false.
683 /// Whether to disable linking to the default libraries, typically corresponds
684 /// to `-nodefaultlibs`. Defaults to true.
685 pub no_default_libraries: bool,
686 /// Dynamically linked executables can be compiled as position independent
687 /// if the default relocation model of position independent code is not
688 /// changed. This is a requirement to take advantage of ASLR, as otherwise
689 /// the functions in the executable are not randomized and can be used
690 /// during an exploit of a vulnerability in any code.
691 pub position_independent_executables: bool,
692 /// Determines if the target always requires using the PLT for indirect
693 /// library calls or not. This controls the default value of the `-Z plt` flag.
695 /// Either partial, full, or off. Full RELRO makes the dynamic linker
696 /// resolve all symbols at startup and marks the GOT read-only before
697 /// starting the program, preventing overwriting the GOT.
698 pub relro_level: RelroLevel,
699 /// Format that archives should be emitted in. This affects whether we use
700 /// LLVM to assemble an archive or fall back to the system linker, and
701 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
702 /// the system linker to be used.
703 pub archive_format: String,
704 /// Is asm!() allowed? Defaults to true.
706 /// Whether the runtime startup code requires the `main` function be passed
707 /// `argc` and `argv` values.
708 pub main_needs_argc_argv: bool,
710 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
712 pub has_elf_tls: bool,
713 // This is mainly for easy compatibility with emscripten.
714 // If we give emcc .o files that are actually .bc files it
716 pub obj_is_bitcode: bool,
718 /// Don't use this field; instead use the `.min_atomic_width()` method.
719 pub min_atomic_width: Option<u64>,
721 /// Don't use this field; instead use the `.max_atomic_width()` method.
722 pub max_atomic_width: Option<u64>,
724 /// Whether the target supports atomic CAS operations natively
725 pub atomic_cas: bool,
727 /// Panic strategy: "unwind" or "abort"
728 pub panic_strategy: PanicStrategy,
730 /// A blacklist of ABIs unsupported by the current target. Note that generic
731 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
732 pub abi_blacklist: Vec<Abi>,
734 /// Whether or not linking dylibs to a static CRT is allowed.
735 pub crt_static_allows_dylibs: bool,
736 /// Whether or not the CRT is statically linked by default.
737 pub crt_static_default: bool,
738 /// Whether or not crt-static is respected by the compiler (or is a no-op).
739 pub crt_static_respected: bool,
741 /// Whether or not stack probes (__rust_probestack) are enabled
742 pub stack_probes: bool,
744 /// The minimum alignment for global symbols.
745 pub min_global_align: Option<u64>,
747 /// Default number of codegen units to use in debug mode
748 pub default_codegen_units: Option<u64>,
750 /// Whether to generate trap instructions in places where optimization would
751 /// otherwise produce control flow that falls through into unrelated memory.
752 pub trap_unreachable: bool,
754 /// This target requires everything to be compiled with LTO to emit a final
755 /// executable, aka there is no native linker for this target.
756 pub requires_lto: bool,
758 /// This target has no support for threads.
759 pub singlethread: bool,
761 /// Whether library functions call lowering/optimization is disabled in LLVM
762 /// for this target unconditionally.
763 pub no_builtins: bool,
765 /// The codegen backend to use for this target, typically "llvm"
766 pub codegen_backend: String,
768 /// The default visibility for symbols in this target should be "hidden"
769 /// rather than "default"
770 pub default_hidden_visibility: bool,
772 /// Whether a .debug_gdb_scripts section will be added to the output object file
773 pub emit_debug_gdb_scripts: bool,
775 /// Whether or not to unconditionally `uwtable` attributes on functions,
776 /// typically because the platform needs to unwind for things like stack
778 pub requires_uwtable: bool,
780 /// Whether or not SIMD types are passed by reference in the Rust ABI,
781 /// typically required if a target can be compiled with a mixed set of
782 /// target features. This is `true` by default, and `false` for targets like
783 /// wasm32 where the whole program either has simd or not.
784 pub simd_types_indirect: bool,
786 /// Pass a list of symbol which should be exported in the dylib to the linker.
787 pub limit_rdylib_exports: bool,
789 /// If set, have the linker export exactly these symbols, instead of using
790 /// the usual logic to figure this out from the crate itself.
791 pub override_export_symbols: Option<Vec<String>>,
793 /// Determines how or whether the MergeFunctions LLVM pass should run for
794 /// this target. Either "disabled", "trampolines", or "aliases".
795 /// The MergeFunctions pass is generally useful, but some targets may need
796 /// to opt out. The default is "aliases".
798 /// Workaround for: https://github.com/rust-lang/rust/issues/57356
799 pub merge_functions: MergeFunctions,
801 /// Use platform dependent mcount function
802 pub target_mcount: String,
804 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
805 pub llvm_abiname: String,
807 /// Whether or not RelaxElfRelocation flag will be passed to the linker
808 pub relax_elf_relocations: bool,
810 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
811 pub llvm_args: Vec<String>,
814 impl Default for TargetOptions {
815 /// Creates a set of "sane defaults" for any target. This is still
816 /// incomplete, and if used for compilation, will certainly not work.
817 fn default() -> TargetOptions {
820 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
821 lld_flavor: LldFlavor::Ld,
822 pre_link_args: LinkArgs::new(),
823 pre_link_args_crt: LinkArgs::new(),
824 post_link_args: LinkArgs::new(),
825 asm_args: Vec::new(),
826 cpu: "generic".to_string(),
827 features: String::new(),
828 dynamic_linking: false,
831 relocation_model: "pic".to_string(),
833 tls_model: "global-dynamic".to_string(),
834 disable_redzone: false,
835 eliminate_frame_pointer: true,
836 function_sections: true,
837 dll_prefix: "lib".to_string(),
838 dll_suffix: ".so".to_string(),
839 exe_suffix: String::new(),
840 staticlib_prefix: "lib".to_string(),
841 staticlib_suffix: ".a".to_string(),
843 abi_return_struct_as_int: false,
845 is_like_solaris: false,
846 is_like_windows: false,
847 is_like_android: false,
848 is_like_emscripten: false,
850 is_like_fuchsia: false,
851 linker_is_gnu: false,
852 allows_weak_linkage: true,
854 no_default_libraries: true,
855 position_independent_executables: false,
857 relro_level: RelroLevel::None,
858 pre_link_objects_exe: Vec::new(),
859 pre_link_objects_exe_crt: Vec::new(),
860 pre_link_objects_dll: Vec::new(),
861 post_link_objects: Vec::new(),
862 post_link_objects_crt: Vec::new(),
863 late_link_args: LinkArgs::new(),
864 late_link_args_dynamic: LinkArgs::new(),
865 late_link_args_static: LinkArgs::new(),
866 link_env: Vec::new(),
867 link_env_remove: Vec::new(),
868 archive_format: "gnu".to_string(),
869 main_needs_argc_argv: true,
872 obj_is_bitcode: false,
873 min_atomic_width: None,
874 max_atomic_width: None,
876 panic_strategy: PanicStrategy::Unwind,
877 abi_blacklist: vec![],
878 crt_static_allows_dylibs: false,
879 crt_static_default: false,
880 crt_static_respected: false,
882 min_global_align: None,
883 default_codegen_units: None,
884 trap_unreachable: true,
888 codegen_backend: "llvm".to_string(),
889 default_hidden_visibility: false,
890 emit_debug_gdb_scripts: true,
891 requires_uwtable: false,
892 simd_types_indirect: true,
893 limit_rdylib_exports: true,
894 override_export_symbols: None,
895 merge_functions: MergeFunctions::Aliases,
896 target_mcount: "mcount".to_string(),
897 llvm_abiname: "".to_string(),
898 relax_elf_relocations: false,
905 /// Given a function ABI, turn it into the correct ABI for this target.
906 pub fn adjust_abi(&self, abi: Abi) -> Abi {
909 if self.options.is_like_windows && self.arch == "x86" {
915 // These ABI kinds are ignored on non-x86 Windows targets.
916 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
917 // and the individual pages for __stdcall et al.
918 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
919 if self.options.is_like_windows && self.arch != "x86" { Abi::C } else { abi }
922 if self.arch == "x86_64" {
932 /// Minimum integer size in bits that this target can perform atomic
934 pub fn min_atomic_width(&self) -> u64 {
935 self.options.min_atomic_width.unwrap_or(8)
938 /// Maximum integer size in bits that this target can perform atomic
940 pub fn max_atomic_width(&self) -> u64 {
941 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
944 pub fn is_abi_supported(&self, abi: Abi) -> bool {
945 abi.generic() || !self.options.abi_blacklist.contains(&abi)
948 /// Loads a target descriptor from a JSON object.
949 pub fn from_json(obj: Json) -> TargetResult {
950 // While ugly, this code must remain this way to retain
951 // compatibility with existing JSON fields and the internal
952 // expected naming of the Target and TargetOptions structs.
953 // To ensure compatibility is retained, the built-in targets
954 // are round-tripped through this code to catch cases where
955 // the JSON parser is not updated to match the structs.
957 let get_req_field = |name: &str| {
959 .map(|s| s.as_string())
960 .and_then(|os| os.map(|s| s.to_string()))
961 .ok_or_else(|| format!("Field {} in target specification is required", name))
964 let get_opt_field = |name: &str, default: &str| {
966 .and_then(|s| s.as_string())
967 .map(|s| s.to_string())
968 .unwrap_or_else(|| default.to_string())
971 let mut base = Target {
972 llvm_target: get_req_field("llvm-target")?,
973 target_endian: get_req_field("target-endian")?,
974 target_pointer_width: get_req_field("target-pointer-width")?,
975 target_c_int_width: get_req_field("target-c-int-width")?,
976 data_layout: get_req_field("data-layout")?,
977 arch: get_req_field("arch")?,
978 target_os: get_req_field("os")?,
979 target_env: get_opt_field("env", ""),
980 target_vendor: get_opt_field("vendor", "unknown"),
981 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
982 .ok_or_else(|| format!("linker flavor must be {}", LinkerFlavor::one_of()))?,
983 options: Default::default(),
987 ($key_name:ident) => ( {
988 let name = (stringify!($key_name)).replace("_", "-");
989 obj.find(&name[..]).map(|o| o.as_string()
990 .map(|s| base.options.$key_name = s.to_string()));
992 ($key_name:ident, bool) => ( {
993 let name = (stringify!($key_name)).replace("_", "-");
995 .map(|o| o.as_boolean()
996 .map(|s| base.options.$key_name = s));
998 ($key_name:ident, Option<u64>) => ( {
999 let name = (stringify!($key_name)).replace("_", "-");
1002 .map(|s| base.options.$key_name = Some(s)));
1004 ($key_name:ident, MergeFunctions) => ( {
1005 let name = (stringify!($key_name)).replace("_", "-");
1006 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1007 match s.parse::<MergeFunctions>() {
1008 Ok(mergefunc) => base.options.$key_name = mergefunc,
1009 _ => return Some(Err(format!("'{}' is not a valid value for \
1010 merge-functions. Use 'disabled', \
1011 'trampolines', or 'aliases'.",
1015 })).unwrap_or(Ok(()))
1017 ($key_name:ident, PanicStrategy) => ( {
1018 let name = (stringify!($key_name)).replace("_", "-");
1019 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1021 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
1022 "abort" => base.options.$key_name = PanicStrategy::Abort,
1023 _ => return Some(Err(format!("'{}' is not a valid value for \
1024 panic-strategy. Use 'unwind' or 'abort'.",
1028 })).unwrap_or(Ok(()))
1030 ($key_name:ident, RelroLevel) => ( {
1031 let name = (stringify!($key_name)).replace("_", "-");
1032 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1033 match s.parse::<RelroLevel>() {
1034 Ok(level) => base.options.$key_name = level,
1035 _ => return Some(Err(format!("'{}' is not a valid value for \
1036 relro-level. Use 'full', 'partial, or 'off'.",
1040 })).unwrap_or(Ok(()))
1042 ($key_name:ident, list) => ( {
1043 let name = (stringify!($key_name)).replace("_", "-");
1044 obj.find(&name[..]).map(|o| o.as_array()
1045 .map(|v| base.options.$key_name = v.iter()
1046 .map(|a| a.as_string().unwrap().to_string()).collect()
1050 ($key_name:ident, opt_list) => ( {
1051 let name = (stringify!($key_name)).replace("_", "-");
1052 obj.find(&name[..]).map(|o| o.as_array()
1053 .map(|v| base.options.$key_name = Some(v.iter()
1054 .map(|a| a.as_string().unwrap().to_string()).collect())
1058 ($key_name:ident, optional) => ( {
1059 let name = (stringify!($key_name)).replace("_", "-");
1060 if let Some(o) = obj.find(&name[..]) {
1061 base.options.$key_name = o
1063 .map(|s| s.to_string() );
1066 ($key_name:ident, LldFlavor) => ( {
1067 let name = (stringify!($key_name)).replace("_", "-");
1068 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1069 if let Some(flavor) = LldFlavor::from_str(&s) {
1070 base.options.$key_name = flavor;
1072 return Some(Err(format!(
1073 "'{}' is not a valid value for lld-flavor. \
1074 Use 'darwin', 'gnu', 'link' or 'wasm.",
1078 })).unwrap_or(Ok(()))
1080 ($key_name:ident, LinkerFlavor) => ( {
1081 let name = (stringify!($key_name)).replace("_", "-");
1082 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
1083 LinkerFlavor::from_str(&s).ok_or_else(|| {
1084 Err(format!("'{}' is not a valid value for linker-flavor. \
1085 Use 'em', 'gcc', 'ld' or 'msvc.", s))
1087 })).unwrap_or(Ok(()))
1089 ($key_name:ident, link_args) => ( {
1090 let name = (stringify!($key_name)).replace("_", "-");
1091 if let Some(val) = obj.find(&name[..]) {
1092 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1093 JSON object with fields per linker-flavor.", name))?;
1094 let mut args = LinkArgs::new();
1096 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1097 format!("{}: '{}' is not a valid value for linker-flavor. \
1098 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1101 let v = v.as_array().ok_or_else(||
1102 format!("{}.{}: expected a JSON array", name, k)
1103 )?.iter().enumerate()
1105 let s = s.as_string().ok_or_else(||
1106 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1109 .collect::<Result<Vec<_>, String>>()?;
1111 args.insert(flavor, v);
1113 base.options.$key_name = args;
1116 ($key_name:ident, env) => ( {
1117 let name = (stringify!($key_name)).replace("_", "-");
1118 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1120 if let Some(s) = o.as_string() {
1121 let p = s.split('=').collect::<Vec<_>>();
1123 let k = p[0].to_string();
1124 let v = p[1].to_string();
1125 base.options.$key_name.push((k, v));
1133 key!(is_builtin, bool);
1134 key!(linker, optional);
1135 key!(lld_flavor, LldFlavor)?;
1136 key!(pre_link_args, link_args);
1137 key!(pre_link_args_crt, link_args);
1138 key!(pre_link_objects_exe, list);
1139 key!(pre_link_objects_exe_crt, list);
1140 key!(pre_link_objects_dll, list);
1141 key!(late_link_args, link_args);
1142 key!(late_link_args_dynamic, link_args);
1143 key!(late_link_args_static, link_args);
1144 key!(post_link_objects, list);
1145 key!(post_link_objects_crt, list);
1146 key!(post_link_args, link_args);
1147 key!(link_env, env);
1148 key!(link_env_remove, list);
1149 key!(asm_args, list);
1152 key!(dynamic_linking, bool);
1153 key!(only_cdylib, bool);
1154 key!(executables, bool);
1155 key!(relocation_model);
1156 key!(code_model, optional);
1158 key!(disable_redzone, bool);
1159 key!(eliminate_frame_pointer, bool);
1160 key!(function_sections, bool);
1164 key!(staticlib_prefix);
1165 key!(staticlib_suffix);
1166 key!(target_family, optional);
1167 key!(abi_return_struct_as_int, bool);
1168 key!(is_like_osx, bool);
1169 key!(is_like_solaris, bool);
1170 key!(is_like_windows, bool);
1171 key!(is_like_msvc, bool);
1172 key!(is_like_emscripten, bool);
1173 key!(is_like_android, bool);
1174 key!(is_like_fuchsia, bool);
1175 key!(linker_is_gnu, bool);
1176 key!(allows_weak_linkage, bool);
1177 key!(has_rpath, bool);
1178 key!(no_default_libraries, bool);
1179 key!(position_independent_executables, bool);
1180 key!(needs_plt, bool);
1181 key!(relro_level, RelroLevel)?;
1182 key!(archive_format);
1183 key!(allow_asm, bool);
1184 key!(main_needs_argc_argv, bool);
1185 key!(has_elf_tls, bool);
1186 key!(obj_is_bitcode, bool);
1187 key!(max_atomic_width, Option<u64>);
1188 key!(min_atomic_width, Option<u64>);
1189 key!(atomic_cas, bool);
1190 key!(panic_strategy, PanicStrategy)?;
1191 key!(crt_static_allows_dylibs, bool);
1192 key!(crt_static_default, bool);
1193 key!(crt_static_respected, bool);
1194 key!(stack_probes, bool);
1195 key!(min_global_align, Option<u64>);
1196 key!(default_codegen_units, Option<u64>);
1197 key!(trap_unreachable, bool);
1198 key!(requires_lto, bool);
1199 key!(singlethread, bool);
1200 key!(no_builtins, bool);
1201 key!(codegen_backend);
1202 key!(default_hidden_visibility, bool);
1203 key!(emit_debug_gdb_scripts, bool);
1204 key!(requires_uwtable, bool);
1205 key!(simd_types_indirect, bool);
1206 key!(limit_rdylib_exports, bool);
1207 key!(override_export_symbols, opt_list);
1208 key!(merge_functions, MergeFunctions)?;
1209 key!(target_mcount);
1211 key!(relax_elf_relocations, bool);
1212 key!(llvm_args, list);
1214 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1215 for name in array.iter().filter_map(|abi| abi.as_string()) {
1216 match lookup_abi(name) {
1220 "The ABI \"{}\" is considered to be supported on \
1221 all targets and cannot be blacklisted",
1226 base.options.abi_blacklist.push(abi)
1229 return Err(format!("Unknown ABI \"{}\" in target specification", name));
1238 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1239 /// triple. Note that it could also just be a bare filename already, so also
1240 /// check for that. If one of the hardcoded targets we know about, just
1241 /// return it directly.
1243 /// The error string could come from any of the APIs called, including
1244 /// filesystem access and JSON decoding.
1245 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1246 use rustc_serialize::json;
1250 fn load_file(path: &Path) -> Result<Target, String> {
1251 let contents = fs::read(path).map_err(|e| e.to_string())?;
1252 let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1253 Target::from_json(obj)
1256 match *target_triple {
1257 TargetTriple::TargetTriple(ref target_triple) => {
1258 // check if triple is in list of supported targets
1259 match load_specific(target_triple) {
1260 Ok(t) => return Ok(t),
1261 Err(LoadTargetError::BuiltinTargetNotFound(_)) => (),
1262 Err(LoadTargetError::Other(e)) => return Err(e),
1265 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1267 let mut target = target_triple.to_string();
1268 target.push_str(".json");
1269 PathBuf::from(target)
1272 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1274 // FIXME 16351: add a sane default search path?
1276 for dir in env::split_paths(&target_path) {
1277 let p = dir.join(&path);
1279 return load_file(&p);
1282 Err(format!("Could not find specification for target {:?}", target_triple))
1284 TargetTriple::TargetPath(ref target_path) => {
1285 if target_path.is_file() {
1286 return load_file(&target_path);
1288 Err(format!("Target path {:?} is not a valid file", target_path))
1294 fn check_consistency(&self) {
1295 // Check that LLD with the given flavor is treated identically to the linker it emulates.
1296 // If you target really needs to deviate from the rules below, whitelist it
1297 // and document the reasons.
1299 self.linker_flavor == LinkerFlavor::Msvc
1300 || self.linker_flavor == LinkerFlavor::Lld(LldFlavor::Link),
1301 self.options.lld_flavor == LldFlavor::Link,
1304 &self.options.pre_link_args,
1305 &self.options.pre_link_args_crt,
1306 &self.options.late_link_args,
1307 &self.options.late_link_args_dynamic,
1308 &self.options.late_link_args_static,
1309 &self.options.post_link_args,
1312 args.get(&LinkerFlavor::Msvc),
1313 args.get(&LinkerFlavor::Lld(LldFlavor::Link)),
1315 if args.contains_key(&LinkerFlavor::Msvc) {
1316 assert_eq!(self.options.lld_flavor, LldFlavor::Link);
1322 impl ToJson for Target {
1323 fn to_json(&self) -> Json {
1324 let mut d = BTreeMap::new();
1325 let default: TargetOptions = Default::default();
1327 macro_rules! target_val {
1329 let name = (stringify!($attr)).replace("_", "-");
1330 d.insert(name, self.$attr.to_json());
1332 ($attr:ident, $key_name:expr) => {{
1333 let name = $key_name;
1334 d.insert(name.to_string(), self.$attr.to_json());
1338 macro_rules! target_option_val {
1340 let name = (stringify!($attr)).replace("_", "-");
1341 if default.$attr != self.options.$attr {
1342 d.insert(name, self.options.$attr.to_json());
1345 ($attr:ident, $key_name:expr) => {{
1346 let name = $key_name;
1347 if default.$attr != self.options.$attr {
1348 d.insert(name.to_string(), self.options.$attr.to_json());
1351 (link_args - $attr:ident) => {{
1352 let name = (stringify!($attr)).replace("_", "-");
1353 if default.$attr != self.options.$attr {
1358 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1359 .collect::<BTreeMap<_, _>>();
1360 d.insert(name, obj.to_json());
1363 (env - $attr:ident) => {{
1364 let name = (stringify!($attr)).replace("_", "-");
1365 if default.$attr != self.options.$attr {
1370 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1371 .collect::<Vec<_>>();
1372 d.insert(name, obj.to_json());
1377 target_val!(llvm_target);
1378 target_val!(target_endian);
1379 target_val!(target_pointer_width);
1380 target_val!(target_c_int_width);
1382 target_val!(target_os, "os");
1383 target_val!(target_env, "env");
1384 target_val!(target_vendor, "vendor");
1385 target_val!(data_layout);
1386 target_val!(linker_flavor);
1388 target_option_val!(is_builtin);
1389 target_option_val!(linker);
1390 target_option_val!(lld_flavor);
1391 target_option_val!(link_args - pre_link_args);
1392 target_option_val!(link_args - pre_link_args_crt);
1393 target_option_val!(pre_link_objects_exe);
1394 target_option_val!(pre_link_objects_exe_crt);
1395 target_option_val!(pre_link_objects_dll);
1396 target_option_val!(link_args - late_link_args);
1397 target_option_val!(link_args - late_link_args_dynamic);
1398 target_option_val!(link_args - late_link_args_static);
1399 target_option_val!(post_link_objects);
1400 target_option_val!(post_link_objects_crt);
1401 target_option_val!(link_args - post_link_args);
1402 target_option_val!(env - link_env);
1403 target_option_val!(link_env_remove);
1404 target_option_val!(asm_args);
1405 target_option_val!(cpu);
1406 target_option_val!(features);
1407 target_option_val!(dynamic_linking);
1408 target_option_val!(only_cdylib);
1409 target_option_val!(executables);
1410 target_option_val!(relocation_model);
1411 target_option_val!(code_model);
1412 target_option_val!(tls_model);
1413 target_option_val!(disable_redzone);
1414 target_option_val!(eliminate_frame_pointer);
1415 target_option_val!(function_sections);
1416 target_option_val!(dll_prefix);
1417 target_option_val!(dll_suffix);
1418 target_option_val!(exe_suffix);
1419 target_option_val!(staticlib_prefix);
1420 target_option_val!(staticlib_suffix);
1421 target_option_val!(target_family);
1422 target_option_val!(abi_return_struct_as_int);
1423 target_option_val!(is_like_osx);
1424 target_option_val!(is_like_solaris);
1425 target_option_val!(is_like_windows);
1426 target_option_val!(is_like_msvc);
1427 target_option_val!(is_like_emscripten);
1428 target_option_val!(is_like_android);
1429 target_option_val!(is_like_fuchsia);
1430 target_option_val!(linker_is_gnu);
1431 target_option_val!(allows_weak_linkage);
1432 target_option_val!(has_rpath);
1433 target_option_val!(no_default_libraries);
1434 target_option_val!(position_independent_executables);
1435 target_option_val!(needs_plt);
1436 target_option_val!(relro_level);
1437 target_option_val!(archive_format);
1438 target_option_val!(allow_asm);
1439 target_option_val!(main_needs_argc_argv);
1440 target_option_val!(has_elf_tls);
1441 target_option_val!(obj_is_bitcode);
1442 target_option_val!(min_atomic_width);
1443 target_option_val!(max_atomic_width);
1444 target_option_val!(atomic_cas);
1445 target_option_val!(panic_strategy);
1446 target_option_val!(crt_static_allows_dylibs);
1447 target_option_val!(crt_static_default);
1448 target_option_val!(crt_static_respected);
1449 target_option_val!(stack_probes);
1450 target_option_val!(min_global_align);
1451 target_option_val!(default_codegen_units);
1452 target_option_val!(trap_unreachable);
1453 target_option_val!(requires_lto);
1454 target_option_val!(singlethread);
1455 target_option_val!(no_builtins);
1456 target_option_val!(codegen_backend);
1457 target_option_val!(default_hidden_visibility);
1458 target_option_val!(emit_debug_gdb_scripts);
1459 target_option_val!(requires_uwtable);
1460 target_option_val!(simd_types_indirect);
1461 target_option_val!(limit_rdylib_exports);
1462 target_option_val!(override_export_symbols);
1463 target_option_val!(merge_functions);
1464 target_option_val!(target_mcount);
1465 target_option_val!(llvm_abiname);
1466 target_option_val!(relax_elf_relocations);
1467 target_option_val!(llvm_args);
1469 if default.abi_blacklist != self.options.abi_blacklist {
1471 "abi-blacklist".to_string(),
1475 .map(|&name| Abi::name(name).to_json())
1476 .collect::<Vec<_>>()
1485 /// Either a target triple string or a path to a JSON file.
1486 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1487 pub enum TargetTriple {
1488 TargetTriple(String),
1489 TargetPath(PathBuf),
1493 /// Creates a target triple from the passed target triple string.
1494 pub fn from_triple(triple: &str) -> Self {
1495 TargetTriple::TargetTriple(triple.to_string())
1498 /// Creates a target triple from the passed target path.
1499 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1500 let canonicalized_path = path.canonicalize()?;
1501 Ok(TargetTriple::TargetPath(canonicalized_path))
1504 /// Returns a string triple for this target.
1506 /// If this target is a path, the file name (without extension) is returned.
1507 pub fn triple(&self) -> &str {
1509 TargetTriple::TargetTriple(ref triple) => triple,
1510 TargetTriple::TargetPath(ref path) => path
1512 .expect("target path must not be empty")
1514 .expect("target path must be valid unicode"),
1518 /// Returns an extended string triple for this target.
1520 /// If this target is a path, a hash of the path is appended to the triple returned
1522 pub fn debug_triple(&self) -> String {
1523 use std::collections::hash_map::DefaultHasher;
1524 use std::hash::{Hash, Hasher};
1526 let triple = self.triple();
1527 if let TargetTriple::TargetPath(ref path) = *self {
1528 let mut hasher = DefaultHasher::new();
1529 path.hash(&mut hasher);
1530 let hash = hasher.finish();
1531 format!("{}-{}", triple, hash)
1538 impl fmt::Display for TargetTriple {
1539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1540 write!(f, "{}", self.debug_triple())