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