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 if let Some(target) = target {
111 // The stage0 compiler has a special sysroot distinct from what we
112 // actually downloaded, so we just always pass the `--sysroot` option.
113 cmd.arg("--sysroot").arg(&sysroot);
115 // When we build Rust dylibs they're all intended for intermediate
116 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
117 // linking all deps statically into the dylib.
118 if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
119 cmd.arg("-Cprefer-dynamic");
122 // Help the libc crate compile by assisting it in finding the MUSL
124 if let Some(s) = env::var_os("MUSL_ROOT") {
125 let mut root = OsString::from("native=");
128 cmd.arg("-L").arg(&root);
131 // Override linker if necessary.
132 if let Ok(target_linker) = env::var("RUSTC_TARGET_LINKER") {
133 cmd.arg(format!("-Clinker={}", target_linker));
136 let crate_name = args.windows(2)
137 .find(|a| &*a[0] == "--crate-name")
139 let crate_name = &*crate_name[1];
140 maybe_crate = Some(crate_name);
142 // If we're compiling specifically the `panic_abort` crate then we pass
143 // the `-C panic=abort` option. Note that we do not do this for any
144 // other crate intentionally as this is the only crate for now that we
145 // ship with panic=abort.
147 // This... is a bit of a hack how we detect this. Ideally this
148 // information should be encoded in the crate I guess? Would likely
149 // require an RFC amendment to RFC 1513, however.
151 // `compiler_builtins` are unconditionally compiled with panic=abort to
152 // workaround undefined references to `rust_eh_unwind_resume` generated
153 // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
154 if crate_name == "panic_abort" ||
155 crate_name == "compiler_builtins" && stage != "0" {
156 cmd.arg("-C").arg("panic=abort");
159 // Set various options from config.toml to configure how we're building
161 if env::var("RUSTC_DEBUGINFO") == Ok("true".to_string()) {
163 } else if env::var("RUSTC_DEBUGINFO_LINES") == Ok("true".to_string()) {
164 cmd.arg("-Cdebuginfo=1");
166 let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
167 Ok(s) => if s == "true" { "y" } else { "n" },
171 // The compiler builtins are pretty sensitive to symbols referenced in
172 // libcore and such, so we never compile them with debug assertions.
173 if crate_name == "compiler_builtins" {
174 cmd.arg("-C").arg("debug-assertions=no");
176 cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
179 if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
180 cmd.arg("-C").arg(format!("codegen-units={}", s));
183 // Emit save-analysis info.
184 if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
185 cmd.arg("-Zsave-analysis");
186 cmd.env("RUST_SAVE_ANALYSIS_CONFIG",
187 "{\"output_file\": null,\"full_docs\": false,\
188 \"pub_only\": true,\"reachable_only\": false,\
189 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
192 // Dealing with rpath here is a little special, so let's go into some
193 // detail. First off, `-rpath` is a linker option on Unix platforms
194 // which adds to the runtime dynamic loader path when looking for
195 // dynamic libraries. We use this by default on Unix platforms to ensure
196 // that our nightlies behave the same on Windows, that is they work out
197 // of the box. This can be disabled, of course, but basically that's why
198 // we're gated on RUSTC_RPATH here.
200 // Ok, so the astute might be wondering "why isn't `-C rpath` used
201 // here?" and that is indeed a good question to task. This codegen
202 // option is the compiler's current interface to generating an rpath.
203 // Unfortunately it doesn't quite suffice for us. The flag currently
204 // takes no value as an argument, so the compiler calculates what it
205 // should pass to the linker as `-rpath`. This unfortunately is based on
206 // the **compile time** directory structure which when building with
207 // Cargo will be very different than the runtime directory structure.
209 // All that's a really long winded way of saying that if we use
210 // `-Crpath` then the executables generated have the wrong rpath of
211 // something like `$ORIGIN/deps` when in fact the way we distribute
212 // rustc requires the rpath to be `$ORIGIN/../lib`.
214 // So, all in all, to set up the correct rpath we pass the linker
215 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
216 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
217 // to change a flag in a binary?
218 if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
219 let rpath = if target.contains("apple") {
221 // Note that we need to take one extra step on macOS to also pass
222 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
223 // do that we pass a weird flag to the compiler to get it to do
224 // so. Note that this is definitely a hack, and we should likely
225 // flesh out rpath support more fully in the future.
226 cmd.arg("-Z").arg("osx-rpath-install-name");
227 Some("-Wl,-rpath,@loader_path/../lib")
228 } else if !target.contains("windows") && !target.contains("wasm32") {
229 Some("-Wl,-rpath,$ORIGIN/../lib")
233 if let Some(rpath) = rpath {
234 cmd.arg("-C").arg(format!("link-args={}", rpath));
238 if let Ok(s) = env::var("RUSTC_CRT_STATIC") {
240 cmd.arg("-C").arg("target-feature=+crt-static");
243 cmd.arg("-C").arg("target-feature=-crt-static");
247 // When running miri tests, we need to generate MIR for all libraries
248 if env::var("TEST_MIRI").ok().map_or(false, |val| val == "true") {
249 cmd.arg("-Zalways-encode-mir");
250 cmd.arg("-Zmir-emit-validate=1");
253 // Force all crates compiled by this compiler to (a) be unstable and (b)
254 // allow the `rustc_private` feature to link to other unstable crates
255 // also in the sysroot.
256 if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() {
257 cmd.arg("-Z").arg("force-unstable-if-unmarked");
260 // Override linker if necessary.
261 if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
262 cmd.arg(format!("-Clinker={}", host_linker));
266 if env::var_os("RUSTC_PARALLEL_QUERIES").is_some() {
267 cmd.arg("--cfg").arg("parallel_queries");
270 let color = match env::var("RUSTC_COLOR") {
271 Ok(s) => usize::from_str(&s).expect("RUSTC_COLOR should be an integer"),
276 cmd.arg("--color=always");
279 if env::var_os("RUSTC_DENY_WARNINGS").is_some() {
280 cmd.arg("-Dwarnings");
284 eprintln!("rustc command: {:?}", cmd);
285 eprintln!("sysroot: {:?}", sysroot);
286 eprintln!("libdir: {:?}", libdir);
289 if let Some(mut on_fail) = on_fail {
290 let e = match cmd.status() {
291 Ok(s) if s.success() => std::process::exit(0),
294 println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
295 exec_cmd(&mut on_fail).expect("could not run the backup command");
296 std::process::exit(1);
299 if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
300 if let Some(krate) = maybe_crate {
301 let start = Instant::now();
304 .expect(&format!("\n\n failed to run {:?}", cmd));
305 let dur = start.elapsed();
307 let is_test = args.iter().any(|a| a == "--test");
308 eprintln!("[RUSTC-TIMING] {} test:{} {}.{:03}",
309 krate.to_string_lossy(),
312 dur.subsec_nanos() / 1_000_000);
314 match status.code() {
315 Some(i) => std::process::exit(i),
317 eprintln!("rustc exited with {}", status);
318 std::process::exit(0xfe);
324 let code = exec_cmd(&mut cmd).expect(&format!("\n\n failed to run {:?}", cmd));
325 std::process::exit(code);
329 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
330 use std::os::unix::process::CommandExt;
335 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
336 cmd.status().map(|status| status.code().unwrap())