]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
Auto merge of #31465 - nagisa:mir-free-fix, r=nikomatsakis
[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     // This is mainly for easy compatibility with emscripten.
208     // If we give emcc .o files that are actually .bc files it
209     // will 'just work'.
210     pub obj_is_bitcode: bool,
211 }
212
213 impl Default for TargetOptions {
214     /// Create a set of "sane defaults" for any target. This is still
215     /// incomplete, and if used for compilation, will certainly not work.
216     fn default() -> TargetOptions {
217         TargetOptions {
218             data_layout: None,
219             linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
220             ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
221             pre_link_args: Vec::new(),
222             post_link_args: Vec::new(),
223             cpu: "generic".to_string(),
224             features: "".to_string(),
225             dynamic_linking: false,
226             executables: false,
227             relocation_model: "pic".to_string(),
228             code_model: "default".to_string(),
229             disable_redzone: false,
230             eliminate_frame_pointer: true,
231             function_sections: true,
232             dll_prefix: "lib".to_string(),
233             dll_suffix: ".so".to_string(),
234             exe_suffix: "".to_string(),
235             staticlib_prefix: "lib".to_string(),
236             staticlib_suffix: ".a".to_string(),
237             target_family: None,
238             is_like_osx: false,
239             is_like_solaris: false,
240             is_like_windows: false,
241             is_like_android: false,
242             is_like_msvc: false,
243             linker_is_gnu: false,
244             has_rpath: false,
245             no_compiler_rt: false,
246             no_default_libraries: true,
247             position_independent_executables: false,
248             pre_link_objects_exe: Vec::new(),
249             pre_link_objects_dll: Vec::new(),
250             post_link_objects: Vec::new(),
251             late_link_args: Vec::new(),
252             archive_format: String::new(),
253             custom_unwind_resume: false,
254             lib_allocation_crate: "alloc_system".to_string(),
255             exe_allocation_crate: "alloc_system".to_string(),
256             allow_asm: true,
257             has_elf_tls: false,
258             obj_is_bitcode: false,
259         }
260     }
261 }
262
263 impl Target {
264     /// Given a function ABI, turn "System" into the correct ABI for this target.
265     pub fn adjust_abi(&self, abi: abi::Abi) -> abi::Abi {
266         match abi {
267             abi::System => {
268                 if self.options.is_like_windows && self.arch == "x86" {
269                     abi::Stdcall
270                 } else {
271                     abi::C
272                 }
273             },
274             abi => abi
275         }
276     }
277
278     /// Load a target descriptor from a JSON object.
279     pub fn from_json(obj: Json) -> Target {
280         // this is 1. ugly, 2. error prone.
281
282         let get_req_field = |name: &str| {
283             match obj.find(name)
284                      .map(|s| s.as_string())
285                      .and_then(|os| os.map(|s| s.to_string())) {
286                 Some(val) => val,
287                 None => {
288                     panic!("Field {} in target specification is required", name)
289                 }
290             }
291         };
292
293         let get_opt_field = |name: &str, default: &str| {
294             obj.find(name).and_then(|s| s.as_string())
295                .map(|s| s.to_string())
296                .unwrap_or(default.to_string())
297         };
298
299         let mut base = Target {
300             llvm_target: get_req_field("llvm-target"),
301             target_endian: get_req_field("target-endian"),
302             target_pointer_width: get_req_field("target-pointer-width"),
303             arch: get_req_field("arch"),
304             target_os: get_req_field("os"),
305             target_env: get_opt_field("env", ""),
306             target_vendor: get_opt_field("vendor", "unknown"),
307             options: Default::default(),
308         };
309
310         macro_rules! key {
311             ($key_name:ident) => ( {
312                 let name = (stringify!($key_name)).replace("_", "-");
313                 obj.find(&name[..]).map(|o| o.as_string()
314                                     .map(|s| base.options.$key_name = s.to_string()));
315             } );
316             ($key_name:ident, bool) => ( {
317                 let name = (stringify!($key_name)).replace("_", "-");
318                 obj.find(&name[..])
319                     .map(|o| o.as_boolean()
320                          .map(|s| base.options.$key_name = s));
321             } );
322             ($key_name:ident, list) => ( {
323                 let name = (stringify!($key_name)).replace("_", "-");
324                 obj.find(&name[..]).map(|o| o.as_array()
325                     .map(|v| base.options.$key_name = v.iter()
326                         .map(|a| a.as_string().unwrap().to_string()).collect()
327                         )
328                     );
329             } );
330             ($key_name:ident, optional) => ( {
331                 let name = (stringify!($key_name)).replace("_", "-");
332                 if let Some(o) = obj.find(&name[..]) {
333                     base.options.$key_name = o
334                         .as_string()
335                         .map(|s| s.to_string() );
336                 }
337             } );
338         }
339
340         key!(cpu);
341         key!(ar);
342         key!(linker);
343         key!(relocation_model);
344         key!(code_model);
345         key!(dll_prefix);
346         key!(dll_suffix);
347         key!(exe_suffix);
348         key!(staticlib_prefix);
349         key!(staticlib_suffix);
350         key!(features);
351         key!(data_layout, optional);
352         key!(dynamic_linking, bool);
353         key!(executables, bool);
354         key!(disable_redzone, bool);
355         key!(eliminate_frame_pointer, bool);
356         key!(function_sections, bool);
357         key!(target_family, optional);
358         key!(is_like_osx, bool);
359         key!(is_like_windows, bool);
360         key!(linker_is_gnu, bool);
361         key!(has_rpath, bool);
362         key!(no_compiler_rt, bool);
363         key!(no_default_libraries, bool);
364         key!(pre_link_args, list);
365         key!(post_link_args, list);
366         key!(archive_format);
367         key!(allow_asm, bool);
368         key!(custom_unwind_resume, bool);
369
370         base
371     }
372
373     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
374     /// triple. Note that it could also just be a bare filename already, so also
375     /// check for that. If one of the hardcoded targets we know about, just
376     /// return it directly.
377     ///
378     /// The error string could come from any of the APIs called, including
379     /// filesystem access and JSON decoding.
380     pub fn search(target: &str) -> Result<Target, String> {
381         use std::env;
382         use std::ffi::OsString;
383         use std::fs::File;
384         use std::path::{Path, PathBuf};
385         use serialize::json;
386
387         fn load_file(path: &Path) -> Result<Target, String> {
388             let mut f = try!(File::open(path).map_err(|e| e.to_string()));
389             let mut contents = Vec::new();
390             try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
391             let obj = try!(json::from_reader(&mut &contents[..])
392                                 .map_err(|e| e.to_string()));
393             Ok(Target::from_json(obj))
394         }
395
396         // this would use a match if stringify! were allowed in pattern position
397         macro_rules! load_specific {
398             ( $($name:ident),+ ) => (
399                 {
400                     $(mod $name;)*
401                     let target = target.replace("-", "_");
402                     if false { }
403                     $(
404                         else if target == stringify!($name) {
405                             let t = $name::target();
406                             debug!("Got builtin target: {:?}", t);
407                             return Ok(t);
408                         }
409                     )*
410                     else if target == "x86_64-w64-mingw32" {
411                         let t = x86_64_pc_windows_gnu::target();
412                         return Ok(t);
413                     } else if target == "i686-w64-mingw32" {
414                         let t = i686_pc_windows_gnu::target();
415                         return Ok(t);
416                     }
417                 }
418             )
419         }
420
421         load_specific!(
422             x86_64_unknown_linux_gnu,
423             i686_unknown_linux_gnu,
424             mips_unknown_linux_gnu,
425             mipsel_unknown_linux_gnu,
426             powerpc_unknown_linux_gnu,
427             powerpc64_unknown_linux_gnu,
428             powerpc64le_unknown_linux_gnu,
429             arm_unknown_linux_gnueabi,
430             arm_unknown_linux_gnueabihf,
431             armv7_unknown_linux_gnueabihf,
432             aarch64_unknown_linux_gnu,
433             x86_64_unknown_linux_musl,
434             i686_unknown_linux_musl,
435             mips_unknown_linux_musl,
436             mipsel_unknown_linux_musl,
437
438             i686_linux_android,
439             arm_linux_androideabi,
440             aarch64_linux_android,
441
442             i686_unknown_freebsd,
443             x86_64_unknown_freebsd,
444
445             i686_unknown_dragonfly,
446             x86_64_unknown_dragonfly,
447
448             x86_64_unknown_bitrig,
449             x86_64_unknown_openbsd,
450             x86_64_unknown_netbsd,
451             x86_64_rumprun_netbsd,
452
453             x86_64_apple_darwin,
454             i686_apple_darwin,
455
456             i386_apple_ios,
457             x86_64_apple_ios,
458             aarch64_apple_ios,
459             armv7_apple_ios,
460             armv7s_apple_ios,
461
462             x86_64_sun_solaris,
463
464             x86_64_pc_windows_gnu,
465             i686_pc_windows_gnu,
466
467             x86_64_pc_windows_msvc,
468             i686_pc_windows_msvc,
469
470             le32_unknown_nacl,
471             asmjs_unknown_emscripten
472         );
473
474
475         let path = Path::new(target);
476
477         if path.is_file() {
478             return load_file(&path);
479         }
480
481         let path = {
482             let mut target = target.to_string();
483             target.push_str(".json");
484             PathBuf::from(target)
485         };
486
487         let target_path = env::var_os("RUST_TARGET_PATH")
488                               .unwrap_or(OsString::new());
489
490         // FIXME 16351: add a sane default search path?
491
492         for dir in env::split_paths(&target_path) {
493             let p =  dir.join(&path);
494             if p.is_file() {
495                 return load_file(&p);
496             }
497         }
498
499         Err(format!("Could not find specification for target {:?}", target))
500     }
501 }
502
503 fn maybe_jemalloc() -> String {
504     if cfg!(disable_jemalloc) {
505         "alloc_system".to_string()
506     } else {
507         "alloc_jemalloc".to_string()
508     }
509 }