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.
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.
11 //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
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:
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.
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.
30 extern crate bootstrap;
33 use std::ffi::OsString;
35 use std::path::PathBuf;
36 use std::process::Command;
37 use std::str::FromStr;
38 use std::time::Instant;
41 let mut args = env::args_os().skip(1).collect::<Vec<_>>();
43 // Append metadata suffix for internal crates. See the corresponding entry
44 // in bootstrap/lib.rs for details.
45 if let Ok(s) = env::var("RUSTC_METADATA_SUFFIX") {
46 for i in 1..args.len() {
47 // Dirty code for borrowing issues
49 if let Some(current_as_str) = args[i].to_str() {
50 if (&*args[i - 1] == "-C" && current_as_str.starts_with("metadata")) ||
51 current_as_str.starts_with("-Cmetadata") {
52 new = Some(format!("{}-{}", current_as_str, s));
55 if let Some(new) = new { args[i] = new.into(); }
59 // Drop `--error-format json` because despite our desire for json messages
60 // from Cargo we don't want any from rustc itself.
61 if let Some(n) = args.iter().position(|n| n == "--error-format") {
66 if let Some(s) = env::var_os("RUSTC_ERROR_FORMAT") {
67 args.push("--error-format".into());
71 // Detect whether or not we're a build script depending on whether --target
72 // is passed (a bit janky...)
73 let target = args.windows(2)
74 .find(|w| &*w[0] == "--target")
75 .and_then(|w| w[1].to_str());
76 let version = args.iter().find(|w| &**w == "-vV");
78 let verbose = match env::var("RUSTC_VERBOSE") {
79 Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
83 // Use a different compiler for build scripts, since there may not yet be a
84 // libstd for the real compiler to use. However, if Cargo is attempting to
85 // determine the version of the compiler, the real compiler needs to be
86 // used. Currently, these two states are differentiated based on whether
87 // --target and -vV is/isn't passed.
88 let (rustc, libdir) = if target.is_none() && version.is_none() {
89 ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
91 ("RUSTC_REAL", "RUSTC_LIBDIR")
93 let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
94 let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
95 let on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of));
97 let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
98 let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
99 let mut dylib_path = bootstrap::util::dylib_path();
100 dylib_path.insert(0, PathBuf::from(&libdir));
102 let mut cmd = Command::new(rustc);
105 .arg(format!("stage{}", stage))
106 .env(bootstrap::util::dylib_path_var(),
107 env::join_paths(&dylib_path).unwrap());
108 let mut maybe_crate = None;
110 // Print backtrace in case of ICE
111 if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() {
112 cmd.env("RUST_BACKTRACE", "1");
115 cmd.env("RUSTC_BREAK_ON_ICE", "1");
117 if let Some(target) = target {
118 // The stage0 compiler has a special sysroot distinct from what we
119 // actually downloaded, so we just always pass the `--sysroot` option.
120 cmd.arg("--sysroot").arg(&sysroot);
122 // When we build Rust dylibs they're all intended for intermediate
123 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
124 // linking all deps statically into the dylib.
125 if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
126 cmd.arg("-Cprefer-dynamic");
129 // Help the libc crate compile by assisting it in finding the MUSL
131 if let Some(s) = env::var_os("MUSL_ROOT") {
132 let mut root = OsString::from("native=");
135 cmd.arg("-L").arg(&root);
138 // Override linker if necessary.
139 if let Ok(target_linker) = env::var("RUSTC_TARGET_LINKER") {
140 cmd.arg(format!("-Clinker={}", target_linker));
143 let crate_name = args.windows(2)
144 .find(|a| &*a[0] == "--crate-name")
146 let crate_name = &*crate_name[1];
147 maybe_crate = Some(crate_name);
149 // If we're compiling specifically the `panic_abort` crate then we pass
150 // the `-C panic=abort` option. Note that we do not do this for any
151 // other crate intentionally as this is the only crate for now that we
152 // ship with panic=abort.
154 // This... is a bit of a hack how we detect this. Ideally this
155 // information should be encoded in the crate I guess? Would likely
156 // require an RFC amendment to RFC 1513, however.
158 // `compiler_builtins` are unconditionally compiled with panic=abort to
159 // workaround undefined references to `rust_eh_unwind_resume` generated
160 // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
161 if crate_name == "panic_abort" ||
162 crate_name == "compiler_builtins" && stage != "0" {
163 cmd.arg("-C").arg("panic=abort");
166 // Set various options from config.toml to configure how we're building
168 if env::var("RUSTC_DEBUGINFO") == Ok("true".to_string()) {
170 } else if env::var("RUSTC_DEBUGINFO_LINES") == Ok("true".to_string()) {
171 cmd.arg("-Cdebuginfo=1");
173 let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
174 Ok(s) => if s == "true" { "y" } else { "n" },
178 // The compiler builtins are pretty sensitive to symbols referenced in
179 // libcore and such, so we never compile them with debug assertions.
180 if crate_name == "compiler_builtins" {
181 cmd.arg("-C").arg("debug-assertions=no");
183 cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
186 if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
187 cmd.arg("-C").arg(format!("codegen-units={}", s));
190 // Emit save-analysis info.
191 if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
192 cmd.arg("-Zsave-analysis");
193 cmd.env("RUST_SAVE_ANALYSIS_CONFIG",
194 "{\"output_file\": null,\"full_docs\": false,\
195 \"pub_only\": true,\"reachable_only\": false,\
196 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
199 // Dealing with rpath here is a little special, so let's go into some
200 // detail. First off, `-rpath` is a linker option on Unix platforms
201 // which adds to the runtime dynamic loader path when looking for
202 // dynamic libraries. We use this by default on Unix platforms to ensure
203 // that our nightlies behave the same on Windows, that is they work out
204 // of the box. This can be disabled, of course, but basically that's why
205 // we're gated on RUSTC_RPATH here.
207 // Ok, so the astute might be wondering "why isn't `-C rpath` used
208 // here?" and that is indeed a good question to task. This codegen
209 // option is the compiler's current interface to generating an rpath.
210 // Unfortunately it doesn't quite suffice for us. The flag currently
211 // takes no value as an argument, so the compiler calculates what it
212 // should pass to the linker as `-rpath`. This unfortunately is based on
213 // the **compile time** directory structure which when building with
214 // Cargo will be very different than the runtime directory structure.
216 // All that's a really long winded way of saying that if we use
217 // `-Crpath` then the executables generated have the wrong rpath of
218 // something like `$ORIGIN/deps` when in fact the way we distribute
219 // rustc requires the rpath to be `$ORIGIN/../lib`.
221 // So, all in all, to set up the correct rpath we pass the linker
222 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
223 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
224 // to change a flag in a binary?
225 if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
226 let rpath = if target.contains("apple") {
228 // Note that we need to take one extra step on macOS to also pass
229 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
230 // do that we pass a weird flag to the compiler to get it to do
231 // so. Note that this is definitely a hack, and we should likely
232 // flesh out rpath support more fully in the future.
233 cmd.arg("-Z").arg("osx-rpath-install-name");
234 Some("-Wl,-rpath,@loader_path/../lib")
235 } else if !target.contains("windows") && !target.contains("wasm32") {
236 Some("-Wl,-rpath,$ORIGIN/../lib")
240 if let Some(rpath) = rpath {
241 cmd.arg("-C").arg(format!("link-args={}", rpath));
245 if let Ok(s) = env::var("RUSTC_CRT_STATIC") {
247 cmd.arg("-C").arg("target-feature=+crt-static");
250 cmd.arg("-C").arg("target-feature=-crt-static");
254 // When running miri tests, we need to generate MIR for all libraries
255 if env::var("TEST_MIRI").ok().map_or(false, |val| val == "true") {
256 cmd.arg("-Zalways-encode-mir");
257 cmd.arg("-Zmir-emit-validate=1");
260 // Force all crates compiled by this compiler to (a) be unstable and (b)
261 // allow the `rustc_private` feature to link to other unstable crates
262 // also in the sysroot.
263 if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() {
264 cmd.arg("-Z").arg("force-unstable-if-unmarked");
267 // Override linker if necessary.
268 if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
269 cmd.arg(format!("-Clinker={}", host_linker));
273 if env::var_os("RUSTC_PARALLEL_QUERIES").is_some() {
274 cmd.arg("--cfg").arg("parallel_queries");
277 let color = match env::var("RUSTC_COLOR") {
278 Ok(s) => usize::from_str(&s).expect("RUSTC_COLOR should be an integer"),
283 cmd.arg("--color=always");
286 if env::var_os("RUSTC_DENY_WARNINGS").is_some() {
287 cmd.arg("-Dwarnings");
292 "rustc command: {:?}={:?} {:?}",
293 bootstrap::util::dylib_path_var(),
294 env::join_paths(&dylib_path).unwrap(),
297 eprintln!("sysroot: {:?}", sysroot);
298 eprintln!("libdir: {:?}", libdir);
301 if let Some(mut on_fail) = on_fail {
302 let e = match cmd.status() {
303 Ok(s) if s.success() => std::process::exit(0),
306 println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
307 exec_cmd(&mut on_fail).expect("could not run the backup command");
308 std::process::exit(1);
311 if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
312 if let Some(krate) = maybe_crate {
313 let start = Instant::now();
316 .expect(&format!("\n\n failed to run {:?}", cmd));
317 let dur = start.elapsed();
319 let is_test = args.iter().any(|a| a == "--test");
320 eprintln!("[RUSTC-TIMING] {} test:{} {}.{:03}",
321 krate.to_string_lossy(),
324 dur.subsec_nanos() / 1_000_000);
326 match status.code() {
327 Some(i) => std::process::exit(i),
329 eprintln!("rustc exited with {}", status);
330 std::process::exit(0xfe);
336 let code = exec_cmd(&mut cmd).expect(&format!("\n\n failed to run {:?}", cmd));
337 std::process::exit(code);
341 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
342 use std::os::unix::process::CommandExt;
347 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
348 cmd.status().map(|status| status.code().unwrap())