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
30 //! will be given. `RUST_TARGET_PATH` includes `/etc/rustc` as its last entry,
31 //! to be searched by default.
33 //! Projects defining their own targets should use
34 //! `--target=path/to/my-awesome-platform.json` instead of adding to
35 //! `RUST_TARGET_PATH`.
37 //! # Defining a new target
39 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
40 //! this module defines the format the JSON file should take, though each
41 //! underscore in the field names should be replaced with a hyphen (`-`) in the
42 //! JSON file. Some fields are required in every target specification, such as
43 //! `data-layout`, `llvm-target`, `target-endian`, `target-pointer-width`, and
44 //! `arch`. In general, options passed to rustc with `-C` override the target's
45 //! settings, though `target-feature` and `link-args` will *add* to the list
46 //! specified by the target, rather than replace.
48 use serialize::json::Json;
49 use std::default::Default;
50 use std::io::prelude::*;
64 mod windows_msvc_base;
66 macro_rules! supported_targets {
67 ( $(($triple:expr, $module:ident)),+ ) => (
68 /// List of supported targets
69 pub const TARGETS: &'static [&'static str] = &[$($triple),*];
71 // this would use a match if stringify! were allowed in pattern position
72 fn load_specific(target: &str) -> Option<Target> {
74 let target = target.replace("-", "_");
77 else if target == stringify!($module) {
78 let t = $module::target();
79 debug!("Got builtin target: {:?}", t);
90 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
91 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
92 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
93 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
94 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
95 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
96 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
97 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
98 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
99 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
100 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
101 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
102 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
103 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
104 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
106 ("i686-linux-android", i686_linux_android),
107 ("arm-linux-androideabi", arm_linux_androideabi),
108 ("aarch64-linux-android", aarch64_linux_android),
110 ("i686-unknown-freebsd", i686_unknown_freebsd),
111 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
113 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
114 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
116 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
117 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
118 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
119 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
121 ("x86_64-apple-darwin", x86_64_apple_darwin),
122 ("i686-apple-darwin", i686_apple_darwin),
124 ("i386-apple-ios", i386_apple_ios),
125 ("x86_64-apple-ios", x86_64_apple_ios),
126 ("aarch64-apple-ios", aarch64_apple_ios),
127 ("armv7-apple-ios", armv7_apple_ios),
128 ("armv7s-apple-ios", armv7s_apple_ios),
130 ("x86_64-sun-solaris", x86_64_sun_solaris),
132 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
133 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
135 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
136 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
138 ("le32-unknown-nacl", le32_unknown_nacl),
139 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten)
142 /// Everything `rustc` knows about how to compile for a specific target.
144 /// Every field here must be specified, and has no default value.
145 #[derive(Clone, Debug)]
147 /// Target triple to pass to LLVM.
148 pub llvm_target: String,
149 /// String to use as the `target_endian` `cfg` variable.
150 pub target_endian: String,
151 /// String to use as the `target_pointer_width` `cfg` variable.
152 pub target_pointer_width: String,
153 /// OS name to use for conditional compilation.
154 pub target_os: String,
155 /// Environment name to use for conditional compilation.
156 pub target_env: String,
157 /// Vendor name to use for conditional compilation.
158 pub target_vendor: String,
159 /// Architecture to use for ABI considerations. Valid options: "x86",
160 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
162 /// Optional settings with defaults.
163 pub options: TargetOptions,
166 /// Optional aspects of a target specification.
168 /// This has an implementation of `Default`, see each field for what the default is. In general,
169 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
170 #[derive(Clone, Debug)]
171 pub struct TargetOptions {
172 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
173 pub data_layout: Option<String>,
174 /// Linker to invoke. Defaults to "cc".
176 /// Archive utility to use when managing archives. Defaults to "ar".
179 /// Linker arguments that are unconditionally passed *before* any
180 /// user-defined libraries.
181 pub pre_link_args: Vec<String>,
182 /// Objects to link before all others, always found within the
184 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
185 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
186 /// Linker arguments that are unconditionally passed after any
187 /// user-defined but before post_link_objects. Standard platform
188 /// libraries that should be always be linked to, usually go here.
189 pub late_link_args: Vec<String>,
190 /// Objects to link after all others, always found within the
192 pub post_link_objects: Vec<String>,
193 /// Linker arguments that are unconditionally passed *after* any
194 /// user-defined libraries.
195 pub post_link_args: Vec<String>,
197 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
200 /// Default target features to pass to LLVM. These features will *always* be
201 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
202 /// -mattr=$features`.
203 pub features: String,
204 /// Whether dynamic linking is available on this target. Defaults to false.
205 pub dynamic_linking: bool,
206 /// Whether executables are available on this target. iOS, for example, only allows static
207 /// libraries. Defaults to false.
208 pub executables: bool,
209 /// Relocation model to use in object file. Corresponds to `llc
210 /// -relocation-model=$relocation_model`. Defaults to "pic".
211 pub relocation_model: String,
212 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
213 pub code_model: String,
214 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
215 pub disable_redzone: bool,
216 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
217 pub eliminate_frame_pointer: bool,
218 /// Emit each function in its own section. Defaults to true.
219 pub function_sections: bool,
220 /// String to prepend to the name of every dynamic library. Defaults to "lib".
221 pub dll_prefix: String,
222 /// String to append to the name of every dynamic library. Defaults to ".so".
223 pub dll_suffix: String,
224 /// String to append to the name of every executable.
225 pub exe_suffix: String,
226 /// String to prepend to the name of every static library. Defaults to "lib".
227 pub staticlib_prefix: String,
228 /// String to append to the name of every static library. Defaults to ".a".
229 pub staticlib_suffix: String,
230 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
231 pub target_family: Option<String>,
232 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
233 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
234 pub is_like_osx: bool,
235 /// Whether the target toolchain is like Solaris's.
236 /// Only useful for compiling against Illumos/Solaris,
237 /// as they have a different set of linker flags. Defaults to false.
238 pub is_like_solaris: bool,
239 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
240 /// only really used for figuring out how to find libraries, since Windows uses its own
241 /// library naming convention. Defaults to false.
242 pub is_like_windows: bool,
243 pub is_like_msvc: bool,
244 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
245 /// Defaults to false.
246 pub is_like_android: bool,
247 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
248 pub linker_is_gnu: bool,
249 /// Whether the linker support rpaths or not. Defaults to false.
251 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
252 /// will emit references to the functions that compiler-rt provides.
253 pub no_compiler_rt: bool,
254 /// Whether to disable linking to the default libraries, typically corresponds
255 /// to `-nodefaultlibs`. Defaults to true.
256 pub no_default_libraries: bool,
257 /// Dynamically linked executables can be compiled as position independent
258 /// if the default relocation model of position independent code is not
259 /// changed. This is a requirement to take advantage of ASLR, as otherwise
260 /// the functions in the executable are not randomized and can be used
261 /// during an exploit of a vulnerability in any code.
262 pub position_independent_executables: bool,
263 /// Format that archives should be emitted in. This affects whether we use
264 /// LLVM to assemble an archive or fall back to the system linker, and
265 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
266 /// the system linker to be used.
267 pub archive_format: String,
268 /// Is asm!() allowed? Defaults to true.
270 /// Whether the target uses a custom unwind resumption routine.
271 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
272 /// defined in libgcc. If this option is enabled, the target must provide
273 /// `eh_unwind_resume` lang item.
274 pub custom_unwind_resume: bool,
276 /// Default crate for allocation symbols to link against
277 pub lib_allocation_crate: String,
278 pub exe_allocation_crate: String,
280 /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
282 pub has_elf_tls: bool,
283 // This is mainly for easy compatibility with emscripten.
284 // If we give emcc .o files that are actually .bc files it
286 pub obj_is_bitcode: bool,
289 impl Default for TargetOptions {
290 /// Create a set of "sane defaults" for any target. This is still
291 /// incomplete, and if used for compilation, will certainly not work.
292 fn default() -> TargetOptions {
295 linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
296 ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
297 pre_link_args: Vec::new(),
298 post_link_args: Vec::new(),
299 cpu: "generic".to_string(),
300 features: "".to_string(),
301 dynamic_linking: false,
303 relocation_model: "pic".to_string(),
304 code_model: "default".to_string(),
305 disable_redzone: false,
306 eliminate_frame_pointer: true,
307 function_sections: true,
308 dll_prefix: "lib".to_string(),
309 dll_suffix: ".so".to_string(),
310 exe_suffix: "".to_string(),
311 staticlib_prefix: "lib".to_string(),
312 staticlib_suffix: ".a".to_string(),
315 is_like_solaris: false,
316 is_like_windows: false,
317 is_like_android: false,
319 linker_is_gnu: false,
321 no_compiler_rt: false,
322 no_default_libraries: true,
323 position_independent_executables: false,
324 pre_link_objects_exe: Vec::new(),
325 pre_link_objects_dll: Vec::new(),
326 post_link_objects: Vec::new(),
327 late_link_args: Vec::new(),
328 archive_format: "gnu".to_string(),
329 custom_unwind_resume: false,
330 lib_allocation_crate: "alloc_system".to_string(),
331 exe_allocation_crate: "alloc_system".to_string(),
334 obj_is_bitcode: false,
340 /// Given a function ABI, turn "System" into the correct ABI for this target.
341 pub fn adjust_abi(&self, abi: Abi) -> Abi {
344 if self.options.is_like_windows && self.arch == "x86" {
354 /// Load a target descriptor from a JSON object.
355 pub fn from_json(obj: Json) -> Target {
356 // this is 1. ugly, 2. error prone.
358 let get_req_field = |name: &str| {
360 .map(|s| s.as_string())
361 .and_then(|os| os.map(|s| s.to_string())) {
364 panic!("Field {} in target specification is required", name)
369 let get_opt_field = |name: &str, default: &str| {
370 obj.find(name).and_then(|s| s.as_string())
371 .map(|s| s.to_string())
372 .unwrap_or(default.to_string())
375 let mut base = Target {
376 llvm_target: get_req_field("llvm-target"),
377 target_endian: get_req_field("target-endian"),
378 target_pointer_width: get_req_field("target-pointer-width"),
379 arch: get_req_field("arch"),
380 target_os: get_req_field("os"),
381 target_env: get_opt_field("env", ""),
382 target_vendor: get_opt_field("vendor", "unknown"),
383 options: Default::default(),
387 ($key_name:ident) => ( {
388 let name = (stringify!($key_name)).replace("_", "-");
389 obj.find(&name[..]).map(|o| o.as_string()
390 .map(|s| base.options.$key_name = s.to_string()));
392 ($key_name:ident, bool) => ( {
393 let name = (stringify!($key_name)).replace("_", "-");
395 .map(|o| o.as_boolean()
396 .map(|s| base.options.$key_name = s));
398 ($key_name:ident, list) => ( {
399 let name = (stringify!($key_name)).replace("_", "-");
400 obj.find(&name[..]).map(|o| o.as_array()
401 .map(|v| base.options.$key_name = v.iter()
402 .map(|a| a.as_string().unwrap().to_string()).collect()
406 ($key_name:ident, optional) => ( {
407 let name = (stringify!($key_name)).replace("_", "-");
408 if let Some(o) = obj.find(&name[..]) {
409 base.options.$key_name = o
411 .map(|s| s.to_string() );
419 key!(relocation_model);
424 key!(staticlib_prefix);
425 key!(staticlib_suffix);
427 key!(data_layout, optional);
428 key!(dynamic_linking, bool);
429 key!(executables, bool);
430 key!(disable_redzone, bool);
431 key!(eliminate_frame_pointer, bool);
432 key!(function_sections, bool);
433 key!(target_family, optional);
434 key!(is_like_osx, bool);
435 key!(is_like_windows, bool);
436 key!(linker_is_gnu, bool);
437 key!(has_rpath, bool);
438 key!(no_compiler_rt, bool);
439 key!(no_default_libraries, bool);
440 key!(pre_link_args, list);
441 key!(post_link_args, list);
442 key!(archive_format);
443 key!(allow_asm, bool);
444 key!(custom_unwind_resume, bool);
449 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
450 /// triple. Note that it could also just be a bare filename already, so also
451 /// check for that. If one of the hardcoded targets we know about, just
452 /// return it directly.
454 /// The error string could come from any of the APIs called, including
455 /// filesystem access and JSON decoding.
456 pub fn search(target: &str) -> Result<Target, String> {
458 use std::ffi::OsString;
460 use std::path::{Path, PathBuf};
463 fn load_file(path: &Path) -> Result<Target, String> {
464 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
465 let mut contents = Vec::new();
466 try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
467 let obj = try!(json::from_reader(&mut &contents[..])
468 .map_err(|e| e.to_string()));
469 Ok(Target::from_json(obj))
472 if let Some(t) = load_specific(target) {
476 let path = Path::new(target);
479 return load_file(&path);
483 let mut target = target.to_string();
484 target.push_str(".json");
485 PathBuf::from(target)
488 let target_path = env::var_os("RUST_TARGET_PATH")
489 .unwrap_or(OsString::new());
491 // FIXME 16351: add a sane default search path?
493 for dir in env::split_paths(&target_path) {
494 let p = dir.join(&path);
496 return load_file(&p);
500 Err(format!("Could not find specification for target {:?}", target))
504 fn maybe_jemalloc() -> String {
505 if cfg!(feature = "jemalloc") {
506 "alloc_jemalloc".to_string()
508 "alloc_system".to_string()