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