1 #![feature(rustc_private)]
6 extern crate rustc_metadata;
7 extern crate rustc_driver;
8 extern crate rustc_errors;
9 extern crate rustc_codegen_utils;
10 extern crate env_logger;
11 extern crate log_settings;
17 use std::path::PathBuf;
18 use std::str::FromStr;
21 use rustc::session::Session;
22 use rustc_metadata::cstore::CStore;
23 use rustc_driver::{Compilation, CompilerCalls, RustcDefaultCalls};
24 use rustc_driver::driver::{CompileState, CompileController};
25 use rustc::session::config::{self, Input, ErrorOutputType};
26 use rustc::hir::{self, itemlikevisit};
27 use rustc::ty::TyCtxt;
28 use rustc_codegen_utils::codegen_backend::CodegenBackend;
31 struct MiriCompilerCalls {
32 default: Box<RustcDefaultCalls>,
34 /// Whether to enforce the validity invariant.
38 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
41 matches: &getopts::Matches,
42 sopts: &config::Options,
43 cfg: &ast::CrateConfig,
44 descriptions: &rustc_errors::registry::Registry,
45 output: ErrorOutputType,
47 self.default.early_callback(
57 matches: &getopts::Matches,
58 sopts: &config::Options,
59 cfg: &ast::CrateConfig,
60 odir: &Option<PathBuf>,
61 ofile: &Option<PathBuf>,
62 descriptions: &rustc_errors::registry::Registry,
63 ) -> Option<(Input, Option<PathBuf>)> {
64 self.default.no_input(
75 codegen_backend: &CodegenBackend,
76 matches: &getopts::Matches,
80 odir: &Option<PathBuf>,
81 ofile: &Option<PathBuf>,
83 self.default.late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
88 matches: &getopts::Matches,
89 ) -> CompileController<'a> {
91 let mut control = this.default.build_controller(sess, matches);
92 control.after_hir_lowering.callback = Box::new(after_hir_lowering);
93 let validate = this.validate;
94 control.after_analysis.callback =
95 Box::new(move |state| after_analysis(state, validate));
96 control.after_analysis.stop = Compilation::Stop;
101 fn after_hir_lowering(state: &mut CompileState) {
103 String::from("miri"),
104 syntax::feature_gate::AttributeType::Whitelisted,
106 state.session.plugin_attributes.borrow_mut().push(attr);
109 fn after_analysis<'a, 'tcx>(
110 state: &mut CompileState<'a, 'tcx>,
114 state.session.abort_if_errors();
116 let tcx = state.tcx.unwrap();
118 if std::env::args().any(|arg| arg == "--test") {
119 struct Visitor<'a, 'tcx: 'a> {
120 tcx: TyCtxt<'a, 'tcx, 'tcx>,
121 state: &'a CompileState<'a, 'tcx>,
124 impl<'a, 'tcx: 'a, 'hir> itemlikevisit::ItemLikeVisitor<'hir> for Visitor<'a, 'tcx> {
125 fn visit_item(&mut self, i: &'hir hir::Item) {
126 if let hir::ItemKind::Fn(.., body_id) = i.node {
127 if i.attrs.iter().any(|attr| {
128 attr.name() == "test"
131 let did = self.tcx.hir.body_owner_def_id(body_id);
134 self.tcx.def_path_debug_str(did),
136 miri::eval_main(self.tcx, did, self.validate);
137 self.state.session.abort_if_errors();
141 fn visit_trait_item(&mut self, _trait_item: &'hir hir::TraitItem) {}
142 fn visit_impl_item(&mut self, _impl_item: &'hir hir::ImplItem) {}
144 state.hir_crate.unwrap().visit_all_item_likes(
145 &mut Visitor { tcx, state, validate }
147 } else if let Some((entry_node_id, _, _)) = *state.session.entry_fn.borrow() {
148 let entry_def_id = tcx.hir.local_def_id(entry_node_id);
149 miri::eval_main(tcx, entry_def_id, validate);
151 state.session.abort_if_errors();
153 println!("no main function found, assuming auxiliary build");
157 fn init_early_loggers() {
158 // Notice that our `extern crate log` is NOT the same as rustc's! So we have to initialize
159 // them both. We always initialize miri early.
160 let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
161 env_logger::init_from_env(env);
162 // We only initialize rustc if the env var is set (so the user asked for it).
163 // If it is not set, we avoid initializing now so that we can initialize
164 // later with our custom settings, and NOT log anything for what happens before
165 // miri gets started.
166 if env::var("RUST_LOG").is_ok() {
167 rustc_driver::init_rustc_env_logger();
171 fn init_late_loggers() {
172 // Initializing loggers right before we start evaluation. We overwrite the RUST_LOG
173 // env var if it is not set, control it based on MIRI_LOG.
174 if let Ok(var) = env::var("MIRI_LOG") {
175 if env::var("RUST_LOG").is_err() {
176 // We try to be a bit clever here: If MIRI_LOG is just a single level
177 // used for everything, we only apply it to the parts of rustc that are
178 // CTFE-related. Otherwise, we use it verbatim for RUST_LOG.
179 // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
180 // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
181 if log::Level::from_str(&var).is_ok() {
182 env::set_var("RUST_LOG",
183 &format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var));
185 env::set_var("RUST_LOG", &var);
187 rustc_driver::init_rustc_env_logger();
192 fn find_sysroot() -> String {
193 if let Ok(sysroot) = std::env::var("MIRI_SYSROOT") {
197 // Taken from https://github.com/Manishearth/rust-clippy/pull/911.
198 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
199 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
200 match (home, toolchain) {
201 (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
203 option_env!("RUST_SYSROOT")
205 "Could not find sysroot. Either set MIRI_SYSROOT at run-time, or at \
206 build-time specify RUST_SYSROOT env var or use rustup or multirust",
214 init_early_loggers();
215 let mut args: Vec<String> = std::env::args().collect();
217 // Parse our own -Z flags and remove them before rustc gets their hand on them.
218 let mut validate = true;
221 "-Zmiri-disable-validation" => {
229 // Determine sysroot and let rustc know about it
230 let sysroot_flag = String::from("--sysroot");
231 if !args.contains(&sysroot_flag) {
232 args.push(sysroot_flag);
233 args.push(find_sysroot());
235 // Finally, add the default flags all the way in the beginning, but after the binary name.
236 args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
238 trace!("rustc arguments: {:?}", args);
239 let result = rustc_driver::run(move || {
240 rustc_driver::run_compiler(&args, Box::new(MiriCompilerCalls {
241 default: Box::new(RustcDefaultCalls),
245 std::process::exit(result as i32);