]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/bin/rustc.rs
Auto merge of #42394 - ollie27:rustdoc_deref_box, r=QuietMisdreavus
[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::io::prelude::*;
36 use std::str::FromStr;
37 use std::path::PathBuf;
38 use std::process::{Command, ExitStatus};
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     // Detect whether or not we're a build script depending on whether --target
67     // is passed (a bit janky...)
68     let target = args.windows(2)
69         .find(|w| &*w[0] == "--target")
70         .and_then(|w| w[1].to_str());
71     let version = args.iter().find(|w| &**w == "-vV");
72
73     let verbose = match env::var("RUSTC_VERBOSE") {
74         Ok(s) => usize::from_str(&s).expect("RUSTC_VERBOSE should be an integer"),
75         Err(_) => 0,
76     };
77
78     // Build scripts always use the snapshot compiler which is guaranteed to be
79     // able to produce an executable, whereas intermediate compilers may not
80     // have the standard library built yet and may not be able to produce an
81     // executable. Otherwise we just use the standard compiler we're
82     // bootstrapping with.
83     //
84     // Also note that cargo will detect the version of the compiler to trigger
85     // a rebuild when the compiler changes. If this happens, we want to make
86     // sure to use the actual compiler instead of the snapshot compiler becase
87     // that's the one that's actually changing.
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 mut 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
109     if let Some(target) = target {
110         // The stage0 compiler has a special sysroot distinct from what we
111         // actually downloaded, so we just always pass the `--sysroot` option.
112         cmd.arg("--sysroot").arg(sysroot);
113
114         // When we build Rust dylibs they're all intended for intermediate
115         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
116         // linking all deps statically into the dylib.
117         if env::var_os("RUSTC_NO_PREFER_DYNAMIC").is_none() {
118             cmd.arg("-Cprefer-dynamic");
119         }
120
121         // Pass the `rustbuild` feature flag to crates which rustbuild is
122         // building. See the comment in bootstrap/lib.rs where this env var is
123         // set for more details.
124         if env::var_os("RUSTBUILD_UNSTABLE").is_some() {
125             cmd.arg("--cfg").arg("rustbuild");
126         }
127
128         // Help the libc crate compile by assisting it in finding the MUSL
129         // native libraries.
130         if let Some(s) = env::var_os("MUSL_ROOT") {
131             let mut root = OsString::from("native=");
132             root.push(&s);
133             root.push("/lib");
134             cmd.arg("-L").arg(&root);
135         }
136
137         // Pass down extra flags, commonly used to configure `-Clinker` when
138         // cross compiling.
139         if let Ok(s) = env::var("RUSTC_FLAGS") {
140             cmd.args(&s.split(" ").filter(|s| !s.is_empty()).collect::<Vec<_>>());
141         }
142
143         // Pass down incremental directory, if any.
144         if let Ok(dir) = env::var("RUSTC_INCREMENTAL") {
145             cmd.arg(format!("-Zincremental={}", dir));
146
147             if verbose > 0 {
148                 cmd.arg("-Zincremental-info");
149             }
150         }
151
152         // If we're compiling specifically the `panic_abort` crate then we pass
153         // the `-C panic=abort` option. Note that we do not do this for any
154         // other crate intentionally as this is the only crate for now that we
155         // ship with panic=abort.
156         //
157         // This... is a bit of a hack how we detect this. Ideally this
158         // information should be encoded in the crate I guess? Would likely
159         // require an RFC amendment to RFC 1513, however.
160         let is_panic_abort = args.windows(2)
161             .any(|a| &*a[0] == "--crate-name" && &*a[1] == "panic_abort");
162         if is_panic_abort {
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         cmd.arg("-C").arg(format!("debug-assertions={}", debug_assertions));
178         if let Ok(s) = env::var("RUSTC_CODEGEN_UNITS") {
179             cmd.arg("-C").arg(format!("codegen-units={}", s));
180         }
181
182         // Emit save-analysis info.
183         if env::var("RUSTC_SAVE_ANALYSIS") == Ok("api".to_string()) {
184             cmd.arg("-Zsave-analysis-api");
185         }
186
187         // Dealing with rpath here is a little special, so let's go into some
188         // detail. First off, `-rpath` is a linker option on Unix platforms
189         // which adds to the runtime dynamic loader path when looking for
190         // dynamic libraries. We use this by default on Unix platforms to ensure
191         // that our nightlies behave the same on Windows, that is they work out
192         // of the box. This can be disabled, of course, but basically that's why
193         // we're gated on RUSTC_RPATH here.
194         //
195         // Ok, so the astute might be wondering "why isn't `-C rpath` used
196         // here?" and that is indeed a good question to task. This codegen
197         // option is the compiler's current interface to generating an rpath.
198         // Unfortunately it doesn't quite suffice for us. The flag currently
199         // takes no value as an argument, so the compiler calculates what it
200         // should pass to the linker as `-rpath`. This unfortunately is based on
201         // the **compile time** directory structure which when building with
202         // Cargo will be very different than the runtime directory structure.
203         //
204         // All that's a really long winded way of saying that if we use
205         // `-Crpath` then the executables generated have the wrong rpath of
206         // something like `$ORIGIN/deps` when in fact the way we distribute
207         // rustc requires the rpath to be `$ORIGIN/../lib`.
208         //
209         // So, all in all, to set up the correct rpath we pass the linker
210         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
211         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
212         // to change a flag in a binary?
213         if env::var("RUSTC_RPATH") == Ok("true".to_string()) {
214             let rpath = if target.contains("apple") {
215
216                 // Note that we need to take one extra step on macOS to also pass
217                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
218                 // do that we pass a weird flag to the compiler to get it to do
219                 // so. Note that this is definitely a hack, and we should likely
220                 // flesh out rpath support more fully in the future.
221                 //
222                 // FIXME: remove condition after next stage0
223                 if stage != "0" {
224                     cmd.arg("-Z").arg("osx-rpath-install-name");
225                 }
226                 Some("-Wl,-rpath,@loader_path/../lib")
227             } else if !target.contains("windows") {
228                 Some("-Wl,-rpath,$ORIGIN/../lib")
229             } else {
230                 None
231             };
232             if let Some(rpath) = rpath {
233                 cmd.arg("-C").arg(format!("link-args={}", rpath));
234             }
235         }
236
237         if target.contains("pc-windows-msvc") {
238             cmd.arg("-Z").arg("unstable-options");
239             cmd.arg("-C").arg("target-feature=+crt-static");
240         }
241
242         // Force all crates compiled by this compiler to (a) be unstable and (b)
243         // allow the `rustc_private` feature to link to other unstable crates
244         // also in the sysroot.
245         //
246         // FIXME: remove condition after next stage0
247         if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() {
248             if stage != "0" {
249                 cmd.arg("-Z").arg("force-unstable-if-unmarked");
250             }
251         }
252     }
253
254     if verbose > 1 {
255         writeln!(&mut io::stderr(), "rustc command: {:?}", cmd).unwrap();
256     }
257
258     // Actually run the compiler!
259     std::process::exit(if let Some(ref mut on_fail) = on_fail {
260         match cmd.status() {
261             Ok(s) if s.success() => 0,
262             _ => {
263                 println!("\nDid not run successfully:\n{:?}\n-------------", cmd);
264                 exec_cmd(on_fail).expect("could not run the backup command");
265                 1
266             }
267         }
268     } else {
269         std::process::exit(match exec_cmd(&mut cmd) {
270             Ok(s) => s.code().unwrap_or(0xfe),
271             Err(e) => panic!("\n\nfailed to run {:?}: {}\n\n", cmd, e),
272         })
273     })
274 }
275
276 #[cfg(unix)]
277 fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> {
278     use std::os::unix::process::CommandExt;
279     Err(cmd.exec())
280 }
281
282 #[cfg(not(unix))]
283 fn exec_cmd(cmd: &mut Command) -> ::std::io::Result<ExitStatus> {
284     cmd.status()
285 }