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-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;
64 mod arm_linux_androideabi;
65 mod arm_unknown_linux_gnueabi;
66 mod arm_unknown_linux_gnueabihf;
67 mod aarch64_apple_ios;
68 mod aarch64_unknown_linux_gnu;
69 mod i686_apple_darwin;
70 mod i686_pc_windows_gnu;
71 mod i686_unknown_dragonfly;
72 mod i686_unknown_linux_gnu;
73 mod mips_unknown_linux_gnu;
74 mod mipsel_unknown_linux_gnu;
75 mod powerpc_unknown_linux_gnu;
76 mod x86_64_apple_darwin;
78 mod x86_64_pc_windows_gnu;
79 mod x86_64_unknown_freebsd;
80 mod x86_64_unknown_dragonfly;
81 mod x86_64_unknown_linux_gnu;
83 /// Everything `rustc` knows about how to compile for a specific target.
85 /// Every field here must be specified, and has no default value.
86 #[derive(Clone, Show)]
88 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
89 pub data_layout: String,
90 /// Target triple to pass to LLVM.
91 pub llvm_target: String,
92 /// String to use as the `target_endian` `cfg` variable.
93 pub target_endian: String,
94 /// String to use as the `target_pointer_width` `cfg` variable.
95 pub target_pointer_width: String,
96 /// OS name to use for conditional compilation.
97 pub target_os: String,
98 /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm",
99 /// "aarch64", "mips", and "powerpc". "mips" includes "mipsel".
101 /// Optional settings with defaults.
102 pub options: TargetOptions,
105 /// Optional aspects of a target specification.
107 /// This has an implementation of `Default`, see each field for what the default is. In general,
108 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
109 #[derive(Clone, Show)]
110 pub struct TargetOptions {
111 /// Linker to invoke. Defaults to "cc".
113 /// Linker arguments that are unconditionally passed *before* any user-defined libraries.
114 pub pre_link_args: Vec<String>,
115 /// Linker arguments that are unconditionally passed *after* any user-defined libraries.
116 pub post_link_args: Vec<String>,
117 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults to "default".
119 /// Default target features to pass to LLVM. These features will *always* be passed, and cannot
120 /// be disabled even via `-C`. Corresponds to `llc -mattr=$features`.
121 pub features: String,
122 /// Whether dynamic linking is available on this target. Defaults to false.
123 pub dynamic_linking: bool,
124 /// Whether executables are available on this target. iOS, for example, only allows static
125 /// libraries. Defaults to false.
126 pub executables: bool,
127 /// Whether LLVM's segmented stack prelude is supported by whatever runtime is available.
128 /// Will emit stack checks and calls to __morestack. Defaults to false.
130 /// Relocation model to use in object file. Corresponds to `llc
131 /// -relocation-model=$relocation_model`. Defaults to "pic".
132 pub relocation_model: String,
133 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
134 pub code_model: String,
135 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
136 pub disable_redzone: bool,
137 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
138 pub eliminate_frame_pointer: bool,
139 /// Emit each function in its own section. Defaults to true.
140 pub function_sections: bool,
141 /// String to prepend to the name of every dynamic library. Defaults to "lib".
142 pub dll_prefix: String,
143 /// String to append to the name of every dynamic library. Defaults to ".so".
144 pub dll_suffix: String,
145 /// String to append to the name of every executable.
146 pub exe_suffix: String,
147 /// String to prepend to the name of every static library. Defaults to "lib".
148 pub staticlib_prefix: String,
149 /// String to append to the name of every static library. Defaults to ".a".
150 pub staticlib_suffix: String,
151 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
152 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
153 pub is_like_osx: bool,
154 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
155 /// only realy used for figuring out how to find libraries, since Windows uses its own
156 /// library naming convention. Defaults to false.
157 pub is_like_windows: bool,
158 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
159 pub linker_is_gnu: bool,
160 /// Whether the linker support rpaths or not. Defaults to false.
162 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM will emit references
163 /// to the functions that compiler-rt provides.
164 pub no_compiler_rt: bool,
165 /// Dynamically linked executables can be compiled as position independent if the default
166 /// relocation model of position independent code is not changed. This is a requirement to take
167 /// advantage of ASLR, as otherwise the functions in the executable are not randomized and can
168 /// be used during an exploit of a vulnerability in any code.
169 pub position_independent_executables: bool,
172 impl Default for TargetOptions {
173 /// Create a set of "sane defaults" for any target. This is still incomplete, and if used for
174 /// compilation, will certainly not work.
175 fn default() -> TargetOptions {
177 linker: "cc".to_string(),
178 pre_link_args: Vec::new(),
179 post_link_args: Vec::new(),
180 cpu: "generic".to_string(),
181 features: "".to_string(),
182 dynamic_linking: false,
185 relocation_model: "pic".to_string(),
186 code_model: "default".to_string(),
187 disable_redzone: false,
188 eliminate_frame_pointer: true,
189 function_sections: true,
190 dll_prefix: "lib".to_string(),
191 dll_suffix: ".so".to_string(),
192 exe_suffix: "".to_string(),
193 staticlib_prefix: "lib".to_string(),
194 staticlib_suffix: ".a".to_string(),
196 is_like_windows: false,
197 linker_is_gnu: false,
199 no_compiler_rt: false,
200 position_independent_executables: false,
206 /// Given a function ABI, turn "System" into the correct ABI for this target.
207 pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
210 if self.options.is_like_windows && self.arch == "x86" {
220 /// Load a target descriptor from a JSON object.
221 pub fn from_json(obj: Json) -> Target {
222 // this is 1. ugly, 2. error prone.
225 let handler = diagnostic::default_handler(diagnostic::Auto, None);
227 let get_req_field = |&: name: &str| {
229 .map(|s| s.as_string())
230 .and_then(|os| os.map(|s| s.to_string())) {
233 handler.fatal(&format!("Field {} in target specification is required", name)[])
237 let mut base = Target {
238 data_layout: get_req_field("data-layout"),
239 llvm_target: get_req_field("llvm-target"),
240 target_endian: get_req_field("target-endian"),
241 target_pointer_width: get_req_field("target-word-size"),
242 arch: get_req_field("arch"),
243 target_os: get_req_field("os"),
244 options: Default::default(),
248 ($key_name:ident) => ( {
249 let name = (stringify!($key_name)).replace("_", "-");
250 obj.find(&name[]).map(|o| o.as_string()
251 .map(|s| base.options.$key_name = s.to_string()));
253 ($key_name:ident, bool) => ( {
254 let name = (stringify!($key_name)).replace("_", "-");
256 .map(|o| o.as_boolean()
257 .map(|s| base.options.$key_name = s));
259 ($key_name:ident, list) => ( {
260 let name = (stringify!($key_name)).replace("_", "-");
261 obj.find(&name[]).map(|o| o.as_array()
262 .map(|v| base.options.$key_name = v.iter()
263 .map(|a| a.as_string().unwrap().to_string()).collect()
271 key!(relocation_model);
276 key!(staticlib_prefix);
277 key!(staticlib_suffix);
279 key!(dynamic_linking, bool);
280 key!(executables, bool);
281 key!(morestack, bool);
282 key!(disable_redzone, bool);
283 key!(eliminate_frame_pointer, bool);
284 key!(function_sections, bool);
285 key!(is_like_osx, bool);
286 key!(is_like_windows, bool);
287 key!(linker_is_gnu, bool);
288 key!(has_rpath, bool);
289 key!(no_compiler_rt, bool);
290 key!(pre_link_args, list);
291 key!(post_link_args, list);
296 /// Search RUST_TARGET_PATH for a JSON file specifying the given target triple. Note that it
297 /// could also just be a bare filename already, so also check for that. If one of the hardcoded
298 /// targets we know about, just return it directly.
300 /// The error string could come from any of the APIs called, including filesystem access and
302 pub fn search(target: &str) -> Result<Target, String> {
308 fn load_file(path: &Path) -> Result<Target, String> {
309 let mut f = try!(File::open(path).map_err(|e| format!("{:?}", e)));
310 let obj = try!(json::from_reader(&mut f).map_err(|e| format!("{:?}", e)));
311 Ok(Target::from_json(obj))
314 // this would use a match if stringify! were allowed in pattern position
315 macro_rules! load_specific {
316 ( $($name:ident),+ ) => (
318 let target = target.replace("-", "_");
321 else if target == stringify!($name) {
322 let t = $name::target();
323 debug!("Got builtin target: {:?}", t);
327 else if target == "x86_64-w64-mingw32" {
328 let t = x86_64_pc_windows_gnu::target();
330 } else if target == "i686-w64-mingw32" {
331 let t = i686_pc_windows_gnu::target();
339 x86_64_unknown_linux_gnu,
340 i686_unknown_linux_gnu,
341 mips_unknown_linux_gnu,
342 mipsel_unknown_linux_gnu,
343 powerpc_unknown_linux_gnu,
344 arm_linux_androideabi,
345 arm_unknown_linux_gnueabi,
346 arm_unknown_linux_gnueabihf,
347 aarch64_unknown_linux_gnu,
349 x86_64_unknown_freebsd,
351 i686_unknown_dragonfly,
352 x86_64_unknown_dragonfly,
363 x86_64_pc_windows_gnu,
368 let path = Path::new(target);
371 return load_file(&path);
375 let mut target = target.to_string();
376 target.push_str(".json");
380 let target_path = os::getenv("RUST_TARGET_PATH").unwrap_or(String::new());
382 let paths = os::split_paths(&target_path[]);
383 // FIXME 16351: add a sane default search path?
385 for dir in paths.iter() {
386 let p = dir.join(path.clone());
388 return load_file(&p);
392 Err(format!("Could not find specification for target {:?}", target))