]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/bin/rustc.rs
add inline attributes to stage 0 methods
[rust.git] / src / bootstrap / bin / rustc.rs
1 // Copyright 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 //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
12 //!
13 //! This shim will take care of some various tasks that our build process
14 //! requires that Cargo can't quite do through normal configuration:
15 //!
16 //! 1. When compiling build scripts and build dependencies, we need a guaranteed
17 //!    full standard library available. The only compiler which actually has
18 //!    this is the snapshot, so we detect this situation and always compile with
19 //!    the snapshot compiler.
20 //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling
21 //!    (and this slightly differs based on a whether we're using a snapshot or
22 //!    not), so we do that all here.
23 //!
24 //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of
25 //! switching compilers for the bootstrap and for build scripts will probably
26 //! never get replaced.
27
28 #![deny(warnings)]
29
30 extern crate bootstrap;
31
32 use std::env;
33 use std::ffi::OsString;
34 use std::io;
35 use std::io::prelude::*;
36 use std::str::FromStr;
37 use std::path::PathBuf;
38 use std::process::{Command, ExitStatus};
39
40 fn main() {
41     let args = env::args_os().skip(1).collect::<Vec<_>>();
42     // Detect whether or not we're a build script depending on whether --target
43     // is passed (a bit janky...)
44     let target = args.windows(2)
45         .find(|w| &*w[0] == "--target")
46         .and_then(|w| w[1].to_str());
47     let version = args.iter().find(|w| &**w == "-vV");
48
49     let verbose = match env::var("RUSTC_VERBOSE") {
50         Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
51         Err(_) => 0,
52     };
53
54     // Build scripts always use the snapshot compiler which is guaranteed to be
55     // able to produce an executable, whereas intermediate compilers may not
56     // have the standard library built yet and may not be able to produce an
57     // executable. Otherwise we just use the standard compiler we're
58     // bootstrapping with.
59     //
60     // Also note that cargo will detect the version of the compiler to trigger
61     // a rebuild when the compiler changes. If this happens, we want to make
62     // sure to use the actual compiler instead of the snapshot compiler becase
63     // that's the one that's actually changing.
64     let (rustc, libdir) = if target.is_none() && version.is_none() {
65         ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
66     } else {
67         ("RUSTC_REAL", "RUSTC_LIBDIR")
68     };
69     let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
70     let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
71     let mut on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of));
72
73     let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
74     let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
75     let mut dylib_path = bootstrap::util::dylib_path();
76     dylib_path.insert(0, PathBuf::from(libdir));
77
78     let mut cmd = Command::new(rustc);
79     cmd.args(&args)
80         .arg("--cfg")
81         .arg(format!("stage{}", stage))
82         .env(bootstrap::util::dylib_path_var(),
83              env::join_paths(&dylib_path).unwrap());
84
85     if let Some(target) = target {
86         // The stage0 compiler has a special sysroot distinct from what we
87         // actually downloaded, so we just always pass the `--sysroot` option.
88         cmd.arg("--sysroot").arg(sysroot);
89
90         // When we build Rust dylibs they're all intended for intermediate
91         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
92         // linking all deps statically into the dylib.
93         if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
94             cmd.arg("-Cprefer-dynamic");
95         }
96
97         // Help the libc crate compile by assisting it in finding the MUSL
98         // native libraries.
99         if let Some(s) = env::var_os("MUSL_ROOT") {
100             let mut root = OsString::from("native=");
101             root.push(&s);
102             root.push("/lib");
103             cmd.arg("-L").arg(&root);
104         }
105
106         // Pass down extra flags, commonly used to configure `-Clinker` when
107         // cross compiling.
108         if let Ok(s) = env::var("RUSTC_FLAGS") {
109             cmd.args(&s.split(" ").filter(|s| !s.is_empty()).collect::<Vec<_>>());
110         }
111
112         // Pass down incremental directory, if any.
113         if let Ok(dir) = env::var("RUSTC_INCREMENTAL") {
114             cmd.arg(format!("-Zincremental={}", dir));
115
116             if verbose > 0 {
117                 cmd.arg("-Zincremental-info");
118             }
119         }
120
121         // If we're compiling specifically the `panic_abort` crate then we pass
122         // the `-C panic=abort` option. Note that we do not do this for any
123         // other crate intentionally as this is the only crate for now that we
124         // ship with panic=abort.
125         //
126         // This... is a bit of a hack how we detect this. Ideally this
127         // information should be encoded in the crate I guess? Would likely
128         // require an RFC amendment to RFC 1513, however.
129         let is_panic_abort = args.windows(2)
130             .any(|a| &*a[0] == "--crate-name" && &*a[1] == "panic_abort");
131         if is_panic_abort {
132             cmd.arg("-C").arg("panic=abort");
133         }
134
135         // Set various options from config.toml to configure how we're building
136         // code.
137         if env::var("RUSTC_DEBUGINFO") == Ok("true".to_string()) {
138             cmd.arg("-g");
139         } else if env::var("RUSTC_DEBUGINFO_LINES") == Ok("true".to_string()) {
140             cmd.arg("-Cdebuginfo=1");
141         }
142         let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
143             Ok(s) => if s == "true" { "y" } else { "n" },
144             Err(..) => "n",
145         };
146         cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
147         if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
148             cmd.arg("-C").arg(format!("codegen-units={}", s));
149         }
150
151         // Emit save-analysis info.
152         if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
153             cmd.arg("-Zsave-analysis-api");
154         }
155
156         // Dealing with rpath here is a little special, so let's go into some
157         // detail. First off, `-rpath` is a linker option on Unix platforms
158         // which adds to the runtime dynamic loader path when looking for
159         // dynamic libraries. We use this by default on Unix platforms to ensure
160         // that our nightlies behave the same on Windows, that is they work out
161         // of the box. This can be disabled, of course, but basically that's why
162         // we're gated on RUSTC_RPATH here.
163         //
164         // Ok, so the astute might be wondering "why isn't `-C rpath` used
165         // here?" and that is indeed a good question to task. This codegen
166         // option is the compiler's current interface to generating an rpath.
167         // Unfortunately it doesn't quite suffice for us. The flag currently
168         // takes no value as an argument, so the compiler calculates what it
169         // should pass to the linker as `-rpath`. This unfortunately is based on
170         // the **compile time** directory structure which when building with
171         // Cargo will be very different than the runtime directory structure.
172         //
173         // All that's a really long winded way of saying that if we use
174         // `-Crpath` then the executables generated have the wrong rpath of
175         // something like `$ORIGIN/deps` when in fact the way we distribute
176         // rustc requires the rpath to be `$ORIGIN/../lib`.
177         //
178         // So, all in all, to set up the correct rpath we pass the linker
179         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
180         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
181         // to change a flag in a binary?
182         if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
183             let rpath = if target.contains("apple") {
184
185                 // Note that we need to take one extra step on OSX to also pass
186                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
187                 // do that we pass a weird flag to the compiler to get it to do
188                 // so. Note that this is definitely a hack, and we should likely
189                 // flesh out rpath support more fully in the future.
190                 if stage != "0" {
191                     cmd.arg("-Z").arg("osx-rpath-install-name");
192                 }
193                 Some("-Wl,-rpath,@loader_path/../lib")
194             } else if !target.contains("windows") {
195                 Some("-Wl,-rpath,$ORIGIN/../lib")
196             } else {
197                 None
198             };
199             if let Some(rpath) = rpath {
200                 cmd.arg("-C").arg(format!("link-args={}", rpath));
201             }
202
203             if let Ok(s) = env::var("RUSTFLAGS") {
204                 for flag in s.split_whitespace() {
205                     cmd.arg(flag);
206                 }
207             }
208         }
209
210         if target.contains("pc-windows-msvc") {
211             cmd.arg("-Z").arg("unstable-options");
212             cmd.arg("-C").arg("target-feature=+crt-static");
213         }
214     }
215
216     if verbose > 1 {
217         writeln!(&mut io::stderr(), "rustc command: {:?}", cmd).unwrap();
218     }
219
220     // Actually run the compiler!
221     std::process::exit(if let Some(ref mut on_fail) = on_fail {
222         match cmd.status() {
223             Ok(s) if s.success() => 0,
224             _ => {
225                 println!("\nDid not run successfully:\n{:?}\n-------------", cmd);
226                 exec_cmd(on_fail).expect("could not run the backup command");
227                 1
228             }
229         }
230     } else {
231         std::process::exit(match exec_cmd(&mut cmd) {
232             Ok(s) => s.code().unwrap_or(0xfe),
233             Err(e) => panic!("\n\nfailed to run {:?}: {}\n\n", cmd, e),
234         })
235     })
236 }
237
238 #[cfg(unix)]
239 fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> {
240     use std::os::unix::process::CommandExt;
241     Err(cmd.exec())
242 }
243
244 #[cfg(not(unix))]
245 fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> {
246     cmd.status()
247 }