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