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