]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/bin/rustc.rs
Rollup merge of #68232 - Mark-Simulacrum:unicode-tables, r=joshtriplett
[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(|of| Command::new(of));
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
105         // Set various options from config.toml to configure how we're building
106         // code.
107         let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
108             Ok(s) => {
109                 if s == "true" {
110                     "y"
111                 } else {
112                     "n"
113                 }
114             }
115             Err(..) => "n",
116         };
117
118         // The compiler builtins are pretty sensitive to symbols referenced in
119         // libcore and such, so we never compile them with debug assertions.
120         //
121         // FIXME(rust-lang/cargo#7253) we should be doing this in `builder.rs`
122         // with env vars instead of doing it here in this script.
123         if crate_name == Some("compiler_builtins") {
124             cmd.arg("-C").arg("debug-assertions=no");
125         } else {
126             cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
127         }
128     } else {
129         // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars
130         // here, but rather Cargo should know what flags to pass rustc itself.
131
132         // Override linker if necessary.
133         if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
134             cmd.arg(format!("-Clinker={}", host_linker));
135         }
136
137         if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") {
138             if s == "true" {
139                 cmd.arg("-C").arg("target-feature=+crt-static");
140             }
141             if s == "false" {
142                 cmd.arg("-C").arg("target-feature=-crt-static");
143             }
144         }
145     }
146
147     if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
148         cmd.arg("--remap-path-prefix").arg(&map);
149     }
150
151     // Force all crates compiled by this compiler to (a) be unstable and (b)
152     // allow the `rustc_private` feature to link to other unstable crates
153     // also in the sysroot. We also do this for host crates, since those
154     // may be proc macros, in which case we might ship them.
155     if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) {
156         cmd.arg("-Z").arg("force-unstable-if-unmarked");
157     }
158
159     if verbose > 1 {
160         eprintln!(
161             "rustc command: {:?}={:?} {:?}",
162             bootstrap::util::dylib_path_var(),
163             env::join_paths(&dylib_path).unwrap(),
164             cmd,
165         );
166         eprintln!("sysroot: {:?}", sysroot);
167         eprintln!("libdir: {:?}", libdir);
168     }
169
170     if let Some(mut on_fail) = on_fail {
171         let e = match cmd.status() {
172             Ok(s) if s.success() => std::process::exit(0),
173             e => e,
174         };
175         println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
176         exec_cmd(&mut on_fail).expect("could not run the backup command");
177         std::process::exit(1);
178     }
179
180     if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
181         if let Some(crate_name) = crate_name {
182             let start = Instant::now();
183             let status = cmd.status().unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
184             let dur = start.elapsed();
185
186             let is_test = args.iter().any(|a| a == "--test");
187             eprintln!(
188                 "[RUSTC-TIMING] {} test:{} {}.{:03}",
189                 crate_name,
190                 is_test,
191                 dur.as_secs(),
192                 dur.subsec_nanos() / 1_000_000
193             );
194
195             match status.code() {
196                 Some(i) => std::process::exit(i),
197                 None => {
198                     eprintln!("rustc exited with {}", status);
199                     std::process::exit(0xfe);
200                 }
201             }
202         }
203     }
204
205     let code = exec_cmd(&mut cmd).unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
206     std::process::exit(code);
207 }
208
209 #[cfg(unix)]
210 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
211     use std::os::unix::process::CommandExt;
212     Err(cmd.exec())
213 }
214
215 #[cfg(not(unix))]
216 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
217     cmd.status().map(|status| status.code().unwrap())
218 }