1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
9 //! # Using custom targets
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
26 //! # Defining a new target
28 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
37 use crate::spec::abi::{lookup as lookup_abi, Abi};
38 use rustc_serialize::json::{Json, ToJson};
39 use std::collections::BTreeMap;
40 use std::path::{Path, PathBuf};
41 use std::str::FromStr;
44 use rustc_macros::HashStable_Generic;
57 mod hermit_kernel_base;
61 mod linux_kernel_base;
74 mod windows_msvc_base;
75 mod windows_uwp_gnu_base;
76 mod windows_uwp_msvc_base;
78 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
79 pub enum LinkerFlavor {
88 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
97 fn from_str(s: &str) -> Option<Self> {
99 "darwin" => LldFlavor::Ld64,
100 "gnu" => LldFlavor::Ld,
101 "link" => LldFlavor::Link,
102 "wasm" => LldFlavor::Wasm,
108 impl ToJson for LldFlavor {
109 fn to_json(&self) -> Json {
111 LldFlavor::Ld64 => "darwin",
112 LldFlavor::Ld => "gnu",
113 LldFlavor::Link => "link",
114 LldFlavor::Wasm => "wasm",
120 impl ToJson for LinkerFlavor {
121 fn to_json(&self) -> Json {
122 self.desc().to_json()
125 macro_rules! flavor_mappings {
126 ($((($($flavor:tt)*), $string:expr),)*) => (
128 pub const fn one_of() -> &'static str {
129 concat!("one of: ", $($string, " ",)*)
132 pub fn from_str(s: &str) -> Option<Self> {
134 $($string => $($flavor)*,)*
139 pub fn desc(&self) -> &str {
141 $($($flavor)* => $string,)*
149 ((LinkerFlavor::Em), "em"),
150 ((LinkerFlavor::Gcc), "gcc"),
151 ((LinkerFlavor::Ld), "ld"),
152 ((LinkerFlavor::Msvc), "msvc"),
153 ((LinkerFlavor::PtxLinker), "ptx-linker"),
154 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
155 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
156 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
157 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
160 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable, HashStable_Generic)]
161 pub enum PanicStrategy {
167 pub fn desc(&self) -> &str {
169 PanicStrategy::Unwind => "unwind",
170 PanicStrategy::Abort => "abort",
175 impl ToJson for PanicStrategy {
176 fn to_json(&self) -> Json {
178 PanicStrategy::Abort => "abort".to_json(),
179 PanicStrategy::Unwind => "unwind".to_json(),
184 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
185 pub enum RelroLevel {
193 pub fn desc(&self) -> &str {
195 RelroLevel::Full => "full",
196 RelroLevel::Partial => "partial",
197 RelroLevel::Off => "off",
198 RelroLevel::None => "none",
203 impl FromStr for RelroLevel {
206 fn from_str(s: &str) -> Result<RelroLevel, ()> {
208 "full" => Ok(RelroLevel::Full),
209 "partial" => Ok(RelroLevel::Partial),
210 "off" => Ok(RelroLevel::Off),
211 "none" => Ok(RelroLevel::None),
217 impl ToJson for RelroLevel {
218 fn to_json(&self) -> Json {
220 RelroLevel::Full => "full".to_json(),
221 RelroLevel::Partial => "partial".to_json(),
222 RelroLevel::Off => "off".to_json(),
223 RelroLevel::None => "None".to_json(),
228 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
229 pub enum MergeFunctions {
235 impl MergeFunctions {
236 pub fn desc(&self) -> &str {
238 MergeFunctions::Disabled => "disabled",
239 MergeFunctions::Trampolines => "trampolines",
240 MergeFunctions::Aliases => "aliases",
245 impl FromStr for MergeFunctions {
248 fn from_str(s: &str) -> Result<MergeFunctions, ()> {
250 "disabled" => Ok(MergeFunctions::Disabled),
251 "trampolines" => Ok(MergeFunctions::Trampolines),
252 "aliases" => Ok(MergeFunctions::Aliases),
258 impl ToJson for MergeFunctions {
259 fn to_json(&self) -> Json {
261 MergeFunctions::Disabled => "disabled".to_json(),
262 MergeFunctions::Trampolines => "trampolines".to_json(),
263 MergeFunctions::Aliases => "aliases".to_json(),
268 pub enum LoadTargetError {
269 BuiltinTargetNotFound(String),
273 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
274 pub type TargetResult = Result<Target, String>;
276 macro_rules! supported_targets {
277 ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
280 /// List of supported targets
281 const TARGETS: &[&str] = &[$($($triple),+),+];
283 fn load_specific(target: &str) -> Result<Target, LoadTargetError> {
287 let mut t = $module::target()
288 .map_err(LoadTargetError::Other)?;
289 t.options.is_builtin = true;
291 // round-trip through the JSON parser to ensure at
292 // run-time that the parser works correctly
293 t = Target::from_json(t.to_json())
294 .map_err(LoadTargetError::Other)?;
295 debug!("got builtin target: {:?}", t);
299 _ => Err(LoadTargetError::BuiltinTargetNotFound(
300 format!("Unable to find target: {}", target)))
304 pub fn get_targets() -> impl Iterator<Item = String> {
305 TARGETS.iter().filter_map(|t| -> Option<String> {
307 .and(Ok(t.to_string()))
316 // Cannot put this into a separate file without duplication, make an exception.
320 tests_impl::test_target(super::$module::target());
328 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
329 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
330 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
331 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
332 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
333 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
334 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
335 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
336 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
337 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
338 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
339 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
340 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
341 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
342 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
343 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
344 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
345 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
346 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
347 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
348 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
349 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
350 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
351 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
352 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
353 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
354 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
355 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
356 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
357 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
358 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
359 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
360 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
361 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
362 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
363 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
364 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
365 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
366 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
367 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
368 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
369 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
370 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
371 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
372 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
374 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
375 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
377 ("i686-linux-android", i686_linux_android),
378 ("x86_64-linux-android", x86_64_linux_android),
379 ("arm-linux-androideabi", arm_linux_androideabi),
380 ("armv7-linux-androideabi", armv7_linux_androideabi),
381 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
382 ("aarch64-linux-android", aarch64_linux_android),
384 ("x86_64-linux-kernel", x86_64_linux_kernel),
386 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
387 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
388 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
389 ("i686-unknown-freebsd", i686_unknown_freebsd),
390 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
391 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
393 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
395 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
396 ("i686-unknown-openbsd", i686_unknown_openbsd),
397 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
398 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
400 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
401 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
402 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
403 ("i686-unknown-netbsd", i686_unknown_netbsd),
404 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
405 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
406 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
407 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
409 ("i686-unknown-haiku", i686_unknown_haiku),
410 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
412 ("x86_64-apple-darwin", x86_64_apple_darwin),
413 ("i686-apple-darwin", i686_apple_darwin),
415 ("aarch64-fuchsia", aarch64_fuchsia),
416 ("x86_64-fuchsia", x86_64_fuchsia),
418 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
420 ("aarch64-unknown-redox", aarch64_unknown_redox),
421 ("x86_64-unknown-redox", x86_64_unknown_redox),
423 ("i386-apple-ios", i386_apple_ios),
424 ("x86_64-apple-ios", x86_64_apple_ios),
425 ("aarch64-apple-ios", aarch64_apple_ios),
426 ("armv7-apple-ios", armv7_apple_ios),
427 ("armv7s-apple-ios", armv7s_apple_ios),
428 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
429 ("aarch64-apple-tvos", aarch64_apple_tvos),
430 ("x86_64-apple-tvos", x86_64_apple_tvos),
432 ("armebv7r-none-eabi", armebv7r_none_eabi),
433 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
434 ("armv7r-none-eabi", armv7r_none_eabi),
435 ("armv7r-none-eabihf", armv7r_none_eabihf),
437 // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons.
438 // (See <https://github.com/rust-lang/rust/issues/40531>.)
439 ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris),
440 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
442 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
444 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
445 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
446 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
447 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
449 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
450 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
451 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
452 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
453 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
454 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
455 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
456 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
458 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
459 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
460 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
461 ("wasm32-wasi", wasm32_wasi),
463 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
464 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
465 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
466 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
467 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
468 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
469 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
471 ("armv7a-none-eabi", armv7a_none_eabi),
472 ("armv7a-none-eabihf", armv7a_none_eabihf),
474 ("msp430-none-elf", msp430_none_elf),
476 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
477 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
478 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
479 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
481 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
482 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
483 ("x86_64-unknown-hermit-kernel", x86_64_unknown_hermit_kernel),
485 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
486 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
487 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
488 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
489 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
490 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
492 ("aarch64-unknown-none", aarch64_unknown_none),
493 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
495 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
497 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
498 ("i686-unknown-uefi", i686_unknown_uefi),
500 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
502 ("i686-wrs-vxworks", i686_wrs_vxworks),
503 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
504 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
505 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
506 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
507 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
508 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
511 /// Everything `rustc` knows about how to compile for a specific target.
513 /// Every field here must be specified, and has no default value.
514 #[derive(PartialEq, Clone, Debug)]
516 /// Target triple to pass to LLVM.
517 pub llvm_target: String,
518 /// String to use as the `target_endian` `cfg` variable.
519 pub target_endian: String,
520 /// String to use as the `target_pointer_width` `cfg` variable.
521 pub target_pointer_width: String,
522 /// Width of c_int type
523 pub target_c_int_width: String,
524 /// OS name to use for conditional compilation.
525 pub target_os: String,
526 /// Environment name to use for conditional compilation.
527 pub target_env: String,
528 /// Vendor name to use for conditional compilation.
529 pub target_vendor: String,
530 /// Architecture to use for ABI considerations. Valid options include: "x86",
531 /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
533 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
534 pub data_layout: String,
535 /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
536 /// on the command line.
537 pub linker_flavor: LinkerFlavor,
538 /// Optional settings with defaults.
539 pub options: TargetOptions,
542 pub trait HasTargetSpec {
543 fn target_spec(&self) -> &Target;
546 impl HasTargetSpec for Target {
547 fn target_spec(&self) -> &Target {
552 /// Optional aspects of a target specification.
554 /// This has an implementation of `Default`, see each field for what the default is. In general,
555 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
556 #[derive(PartialEq, Clone, Debug)]
557 pub struct TargetOptions {
558 /// Whether the target is built-in or loaded from a custom target specification.
559 pub is_builtin: bool,
562 pub linker: Option<String>,
564 /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
565 /// without clarifying its flavor in any way.
566 pub lld_flavor: LldFlavor,
568 /// Linker arguments that are passed *before* any user-defined libraries.
569 pub pre_link_args: LinkArgs, // ... unconditionally
570 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
571 /// Objects to link before all others, always found within the
573 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
574 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
575 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
576 /// Linker arguments that are unconditionally passed after any
577 /// user-defined but before post_link_objects. Standard platform
578 /// libraries that should be always be linked to, usually go here.
579 pub late_link_args: LinkArgs,
580 /// Linker arguments used in addition to `late_link_args` if at least one
581 /// Rust dependency is dynamically linked.
582 pub late_link_args_dynamic: LinkArgs,
583 /// Linker arguments used in addition to `late_link_args` if aall Rust
584 /// dependencies are statically linked.
585 pub late_link_args_static: LinkArgs,
586 /// Objects to link after all others, always found within the
588 pub post_link_objects: Vec<String>, // ... unconditionally
589 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
590 /// Linker arguments that are unconditionally passed *after* any
591 /// user-defined libraries.
592 pub post_link_args: LinkArgs,
594 /// Environment variables to be set for the linker invocation.
595 pub link_env: Vec<(String, String)>,
596 /// Environment variables to be removed for the linker invocation.
597 pub link_env_remove: Vec<String>,
599 /// Extra arguments to pass to the external assembler (when used)
600 pub asm_args: Vec<String>,
602 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
605 /// Default target features to pass to LLVM. These features will *always* be
606 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
607 /// -mattr=$features`.
608 pub features: String,
609 /// Whether dynamic linking is available on this target. Defaults to false.
610 pub dynamic_linking: bool,
611 /// If dynamic linking is available, whether only cdylibs are supported.
612 pub only_cdylib: bool,
613 /// Whether executables are available on this target. iOS, for example, only allows static
614 /// libraries. Defaults to false.
615 pub executables: bool,
616 /// Relocation model to use in object file. Corresponds to `llc
617 /// -relocation-model=$relocation_model`. Defaults to "pic".
618 pub relocation_model: String,
619 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
620 pub code_model: Option<String>,
621 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
622 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
623 pub tls_model: String,
624 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
625 pub disable_redzone: bool,
626 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
627 pub eliminate_frame_pointer: bool,
628 /// Emit each function in its own section. Defaults to true.
629 pub function_sections: bool,
630 /// String to prepend to the name of every dynamic library. Defaults to "lib".
631 pub dll_prefix: String,
632 /// String to append to the name of every dynamic library. Defaults to ".so".
633 pub dll_suffix: String,
634 /// String to append to the name of every executable.
635 pub exe_suffix: String,
636 /// String to prepend to the name of every static library. Defaults to "lib".
637 pub staticlib_prefix: String,
638 /// String to append to the name of every static library. Defaults to ".a".
639 pub staticlib_suffix: String,
640 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
641 pub target_family: Option<String>,
642 /// Whether the target toolchain's ABI supports returning small structs as an integer.
643 pub abi_return_struct_as_int: bool,
644 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
645 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
646 pub is_like_osx: bool,
647 /// Whether the target toolchain is like Solaris's.
648 /// Only useful for compiling against Illumos/Solaris,
649 /// as they have a different set of linker flags. Defaults to false.
650 pub is_like_solaris: bool,
651 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
652 /// only really used for figuring out how to find libraries, since Windows uses its own
653 /// library naming convention. Defaults to false.
654 pub is_like_windows: bool,
655 pub is_like_msvc: bool,
656 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
657 /// Defaults to false.
658 pub is_like_android: bool,
659 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
660 /// Emscripten toolchain.
661 /// Defaults to false.
662 pub is_like_emscripten: bool,
663 /// Whether the target toolchain is like Fuchsia's.
664 pub is_like_fuchsia: bool,
665 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
666 pub linker_is_gnu: bool,
667 /// The MinGW toolchain has a known issue that prevents it from correctly
668 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
669 /// symbol needs its own COMDAT section, weak linkage implies a large
670 /// number sections that easily exceeds the given limit for larger
671 /// codebases. Consequently we want a way to disallow weak linkage on some
673 pub allows_weak_linkage: bool,
674 /// Whether the linker support rpaths or not. Defaults to false.
676 /// Whether to disable linking to the default libraries, typically corresponds
677 /// to `-nodefaultlibs`. Defaults to true.
678 pub no_default_libraries: bool,
679 /// Dynamically linked executables can be compiled as position independent
680 /// if the default relocation model of position independent code is not
681 /// changed. This is a requirement to take advantage of ASLR, as otherwise
682 /// the functions in the executable are not randomized and can be used
683 /// during an exploit of a vulnerability in any code.
684 pub position_independent_executables: bool,
685 /// Determines if the target always requires using the PLT for indirect
686 /// library calls or not. This controls the default value of the `-Z plt` flag.
688 /// Either partial, full, or off. Full RELRO makes the dynamic linker
689 /// resolve all symbols at startup and marks the GOT read-only before
690 /// starting the program, preventing overwriting the GOT.
691 pub relro_level: RelroLevel,
692 /// Format that archives should be emitted in. This affects whether we use
693 /// LLVM to assemble an archive or fall back to the system linker, and
694 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
695 /// the system linker to be used.
696 pub archive_format: String,
697 /// Is asm!() allowed? Defaults to true.
699 /// Whether the runtime startup code requires the `main` function be passed
700 /// `argc` and `argv` values.
701 pub main_needs_argc_argv: bool,
703 /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
705 pub has_elf_tls: bool,
706 // This is mainly for easy compatibility with emscripten.
707 // If we give emcc .o files that are actually .bc files it
709 pub obj_is_bitcode: bool,
711 /// Don't use this field; instead use the `.min_atomic_width()` method.
712 pub min_atomic_width: Option<u64>,
714 /// Don't use this field; instead use the `.max_atomic_width()` method.
715 pub max_atomic_width: Option<u64>,
717 /// Whether the target supports atomic CAS operations natively
718 pub atomic_cas: bool,
720 /// Panic strategy: "unwind" or "abort"
721 pub panic_strategy: PanicStrategy,
723 /// A blacklist of ABIs unsupported by the current target. Note that generic
724 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
725 pub abi_blacklist: Vec<Abi>,
727 /// Whether or not linking dylibs to a static CRT is allowed.
728 pub crt_static_allows_dylibs: bool,
729 /// Whether or not the CRT is statically linked by default.
730 pub crt_static_default: bool,
731 /// Whether or not crt-static is respected by the compiler (or is a no-op).
732 pub crt_static_respected: bool,
734 /// Whether or not stack probes (__rust_probestack) are enabled
735 pub stack_probes: bool,
737 /// The minimum alignment for global symbols.
738 pub min_global_align: Option<u64>,
740 /// Default number of codegen units to use in debug mode
741 pub default_codegen_units: Option<u64>,
743 /// Whether to generate trap instructions in places where optimization would
744 /// otherwise produce control flow that falls through into unrelated memory.
745 pub trap_unreachable: bool,
747 /// This target requires everything to be compiled with LTO to emit a final
748 /// executable, aka there is no native linker for this target.
749 pub requires_lto: bool,
751 /// This target has no support for threads.
752 pub singlethread: bool,
754 /// Whether library functions call lowering/optimization is disabled in LLVM
755 /// for this target unconditionally.
756 pub no_builtins: bool,
758 /// The codegen backend to use for this target, typically "llvm"
759 pub codegen_backend: String,
761 /// The default visibility for symbols in this target should be "hidden"
762 /// rather than "default"
763 pub default_hidden_visibility: bool,
765 /// Whether a .debug_gdb_scripts section will be added to the output object file
766 pub emit_debug_gdb_scripts: bool,
768 /// Whether or not to unconditionally `uwtable` attributes on functions,
769 /// typically because the platform needs to unwind for things like stack
771 pub requires_uwtable: bool,
773 /// Whether or not SIMD types are passed by reference in the Rust ABI,
774 /// typically required if a target can be compiled with a mixed set of
775 /// target features. This is `true` by default, and `false` for targets like
776 /// wasm32 where the whole program either has simd or not.
777 pub simd_types_indirect: bool,
779 /// Pass a list of symbol which should be exported in the dylib to the linker.
780 pub limit_rdylib_exports: bool,
782 /// If set, have the linker export exactly these symbols, instead of using
783 /// the usual logic to figure this out from the crate itself.
784 pub override_export_symbols: Option<Vec<String>>,
786 /// Determines how or whether the MergeFunctions LLVM pass should run for
787 /// this target. Either "disabled", "trampolines", or "aliases".
788 /// The MergeFunctions pass is generally useful, but some targets may need
789 /// to opt out. The default is "aliases".
791 /// Workaround for: https://github.com/rust-lang/rust/issues/57356
792 pub merge_functions: MergeFunctions,
794 /// Use platform dependent mcount function
795 pub target_mcount: String,
797 /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
798 pub llvm_abiname: String,
800 /// Whether or not RelaxElfRelocation flag will be passed to the linker
801 pub relax_elf_relocations: bool,
803 /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
804 pub llvm_args: Vec<String>,
807 impl Default for TargetOptions {
808 /// Creates a set of "sane defaults" for any target. This is still
809 /// incomplete, and if used for compilation, will certainly not work.
810 fn default() -> TargetOptions {
813 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
814 lld_flavor: LldFlavor::Ld,
815 pre_link_args: LinkArgs::new(),
816 pre_link_args_crt: LinkArgs::new(),
817 post_link_args: LinkArgs::new(),
818 asm_args: Vec::new(),
819 cpu: "generic".to_string(),
820 features: String::new(),
821 dynamic_linking: false,
824 relocation_model: "pic".to_string(),
826 tls_model: "global-dynamic".to_string(),
827 disable_redzone: false,
828 eliminate_frame_pointer: true,
829 function_sections: true,
830 dll_prefix: "lib".to_string(),
831 dll_suffix: ".so".to_string(),
832 exe_suffix: String::new(),
833 staticlib_prefix: "lib".to_string(),
834 staticlib_suffix: ".a".to_string(),
836 abi_return_struct_as_int: false,
838 is_like_solaris: false,
839 is_like_windows: false,
840 is_like_android: false,
841 is_like_emscripten: false,
843 is_like_fuchsia: false,
844 linker_is_gnu: false,
845 allows_weak_linkage: true,
847 no_default_libraries: true,
848 position_independent_executables: false,
850 relro_level: RelroLevel::None,
851 pre_link_objects_exe: Vec::new(),
852 pre_link_objects_exe_crt: Vec::new(),
853 pre_link_objects_dll: Vec::new(),
854 post_link_objects: Vec::new(),
855 post_link_objects_crt: Vec::new(),
856 late_link_args: LinkArgs::new(),
857 late_link_args_dynamic: LinkArgs::new(),
858 late_link_args_static: LinkArgs::new(),
859 link_env: Vec::new(),
860 link_env_remove: Vec::new(),
861 archive_format: "gnu".to_string(),
862 main_needs_argc_argv: true,
865 obj_is_bitcode: false,
866 min_atomic_width: None,
867 max_atomic_width: None,
869 panic_strategy: PanicStrategy::Unwind,
870 abi_blacklist: vec![],
871 crt_static_allows_dylibs: false,
872 crt_static_default: false,
873 crt_static_respected: false,
875 min_global_align: None,
876 default_codegen_units: None,
877 trap_unreachable: true,
881 codegen_backend: "llvm".to_string(),
882 default_hidden_visibility: false,
883 emit_debug_gdb_scripts: true,
884 requires_uwtable: false,
885 simd_types_indirect: true,
886 limit_rdylib_exports: true,
887 override_export_symbols: None,
888 merge_functions: MergeFunctions::Aliases,
889 target_mcount: "mcount".to_string(),
890 llvm_abiname: "".to_string(),
891 relax_elf_relocations: false,
898 /// Given a function ABI, turn it into the correct ABI for this target.
899 pub fn adjust_abi(&self, abi: Abi) -> Abi {
902 if self.options.is_like_windows && self.arch == "x86" {
908 // These ABI kinds are ignored on non-x86 Windows targets.
909 // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
910 // and the individual pages for __stdcall et al.
911 Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => {
912 if self.options.is_like_windows && self.arch != "x86" { Abi::C } else { abi }
915 if self.arch == "x86_64" {
925 /// Minimum integer size in bits that this target can perform atomic
927 pub fn min_atomic_width(&self) -> u64 {
928 self.options.min_atomic_width.unwrap_or(8)
931 /// Maximum integer size in bits that this target can perform atomic
933 pub fn max_atomic_width(&self) -> u64 {
934 self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap())
937 pub fn is_abi_supported(&self, abi: Abi) -> bool {
938 abi.generic() || !self.options.abi_blacklist.contains(&abi)
941 /// Loads a target descriptor from a JSON object.
942 pub fn from_json(obj: Json) -> TargetResult {
943 // While ugly, this code must remain this way to retain
944 // compatibility with existing JSON fields and the internal
945 // expected naming of the Target and TargetOptions structs.
946 // To ensure compatibility is retained, the built-in targets
947 // are round-tripped through this code to catch cases where
948 // the JSON parser is not updated to match the structs.
950 let get_req_field = |name: &str| {
952 .map(|s| s.as_string())
953 .and_then(|os| os.map(|s| s.to_string()))
954 .ok_or_else(|| format!("Field {} in target specification is required", name))
957 let get_opt_field = |name: &str, default: &str| {
959 .and_then(|s| s.as_string())
960 .map(|s| s.to_string())
961 .unwrap_or_else(|| default.to_string())
964 let mut base = Target {
965 llvm_target: get_req_field("llvm-target")?,
966 target_endian: get_req_field("target-endian")?,
967 target_pointer_width: get_req_field("target-pointer-width")?,
968 target_c_int_width: get_req_field("target-c-int-width")?,
969 data_layout: get_req_field("data-layout")?,
970 arch: get_req_field("arch")?,
971 target_os: get_req_field("os")?,
972 target_env: get_opt_field("env", ""),
973 target_vendor: get_opt_field("vendor", "unknown"),
974 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
975 .ok_or_else(|| format!("linker flavor must be {}", LinkerFlavor::one_of()))?,
976 options: Default::default(),
980 ($key_name:ident) => ( {
981 let name = (stringify!($key_name)).replace("_", "-");
982 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
983 base.options.$key_name = s.to_string();
986 ($key_name:ident, bool) => ( {
987 let name = (stringify!($key_name)).replace("_", "-");
988 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
989 base.options.$key_name = s;
992 ($key_name:ident, Option<u64>) => ( {
993 let name = (stringify!($key_name)).replace("_", "-");
994 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
995 base.options.$key_name = Some(s);
998 ($key_name:ident, MergeFunctions) => ( {
999 let name = (stringify!($key_name)).replace("_", "-");
1000 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1001 match s.parse::<MergeFunctions>() {
1002 Ok(mergefunc) => base.options.$key_name = mergefunc,
1003 _ => return Some(Err(format!("'{}' is not a valid value for \
1004 merge-functions. Use 'disabled', \
1005 'trampolines', or 'aliases'.",
1009 })).unwrap_or(Ok(()))
1011 ($key_name:ident, PanicStrategy) => ( {
1012 let name = (stringify!($key_name)).replace("_", "-");
1013 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1015 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
1016 "abort" => base.options.$key_name = PanicStrategy::Abort,
1017 _ => return Some(Err(format!("'{}' is not a valid value for \
1018 panic-strategy. Use 'unwind' or 'abort'.",
1022 })).unwrap_or(Ok(()))
1024 ($key_name:ident, RelroLevel) => ( {
1025 let name = (stringify!($key_name)).replace("_", "-");
1026 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1027 match s.parse::<RelroLevel>() {
1028 Ok(level) => base.options.$key_name = level,
1029 _ => return Some(Err(format!("'{}' is not a valid value for \
1030 relro-level. Use 'full', 'partial, or 'off'.",
1034 })).unwrap_or(Ok(()))
1036 ($key_name:ident, list) => ( {
1037 let name = (stringify!($key_name)).replace("_", "-");
1038 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1039 base.options.$key_name = v.iter()
1040 .map(|a| a.as_string().unwrap().to_string())
1044 ($key_name:ident, opt_list) => ( {
1045 let name = (stringify!($key_name)).replace("_", "-");
1046 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1047 base.options.$key_name = Some(v.iter()
1048 .map(|a| a.as_string().unwrap().to_string())
1052 ($key_name:ident, optional) => ( {
1053 let name = (stringify!($key_name)).replace("_", "-");
1054 if let Some(o) = obj.find(&name[..]) {
1055 base.options.$key_name = o
1057 .map(|s| s.to_string() );
1060 ($key_name:ident, LldFlavor) => ( {
1061 let name = (stringify!($key_name)).replace("_", "-");
1062 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1063 if let Some(flavor) = LldFlavor::from_str(&s) {
1064 base.options.$key_name = flavor;
1066 return Some(Err(format!(
1067 "'{}' is not a valid value for lld-flavor. \
1068 Use 'darwin', 'gnu', 'link' or 'wasm.",
1072 })).unwrap_or(Ok(()))
1074 ($key_name:ident, LinkerFlavor) => ( {
1075 let name = (stringify!($key_name)).replace("_", "-");
1076 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
1077 LinkerFlavor::from_str(&s).ok_or_else(|| {
1078 Err(format!("'{}' is not a valid value for linker-flavor. \
1079 Use 'em', 'gcc', 'ld' or 'msvc.", s))
1081 })).unwrap_or(Ok(()))
1083 ($key_name:ident, link_args) => ( {
1084 let name = (stringify!($key_name)).replace("_", "-");
1085 if let Some(val) = obj.find(&name[..]) {
1086 let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1087 JSON object with fields per linker-flavor.", name))?;
1088 let mut args = LinkArgs::new();
1090 let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1091 format!("{}: '{}' is not a valid value for linker-flavor. \
1092 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1095 let v = v.as_array().ok_or_else(||
1096 format!("{}.{}: expected a JSON array", name, k)
1097 )?.iter().enumerate()
1099 let s = s.as_string().ok_or_else(||
1100 format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1103 .collect::<Result<Vec<_>, String>>()?;
1105 args.insert(flavor, v);
1107 base.options.$key_name = args;
1110 ($key_name:ident, env) => ( {
1111 let name = (stringify!($key_name)).replace("_", "-");
1112 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1114 if let Some(s) = o.as_string() {
1115 let p = s.split('=').collect::<Vec<_>>();
1117 let k = p[0].to_string();
1118 let v = p[1].to_string();
1119 base.options.$key_name.push((k, v));
1127 key!(is_builtin, bool);
1128 key!(linker, optional);
1129 key!(lld_flavor, LldFlavor)?;
1130 key!(pre_link_args, link_args);
1131 key!(pre_link_args_crt, link_args);
1132 key!(pre_link_objects_exe, list);
1133 key!(pre_link_objects_exe_crt, list);
1134 key!(pre_link_objects_dll, list);
1135 key!(late_link_args, link_args);
1136 key!(late_link_args_dynamic, link_args);
1137 key!(late_link_args_static, link_args);
1138 key!(post_link_objects, list);
1139 key!(post_link_objects_crt, list);
1140 key!(post_link_args, link_args);
1141 key!(link_env, env);
1142 key!(link_env_remove, list);
1143 key!(asm_args, list);
1146 key!(dynamic_linking, bool);
1147 key!(only_cdylib, bool);
1148 key!(executables, bool);
1149 key!(relocation_model);
1150 key!(code_model, optional);
1152 key!(disable_redzone, bool);
1153 key!(eliminate_frame_pointer, bool);
1154 key!(function_sections, bool);
1158 key!(staticlib_prefix);
1159 key!(staticlib_suffix);
1160 key!(target_family, optional);
1161 key!(abi_return_struct_as_int, bool);
1162 key!(is_like_osx, bool);
1163 key!(is_like_solaris, bool);
1164 key!(is_like_windows, bool);
1165 key!(is_like_msvc, bool);
1166 key!(is_like_emscripten, bool);
1167 key!(is_like_android, bool);
1168 key!(is_like_fuchsia, bool);
1169 key!(linker_is_gnu, bool);
1170 key!(allows_weak_linkage, bool);
1171 key!(has_rpath, bool);
1172 key!(no_default_libraries, bool);
1173 key!(position_independent_executables, bool);
1174 key!(needs_plt, bool);
1175 key!(relro_level, RelroLevel)?;
1176 key!(archive_format);
1177 key!(allow_asm, bool);
1178 key!(main_needs_argc_argv, bool);
1179 key!(has_elf_tls, bool);
1180 key!(obj_is_bitcode, bool);
1181 key!(max_atomic_width, Option<u64>);
1182 key!(min_atomic_width, Option<u64>);
1183 key!(atomic_cas, bool);
1184 key!(panic_strategy, PanicStrategy)?;
1185 key!(crt_static_allows_dylibs, bool);
1186 key!(crt_static_default, bool);
1187 key!(crt_static_respected, bool);
1188 key!(stack_probes, bool);
1189 key!(min_global_align, Option<u64>);
1190 key!(default_codegen_units, Option<u64>);
1191 key!(trap_unreachable, bool);
1192 key!(requires_lto, bool);
1193 key!(singlethread, bool);
1194 key!(no_builtins, bool);
1195 key!(codegen_backend);
1196 key!(default_hidden_visibility, bool);
1197 key!(emit_debug_gdb_scripts, bool);
1198 key!(requires_uwtable, bool);
1199 key!(simd_types_indirect, bool);
1200 key!(limit_rdylib_exports, bool);
1201 key!(override_export_symbols, opt_list);
1202 key!(merge_functions, MergeFunctions)?;
1203 key!(target_mcount);
1205 key!(relax_elf_relocations, bool);
1206 key!(llvm_args, list);
1208 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
1209 for name in array.iter().filter_map(|abi| abi.as_string()) {
1210 match lookup_abi(name) {
1214 "The ABI \"{}\" is considered to be supported on \
1215 all targets and cannot be blacklisted",
1220 base.options.abi_blacklist.push(abi)
1223 return Err(format!("Unknown ABI \"{}\" in target specification", name));
1232 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
1233 /// triple. Note that it could also just be a bare filename already, so also
1234 /// check for that. If one of the hardcoded targets we know about, just
1235 /// return it directly.
1237 /// The error string could come from any of the APIs called, including
1238 /// filesystem access and JSON decoding.
1239 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
1240 use rustc_serialize::json;
1244 fn load_file(path: &Path) -> Result<Target, String> {
1245 let contents = fs::read(path).map_err(|e| e.to_string())?;
1246 let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1247 Target::from_json(obj)
1250 match *target_triple {
1251 TargetTriple::TargetTriple(ref target_triple) => {
1252 // check if triple is in list of supported targets
1253 match load_specific(target_triple) {
1254 Ok(t) => return Ok(t),
1255 Err(LoadTargetError::BuiltinTargetNotFound(_)) => (),
1256 Err(LoadTargetError::Other(e)) => return Err(e),
1259 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1261 let mut target = target_triple.to_string();
1262 target.push_str(".json");
1263 PathBuf::from(target)
1266 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1268 // FIXME 16351: add a sane default search path?
1270 for dir in env::split_paths(&target_path) {
1271 let p = dir.join(&path);
1273 return load_file(&p);
1276 Err(format!("Could not find specification for target {:?}", target_triple))
1278 TargetTriple::TargetPath(ref target_path) => {
1279 if target_path.is_file() {
1280 return load_file(&target_path);
1282 Err(format!("Target path {:?} is not a valid file", target_path))
1288 impl ToJson for Target {
1289 fn to_json(&self) -> Json {
1290 let mut d = BTreeMap::new();
1291 let default: TargetOptions = Default::default();
1293 macro_rules! target_val {
1295 let name = (stringify!($attr)).replace("_", "-");
1296 d.insert(name, self.$attr.to_json());
1298 ($attr:ident, $key_name:expr) => {{
1299 let name = $key_name;
1300 d.insert(name.to_string(), self.$attr.to_json());
1304 macro_rules! target_option_val {
1306 let name = (stringify!($attr)).replace("_", "-");
1307 if default.$attr != self.options.$attr {
1308 d.insert(name, self.options.$attr.to_json());
1311 ($attr:ident, $key_name:expr) => {{
1312 let name = $key_name;
1313 if default.$attr != self.options.$attr {
1314 d.insert(name.to_string(), self.options.$attr.to_json());
1317 (link_args - $attr:ident) => {{
1318 let name = (stringify!($attr)).replace("_", "-");
1319 if default.$attr != self.options.$attr {
1324 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1325 .collect::<BTreeMap<_, _>>();
1326 d.insert(name, obj.to_json());
1329 (env - $attr:ident) => {{
1330 let name = (stringify!($attr)).replace("_", "-");
1331 if default.$attr != self.options.$attr {
1336 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1337 .collect::<Vec<_>>();
1338 d.insert(name, obj.to_json());
1343 target_val!(llvm_target);
1344 target_val!(target_endian);
1345 target_val!(target_pointer_width);
1346 target_val!(target_c_int_width);
1348 target_val!(target_os, "os");
1349 target_val!(target_env, "env");
1350 target_val!(target_vendor, "vendor");
1351 target_val!(data_layout);
1352 target_val!(linker_flavor);
1354 target_option_val!(is_builtin);
1355 target_option_val!(linker);
1356 target_option_val!(lld_flavor);
1357 target_option_val!(link_args - pre_link_args);
1358 target_option_val!(link_args - pre_link_args_crt);
1359 target_option_val!(pre_link_objects_exe);
1360 target_option_val!(pre_link_objects_exe_crt);
1361 target_option_val!(pre_link_objects_dll);
1362 target_option_val!(link_args - late_link_args);
1363 target_option_val!(link_args - late_link_args_dynamic);
1364 target_option_val!(link_args - late_link_args_static);
1365 target_option_val!(post_link_objects);
1366 target_option_val!(post_link_objects_crt);
1367 target_option_val!(link_args - post_link_args);
1368 target_option_val!(env - link_env);
1369 target_option_val!(link_env_remove);
1370 target_option_val!(asm_args);
1371 target_option_val!(cpu);
1372 target_option_val!(features);
1373 target_option_val!(dynamic_linking);
1374 target_option_val!(only_cdylib);
1375 target_option_val!(executables);
1376 target_option_val!(relocation_model);
1377 target_option_val!(code_model);
1378 target_option_val!(tls_model);
1379 target_option_val!(disable_redzone);
1380 target_option_val!(eliminate_frame_pointer);
1381 target_option_val!(function_sections);
1382 target_option_val!(dll_prefix);
1383 target_option_val!(dll_suffix);
1384 target_option_val!(exe_suffix);
1385 target_option_val!(staticlib_prefix);
1386 target_option_val!(staticlib_suffix);
1387 target_option_val!(target_family);
1388 target_option_val!(abi_return_struct_as_int);
1389 target_option_val!(is_like_osx);
1390 target_option_val!(is_like_solaris);
1391 target_option_val!(is_like_windows);
1392 target_option_val!(is_like_msvc);
1393 target_option_val!(is_like_emscripten);
1394 target_option_val!(is_like_android);
1395 target_option_val!(is_like_fuchsia);
1396 target_option_val!(linker_is_gnu);
1397 target_option_val!(allows_weak_linkage);
1398 target_option_val!(has_rpath);
1399 target_option_val!(no_default_libraries);
1400 target_option_val!(position_independent_executables);
1401 target_option_val!(needs_plt);
1402 target_option_val!(relro_level);
1403 target_option_val!(archive_format);
1404 target_option_val!(allow_asm);
1405 target_option_val!(main_needs_argc_argv);
1406 target_option_val!(has_elf_tls);
1407 target_option_val!(obj_is_bitcode);
1408 target_option_val!(min_atomic_width);
1409 target_option_val!(max_atomic_width);
1410 target_option_val!(atomic_cas);
1411 target_option_val!(panic_strategy);
1412 target_option_val!(crt_static_allows_dylibs);
1413 target_option_val!(crt_static_default);
1414 target_option_val!(crt_static_respected);
1415 target_option_val!(stack_probes);
1416 target_option_val!(min_global_align);
1417 target_option_val!(default_codegen_units);
1418 target_option_val!(trap_unreachable);
1419 target_option_val!(requires_lto);
1420 target_option_val!(singlethread);
1421 target_option_val!(no_builtins);
1422 target_option_val!(codegen_backend);
1423 target_option_val!(default_hidden_visibility);
1424 target_option_val!(emit_debug_gdb_scripts);
1425 target_option_val!(requires_uwtable);
1426 target_option_val!(simd_types_indirect);
1427 target_option_val!(limit_rdylib_exports);
1428 target_option_val!(override_export_symbols);
1429 target_option_val!(merge_functions);
1430 target_option_val!(target_mcount);
1431 target_option_val!(llvm_abiname);
1432 target_option_val!(relax_elf_relocations);
1433 target_option_val!(llvm_args);
1435 if default.abi_blacklist != self.options.abi_blacklist {
1437 "abi-blacklist".to_string(),
1441 .map(|&name| Abi::name(name).to_json())
1442 .collect::<Vec<_>>()
1451 /// Either a target triple string or a path to a JSON file.
1452 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1453 pub enum TargetTriple {
1454 TargetTriple(String),
1455 TargetPath(PathBuf),
1459 /// Creates a target triple from the passed target triple string.
1460 pub fn from_triple(triple: &str) -> Self {
1461 TargetTriple::TargetTriple(triple.to_string())
1464 /// Creates a target triple from the passed target path.
1465 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1466 let canonicalized_path = path.canonicalize()?;
1467 Ok(TargetTriple::TargetPath(canonicalized_path))
1470 /// Returns a string triple for this target.
1472 /// If this target is a path, the file name (without extension) is returned.
1473 pub fn triple(&self) -> &str {
1475 TargetTriple::TargetTriple(ref triple) => triple,
1476 TargetTriple::TargetPath(ref path) => path
1478 .expect("target path must not be empty")
1480 .expect("target path must be valid unicode"),
1484 /// Returns an extended string triple for this target.
1486 /// If this target is a path, a hash of the path is appended to the triple returned
1488 pub fn debug_triple(&self) -> String {
1489 use std::collections::hash_map::DefaultHasher;
1490 use std::hash::{Hash, Hasher};
1492 let triple = self.triple();
1493 if let TargetTriple::TargetPath(ref path) = *self {
1494 let mut hasher = DefaultHasher::new();
1495 path.hash(&mut hasher);
1496 let hash = hasher.finish();
1497 format!("{}-{}", triple, hash)
1504 impl fmt::Display for TargetTriple {
1505 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1506 write!(f, "{}", self.debug_triple())