]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.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 syntax::{diagnostic, abi};
50 use std::default::Default;
51 use std::old_io::fs::PathExtensions;
52
53 mod windows_base;
54 mod linux_base;
55 mod apple_base;
56 mod apple_ios_base;
57 mod freebsd_base;
58 mod dragonfly_base;
59 mod openbsd_base;
60
61 mod armv7_apple_ios;
62 mod armv7s_apple_ios;
63 mod i386_apple_ios;
64
65 mod arm_linux_androideabi;
66 mod arm_unknown_linux_gnueabi;
67 mod arm_unknown_linux_gnueabihf;
68 mod aarch64_apple_ios;
69 mod aarch64_linux_android;
70 mod aarch64_unknown_linux_gnu;
71 mod i686_apple_darwin;
72 mod i686_pc_windows_gnu;
73 mod i686_unknown_dragonfly;
74 mod i686_unknown_linux_gnu;
75 mod mips_unknown_linux_gnu;
76 mod mipsel_unknown_linux_gnu;
77 mod powerpc_unknown_linux_gnu;
78 mod x86_64_apple_darwin;
79 mod x86_64_apple_ios;
80 mod x86_64_pc_windows_gnu;
81 mod x86_64_unknown_freebsd;
82 mod x86_64_unknown_dragonfly;
83 mod x86_64_unknown_linux_gnu;
84 mod x86_64_unknown_openbsd;
85
86 /// Everything `rustc` knows about how to compile for a specific target.
87 ///
88 /// Every field here must be specified, and has no default value.
89 #[derive(Clone, Debug)]
90 pub struct Target {
91     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
92     pub data_layout: String,
93     /// Target triple to pass to LLVM.
94     pub llvm_target: String,
95     /// String to use as the `target_endian` `cfg` variable.
96     pub target_endian: String,
97     /// String to use as the `target_pointer_width` `cfg` variable.
98     pub target_pointer_width: String,
99     /// OS name to use for conditional compilation.
100     pub target_os: String,
101     /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm",
102     /// "aarch64", "mips", and "powerpc". "mips" includes "mipsel".
103     pub arch: String,
104     /// Optional settings with defaults.
105     pub options: TargetOptions,
106 }
107
108 /// Optional aspects of a target specification.
109 ///
110 /// This has an implementation of `Default`, see each field for what the default is. In general,
111 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
112 #[derive(Clone, Debug)]
113 pub struct TargetOptions {
114     /// Linker to invoke. Defaults to "cc".
115     pub linker: String,
116     /// Linker arguments that are unconditionally passed *before* any user-defined libraries.
117     pub pre_link_args: Vec<String>,
118     /// Linker arguments that are unconditionally passed *after* any user-defined libraries.
119     pub post_link_args: Vec<String>,
120     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults to "default".
121     pub cpu: String,
122     /// Default target features to pass to LLVM. These features will *always* be passed, and cannot
123     /// be disabled even via `-C`. Corresponds to `llc -mattr=$features`.
124     pub features: String,
125     /// Whether dynamic linking is available on this target. Defaults to false.
126     pub dynamic_linking: bool,
127     /// Whether executables are available on this target. iOS, for example, only allows static
128     /// libraries. Defaults to false.
129     pub executables: bool,
130     /// Whether LLVM's segmented stack prelude is supported by whatever runtime is available.
131     /// Will emit stack checks and calls to __morestack. Defaults to false.
132     pub morestack: bool,
133     /// Relocation model to use in object file. Corresponds to `llc
134     /// -relocation-model=$relocation_model`. Defaults to "pic".
135     pub relocation_model: String,
136     /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
137     pub code_model: String,
138     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
139     pub disable_redzone: bool,
140     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
141     pub eliminate_frame_pointer: bool,
142     /// Emit each function in its own section. Defaults to true.
143     pub function_sections: bool,
144     /// String to prepend to the name of every dynamic library. Defaults to "lib".
145     pub dll_prefix: String,
146     /// String to append to the name of every dynamic library. Defaults to ".so".
147     pub dll_suffix: String,
148     /// String to append to the name of every executable.
149     pub exe_suffix: String,
150     /// String to prepend to the name of every static library. Defaults to "lib".
151     pub staticlib_prefix: String,
152     /// String to append to the name of every static library. Defaults to ".a".
153     pub staticlib_suffix: String,
154     /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
155     /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
156     pub is_like_osx: bool,
157     /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
158     /// only realy used for figuring out how to find libraries, since Windows uses its own
159     /// library naming convention. Defaults to false.
160     pub is_like_windows: bool,
161     /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
162     /// Defaults to false.
163     pub is_like_android: bool,
164     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
165     pub linker_is_gnu: bool,
166     /// Whether the linker support rpaths or not. Defaults to false.
167     pub has_rpath: bool,
168     /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM will emit references
169     /// to the functions that compiler-rt provides.
170     pub no_compiler_rt: bool,
171     /// Dynamically linked executables can be compiled as position independent if the default
172     /// relocation model of position independent code is not changed. This is a requirement to take
173     /// advantage of ASLR, as otherwise the functions in the executable are not randomized and can
174     /// be used during an exploit of a vulnerability in any code.
175     pub position_independent_executables: bool,
176 }
177
178 impl Default for TargetOptions {
179     /// Create a set of "sane defaults" for any target. This is still incomplete, and if used for
180     /// compilation, will certainly not work.
181     fn default() -> TargetOptions {
182         TargetOptions {
183             linker: "cc".to_string(),
184             pre_link_args: Vec::new(),
185             post_link_args: Vec::new(),
186             cpu: "generic".to_string(),
187             features: "".to_string(),
188             dynamic_linking: false,
189             executables: false,
190             morestack: false,
191             relocation_model: "pic".to_string(),
192             code_model: "default".to_string(),
193             disable_redzone: false,
194             eliminate_frame_pointer: true,
195             function_sections: true,
196             dll_prefix: "lib".to_string(),
197             dll_suffix: ".so".to_string(),
198             exe_suffix: "".to_string(),
199             staticlib_prefix: "lib".to_string(),
200             staticlib_suffix: ".a".to_string(),
201             is_like_osx: false,
202             is_like_windows: false,
203             is_like_android: false,
204             linker_is_gnu: false,
205             has_rpath: false,
206             no_compiler_rt: false,
207             position_independent_executables: false,
208         }
209     }
210 }
211
212 impl Target {
213     /// Given a function ABI, turn "System" into the correct ABI for this target.
214     pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
215         match abi {
216             abi::System => {
217                 if self.options.is_like_windows && self.arch == "x86" {
218                     abi::Stdcall
219                 } else {
220                     abi::C
221                 }
222             },
223             abi => abi
224         }
225     }
226
227     /// Load a target descriptor from a JSON object.
228     pub fn from_json(obj: Json) -> Target {
229         // this is 1. ugly, 2. error prone.
230
231
232         let handler = diagnostic::default_handler(diagnostic::Auto, None, true);
233
234         let get_req_field = |name: &str| {
235             match obj.find(name)
236                      .map(|s| s.as_string())
237                      .and_then(|os| os.map(|s| s.to_string())) {
238                 Some(val) => val,
239                 None =>
240                     handler.fatal(&format!("Field {} in target specification is required", name)[])
241             }
242         };
243
244         let mut base = Target {
245             data_layout: get_req_field("data-layout"),
246             llvm_target: get_req_field("llvm-target"),
247             target_endian: get_req_field("target-endian"),
248             target_pointer_width: get_req_field("target-pointer-width"),
249             arch: get_req_field("arch"),
250             target_os: get_req_field("os"),
251             options: Default::default(),
252         };
253
254         macro_rules! key {
255             ($key_name:ident) => ( {
256                 let name = (stringify!($key_name)).replace("_", "-");
257                 obj.find(&name[..]).map(|o| o.as_string()
258                                     .map(|s| base.options.$key_name = s.to_string()));
259             } );
260             ($key_name:ident, bool) => ( {
261                 let name = (stringify!($key_name)).replace("_", "-");
262                 obj.find(&name[..])
263                     .map(|o| o.as_boolean()
264                          .map(|s| base.options.$key_name = s));
265             } );
266             ($key_name:ident, list) => ( {
267                 let name = (stringify!($key_name)).replace("_", "-");
268                 obj.find(&name[..]).map(|o| o.as_array()
269                     .map(|v| base.options.$key_name = v.iter()
270                         .map(|a| a.as_string().unwrap().to_string()).collect()
271                         )
272                     );
273             } );
274         }
275
276         key!(cpu);
277         key!(linker);
278         key!(relocation_model);
279         key!(code_model);
280         key!(dll_prefix);
281         key!(dll_suffix);
282         key!(exe_suffix);
283         key!(staticlib_prefix);
284         key!(staticlib_suffix);
285         key!(features);
286         key!(dynamic_linking, bool);
287         key!(executables, bool);
288         key!(morestack, bool);
289         key!(disable_redzone, bool);
290         key!(eliminate_frame_pointer, bool);
291         key!(function_sections, bool);
292         key!(is_like_osx, bool);
293         key!(is_like_windows, bool);
294         key!(linker_is_gnu, bool);
295         key!(has_rpath, bool);
296         key!(no_compiler_rt, bool);
297         key!(pre_link_args, list);
298         key!(post_link_args, list);
299
300         base
301     }
302
303     /// Search RUST_TARGET_PATH for a JSON file specifying the given target triple. Note that it
304     /// could also just be a bare filename already, so also check for that. If one of the hardcoded
305     /// targets we know about, just return it directly.
306     ///
307     /// The error string could come from any of the APIs called, including filesystem access and
308     /// JSON decoding.
309     pub fn search(target: &str) -> Result<Target, String> {
310         use std::env;
311         use std::ffi::OsString;
312         use std::old_io::File;
313         use std::old_path::Path;
314         use serialize::json;
315
316         fn load_file(path: &Path) -> Result<Target, String> {
317             let mut f = try!(File::open(path).map_err(|e| format!("{:?}", e)));
318             let obj = try!(json::from_reader(&mut f).map_err(|e| format!("{:?}", e)));
319             Ok(Target::from_json(obj))
320         }
321
322         // this would use a match if stringify! were allowed in pattern position
323         macro_rules! load_specific {
324             ( $($name:ident),+ ) => (
325                 {
326                     let target = target.replace("-", "_");
327                     if false { }
328                     $(
329                         else if target == stringify!($name) {
330                             let t = $name::target();
331                             debug!("Got builtin target: {:?}", t);
332                             return Ok(t);
333                         }
334                     )*
335                     else if target == "x86_64-w64-mingw32" {
336                         let t = x86_64_pc_windows_gnu::target();
337                         return Ok(t);
338                     } else if target == "i686-w64-mingw32" {
339                         let t = i686_pc_windows_gnu::target();
340                         return Ok(t);
341                     }
342                 }
343             )
344         }
345
346         load_specific!(
347             x86_64_unknown_linux_gnu,
348             i686_unknown_linux_gnu,
349             mips_unknown_linux_gnu,
350             mipsel_unknown_linux_gnu,
351             powerpc_unknown_linux_gnu,
352             arm_unknown_linux_gnueabi,
353             arm_unknown_linux_gnueabihf,
354             aarch64_unknown_linux_gnu,
355
356             arm_linux_androideabi,
357             aarch64_linux_android,
358
359             x86_64_unknown_freebsd,
360
361             i686_unknown_dragonfly,
362             x86_64_unknown_dragonfly,
363
364             x86_64_unknown_openbsd,
365
366             x86_64_apple_darwin,
367             i686_apple_darwin,
368
369             i386_apple_ios,
370             x86_64_apple_ios,
371             aarch64_apple_ios,
372             armv7_apple_ios,
373             armv7s_apple_ios,
374
375             x86_64_pc_windows_gnu,
376             i686_pc_windows_gnu
377         );
378
379
380         let path = Path::new(target);
381
382         if path.is_file() {
383             return load_file(&path);
384         }
385
386         let path = {
387             let mut target = target.to_string();
388             target.push_str(".json");
389             Path::new(target)
390         };
391
392         let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or(OsString::from_str(""));
393
394         // FIXME 16351: add a sane default search path?
395
396         for dir in env::split_paths(&target_path) {
397             let p =  dir.join(path.clone());
398             if p.is_file() {
399                 return load_file(&p);
400             }
401         }
402
403         Err(format!("Could not find specification for target {:?}", target))
404     }
405 }