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