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