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