]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
add cargo-miri subcommand to directly interpret the main binary of a crate
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private, i128_type)]
2
3 extern crate getopts;
4 extern crate miri;
5 extern crate rustc;
6 extern crate rustc_driver;
7 extern crate rustc_errors;
8 extern crate env_logger;
9 extern crate log_settings;
10 extern crate syntax;
11 #[macro_use] extern crate log;
12
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;
19
20 struct MiriCompilerCalls(RustcDefaultCalls);
21
22 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
23     fn early_callback(
24         &mut self,
25         matches: &getopts::Matches,
26         sopts: &config::Options,
27         cfg: &ast::CrateConfig,
28         descriptions: &rustc_errors::registry::Registry,
29         output: ErrorOutputType
30     ) -> Compilation {
31         self.0.early_callback(matches, sopts, cfg, descriptions, output)
32     }
33     fn no_input(
34         &mut self,
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)
43     }
44     fn late_callback(
45         &mut self,
46         matches: &getopts::Matches,
47         sess: &Session,
48         input: &Input,
49         odir: &Option<PathBuf>,
50         ofile: &Option<PathBuf>
51     ) -> Compilation {
52         self.0.late_callback(matches, sess, input, odir, ofile)
53     }
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;
61         }
62         control
63     }
64 }
65
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);
69 }
70
71 fn after_analysis(state: &mut CompileState) {
72     state.session.abort_if_errors();
73
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);
80
81         state.session.abort_if_errors();
82     } else {
83         println!("no main function found, assuming auxiliary build");
84     }
85 }
86
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 {
92         match lit.node {
93             syntax::ast::LitKind::Int(i, _) => i,
94             _ => state.session.span_fatal(lit.span, "expected an integer literal"),
95         }
96     };
97
98     for attr in krate.attrs.iter().filter(|a| a.name() == "miri") {
99         if let MetaItemKind::List(ref items) = attr.value.node {
100             for item in items {
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"),
108                         }
109                     } else {
110                         state.session.span_err(inner.span, err_msg);
111                     }
112                 } else {
113                     state.session.span_err(item.span, err_msg);
114                 }
115             }
116         } else {
117             state.session.span_err(attr.span, err_msg);
118         }
119     }
120     limits
121 }
122
123 fn init_logger() {
124     const MAX_INDENT: usize = 40;
125
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,
135                 indent = "",
136                 text = record.args())
137         } else {
138             format!("{lvl}:{module}: {text}",
139                 lvl = record.level(),
140                 module = record.location().module_path(),
141                 text = record.args())
142         }
143     };
144
145     let mut builder = env_logger::LogBuilder::new();
146     builder.format(format).filter(None, log::LogLevelFilter::Info);
147
148     if std::env::var("MIRI_LOG").is_ok() {
149         builder.parse(&std::env::var("MIRI_LOG").unwrap());
150     }
151
152     builder.init().unwrap();
153 }
154
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")
163             .to_owned(),
164     }
165 }
166
167 fn main() {
168     init_logger();
169     let mut args: Vec<String> = std::env::args().collect();
170
171     let sysroot_flag = String::from("--sysroot");
172     if !args.contains(&sysroot_flag) {
173         args.push(sysroot_flag);
174         args.push(find_sysroot());
175     }
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
178     // unoptimized MIR
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());
183
184     rustc_driver::run_compiler(&args, &mut MiriCompilerCalls(RustcDefaultCalls), None, None);
185 }