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