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::io::prelude::*;
36 use std::str::FromStr;
37 use std::path::PathBuf;
38 use std::process::{Command, ExitStatus};
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 // Detect whether or not we're a build script depending on whether --target
67 // is passed (a bit janky...)
68 let target = args.windows(2)
69 .find(|w| &*w[0] == "--target")
70 .and_then(|w| w[1].to_str());
71 let version = args.iter().find(|w| &**w == "-vV");
73 let verbose = match env::var("RUSTC_VERBOSE") {
74 Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
78 // Use a different compiler for build scripts, since there may not yet be a
79 // libstd for the real compiler to use. However, if Cargo is attempting to
80 // determine the version of the compiler, the real compiler needs to be
81 // used. Currently, these two states are differentiated based on whether
82 // --target and -vV is/isn't passed.
83 let (rustc, libdir) = if target.is_none() && version.is_none() {
84 ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
86 ("RUSTC_REAL", "RUSTC_LIBDIR")
88 let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
89 let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
90 let mut on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of));
92 let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
93 let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
94 let mut dylib_path = bootstrap::util::dylib_path();
95 dylib_path.insert(0, PathBuf::from(libdir));
97 let mut cmd = Command::new(rustc);
100 .arg(format!("stage{}", stage))
101 .env(bootstrap::util::dylib_path_var(),
102 env::join_paths(&dylib_path).unwrap());
104 if let Some(target) = target {
105 // The stage0 compiler has a special sysroot distinct from what we
106 // actually downloaded, so we just always pass the `--sysroot` option.
107 cmd.arg("--sysroot").arg(sysroot);
109 // When we build Rust dylibs they're all intended for intermediate
110 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
111 // linking all deps statically into the dylib.
112 if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
113 cmd.arg("-Cprefer-dynamic");
116 // Help the libc crate compile by assisting it in finding the MUSL
118 if let Some(s) = env::var_os("MUSL_ROOT") {
119 let mut root = OsString::from("native=");
122 cmd.arg("-L").arg(&root);
125 // Pass down extra flags, commonly used to configure `-Clinker` when
127 if let Ok(s) = env::var("RUSTC_FLAGS") {
128 cmd.args(&s.split(" ").filter(|s| !s.is_empty()).collect::<Vec<_>>());
131 // Pass down incremental directory, if any.
132 if let Ok(dir) = env::var("RUSTC_INCREMENTAL") {
133 cmd.arg(format!("-Zincremental={}", dir));
136 cmd.arg("-Zincremental-info");
140 let crate_name = args.windows(2)
141 .find(|a| &*a[0] == "--crate-name")
143 let crate_name = &*crate_name[1];
145 // If we're compiling specifically the `panic_abort` crate then we pass
146 // the `-C panic=abort` option. Note that we do not do this for any
147 // other crate intentionally as this is the only crate for now that we
148 // ship with panic=abort.
150 // This... is a bit of a hack how we detect this. Ideally this
151 // information should be encoded in the crate I guess? Would likely
152 // require an RFC amendment to RFC 1513, however.
154 // `compiler_builtins` are unconditionally compiled with panic=abort to
155 // workaround undefined references to `rust_eh_unwind_resume` generated
156 // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
157 if crate_name == "panic_abort" ||
158 crate_name == "compiler_builtins" && stage != "0" {
159 cmd.arg("-C").arg("panic=abort");
162 // Set various options from config.toml to configure how we're building
164 if env::var("RUSTC_DEBUGINFO") == Ok("true".to_string()) {
166 } else if env::var("RUSTC_DEBUGINFO_LINES") == Ok("true".to_string()) {
167 cmd.arg("-Cdebuginfo=1");
169 let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
170 Ok(s) => if s == "true" { "y" } else { "n" },
174 // The compiler builtins are pretty sensitive to symbols referenced in
175 // libcore and such, so we never compile them with debug assertions.
176 if crate_name == "compiler_builtins" {
177 cmd.arg("-C").arg("debug-assertions=no");
179 cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
182 if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
183 cmd.arg("-C").arg(format!("codegen-units={}", s));
186 // Emit save-analysis info.
187 if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
188 cmd.arg("-Zsave-analysis");
189 cmd.env("RUST_SAVE_ANALYSIS_CONFIG",
190 "{\"output_file\": null,\"full_docs\": false,\"pub_only\": true,\
191 \"signatures\": false,\"borrow_data\": false}");
194 // Dealing with rpath here is a little special, so let's go into some
195 // detail. First off, `-rpath` is a linker option on Unix platforms
196 // which adds to the runtime dynamic loader path when looking for
197 // dynamic libraries. We use this by default on Unix platforms to ensure
198 // that our nightlies behave the same on Windows, that is they work out
199 // of the box. This can be disabled, of course, but basically that's why
200 // we're gated on RUSTC_RPATH here.
202 // Ok, so the astute might be wondering "why isn't `-C rpath` used
203 // here?" and that is indeed a good question to task. This codegen
204 // option is the compiler's current interface to generating an rpath.
205 // Unfortunately it doesn't quite suffice for us. The flag currently
206 // takes no value as an argument, so the compiler calculates what it
207 // should pass to the linker as `-rpath`. This unfortunately is based on
208 // the **compile time** directory structure which when building with
209 // Cargo will be very different than the runtime directory structure.
211 // All that's a really long winded way of saying that if we use
212 // `-Crpath` then the executables generated have the wrong rpath of
213 // something like `$ORIGIN/deps` when in fact the way we distribute
214 // rustc requires the rpath to be `$ORIGIN/../lib`.
216 // So, all in all, to set up the correct rpath we pass the linker
217 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
218 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
219 // to change a flag in a binary?
220 if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
221 let rpath = if target.contains("apple") {
223 // Note that we need to take one extra step on macOS to also pass
224 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
225 // do that we pass a weird flag to the compiler to get it to do
226 // so. Note that this is definitely a hack, and we should likely
227 // flesh out rpath support more fully in the future.
228 cmd.arg("-Z").arg("osx-rpath-install-name");
229 Some("-Wl,-rpath,@loader_path/../lib")
230 } else if !target.contains("windows") {
231 Some("-Wl,-rpath,$ORIGIN/../lib")
235 if let Some(rpath) = rpath {
236 cmd.arg("-C").arg(format!("link-args={}", rpath));
240 if target.contains("pc-windows-msvc") {
241 cmd.arg("-Z").arg("unstable-options");
242 cmd.arg("-C").arg("target-feature=+crt-static");
245 // Force all crates compiled by this compiler to (a) be unstable and (b)
246 // allow the `rustc_private` feature to link to other unstable crates
247 // also in the sysroot.
248 if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() {
249 cmd.arg("-Z").arg("force-unstable-if-unmarked");
253 let color = match env::var("RUSTC_COLOR") {
254 Ok(s) => usize::from_str(&s).expect("RUSTC_COLOR should be an integer"),
259 cmd.arg("--color=always");
263 writeln!(&mut io::stderr(), "rustc command: {:?}", cmd).unwrap();
266 // Actually run the compiler!
267 std::process::exit(if let Some(ref mut on_fail) = on_fail {
269 Ok(s) if s.success() => 0,
271 println!("\nDid not run successfully:\n{:?}\n-------------", cmd);
272 exec_cmd(on_fail).expect("could not run the backup command");
277 std::process::exit(match exec_cmd(&mut cmd) {
278 Ok(s) => s.code().unwrap_or(0xfe),
279 Err(e) => panic!("\n\nfailed to run {:?}: {}\n\n", cmd, e),
285 fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> {
286 use std::os::unix::process::CommandExt;
291 fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> {