1 #![feature(rustc_private)]
3 extern crate env_logger;
7 extern crate log_settings;
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;
17 use std::str::FromStr;
20 use hex::FromHexError;
22 use rustc_interface::interface;
23 use rustc::hir::def_id::LOCAL_CRATE;
24 use rustc_driver::Compilation;
26 struct MiriCompilerCalls {
27 miri_config: miri::MiriConfig,
30 impl rustc_driver::Callbacks for MiriCompilerCalls {
31 fn after_analysis(&mut self, compiler: &interface::Compiler) -> Compilation {
33 compiler.session().abort_if_errors();
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();
39 // Add filename to `miri` arguments.
40 config.args.insert(0, compiler.input().filestem().to_string());
42 miri::eval_main(tcx, entry_def_id, config);
45 compiler.session().abort_if_errors();
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();
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));
79 env::set_var("RUSTC_LOG", &var);
81 rustc_driver::init_rustc_env_logger();
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);
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.
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),
111 option_env!("RUST_SYSROOT")
112 .expect("To build Miri without rustup, set the `RUST_SYSROOT` env var at build time")
119 init_early_loggers();
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);
134 else if after_dashdash {
135 // Everything that comes after are `miri` args.
139 "-Zmiri-disable-validation" => {
142 "-Zmiri-disable-isolation" => {
146 after_dashdash = true;
148 arg if arg.starts_with("-Zmiri-seed=") => {
150 panic!("Cannot specify -Zmiri-seed multiple times!");
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]"
157 FromHexError::OddLength => panic!("-Zmiri-seed should have an even number of digits"),
158 err => panic!("Unknown error decoding -Zmiri-seed as hex: {:?}", err),
160 if seed_raw.len() > 8 {
161 panic!(format!("-Zmiri-seed must be at most 8 bytes, was {}", seed_raw.len()));
164 let mut bytes = [0; 8];
165 bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
166 seed = Some(u64::from_be_bytes(bytes));
169 arg if arg.starts_with("-Zmiri-env-exclude=") => {
170 excluded_env_vars.push(arg.trim_start_matches("-Zmiri-env-exclude=").to_owned());
173 rustc_args.push(arg);
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);
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));
195 debug!("rustc arguments: {:?}", rustc_args);
196 debug!("miri arguments: {:?}", miri_args);
197 let miri_config = miri::MiriConfig {
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);