1 #![feature(rustc_private)]
3 extern crate rustc_middle;
4 extern crate rustc_driver;
5 extern crate rustc_hir;
6 extern crate rustc_interface;
7 extern crate rustc_session;
8 extern crate rustc_errors;
10 use std::convert::TryFrom;
12 use std::str::FromStr;
14 use hex::FromHexError;
17 use rustc_session::{CtfeBacktrace, config::ErrorOutputType};
18 use rustc_errors::emitter::{HumanReadableErrorType, ColorConfig};
19 use rustc_driver::Compilation;
20 use rustc_hir::def_id::LOCAL_CRATE;
21 use rustc_middle::ty::TyCtxt;
23 struct MiriCompilerCalls {
24 miri_config: miri::MiriConfig,
27 impl rustc_driver::Callbacks for MiriCompilerCalls {
28 fn after_analysis<'tcx>(
30 compiler: &rustc_interface::interface::Compiler,
31 queries: &'tcx rustc_interface::Queries<'tcx>,
33 compiler.session().abort_if_errors();
35 queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
36 init_late_loggers(tcx);
37 let (entry_def_id, _) = if let Some((entry_def, x)) = tcx.entry_fn(LOCAL_CRATE) {
40 let output_ty = ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto));
41 rustc_session::early_error(output_ty, "miri can only run programs that have a main function");
43 let mut config = self.miri_config.clone();
45 // Add filename to `miri` arguments.
46 config.args.insert(0, compiler.input().filestem().to_string());
48 // Adjust working directory for interpretation.
49 if let Some(cwd) = env::var_os("MIRI_CWD") {
50 env::set_current_dir(cwd).unwrap();
53 if let Some(return_code) = miri::eval_main(tcx, entry_def_id.to_def_id(), config) {
55 i32::try_from(return_code).expect("Return value was too large!"),
60 compiler.session().abort_if_errors();
66 fn init_early_loggers() {
67 // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
68 // initialize them both, and we always initialize `miri`'s first.
69 let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
70 env_logger::init_from_env(env);
71 // We only initialize `rustc` if the env var is set (so the user asked for it).
72 // If it is not set, we avoid initializing now so that we can initialize
73 // later with our custom settings, and *not* log anything for what happens before
74 // `miri` gets started.
75 if env::var_os("RUSTC_LOG").is_some() {
76 rustc_driver::init_rustc_env_logger();
80 fn init_late_loggers(tcx: TyCtxt<'_>) {
81 // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
82 // env var if it is not set, control it based on `MIRI_LOG`.
83 // (FIXME: use `var_os`, but then we need to manually concatenate instead of `format!`.)
84 if let Ok(var) = env::var("MIRI_LOG") {
85 if env::var_os("RUSTC_LOG").is_none() {
86 // We try to be a bit clever here: if `MIRI_LOG` is just a single level
87 // used for everything, we only apply it to the parts of rustc that are
88 // CTFE-related. Otherwise, we use it verbatim for `RUSTC_LOG`.
89 // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
90 // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
91 if log::Level::from_str(&var).is_ok() {
94 &format!("rustc_middle::mir::interpret={0},rustc_mir::interpret={0}", var),
97 env::set_var("RUSTC_LOG", &var);
99 rustc_driver::init_rustc_env_logger();
103 // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.
104 // Do this late, so we ideally only apply this to Miri's errors.
105 if let Some(val) = env::var_os("MIRI_BACKTRACE") {
106 let ctfe_backtrace = match &*val.to_string_lossy() {
107 "immediate" => CtfeBacktrace::Immediate,
108 "0" => CtfeBacktrace::Disabled,
109 _ => CtfeBacktrace::Capture,
111 *tcx.sess.ctfe_backtrace.borrow_mut() = ctfe_backtrace;
115 /// Returns the "default sysroot" that Miri will use if no `--sysroot` flag is set.
116 /// Should be a compile-time constant.
117 fn compile_time_sysroot() -> Option<String> {
118 if option_env!("RUSTC_STAGE").is_some() {
119 // This is being built as part of rustc, and gets shipped with rustup.
120 // We can rely on the sysroot computation in librustc_session.
123 // For builds outside rustc, we need to ensure that we got a sysroot
124 // that gets used as a default. The sysroot computation in librustc_session would
125 // end up somewhere in the build dir (see `get_or_default_sysroot`).
126 // Taken from PR <https://github.com/Manishearth/rust-clippy/pull/911>.
127 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
128 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
129 Some(match (home, toolchain) {
130 (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
131 _ => option_env!("RUST_SYSROOT")
132 .expect("To build Miri without rustup, set the `RUST_SYSROOT` env var at build time")
137 /// Execute a compiler with the given CLI arguments and callbacks.
138 fn run_compiler(mut args: Vec<String>, callbacks: &mut (dyn rustc_driver::Callbacks + Send)) -> ! {
139 // Make sure we use the right default sysroot. The default sysroot is wrong,
140 // because `get_or_default_sysroot` in `librustc_session` bases that on `current_exe`.
142 // Make sure we always call `compile_time_sysroot` as that also does some sanity-checks
143 // of the environment we were built in.
144 // FIXME: Ideally we'd turn a bad build env into a compile-time error via CTFE or so.
145 if let Some(sysroot) = compile_time_sysroot() {
146 let sysroot_flag = "--sysroot";
147 if !args.iter().any(|e| e == sysroot_flag) {
148 // We need to overwrite the default that librustc_session would compute.
149 args.push(sysroot_flag.to_owned());
154 // Some options have different defaults in Miri than in plain rustc; apply those by making
155 // them the first arguments after the binary name (but later arguments can overwrite them).
156 args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
158 // Invoke compiler, and handle return code.
159 let exit_code = rustc_driver::catch_with_exit_code(move || {
160 rustc_driver::RunCompiler::new(&args, callbacks).run()
162 std::process::exit(exit_code)
166 rustc_driver::install_ice_hook();
168 // If the environment asks us to actually be rustc, then do that.
169 if env::var_os("MIRI_BE_RUSTC").is_some() {
170 rustc_driver::init_rustc_env_logger();
171 // We cannot use `rustc_driver::main` as we need to adjust the CLI arguments.
172 let mut callbacks = rustc_driver::TimePassesCallbacks::default();
173 run_compiler(env::args().collect(), &mut callbacks)
176 // Init loggers the Miri way.
177 init_early_loggers();
179 // Parse our arguments and split them across `rustc` and `miri`.
180 let mut miri_config = miri::MiriConfig::default();
181 let mut rustc_args = vec![];
182 let mut after_dashdash = false;
183 for arg in env::args() {
184 if rustc_args.is_empty() {
185 // Very first arg: binary name.
186 rustc_args.push(arg);
187 } else if after_dashdash {
188 // Everything that comes after `--` is forwarded to the interpreted crate.
189 miri_config.args.push(arg);
192 "-Zmiri-disable-validation" => {
193 miri_config.validate = false;
195 "-Zmiri-disable-stacked-borrows" => {
196 miri_config.stacked_borrows = false;
198 "-Zmiri-disable-alignment-check" => {
199 miri_config.check_alignment = miri::AlignmentCheck::None;
201 "-Zmiri-symbolic-alignment-check" => {
202 miri_config.check_alignment = miri::AlignmentCheck::Symbolic;
204 "-Zmiri-disable-isolation" => {
205 miri_config.communicate = true;
207 "-Zmiri-ignore-leaks" => {
208 miri_config.ignore_leaks = true;
211 after_dashdash = true;
213 arg if arg.starts_with("-Zmiri-seed=") => {
214 if miri_config.seed.is_some() {
215 panic!("Cannot specify -Zmiri-seed multiple times!");
217 let seed_raw = hex::decode(arg.strip_prefix("-Zmiri-seed=").unwrap())
218 .unwrap_or_else(|err| match err {
219 FromHexError::InvalidHexCharacter { .. } => panic!(
220 "-Zmiri-seed should only contain valid hex digits [0-9a-fA-F]"
222 FromHexError::OddLength =>
223 panic!("-Zmiri-seed should have an even number of digits"),
224 err => panic!("unknown error decoding -Zmiri-seed as hex: {:?}", err),
226 if seed_raw.len() > 8 {
228 "-Zmiri-seed must be at most 8 bytes, was {}",
233 let mut bytes = [0; 8];
234 bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
235 miri_config.seed = Some(u64::from_be_bytes(bytes));
237 arg if arg.starts_with("-Zmiri-env-exclude=") => {
238 miri_config.excluded_env_vars
239 .push(arg.strip_prefix("-Zmiri-env-exclude=").unwrap().to_owned());
241 arg if arg.starts_with("-Zmiri-track-pointer-tag=") => {
242 let id: u64 = match arg.strip_prefix("-Zmiri-track-pointer-tag=").unwrap().parse() {
245 "-Zmiri-track-pointer-tag requires a valid `u64` argument: {}",
249 if let Some(id) = miri::PtrId::new(id) {
250 miri_config.tracked_pointer_tag = Some(id);
252 panic!("-Zmiri-track-pointer-tag requires a nonzero argument");
255 arg if arg.starts_with("-Zmiri-track-call-id=") => {
256 let id: u64 = match arg.strip_prefix("-Zmiri-track-call-id=").unwrap().parse() {
259 "-Zmiri-track-call-id requires a valid `u64` argument: {}",
263 if let Some(id) = miri::CallId::new(id) {
264 miri_config.tracked_call_id = Some(id);
266 panic!("-Zmiri-track-call-id requires a nonzero argument");
269 arg if arg.starts_with("-Zmiri-track-alloc-id=") => {
270 let id: u64 = match arg.strip_prefix("-Zmiri-track-alloc-id=").unwrap().parse() {
273 "-Zmiri-track-alloc-id requires a valid `u64` argument: {}",
277 miri_config.tracked_alloc_id = Some(miri::AllocId(id));
281 rustc_args.push(arg);
287 debug!("rustc arguments: {:?}", rustc_args);
288 debug!("crate arguments: {:?}", miri_config.args);
289 run_compiler(rustc_args, &mut MiriCompilerCalls { miri_config })