]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
RUST_LOG got renamed to RUSTC_LOG
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private)]
2
3 extern crate env_logger;
4 extern crate getopts;
5 #[macro_use]
6 extern crate log;
7 extern crate log_settings;
8 extern crate miri;
9 extern crate rustc;
10 extern crate rustc_metadata;
11 extern crate rustc_driver;
12 extern crate rustc_errors;
13 extern crate rustc_codegen_utils;
14 extern crate rustc_interface;
15 extern crate syntax;
16
17 use std::str::FromStr;
18 use std::env;
19
20 use rustc_interface::interface;
21 use rustc::hir::def_id::LOCAL_CRATE;
22
23 struct MiriCompilerCalls {
24     miri_config: miri::MiriConfig,
25 }
26
27 impl rustc_driver::Callbacks for MiriCompilerCalls {
28     fn after_parsing(&mut self, compiler: &interface::Compiler) -> bool {
29         let attr = (
30             String::from("miri"),
31             syntax::feature_gate::AttributeType::Whitelisted,
32         );
33         compiler.session().plugin_attributes.borrow_mut().push(attr);
34
35         // Continue execution
36         true
37     }
38
39     fn after_analysis(&mut self, compiler: &interface::Compiler) -> bool {
40         init_late_loggers();
41         compiler.session().abort_if_errors();
42
43         compiler.global_ctxt().unwrap().peek_mut().enter(|tcx| {
44             let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
45             let mut config = self.miri_config.clone();
46
47             // Add filename to `miri` arguments.
48             config.args.insert(0, compiler.input().filestem().to_string());
49
50             miri::eval_main(tcx, entry_def_id, config);
51         });
52
53         compiler.session().abort_if_errors();
54
55         // Don't continue execution
56         false
57     }
58 }
59
60 fn init_early_loggers() {
61     // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
62     // initialize them both, and we always initialize `miri`'s first.
63     let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
64     env_logger::init_from_env(env);
65     // We only initialize `rustc` if the env var is set (so the user asked for it).
66     // If it is not set, we avoid initializing now so that we can initialize
67     // later with our custom settings, and *not* log anything for what happens before
68     // `miri` gets started.
69     if env::var("RUSTC_LOG").is_ok() {
70         rustc_driver::init_rustc_env_logger();
71     }
72 }
73
74 fn init_late_loggers() {
75     // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
76     // env var if it is not set, control it based on `MIRI_LOG`.
77     if let Ok(var) = env::var("MIRI_LOG") {
78         if env::var("RUSTC_LOG").is_err() {
79             // We try to be a bit clever here: if `MIRI_LOG` is just a single level
80             // used for everything, we only apply it to the parts of rustc that are
81             // CTFE-related. Otherwise, we use it verbatim for `RUSTC_LOG`.
82             // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
83             // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
84             if log::Level::from_str(&var).is_ok() {
85                 env::set_var("RUSTC_LOG",
86                     &format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var));
87             } else {
88                 env::set_var("RUSTC_LOG", &var);
89             }
90             rustc_driver::init_rustc_env_logger();
91         }
92     }
93
94     // If `MIRI_BACKTRACE` is set and `RUST_CTFE_BACKTRACE` is not, set `RUST_CTFE_BACKTRACE`.
95     // Do this late, so we really only apply this to miri's errors.
96     if let Ok(var) = env::var("MIRI_BACKTRACE") {
97         if env::var("RUST_CTFE_BACKTRACE") == Err(env::VarError::NotPresent) {
98             env::set_var("RUST_CTFE_BACKTRACE", &var);
99         }
100     }
101 }
102
103 fn find_sysroot() -> String {
104     if let Ok(sysroot) = std::env::var("MIRI_SYSROOT") {
105         return sysroot;
106     }
107
108     // Taken from PR <https://github.com/Manishearth/rust-clippy/pull/911>.
109     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
110     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
111     match (home, toolchain) {
112         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
113         _ => {
114             option_env!("RUST_SYSROOT")
115                 .expect(
116                     "could not find sysroot. Either set `MIRI_SYSROOT` at run-time, or at \
117                      build-time specify `RUST_SYSROOT` env var or use rustup or multirust",
118                 )
119                 .to_owned()
120         }
121     }
122 }
123
124 fn main() {
125     init_early_loggers();
126
127     // Parse our arguments and split them across `rustc` and `miri`.
128     let mut validate = true;
129     let mut seed: Option<u64> = None;
130     let mut rustc_args = vec![];
131     let mut miri_args = vec![];
132     let mut after_dashdash = false;
133     for arg in std::env::args() {
134         if rustc_args.is_empty() {
135             // Very first arg: for `rustc`.
136             rustc_args.push(arg);
137         }
138         else if after_dashdash {
139             // Everything that comes after are `miri` args.
140             miri_args.push(arg);
141         } else {
142             match arg.as_str() {
143                 "-Zmiri-disable-validation" => {
144                     validate = false;
145                 },
146                 "--" => {
147                     after_dashdash = true;
148                 }
149                 arg if arg.starts_with("-Zmiri-seed=") => {
150                     if seed.is_some() {
151                         panic!("Cannot specify -Zmiri-seed multiple times!");
152                     }
153                     let seed_raw = hex::decode(arg.trim_start_matches("-Zmiri-seed=")).unwrap();
154                     if seed_raw.len() > 8 {
155                         panic!(format!("-Zmiri-seed must be at most 8 bytes, was {}", seed_raw.len()));
156                     }
157
158                     let mut bytes = [0; 8];
159                     bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
160                     seed = Some(u64::from_be_bytes(bytes));
161
162                 },
163                 _ => {
164                     rustc_args.push(arg);
165                 }
166             }
167         }
168     }
169
170     // Determine sysroot and let rustc know about it.
171     let sysroot_flag = String::from("--sysroot");
172     if !rustc_args.contains(&sysroot_flag) {
173         rustc_args.push(sysroot_flag);
174         rustc_args.push(find_sysroot());
175     }
176     // Finally, add the default flags all the way in the beginning, but after the binary name.
177     rustc_args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
178
179     debug!("rustc arguments: {:?}", rustc_args);
180     debug!("miri arguments: {:?}", miri_args);
181     let miri_config = miri::MiriConfig { validate, args: miri_args, seed };
182     let result = rustc_driver::report_ices_to_stderr_if_any(move || {
183         rustc_driver::run_compiler(&rustc_args, &mut MiriCompilerCalls { miri_config }, None, None)
184     }).and_then(|result| result);
185     std::process::exit(result.is_err() as i32);
186 }