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)),+ ) => (
70 /// List of supported targets
71 pub const TARGETS: &'static [&'static str] = &[$($triple),*];
73 // this would use a match if stringify! were allowed in pattern position
74 fn load_specific(target: &str) -> Option<Target> {
75 let target = target.replace("-", "_");
78 else if target == stringify!($module) {
79 let t = $module::target();
80 debug!("Got builtin target: {:?}", t);
91 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
92 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
93 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
94 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
95 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
96 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
97 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
98 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
99 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
100 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
101 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
102 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
103 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
104 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
105 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
106 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
108 ("i686-linux-android", i686_linux_android),
109 ("arm-linux-androideabi", arm_linux_androideabi),
110 ("aarch64-linux-android", aarch64_linux_android),
112 ("i686-unknown-freebsd", i686_unknown_freebsd),
113 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
115 ("i686-unknown-dragonfly", i686_unknown_dragonfly),
116 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
118 ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
119 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
120 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
121 ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
123 ("x86_64-apple-darwin", x86_64_apple_darwin),
124 ("i686-apple-darwin", i686_apple_darwin),
126 ("i386-apple-ios", i386_apple_ios),
127 ("x86_64-apple-ios", x86_64_apple_ios),
128 ("aarch64-apple-ios", aarch64_apple_ios),
129 ("armv7-apple-ios", armv7_apple_ios),
130 ("armv7s-apple-ios", armv7s_apple_ios),
132 ("x86_64-sun-solaris", x86_64_sun_solaris),
134 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
135 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
137 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
138 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
140 ("le32-unknown-nacl", le32_unknown_nacl),
141 ("asmjs-unknown-emscripten", asmjs_unknown_emscripten)
144 /// Everything `rustc` knows about how to compile for a specific target.
146 /// Every field here must be specified, and has no default value.
147 #[derive(Clone, Debug)]
149 /// Target triple to pass to LLVM.
150 pub llvm_target: String,
151 /// String to use as the `target_endian` `cfg` variable.
152 pub target_endian: String,
153 /// String to use as the `target_pointer_width` `cfg` variable.
154 pub target_pointer_width: String,
155 /// OS name to use for conditional compilation.
156 pub target_os: String,
157 /// Environment name to use for conditional compilation.
158 pub target_env: String,
159 /// Vendor name to use for conditional compilation.
160 pub target_vendor: String,
161 /// Architecture to use for ABI considerations. Valid options: "x86",
162 /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
164 /// Optional settings with defaults.
165 pub options: TargetOptions,
168 /// Optional aspects of a target specification.
170 /// This has an implementation of `Default`, see each field for what the default is. In general,
171 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
172 #[derive(Clone, Debug)]
173 pub struct TargetOptions {
174 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
175 pub data_layout: Option<String>,
176 /// Linker to invoke. Defaults to "cc".
178 /// Archive utility to use when managing archives. Defaults to "ar".
181 /// Linker arguments that are unconditionally passed *before* any
182 /// user-defined libraries.
183 pub pre_link_args: Vec<String>,
184 /// Objects to link before all others, always found within the
186 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
187 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
188 /// Linker arguments that are unconditionally passed after any
189 /// user-defined but before post_link_objects. Standard platform
190 /// libraries that should be always be linked to, usually go here.
191 pub late_link_args: Vec<String>,
192 /// Objects to link after all others, always found within the
194 pub post_link_objects: Vec<String>,
195 /// Linker arguments that are unconditionally passed *after* any
196 /// user-defined libraries.
197 pub post_link_args: Vec<String>,
199 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
202 /// Default target features to pass to LLVM. These features will *always* be
203 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
204 /// -mattr=$features`.
205 pub features: String,
206 /// Whether dynamic linking is available on this target. Defaults to false.
207 pub dynamic_linking: bool,
208 /// Whether executables are available on this target. iOS, for example, only allows static
209 /// libraries. Defaults to false.
210 pub executables: bool,
211 /// Relocation model to use in object file. Corresponds to `llc
212 /// -relocation-model=$relocation_model`. Defaults to "pic".
213 pub relocation_model: String,
214 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
215 pub code_model: String,
216 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
217 pub disable_redzone: bool,
218 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
219 pub eliminate_frame_pointer: bool,
220 /// Emit each function in its own section. Defaults to true.
221 pub function_sections: bool,
222 /// String to prepend to the name of every dynamic library. Defaults to "lib".
223 pub dll_prefix: String,
224 /// String to append to the name of every dynamic library. Defaults to ".so".
225 pub dll_suffix: String,
226 /// String to append to the name of every executable.
227 pub exe_suffix: String,
228 /// String to prepend to the name of every static library. Defaults to "lib".
229 pub staticlib_prefix: String,
230 /// String to append to the name of every static library. Defaults to ".a".
231 pub staticlib_suffix: String,
232 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
233 pub target_family: Option<String>,
234 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
235 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
236 pub is_like_osx: bool,
237 /// Whether the target toolchain is like Solaris's.
238 /// Only useful for compiling against Illumos/Solaris,
239 /// as they have a different set of linker flags. Defaults to false.
240 pub is_like_solaris: bool,
241 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
242 /// only really used for figuring out how to find libraries, since Windows uses its own
243 /// library naming convention. Defaults to false.
244 pub is_like_windows: bool,
245 pub is_like_msvc: bool,
246 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
247 /// Defaults to false.
248 pub is_like_android: bool,
249 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
250 pub linker_is_gnu: bool,
251 /// Whether the linker support rpaths or not. Defaults to false.
253 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
254 /// will emit references to the functions that compiler-rt provides.
255 pub no_compiler_rt: bool,
256 /// Whether to disable linking to the default libraries, typically corresponds
257 /// to `-nodefaultlibs`. Defaults to true.
258 pub no_default_libraries: bool,
259 /// Dynamically linked executables can be compiled as position independent
260 /// if the default relocation model of position independent code is not
261 /// changed. This is a requirement to take advantage of ASLR, as otherwise
262 /// the functions in the executable are not randomized and can be used
263 /// during an exploit of a vulnerability in any code.
264 pub position_independent_executables: bool,
265 /// Format that archives should be emitted in. This affects whether we use
266 /// LLVM to assemble an archive or fall back to the system linker, and
267 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
268 /// the system linker to be used.
269 pub archive_format: String,
270 /// Is asm!() allowed? Defaults to true.
272 /// Whether the target uses a custom unwind resumption routine.
273 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
274 /// defined in libgcc. If this option is enabled, the target must provide
275 /// `eh_unwind_resume` lang item.
276 pub custom_unwind_resume: bool,
278 /// Default crate for allocation symbols to link against
279 pub lib_allocation_crate: String,
280 pub exe_allocation_crate: String,
282 /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
284 pub has_elf_tls: bool,
285 // This is mainly for easy compatibility with emscripten.
286 // If we give emcc .o files that are actually .bc files it
288 pub obj_is_bitcode: bool,
291 impl Default for TargetOptions {
292 /// Create a set of "sane defaults" for any target. This is still
293 /// incomplete, and if used for compilation, will certainly not work.
294 fn default() -> TargetOptions {
297 linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
298 ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
299 pre_link_args: Vec::new(),
300 post_link_args: Vec::new(),
301 cpu: "generic".to_string(),
302 features: "".to_string(),
303 dynamic_linking: false,
305 relocation_model: "pic".to_string(),
306 code_model: "default".to_string(),
307 disable_redzone: false,
308 eliminate_frame_pointer: true,
309 function_sections: true,
310 dll_prefix: "lib".to_string(),
311 dll_suffix: ".so".to_string(),
312 exe_suffix: "".to_string(),
313 staticlib_prefix: "lib".to_string(),
314 staticlib_suffix: ".a".to_string(),
317 is_like_solaris: false,
318 is_like_windows: false,
319 is_like_android: false,
321 linker_is_gnu: false,
323 no_compiler_rt: false,
324 no_default_libraries: true,
325 position_independent_executables: false,
326 pre_link_objects_exe: Vec::new(),
327 pre_link_objects_dll: Vec::new(),
328 post_link_objects: Vec::new(),
329 late_link_args: Vec::new(),
330 archive_format: "gnu".to_string(),
331 custom_unwind_resume: false,
332 lib_allocation_crate: "alloc_system".to_string(),
333 exe_allocation_crate: "alloc_system".to_string(),
336 obj_is_bitcode: false,
342 /// Given a function ABI, turn "System" into the correct ABI for this target.
343 pub fn adjust_abi(&self, abi: Abi) -> Abi {
346 if self.options.is_like_windows && self.arch == "x86" {
356 /// Load a target descriptor from a JSON object.
357 pub fn from_json(obj: Json) -> Target {
358 // this is 1. ugly, 2. error prone.
360 let get_req_field = |name: &str| {
362 .map(|s| s.as_string())
363 .and_then(|os| os.map(|s| s.to_string())) {
366 panic!("Field {} in target specification is required", name)
371 let get_opt_field = |name: &str, default: &str| {
372 obj.find(name).and_then(|s| s.as_string())
373 .map(|s| s.to_string())
374 .unwrap_or(default.to_string())
377 let mut base = Target {
378 llvm_target: get_req_field("llvm-target"),
379 target_endian: get_req_field("target-endian"),
380 target_pointer_width: get_req_field("target-pointer-width"),
381 arch: get_req_field("arch"),
382 target_os: get_req_field("os"),
383 target_env: get_opt_field("env", ""),
384 target_vendor: get_opt_field("vendor", "unknown"),
385 options: Default::default(),
389 ($key_name:ident) => ( {
390 let name = (stringify!($key_name)).replace("_", "-");
391 obj.find(&name[..]).map(|o| o.as_string()
392 .map(|s| base.options.$key_name = s.to_string()));
394 ($key_name:ident, bool) => ( {
395 let name = (stringify!($key_name)).replace("_", "-");
397 .map(|o| o.as_boolean()
398 .map(|s| base.options.$key_name = s));
400 ($key_name:ident, list) => ( {
401 let name = (stringify!($key_name)).replace("_", "-");
402 obj.find(&name[..]).map(|o| o.as_array()
403 .map(|v| base.options.$key_name = v.iter()
404 .map(|a| a.as_string().unwrap().to_string()).collect()
408 ($key_name:ident, optional) => ( {
409 let name = (stringify!($key_name)).replace("_", "-");
410 if let Some(o) = obj.find(&name[..]) {
411 base.options.$key_name = o
413 .map(|s| s.to_string() );
421 key!(relocation_model);
426 key!(staticlib_prefix);
427 key!(staticlib_suffix);
429 key!(data_layout, optional);
430 key!(dynamic_linking, bool);
431 key!(executables, bool);
432 key!(disable_redzone, bool);
433 key!(eliminate_frame_pointer, bool);
434 key!(function_sections, bool);
435 key!(target_family, optional);
436 key!(is_like_osx, bool);
437 key!(is_like_windows, bool);
438 key!(linker_is_gnu, bool);
439 key!(has_rpath, bool);
440 key!(no_compiler_rt, bool);
441 key!(no_default_libraries, bool);
442 key!(pre_link_args, list);
443 key!(post_link_args, list);
444 key!(archive_format);
445 key!(allow_asm, bool);
446 key!(custom_unwind_resume, bool);
451 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
452 /// triple. Note that it could also just be a bare filename already, so also
453 /// check for that. If one of the hardcoded targets we know about, just
454 /// return it directly.
456 /// The error string could come from any of the APIs called, including
457 /// filesystem access and JSON decoding.
458 pub fn search(target: &str) -> Result<Target, String> {
460 use std::ffi::OsString;
462 use std::path::{Path, PathBuf};
465 fn load_file(path: &Path) -> Result<Target, String> {
466 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
467 let mut contents = Vec::new();
468 try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
469 let obj = try!(json::from_reader(&mut &contents[..])
470 .map_err(|e| e.to_string()));
471 Ok(Target::from_json(obj))
474 if let Some(t) = load_specific(target) {
478 let path = Path::new(target);
481 return load_file(&path);
485 let mut target = target.to_string();
486 target.push_str(".json");
487 PathBuf::from(target)
490 let target_path = env::var_os("RUST_TARGET_PATH")
491 .unwrap_or(OsString::new());
493 // FIXME 16351: add a sane default search path?
495 for dir in env::split_paths(&target_path) {
496 let p = dir.join(&path);
498 return load_file(&p);
502 Err(format!("Could not find specification for target {:?}", target))
506 fn maybe_jemalloc() -> String {
507 if cfg!(feature = "jemalloc") {
508 "alloc_jemalloc".to_string()
510 "alloc_system".to_string()