1 #![feature(rustc_private, i128_type)]
6 extern crate rustc_driver;
7 extern crate rustc_errors;
8 extern crate env_logger;
9 extern crate log_settings;
11 #[macro_use] extern crate log;
13 use rustc::session::Session;
14 use rustc_driver::{Compilation, CompilerCalls, RustcDefaultCalls};
15 use rustc_driver::driver::{CompileState, CompileController};
16 use rustc::session::config::{self, Input, ErrorOutputType};
17 use syntax::ast::{MetaItemKind, NestedMetaItemKind, self};
18 use std::path::PathBuf;
20 struct MiriCompilerCalls(RustcDefaultCalls);
22 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
25 matches: &getopts::Matches,
26 sopts: &config::Options,
27 cfg: &ast::CrateConfig,
28 descriptions: &rustc_errors::registry::Registry,
29 output: ErrorOutputType
31 self.0.early_callback(matches, sopts, cfg, descriptions, output)
35 matches: &getopts::Matches,
36 sopts: &config::Options,
37 cfg: &ast::CrateConfig,
38 odir: &Option<PathBuf>,
39 ofile: &Option<PathBuf>,
40 descriptions: &rustc_errors::registry::Registry
41 ) -> Option<(Input, Option<PathBuf>)> {
42 self.0.no_input(matches, sopts, cfg, odir, ofile, descriptions)
46 matches: &getopts::Matches,
49 odir: &Option<PathBuf>,
50 ofile: &Option<PathBuf>
52 self.0.late_callback(matches, sess, input, odir, ofile)
54 fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> CompileController<'a> {
55 let mut control = self.0.build_controller(sess, matches);
56 control.after_hir_lowering.callback = Box::new(after_hir_lowering);
57 control.after_analysis.callback = Box::new(after_analysis);
58 if std::env::var("MIRI_HOST_TARGET") != Ok("yes".to_owned()) {
59 // only fully compile targets on the host
60 control.after_analysis.stop = Compilation::Stop;
66 fn after_hir_lowering(state: &mut CompileState) {
67 let attr = (String::from("miri"), syntax::feature_gate::AttributeType::Whitelisted);
68 state.session.plugin_attributes.borrow_mut().push(attr);
71 fn after_analysis(state: &mut CompileState) {
72 state.session.abort_if_errors();
74 let tcx = state.tcx.unwrap();
75 if let Some((entry_node_id, _)) = *state.session.entry_fn.borrow() {
76 let entry_def_id = tcx.map.local_def_id(entry_node_id);
77 let limits = resource_limits_from_attributes(state);
78 miri::run_mir_passes(tcx);
79 miri::eval_main(tcx, entry_def_id, limits);
81 state.session.abort_if_errors();
83 println!("no main function found, assuming auxiliary build");
87 fn resource_limits_from_attributes(state: &CompileState) -> miri::ResourceLimits {
88 let mut limits = miri::ResourceLimits::default();
89 let krate = state.hir_crate.as_ref().unwrap();
90 let err_msg = "miri attributes need to be in the form `miri(key = value)`";
91 let extract_int = |lit: &syntax::ast::Lit| -> u128 {
93 syntax::ast::LitKind::Int(i, _) => i,
94 _ => state.session.span_fatal(lit.span, "expected an integer literal"),
98 for attr in krate.attrs.iter().filter(|a| a.name() == "miri") {
99 if let MetaItemKind::List(ref items) = attr.value.node {
101 if let NestedMetaItemKind::MetaItem(ref inner) = item.node {
102 if let MetaItemKind::NameValue(ref value) = inner.node {
103 match &inner.name().as_str()[..] {
104 "memory_size" => limits.memory_size = extract_int(value) as u64,
105 "step_limit" => limits.step_limit = extract_int(value) as u64,
106 "stack_limit" => limits.stack_limit = extract_int(value) as usize,
107 _ => state.session.span_err(item.span, "unknown miri attribute"),
110 state.session.span_err(inner.span, err_msg);
113 state.session.span_err(item.span, err_msg);
117 state.session.span_err(attr.span, err_msg);
124 const MAX_INDENT: usize = 40;
126 let format = |record: &log::LogRecord| {
127 if record.level() == log::LogLevel::Trace {
128 // prepend spaces to indent the final string
129 let indentation = log_settings::settings().indentation;
130 format!("{lvl}:{module}{depth:2}{indent:<indentation$} {text}",
131 lvl = record.level(),
132 module = record.location().module_path(),
133 depth = indentation / MAX_INDENT,
134 indentation = indentation % MAX_INDENT,
136 text = record.args())
138 format!("{lvl}:{module}: {text}",
139 lvl = record.level(),
140 module = record.location().module_path(),
141 text = record.args())
145 let mut builder = env_logger::LogBuilder::new();
146 builder.format(format).filter(None, log::LogLevelFilter::Info);
148 if std::env::var("MIRI_LOG").is_ok() {
149 builder.parse(&std::env::var("MIRI_LOG").unwrap());
152 builder.init().unwrap();
155 fn find_sysroot() -> String {
156 // Taken from https://github.com/Manishearth/rust-clippy/pull/911.
157 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
158 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
159 match (home, toolchain) {
160 (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
161 _ => option_env!("RUST_SYSROOT")
162 .expect("need to specify RUST_SYSROOT env var or use rustup or multirust")
169 let mut args: Vec<String> = std::env::args().collect();
171 let sysroot_flag = String::from("--sysroot");
172 if !args.contains(&sysroot_flag) {
173 args.push(sysroot_flag);
174 args.push(find_sysroot());
176 // we run the optimization passes inside miri
177 // if we ran them twice we'd get funny failures due to borrowck ElaborateDrops only working on
179 // FIXME: add an after-mir-passes hook to rustc driver
180 args.push("-Zmir-opt-level=0".to_owned());
181 // for auxilary builds in unit tests
182 args.push("-Zalways-encode-mir".to_owned());
184 rustc_driver::run_compiler(&args, &mut MiriCompilerCalls(RustcDefaultCalls), None, None);