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