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