1 // Copyright 2014 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-word-size`, 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 syntax::{diagnostic, abi};
50 use std::default::Default;
51 use std::io::fs::PathExtensions;
60 mod arm_linux_androideabi;
61 mod arm_unknown_linux_gnueabi;
62 mod arm_unknown_linux_gnueabihf;
63 mod i686_apple_darwin;
65 mod i686_pc_windows_gnu;
66 mod i686_unknown_dragonfly;
67 mod i686_unknown_linux_gnu;
68 mod mips_unknown_linux_gnu;
69 mod mipsel_unknown_linux_gnu;
70 mod x86_64_apple_darwin;
71 mod x86_64_pc_windows_gnu;
72 mod x86_64_unknown_freebsd;
73 mod x86_64_unknown_dragonfly;
74 mod x86_64_unknown_linux_gnu;
76 /// Everything `rustc` knows about how to compile for a specific target.
78 /// Every field here must be specified, and has no default value.
79 #[deriving(Clone, Show)]
81 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
82 pub data_layout: String,
83 /// Target triple to pass to LLVM.
84 pub llvm_target: String,
85 /// String to use as the `target_endian` `cfg` variable.
86 pub target_endian: String,
87 /// String to use as the `target_word_size` `cfg` variable.
88 pub target_word_size: String,
89 /// OS name to use for conditional compilation.
90 pub target_os: String,
91 /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm", and
92 /// "mips". "mips" includes "mipsel".
94 /// Optional settings with defaults.
95 pub options: TargetOptions,
98 /// Optional aspects of a target specification.
100 /// This has an implementation of `Default`, see each field for what the default is. In general,
101 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
102 #[deriving(Clone, Show)]
103 pub struct TargetOptions {
104 /// Linker to invoke. Defaults to "cc".
106 /// Linker arguments that are unconditionally passed *before* any user-defined libraries.
107 pub pre_link_args: Vec<String>,
108 /// Linker arguments that are unconditionally passed *after* any user-defined libraries.
109 pub post_link_args: Vec<String>,
110 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults to "default".
112 /// Default target features to pass to LLVM. These features will *always* be passed, and cannot
113 /// be disabled even via `-C`. Corresponds to `llc -mattr=$features`.
114 pub features: String,
115 /// Whether dynamic linking is available on this target. Defaults to false.
116 pub dynamic_linking: bool,
117 /// Whether executables are available on this target. iOS, for example, only allows static
118 /// libraries. Defaults to false.
119 pub executables: bool,
120 /// Whether LLVM's segmented stack prelude is supported by whatever runtime is available.
121 /// Will emit stack checks and calls to __morestack. Defaults to false.
123 /// Relocation model to use in object file. Corresponds to `llc
124 /// -relocation-model=$relocation_model`. Defaults to "pic".
125 pub relocation_model: String,
126 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
127 pub code_model: String,
128 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
129 pub disable_redzone: bool,
130 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
131 pub eliminate_frame_pointer: bool,
132 /// Emit each function in its own section. Defaults to true.
133 pub function_sections: bool,
134 /// String to prepend to the name of every dynamic library. Defaults to "lib".
135 pub dll_prefix: String,
136 /// String to append to the name of every dynamic library. Defaults to ".so".
137 pub dll_suffix: String,
138 /// String to append to the name of every executable.
139 pub exe_suffix: String,
140 /// String to prepend to the name of every static library. Defaults to "lib".
141 pub staticlib_prefix: String,
142 /// String to append to the name of every static library. Defaults to ".a".
143 pub staticlib_suffix: String,
144 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
145 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
146 pub is_like_osx: bool,
147 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
148 /// only realy used for figuring out how to find libraries, since Windows uses its own
149 /// library naming convention. Defaults to false.
150 pub is_like_windows: bool,
151 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
152 pub linker_is_gnu: bool,
153 /// Whether the linker support rpaths or not. Defaults to false.
155 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM will emit references
156 /// to the functions that compiler-rt provides.
157 pub no_compiler_rt: bool,
158 /// Dynamically linked executables can be compiled as position independent if the default
159 /// relocation model of position independent code is not changed. This is a requirement to take
160 /// advantage of ASLR, as otherwise the functions in the executable are not randomized and can
161 /// be used during an exploit of a vulnerability in any code.
162 pub position_independent_executables: bool,
165 impl Default for TargetOptions {
166 /// Create a set of "sane defaults" for any target. This is still incomplete, and if used for
167 /// compilation, will certainly not work.
168 fn default() -> TargetOptions {
170 linker: "cc".to_string(),
171 pre_link_args: Vec::new(),
172 post_link_args: Vec::new(),
173 cpu: "generic".to_string(),
174 features: "".to_string(),
175 dynamic_linking: false,
178 relocation_model: "pic".to_string(),
179 code_model: "default".to_string(),
180 disable_redzone: false,
181 eliminate_frame_pointer: true,
182 function_sections: true,
183 dll_prefix: "lib".to_string(),
184 dll_suffix: ".so".to_string(),
185 exe_suffix: "".to_string(),
186 staticlib_prefix: "lib".to_string(),
187 staticlib_suffix: ".a".to_string(),
189 is_like_windows: false,
190 linker_is_gnu: false,
192 no_compiler_rt: false,
193 position_independent_executables: false,
199 /// Given a function ABI, turn "System" into the correct ABI for this target.
200 pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
203 if self.options.is_like_windows && self.arch == "x86" {
213 /// Load a target descriptor from a JSON object.
214 pub fn from_json(obj: Json) -> Target {
215 // this is 1. ugly, 2. error prone.
218 let handler = diagnostic::default_handler(diagnostic::Auto, None);
220 let get_req_field = |name: &str| {
222 .map(|s| s.as_string())
223 .and_then(|os| os.map(|s| s.to_string())) {
226 handler.fatal((format!("Field {} in target specification is required", name))
231 let mut base = Target {
232 data_layout: get_req_field("data-layout"),
233 llvm_target: get_req_field("llvm-target"),
234 target_endian: get_req_field("target-endian"),
235 target_word_size: get_req_field("target-word-size"),
236 arch: get_req_field("arch"),
237 target_os: get_req_field("os"),
238 options: Default::default(),
242 ($key_name:ident) => ( {
243 let name = (stringify!($key_name)).replace("_", "-");
244 obj.find(name[]).map(|o| o.as_string()
245 .map(|s| base.options.$key_name = s.to_string()));
247 ($key_name:ident, bool) => ( {
248 let name = (stringify!($key_name)).replace("_", "-");
249 obj.find(name[]).map(|o| o.as_boolean().map(|s| base.options.$key_name = s));
251 ($key_name:ident, list) => ( {
252 let name = (stringify!($key_name)).replace("_", "-");
253 obj.find(name[]).map(|o| o.as_array()
254 .map(|v| base.options.$key_name = v.iter()
255 .map(|a| a.as_string().unwrap().to_string()).collect()
263 key!(relocation_model);
268 key!(staticlib_prefix);
269 key!(staticlib_suffix);
271 key!(dynamic_linking, bool);
272 key!(executables, bool);
273 key!(morestack, bool);
274 key!(disable_redzone, bool);
275 key!(eliminate_frame_pointer, bool);
276 key!(function_sections, bool);
277 key!(is_like_osx, bool);
278 key!(is_like_windows, bool);
279 key!(linker_is_gnu, bool);
280 key!(has_rpath, bool);
281 key!(no_compiler_rt, bool);
282 key!(pre_link_args, list);
283 key!(post_link_args, list);
288 /// Search RUST_TARGET_PATH for a JSON file specifying the given target triple. Note that it
289 /// could also just be a bare filename already, so also check for that. If one of the hardcoded
290 /// targets we know about, just return it directly.
292 /// The error string could come from any of the APIs called, including filesystem access and
294 pub fn search(target: &str) -> Result<Target, String> {
300 fn load_file(path: &Path) -> Result<Target, String> {
301 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
302 let obj = try!(json::from_reader(&mut f).map_err(|e| e.to_string()));
303 Ok(Target::from_json(obj))
306 // this would use a match if stringify! were allowed in pattern position
307 macro_rules! load_specific (
308 ( $($name:ident),+ ) => (
310 let target = target.replace("-", "_");
313 else if target == stringify!($name) {
314 let t = $name::target();
315 debug!("Got builtin target: {}", t);
319 else if target == "x86_64-w64-mingw32" {
320 let t = x86_64_pc_windows_gnu::target();
322 } else if target == "i686-w64-mingw32" {
323 let t = i686_pc_windows_gnu::target();
331 x86_64_unknown_linux_gnu,
332 i686_unknown_linux_gnu,
333 mips_unknown_linux_gnu,
334 mipsel_unknown_linux_gnu,
335 arm_linux_androideabi,
336 arm_unknown_linux_gnueabi,
337 arm_unknown_linux_gnueabihf,
339 x86_64_unknown_freebsd,
341 i686_unknown_dragonfly,
342 x86_64_unknown_dragonfly,
349 x86_64_pc_windows_gnu,
354 let path = Path::new(target);
357 return load_file(&path);
361 let mut target = target.to_string();
362 target.push_str(".json");
366 let target_path = os::getenv("RUST_TARGET_PATH").unwrap_or(String::new());
368 let paths = os::split_paths(target_path.as_slice());
369 // FIXME 16351: add a sane default search path?
371 for dir in paths.iter() {
372 let p = dir.join(path.clone());
374 return load_file(&p);
378 Err(format!("Could not find specification for target {}", target))