]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
debuginfo: Make debuginfo source location assignment more stable (Pt. 1)
[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-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.
47
48 use serialize::json::Json;
49 use syntax::{diagnostic, abi};
50 use std::default::Default;
51 use std::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
60 mod armv7_apple_ios;
61 mod armv7s_apple_ios;
62 mod i386_apple_ios;
63
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;
77 mod x86_64_apple_ios;
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;
82
83 /// Everything `rustc` knows about how to compile for a specific target.
84 ///
85 /// Every field here must be specified, and has no default value.
86 #[derive(Clone, Show)]
87 pub struct Target {
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".
100     pub arch: String,
101     /// Optional settings with defaults.
102     pub options: TargetOptions,
103 }
104
105 /// Optional aspects of a target specification.
106 ///
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".
112     pub linker: String,
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".
118     pub cpu: String,
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.
129     pub morestack: bool,
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.
161     pub has_rpath: bool,
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,
170 }
171
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 {
176         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,
183             executables: false,
184             morestack: 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(),
195             is_like_osx: false,
196             is_like_windows: false,
197             linker_is_gnu: false,
198             has_rpath: false,
199             no_compiler_rt: false,
200             position_independent_executables: false,
201         }
202     }
203 }
204
205 impl Target {
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 {
208         match abi {
209             abi::System => {
210                 if self.options.is_like_windows && self.arch == "x86" {
211                     abi::Stdcall
212                 } else {
213                     abi::C
214                 }
215             },
216             abi => abi
217         }
218     }
219
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.
223
224
225         let handler = diagnostic::default_handler(diagnostic::Auto, None);
226
227         let get_req_field = |&: name: &str| {
228             match obj.find(name)
229                      .map(|s| s.as_string())
230                      .and_then(|os| os.map(|s| s.to_string())) {
231                 Some(val) => val,
232                 None =>
233                     handler.fatal(&format!("Field {} in target specification is required", name)[])
234             }
235         };
236
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(),
245         };
246
247         macro_rules! key {
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()));
252             } );
253             ($key_name:ident, bool) => ( {
254                 let name = (stringify!($key_name)).replace("_", "-");
255                 obj.find(&name[])
256                     .map(|o| o.as_boolean()
257                          .map(|s| base.options.$key_name = s));
258             } );
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()
264                         )
265                     );
266             } );
267         }
268
269         key!(cpu);
270         key!(linker);
271         key!(relocation_model);
272         key!(code_model);
273         key!(dll_prefix);
274         key!(dll_suffix);
275         key!(exe_suffix);
276         key!(staticlib_prefix);
277         key!(staticlib_suffix);
278         key!(features);
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);
292
293         base
294     }
295
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.
299     ///
300     /// The error string could come from any of the APIs called, including filesystem access and
301     /// JSON decoding.
302     pub fn search(target: &str) -> Result<Target, String> {
303         use std::os;
304         use std::io::File;
305         use std::path::Path;
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| format!("{:?}", e)));
310             let obj = try!(json::from_reader(&mut f).map_err(|e| format!("{:?}", e)));
311             Ok(Target::from_json(obj))
312         }
313
314         // this would use a match if stringify! were allowed in pattern position
315         macro_rules! load_specific {
316             ( $($name:ident),+ ) => (
317                 {
318                     let target = target.replace("-", "_");
319                     if false { }
320                     $(
321                         else if target == stringify!($name) {
322                             let t = $name::target();
323                             debug!("Got builtin target: {:?}", t);
324                             return Ok(t);
325                         }
326                     )*
327                     else if target == "x86_64-w64-mingw32" {
328                         let t = x86_64_pc_windows_gnu::target();
329                         return Ok(t);
330                     } else if target == "i686-w64-mingw32" {
331                         let t = i686_pc_windows_gnu::target();
332                         return Ok(t);
333                     }
334                 }
335             )
336         }
337
338         load_specific!(
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,
348
349             x86_64_unknown_freebsd,
350
351             i686_unknown_dragonfly,
352             x86_64_unknown_dragonfly,
353
354             x86_64_apple_darwin,
355             i686_apple_darwin,
356
357             i386_apple_ios,
358             x86_64_apple_ios,
359             aarch64_apple_ios,
360             armv7_apple_ios,
361             armv7s_apple_ios,
362
363             x86_64_pc_windows_gnu,
364             i686_pc_windows_gnu
365         );
366
367
368         let path = Path::new(target);
369
370         if path.is_file() {
371             return load_file(&path);
372         }
373
374         let path = {
375             let mut target = target.to_string();
376             target.push_str(".json");
377             Path::new(target)
378         };
379
380         let target_path = os::getenv("RUST_TARGET_PATH").unwrap_or(String::new());
381
382         let paths = os::split_paths(&target_path[]);
383         // FIXME 16351: add a sane default search path?
384
385         for dir in paths.iter() {
386             let p =  dir.join(path.clone());
387             if p.is_file() {
388                 return load_file(&p);
389             }
390         }
391
392         Err(format!("Could not find specification for target {:?}", target))
393     }
394 }