]> git.proxmox.com Git - rustc.git/blame - src/librustc_back/target/mod.rs
Imported Upstream version 1.6.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,
b039eaaf
SL
80 /// Vendor name to use for conditional compilation.
81 pub target_vendor: String,
1a4d82fc 82 /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm",
85aaf69f 83 /// "aarch64", "mips", and "powerpc". "mips" includes "mipsel".
1a4d82fc
JJ
84 pub arch: String,
85 /// Optional settings with defaults.
86 pub options: TargetOptions,
87}
88
89/// Optional aspects of a target specification.
90///
91/// This has an implementation of `Default`, see each field for what the default is. In general,
92/// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
85aaf69f 93#[derive(Clone, Debug)]
1a4d82fc 94pub struct TargetOptions {
c1a9b12d 95 /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
e9174d1e 96 pub data_layout: Option<String>,
1a4d82fc
JJ
97 /// Linker to invoke. Defaults to "cc".
98 pub linker: String,
62682a34
SL
99 /// Archive utility to use when managing archives. Defaults to "ar".
100 pub ar: String,
92a42be0 101
d9579d0f
AL
102 /// Linker arguments that are unconditionally passed *before* any
103 /// user-defined libraries.
1a4d82fc 104 pub pre_link_args: Vec<String>,
92a42be0
SL
105 /// Objects to link before all others, always found within the
106 /// sysroot folder.
107 pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
108 pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
109 /// Linker arguments that are unconditionally passed after any
110 /// user-defined but before post_link_objects. Standard platform
111 /// libraries that should be always be linked to, usually go here.
112 pub late_link_args: Vec<String>,
113 /// Objects to link after all others, always found within the
114 /// sysroot folder.
115 pub post_link_objects: Vec<String>,
d9579d0f
AL
116 /// Linker arguments that are unconditionally passed *after* any
117 /// user-defined libraries.
1a4d82fc 118 pub post_link_args: Vec<String>,
92a42be0 119
d9579d0f
AL
120 /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
121 /// to "default".
1a4d82fc 122 pub cpu: String,
d9579d0f
AL
123 /// Default target features to pass to LLVM. These features will *always* be
124 /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
125 /// -mattr=$features`.
1a4d82fc
JJ
126 pub features: String,
127 /// Whether dynamic linking is available on this target. Defaults to false.
128 pub dynamic_linking: bool,
129 /// Whether executables are available on this target. iOS, for example, only allows static
130 /// libraries. Defaults to false.
131 pub executables: bool,
1a4d82fc
JJ
132 /// Relocation model to use in object file. Corresponds to `llc
133 /// -relocation-model=$relocation_model`. Defaults to "pic".
134 pub relocation_model: String,
135 /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
136 pub code_model: String,
137 /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
138 pub disable_redzone: bool,
139 /// Eliminate frame pointers from stack frames if possible. Defaults to true.
140 pub eliminate_frame_pointer: bool,
141 /// Emit each function in its own section. Defaults to true.
142 pub function_sections: bool,
143 /// String to prepend to the name of every dynamic library. Defaults to "lib".
144 pub dll_prefix: String,
145 /// String to append to the name of every dynamic library. Defaults to ".so".
146 pub dll_suffix: String,
147 /// String to append to the name of every executable.
148 pub exe_suffix: String,
149 /// String to prepend to the name of every static library. Defaults to "lib".
150 pub staticlib_prefix: String,
151 /// String to append to the name of every static library. Defaults to ".a".
152 pub staticlib_suffix: String,
92a42be0
SL
153 /// OS family to use for conditional compilation. Valid options: "unix", "windows".
154 pub target_family: Option<String>,
1a4d82fc
JJ
155 /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
156 /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
157 pub is_like_osx: bool,
158 /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
c34b1796 159 /// only really used for figuring out how to find libraries, since Windows uses its own
1a4d82fc
JJ
160 /// library naming convention. Defaults to false.
161 pub is_like_windows: bool,
62682a34 162 pub is_like_msvc: bool,
85aaf69f
SL
163 /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
164 /// Defaults to false.
165 pub is_like_android: bool,
1a4d82fc
JJ
166 /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
167 pub linker_is_gnu: bool,
168 /// Whether the linker support rpaths or not. Defaults to false.
169 pub has_rpath: bool,
62682a34
SL
170 /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
171 /// will emit references to the functions that compiler-rt provides.
1a4d82fc 172 pub no_compiler_rt: bool,
b039eaaf
SL
173 /// Whether to disable linking to the default libraries, typically corresponds
174 /// to `-nodefaultlibs`. Defaults to true.
175 pub no_default_libraries: bool,
62682a34
SL
176 /// Dynamically linked executables can be compiled as position independent
177 /// if the default relocation model of position independent code is not
178 /// changed. This is a requirement to take advantage of ASLR, as otherwise
179 /// the functions in the executable are not randomized and can be used
180 /// during an exploit of a vulnerability in any code.
1a4d82fc 181 pub position_independent_executables: bool,
c1a9b12d
SL
182 /// Format that archives should be emitted in. This affects whether we use
183 /// LLVM to assemble an archive or fall back to the system linker, and
184 /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
185 /// the system linker to be used.
186 pub archive_format: String,
e9174d1e
SL
187 /// Is asm!() allowed? Defaults to true.
188 pub allow_asm: bool,
c1a9b12d
SL
189 /// Whether the target uses a custom unwind resumption routine.
190 /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
191 /// defined in libgcc. If this option is enabled, the target must provide
192 /// `eh_unwind_resume` lang item.
193 pub custom_unwind_resume: bool,
e9174d1e
SL
194
195 /// Default crate for allocation symbols to link against
196 pub lib_allocation_crate: String,
197 pub exe_allocation_crate: String,
1a4d82fc
JJ
198}
199
200impl Default for TargetOptions {
62682a34
SL
201 /// Create a set of "sane defaults" for any target. This is still
202 /// incomplete, and if used for compilation, will certainly not work.
1a4d82fc
JJ
203 fn default() -> TargetOptions {
204 TargetOptions {
e9174d1e
SL
205 data_layout: None,
206 linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
207 ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
1a4d82fc
JJ
208 pre_link_args: Vec::new(),
209 post_link_args: Vec::new(),
210 cpu: "generic".to_string(),
211 features: "".to_string(),
212 dynamic_linking: false,
213 executables: false,
1a4d82fc
JJ
214 relocation_model: "pic".to_string(),
215 code_model: "default".to_string(),
216 disable_redzone: false,
217 eliminate_frame_pointer: true,
218 function_sections: true,
219 dll_prefix: "lib".to_string(),
220 dll_suffix: ".so".to_string(),
221 exe_suffix: "".to_string(),
222 staticlib_prefix: "lib".to_string(),
223 staticlib_suffix: ".a".to_string(),
92a42be0 224 target_family: None,
1a4d82fc
JJ
225 is_like_osx: false,
226 is_like_windows: false,
85aaf69f 227 is_like_android: false,
62682a34 228 is_like_msvc: false,
1a4d82fc
JJ
229 linker_is_gnu: false,
230 has_rpath: false,
231 no_compiler_rt: false,
b039eaaf 232 no_default_libraries: true,
1a4d82fc 233 position_independent_executables: false,
92a42be0
SL
234 pre_link_objects_exe: Vec::new(),
235 pre_link_objects_dll: Vec::new(),
d9579d0f 236 post_link_objects: Vec::new(),
92a42be0 237 late_link_args: Vec::new(),
c1a9b12d
SL
238 archive_format: String::new(),
239 custom_unwind_resume: false,
e9174d1e
SL
240 lib_allocation_crate: "alloc_system".to_string(),
241 exe_allocation_crate: "alloc_system".to_string(),
242 allow_asm: true,
1a4d82fc
JJ
243 }
244 }
245}
246
247impl Target {
248 /// Given a function ABI, turn "System" into the correct ABI for this target.
249 pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
250 match abi {
251 abi::System => {
252 if self.options.is_like_windows && self.arch == "x86" {
253 abi::Stdcall
254 } else {
255 abi::C
256 }
257 },
258 abi => abi
259 }
260 }
261
262 /// Load a target descriptor from a JSON object.
263 pub fn from_json(obj: Json) -> Target {
264 // this is 1. ugly, 2. error prone.
265
266
62682a34 267 let handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
1a4d82fc 268
85aaf69f 269 let get_req_field = |name: &str| {
1a4d82fc
JJ
270 match obj.find(name)
271 .map(|s| s.as_string())
272 .and_then(|os| os.map(|s| s.to_string())) {
273 Some(val) => val,
92a42be0
SL
274 None => {
275 panic!(handler.fatal(&format!("Field {} in target specification is required",
276 name)))
277 }
1a4d82fc
JJ
278 }
279 };
280
b039eaaf
SL
281 let get_opt_field = |name: &str, default: &str| {
282 obj.find(name).and_then(|s| s.as_string())
283 .map(|s| s.to_string())
284 .unwrap_or(default.to_string())
285 };
286
1a4d82fc 287 let mut base = Target {
1a4d82fc
JJ
288 llvm_target: get_req_field("llvm-target"),
289 target_endian: get_req_field("target-endian"),
85aaf69f 290 target_pointer_width: get_req_field("target-pointer-width"),
1a4d82fc
JJ
291 arch: get_req_field("arch"),
292 target_os: get_req_field("os"),
b039eaaf
SL
293 target_env: get_opt_field("env", ""),
294 target_vendor: get_opt_field("vendor", "unknown"),
1a4d82fc
JJ
295 options: Default::default(),
296 };
297
298 macro_rules! key {
299 ($key_name:ident) => ( {
300 let name = (stringify!($key_name)).replace("_", "-");
85aaf69f 301 obj.find(&name[..]).map(|o| o.as_string()
1a4d82fc
JJ
302 .map(|s| base.options.$key_name = s.to_string()));
303 } );
304 ($key_name:ident, bool) => ( {
305 let name = (stringify!($key_name)).replace("_", "-");
85aaf69f 306 obj.find(&name[..])
1a4d82fc
JJ
307 .map(|o| o.as_boolean()
308 .map(|s| base.options.$key_name = s));
309 } );
310 ($key_name:ident, list) => ( {
311 let name = (stringify!($key_name)).replace("_", "-");
85aaf69f 312 obj.find(&name[..]).map(|o| o.as_array()
1a4d82fc
JJ
313 .map(|v| base.options.$key_name = v.iter()
314 .map(|a| a.as_string().unwrap().to_string()).collect()
315 )
316 );
317 } );
e9174d1e
SL
318 ($key_name:ident, optional) => ( {
319 let name = (stringify!($key_name)).replace("_", "-");
320 if let Some(o) = obj.find(&name[..]) {
321 base.options.$key_name = o
322 .as_string()
323 .map(|s| s.to_string() );
324 }
325 } );
1a4d82fc
JJ
326 }
327
328 key!(cpu);
62682a34 329 key!(ar);
1a4d82fc
JJ
330 key!(linker);
331 key!(relocation_model);
332 key!(code_model);
333 key!(dll_prefix);
334 key!(dll_suffix);
335 key!(exe_suffix);
336 key!(staticlib_prefix);
337 key!(staticlib_suffix);
338 key!(features);
e9174d1e 339 key!(data_layout, optional);
1a4d82fc
JJ
340 key!(dynamic_linking, bool);
341 key!(executables, bool);
1a4d82fc
JJ
342 key!(disable_redzone, bool);
343 key!(eliminate_frame_pointer, bool);
344 key!(function_sections, bool);
92a42be0 345 key!(target_family, optional);
1a4d82fc
JJ
346 key!(is_like_osx, bool);
347 key!(is_like_windows, bool);
348 key!(linker_is_gnu, bool);
349 key!(has_rpath, bool);
350 key!(no_compiler_rt, bool);
b039eaaf 351 key!(no_default_libraries, bool);
1a4d82fc
JJ
352 key!(pre_link_args, list);
353 key!(post_link_args, list);
92a42be0 354 key!(archive_format);
e9174d1e 355 key!(allow_asm, bool);
92a42be0 356 key!(custom_unwind_resume, bool);
1a4d82fc
JJ
357
358 base
359 }
360
c34b1796
AL
361 /// Search RUST_TARGET_PATH for a JSON file specifying the given target
362 /// triple. Note that it could also just be a bare filename already, so also
363 /// check for that. If one of the hardcoded targets we know about, just
364 /// return it directly.
1a4d82fc 365 ///
c34b1796
AL
366 /// The error string could come from any of the APIs called, including
367 /// filesystem access and JSON decoding.
1a4d82fc 368 pub fn search(target: &str) -> Result<Target, String> {
85aaf69f
SL
369 use std::env;
370 use std::ffi::OsString;
c34b1796
AL
371 use std::fs::File;
372 use std::path::{Path, PathBuf};
1a4d82fc
JJ
373 use serialize::json;
374
375 fn load_file(path: &Path) -> Result<Target, String> {
c34b1796
AL
376 let mut f = try!(File::open(path).map_err(|e| e.to_string()));
377 let mut contents = Vec::new();
378 try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
379 let obj = try!(json::from_reader(&mut &contents[..])
380 .map_err(|e| e.to_string()));
1a4d82fc
JJ
381 Ok(Target::from_json(obj))
382 }
383
384 // this would use a match if stringify! were allowed in pattern position
385 macro_rules! load_specific {
386 ( $($name:ident),+ ) => (
387 {
d9579d0f 388 $(mod $name;)*
1a4d82fc
JJ
389 let target = target.replace("-", "_");
390 if false { }
391 $(
392 else if target == stringify!($name) {
393 let t = $name::target();
394 debug!("Got builtin target: {:?}", t);
395 return Ok(t);
396 }
397 )*
398 else if target == "x86_64-w64-mingw32" {
399 let t = x86_64_pc_windows_gnu::target();
400 return Ok(t);
401 } else if target == "i686-w64-mingw32" {
402 let t = i686_pc_windows_gnu::target();
403 return Ok(t);
404 }
405 }
406 )
407 }
408
409 load_specific!(
410 x86_64_unknown_linux_gnu,
411 i686_unknown_linux_gnu,
412 mips_unknown_linux_gnu,
413 mipsel_unknown_linux_gnu,
85aaf69f 414 powerpc_unknown_linux_gnu,
1a4d82fc
JJ
415 arm_unknown_linux_gnueabi,
416 arm_unknown_linux_gnueabihf,
417 aarch64_unknown_linux_gnu,
d9579d0f 418 x86_64_unknown_linux_musl,
1a4d82fc 419
e9174d1e 420 i686_linux_android,
85aaf69f
SL
421 arm_linux_androideabi,
422 aarch64_linux_android,
423
c1a9b12d 424 i686_unknown_freebsd,
1a4d82fc
JJ
425 x86_64_unknown_freebsd,
426
427 i686_unknown_dragonfly,
428 x86_64_unknown_dragonfly,
429
c34b1796 430 x86_64_unknown_bitrig,
85aaf69f 431 x86_64_unknown_openbsd,
c1a9b12d 432 x86_64_unknown_netbsd,
b039eaaf 433 x86_64_rumprun_netbsd,
85aaf69f 434
1a4d82fc
JJ
435 x86_64_apple_darwin,
436 i686_apple_darwin,
85aaf69f 437
1a4d82fc 438 i386_apple_ios,
85aaf69f
SL
439 x86_64_apple_ios,
440 aarch64_apple_ios,
441 armv7_apple_ios,
442 armv7s_apple_ios,
1a4d82fc
JJ
443
444 x86_64_pc_windows_gnu,
62682a34
SL
445 i686_pc_windows_gnu,
446
c1a9b12d 447 x86_64_pc_windows_msvc,
b039eaaf
SL
448 i686_pc_windows_msvc,
449
450 le32_unknown_nacl
1a4d82fc
JJ
451 );
452
453
454 let path = Path::new(target);
455
456 if path.is_file() {
457 return load_file(&path);
458 }
459
460 let path = {
461 let mut target = target.to_string();
462 target.push_str(".json");
c34b1796 463 PathBuf::from(target)
1a4d82fc
JJ
464 };
465
c34b1796
AL
466 let target_path = env::var_os("RUST_TARGET_PATH")
467 .unwrap_or(OsString::new());
1a4d82fc 468
1a4d82fc
JJ
469 // FIXME 16351: add a sane default search path?
470
85aaf69f 471 for dir in env::split_paths(&target_path) {
c34b1796 472 let p = dir.join(&path);
1a4d82fc
JJ
473 if p.is_file() {
474 return load_file(&p);
475 }
476 }
477
478 Err(format!("Could not find specification for target {:?}", target))
479 }
480}
e9174d1e 481
b039eaaf 482fn maybe_jemalloc() -> String {
e9174d1e
SL
483 if cfg!(disable_jemalloc) {
484 "alloc_system".to_string()
485 } else {
486 "alloc_jemalloc".to_string()
487 }
488}