1 //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
3 //! This shim will take care of some various tasks that our build process
4 //! requires that Cargo can't quite do through normal configuration:
6 //! 1. When compiling build scripts and build dependencies, we need a guaranteed
7 //! full standard library available. The only compiler which actually has
8 //! this is the snapshot, so we detect this situation and always compile with
9 //! the snapshot compiler.
10 //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling
11 //! (and this slightly differs based on a whether we're using a snapshot or
12 //! not), so we do that all here.
14 //! This may one day be replaced by RUSTFLAGS, but the dynamic nature of
15 //! switching compilers for the bootstrap and for build scripts will probably
16 //! never get replaced.
19 use std::ffi::OsString;
21 use std::path::PathBuf;
22 use std::process::Command;
23 use std::str::FromStr;
24 use std::time::Instant;
27 let mut args = env::args_os().skip(1).collect::<Vec<_>>();
29 // Append metadata suffix for internal crates. See the corresponding entry
30 // in bootstrap/lib.rs for details.
31 if let Ok(s) = env::var("RUSTC_METADATA_SUFFIX") {
32 for i in 1..args.len() {
33 // Dirty code for borrowing issues
35 if let Some(current_as_str) = args[i].to_str() {
36 if (&*args[i - 1] == "-C" && current_as_str.starts_with("metadata")) ||
37 current_as_str.starts_with("-Cmetadata") {
38 new = Some(format!("{}-{}", current_as_str, s));
41 if let Some(new) = new { args[i] = new.into(); }
45 // Detect whether or not we're a build script depending on whether --target
46 // is passed (a bit janky...)
47 let target = args.windows(2)
48 .find(|w| &*w[0] == "--target")
49 .and_then(|w| w[1].to_str());
50 let version = args.iter().find(|w| &**w == "-vV");
52 let verbose = match env::var("RUSTC_VERBOSE") {
53 Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
57 // Use a different compiler for build scripts, since there may not yet be a
58 // libstd for the real compiler to use. However, if Cargo is attempting to
59 // determine the version of the compiler, the real compiler needs to be
60 // used. Currently, these two states are differentiated based on whether
61 // --target and -vV is/isn't passed.
62 let (rustc, libdir) = if target.is_none() && version.is_none() {
63 ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
65 ("RUSTC_REAL", "RUSTC_LIBDIR")
67 let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
68 let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
69 let on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of));
71 let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
72 let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
73 let mut dylib_path = bootstrap::util::dylib_path();
74 dylib_path.insert(0, PathBuf::from(&libdir));
76 let mut cmd = Command::new(rustc);
78 .env(bootstrap::util::dylib_path_var(),
79 env::join_paths(&dylib_path).unwrap());
81 // Get the name of the crate we're compiling, if any.
82 let crate_name = args.windows(2)
83 .find(|args| args[0] == "--crate-name")
84 .and_then(|args| args[1].to_str());
86 if let Some(crate_name) = crate_name {
87 if let Some(target) = env::var_os("RUSTC_TIME") {
89 target.into_string().unwrap().split(",").any(|c| c.trim() == crate_name)
96 // Non-zero stages must all be treated uniformly to avoid problems when attempting to uplift
97 // compiler libraries and such from stage 1 to 2.
99 // FIXME: the fact that core here is excluded is due to core_arch from our stdarch submodule
100 // being broken on the beta compiler with bootstrap passed, so this is a temporary workaround
101 // (we've just snapped, so there are no cfg(bootstrap) related annotations in core).
103 if crate_name != Some("core") {
104 cmd.arg("--cfg").arg("bootstrap");
106 // NOTE(eddyb) see FIXME above, except now we need annotations again in core.
107 cmd.arg("--cfg").arg("boostrap_stdarch_ignore_this");
111 // Print backtrace in case of ICE
112 if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() {
113 cmd.env("RUST_BACKTRACE", "1");
116 cmd.env("RUSTC_BREAK_ON_ICE", "1");
118 if let Ok(debuginfo_level) = env::var("RUSTC_DEBUGINFO_LEVEL") {
119 cmd.arg(format!("-Cdebuginfo={}", debuginfo_level));
122 if env::var_os("RUSTC_DENY_WARNINGS").is_some() &&
123 env::var_os("RUSTC_EXTERNAL_TOOL").is_none() {
124 // When extending this list, add the new lints to the RUSTFLAGS of the
125 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
126 // some code doesn't go through this `rustc` wrapper.
127 cmd.arg("-Dwarnings");
128 cmd.arg("-Drust_2018_idioms");
129 cmd.arg("-Dunused_lifetimes");
130 if use_internal_lints(crate_name) {
131 cmd.arg("-Zunstable-options");
132 cmd.arg("-Drustc::internal");
136 if let Some(target) = target {
137 // The stage0 compiler has a special sysroot distinct from what we
138 // actually downloaded, so we just always pass the `--sysroot` option,
139 // unless one is already set.
140 if !args.iter().any(|arg| arg == "--sysroot") {
141 cmd.arg("--sysroot").arg(&sysroot);
144 cmd.arg("-Zexternal-macro-backtrace");
146 // Link crates to the proc macro crate for the target, but use a host proc macro crate
147 // to actually run the macros
148 if env::var_os("RUST_DUAL_PROC_MACROS").is_some() {
149 cmd.arg("-Zdual-proc-macros");
152 // When we build Rust dylibs they're all intended for intermediate
153 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
154 // linking all deps statically into the dylib.
155 if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
156 cmd.arg("-Cprefer-dynamic");
159 // Help the libc crate compile by assisting it in finding various
160 // sysroot native libraries.
161 if let Some(s) = env::var_os("MUSL_ROOT") {
162 if target.contains("musl") {
163 let mut root = OsString::from("native=");
166 cmd.arg("-L").arg(&root);
169 if let Some(s) = env::var_os("WASI_ROOT") {
170 let mut root = OsString::from("native=");
172 root.push("/lib/wasm32-wasi");
173 cmd.arg("-L").arg(&root);
176 // Override linker if necessary.
177 if let Ok(target_linker) = env::var("RUSTC_TARGET_LINKER") {
178 cmd.arg(format!("-Clinker={}", target_linker));
181 // If we're compiling specifically the `panic_abort` crate then we pass
182 // the `-C panic=abort` option. Note that we do not do this for any
183 // other crate intentionally as this is the only crate for now that we
184 // ship with panic=abort.
186 // This... is a bit of a hack how we detect this. Ideally this
187 // information should be encoded in the crate I guess? Would likely
188 // require an RFC amendment to RFC 1513, however.
190 // `compiler_builtins` are unconditionally compiled with panic=abort to
191 // workaround undefined references to `rust_eh_unwind_resume` generated
192 // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
193 if crate_name == Some("panic_abort") ||
194 crate_name == Some("compiler_builtins") && stage != "0" {
195 cmd.arg("-C").arg("panic=abort");
198 // Set various options from config.toml to configure how we're building
200 let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
201 Ok(s) => if s == "true" { "y" } else { "n" },
205 // The compiler builtins are pretty sensitive to symbols referenced in
206 // libcore and such, so we never compile them with debug assertions.
207 if crate_name == Some("compiler_builtins") {
208 cmd.arg("-C").arg("debug-assertions=no");
210 cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
213 if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
214 cmd.arg("-C").arg(format!("codegen-units={}", s));
217 // Emit save-analysis info.
218 if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
219 cmd.arg("-Zsave-analysis");
220 cmd.env("RUST_SAVE_ANALYSIS_CONFIG",
221 "{\"output_file\": null,\"full_docs\": false,\
222 \"pub_only\": true,\"reachable_only\": false,\
223 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
226 // Dealing with rpath here is a little special, so let's go into some
227 // detail. First off, `-rpath` is a linker option on Unix platforms
228 // which adds to the runtime dynamic loader path when looking for
229 // dynamic libraries. We use this by default on Unix platforms to ensure
230 // that our nightlies behave the same on Windows, that is they work out
231 // of the box. This can be disabled, of course, but basically that's why
232 // we're gated on RUSTC_RPATH here.
234 // Ok, so the astute might be wondering "why isn't `-C rpath` used
235 // here?" and that is indeed a good question to task. This codegen
236 // option is the compiler's current interface to generating an rpath.
237 // Unfortunately it doesn't quite suffice for us. The flag currently
238 // takes no value as an argument, so the compiler calculates what it
239 // should pass to the linker as `-rpath`. This unfortunately is based on
240 // the **compile time** directory structure which when building with
241 // Cargo will be very different than the runtime directory structure.
243 // All that's a really long winded way of saying that if we use
244 // `-Crpath` then the executables generated have the wrong rpath of
245 // something like `$ORIGIN/deps` when in fact the way we distribute
246 // rustc requires the rpath to be `$ORIGIN/../lib`.
248 // So, all in all, to set up the correct rpath we pass the linker
249 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
250 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
251 // to change a flag in a binary?
252 if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
253 let rpath = if target.contains("apple") {
255 // Note that we need to take one extra step on macOS to also pass
256 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
257 // do that we pass a weird flag to the compiler to get it to do
258 // so. Note that this is definitely a hack, and we should likely
259 // flesh out rpath support more fully in the future.
260 cmd.arg("-Z").arg("osx-rpath-install-name");
261 Some("-Wl,-rpath,@loader_path/../lib")
262 } else if !target.contains("windows") &&
263 !target.contains("wasm32") &&
264 !target.contains("fuchsia") {
265 Some("-Wl,-rpath,$ORIGIN/../lib")
269 if let Some(rpath) = rpath {
270 cmd.arg("-C").arg(format!("link-args={}", rpath));
274 if let Ok(s) = env::var("RUSTC_CRT_STATIC") {
276 cmd.arg("-C").arg("target-feature=+crt-static");
279 cmd.arg("-C").arg("target-feature=-crt-static");
283 // Override linker if necessary.
284 if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
285 cmd.arg(format!("-Clinker={}", host_linker));
288 if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") {
290 cmd.arg("-C").arg("target-feature=+crt-static");
293 cmd.arg("-C").arg("target-feature=-crt-static");
298 if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
299 cmd.arg("--remap-path-prefix").arg(&map);
302 // Force all crates compiled by this compiler to (a) be unstable and (b)
303 // allow the `rustc_private` feature to link to other unstable crates
304 // also in the sysroot. We also do this for host crates, since those
305 // may be proc macros, in which case we might ship them.
306 if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) {
307 cmd.arg("-Z").arg("force-unstable-if-unmarked");
310 if env::var_os("RUSTC_PARALLEL_COMPILER").is_some() {
311 cmd.arg("--cfg").arg("parallel_compiler");
316 "rustc command: {:?}={:?} {:?}",
317 bootstrap::util::dylib_path_var(),
318 env::join_paths(&dylib_path).unwrap(),
321 eprintln!("sysroot: {:?}", sysroot);
322 eprintln!("libdir: {:?}", libdir);
325 if let Some(mut on_fail) = on_fail {
326 let e = match cmd.status() {
327 Ok(s) if s.success() => std::process::exit(0),
330 println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
331 exec_cmd(&mut on_fail).expect("could not run the backup command");
332 std::process::exit(1);
335 if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
336 if let Some(crate_name) = crate_name {
337 let start = Instant::now();
340 .unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
341 let dur = start.elapsed();
343 let is_test = args.iter().any(|a| a == "--test");
344 eprintln!("[RUSTC-TIMING] {} test:{} {}.{:03}",
348 dur.subsec_nanos() / 1_000_000);
350 match status.code() {
351 Some(i) => std::process::exit(i),
353 eprintln!("rustc exited with {}", status);
354 std::process::exit(0xfe);
360 let code = exec_cmd(&mut cmd).unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
361 std::process::exit(code);
364 // Rustc crates for which internal lints are in effect.
365 fn use_internal_lints(crate_name: Option<&str>) -> bool {
366 crate_name.map_or(false, |crate_name| {
367 crate_name.starts_with("rustc") || crate_name.starts_with("syntax") ||
368 ["arena", "fmt_macros"].contains(&crate_name)
373 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
374 use std::os::unix::process::CommandExt;
379 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
380 cmd.status().map(|status| status.code().unwrap())