]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/bin/rustc.rs
Rollup merge of #88706 - ThePuzzlemaker:issue-88609, r=jackh726
[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::path::PathBuf;
20 use std::process::{Child, Command};
21 use std::str::FromStr;
22 use std::time::Instant;
23
24 fn main() {
25     let args = env::args_os().skip(1).collect::<Vec<_>>();
26
27     // Detect whether or not we're a build script depending on whether --target
28     // is passed (a bit janky...)
29     let target = args.windows(2).find(|w| &*w[0] == "--target").and_then(|w| w[1].to_str());
30     let version = args.iter().find(|w| &**w == "-vV");
31
32     let verbose = match env::var("RUSTC_VERBOSE") {
33         Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
34         Err(_) => 0,
35     };
36
37     // Use a different compiler for build scripts, since there may not yet be a
38     // libstd for the real compiler to use. However, if Cargo is attempting to
39     // determine the version of the compiler, the real compiler needs to be
40     // used. Currently, these two states are differentiated based on whether
41     // --target and -vV is/isn't passed.
42     let (rustc, libdir) = if target.is_none() && version.is_none() {
43         ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
44     } else {
45         ("RUSTC_REAL", "RUSTC_LIBDIR")
46     };
47     let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
48     let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
49     let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new);
50
51     let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
52     let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
53     let mut dylib_path = bootstrap::util::dylib_path();
54     dylib_path.insert(0, PathBuf::from(&libdir));
55
56     let mut cmd = Command::new(rustc);
57     cmd.args(&args).env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
58
59     // Get the name of the crate we're compiling, if any.
60     let crate_name =
61         args.windows(2).find(|args| args[0] == "--crate-name").and_then(|args| args[1].to_str());
62
63     if let Some(crate_name) = crate_name {
64         if let Some(target) = env::var_os("RUSTC_TIME") {
65             if target == "all"
66                 || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name)
67             {
68                 cmd.arg("-Ztime");
69             }
70         }
71     }
72
73     // Print backtrace in case of ICE
74     if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() {
75         cmd.env("RUST_BACKTRACE", "1");
76     }
77
78     if let Ok(lint_flags) = env::var("RUSTC_LINT_FLAGS") {
79         cmd.args(lint_flags.split_whitespace());
80     }
81
82     if target.is_some() {
83         // The stage0 compiler has a special sysroot distinct from what we
84         // actually downloaded, so we just always pass the `--sysroot` option,
85         // unless one is already set.
86         if !args.iter().any(|arg| arg == "--sysroot") {
87             cmd.arg("--sysroot").arg(&sysroot);
88         }
89
90         // If we're compiling specifically the `panic_abort` crate then we pass
91         // the `-C panic=abort` option. Note that we do not do this for any
92         // other crate intentionally as this is the only crate for now that we
93         // ship with panic=abort.
94         //
95         // This... is a bit of a hack how we detect this. Ideally this
96         // information should be encoded in the crate I guess? Would likely
97         // require an RFC amendment to RFC 1513, however.
98         //
99         // `compiler_builtins` are unconditionally compiled with panic=abort to
100         // workaround undefined references to `rust_eh_unwind_resume` generated
101         // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
102         if crate_name == Some("panic_abort")
103             || crate_name == Some("compiler_builtins") && stage != "0"
104         {
105             cmd.arg("-C").arg("panic=abort");
106         }
107     } else {
108         // FIXME(rust-lang/cargo#5754) we shouldn't be using special env vars
109         // here, but rather Cargo should know what flags to pass rustc itself.
110
111         // Override linker if necessary.
112         if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
113             cmd.arg(format!("-Clinker={}", host_linker));
114         }
115         if env::var_os("RUSTC_HOST_FUSE_LD_LLD").is_some() {
116             cmd.arg("-Clink-args=-fuse-ld=lld");
117         }
118
119         if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") {
120             if s == "true" {
121                 cmd.arg("-C").arg("target-feature=+crt-static");
122             }
123             if s == "false" {
124                 cmd.arg("-C").arg("target-feature=-crt-static");
125             }
126         }
127
128         if stage == "0" {
129             // Cargo doesn't pass RUSTFLAGS to proc_macros:
130             // https://github.com/rust-lang/cargo/issues/4423
131             // Set `--cfg=bootstrap` explicitly instead.
132             cmd.arg("--cfg=bootstrap");
133         }
134     }
135
136     if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
137         cmd.arg("--remap-path-prefix").arg(&map);
138     }
139
140     // Force all crates compiled by this compiler to (a) be unstable and (b)
141     // allow the `rustc_private` feature to link to other unstable crates
142     // also in the sysroot. We also do this for host crates, since those
143     // may be proc macros, in which case we might ship them.
144     if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) {
145         cmd.arg("-Z").arg("force-unstable-if-unmarked");
146     }
147
148     let is_test = args.iter().any(|a| a == "--test");
149     if verbose > 1 {
150         let rust_env_vars =
151             env::vars().filter(|(k, _)| k.starts_with("RUST") || k.starts_with("CARGO"));
152         let prefix = if is_test { "[RUSTC-SHIM] rustc --test" } else { "[RUSTC-SHIM] rustc" };
153         let prefix = match crate_name {
154             Some(crate_name) => format!("{} {}", prefix, crate_name),
155             None => prefix.to_string(),
156         };
157         for (i, (k, v)) in rust_env_vars.enumerate() {
158             eprintln!("{} env[{}]: {:?}={:?}", prefix, i, k, v);
159         }
160         eprintln!("{} working directory: {}", prefix, env::current_dir().unwrap().display());
161         eprintln!(
162             "{} command: {:?}={:?} {:?}",
163             prefix,
164             bootstrap::util::dylib_path_var(),
165             env::join_paths(&dylib_path).unwrap(),
166             cmd,
167         );
168         eprintln!("{} sysroot: {:?}", prefix, sysroot);
169         eprintln!("{} libdir: {:?}", prefix, libdir);
170     }
171
172     let start = Instant::now();
173     let (child, status) = {
174         let errmsg = format!("\nFailed to run:\n{:?}\n-------------", cmd);
175         let mut child = cmd.spawn().expect(&errmsg);
176         let status = child.wait().expect(&errmsg);
177         (child, status)
178     };
179
180     if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some()
181         || env::var_os("RUSTC_PRINT_STEP_RUSAGE").is_some()
182     {
183         if let Some(crate_name) = crate_name {
184             let dur = start.elapsed();
185             // If the user requested resource usage data, then
186             // include that in addition to the timing output.
187             let rusage_data =
188                 env::var_os("RUSTC_PRINT_STEP_RUSAGE").and_then(|_| format_rusage_data(child));
189             eprintln!(
190                 "[RUSTC-TIMING] {} test:{} {}.{:03}{}{}",
191                 crate_name,
192                 is_test,
193                 dur.as_secs(),
194                 dur.subsec_millis(),
195                 if rusage_data.is_some() { " " } else { "" },
196                 rusage_data.unwrap_or(String::new()),
197             );
198         }
199     }
200
201     if status.success() {
202         std::process::exit(0);
203         // note: everything below here is unreachable. do not put code that
204         // should run on success, after this block.
205     }
206     if verbose > 0 {
207         println!("\nDid not run successfully: {}\n{:?}\n-------------", status, cmd);
208     }
209
210     if let Some(mut on_fail) = on_fail {
211         on_fail.status().expect("Could not run the on_fail command");
212     }
213
214     // Preserve the exit code. In case of signal, exit with 0xfe since it's
215     // awkward to preserve this status in a cross-platform way.
216     match status.code() {
217         Some(i) => std::process::exit(i),
218         None => {
219             eprintln!("rustc exited with {}", status);
220             std::process::exit(0xfe);
221         }
222     }
223 }
224
225 #[cfg(all(not(unix), not(windows)))]
226 // In the future we can add this for more platforms
227 fn format_rusage_data(_child: Child) -> Option<String> {
228     None
229 }
230
231 #[cfg(windows)]
232 fn format_rusage_data(child: Child) -> Option<String> {
233     use std::os::windows::io::AsRawHandle;
234     use winapi::um::{processthreadsapi, psapi, timezoneapi};
235     let handle = child.as_raw_handle();
236     macro_rules! try_bool {
237         ($e:expr) => {
238             if $e != 1 {
239                 return None;
240             }
241         };
242     }
243
244     let mut user_filetime = Default::default();
245     let mut user_time = Default::default();
246     let mut kernel_filetime = Default::default();
247     let mut kernel_time = Default::default();
248     let mut memory_counters = psapi::PROCESS_MEMORY_COUNTERS::default();
249
250     unsafe {
251         try_bool!(processthreadsapi::GetProcessTimes(
252             handle,
253             &mut Default::default(),
254             &mut Default::default(),
255             &mut kernel_filetime,
256             &mut user_filetime,
257         ));
258         try_bool!(timezoneapi::FileTimeToSystemTime(&user_filetime, &mut user_time));
259         try_bool!(timezoneapi::FileTimeToSystemTime(&kernel_filetime, &mut kernel_time));
260
261         // Unlike on Linux with RUSAGE_CHILDREN, this will only return memory information for the process
262         // with the given handle and none of that process's children.
263         try_bool!(psapi::GetProcessMemoryInfo(
264             handle as _,
265             &mut memory_counters as *mut _ as _,
266             std::mem::size_of::<psapi::PROCESS_MEMORY_COUNTERS_EX>() as u32,
267         ));
268     }
269
270     // Guide on interpreting these numbers:
271     // https://docs.microsoft.com/en-us/windows/win32/psapi/process-memory-usage-information
272     let peak_working_set = memory_counters.PeakWorkingSetSize / 1024;
273     let peak_page_file = memory_counters.PeakPagefileUsage / 1024;
274     let peak_paged_pool = memory_counters.QuotaPeakPagedPoolUsage / 1024;
275     let peak_nonpaged_pool = memory_counters.QuotaPeakNonPagedPoolUsage / 1024;
276     Some(format!(
277         "user: {USER_SEC}.{USER_USEC:03} \
278          sys: {SYS_SEC}.{SYS_USEC:03} \
279          peak working set (kb): {PEAK_WORKING_SET} \
280          peak page file usage (kb): {PEAK_PAGE_FILE} \
281          peak paged pool usage (kb): {PEAK_PAGED_POOL} \
282          peak non-paged pool usage (kb): {PEAK_NONPAGED_POOL} \
283          page faults: {PAGE_FAULTS}",
284         USER_SEC = user_time.wSecond + (user_time.wMinute * 60),
285         USER_USEC = user_time.wMilliseconds,
286         SYS_SEC = kernel_time.wSecond + (kernel_time.wMinute * 60),
287         SYS_USEC = kernel_time.wMilliseconds,
288         PEAK_WORKING_SET = peak_working_set,
289         PEAK_PAGE_FILE = peak_page_file,
290         PEAK_PAGED_POOL = peak_paged_pool,
291         PEAK_NONPAGED_POOL = peak_nonpaged_pool,
292         PAGE_FAULTS = memory_counters.PageFaultCount,
293     ))
294 }
295
296 #[cfg(unix)]
297 /// Tries to build a string with human readable data for several of the rusage
298 /// fields. Note that we are focusing mainly on data that we believe to be
299 /// supplied on Linux (the `rusage` struct has other fields in it but they are
300 /// currently unsupported by Linux).
301 fn format_rusage_data(_child: Child) -> Option<String> {
302     let rusage: libc::rusage = unsafe {
303         let mut recv = std::mem::zeroed();
304         // -1 is RUSAGE_CHILDREN, which means to get the rusage for all children
305         // (and grandchildren, etc) processes that have respectively terminated
306         // and been waited for.
307         let retval = libc::getrusage(-1, &mut recv);
308         if retval != 0 {
309             return None;
310         }
311         recv
312     };
313     // Mac OS X reports the maxrss in bytes, not kb.
314     let divisor = if env::consts::OS == "macos" { 1024 } else { 1 };
315     let maxrss = (rusage.ru_maxrss + (divisor - 1)) / divisor;
316
317     let mut init_str = format!(
318         "user: {USER_SEC}.{USER_USEC:03} \
319          sys: {SYS_SEC}.{SYS_USEC:03} \
320          max rss (kb): {MAXRSS}",
321         USER_SEC = rusage.ru_utime.tv_sec,
322         USER_USEC = rusage.ru_utime.tv_usec,
323         SYS_SEC = rusage.ru_stime.tv_sec,
324         SYS_USEC = rusage.ru_stime.tv_usec,
325         MAXRSS = maxrss
326     );
327
328     // The remaining rusage stats vary in platform support. So we treat
329     // uniformly zero values in each category as "not worth printing", since it
330     // either means no events of that type occurred, or that the platform
331     // does not support it.
332
333     let minflt = rusage.ru_minflt;
334     let majflt = rusage.ru_majflt;
335     if minflt != 0 || majflt != 0 {
336         init_str.push_str(&format!(" page reclaims: {} page faults: {}", minflt, majflt));
337     }
338
339     let inblock = rusage.ru_inblock;
340     let oublock = rusage.ru_oublock;
341     if inblock != 0 || oublock != 0 {
342         init_str.push_str(&format!(" fs block inputs: {} fs block outputs: {}", inblock, oublock));
343     }
344
345     let nvcsw = rusage.ru_nvcsw;
346     let nivcsw = rusage.ru_nivcsw;
347     if nvcsw != 0 || nivcsw != 0 {
348         init_str.push_str(&format!(
349             " voluntary ctxt switches: {} involuntary ctxt switches: {}",
350             nvcsw, nivcsw
351         ));
352     }
353
354     return Some(init_str);
355 }