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