]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
Fix infinite loop when debug trace is disabled.
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private, custom_attribute)]
2 #![allow(unused_attributes)]
3
4 extern crate getopts;
5 extern crate miri;
6 extern crate rustc;
7 extern crate rustc_driver;
8 extern crate env_logger;
9 extern crate log_settings;
10 extern crate syntax;
11 #[macro_use] extern crate log;
12
13 use miri::{
14     EvalContext,
15     CachedMir,
16     step,
17     EvalError,
18     Frame,
19 };
20 use rustc::session::Session;
21 use rustc_driver::{driver, CompilerCalls};
22 use rustc::ty::{TyCtxt, subst};
23 use rustc::mir::mir_map::MirMap;
24 use rustc::hir::def_id::DefId;
25
26 struct MiriCompilerCalls;
27
28 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
29     fn build_controller(
30         &mut self,
31         _: &Session,
32         _: &getopts::Matches
33     ) -> driver::CompileController<'a> {
34         let mut control = driver::CompileController::basic();
35
36         control.after_analysis.callback = Box::new(|state| {
37             state.session.abort_if_errors();
38             interpret_start_points(state.tcx.unwrap(), state.mir_map.unwrap());
39         });
40
41         control
42     }
43 }
44
45
46
47 fn interpret_start_points<'a, 'tcx>(
48     tcx: TyCtxt<'a, 'tcx, 'tcx>,
49     mir_map: &MirMap<'tcx>,
50 ) {
51     let initial_indentation = ::log_settings::settings().indentation;
52     for (&id, mir) in &mir_map.map {
53         for attr in tcx.map.attrs(id) {
54             use syntax::attr::AttrMetaMethods;
55             if attr.check_name("miri_run") {
56                 let item = tcx.map.expect_item(id);
57
58                 ::log_settings::settings().indentation = initial_indentation;
59
60                 debug!("Interpreting: {}", item.name);
61
62                 let mut ecx = EvalContext::new(tcx, mir_map);
63                 let substs = tcx.mk_substs(subst::Substs::empty());
64                 let return_ptr = ecx.alloc_ret_ptr(mir.return_ty, substs);
65
66                 ecx.push_stack_frame(tcx.map.local_def_id(id), mir.span, CachedMir::Ref(mir), substs, return_ptr);
67
68                 loop {
69                     match step(&mut ecx) {
70                         Ok(true) => {}
71                         Ok(false) => {
72                             match return_ptr {
73                                 Some(ptr) => if log_enabled!(::log::LogLevel::Debug) {
74                                     ecx.memory().dump(ptr.alloc_id);
75                                 },
76                                 None => warn!("diverging function returned"),
77                             }
78                             break;
79                         }
80                         // FIXME: diverging functions can end up here in some future miri
81                         Err(e) => {
82                             report(tcx, &ecx, e);
83                             break;
84                         }
85                     }
86                 }
87             }
88         }
89     }
90 }
91
92 fn report(tcx: TyCtxt, ecx: &EvalContext, e: EvalError) {
93     let frame = ecx.stack().last().expect("stackframe was empty");
94     let block = &frame.mir.basic_blocks()[frame.next_block];
95     let span = if frame.stmt < block.statements.len() {
96         block.statements[frame.stmt].source_info.span
97     } else {
98         block.terminator().source_info.span
99     };
100     let mut err = tcx.sess.struct_span_err(span, &e.to_string());
101     for &Frame { def_id, substs, span, .. } in ecx.stack().iter().rev() {
102         // FIXME(solson): Find a way to do this without this Display impl hack.
103         use rustc::util::ppaux;
104         use std::fmt;
105         struct Instance<'tcx>(DefId, &'tcx subst::Substs<'tcx>);
106         impl<'tcx> fmt::Display for Instance<'tcx> {
107             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108                 ppaux::parameterized(f, self.1, self.0, ppaux::Ns::Value, &[],
109                     |tcx| Some(tcx.lookup_item_type(self.0).generics))
110             }
111         }
112         err.span_note(span, &format!("inside call to {}", Instance(def_id, substs)));
113     }
114     err.emit();
115 }
116
117 #[miri_run]
118 fn main() {
119     init_logger();
120     let args: Vec<String> = std::env::args().collect();
121     rustc_driver::run_compiler(&args, &mut MiriCompilerCalls);
122 }
123
124 #[miri_run]
125 fn init_logger() {
126     const NSPACES: usize = 40;
127     let format = |record: &log::LogRecord| {
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 / NSPACES,
134             indentation = indentation % NSPACES,
135             indent = "",
136             text = record.args())
137     };
138
139     let mut builder = env_logger::LogBuilder::new();
140     builder.format(format).filter(None, log::LogLevelFilter::Info);
141
142     if std::env::var("MIRI_LOG").is_ok() {
143         builder.parse(&std::env::var("MIRI_LOG").unwrap());
144     }
145
146     builder.init().unwrap();
147 }