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