]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
implement passing arguments to the interpreted program
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private)]
2
3 extern crate getopts;
4 extern crate miri;
5 extern crate rustc;
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;
12 extern crate syntax;
13
14 #[macro_use]
15 extern crate log;
16
17 use std::path::PathBuf;
18 use std::str::FromStr;
19 use std::env;
20
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_codegen_utils::codegen_backend::CodegenBackend;
27 use rustc::hir::def_id::LOCAL_CRATE;
28 use syntax::ast;
29
30 use miri::MiriConfig;
31
32 struct MiriCompilerCalls {
33     default: Box<RustcDefaultCalls>,
34     miri_config: MiriConfig,
35 }
36
37 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
38     fn early_callback(
39         &mut self,
40         matches: &getopts::Matches,
41         sopts: &config::Options,
42         cfg: &ast::CrateConfig,
43         descriptions: &rustc_errors::registry::Registry,
44         output: ErrorOutputType,
45     ) -> Compilation {
46         self.default.early_callback(
47             matches,
48             sopts,
49             cfg,
50             descriptions,
51             output,
52         )
53     }
54     fn no_input(
55         &mut self,
56         matches: &getopts::Matches,
57         sopts: &config::Options,
58         cfg: &ast::CrateConfig,
59         odir: &Option<PathBuf>,
60         ofile: &Option<PathBuf>,
61         descriptions: &rustc_errors::registry::Registry,
62     ) -> Option<(Input, Option<PathBuf>)> {
63         self.default.no_input(
64             matches,
65             sopts,
66             cfg,
67             odir,
68             ofile,
69             descriptions,
70         )
71     }
72     fn late_callback(
73         &mut self,
74         codegen_backend: &CodegenBackend,
75         matches: &getopts::Matches,
76         sess: &Session,
77         cstore: &CStore,
78         input: &Input,
79         odir: &Option<PathBuf>,
80         ofile: &Option<PathBuf>,
81     ) -> Compilation {
82         // Called *before* build_controller. Add filename to miri arguments.
83         self.miri_config.args.insert(0, input.filestem().to_string());
84         self.default.late_callback(codegen_backend, matches, sess, cstore, input, odir, ofile)
85     }
86     fn build_controller(
87         self: Box<Self>,
88         sess: &Session,
89         matches: &getopts::Matches,
90     ) -> CompileController<'a> {
91         let this = *self;
92         let mut control = this.default.build_controller(sess, matches);
93         control.after_hir_lowering.callback = Box::new(after_hir_lowering);
94         let miri_config = this.miri_config;
95         control.after_analysis.callback =
96             Box::new(move |state| after_analysis(state, miri_config.clone()));
97         control.after_analysis.stop = Compilation::Stop;
98         control
99     }
100 }
101
102 fn after_hir_lowering(state: &mut CompileState) {
103     let attr = (
104         String::from("miri"),
105         syntax::feature_gate::AttributeType::Whitelisted,
106     );
107     state.session.plugin_attributes.borrow_mut().push(attr);
108 }
109
110 fn after_analysis<'a, 'tcx>(
111     state: &mut CompileState<'a, 'tcx>,
112     miri_config: MiriConfig,
113 ) {
114     init_late_loggers();
115     state.session.abort_if_errors();
116
117     let tcx = state.tcx.unwrap();
118
119
120     let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
121
122     miri::eval_main(tcx, entry_def_id, miri_config);
123
124     state.session.abort_if_errors();
125 }
126
127 fn init_early_loggers() {
128     // Notice that our `extern crate log` is NOT the same as rustc's!  So we have to initialize
129     // them both.  We always initialize miri early.
130     let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
131     env_logger::init_from_env(env);
132     // We only initialize rustc if the env var is set (so the user asked for it).
133     // If it is not set, we avoid initializing now so that we can initialize
134     // later with our custom settings, and NOT log anything for what happens before
135     // miri gets started.
136     if env::var("RUST_LOG").is_ok() {
137         rustc_driver::init_rustc_env_logger();
138     }
139 }
140
141 fn init_late_loggers() {
142     // Initializing loggers right before we start evaluation.  We overwrite the RUST_LOG
143     // env var if it is not set, control it based on MIRI_LOG.
144     if let Ok(var) = env::var("MIRI_LOG") {
145         if env::var("RUST_LOG").is_err() {
146             // We try to be a bit clever here: If MIRI_LOG is just a single level
147             // used for everything, we only apply it to the parts of rustc that are
148             // CTFE-related.  Otherwise, we use it verbatim for RUST_LOG.
149             // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
150             // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
151             if log::Level::from_str(&var).is_ok() {
152                 env::set_var("RUST_LOG",
153                     &format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var));
154             } else {
155                 env::set_var("RUST_LOG", &var);
156             }
157             rustc_driver::init_rustc_env_logger();
158         }
159     }
160
161     // If MIRI_BACKTRACE is set and RUST_CTFE_BACKTRACE is not, set RUST_CTFE_BACKTRACE.
162     // Do this late, so we really only apply this to miri's errors.
163     if let Ok(var) = env::var("MIRI_BACKTRACE") {
164         if env::var("RUST_CTFE_BACKTRACE") == Err(env::VarError::NotPresent) {
165             env::set_var("RUST_CTFE_BACKTRACE", &var);
166         }
167     }
168 }
169
170 fn find_sysroot() -> String {
171     if let Ok(sysroot) = std::env::var("MIRI_SYSROOT") {
172         return sysroot;
173     }
174
175     // Taken from https://github.com/Manishearth/rust-clippy/pull/911.
176     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
177     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
178     match (home, toolchain) {
179         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
180         _ => {
181             option_env!("RUST_SYSROOT")
182                 .expect(
183                     "Could not find sysroot. Either set MIRI_SYSROOT at run-time, or at \
184                      build-time specify RUST_SYSROOT env var or use rustup or multirust",
185                 )
186                 .to_owned()
187         }
188     }
189 }
190
191 fn main() {
192     init_early_loggers();
193
194     // Parse our arguments and split them across rustc and miri
195     let mut validate = true;
196     let mut rustc_args = vec![];
197     let mut miri_args = vec![];
198     let mut after_dashdash = false;
199     for arg in std::env::args() {
200         if rustc_args.is_empty() {
201             // Very first arg: for rustc
202             rustc_args.push(arg);
203         }
204         else if after_dashdash {
205             // Everything that comes is Miri args
206             miri_args.push(arg);
207         } else {
208             match arg.as_str() {
209                 "-Zmiri-disable-validation" => {
210                     validate = false;
211                 },
212                 "--" => {
213                     after_dashdash = true;
214                 }
215                 _ => {
216                     rustc_args.push(arg);
217                 }
218             }
219         }
220     }
221
222     // Determine sysroot and let rustc know about it
223     let sysroot_flag = String::from("--sysroot");
224     if !rustc_args.contains(&sysroot_flag) {
225         rustc_args.push(sysroot_flag);
226         rustc_args.push(find_sysroot());
227     }
228     // Finally, add the default flags all the way in the beginning, but after the binary name.
229     rustc_args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
230
231     debug!("rustc arguments: {:?}", rustc_args);
232     debug!("miri arguments: {:?}", miri_args);
233     let miri_config = MiriConfig { validate, args: miri_args };
234     let result = rustc_driver::run(move || {
235         rustc_driver::run_compiler(&rustc_args, Box::new(MiriCompilerCalls {
236             default: Box::new(RustcDefaultCalls),
237             miri_config,
238         }), None, None)
239     });
240     std::process::exit(result as i32);
241 }