rust/src/bin/miri.rs
Ralf Jung eb153810e3 Use MIRI_ env vars to set RUST_ ones
This means we can do `MIRI_LOG=debug cargo run` and get something reasonable,
even if cargo has to build some dependencies first.
2018-10-31 10:09:55 +01:00

231 lines
7.4 KiB
Rust

#![feature(rustc_private)]
extern crate getopts;
extern crate miri;
extern crate rustc;
extern crate rustc_metadata;
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_codegen_utils;
extern crate env_logger;
extern crate log_settings;
extern crate syntax;
extern crate log;
use std::path::PathBuf;
use std::env;
use rustc::session::Session;
use rustc_metadata::cstore::CStore;
use rustc_driver::{Compilation, CompilerCalls, RustcDefaultCalls};
use rustc_driver::driver::{CompileState, CompileController};
use rustc::session::config::{self, Input, ErrorOutputType};
use rustc::hir::{self, itemlikevisit};
use rustc::ty::TyCtxt;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use syntax::ast;
struct MiriCompilerCalls {
default: Box<RustcDefaultCalls>,
/// Whether to enforce the validity invariant.
validate: bool,
}
impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
fn early_callback(
&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
cfg: &ast::CrateConfig,
descriptions: &rustc_errors::registry::Registry,
output: ErrorOutputType,
) -> Compilation {
self.default.early_callback(
matches,
sopts,
cfg,
descriptions,
output,
)
}
fn no_input(
&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
cfg: &ast::CrateConfig,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
descriptions: &rustc_errors::registry::Registry,
) -> Option<(Input, Option<PathBuf>)> {
self.default.no_input(
matches,
sopts,
cfg,
odir,
ofile,
descriptions,
)
}
fn late_callback(
&mut self,
codegen_backend: &CodegenBackend,
matches: &getopts::Matches,
sess: &Session,
cstore: &CStore,
input: &Input,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
) -> Compilation {
self.default.late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
}
fn build_controller(
self: Box<Self>,
sess: &Session,
matches: &getopts::Matches,
) -> CompileController<'a> {
let this = *self;
let mut control = this.default.build_controller(sess, matches);
control.after_hir_lowering.callback = Box::new(after_hir_lowering);
let validate = this.validate;
control.after_analysis.callback =
Box::new(move |state| after_analysis(state, validate));
control.after_analysis.stop = Compilation::Stop;
control
}
}
fn after_hir_lowering(state: &mut CompileState) {
let attr = (
String::from("miri"),
syntax::feature_gate::AttributeType::Whitelisted,
);
state.session.plugin_attributes.borrow_mut().push(attr);
}
fn after_analysis<'a, 'tcx>(
state: &mut CompileState<'a, 'tcx>,
validate: bool,
) {
state.session.abort_if_errors();
let tcx = state.tcx.unwrap();
if std::env::args().any(|arg| arg == "--test") {
struct Visitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
state: &'a CompileState<'a, 'tcx>,
validate: bool,
};
impl<'a, 'tcx: 'a, 'hir> itemlikevisit::ItemLikeVisitor<'hir> for Visitor<'a, 'tcx> {
fn visit_item(&mut self, i: &'hir hir::Item) {
if let hir::ItemKind::Fn(.., body_id) = i.node {
if i.attrs.iter().any(|attr| {
attr.name() == "test"
})
{
let did = self.tcx.hir.body_owner_def_id(body_id);
println!(
"running test: {}",
self.tcx.def_path_debug_str(did),
);
miri::eval_main(self.tcx, did, self.validate);
self.state.session.abort_if_errors();
}
}
}
fn visit_trait_item(&mut self, _trait_item: &'hir hir::TraitItem) {}
fn visit_impl_item(&mut self, _impl_item: &'hir hir::ImplItem) {}
}
state.hir_crate.unwrap().visit_all_item_likes(
&mut Visitor { tcx, state, validate }
);
} else if let Some((entry_node_id, _, _)) = *state.session.entry_fn.borrow() {
let entry_def_id = tcx.hir.local_def_id(entry_node_id);
miri::eval_main(tcx, entry_def_id, validate);
state.session.abort_if_errors();
} else {
println!("no main function found, assuming auxiliary build");
}
}
fn init_loggers() {
// Notice that our `extern crate log` is NOT the same as rustc's! So we have to initialize
// them both.
// First, miri.
let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
env_logger::init_from_env(env);
// Now, change the RUST_LOG env var to control rustc's logger.
// If MIRI_LOG is set and RUST_LOG is not, set RUST_LOG.
if let Ok(var) = env::var("MIRI_LOG") {
if env::var("RUST_LOG") == Err(env::VarError::NotPresent) {
// We try to be a bit clever here: If MIRI_LOG is just a single level
// used for everything, we only apply it to the parts of rustc that are
// CTFE-related. Only if MIRI_LOG contains `module=level`, we just
// use the same value for RUST_LOG.
// This way, if you set `MIRI_LOG=trace`, you get only the right parts of
// rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
if var.contains('=') {
env::set_var("RUST_LOG", &var);
} else {
env::set_var("RUST_LOG",
&format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var));
}
}
}
rustc_driver::init_rustc_env_logger();
}
fn find_sysroot() -> String {
if let Ok(sysroot) = std::env::var("MIRI_SYSROOT") {
return sysroot;
}
// Taken from https://github.com/Manishearth/rust-clippy/pull/911.
let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
match (home, toolchain) {
(Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
_ => {
option_env!("RUST_SYSROOT")
.expect(
"Could not find sysroot. Either set MIRI_SYSROOT at run-time, or at \
build-time specify RUST_SYSROOT env var or use rustup or multirust",
)
.to_owned()
}
}
}
fn main() {
init_loggers();
let mut args: Vec<String> = std::env::args().collect();
let sysroot_flag = String::from("--sysroot");
if !args.contains(&sysroot_flag) {
args.push(sysroot_flag);
args.push(find_sysroot());
}
let mut validate = true;
args.retain(|arg| {
match arg.as_str() {
"-Zmiri-disable-validation" => {
validate = false;
false
},
_ => true
}
});
let result = rustc_driver::run(move || {
rustc_driver::run_compiler(&args, Box::new(MiriCompilerCalls {
default: Box::new(RustcDefaultCalls),
validate,
}), None, None)
});
std::process::exit(result as i32);
}