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::*;
51 use syntax::{diagnostic, abi};
63 mod windows_msvc_base;
65 /// Everything `rustc` knows about how to compile for a specific target.
67 /// Every field here must be specified, and has no default value.
68 #[derive(Clone, Debug)]
70 /// Target triple to pass to LLVM.
71 pub llvm_target: String,
72 /// String to use as the `target_endian` `cfg` variable.
73 pub target_endian: String,
74 /// String to use as the `target_pointer_width` `cfg` variable.
75 pub target_pointer_width: String,
76 /// OS name to use for conditional compilation.
77 pub target_os: String,
78 /// Environment name to use for conditional compilation.
79 pub target_env: String,
80 /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm",
81 /// "aarch64", "mips", and "powerpc". "mips" includes "mipsel".
83 /// Optional settings with defaults.
84 pub options: TargetOptions,
87 /// Optional aspects of a target specification.
89 /// This has an implementation of `Default`, see each field for what the default is. In general,
90 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
91 #[derive(Clone, Debug)]
92 pub struct TargetOptions {
93 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
94 pub data_layout: String,
95 /// Linker to invoke. Defaults to "cc".
97 /// Archive utility to use when managing archives. Defaults to "ar".
99 /// Linker arguments that are unconditionally passed *before* any
100 /// user-defined libraries.
101 pub pre_link_args: Vec<String>,
102 /// Linker arguments that are unconditionally passed *after* any
103 /// user-defined libraries.
104 pub post_link_args: Vec<String>,
105 /// Objects to link before and after all others, always found within the
107 pub pre_link_objects: Vec<String>,
108 pub post_link_objects: Vec<String>,
109 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
112 /// Default target features to pass to LLVM. These features will *always* be
113 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
114 /// -mattr=$features`.
115 pub features: String,
116 /// Whether dynamic linking is available on this target. Defaults to false.
117 pub dynamic_linking: bool,
118 /// Whether executables are available on this target. iOS, for example, only allows static
119 /// libraries. Defaults to false.
120 pub executables: bool,
121 /// Relocation model to use in object file. Corresponds to `llc
122 /// -relocation-model=$relocation_model`. Defaults to "pic".
123 pub relocation_model: String,
124 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
125 pub code_model: String,
126 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
127 pub disable_redzone: bool,
128 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
129 pub eliminate_frame_pointer: bool,
130 /// Emit each function in its own section. Defaults to true.
131 pub function_sections: bool,
132 /// String to prepend to the name of every dynamic library. Defaults to "lib".
133 pub dll_prefix: String,
134 /// String to append to the name of every dynamic library. Defaults to ".so".
135 pub dll_suffix: String,
136 /// String to append to the name of every executable.
137 pub exe_suffix: String,
138 /// String to prepend to the name of every static library. Defaults to "lib".
139 pub staticlib_prefix: String,
140 /// String to append to the name of every static library. Defaults to ".a".
141 pub staticlib_suffix: String,
142 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
143 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
144 pub is_like_osx: bool,
145 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
146 /// only really used for figuring out how to find libraries, since Windows uses its own
147 /// library naming convention. Defaults to false.
148 pub is_like_windows: bool,
149 pub is_like_msvc: bool,
150 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
151 /// Defaults to false.
152 pub is_like_android: bool,
153 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
154 pub linker_is_gnu: bool,
155 /// Whether the linker support rpaths or not. Defaults to false.
157 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
158 /// will emit references to the functions that compiler-rt provides.
159 pub no_compiler_rt: bool,
160 /// Dynamically linked executables can be compiled as position independent
161 /// if the default relocation model of position independent code is not
162 /// changed. This is a requirement to take advantage of ASLR, as otherwise
163 /// the functions in the executable are not randomized and can be used
164 /// during an exploit of a vulnerability in any code.
165 pub position_independent_executables: bool,
166 /// Format that archives should be emitted in. This affects whether we use
167 /// LLVM to assemble an archive or fall back to the system linker, and
168 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
169 /// the system linker to be used.
170 pub archive_format: String,
171 /// Whether the target uses a custom unwind resumption routine.
172 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
173 /// defined in libgcc. If this option is enabled, the target must provide
174 /// `eh_unwind_resume` lang item.
175 pub custom_unwind_resume: bool,
177 /// Default crate for allocation symbols to link against
178 pub lib_allocation_crate: String,
179 pub exe_allocation_crate: String,
182 impl Default for TargetOptions {
183 /// Create a set of "sane defaults" for any target. This is still
184 /// incomplete, and if used for compilation, will certainly not work.
185 fn default() -> TargetOptions {
187 data_layout: String::new(),
188 linker: "cc".to_string(),
189 ar: "ar".to_string(),
190 pre_link_args: Vec::new(),
191 post_link_args: Vec::new(),
192 cpu: "generic".to_string(),
193 features: "".to_string(),
194 dynamic_linking: false,
196 relocation_model: "pic".to_string(),
197 code_model: "default".to_string(),
198 disable_redzone: false,
199 eliminate_frame_pointer: true,
200 function_sections: true,
201 dll_prefix: "lib".to_string(),
202 dll_suffix: ".so".to_string(),
203 exe_suffix: "".to_string(),
204 staticlib_prefix: "lib".to_string(),
205 staticlib_suffix: ".a".to_string(),
207 is_like_windows: false,
208 is_like_android: false,
210 linker_is_gnu: false,
212 no_compiler_rt: false,
213 position_independent_executables: false,
214 pre_link_objects: Vec::new(),
215 post_link_objects: Vec::new(),
216 archive_format: String::new(),
217 custom_unwind_resume: false,
218 lib_allocation_crate: "alloc_system".to_string(),
219 exe_allocation_crate: "alloc_system".to_string(),
225 /// Given a function ABI, turn "System" into the correct ABI for this target.
226 pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
229 if self.options.is_like_windows && self.arch == "x86" {
239 /// Load a target descriptor from a JSON object.
240 pub fn from_json(obj: Json) -> Target {
241 // this is 1. ugly, 2. error prone.
244 let handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
246 let get_req_field = |name: &str| {
248 .map(|s| s.as_string())
249 .and_then(|os| os.map(|s| s.to_string())) {
252 handler.fatal(&format!("Field {} in target specification is required", name))
256 let mut base = Target {
257 llvm_target: get_req_field("llvm-target"),
258 target_endian: get_req_field("target-endian"),
259 target_pointer_width: get_req_field("target-pointer-width"),
260 arch: get_req_field("arch"),
261 target_os: get_req_field("os"),
262 target_env: obj.find("env").and_then(|s| s.as_string())
263 .map(|s| s.to_string()).unwrap_or(String::new()),
264 options: Default::default(),
268 ($key_name:ident) => ( {
269 let name = (stringify!($key_name)).replace("_", "-");
270 obj.find(&name[..]).map(|o| o.as_string()
271 .map(|s| base.options.$key_name = s.to_string()));
273 ($key_name:ident, bool) => ( {
274 let name = (stringify!($key_name)).replace("_", "-");
276 .map(|o| o.as_boolean()
277 .map(|s| base.options.$key_name = s));
279 ($key_name:ident, list) => ( {
280 let name = (stringify!($key_name)).replace("_", "-");
281 obj.find(&name[..]).map(|o| o.as_array()
282 .map(|v| base.options.$key_name = v.iter()
283 .map(|a| a.as_string().unwrap().to_string()).collect()
292 key!(relocation_model);
297 key!(staticlib_prefix);
298 key!(staticlib_suffix);
301 key!(dynamic_linking, bool);
302 key!(executables, bool);
303 key!(disable_redzone, bool);
304 key!(eliminate_frame_pointer, bool);
305 key!(function_sections, bool);
306 key!(is_like_osx, bool);
307 key!(is_like_windows, bool);
308 key!(linker_is_gnu, bool);
309 key!(has_rpath, bool);
310 key!(no_compiler_rt, bool);
311 key!(pre_link_args, list);
312 key!(post_link_args, list);
317 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
318 /// triple. Note that it could also just be a bare filename already, so also
319 /// check for that. If one of the hardcoded targets we know about, just
320 /// return it directly.
322 /// The error string could come from any of the APIs called, including
323 /// filesystem access and JSON decoding.
324 pub fn search(target: &str) -> Result<Target, String> {
326 use std::ffi::OsString;
328 use std::path::{Path, PathBuf};
331 fn load_file(path: &Path) -> Result<Target, String> {
332 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
333 let mut contents = Vec::new();
334 try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
335 let obj = try!(json::from_reader(&mut &contents[..])
336 .map_err(|e| e.to_string()));
337 Ok(Target::from_json(obj))
340 // this would use a match if stringify! were allowed in pattern position
341 macro_rules! load_specific {
342 ( $($name:ident),+ ) => (
345 let target = target.replace("-", "_");
348 else if target == stringify!($name) {
349 let t = $name::target();
350 debug!("Got builtin target: {:?}", t);
354 else if target == "x86_64-w64-mingw32" {
355 let t = x86_64_pc_windows_gnu::target();
357 } else if target == "i686-w64-mingw32" {
358 let t = i686_pc_windows_gnu::target();
366 x86_64_unknown_linux_gnu,
367 i686_unknown_linux_gnu,
368 mips_unknown_linux_gnu,
369 mipsel_unknown_linux_gnu,
370 powerpc_unknown_linux_gnu,
371 arm_unknown_linux_gnueabi,
372 arm_unknown_linux_gnueabihf,
373 aarch64_unknown_linux_gnu,
374 x86_64_unknown_linux_musl,
376 arm_linux_androideabi,
377 aarch64_linux_android,
379 i686_unknown_freebsd,
380 x86_64_unknown_freebsd,
382 i686_unknown_dragonfly,
383 x86_64_unknown_dragonfly,
385 x86_64_unknown_bitrig,
386 x86_64_unknown_openbsd,
387 x86_64_unknown_netbsd,
398 x86_64_pc_windows_gnu,
401 x86_64_pc_windows_msvc,
406 let path = Path::new(target);
409 return load_file(&path);
413 let mut target = target.to_string();
414 target.push_str(".json");
415 PathBuf::from(target)
418 let target_path = env::var_os("RUST_TARGET_PATH")
419 .unwrap_or(OsString::new());
421 // FIXME 16351: add a sane default search path?
423 for dir in env::split_paths(&target_path) {
424 let p = dir.join(&path);
426 return load_file(&p);
430 Err(format!("Could not find specification for target {:?}", target))
434 fn best_allocator() -> String {
435 if cfg!(disable_jemalloc) {
436 "alloc_system".to_string()
438 "alloc_jemalloc".to_string()