]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
Add the asmjs-unknown-emscripten triple. Add cfgs to libs.
[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::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 solaris_base;
63 mod windows_base;
64 mod windows_msvc_base;
65
66 /// Everything `rustc` knows about how to compile for a specific target.
67 ///
68 /// Every field here must be specified, and has no default value.
69 #[derive(Clone, Debug)]
70 pub struct Target {
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     /// Vendor name to use for conditional compilation.
82     pub target_vendor: String,
83     /// Architecture to use for ABI considerations. Valid options: "x86",
84     /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
85     pub arch: String,
86     /// Optional settings with defaults.
87     pub options: TargetOptions,
88 }
89
90 /// Optional aspects of a target specification.
91 ///
92 /// This has an implementation of `Default`, see each field for what the default is. In general,
93 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
94 #[derive(Clone, Debug)]
95 pub struct TargetOptions {
96     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
97     pub data_layout: Option<String>,
98     /// Linker to invoke. Defaults to "cc".
99     pub linker: String,
100     /// Archive utility to use when managing archives. Defaults to "ar".
101     pub ar: String,
102
103     /// Linker arguments that are unconditionally passed *before* any
104     /// user-defined libraries.
105     pub pre_link_args: Vec<String>,
106     /// Objects to link before all others, always found within the
107     /// sysroot folder.
108     pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
109     pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
110     /// Linker arguments that are unconditionally passed after any
111     /// user-defined but before post_link_objects.  Standard platform
112     /// libraries that should be always be linked to, usually go here.
113     pub late_link_args: Vec<String>,
114     /// Objects to link after all others, always found within the
115     /// sysroot folder.
116     pub post_link_objects: Vec<String>,
117     /// Linker arguments that are unconditionally passed *after* any
118     /// user-defined libraries.
119     pub post_link_args: Vec<String>,
120
121     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
122     /// to "default".
123     pub cpu: String,
124     /// Default target features to pass to LLVM. These features will *always* be
125     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
126     /// -mattr=$features`.
127     pub features: String,
128     /// Whether dynamic linking is available on this target. Defaults to false.
129     pub dynamic_linking: bool,
130     /// Whether executables are available on this target. iOS, for example, only allows static
131     /// libraries. Defaults to false.
132     pub executables: bool,
133     /// Relocation model to use in object file. Corresponds to `llc
134     /// -relocation-model=$relocation_model`. Defaults to "pic".
135     pub relocation_model: String,
136     /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
137     pub code_model: String,
138     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
139     pub disable_redzone: bool,
140     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
141     pub eliminate_frame_pointer: bool,
142     /// Emit each function in its own section. Defaults to true.
143     pub function_sections: bool,
144     /// String to prepend to the name of every dynamic library. Defaults to "lib".
145     pub dll_prefix: String,
146     /// String to append to the name of every dynamic library. Defaults to ".so".
147     pub dll_suffix: String,
148     /// String to append to the name of every executable.
149     pub exe_suffix: String,
150     /// String to prepend to the name of every static library. Defaults to "lib".
151     pub staticlib_prefix: String,
152     /// String to append to the name of every static library. Defaults to ".a".
153     pub staticlib_suffix: String,
154     /// OS family to use for conditional compilation. Valid options: "unix", "windows".
155     pub target_family: Option<String>,
156     /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
157     /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
158     pub is_like_osx: bool,
159     /// Whether the target toolchain is like Solaris's.
160     /// Only useful for compiling against Illumos/Solaris,
161     /// as they have a different set of linker flags. Defaults to false.
162     pub is_like_solaris: bool,
163     /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
164     /// only really used for figuring out how to find libraries, since Windows uses its own
165     /// library naming convention. Defaults to false.
166     pub is_like_windows: bool,
167     pub is_like_msvc: bool,
168     /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
169     /// Defaults to false.
170     pub is_like_android: bool,
171     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
172     pub linker_is_gnu: bool,
173     /// Whether the linker support rpaths or not. Defaults to false.
174     pub has_rpath: bool,
175     /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
176     /// will emit references to the functions that compiler-rt provides.
177     pub no_compiler_rt: bool,
178     /// Whether to disable linking to the default libraries, typically corresponds
179     /// to `-nodefaultlibs`. Defaults to true.
180     pub no_default_libraries: bool,
181     /// Dynamically linked executables can be compiled as position independent
182     /// if the default relocation model of position independent code is not
183     /// changed. This is a requirement to take advantage of ASLR, as otherwise
184     /// the functions in the executable are not randomized and can be used
185     /// during an exploit of a vulnerability in any code.
186     pub position_independent_executables: bool,
187     /// Format that archives should be emitted in. This affects whether we use
188     /// LLVM to assemble an archive or fall back to the system linker, and
189     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
190     /// the system linker to be used.
191     pub archive_format: String,
192     /// Is asm!() allowed? Defaults to true.
193     pub allow_asm: bool,
194     /// Whether the target uses a custom unwind resumption routine.
195     /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
196     /// defined in libgcc.  If this option is enabled, the target must provide
197     /// `eh_unwind_resume` lang item.
198     pub custom_unwind_resume: bool,
199
200     /// Default crate for allocation symbols to link against
201     pub lib_allocation_crate: String,
202     pub exe_allocation_crate: String,
203
204     /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
205     /// this target.
206     pub has_elf_tls: bool,
207 }
208
209 impl Default for TargetOptions {
210     /// Create a set of "sane defaults" for any target. This is still
211     /// incomplete, and if used for compilation, will certainly not work.
212     fn default() -> TargetOptions {
213         TargetOptions {
214             data_layout: None,
215             linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
216             ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
217             pre_link_args: Vec::new(),
218             post_link_args: Vec::new(),
219             cpu: "generic".to_string(),
220             features: "".to_string(),
221             dynamic_linking: false,
222             executables: false,
223             relocation_model: "pic".to_string(),
224             code_model: "default".to_string(),
225             disable_redzone: false,
226             eliminate_frame_pointer: true,
227             function_sections: true,
228             dll_prefix: "lib".to_string(),
229             dll_suffix: ".so".to_string(),
230             exe_suffix: "".to_string(),
231             staticlib_prefix: "lib".to_string(),
232             staticlib_suffix: ".a".to_string(),
233             target_family: None,
234             is_like_osx: false,
235             is_like_solaris: false,
236             is_like_windows: false,
237             is_like_android: false,
238             is_like_msvc: false,
239             linker_is_gnu: false,
240             has_rpath: false,
241             no_compiler_rt: false,
242             no_default_libraries: true,
243             position_independent_executables: false,
244             pre_link_objects_exe: Vec::new(),
245             pre_link_objects_dll: Vec::new(),
246             post_link_objects: Vec::new(),
247             late_link_args: Vec::new(),
248             archive_format: String::new(),
249             custom_unwind_resume: false,
250             lib_allocation_crate: "alloc_system".to_string(),
251             exe_allocation_crate: "alloc_system".to_string(),
252             allow_asm: true,
253             has_elf_tls: false,
254         }
255     }
256 }
257
258 impl Target {
259     /// Given a function ABI, turn "System" into the correct ABI for this target.
260     pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
261         match abi {
262             abi::System => {
263                 if self.options.is_like_windows && self.arch == "x86" {
264                     abi::Stdcall
265                 } else {
266                     abi::C
267                 }
268             },
269             abi => abi
270         }
271     }
272
273     /// Load a target descriptor from a JSON object.
274     pub fn from_json(obj: Json) -> Target {
275         // this is 1. ugly, 2. error prone.
276
277         let get_req_field = |name: &str| {
278             match obj.find(name)
279                      .map(|s| s.as_string())
280                      .and_then(|os| os.map(|s| s.to_string())) {
281                 Some(val) => val,
282                 None => {
283                     panic!("Field {} in target specification is required", name)
284                 }
285             }
286         };
287
288         let get_opt_field = |name: &str, default: &str| {
289             obj.find(name).and_then(|s| s.as_string())
290                .map(|s| s.to_string())
291                .unwrap_or(default.to_string())
292         };
293
294         let mut base = Target {
295             llvm_target: get_req_field("llvm-target"),
296             target_endian: get_req_field("target-endian"),
297             target_pointer_width: get_req_field("target-pointer-width"),
298             arch: get_req_field("arch"),
299             target_os: get_req_field("os"),
300             target_env: get_opt_field("env", ""),
301             target_vendor: get_opt_field("vendor", "unknown"),
302             options: Default::default(),
303         };
304
305         macro_rules! key {
306             ($key_name:ident) => ( {
307                 let name = (stringify!($key_name)).replace("_", "-");
308                 obj.find(&name[..]).map(|o| o.as_string()
309                                     .map(|s| base.options.$key_name = s.to_string()));
310             } );
311             ($key_name:ident, bool) => ( {
312                 let name = (stringify!($key_name)).replace("_", "-");
313                 obj.find(&name[..])
314                     .map(|o| o.as_boolean()
315                          .map(|s| base.options.$key_name = s));
316             } );
317             ($key_name:ident, list) => ( {
318                 let name = (stringify!($key_name)).replace("_", "-");
319                 obj.find(&name[..]).map(|o| o.as_array()
320                     .map(|v| base.options.$key_name = v.iter()
321                         .map(|a| a.as_string().unwrap().to_string()).collect()
322                         )
323                     );
324             } );
325             ($key_name:ident, optional) => ( {
326                 let name = (stringify!($key_name)).replace("_", "-");
327                 if let Some(o) = obj.find(&name[..]) {
328                     base.options.$key_name = o
329                         .as_string()
330                         .map(|s| s.to_string() );
331                 }
332             } );
333         }
334
335         key!(cpu);
336         key!(ar);
337         key!(linker);
338         key!(relocation_model);
339         key!(code_model);
340         key!(dll_prefix);
341         key!(dll_suffix);
342         key!(exe_suffix);
343         key!(staticlib_prefix);
344         key!(staticlib_suffix);
345         key!(features);
346         key!(data_layout, optional);
347         key!(dynamic_linking, bool);
348         key!(executables, bool);
349         key!(disable_redzone, bool);
350         key!(eliminate_frame_pointer, bool);
351         key!(function_sections, bool);
352         key!(target_family, optional);
353         key!(is_like_osx, bool);
354         key!(is_like_windows, bool);
355         key!(linker_is_gnu, bool);
356         key!(has_rpath, bool);
357         key!(no_compiler_rt, bool);
358         key!(no_default_libraries, bool);
359         key!(pre_link_args, list);
360         key!(post_link_args, list);
361         key!(archive_format);
362         key!(allow_asm, bool);
363         key!(custom_unwind_resume, bool);
364
365         base
366     }
367
368     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
369     /// triple. Note that it could also just be a bare filename already, so also
370     /// check for that. If one of the hardcoded targets we know about, just
371     /// return it directly.
372     ///
373     /// The error string could come from any of the APIs called, including
374     /// filesystem access and JSON decoding.
375     pub fn search(target: &str) -> Result<Target, String> {
376         use std::env;
377         use std::ffi::OsString;
378         use std::fs::File;
379         use std::path::{Path, PathBuf};
380         use serialize::json;
381
382         fn load_file(path: &Path) -> Result<Target, String> {
383             let mut f = try!(File::open(path).map_err(|e| e.to_string()));
384             let mut contents = Vec::new();
385             try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
386             let obj = try!(json::from_reader(&mut &contents[..])
387                                 .map_err(|e| e.to_string()));
388             Ok(Target::from_json(obj))
389         }
390
391         // this would use a match if stringify! were allowed in pattern position
392         macro_rules! load_specific {
393             ( $($name:ident),+ ) => (
394                 {
395                     $(mod $name;)*
396                     let target = target.replace("-", "_");
397                     if false { }
398                     $(
399                         else if target == stringify!($name) {
400                             let t = $name::target();
401                             debug!("Got builtin target: {:?}", t);
402                             return Ok(t);
403                         }
404                     )*
405                     else if target == "x86_64-w64-mingw32" {
406                         let t = x86_64_pc_windows_gnu::target();
407                         return Ok(t);
408                     } else if target == "i686-w64-mingw32" {
409                         let t = i686_pc_windows_gnu::target();
410                         return Ok(t);
411                     }
412                 }
413             )
414         }
415
416         load_specific!(
417             x86_64_unknown_linux_gnu,
418             i686_unknown_linux_gnu,
419             mips_unknown_linux_gnu,
420             mipsel_unknown_linux_gnu,
421             powerpc_unknown_linux_gnu,
422             powerpc64_unknown_linux_gnu,
423             powerpc64le_unknown_linux_gnu,
424             arm_unknown_linux_gnueabi,
425             arm_unknown_linux_gnueabihf,
426             armv7_unknown_linux_gnueabihf,
427             aarch64_unknown_linux_gnu,
428             x86_64_unknown_linux_musl,
429             mips_unknown_linux_musl,
430             mipsel_unknown_linux_musl,
431
432             i686_linux_android,
433             arm_linux_androideabi,
434             aarch64_linux_android,
435
436             i686_unknown_freebsd,
437             x86_64_unknown_freebsd,
438
439             i686_unknown_dragonfly,
440             x86_64_unknown_dragonfly,
441
442             x86_64_unknown_bitrig,
443             x86_64_unknown_openbsd,
444             x86_64_unknown_netbsd,
445             x86_64_rumprun_netbsd,
446
447             x86_64_apple_darwin,
448             i686_apple_darwin,
449
450             i386_apple_ios,
451             x86_64_apple_ios,
452             aarch64_apple_ios,
453             armv7_apple_ios,
454             armv7s_apple_ios,
455
456             x86_64_sun_solaris,
457
458             x86_64_pc_windows_gnu,
459             i686_pc_windows_gnu,
460
461             x86_64_pc_windows_msvc,
462             i686_pc_windows_msvc,
463
464             le32_unknown_nacl,
465             asmjs_unknown_emscripten
466         );
467
468
469         let path = Path::new(target);
470
471         if path.is_file() {
472             return load_file(&path);
473         }
474
475         let path = {
476             let mut target = target.to_string();
477             target.push_str(".json");
478             PathBuf::from(target)
479         };
480
481         let target_path = env::var_os("RUST_TARGET_PATH")
482                               .unwrap_or(OsString::new());
483
484         // FIXME 16351: add a sane default search path?
485
486         for dir in env::split_paths(&target_path) {
487             let p =  dir.join(&path);
488             if p.is_file() {
489                 return load_file(&p);
490             }
491         }
492
493         Err(format!("Could not find specification for target {:?}", target))
494     }
495 }
496
497 fn maybe_jemalloc() -> String {
498     if cfg!(disable_jemalloc) {
499         "alloc_system".to_string()
500     } else {
501         "alloc_jemalloc".to_string()
502     }
503 }