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