]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
bc5f306cd3568b8ad8a5521a5172eac59f9997fa
[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 std::default::Default;
50 use std::io::prelude::*;
51 use syntax::{diagnostic, abi};
52
53 mod android_base;
54 mod apple_base;
55 mod apple_ios_base;
56 mod bitrig_base;
57 mod dragonfly_base;
58 mod freebsd_base;
59 mod linux_base;
60 mod openbsd_base;
61 mod netbsd_base;
62 mod windows_base;
63 mod windows_msvc_base;
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.
68 #[derive(Clone, Debug)]
69 pub struct Target {
70     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
71     pub data_layout: String,
72     /// Target triple to pass to LLVM.
73     pub llvm_target: String,
74     /// String to use as the `target_endian` `cfg` variable.
75     pub target_endian: String,
76     /// String to use as the `target_pointer_width` `cfg` variable.
77     pub target_pointer_width: String,
78     /// OS name to use for conditional compilation.
79     pub target_os: String,
80     /// Environment name to use for conditional compilation.
81     pub target_env: String,
82     /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm",
83     /// "aarch64", "mips", and "powerpc". "mips" includes "mipsel".
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.
93 #[derive(Clone, Debug)]
94 pub struct TargetOptions {
95     /// Linker to invoke. Defaults to "cc".
96     pub linker: String,
97     /// Archive utility to use when managing archives. Defaults to "ar".
98     pub ar: String,
99     /// Linker arguments that are unconditionally passed *before* any
100     /// user-defined libraries.
101     pub pre_link_args: Vec<String>,
102     /// Linker arguments that are unconditionally passed *after* any
103     /// user-defined libraries.
104     pub post_link_args: Vec<String>,
105     /// Objects to link before and after all others, always found within the
106     /// sysroot folder.
107     pub pre_link_objects: Vec<String>,
108     pub post_link_objects: Vec<String>,
109     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
110     /// to "default".
111     pub cpu: String,
112     /// Default target features to pass to LLVM. These features will *always* be
113     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
114     /// -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 really 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     pub is_like_msvc: bool,
153     /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
154     /// Defaults to false.
155     pub is_like_android: bool,
156     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
157     pub linker_is_gnu: bool,
158     /// Whether the linker support rpaths or not. Defaults to false.
159     pub has_rpath: bool,
160     /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
161     /// will emit references to the functions that compiler-rt provides.
162     pub no_compiler_rt: bool,
163     /// Dynamically linked executables can be compiled as position independent
164     /// if the default relocation model of position independent code is not
165     /// changed. This is a requirement to take advantage of ASLR, as otherwise
166     /// the functions in the executable are not randomized and can be used
167     /// 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
173     /// incomplete, and if used for compilation, will certainly not work.
174     fn default() -> TargetOptions {
175         TargetOptions {
176             linker: "cc".to_string(),
177             ar: "ar".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             is_like_android: false,
198             is_like_msvc: false,
199             linker_is_gnu: false,
200             has_rpath: false,
201             no_compiler_rt: false,
202             position_independent_executables: false,
203             pre_link_objects: Vec::new(),
204             post_link_objects: Vec::new(),
205         }
206     }
207 }
208
209 impl Target {
210     /// Given a function ABI, turn "System" into the correct ABI for this target.
211     pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
212         match abi {
213             abi::System => {
214                 if self.options.is_like_windows && self.arch == "x86" {
215                     abi::Stdcall
216                 } else {
217                     abi::C
218                 }
219             },
220             abi => abi
221         }
222     }
223
224     /// Load a target descriptor from a JSON object.
225     pub fn from_json(obj: Json) -> Target {
226         // this is 1. ugly, 2. error prone.
227
228
229         let handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
230
231         let get_req_field = |name: &str| {
232             match obj.find(name)
233                      .map(|s| s.as_string())
234                      .and_then(|os| os.map(|s| s.to_string())) {
235                 Some(val) => val,
236                 None =>
237                     handler.fatal(&format!("Field {} in target specification is required", name))
238             }
239         };
240
241         let mut base = Target {
242             data_layout: get_req_field("data-layout"),
243             llvm_target: get_req_field("llvm-target"),
244             target_endian: get_req_field("target-endian"),
245             target_pointer_width: get_req_field("target-pointer-width"),
246             arch: get_req_field("arch"),
247             target_os: get_req_field("os"),
248             target_env: obj.find("env").and_then(|s| s.as_string())
249                            .map(|s| s.to_string()).unwrap_or(String::new()),
250             options: Default::default(),
251         };
252
253         macro_rules! key {
254             ($key_name:ident) => ( {
255                 let name = (stringify!($key_name)).replace("_", "-");
256                 obj.find(&name[..]).map(|o| o.as_string()
257                                     .map(|s| base.options.$key_name = s.to_string()));
258             } );
259             ($key_name:ident, bool) => ( {
260                 let name = (stringify!($key_name)).replace("_", "-");
261                 obj.find(&name[..])
262                     .map(|o| o.as_boolean()
263                          .map(|s| base.options.$key_name = s));
264             } );
265             ($key_name:ident, list) => ( {
266                 let name = (stringify!($key_name)).replace("_", "-");
267                 obj.find(&name[..]).map(|o| o.as_array()
268                     .map(|v| base.options.$key_name = v.iter()
269                         .map(|a| a.as_string().unwrap().to_string()).collect()
270                         )
271                     );
272             } );
273         }
274
275         key!(cpu);
276         key!(ar);
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
304     /// triple. Note that it could also just be a bare filename already, so also
305     /// check for that. If one of the hardcoded targets we know about, just
306     /// return it directly.
307     ///
308     /// The error string could come from any of the APIs called, including
309     /// filesystem access and JSON decoding.
310     pub fn search(target: &str) -> Result<Target, String> {
311         use std::env;
312         use std::ffi::OsString;
313         use std::fs::File;
314         use std::path::{Path, PathBuf};
315         use serialize::json;
316
317         fn load_file(path: &Path) -> Result<Target, String> {
318             let mut f = try!(File::open(path).map_err(|e| e.to_string()));
319             let mut contents = Vec::new();
320             try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
321             let obj = try!(json::from_reader(&mut &contents[..])
322                                 .map_err(|e| e.to_string()));
323             Ok(Target::from_json(obj))
324         }
325
326         // this would use a match if stringify! were allowed in pattern position
327         macro_rules! load_specific {
328             ( $($name:ident),+ ) => (
329                 {
330                     $(mod $name;)*
331                     let target = target.replace("-", "_");
332                     if false { }
333                     $(
334                         else if target == stringify!($name) {
335                             let t = $name::target();
336                             debug!("Got builtin target: {:?}", t);
337                             return Ok(t);
338                         }
339                     )*
340                     else if target == "x86_64-w64-mingw32" {
341                         let t = x86_64_pc_windows_gnu::target();
342                         return Ok(t);
343                     } else if target == "i686-w64-mingw32" {
344                         let t = i686_pc_windows_gnu::target();
345                         return Ok(t);
346                     }
347                 }
348             )
349         }
350
351         load_specific!(
352             x86_64_unknown_linux_gnu,
353             i686_unknown_linux_gnu,
354             mips_unknown_linux_gnu,
355             mipsel_unknown_linux_gnu,
356             powerpc_unknown_linux_gnu,
357             arm_unknown_linux_gnueabi,
358             arm_unknown_linux_gnueabihf,
359             aarch64_unknown_linux_gnu,
360             x86_64_unknown_linux_musl,
361
362             arm_linux_androideabi,
363             aarch64_linux_android,
364
365             x86_64_unknown_freebsd,
366
367             i686_unknown_dragonfly,
368             x86_64_unknown_dragonfly,
369
370             x86_64_unknown_bitrig,
371             x86_64_unknown_openbsd,
372             x86_64_unknown_netbsd,
373
374             x86_64_apple_darwin,
375             i686_apple_darwin,
376
377             i386_apple_ios,
378             x86_64_apple_ios,
379             aarch64_apple_ios,
380             armv7_apple_ios,
381             armv7s_apple_ios,
382
383             x86_64_pc_windows_gnu,
384             i686_pc_windows_gnu,
385
386             x86_64_pc_windows_msvc,
387             i686_pc_windows_msvc
388         );
389
390
391         let path = Path::new(target);
392
393         if path.is_file() {
394             return load_file(&path);
395         }
396
397         let path = {
398             let mut target = target.to_string();
399             target.push_str(".json");
400             PathBuf::from(target)
401         };
402
403         let target_path = env::var_os("RUST_TARGET_PATH")
404                               .unwrap_or(OsString::new());
405
406         // FIXME 16351: add a sane default search path?
407
408         for dir in env::split_paths(&target_path) {
409             let p =  dir.join(&path);
410             if p.is_file() {
411                 return load_file(&p);
412             }
413         }
414
415         Err(format!("Could not find specification for target {:?}", target))
416     }
417 }