]> git.proxmox.com Git - rustc.git/blob - src/librustc_back/target/mod.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / librustc_back / target / mod.rs
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.
4 //
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.
10
11 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
12 //!
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.
18 //!
19 //! # Using custom targets
20 //!
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.
32 //!
33 //! Projects defining their own targets should use
34 //! `--target=path/to/my-awesome-platform.json` instead of adding to
35 //! `RUST_TARGET_PATH`.
36 //!
37 //! # Defining a new target
38 //!
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.
47
48 use serialize::json::Json;
49 use std::default::Default;
50 use std::io::prelude::*;
51 use syntax::{diagnostic, abi};
52
53 mod android_base;
54 mod apple_base;
55 mod apple_ios_base;
56 mod bitrig_base;
57 mod dragonfly_base;
58 mod freebsd_base;
59 mod linux_base;
60 mod openbsd_base;
61 mod windows_base;
62
63 /// Everything `rustc` knows about how to compile for a specific target.
64 ///
65 /// Every field here must be specified, and has no default value.
66 #[derive(Clone, Debug)]
67 pub struct Target {
68 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
69 pub data_layout: String,
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".
82 pub arch: String,
83 /// Optional settings with defaults.
84 pub options: TargetOptions,
85 }
86
87 /// Optional aspects of a target specification.
88 ///
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 /// Linker to invoke. Defaults to "cc".
94 pub linker: String,
95 /// Linker arguments that are unconditionally passed *before* any
96 /// user-defined libraries.
97 pub pre_link_args: Vec<String>,
98 /// Linker arguments that are unconditionally passed *after* any
99 /// user-defined libraries.
100 pub post_link_args: Vec<String>,
101 /// Objects to link before and after all others, always found within the
102 /// sysroot folder.
103 pub pre_link_objects: Vec<String>,
104 pub post_link_objects: Vec<String>,
105 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
106 /// to "default".
107 pub cpu: String,
108 /// Default target features to pass to LLVM. These features will *always* be
109 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
110 /// -mattr=$features`.
111 pub features: String,
112 /// Whether dynamic linking is available on this target. Defaults to false.
113 pub dynamic_linking: bool,
114 /// Whether executables are available on this target. iOS, for example, only allows static
115 /// libraries. Defaults to false.
116 pub executables: bool,
117 /// Whether LLVM's segmented stack prelude is supported by whatever runtime is available.
118 /// Will emit stack checks and calls to __morestack. Defaults to false.
119 pub morestack: bool,
120 /// Relocation model to use in object file. Corresponds to `llc
121 /// -relocation-model=$relocation_model`. Defaults to "pic".
122 pub relocation_model: String,
123 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
124 pub code_model: String,
125 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
126 pub disable_redzone: bool,
127 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
128 pub eliminate_frame_pointer: bool,
129 /// Emit each function in its own section. Defaults to true.
130 pub function_sections: bool,
131 /// String to prepend to the name of every dynamic library. Defaults to "lib".
132 pub dll_prefix: String,
133 /// String to append to the name of every dynamic library. Defaults to ".so".
134 pub dll_suffix: String,
135 /// String to append to the name of every executable.
136 pub exe_suffix: String,
137 /// String to prepend to the name of every static library. Defaults to "lib".
138 pub staticlib_prefix: String,
139 /// String to append to the name of every static library. Defaults to ".a".
140 pub staticlib_suffix: String,
141 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
142 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
143 pub is_like_osx: bool,
144 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
145 /// only really used for figuring out how to find libraries, since Windows uses its own
146 /// library naming convention. Defaults to false.
147 pub is_like_windows: bool,
148 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
149 /// Defaults to false.
150 pub is_like_android: 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.
154 pub has_rpath: bool,
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,
163 }
164
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 {
169 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,
176 executables: false,
177 morestack: 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(),
188 is_like_osx: false,
189 is_like_windows: false,
190 is_like_android: false,
191 linker_is_gnu: false,
192 has_rpath: false,
193 no_compiler_rt: false,
194 position_independent_executables: false,
195 pre_link_objects: Vec::new(),
196 post_link_objects: Vec::new(),
197 }
198 }
199 }
200
201 impl Target {
202 /// Given a function ABI, turn "System" into the correct ABI for this target.
203 pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
204 match abi {
205 abi::System => {
206 if self.options.is_like_windows && self.arch == "x86" {
207 abi::Stdcall
208 } else {
209 abi::C
210 }
211 },
212 abi => abi
213 }
214 }
215
216 /// Load a target descriptor from a JSON object.
217 pub fn from_json(obj: Json) -> Target {
218 // this is 1. ugly, 2. error prone.
219
220
221 let handler = diagnostic::default_handler(diagnostic::Auto, None, true);
222
223 let get_req_field = |name: &str| {
224 match obj.find(name)
225 .map(|s| s.as_string())
226 .and_then(|os| os.map(|s| s.to_string())) {
227 Some(val) => val,
228 None =>
229 handler.fatal(&format!("Field {} in target specification is required", name))
230 }
231 };
232
233 let mut base = Target {
234 data_layout: get_req_field("data-layout"),
235 llvm_target: get_req_field("llvm-target"),
236 target_endian: get_req_field("target-endian"),
237 target_pointer_width: get_req_field("target-pointer-width"),
238 arch: get_req_field("arch"),
239 target_os: get_req_field("os"),
240 target_env: obj.find("env").and_then(|s| s.as_string())
241 .map(|s| s.to_string()).unwrap_or(String::new()),
242 options: Default::default(),
243 };
244
245 macro_rules! key {
246 ($key_name:ident) => ( {
247 let name = (stringify!($key_name)).replace("_", "-");
248 obj.find(&name[..]).map(|o| o.as_string()
249 .map(|s| base.options.$key_name = s.to_string()));
250 } );
251 ($key_name:ident, bool) => ( {
252 let name = (stringify!($key_name)).replace("_", "-");
253 obj.find(&name[..])
254 .map(|o| o.as_boolean()
255 .map(|s| base.options.$key_name = s));
256 } );
257 ($key_name:ident, list) => ( {
258 let name = (stringify!($key_name)).replace("_", "-");
259 obj.find(&name[..]).map(|o| o.as_array()
260 .map(|v| base.options.$key_name = v.iter()
261 .map(|a| a.as_string().unwrap().to_string()).collect()
262 )
263 );
264 } );
265 }
266
267 key!(cpu);
268 key!(linker);
269 key!(relocation_model);
270 key!(code_model);
271 key!(dll_prefix);
272 key!(dll_suffix);
273 key!(exe_suffix);
274 key!(staticlib_prefix);
275 key!(staticlib_suffix);
276 key!(features);
277 key!(dynamic_linking, bool);
278 key!(executables, bool);
279 key!(morestack, bool);
280 key!(disable_redzone, bool);
281 key!(eliminate_frame_pointer, bool);
282 key!(function_sections, bool);
283 key!(is_like_osx, bool);
284 key!(is_like_windows, bool);
285 key!(linker_is_gnu, bool);
286 key!(has_rpath, bool);
287 key!(no_compiler_rt, bool);
288 key!(pre_link_args, list);
289 key!(post_link_args, list);
290
291 base
292 }
293
294 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
295 /// triple. Note that it could also just be a bare filename already, so also
296 /// check for that. If one of the hardcoded targets we know about, just
297 /// return it directly.
298 ///
299 /// The error string could come from any of the APIs called, including
300 /// filesystem access and JSON decoding.
301 pub fn search(target: &str) -> Result<Target, String> {
302 use std::env;
303 use std::ffi::OsString;
304 use std::fs::File;
305 use std::path::{Path, PathBuf};
306 use serialize::json;
307
308 fn load_file(path: &Path) -> Result<Target, String> {
309 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
310 let mut contents = Vec::new();
311 try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
312 let obj = try!(json::from_reader(&mut &contents[..])
313 .map_err(|e| e.to_string()));
314 Ok(Target::from_json(obj))
315 }
316
317 // this would use a match if stringify! were allowed in pattern position
318 macro_rules! load_specific {
319 ( $($name:ident),+ ) => (
320 {
321 $(mod $name;)*
322 let target = target.replace("-", "_");
323 if false { }
324 $(
325 else if target == stringify!($name) {
326 let t = $name::target();
327 debug!("Got builtin target: {:?}", t);
328 return Ok(t);
329 }
330 )*
331 else if target == "x86_64-w64-mingw32" {
332 let t = x86_64_pc_windows_gnu::target();
333 return Ok(t);
334 } else if target == "i686-w64-mingw32" {
335 let t = i686_pc_windows_gnu::target();
336 return Ok(t);
337 }
338 }
339 )
340 }
341
342 load_specific!(
343 x86_64_unknown_linux_gnu,
344 i686_unknown_linux_gnu,
345 mips_unknown_linux_gnu,
346 mipsel_unknown_linux_gnu,
347 powerpc_unknown_linux_gnu,
348 arm_unknown_linux_gnueabi,
349 arm_unknown_linux_gnueabihf,
350 aarch64_unknown_linux_gnu,
351 x86_64_unknown_linux_musl,
352
353 arm_linux_androideabi,
354 aarch64_linux_android,
355
356 x86_64_unknown_freebsd,
357
358 i686_unknown_dragonfly,
359 x86_64_unknown_dragonfly,
360
361 x86_64_unknown_bitrig,
362 x86_64_unknown_openbsd,
363
364 x86_64_apple_darwin,
365 i686_apple_darwin,
366
367 i386_apple_ios,
368 x86_64_apple_ios,
369 aarch64_apple_ios,
370 armv7_apple_ios,
371 armv7s_apple_ios,
372
373 x86_64_pc_windows_gnu,
374 i686_pc_windows_gnu
375 );
376
377
378 let path = Path::new(target);
379
380 if path.is_file() {
381 return load_file(&path);
382 }
383
384 let path = {
385 let mut target = target.to_string();
386 target.push_str(".json");
387 PathBuf::from(target)
388 };
389
390 let target_path = env::var_os("RUST_TARGET_PATH")
391 .unwrap_or(OsString::new());
392
393 // FIXME 16351: add a sane default search path?
394
395 for dir in env::split_paths(&target_path) {
396 let p = dir.join(&path);
397 if p.is_file() {
398 return load_file(&p);
399 }
400 }
401
402 Err(format!("Could not find specification for target {:?}", target))
403 }
404 }