1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
13 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
14 //! allows new target triples to be defined in configuration files. Most users
15 //! will not need to care about these, but this is invaluable when porting Rust
16 //! to a new platform, and allows for an unprecedented level of control over how
17 //! the compiler works.
19 //! # Using custom targets
21 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
22 //! compared against the list of built-in targets. This is to ease distributing
23 //! rustc (no need for configuration files) and also to hold these built-in
24 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
25 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
26 //! will be loaded as the target configuration. If the file does not exist,
27 //! rustc will search each directory in the environment variable
28 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
29 //! be loaded. If no file is found in any of those directories, a fatal error
32 //! Projects defining their own targets should use
33 //! `--target=path/to/my-awesome-platform.json` instead of adding to
34 //! `RUST_TARGET_PATH`.
36 //! # Defining a new target
38 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
39 //! this module defines the format the JSON file should take, though each
40 //! underscore in the field names should be replaced with a hyphen (`-`) in the
41 //! JSON file. Some fields are required in every target specification, such as
42 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
43 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
44 //! the target's settings, though `target-feature` and `link-args` will *add*
45 //! to the list specified by the target, rather than replace.
47 use serialize::json::{Json, ToJson};
48 use std::collections::BTreeMap;
49 use std::default::Default;
51 use std::path::{Path, PathBuf};
52 use std::str::FromStr;
53 use spec::abi::{Abi, lookup as lookup_abi};
71 mod windows_msvc_base;
77 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
78 RustcEncodable, RustcDecodable)]
79 pub enum LinkerFlavor {
87 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash,
88 RustcEncodable, RustcDecodable)]
96 impl ToJson for LinkerFlavor {
97 fn to_json(&self) -> Json {
101 macro_rules! flavor_mappings {
102 ($((($($flavor:tt)*), $string:expr),)*) => (
104 pub const fn one_of() -> &'static str {
105 concat!("one of: ", $($string, " ",)+)
108 pub fn from_str(s: &str) -> Option<Self> {
110 $($string => $($flavor)*,)+
115 pub fn desc(&self) -> &str {
117 $($($flavor)* => $string,)+
126 ((LinkerFlavor::Em), "em"),
127 ((LinkerFlavor::Gcc), "gcc"),
128 ((LinkerFlavor::Ld), "ld"),
129 ((LinkerFlavor::Msvc), "msvc"),
130 ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
131 ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
132 ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
133 ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
136 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
137 pub enum PanicStrategy {
143 pub fn desc(&self) -> &str {
145 PanicStrategy::Unwind => "unwind",
146 PanicStrategy::Abort => "abort",
151 impl ToJson for PanicStrategy {
152 fn to_json(&self) -> Json {
154 PanicStrategy::Abort => "abort".to_json(),
155 PanicStrategy::Unwind => "unwind".to_json(),
160 #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
161 pub enum RelroLevel {
169 pub fn desc(&self) -> &str {
171 RelroLevel::Full => "full",
172 RelroLevel::Partial => "partial",
173 RelroLevel::Off => "off",
174 RelroLevel::None => "none",
179 impl FromStr for RelroLevel {
182 fn from_str(s: &str) -> Result<RelroLevel, ()> {
184 "full" => Ok(RelroLevel::Full),
185 "partial" => Ok(RelroLevel::Partial),
186 "off" => Ok(RelroLevel::Off),
187 "none" => Ok(RelroLevel::None),
193 impl ToJson for RelroLevel {
194 fn to_json(&self) -> Json {
196 RelroLevel::Full => "full".to_json(),
197 RelroLevel::Partial => "partial".to_json(),
198 RelroLevel::Off => "off".to_json(),
199 RelroLevel::None => "None".to_json(),
204 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
205 pub type TargetResult = Result<Target, String>;
207 macro_rules! supported_targets {
208 ( $(($triple:expr, $module:ident),)+ ) => (
211 /// List of supported targets
212 const TARGETS: &'static [&'static str] = &[$($triple),*];
214 fn load_specific(target: &str) -> TargetResult {
218 let mut t = $module::target()?;
219 t.options.is_builtin = true;
221 // round-trip through the JSON parser to ensure at
222 // run-time that the parser works correctly
223 t = Target::from_json(t.to_json())?;
224 debug!("Got builtin target: {:?}", t);
228 _ => Err(format!("Unable to find target: {}", target))
232 pub fn get_targets() -> Box<Iterator<Item=String>> {
233 Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
235 .and(Ok(t.to_string()))
241 mod test_json_encode_decode {
242 use serialize::json::ToJson;
244 $(use super::$module;)*
249 // Grab the TargetResult struct. If we successfully retrieved
250 // a Target, then the test JSON encoding/decoding can run for this
251 // Target on this testing platform (i.e., checking the iOS targets
252 // only on a Mac test platform).
253 let _ = $module::target().map(|original| {
254 let as_json = original.to_json();
255 let parsed = Target::from_json(as_json).unwrap();
256 assert_eq!(original, parsed);
265 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
266 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
267 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
268 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
269 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
270 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
271 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
272 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
273 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
274 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
275 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
276 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
277 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
278 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
279 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
280 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
281 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
282 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
283 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
284 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
285 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
286 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
287 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
288 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
289 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
291 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
292 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
293 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
294 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
295 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
296 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
298 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
299 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
301 ("i686-linux-android", i686_linux_android),
302 ("x86_64-linux-android", x86_64_linux_android),
303 ("arm-linux-androideabi", arm_linux_androideabi),
304 ("armv7-linux-androideabi", armv7_linux_androideabi),
305 ("aarch64-linux-android", aarch64_linux_android),
307 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
308 ("i686-unknown-freebsd", i686_unknown_freebsd),
309 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
311 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
312 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
314 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
316 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
317 ("i686-unknown-openbsd", i686_unknown_openbsd),
318 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
320 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
321 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
322 ("i686-unknown-netbsd", i686_unknown_netbsd),
323 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
324 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
325 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
326 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
328 ("i686-unknown-haiku", i686_unknown_haiku),
329 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
331 ("x86_64-apple-darwin", x86_64_apple_darwin),
332 ("i686-apple-darwin", i686_apple_darwin),
334 ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia),
335 ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
337 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
339 ("x86_64-unknown-redox", x86_64_unknown_redox),
341 ("i386-apple-ios", i386_apple_ios),
342 ("x86_64-apple-ios", x86_64_apple_ios),
343 ("aarch64-apple-ios", aarch64_apple_ios),
344 ("armv7-apple-ios", armv7_apple_ios),
345 ("armv7s-apple-ios", armv7s_apple_ios),
347 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
349 ("x86_64-sun-solaris", x86_64_sun_solaris),
350 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
352 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
353 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
355 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
356 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
357 ("i586-pc-windows-msvc", i586_pc_windows_msvc),
359 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
360 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
361 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
362 ("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
364 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
365 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
366 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
367 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
369 ("msp430-none-elf", msp430_none_elf),
371 ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi),
372 ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf),
373 ("i686-unknown-cloudabi", i686_unknown_cloudabi),
374 ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi),
377 /// Everything `rustc` knows about how to compile for a specific target.
379 /// Every field here must be specified, and has no default value.
380 #[derive(PartialEq, Clone, Debug)]
382 /// Target triple to pass to LLVM.
383 pub llvm_target: String,
384 /// String to use as the `target_endian` `cfg` variable.
385 pub target_endian: String,
386 /// String to use as the `target_pointer_width` `cfg` variable.
387 pub target_pointer_width: String,
388 /// Width of c_int type
389 pub target_c_int_width: String,
390 /// OS name to use for conditional compilation.
391 pub target_os: String,
392 /// Environment name to use for conditional compilation.
393 pub target_env: String,
394 /// Vendor name to use for conditional compilation.
395 pub target_vendor: String,
396 /// Architecture to use for ABI considerations. Valid options: "x86",
397 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
399 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
400 pub data_layout: String,
402 pub linker_flavor: LinkerFlavor,
403 /// Optional settings with defaults.
404 pub options: TargetOptions,
407 pub trait HasTargetSpec: Copy {
408 fn target_spec(&self) -> &Target;
411 impl<'a> HasTargetSpec for &'a Target {
412 fn target_spec(&self) -> &Target {
417 /// Optional aspects of a target specification.
419 /// This has an implementation of `Default`, see each field for what the default is. In general,
420 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
421 #[derive(PartialEq, Clone, Debug)]
422 pub struct TargetOptions {
423 /// Whether the target is built-in or loaded from a custom target specification.
424 pub is_builtin: bool,
427 pub linker: Option<String>,
429 /// Linker arguments that are passed *before* any user-defined libraries.
430 pub pre_link_args: LinkArgs, // ... unconditionally
431 pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt
432 /// Objects to link before all others, always found within the
434 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally
435 pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt
436 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
437 /// Linker arguments that are unconditionally passed after any
438 /// user-defined but before post_link_objects. Standard platform
439 /// libraries that should be always be linked to, usually go here.
440 pub late_link_args: LinkArgs,
441 /// Objects to link after all others, always found within the
443 pub post_link_objects: Vec<String>, // ... unconditionally
444 pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt
445 /// Linker arguments that are unconditionally passed *after* any
446 /// user-defined libraries.
447 pub post_link_args: LinkArgs,
449 /// Environment variables to be set before invoking the linker.
450 pub link_env: Vec<(String, String)>,
452 /// Extra arguments to pass to the external assembler (when used)
453 pub asm_args: Vec<String>,
455 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
458 /// Default target features to pass to LLVM. These features will *always* be
459 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
460 /// -mattr=$features`.
461 pub features: String,
462 /// Whether dynamic linking is available on this target. Defaults to false.
463 pub dynamic_linking: bool,
464 /// If dynamic linking is available, whether only cdylibs are supported.
465 pub only_cdylib: bool,
466 /// Whether executables are available on this target. iOS, for example, only allows static
467 /// libraries. Defaults to false.
468 pub executables: bool,
469 /// Relocation model to use in object file. Corresponds to `llc
470 /// -relocation-model=$relocation_model`. Defaults to "pic".
471 pub relocation_model: String,
472 /// Code model to use. Corresponds to `llc -code-model=$code_model`.
473 pub code_model: Option<String>,
474 /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
475 /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
476 pub tls_model: String,
477 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
478 pub disable_redzone: bool,
479 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
480 pub eliminate_frame_pointer: bool,
481 /// Emit each function in its own section. Defaults to true.
482 pub function_sections: bool,
483 /// String to prepend to the name of every dynamic library. Defaults to "lib".
484 pub dll_prefix: String,
485 /// String to append to the name of every dynamic library. Defaults to ".so".
486 pub dll_suffix: String,
487 /// String to append to the name of every executable.
488 pub exe_suffix: String,
489 /// String to prepend to the name of every static library. Defaults to "lib".
490 pub staticlib_prefix: String,
491 /// String to append to the name of every static library. Defaults to ".a".
492 pub staticlib_suffix: String,
493 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
494 pub target_family: Option<String>,
495 /// Whether the target toolchain's ABI supports returning small structs as an integer.
496 pub abi_return_struct_as_int: bool,
497 /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
498 /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
499 pub is_like_osx: bool,
500 /// Whether the target toolchain is like Solaris's.
501 /// Only useful for compiling against Illumos/Solaris,
502 /// as they have a different set of linker flags. Defaults to false.
503 pub is_like_solaris: bool,
504 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
505 /// only really used for figuring out how to find libraries, since Windows uses its own
506 /// library naming convention. Defaults to false.
507 pub is_like_windows: bool,
508 pub is_like_msvc: bool,
509 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
510 /// Defaults to false.
511 pub is_like_android: bool,
512 /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
513 /// Emscripten toolchain.
514 /// Defaults to false.
515 pub is_like_emscripten: bool,
516 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
517 pub linker_is_gnu: bool,
518 /// The MinGW toolchain has a known issue that prevents it from correctly
519 /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
520 /// symbol needs its own COMDAT section, weak linkage implies a large
521 /// number sections that easily exceeds the given limit for larger
522 /// codebases. Consequently we want a way to disallow weak linkage on some
524 pub allows_weak_linkage: bool,
525 /// Whether the linker support rpaths or not. Defaults to false.
527 /// Whether to disable linking to the default libraries, typically corresponds
528 /// to `-nodefaultlibs`. Defaults to true.
529 pub no_default_libraries: bool,
530 /// Dynamically linked executables can be compiled as position independent
531 /// if the default relocation model of position independent code is not
532 /// changed. This is a requirement to take advantage of ASLR, as otherwise
533 /// the functions in the executable are not randomized and can be used
534 /// during an exploit of a vulnerability in any code.
535 pub position_independent_executables: bool,
536 /// Either partial, full, or off. Full RELRO makes the dynamic linker
537 /// resolve all symbols at startup and marks the GOT read-only before
538 /// starting the program, preventing overwriting the GOT.
539 pub relro_level: RelroLevel,
540 /// Format that archives should be emitted in. This affects whether we use
541 /// LLVM to assemble an archive or fall back to the system linker, and
542 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
543 /// the system linker to be used.
544 pub archive_format: String,
545 /// Is asm!() allowed? Defaults to true.
547 /// Whether the target uses a custom unwind resumption routine.
548 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
549 /// defined in libgcc. If this option is enabled, the target must provide
550 /// `eh_unwind_resume` lang item.
551 pub custom_unwind_resume: bool,
553 /// If necessary, a different crate to link exe allocators by default
554 pub exe_allocation_crate: Option<String>,
556 /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
558 pub has_elf_tls: bool,
559 // This is mainly for easy compatibility with emscripten.
560 // If we give emcc .o files that are actually .bc files it
562 pub obj_is_bitcode: bool,
564 // LLVM can't produce object files for this target. Instead, we'll make LLVM
565 // emit assembly and then use `gcc` to turn that assembly into an object
567 pub no_integrated_as: bool,
569 /// Don't use this field; instead use the `.min_atomic_width()` method.
570 pub min_atomic_width: Option<u64>,
572 /// Don't use this field; instead use the `.max_atomic_width()` method.
573 pub max_atomic_width: Option<u64>,
575 /// Panic strategy: "unwind" or "abort"
576 pub panic_strategy: PanicStrategy,
578 /// A blacklist of ABIs unsupported by the current target. Note that generic
579 /// ABIs are considered to be supported on all platforms and cannot be blacklisted.
580 pub abi_blacklist: Vec<Abi>,
582 /// Whether or not linking dylibs to a static CRT is allowed.
583 pub crt_static_allows_dylibs: bool,
584 /// Whether or not the CRT is statically linked by default.
585 pub crt_static_default: bool,
586 /// Whether or not crt-static is respected by the compiler (or is a no-op).
587 pub crt_static_respected: bool,
589 /// Whether or not stack probes (__rust_probestack) are enabled
590 pub stack_probes: bool,
592 /// The minimum alignment for global symbols.
593 pub min_global_align: Option<u64>,
595 /// Default number of codegen units to use in debug mode
596 pub default_codegen_units: Option<u64>,
598 /// Whether to generate trap instructions in places where optimization would
599 /// otherwise produce control flow that falls through into unrelated memory.
600 pub trap_unreachable: bool,
602 /// This target requires everything to be compiled with LTO to emit a final
603 /// executable, aka there is no native linker for this target.
604 pub requires_lto: bool,
606 /// This target has no support for threads.
607 pub singlethread: bool,
609 /// Whether library functions call lowering/optimization is disabled in LLVM
610 /// for this target unconditionally.
611 pub no_builtins: bool,
613 /// Whether to lower 128-bit operations to compiler_builtins calls. Use if
614 /// your backend only supports 64-bit and smaller math.
615 pub i128_lowering: bool,
617 /// The codegen backend to use for this target, typically "llvm"
618 pub codegen_backend: String,
620 /// The default visibility for symbols in this target should be "hidden"
621 /// rather than "default"
622 pub default_hidden_visibility: bool,
624 /// Whether or not bitcode is embedded in object files
625 pub embed_bitcode: bool,
627 /// Whether a .debug_gdb_scripts section will be added to the output object file
628 pub emit_debug_gdb_scripts: bool,
630 /// Whether or not to unconditionally `uwtable` attributes on functions,
631 /// typically because the platform needs to unwind for things like stack
633 pub requires_uwtable: bool,
636 impl Default for TargetOptions {
637 /// Create a set of "sane defaults" for any target. This is still
638 /// incomplete, and if used for compilation, will certainly not work.
639 fn default() -> TargetOptions {
642 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
643 pre_link_args: LinkArgs::new(),
644 pre_link_args_crt: LinkArgs::new(),
645 post_link_args: LinkArgs::new(),
646 asm_args: Vec::new(),
647 cpu: "generic".to_string(),
648 features: "".to_string(),
649 dynamic_linking: false,
652 relocation_model: "pic".to_string(),
654 tls_model: "global-dynamic".to_string(),
655 disable_redzone: false,
656 eliminate_frame_pointer: true,
657 function_sections: true,
658 dll_prefix: "lib".to_string(),
659 dll_suffix: ".so".to_string(),
660 exe_suffix: "".to_string(),
661 staticlib_prefix: "lib".to_string(),
662 staticlib_suffix: ".a".to_string(),
664 abi_return_struct_as_int: false,
666 is_like_solaris: false,
667 is_like_windows: false,
668 is_like_android: false,
669 is_like_emscripten: false,
671 linker_is_gnu: false,
672 allows_weak_linkage: true,
674 no_default_libraries: true,
675 position_independent_executables: false,
676 relro_level: RelroLevel::None,
677 pre_link_objects_exe: Vec::new(),
678 pre_link_objects_exe_crt: Vec::new(),
679 pre_link_objects_dll: Vec::new(),
680 post_link_objects: Vec::new(),
681 post_link_objects_crt: Vec::new(),
682 late_link_args: LinkArgs::new(),
683 link_env: Vec::new(),
684 archive_format: "gnu".to_string(),
685 custom_unwind_resume: false,
686 exe_allocation_crate: None,
689 obj_is_bitcode: false,
690 no_integrated_as: false,
691 min_atomic_width: None,
692 max_atomic_width: None,
693 panic_strategy: PanicStrategy::Unwind,
694 abi_blacklist: vec![],
695 crt_static_allows_dylibs: false,
696 crt_static_default: false,
697 crt_static_respected: false,
699 min_global_align: None,
700 default_codegen_units: None,
701 trap_unreachable: true,
705 i128_lowering: false,
706 codegen_backend: "llvm".to_string(),
707 default_hidden_visibility: false,
708 embed_bitcode: false,
709 emit_debug_gdb_scripts: true,
710 requires_uwtable: false,
716 /// Given a function ABI, turn "System" into the correct ABI for this target.
717 pub fn adjust_abi(&self, abi: Abi) -> Abi {
720 if self.options.is_like_windows && self.arch == "x86" {
730 /// Minimum integer size in bits that this target can perform atomic
732 pub fn min_atomic_width(&self) -> u64 {
733 self.options.min_atomic_width.unwrap_or(8)
736 /// Maximum integer size in bits that this target can perform atomic
738 pub fn max_atomic_width(&self) -> u64 {
739 self.options.max_atomic_width.unwrap_or(self.target_pointer_width.parse().unwrap())
742 pub fn is_abi_supported(&self, abi: Abi) -> bool {
743 abi.generic() || !self.options.abi_blacklist.contains(&abi)
746 /// Load a target descriptor from a JSON object.
747 pub fn from_json(obj: Json) -> TargetResult {
748 // While ugly, this code must remain this way to retain
749 // compatibility with existing JSON fields and the internal
750 // expected naming of the Target and TargetOptions structs.
751 // To ensure compatibility is retained, the built-in targets
752 // are round-tripped through this code to catch cases where
753 // the JSON parser is not updated to match the structs.
755 let get_req_field = |name: &str| {
757 .map(|s| s.as_string())
758 .and_then(|os| os.map(|s| s.to_string())) {
759 Some(val) => Ok(val),
761 return Err(format!("Field {} in target specification is required", name))
766 let get_opt_field = |name: &str, default: &str| {
767 obj.find(name).and_then(|s| s.as_string())
768 .map(|s| s.to_string())
769 .unwrap_or(default.to_string())
772 let mut base = Target {
773 llvm_target: get_req_field("llvm-target")?,
774 target_endian: get_req_field("target-endian")?,
775 target_pointer_width: get_req_field("target-pointer-width")?,
776 target_c_int_width: get_req_field("target-c-int-width")?,
777 data_layout: get_req_field("data-layout")?,
778 arch: get_req_field("arch")?,
779 target_os: get_req_field("os")?,
780 target_env: get_opt_field("env", ""),
781 target_vendor: get_opt_field("vendor", "unknown"),
782 linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?)
784 format!("linker flavor must be {}", LinkerFlavor::one_of())
786 options: Default::default(),
790 ($key_name:ident) => ( {
791 let name = (stringify!($key_name)).replace("_", "-");
792 obj.find(&name[..]).map(|o| o.as_string()
793 .map(|s| base.options.$key_name = s.to_string()));
795 ($key_name:ident, bool) => ( {
796 let name = (stringify!($key_name)).replace("_", "-");
798 .map(|o| o.as_boolean()
799 .map(|s| base.options.$key_name = s));
801 ($key_name:ident, Option<u64>) => ( {
802 let name = (stringify!($key_name)).replace("_", "-");
805 .map(|s| base.options.$key_name = Some(s)));
807 ($key_name:ident, PanicStrategy) => ( {
808 let name = (stringify!($key_name)).replace("_", "-");
809 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
811 "unwind" => base.options.$key_name = PanicStrategy::Unwind,
812 "abort" => base.options.$key_name = PanicStrategy::Abort,
813 _ => return Some(Err(format!("'{}' is not a valid value for \
814 panic-strategy. Use 'unwind' or 'abort'.",
818 })).unwrap_or(Ok(()))
820 ($key_name:ident, RelroLevel) => ( {
821 let name = (stringify!($key_name)).replace("_", "-");
822 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
823 match s.parse::<RelroLevel>() {
824 Ok(level) => base.options.$key_name = level,
825 _ => return Some(Err(format!("'{}' is not a valid value for \
826 relro-level. Use 'full', 'partial, or 'off'.",
830 })).unwrap_or(Ok(()))
832 ($key_name:ident, list) => ( {
833 let name = (stringify!($key_name)).replace("_", "-");
834 obj.find(&name[..]).map(|o| o.as_array()
835 .map(|v| base.options.$key_name = v.iter()
836 .map(|a| a.as_string().unwrap().to_string()).collect()
840 ($key_name:ident, optional) => ( {
841 let name = (stringify!($key_name)).replace("_", "-");
842 if let Some(o) = obj.find(&name[..]) {
843 base.options.$key_name = o
845 .map(|s| s.to_string() );
848 ($key_name:ident, LinkerFlavor) => ( {
849 let name = (stringify!($key_name)).replace("_", "-");
850 obj.find(&name[..]).and_then(|o| o.as_string().map(|s| {
851 LinkerFlavor::from_str(&s).ok_or_else(|| {
852 Err(format!("'{}' is not a valid value for linker-flavor. \
853 Use 'em', 'gcc', 'ld' or 'msvc.", s))
855 })).unwrap_or(Ok(()))
857 ($key_name:ident, link_args) => ( {
858 let name = (stringify!($key_name)).replace("_", "-");
859 if let Some(obj) = obj.find(&name[..]).and_then(|o| o.as_object()) {
860 let mut args = LinkArgs::new();
862 let k = LinkerFlavor::from_str(&k).ok_or_else(|| {
863 format!("{}: '{}' is not a valid value for linker-flavor. \
864 Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
867 let v = v.as_array().map(|a| {
870 .filter_map(|o| o.as_string())
871 .map(|s| s.to_owned())
873 }).unwrap_or(vec![]);
877 base.options.$key_name = args;
880 ($key_name:ident, env) => ( {
881 let name = (stringify!($key_name)).replace("_", "-");
882 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
884 if let Some(s) = o.as_string() {
885 let p = s.split('=').collect::<Vec<_>>();
887 let k = p[0].to_string();
888 let v = p[1].to_string();
889 base.options.$key_name.push((k, v));
897 key!(is_builtin, bool);
898 key!(linker, optional);
899 key!(pre_link_args, link_args);
900 key!(pre_link_args_crt, link_args);
901 key!(pre_link_objects_exe, list);
902 key!(pre_link_objects_exe_crt, list);
903 key!(pre_link_objects_dll, list);
904 key!(late_link_args, link_args);
905 key!(post_link_objects, list);
906 key!(post_link_objects_crt, list);
907 key!(post_link_args, link_args);
909 key!(asm_args, list);
912 key!(dynamic_linking, bool);
913 key!(only_cdylib, bool);
914 key!(executables, bool);
915 key!(relocation_model);
916 key!(code_model, optional);
918 key!(disable_redzone, bool);
919 key!(eliminate_frame_pointer, bool);
920 key!(function_sections, bool);
924 key!(staticlib_prefix);
925 key!(staticlib_suffix);
926 key!(target_family, optional);
927 key!(abi_return_struct_as_int, bool);
928 key!(is_like_osx, bool);
929 key!(is_like_solaris, bool);
930 key!(is_like_windows, bool);
931 key!(is_like_msvc, bool);
932 key!(is_like_emscripten, bool);
933 key!(is_like_android, bool);
934 key!(linker_is_gnu, bool);
935 key!(allows_weak_linkage, bool);
936 key!(has_rpath, bool);
937 key!(no_default_libraries, bool);
938 key!(position_independent_executables, bool);
939 try!(key!(relro_level, RelroLevel));
940 key!(archive_format);
941 key!(allow_asm, bool);
942 key!(custom_unwind_resume, bool);
943 key!(exe_allocation_crate, optional);
944 key!(has_elf_tls, bool);
945 key!(obj_is_bitcode, bool);
946 key!(no_integrated_as, bool);
947 key!(max_atomic_width, Option<u64>);
948 key!(min_atomic_width, Option<u64>);
949 try!(key!(panic_strategy, PanicStrategy));
950 key!(crt_static_allows_dylibs, bool);
951 key!(crt_static_default, bool);
952 key!(crt_static_respected, bool);
953 key!(stack_probes, bool);
954 key!(min_global_align, Option<u64>);
955 key!(default_codegen_units, Option<u64>);
956 key!(trap_unreachable, bool);
957 key!(requires_lto, bool);
958 key!(singlethread, bool);
959 key!(no_builtins, bool);
960 key!(codegen_backend);
961 key!(default_hidden_visibility, bool);
962 key!(embed_bitcode, bool);
963 key!(emit_debug_gdb_scripts, bool);
964 key!(requires_uwtable, bool);
966 if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
967 for name in array.iter().filter_map(|abi| abi.as_string()) {
968 match lookup_abi(name) {
971 return Err(format!("The ABI \"{}\" is considered to be supported on \
972 all targets and cannot be blacklisted", abi))
975 base.options.abi_blacklist.push(abi)
977 None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
985 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
986 /// triple. Note that it could also just be a bare filename already, so also
987 /// check for that. If one of the hardcoded targets we know about, just
988 /// return it directly.
990 /// The error string could come from any of the APIs called, including
991 /// filesystem access and JSON decoding.
992 pub fn search(target_triple: &TargetTriple) -> Result<Target, String> {
994 use std::ffi::OsString;
998 fn load_file(path: &Path) -> Result<Target, String> {
999 let contents = fs::read(path).map_err(|e| e.to_string())?;
1000 let obj = json::from_reader(&mut &contents[..])
1001 .map_err(|e| e.to_string())?;
1002 Target::from_json(obj)
1005 match target_triple {
1006 &TargetTriple::TargetTriple(ref target_triple) => {
1007 // check if triple is in list of supported targets
1008 if let Ok(t) = load_specific(target_triple) {
1012 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1014 let mut target = target_triple.to_string();
1015 target.push_str(".json");
1016 PathBuf::from(target)
1019 let target_path = env::var_os("RUST_TARGET_PATH")
1020 .unwrap_or(OsString::new());
1022 // FIXME 16351: add a sane default search path?
1024 for dir in env::split_paths(&target_path) {
1025 let p = dir.join(&path);
1027 return load_file(&p);
1030 Err(format!("Could not find specification for target {:?}", target_triple))
1032 &TargetTriple::TargetPath(ref target_path) => {
1033 if target_path.is_file() {
1034 return load_file(&target_path);
1036 Err(format!("Target path {:?} is not a valid file", target_path))
1042 impl ToJson for Target {
1043 fn to_json(&self) -> Json {
1044 let mut d = BTreeMap::new();
1045 let default: TargetOptions = Default::default();
1047 macro_rules! target_val {
1048 ($attr:ident) => ( {
1049 let name = (stringify!($attr)).replace("_", "-");
1050 d.insert(name.to_string(), self.$attr.to_json());
1052 ($attr:ident, $key_name:expr) => ( {
1053 let name = $key_name;
1054 d.insert(name.to_string(), self.$attr.to_json());
1058 macro_rules! target_option_val {
1059 ($attr:ident) => ( {
1060 let name = (stringify!($attr)).replace("_", "-");
1061 if default.$attr != self.options.$attr {
1062 d.insert(name.to_string(), self.options.$attr.to_json());
1065 ($attr:ident, $key_name:expr) => ( {
1066 let name = $key_name;
1067 if default.$attr != self.options.$attr {
1068 d.insert(name.to_string(), self.options.$attr.to_json());
1071 (link_args - $attr:ident) => ( {
1072 let name = (stringify!($attr)).replace("_", "-");
1073 if default.$attr != self.options.$attr {
1074 let obj = self.options.$attr
1076 .map(|(k, v)| (k.desc().to_owned(), v.clone()))
1077 .collect::<BTreeMap<_, _>>();
1078 d.insert(name.to_string(), obj.to_json());
1081 (env - $attr:ident) => ( {
1082 let name = (stringify!($attr)).replace("_", "-");
1083 if default.$attr != self.options.$attr {
1084 let obj = self.options.$attr
1086 .map(|&(ref k, ref v)| k.clone() + "=" + &v)
1087 .collect::<Vec<_>>();
1088 d.insert(name.to_string(), obj.to_json());
1094 target_val!(llvm_target);
1095 target_val!(target_endian);
1096 target_val!(target_pointer_width);
1097 target_val!(target_c_int_width);
1099 target_val!(target_os, "os");
1100 target_val!(target_env, "env");
1101 target_val!(target_vendor, "vendor");
1102 target_val!(data_layout);
1103 target_val!(linker_flavor);
1105 target_option_val!(is_builtin);
1106 target_option_val!(linker);
1107 target_option_val!(link_args - pre_link_args);
1108 target_option_val!(link_args - pre_link_args_crt);
1109 target_option_val!(pre_link_objects_exe);
1110 target_option_val!(pre_link_objects_exe_crt);
1111 target_option_val!(pre_link_objects_dll);
1112 target_option_val!(link_args - late_link_args);
1113 target_option_val!(post_link_objects);
1114 target_option_val!(post_link_objects_crt);
1115 target_option_val!(link_args - post_link_args);
1116 target_option_val!(env - link_env);
1117 target_option_val!(asm_args);
1118 target_option_val!(cpu);
1119 target_option_val!(features);
1120 target_option_val!(dynamic_linking);
1121 target_option_val!(only_cdylib);
1122 target_option_val!(executables);
1123 target_option_val!(relocation_model);
1124 target_option_val!(code_model);
1125 target_option_val!(tls_model);
1126 target_option_val!(disable_redzone);
1127 target_option_val!(eliminate_frame_pointer);
1128 target_option_val!(function_sections);
1129 target_option_val!(dll_prefix);
1130 target_option_val!(dll_suffix);
1131 target_option_val!(exe_suffix);
1132 target_option_val!(staticlib_prefix);
1133 target_option_val!(staticlib_suffix);
1134 target_option_val!(target_family);
1135 target_option_val!(abi_return_struct_as_int);
1136 target_option_val!(is_like_osx);
1137 target_option_val!(is_like_solaris);
1138 target_option_val!(is_like_windows);
1139 target_option_val!(is_like_msvc);
1140 target_option_val!(is_like_emscripten);
1141 target_option_val!(is_like_android);
1142 target_option_val!(linker_is_gnu);
1143 target_option_val!(allows_weak_linkage);
1144 target_option_val!(has_rpath);
1145 target_option_val!(no_default_libraries);
1146 target_option_val!(position_independent_executables);
1147 target_option_val!(relro_level);
1148 target_option_val!(archive_format);
1149 target_option_val!(allow_asm);
1150 target_option_val!(custom_unwind_resume);
1151 target_option_val!(exe_allocation_crate);
1152 target_option_val!(has_elf_tls);
1153 target_option_val!(obj_is_bitcode);
1154 target_option_val!(no_integrated_as);
1155 target_option_val!(min_atomic_width);
1156 target_option_val!(max_atomic_width);
1157 target_option_val!(panic_strategy);
1158 target_option_val!(crt_static_allows_dylibs);
1159 target_option_val!(crt_static_default);
1160 target_option_val!(crt_static_respected);
1161 target_option_val!(stack_probes);
1162 target_option_val!(min_global_align);
1163 target_option_val!(default_codegen_units);
1164 target_option_val!(trap_unreachable);
1165 target_option_val!(requires_lto);
1166 target_option_val!(singlethread);
1167 target_option_val!(no_builtins);
1168 target_option_val!(codegen_backend);
1169 target_option_val!(default_hidden_visibility);
1170 target_option_val!(embed_bitcode);
1171 target_option_val!(emit_debug_gdb_scripts);
1172 target_option_val!(requires_uwtable);
1174 if default.abi_blacklist != self.options.abi_blacklist {
1175 d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
1176 .map(Abi::name).map(|name| name.to_json())
1177 .collect::<Vec<_>>().to_json());
1184 fn maybe_jemalloc() -> Option<String> {
1185 if cfg!(feature = "jemalloc") {
1186 Some("alloc_jemalloc".to_string())
1192 /// Either a target triple string or a path to a JSON file.
1193 #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
1194 pub enum TargetTriple {
1195 TargetTriple(String),
1196 TargetPath(PathBuf),
1200 /// Creates a target triple from the passed target triple string.
1201 pub fn from_triple(triple: &str) -> Self {
1202 TargetTriple::TargetTriple(triple.to_string())
1205 /// Creates a target triple from the passed target path.
1206 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
1207 let canonicalized_path = path.canonicalize()?;
1208 Ok(TargetTriple::TargetPath(canonicalized_path))
1211 /// Returns a string triple for this target.
1213 /// If this target is a path, the file name (without extension) is returned.
1214 pub fn triple(&self) -> &str {
1216 &TargetTriple::TargetTriple(ref triple) => triple,
1217 &TargetTriple::TargetPath(ref path) => {
1218 path.file_stem().expect("target path must not be empty").to_str()
1219 .expect("target path must be valid unicode")
1224 /// Returns an extended string triple for this target.
1226 /// If this target is a path, a hash of the path is appended to the triple returned
1228 pub fn debug_triple(&self) -> String {
1229 use std::hash::{Hash, Hasher};
1230 use std::collections::hash_map::DefaultHasher;
1232 let triple = self.triple();
1233 if let &TargetTriple::TargetPath(ref path) = self {
1234 let mut hasher = DefaultHasher::new();
1235 path.hash(&mut hasher);
1236 let hash = hasher.finish();
1237 format!("{}-{}", triple, hash)
1244 impl fmt::Display for TargetTriple {
1245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1246 write!(f, "{}", self.debug_triple())