]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/bin/rustc.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[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 // NO-RUSTC-WRAPPER
19 #![deny(warnings, rust_2018_idioms, unused_lifetimes)]
20
21 use std::env;
22 use std::ffi::OsString;
23 use std::io;
24 use std::path::PathBuf;
25 use std::process::Command;
26 use std::str::FromStr;
27 use std::time::Instant;
28
29 fn main() {
30     let mut args = env::args_os().skip(1).collect::<Vec<_>>();
31
32     // Append metadata suffix for internal crates. See the corresponding entry
33     // in bootstrap/lib.rs for details.
34     if let Ok(s) = env::var("RUSTC_METADATA_SUFFIX") {
35         for i in 1..args.len() {
36             // Dirty code for borrowing issues
37             let mut new = None;
38             if let Some(current_as_str) = args[i].to_str() {
39                 if (&*args[i - 1] == "-C" && current_as_str.starts_with("metadata")) ||
40                    current_as_str.starts_with("-Cmetadata") {
41                     new = Some(format!("{}-{}", current_as_str, s));
42                 }
43             }
44             if let Some(new) = new { args[i] = new.into(); }
45         }
46     }
47
48     // Drop `--error-format json` because despite our desire for json messages
49     // from Cargo we don't want any from rustc itself.
50     if let Some(n) = args.iter().position(|n| n == "--error-format") {
51         args.remove(n);
52         args.remove(n);
53     }
54
55     if let Some(s) = env::var_os("RUSTC_ERROR_FORMAT") {
56         args.push("--error-format".into());
57         args.push(s);
58     }
59
60     // Detect whether or not we're a build script depending on whether --target
61     // is passed (a bit janky...)
62     let target = args.windows(2)
63         .find(|w| &*w[0] == "--target")
64         .and_then(|w| w[1].to_str());
65     let version = args.iter().find(|w| &**w == "-vV");
66
67     let verbose = match env::var("RUSTC_VERBOSE") {
68         Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
69         Err(_) => 0,
70     };
71
72     // Use a different compiler for build scripts, since there may not yet be a
73     // libstd for the real compiler to use. However, if Cargo is attempting to
74     // determine the version of the compiler, the real compiler needs to be
75     // used. Currently, these two states are differentiated based on whether
76     // --target and -vV is/isn't passed.
77     let (rustc, libdir) = if target.is_none() && version.is_none() {
78         ("RUSTC_SNAPSHOT", "RUSTC_SNAPSHOT_LIBDIR")
79     } else {
80         ("RUSTC_REAL", "RUSTC_LIBDIR")
81     };
82     let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set");
83     let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set");
84     let on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of));
85
86     let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc));
87     let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir));
88     let mut dylib_path = bootstrap::util::dylib_path();
89     dylib_path.insert(0, PathBuf::from(&libdir));
90
91     let mut cmd = Command::new(rustc);
92     cmd.args(&args)
93         .env(bootstrap::util::dylib_path_var(),
94              env::join_paths(&dylib_path).unwrap());
95
96     // Get the name of the crate we're compiling, if any.
97     let crate_name = args.windows(2)
98         .find(|args| args[0] == "--crate-name")
99         .and_then(|args| args[1].to_str());
100
101     if let Some(crate_name) = crate_name {
102         if let Some(target) = env::var_os("RUSTC_TIME") {
103             if target == "all" ||
104                target.into_string().unwrap().split(",").any(|c| c.trim() == crate_name)
105             {
106                 cmd.arg("-Ztime");
107             }
108         }
109     }
110
111     // Non-zero stages must all be treated uniformly to avoid problems when attempting to uplift
112     // compiler libraries and such from stage 1 to 2.
113     if stage == "0" {
114         cmd.arg("--cfg").arg("bootstrap");
115     }
116
117     // Print backtrace in case of ICE
118     if env::var("RUSTC_BACKTRACE_ON_ICE").is_ok() && env::var("RUST_BACKTRACE").is_err() {
119         cmd.env("RUST_BACKTRACE", "1");
120     }
121
122     cmd.env("RUSTC_BREAK_ON_ICE", "1");
123
124     if let Ok(debuginfo_level) = env::var("RUSTC_DEBUGINFO_LEVEL") {
125         cmd.arg(format!("-Cdebuginfo={}", debuginfo_level));
126     }
127
128     if env::var_os("RUSTC_DENY_WARNINGS").is_some() &&
129        env::var_os("RUSTC_EXTERNAL_TOOL").is_none() {
130         // When extending this list, search for `NO-RUSTC-WRAPPER` and add the new lints
131         // there as well, some code doesn't go through this `rustc` wrapper.
132         cmd.arg("-Dwarnings");
133         cmd.arg("-Drust_2018_idioms");
134         cmd.arg("-Dunused_lifetimes");
135         // cfg(not(bootstrap)): Remove this during the next stage 0 compiler update.
136         // `-Drustc::internal` is a new feature and `rustc_version` mis-reports the `stage`.
137         let cfg_not_bootstrap = stage != "0" && crate_name != Some("rustc_version");
138         if cfg_not_bootstrap && use_internal_lints(crate_name) {
139             cmd.arg("-Zunstable-options");
140             cmd.arg("-Drustc::internal");
141         }
142     }
143
144     if let Some(target) = target {
145         // The stage0 compiler has a special sysroot distinct from what we
146         // actually downloaded, so we just always pass the `--sysroot` option.
147         cmd.arg("--sysroot").arg(&sysroot);
148
149         cmd.arg("-Zexternal-macro-backtrace");
150
151         // Link crates to the proc macro crate for the target, but use a host proc macro crate
152         // to actually run the macros
153         if env::var_os("RUST_DUAL_PROC_MACROS").is_some() {
154             cmd.arg("-Zdual-proc-macros");
155         }
156
157         // When we build Rust dylibs they're all intended for intermediate
158         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
159         // linking all deps statically into the dylib.
160         if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
161             cmd.arg("-Cprefer-dynamic");
162         }
163
164         // Help the libc crate compile by assisting it in finding various
165         // sysroot native libraries.
166         if let Some(s) = env::var_os("MUSL_ROOT") {
167             if target.contains("musl") {
168                 let mut root = OsString::from("native=");
169                 root.push(&s);
170                 root.push("/lib");
171                 cmd.arg("-L").arg(&root);
172             }
173         }
174         if let Some(s) = env::var_os("WASI_ROOT") {
175             let mut root = OsString::from("native=");
176             root.push(&s);
177             root.push("/lib/wasm32-wasi");
178             cmd.arg("-L").arg(&root);
179         }
180
181         // Override linker if necessary.
182         if let Ok(target_linker) = env::var("RUSTC_TARGET_LINKER") {
183             cmd.arg(format!("-Clinker={}", target_linker));
184         }
185
186         // If we're compiling specifically the `panic_abort` crate then we pass
187         // the `-C panic=abort` option. Note that we do not do this for any
188         // other crate intentionally as this is the only crate for now that we
189         // ship with panic=abort.
190         //
191         // This... is a bit of a hack how we detect this. Ideally this
192         // information should be encoded in the crate I guess? Would likely
193         // require an RFC amendment to RFC 1513, however.
194         //
195         // `compiler_builtins` are unconditionally compiled with panic=abort to
196         // workaround undefined references to `rust_eh_unwind_resume` generated
197         // otherwise, see issue https://github.com/rust-lang/rust/issues/43095.
198         if crate_name == Some("panic_abort") ||
199            crate_name == Some("compiler_builtins") && stage != "0" {
200             cmd.arg("-C").arg("panic=abort");
201         }
202
203         // Set various options from config.toml to configure how we're building
204         // code.
205         let debug_assertions = match env::var("RUSTC_DEBUG_ASSERTIONS") {
206             Ok(s) => if s == "true" { "y" } else { "n" },
207             Err(..) => "n",
208         };
209
210         // The compiler builtins are pretty sensitive to symbols referenced in
211         // libcore and such, so we never compile them with debug assertions.
212         if crate_name == Some("compiler_builtins") {
213             cmd.arg("-C").arg("debug-assertions=no");
214         } else {
215             cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
216         }
217
218         if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
219             cmd.arg("-C").arg(format!("codegen-units={}", s));
220         }
221
222         // Emit save-analysis info.
223         if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
224             cmd.arg("-Zsave-analysis");
225             cmd.env("RUST_SAVE_ANALYSIS_CONFIG",
226                     "{\"output_file\": null,\"full_docs\": false,\
227                      \"pub_only\": true,\"reachable_only\": false,\
228                      \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
229         }
230
231         // Dealing with rpath here is a little special, so let's go into some
232         // detail. First off, `-rpath` is a linker option on Unix platforms
233         // which adds to the runtime dynamic loader path when looking for
234         // dynamic libraries. We use this by default on Unix platforms to ensure
235         // that our nightlies behave the same on Windows, that is they work out
236         // of the box. This can be disabled, of course, but basically that's why
237         // we're gated on RUSTC_RPATH here.
238         //
239         // Ok, so the astute might be wondering "why isn't `-C rpath` used
240         // here?" and that is indeed a good question to task. This codegen
241         // option is the compiler's current interface to generating an rpath.
242         // Unfortunately it doesn't quite suffice for us. The flag currently
243         // takes no value as an argument, so the compiler calculates what it
244         // should pass to the linker as `-rpath`. This unfortunately is based on
245         // the **compile time** directory structure which when building with
246         // Cargo will be very different than the runtime directory structure.
247         //
248         // All that's a really long winded way of saying that if we use
249         // `-Crpath` then the executables generated have the wrong rpath of
250         // something like `$ORIGIN/deps` when in fact the way we distribute
251         // rustc requires the rpath to be `$ORIGIN/../lib`.
252         //
253         // So, all in all, to set up the correct rpath we pass the linker
254         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
255         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
256         // to change a flag in a binary?
257         if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
258             let rpath = if target.contains("apple") {
259
260                 // Note that we need to take one extra step on macOS to also pass
261                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
262                 // do that we pass a weird flag to the compiler to get it to do
263                 // so. Note that this is definitely a hack, and we should likely
264                 // flesh out rpath support more fully in the future.
265                 cmd.arg("-Z").arg("osx-rpath-install-name");
266                 Some("-Wl,-rpath,@loader_path/../lib")
267             } else if !target.contains("windows") &&
268                       !target.contains("wasm32") &&
269                       !target.contains("fuchsia") {
270                 Some("-Wl,-rpath,$ORIGIN/../lib")
271             } else {
272                 None
273             };
274             if let Some(rpath) = rpath {
275                 cmd.arg("-C").arg(format!("link-args={}", rpath));
276             }
277         }
278
279         if let Ok(s) = env::var("RUSTC_CRT_STATIC") {
280             if s == "true" {
281                 cmd.arg("-C").arg("target-feature=+crt-static");
282             }
283             if s == "false" {
284                 cmd.arg("-C").arg("target-feature=-crt-static");
285             }
286         }
287
288         // When running miri tests, we need to generate MIR for all libraries
289         if env::var("TEST_MIRI").ok().map_or(false, |val| val == "true") {
290             // The flags here should be kept in sync with `add_miri_default_args`
291             // in miri's `src/lib.rs`.
292             cmd.arg("-Zalways-encode-mir");
293             cmd.arg("--cfg=miri");
294             // These options are preferred by miri, to be able to perform better validation,
295             // but the bootstrap compiler might not understand them.
296             if stage != "0" {
297                 cmd.arg("-Zmir-emit-retag");
298                 cmd.arg("-Zmir-opt-level=0");
299             }
300         }
301
302         if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
303             cmd.arg("--remap-path-prefix").arg(&map);
304         }
305     } else {
306         // Override linker if necessary.
307         if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
308             cmd.arg(format!("-Clinker={}", host_linker));
309         }
310
311         if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") {
312             if s == "true" {
313                 cmd.arg("-C").arg("target-feature=+crt-static");
314             }
315             if s == "false" {
316                 cmd.arg("-C").arg("target-feature=-crt-static");
317             }
318         }
319     }
320
321     // Force all crates compiled by this compiler to (a) be unstable and (b)
322     // allow the `rustc_private` feature to link to other unstable crates
323     // also in the sysroot. We also do this for host crates, since those
324     // may be proc macros, in which case we might ship them.
325     if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) {
326         cmd.arg("-Z").arg("force-unstable-if-unmarked");
327     }
328
329     if env::var_os("RUSTC_PARALLEL_COMPILER").is_some() {
330         cmd.arg("--cfg").arg("parallel_compiler");
331     }
332
333     if verbose > 1 {
334         eprintln!(
335             "rustc command: {:?}={:?} {:?}",
336             bootstrap::util::dylib_path_var(),
337             env::join_paths(&dylib_path).unwrap(),
338             cmd,
339         );
340         eprintln!("sysroot: {:?}", sysroot);
341         eprintln!("libdir: {:?}", libdir);
342     }
343
344     if let Some(mut on_fail) = on_fail {
345         let e = match cmd.status() {
346             Ok(s) if s.success() => std::process::exit(0),
347             e => e,
348         };
349         println!("\nDid not run successfully: {:?}\n{:?}\n-------------", e, cmd);
350         exec_cmd(&mut on_fail).expect("could not run the backup command");
351         std::process::exit(1);
352     }
353
354     if env::var_os("RUSTC_PRINT_STEP_TIMINGS").is_some() {
355         if let Some(crate_name) = crate_name {
356             let start = Instant::now();
357             let status = cmd
358                 .status()
359                 .unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
360             let dur = start.elapsed();
361
362             let is_test = args.iter().any(|a| a == "--test");
363             eprintln!("[RUSTC-TIMING] {} test:{} {}.{:03}",
364                       crate_name,
365                       is_test,
366                       dur.as_secs(),
367                       dur.subsec_nanos() / 1_000_000);
368
369             match status.code() {
370                 Some(i) => std::process::exit(i),
371                 None => {
372                     eprintln!("rustc exited with {}", status);
373                     std::process::exit(0xfe);
374                 }
375             }
376         }
377     }
378
379     let code = exec_cmd(&mut cmd).unwrap_or_else(|_| panic!("\n\n failed to run {:?}", cmd));
380     std::process::exit(code);
381 }
382
383 // Rustc crates for which internal lints are in effect.
384 fn use_internal_lints(crate_name: Option<&str>) -> bool {
385     crate_name.map_or(false, |crate_name| {
386         crate_name.starts_with("rustc") || crate_name.starts_with("syntax") ||
387         ["arena", "fmt_macros"].contains(&crate_name)
388     })
389 }
390
391 #[cfg(unix)]
392 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
393     use std::os::unix::process::CommandExt;
394     Err(cmd.exec())
395 }
396
397 #[cfg(not(unix))]
398 fn exec_cmd(cmd: &mut Command) -> io::Result<i32> {
399     cmd.status().map(|status| status.code().unwrap())
400 }