]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/bin/rustc.rs
Auto merge of #73456 - tmiasko:musl-libdir, r=Mark-Simulacrum
[rust.git] / src / bootstrap / bin / rustc.rs
1 //! Shim which is passed to Cargo as "rustc" when running the bootstrap.
2 //!
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:
5 //!
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.
13 //!
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.
17
18 use std::env;
19 use std::io;
20 use std::path::PathBuf;
21 use std::process::Command;
22 use std::str::FromStr;
23 use std::time::Instant;
24
25 fn main() {
26     let args = env::args_os().skip(1).collect::<Vec<_>>();
27
28     // Detect whether or not we're a build script depending on whether --target
29     // is passed (a bit janky...)
30     let target = args.windows(2).find(|w| &*w[0] == "--target").and_then(|w| w[1].to_str());
31     let version = args.iter().find(|w| &**w == "-vV");
32
33     let verbose = match env::var("RUSTC_VERBOSE") {
34         Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
35         Err(_) => 0,
36     };
37
38     // Use a different compiler for build scripts, since there may not yet be a
39     // libstd for the real compiler to use. However, if Cargo is attempting to
40     // determine the version of the compiler, the real compiler needs to be
41     // used. Currently, these two states are differentiated based on whether
42     // --target and -vV is/isn't passed.
43     let (rustc, libdir) = if target.is_none() && version.is_none() {
44         ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
45     } else {
46         ("RUSTC_REAL", "RUSTC_LIBDIR")
47     };
48     let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
49     let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
50     let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new);
51
52     let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
53     let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
54     let mut dylib_path = bootstrap::util::dylib_path();
55     dylib_path.insert(0, PathBuf::from(&libdir));
56
57     let mut cmd = Command::new(rustc);
58     cmd.args(&args).env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
59
60     // Get the name of the crate we're compiling, if any.
61     let crate_name =
62         args.windows(2).find(|args| args[0] == "--crate-name").and_then(|args| args[1].to_str());
63
64     if let Some(crate_name) = crate_name {
65         if let Some(target) = env::var_os("RUSTC_TIME") {
66             if target == "all"
67                 || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name)
68             {
69                 cmd.arg("-Ztime");
70             }
71         }
72     }
73
74     // Print backtrace in case of ICE
75     if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() {
76         cmd.env("RUST_BACKTRACE", "1");
77     }
78
79     if target.is_some() {
80         // The stage0 compiler has a special sysroot distinct from what we
81         // actually downloaded, so we just always pass the `--sysroot` option,
82         // unless one is already set.
83         if !args.iter().any(|arg| arg == "--sysroot") {
84             cmd.arg("--sysroot").arg(&sysroot);
85         }
86
87         // If we're compiling specifically the `panic_abort` crate then we pass
88         // the `-C panic=abort` option. Note that we do not do this for any
89         // other crate intentionally as this is the only crate for now that we
90         // ship with panic=abort.
91         //
92         // This... is a bit of a hack how we detect this. Ideally this
93         // information should be encoded in the crate I guess? Would likely
94         // require an RFC amendment to RFC 1513, however.
95         //
96         // `compiler_builtins` are unconditionally compiled with panic=abort to
97         // workaround undefined references to `rust_eh_unwind_resume` generated
98         // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
99         if crate_name == Some("panic_abort")
100             || crate_name == Some("compiler_builtins") && stage != "0"
101         {
102             cmd.arg("-C").arg("panic=abort");
103         }
104     } else {
105         // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars
106         // here, but rather Cargo should know what flags to pass rustc itself.
107
108         // Override linker if necessary.
109         if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
110             cmd.arg(format!("-Clinker={}", host_linker));
111         }
112
113         if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") {
114             if s == "true" {
115                 cmd.arg("-C").arg("target-feature=+crt-static");
116             }
117             if s == "false" {
118                 cmd.arg("-C").arg("target-feature=-crt-static");
119             }
120         }
121     }
122
123     if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
124         cmd.arg("--remap-path-prefix").arg(&map);
125     }
126
127     // Force all crates compiled by this compiler to (a) be unstable and (b)
128     // allow the `rustc_private` feature to link to other unstable crates
129     // also in the sysroot. We also do this for host crates, since those
130     // may be proc macros, in which case we might ship them.
131     if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) {
132         cmd.arg("-Z").arg("force-unstable-if-unmarked");
133     }
134
135     if verbose > 1 {
136         eprintln!(
137             "rustc command: {:?}={:?} {:?}",
138             bootstrap::util::dylib_path_var(),
139             env::join_paths(&dylib_path).unwrap(),
140             cmd,
141         );
142         eprintln!("sysroot: {:?}", sysroot);
143         eprintln!("libdir: {:?}", libdir);
144     }
145
146     if let Some(mut on_fail) = on_fail {
147         let e = match cmd.status() {
148             Ok(s) if s.success() => std::process::exit(0),
149             e => e,
150         };
151         println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
152         exec_cmd(&mut on_fail).expect("could not run the backup command");
153         std::process::exit(1);
154     }
155
156     if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
157         if let Some(crate_name) = crate_name {
158             let start = Instant::now();
159             let status = cmd.status().unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
160             let dur = start.elapsed();
161
162             let is_test = args.iter().any(|a| a == "--test");
163             eprintln!(
164                 "[RUSTC-TIMING] {} test:{} {}.{:03}",
165                 crate_name,
166                 is_test,
167                 dur.as_secs(),
168                 dur.subsec_millis()
169             );
170
171             match status.code() {
172                 Some(i) => std::process::exit(i),
173                 None => {
174                     eprintln!("rustc exited with {}", status);
175                     std::process::exit(0xfe);
176                 }
177             }
178         }
179     }
180
181     let code = exec_cmd(&mut cmd).unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
182     std::process::exit(code);
183 }
184
185 #[cfg(unix)]
186 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
187     use std::os::unix::process::CommandExt;
188     Err(cmd.exec())
189 }
190
191 #[cfg(not(unix))]
192 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
193     cmd.status().map(|status| status.code().unwrap())
194 }