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.
21 use std::ffi::OsString;
23 use std::path::PathBuf;
24 use std::process::Command;
25 use std::str::FromStr;
26 use std::time::Instant;
29 let mut args = env::args_os().skip(1).collect::<Vec<_>>();
31 // Append metadata suffix for internal crates. See the corresponding entry
32 // in bootstrap/lib.rs for details.
33 if let Ok(s) = env::var("RUSTC_METADATA_SUFFIX") {
34 for i in 1..args.len() {
35 // Dirty code for borrowing issues
37 if let Some(current_as_str) = args[i].to_str() {
38 if (&*args[i - 1] == "-C" && current_as_str.starts_with("metadata")) ||
39 current_as_str.starts_with("-Cmetadata") {
40 new = Some(format!("{}-{}", current_as_str, s));
43 if let Some(new) = new { args[i] = new.into(); }
47 // Drop `--error-format json` because despite our desire for json messages
48 // from Cargo we don't want any from rustc itself.
49 if let Some(n) = args.iter().position(|n| n == "--error-format") {
54 if let Some(s) = env::var_os("RUSTC_ERROR_FORMAT") {
55 args.push("--error-format".into());
59 // Detect whether or not we're a build script depending on whether --target
60 // is passed (a bit janky...)
61 let target = args.windows(2)
62 .find(|w| &*w[0] == "--target")
63 .and_then(|w| w[1].to_str());
64 let version = args.iter().find(|w| &**w == "-vV");
66 let verbose = match env::var("RUSTC_VERBOSE") {
67 Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
71 // Use a different compiler for build scripts, since there may not yet be a
72 // libstd for the real compiler to use. However, if Cargo is attempting to
73 // determine the version of the compiler, the real compiler needs to be
74 // used. Currently, these two states are differentiated based on whether
75 // --target and -vV is/isn't passed.
76 let (rustc, libdir) = if target.is_none() && version.is_none() {
77 ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
79 ("RUSTC_REAL", "RUSTC_LIBDIR")
81 let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
82 let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
83 let on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of));
85 let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
86 let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
87 let mut dylib_path = bootstrap::util::dylib_path();
88 dylib_path.insert(0, PathBuf::from(&libdir));
90 let mut cmd = Command::new(rustc);
93 .arg(format!("stage{}", stage))
94 .env(bootstrap::util::dylib_path_var(),
95 env::join_paths(&dylib_path).unwrap());
96 let mut maybe_crate = None;
98 // Print backtrace in case of ICE
99 if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() {
100 cmd.env("RUST_BACKTRACE", "1");
103 cmd.env("RUSTC_BREAK_ON_ICE", "1");
105 if let Some(target) = target {
106 // The stage0 compiler has a special sysroot distinct from what we
107 // actually downloaded, so we just always pass the `--sysroot` option.
108 cmd.arg("--sysroot").arg(&sysroot);
110 cmd.arg("-Zexternal-macro-backtrace");
112 // Link crates to the proc macro crate for the target, but use a host proc macro crate
113 // to actually run the macros
114 if env::var_os("RUST_DUAL_PROC_MACROS").is_some() {
115 cmd.arg("-Zdual-proc-macros");
118 // When we build Rust dylibs they're all intended for intermediate
119 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
120 // linking all deps statically into the dylib.
121 if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
122 cmd.arg("-Cprefer-dynamic");
125 // Help the libc crate compile by assisting it in finding various
126 // sysroot native libraries.
127 if let Some(s) = env::var_os("MUSL_ROOT") {
128 if target.contains("musl") {
129 let mut root = OsString::from("native=");
132 cmd.arg("-L").arg(&root);
135 if let Some(s) = env::var_os("WASI_ROOT") {
136 let mut root = OsString::from("native=");
138 root.push("/lib/wasm32-wasi");
139 cmd.arg("-L").arg(&root);
142 // Override linker if necessary.
143 if let Ok(target_linker) = env::var("RUSTC_TARGET_LINKER") {
144 cmd.arg(format!("-Clinker={}", target_linker));
147 let crate_name = args.windows(2)
148 .find(|a| &*a[0] == "--crate-name")
150 let crate_name = &*crate_name[1];
151 maybe_crate = Some(crate_name);
153 // If we're compiling specifically the `panic_abort` crate then we pass
154 // the `-C panic=abort` option. Note that we do not do this for any
155 // other crate intentionally as this is the only crate for now that we
156 // ship with panic=abort.
158 // This... is a bit of a hack how we detect this. Ideally this
159 // information should be encoded in the crate I guess? Would likely
160 // require an RFC amendment to RFC 1513, however.
162 // `compiler_builtins` are unconditionally compiled with panic=abort to
163 // workaround undefined references to `rust_eh_unwind_resume` generated
164 // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
165 if crate_name == "panic_abort" ||
166 crate_name == "compiler_builtins" && stage != "0" {
167 cmd.arg("-C").arg("panic=abort");
170 // Set various options from config.toml to configure how we're building
172 if env::var("RUSTC_DEBUGINFO") == Ok("true".to_string()) {
174 } else if env::var("RUSTC_DEBUGINFO_LINES") == Ok("true".to_string()) {
175 cmd.arg("-Cdebuginfo=1");
177 let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
178 Ok(s) => if s == "true" { "y" } else { "n" },
182 // The compiler builtins are pretty sensitive to symbols referenced in
183 // libcore and such, so we never compile them with debug assertions.
184 if crate_name == "compiler_builtins" {
185 cmd.arg("-C").arg("debug-assertions=no");
187 cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
190 // Build all crates in the `std` facade with `-Z emit-stack-sizes` to add stack usage
193 // When you use this `-Z` flag with Cargo you get stack usage information on all crates
194 // compiled from source, and when you are using LTO you also get information on pre-compiled
195 // crates like `core` and `std`, even if they were not compiled with `-Z emit-stack-sizes`.
196 // However, there's an exception: `compiler_builtins`. This crate is special and doesn't
197 // participate in LTO because it's always linked as a separate object file. For this reason
198 // it's impossible to get stack usage information about `compiler-builtins` using
199 // `RUSTFLAGS` + Cargo, or `cargo rustc`.
201 // To make the stack usage information of all crates under the `std` facade available to
202 // Cargo based stack usage analysis tools, in both LTO and non-LTO mode, we compile them
203 // with the `-Z emit-stack-sizes` flag. The `RUSTC_EMIT_STACK_SIZES` var helps us apply this
204 // flag only to the crates in the `std` facade. The `-Z` flag is known to currently work
205 // with targets that produce ELF files so we limit its use flag to those targets.
207 // NOTE(japaric) if this ever causes problem with an LLVM upgrade or any PR feel free to
208 // remove it or comment it out
209 if env::var_os("RUSTC_EMIT_STACK_SIZES").is_some()
210 && (target.contains("-linux-")
211 || target.contains("-none-eabi")
212 || target.ends_with("-none-elf"))
214 cmd.arg("-Zemit-stack-sizes");
217 if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
218 cmd.arg("-C").arg(format!("codegen-units={}", s));
221 // Emit save-analysis info.
222 if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
223 cmd.arg("-Zsave-analysis");
224 cmd.env("RUST_SAVE_ANALYSIS_CONFIG",
225 "{\"output_file\": null,\"full_docs\": false,\
226 \"pub_only\": true,\"reachable_only\": false,\
227 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
230 // Dealing with rpath here is a little special, so let's go into some
231 // detail. First off, `-rpath` is a linker option on Unix platforms
232 // which adds to the runtime dynamic loader path when looking for
233 // dynamic libraries. We use this by default on Unix platforms to ensure
234 // that our nightlies behave the same on Windows, that is they work out
235 // of the box. This can be disabled, of course, but basically that's why
236 // we're gated on RUSTC_RPATH here.
238 // Ok, so the astute might be wondering "why isn't `-C rpath` used
239 // here?" and that is indeed a good question to task. This codegen
240 // option is the compiler's current interface to generating an rpath.
241 // Unfortunately it doesn't quite suffice for us. The flag currently
242 // takes no value as an argument, so the compiler calculates what it
243 // should pass to the linker as `-rpath`. This unfortunately is based on
244 // the **compile time** directory structure which when building with
245 // Cargo will be very different than the runtime directory structure.
247 // All that's a really long winded way of saying that if we use
248 // `-Crpath` then the executables generated have the wrong rpath of
249 // something like `$ORIGIN/deps` when in fact the way we distribute
250 // rustc requires the rpath to be `$ORIGIN/../lib`.
252 // So, all in all, to set up the correct rpath we pass the linker
253 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
254 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
255 // to change a flag in a binary?
256 if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
257 let rpath = if target.contains("apple") {
259 // Note that we need to take one extra step on macOS to also pass
260 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
261 // do that we pass a weird flag to the compiler to get it to do
262 // so. Note that this is definitely a hack, and we should likely
263 // flesh out rpath support more fully in the future.
264 cmd.arg("-Z").arg("osx-rpath-install-name");
265 Some("-Wl,-rpath,@loader_path/../lib")
266 } else if !target.contains("windows") &&
267 !target.contains("wasm32") &&
268 !target.contains("fuchsia") {
269 Some("-Wl,-rpath,$ORIGIN/../lib")
273 if let Some(rpath) = rpath {
274 cmd.arg("-C").arg(format!("link-args={}", rpath));
278 if let Ok(s) = env::var("RUSTC_CRT_STATIC") {
280 cmd.arg("-C").arg("target-feature=+crt-static");
283 cmd.arg("-C").arg("target-feature=-crt-static");
287 // When running miri tests, we need to generate MIR for all libraries
288 if env::var("TEST_MIRI").ok().map_or(false, |val| val == "true") {
289 // The flags here should be kept in sync with `add_miri_default_args`
290 // in miri's `src/lib.rs`.
291 cmd.arg("-Zalways-encode-mir");
292 // These options are preferred by miri, to be able to perform better validation,
293 // but the bootstrap compiler might not understand them.
295 cmd.arg("-Zmir-emit-retag");
296 cmd.arg("-Zmir-opt-level=0");
300 if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
301 cmd.arg("--remap-path-prefix").arg(&map);
304 // Override linker if necessary.
305 if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
306 cmd.arg(format!("-Clinker={}", host_linker));
309 if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") {
311 cmd.arg("-C").arg("target-feature=+crt-static");
314 cmd.arg("-C").arg("target-feature=-crt-static");
319 // Force all crates compiled by this compiler to (a) be unstable and (b)
320 // allow the `rustc_private` feature to link to other unstable crates
321 // also in the sysroot. We also do this for host crates, since those
322 // may be proc macros, in which case we might ship them.
323 if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) {
324 cmd.arg("-Z").arg("force-unstable-if-unmarked");
327 if env::var_os("RUSTC_PARALLEL_COMPILER").is_some() {
328 cmd.arg("--cfg").arg("parallel_compiler");
331 if env::var_os("RUSTC_DENY_WARNINGS").is_some() && env::var_os("RUSTC_EXTERNAL_TOOL").is_none()
333 cmd.arg("-Dwarnings");
334 cmd.arg("-Dbare_trait_objects");
339 "rustc command: {:?}={:?} {:?}",
340 bootstrap::util::dylib_path_var(),
341 env::join_paths(&dylib_path).unwrap(),
344 eprintln!("sysroot: {:?}", sysroot);
345 eprintln!("libdir: {:?}", libdir);
348 if let Some(mut on_fail) = on_fail {
349 let e = match cmd.status() {
350 Ok(s) if s.success() => std::process::exit(0),
353 println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
354 exec_cmd(&mut on_fail).expect("could not run the backup command");
355 std::process::exit(1);
358 if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
359 if let Some(krate) = maybe_crate {
360 let start = Instant::now();
363 .unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
364 let dur = start.elapsed();
366 let is_test = args.iter().any(|a| a == "--test");
367 eprintln!("[RUSTC-TIMING] {} test:{} {}.{:03}",
368 krate.to_string_lossy(),
371 dur.subsec_nanos() / 1_000_000);
373 match status.code() {
374 Some(i) => std::process::exit(i),
376 eprintln!("rustc exited with {}", status);
377 std::process::exit(0xfe);
383 let code = exec_cmd(&mut cmd).unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
384 std::process::exit(code);
388 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
389 use std::os::unix::process::CommandExt;
394 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
395 cmd.status().map(|status| status.code().unwrap())