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