]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
fix for GlobalCtxt changes
[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::convert::TryFrom;
19 use std::env;
20
21 use hex::FromHexError;
22
23 use rustc_interface::{interface, Queries};
24 use rustc::hir::def_id::LOCAL_CRATE;
25 use rustc_driver::Compilation;
26
27 struct MiriCompilerCalls {
28     miri_config: miri::MiriConfig,
29 }
30
31 impl rustc_driver::Callbacks for MiriCompilerCalls {
32     fn after_analysis<'tcx>(&mut self, compiler: &interface::Compiler, queries: &'tcx Queries<'tcx>) -> Compilation {
33         init_late_loggers();
34         compiler.session().abort_if_errors();
35
36         queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
37             let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
38             let mut config = self.miri_config.clone();
39
40             // Add filename to `miri` arguments.
41             config.args.insert(0, compiler.input().filestem().to_string());
42
43             if let Some(return_code) = miri::eval_main(tcx, entry_def_id, config) {
44                 std::process::exit(i32::try_from(return_code).expect("Return value was too large!"));
45             }
46         });
47
48         compiler.session().abort_if_errors();
49
50         Compilation::Stop
51     }
52 }
53
54 fn init_early_loggers() {
55     // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
56     // initialize them both, and we always initialize `miri`'s first.
57     let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
58     env_logger::init_from_env(env);
59     // We only initialize `rustc` if the env var is set (so the user asked for it).
60     // If it is not set, we avoid initializing now so that we can initialize
61     // later with our custom settings, and *not* log anything for what happens before
62     // `miri` gets started.
63     if env::var("RUSTC_LOG").is_ok() {
64         rustc_driver::init_rustc_env_logger();
65     }
66 }
67
68 fn init_late_loggers() {
69     // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
70     // env var if it is not set, control it based on `MIRI_LOG`.
71     if let Ok(var) = env::var("MIRI_LOG") {
72         if env::var("RUSTC_LOG").is_err() {
73             // We try to be a bit clever here: if `MIRI_LOG` is just a single level
74             // used for everything, we only apply it to the parts of rustc that are
75             // CTFE-related. Otherwise, we use it verbatim for `RUSTC_LOG`.
76             // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
77             // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_mir::interpret=debug`.
78             if log::Level::from_str(&var).is_ok() {
79                 env::set_var("RUSTC_LOG",
80                     &format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var));
81             } else {
82                 env::set_var("RUSTC_LOG", &var);
83             }
84             rustc_driver::init_rustc_env_logger();
85         }
86     }
87
88     // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.
89     // Do this late, so we ideally only apply this to Miri's errors.
90     if let Ok(var) = env::var("MIRI_BACKTRACE") {
91         if env::var("RUSTC_CTFE_BACKTRACE") == Err(env::VarError::NotPresent) {
92             env::set_var("RUSTC_CTFE_BACKTRACE", &var);
93         }
94     }
95 }
96
97 /// Returns the "default sysroot" that Miri will use if no `--sysroot` flag is set.
98 /// Should be a compile-time constant.
99 fn compile_time_sysroot() -> Option<String> {
100     if option_env!("RUSTC_STAGE").is_some() {
101         // This is being built as part of rustc, and gets shipped with rustup.
102         // We can rely on the sysroot computation in librustc.
103         return None;
104     }
105     // For builds outside rustc, we need to ensure that we got a sysroot
106     // that gets used as a default.  The sysroot computation in librustc would
107     // end up somewhere in the build dir.
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     Some(match (home, toolchain) {
112         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
113         _ => {
114             option_env!("RUST_SYSROOT")
115                 .expect("To build Miri without rustup, set the `RUST_SYSROOT` env var at build time")
116                 .to_owned()
117         }
118     })
119 }
120
121 fn main() {
122     init_early_loggers();
123
124     // Parse our arguments and split them across `rustc` and `miri`.
125     let mut validate = true;
126     let mut communicate = false;
127     let mut seed: Option<u64> = None;
128     let mut rustc_args = vec![];
129     let mut miri_args = vec![];
130     let mut after_dashdash = false;
131     let mut excluded_env_vars = vec![];
132     for arg in std::env::args() {
133         if rustc_args.is_empty() {
134             // Very first arg: for `rustc`.
135             rustc_args.push(arg);
136         }
137         else if after_dashdash {
138             // Everything that comes after are `miri` args.
139             miri_args.push(arg);
140         } else {
141             match arg.as_str() {
142                 "-Zmiri-disable-validation" => {
143                     validate = false;
144                 },
145                 "-Zmiri-disable-isolation" => {
146                     communicate = true;
147                 },
148                 "--" => {
149                     after_dashdash = true;
150                 }
151                 arg if arg.starts_with("-Zmiri-seed=") => {
152                     if seed.is_some() {
153                         panic!("Cannot specify -Zmiri-seed multiple times!");
154                     }
155                     let seed_raw = hex::decode(arg.trim_start_matches("-Zmiri-seed="))
156                         .unwrap_or_else(|err| match err {
157                             FromHexError::InvalidHexCharacter { .. } => panic!(
158                                 "-Zmiri-seed should only contain valid hex digits [0-9a-fA-F]"
159                             ),
160                             FromHexError::OddLength => panic!("-Zmiri-seed should have an even number of digits"),
161                             err => panic!("Unknown error decoding -Zmiri-seed as hex: {:?}", err),
162                         });
163                     if seed_raw.len() > 8 {
164                         panic!(format!("-Zmiri-seed must be at most 8 bytes, was {}", seed_raw.len()));
165                     }
166
167                     let mut bytes = [0; 8];
168                     bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
169                     seed = Some(u64::from_be_bytes(bytes));
170
171                 },
172                 arg if arg.starts_with("-Zmiri-env-exclude=") => {
173                     excluded_env_vars.push(arg.trim_start_matches("-Zmiri-env-exclude=").to_owned());
174                 },
175                 _ => {
176                     rustc_args.push(arg);
177                 }
178             }
179         }
180     }
181
182     // Determine sysroot if needed.  Make sure we always call `compile_time_sysroot`
183     // as that also does some sanity-checks of the environment we were built in.
184     // FIXME: Ideally we'd turn a bad build env into a compile-time error, but
185     // CTFE does not seem powerful enough for that yet.
186     if let Some(sysroot) = compile_time_sysroot() {
187         let sysroot_flag = "--sysroot";
188         if !rustc_args.iter().any(|e| e == sysroot_flag) {
189             // We need to overwrite the default that librustc would compute.
190             rustc_args.push(sysroot_flag.to_owned());
191             rustc_args.push(sysroot);
192         }
193     }
194
195     // Finally, add the default flags all the way in the beginning, but after the binary name.
196     rustc_args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
197
198     debug!("rustc arguments: {:?}", rustc_args);
199     debug!("miri arguments: {:?}", miri_args);
200     let miri_config = miri::MiriConfig {
201         validate,
202         communicate,
203         excluded_env_vars,
204         seed,
205         args: miri_args,
206     };
207     rustc_driver::install_ice_hook();
208     let result = rustc_driver::catch_fatal_errors(move || {
209         rustc_driver::run_compiler(&rustc_args, &mut MiriCompilerCalls { miri_config }, None, None)
210     }).and_then(|result| result);
211     std::process::exit(result.is_err() as i32);
212 }