]> git.proxmox.com Git - rustc.git/blame - src/librustc_back/target/mod.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / librustc_back / target / mod.rs
CommitLineData
1a4d82fc
JJ
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
85aaf69f 43//! `data-layout`, `llvm-target`, `target-endian`, `target-pointer-width`, and
1a4d82fc
JJ
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
48use serialize::json::Json;
1a4d82fc 49use std::default::Default;
c34b1796 50use std::io::prelude::*;
d9579d0f 51use syntax::{diagnostic, abi};
1a4d82fc 52
d9579d0f 53mod android_base;
1a4d82fc 54mod apple_base;
85aaf69f 55mod apple_ios_base;
c34b1796 56mod bitrig_base;
d9579d0f
AL
57mod dragonfly_base;
58mod freebsd_base;
59mod linux_base;
85aaf69f 60mod openbsd_base;
c1a9b12d 61mod netbsd_base;
d9579d0f 62mod windows_base;
62682a34 63mod windows_msvc_base;
1a4d82fc
JJ
64
65/// Everything `rustc` knows about how to compile for a specific target.
66///
67/// Every field here must be specified, and has no default value.
85aaf69f 68#[derive(Clone, Debug)]
1a4d82fc 69pub struct Target {
1a4d82fc
JJ
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,
d9579d0f
AL
78 /// Environment name to use for conditional compilation.
79 pub target_env: String,
1a4d82fc 80 /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm",
85aaf69f 81 /// "aarch64", "mips", and "powerpc". "mips" includes "mipsel".
1a4d82fc
JJ
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.
85aaf69f 91#[derive(Clone, Debug)]
1a4d82fc 92pub struct TargetOptions {
c1a9b12d
SL
93 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
94 pub data_layout: String,
1a4d82fc
JJ
95 /// Linker to invoke. Defaults to "cc".
96 pub linker: String,
62682a34
SL
97 /// Archive utility to use when managing archives. Defaults to "ar".
98 pub ar: String,
d9579d0f
AL
99 /// Linker arguments that are unconditionally passed *before* any
100 /// user-defined libraries.
1a4d82fc 101 pub pre_link_args: Vec<String>,
d9579d0f
AL
102 /// Linker arguments that are unconditionally passed *after* any
103 /// user-defined libraries.
1a4d82fc 104 pub post_link_args: Vec<String>,
d9579d0f
AL
105 /// Objects to link before and after all others, always found within the
106 /// sysroot folder.
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
110 /// to "default".
1a4d82fc 111 pub cpu: String,
d9579d0f
AL
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`.
1a4d82fc
JJ
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 /// Whether LLVM's segmented stack prelude is supported by whatever runtime is available.
122 /// Will emit stack checks and calls to __morestack. Defaults to false.
123 pub morestack: bool,
124 /// Relocation model to use in object file. Corresponds to `llc
125 /// -relocation-model=$relocation_model`. Defaults to "pic".
126 pub relocation_model: String,
127 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
128 pub code_model: String,
129 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
130 pub disable_redzone: bool,
131 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
132 pub eliminate_frame_pointer: bool,
133 /// Emit each function in its own section. Defaults to true.
134 pub function_sections: bool,
135 /// String to prepend to the name of every dynamic library. Defaults to "lib".
136 pub dll_prefix: String,
137 /// String to append to the name of every dynamic library. Defaults to ".so".
138 pub dll_suffix: String,
139 /// String to append to the name of every executable.
140 pub exe_suffix: String,
141 /// String to prepend to the name of every static library. Defaults to "lib".
142 pub staticlib_prefix: String,
143 /// String to append to the name of every static library. Defaults to ".a".
144 pub staticlib_suffix: String,
145 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
146 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
147 pub is_like_osx: bool,
148 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
c34b1796 149 /// only really used for figuring out how to find libraries, since Windows uses its own
1a4d82fc
JJ
150 /// library naming convention. Defaults to false.
151 pub is_like_windows: bool,
62682a34 152 pub is_like_msvc: bool,
85aaf69f
SL
153 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
154 /// Defaults to false.
155 pub is_like_android: bool,
1a4d82fc
JJ
156 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
157 pub linker_is_gnu: bool,
158 /// Whether the linker support rpaths or not. Defaults to false.
159 pub has_rpath: bool,
62682a34
SL
160 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
161 /// will emit references to the functions that compiler-rt provides.
1a4d82fc 162 pub no_compiler_rt: bool,
62682a34
SL
163 /// Dynamically linked executables can be compiled as position independent
164 /// if the default relocation model of position independent code is not
165 /// changed. This is a requirement to take advantage of ASLR, as otherwise
166 /// the functions in the executable are not randomized and can be used
167 /// during an exploit of a vulnerability in any code.
1a4d82fc 168 pub position_independent_executables: bool,
c1a9b12d
SL
169 /// Format that archives should be emitted in. This affects whether we use
170 /// LLVM to assemble an archive or fall back to the system linker, and
171 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
172 /// the system linker to be used.
173 pub archive_format: String,
174 /// Whether the target uses a custom unwind resumption routine.
175 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
176 /// defined in libgcc. If this option is enabled, the target must provide
177 /// `eh_unwind_resume` lang item.
178 pub custom_unwind_resume: bool,
1a4d82fc
JJ
179}
180
181impl Default for TargetOptions {
62682a34
SL
182 /// Create a set of "sane defaults" for any target. This is still
183 /// incomplete, and if used for compilation, will certainly not work.
1a4d82fc
JJ
184 fn default() -> TargetOptions {
185 TargetOptions {
c1a9b12d 186 data_layout: String::new(),
1a4d82fc 187 linker: "cc".to_string(),
62682a34 188 ar: "ar".to_string(),
1a4d82fc
JJ
189 pre_link_args: Vec::new(),
190 post_link_args: Vec::new(),
191 cpu: "generic".to_string(),
192 features: "".to_string(),
193 dynamic_linking: false,
194 executables: false,
195 morestack: 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(),
206 is_like_osx: false,
207 is_like_windows: false,
85aaf69f 208 is_like_android: false,
62682a34 209 is_like_msvc: false,
1a4d82fc
JJ
210 linker_is_gnu: false,
211 has_rpath: false,
212 no_compiler_rt: false,
213 position_independent_executables: false,
d9579d0f
AL
214 pre_link_objects: Vec::new(),
215 post_link_objects: Vec::new(),
c1a9b12d
SL
216 archive_format: String::new(),
217 custom_unwind_resume: false,
1a4d82fc
JJ
218 }
219 }
220}
221
222impl Target {
223 /// Given a function ABI, turn "System" into the correct ABI for this target.
224 pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
225 match abi {
226 abi::System => {
227 if self.options.is_like_windows && self.arch == "x86" {
228 abi::Stdcall
229 } else {
230 abi::C
231 }
232 },
233 abi => abi
234 }
235 }
236
237 /// Load a target descriptor from a JSON object.
238 pub fn from_json(obj: Json) -> Target {
239 // this is 1. ugly, 2. error prone.
240
241
62682a34 242 let handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
1a4d82fc 243
85aaf69f 244 let get_req_field = |name: &str| {
1a4d82fc
JJ
245 match obj.find(name)
246 .map(|s| s.as_string())
247 .and_then(|os| os.map(|s| s.to_string())) {
248 Some(val) => val,
249 None =>
c34b1796 250 handler.fatal(&format!("Field {} in target specification is required", name))
1a4d82fc
JJ
251 }
252 };
253
254 let mut base = Target {
1a4d82fc
JJ
255 llvm_target: get_req_field("llvm-target"),
256 target_endian: get_req_field("target-endian"),
85aaf69f 257 target_pointer_width: get_req_field("target-pointer-width"),
1a4d82fc
JJ
258 arch: get_req_field("arch"),
259 target_os: get_req_field("os"),
d9579d0f
AL
260 target_env: obj.find("env").and_then(|s| s.as_string())
261 .map(|s| s.to_string()).unwrap_or(String::new()),
1a4d82fc
JJ
262 options: Default::default(),
263 };
264
265 macro_rules! key {
266 ($key_name:ident) => ( {
267 let name = (stringify!($key_name)).replace("_", "-");
85aaf69f 268 obj.find(&name[..]).map(|o| o.as_string()
1a4d82fc
JJ
269 .map(|s| base.options.$key_name = s.to_string()));
270 } );
271 ($key_name:ident, bool) => ( {
272 let name = (stringify!($key_name)).replace("_", "-");
85aaf69f 273 obj.find(&name[..])
1a4d82fc
JJ
274 .map(|o| o.as_boolean()
275 .map(|s| base.options.$key_name = s));
276 } );
277 ($key_name:ident, list) => ( {
278 let name = (stringify!($key_name)).replace("_", "-");
85aaf69f 279 obj.find(&name[..]).map(|o| o.as_array()
1a4d82fc
JJ
280 .map(|v| base.options.$key_name = v.iter()
281 .map(|a| a.as_string().unwrap().to_string()).collect()
282 )
283 );
284 } );
285 }
286
287 key!(cpu);
62682a34 288 key!(ar);
1a4d82fc
JJ
289 key!(linker);
290 key!(relocation_model);
291 key!(code_model);
292 key!(dll_prefix);
293 key!(dll_suffix);
294 key!(exe_suffix);
295 key!(staticlib_prefix);
296 key!(staticlib_suffix);
297 key!(features);
c1a9b12d 298 key!(data_layout);
1a4d82fc
JJ
299 key!(dynamic_linking, bool);
300 key!(executables, bool);
301 key!(morestack, bool);
302 key!(disable_redzone, bool);
303 key!(eliminate_frame_pointer, bool);
304 key!(function_sections, bool);
305 key!(is_like_osx, bool);
306 key!(is_like_windows, bool);
307 key!(linker_is_gnu, bool);
308 key!(has_rpath, bool);
309 key!(no_compiler_rt, bool);
310 key!(pre_link_args, list);
311 key!(post_link_args, list);
312
313 base
314 }
315
c34b1796
AL
316 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
317 /// triple. Note that it could also just be a bare filename already, so also
318 /// check for that. If one of the hardcoded targets we know about, just
319 /// return it directly.
1a4d82fc 320 ///
c34b1796
AL
321 /// The error string could come from any of the APIs called, including
322 /// filesystem access and JSON decoding.
1a4d82fc 323 pub fn search(target: &str) -> Result<Target, String> {
85aaf69f
SL
324 use std::env;
325 use std::ffi::OsString;
c34b1796
AL
326 use std::fs::File;
327 use std::path::{Path, PathBuf};
1a4d82fc
JJ
328 use serialize::json;
329
330 fn load_file(path: &Path) -> Result<Target, String> {
c34b1796
AL
331 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
332 let mut contents = Vec::new();
333 try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
334 let obj = try!(json::from_reader(&mut &contents[..])
335 .map_err(|e| e.to_string()));
1a4d82fc
JJ
336 Ok(Target::from_json(obj))
337 }
338
339 // this would use a match if stringify! were allowed in pattern position
340 macro_rules! load_specific {
341 ( $($name:ident),+ ) => (
342 {
d9579d0f 343 $(mod $name;)*
1a4d82fc
JJ
344 let target = target.replace("-", "_");
345 if false { }
346 $(
347 else if target == stringify!($name) {
348 let t = $name::target();
349 debug!("Got builtin target: {:?}", t);
350 return Ok(t);
351 }
352 )*
353 else if target == "x86_64-w64-mingw32" {
354 let t = x86_64_pc_windows_gnu::target();
355 return Ok(t);
356 } else if target == "i686-w64-mingw32" {
357 let t = i686_pc_windows_gnu::target();
358 return Ok(t);
359 }
360 }
361 )
362 }
363
364 load_specific!(
365 x86_64_unknown_linux_gnu,
366 i686_unknown_linux_gnu,
367 mips_unknown_linux_gnu,
368 mipsel_unknown_linux_gnu,
85aaf69f 369 powerpc_unknown_linux_gnu,
1a4d82fc
JJ
370 arm_unknown_linux_gnueabi,
371 arm_unknown_linux_gnueabihf,
372 aarch64_unknown_linux_gnu,
d9579d0f 373 x86_64_unknown_linux_musl,
1a4d82fc 374
85aaf69f
SL
375 arm_linux_androideabi,
376 aarch64_linux_android,
377
c1a9b12d 378 i686_unknown_freebsd,
1a4d82fc
JJ
379 x86_64_unknown_freebsd,
380
381 i686_unknown_dragonfly,
382 x86_64_unknown_dragonfly,
383
c34b1796 384 x86_64_unknown_bitrig,
85aaf69f 385 x86_64_unknown_openbsd,
c1a9b12d 386 x86_64_unknown_netbsd,
85aaf69f 387
1a4d82fc
JJ
388 x86_64_apple_darwin,
389 i686_apple_darwin,
85aaf69f 390
1a4d82fc 391 i386_apple_ios,
85aaf69f
SL
392 x86_64_apple_ios,
393 aarch64_apple_ios,
394 armv7_apple_ios,
395 armv7s_apple_ios,
1a4d82fc
JJ
396
397 x86_64_pc_windows_gnu,
62682a34
SL
398 i686_pc_windows_gnu,
399
c1a9b12d
SL
400 x86_64_pc_windows_msvc,
401 i686_pc_windows_msvc
1a4d82fc
JJ
402 );
403
404
405 let path = Path::new(target);
406
407 if path.is_file() {
408 return load_file(&path);
409 }
410
411 let path = {
412 let mut target = target.to_string();
413 target.push_str(".json");
c34b1796 414 PathBuf::from(target)
1a4d82fc
JJ
415 };
416
c34b1796
AL
417 let target_path = env::var_os("RUST_TARGET_PATH")
418 .unwrap_or(OsString::new());
1a4d82fc 419
1a4d82fc
JJ
420 // FIXME 16351: add a sane default search path?
421
85aaf69f 422 for dir in env::split_paths(&target_path) {
c34b1796 423 let p = dir.join(&path);
1a4d82fc
JJ
424 if p.is_file() {
425 return load_file(&p);
426 }
427 }
428
429 Err(format!("Could not find specification for target {:?}", target))
430 }
431}