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