1 #![feature(rustc_private)]
3 extern crate env_logger;
7 extern crate log_settings;
10 extern crate rustc_codegen_utils;
11 extern crate rustc_driver;
12 extern crate rustc_errors;
13 extern crate rustc_interface;
14 extern crate rustc_metadata;
17 use std::convert::TryFrom;
19 use std::str::FromStr;
21 use hex::FromHexError;
23 use rustc::hir::def_id::LOCAL_CRATE;
24 use rustc_driver::Compilation;
25 use rustc_interface::{interface, Queries};
27 struct MiriCompilerCalls {
28 miri_config: miri::MiriConfig,
31 impl rustc_driver::Callbacks for MiriCompilerCalls {
32 fn after_analysis<'tcx>(
34 compiler: &interface::Compiler,
35 queries: &'tcx Queries<'tcx>,
38 compiler.session().abort_if_errors();
40 queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
41 let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
42 let mut config = self.miri_config.clone();
44 // Add filename to `miri` arguments.
45 config.args.insert(0, compiler.input().filestem().to_string());
47 if let Some(return_code) = miri::eval_main(tcx, entry_def_id, config) {
49 i32::try_from(return_code).expect("Return value was too large!"),
54 compiler.session().abort_if_errors();
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();
74 fn init_late_loggers() {
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() {
87 &format!("rustc::mir::interpret={0},rustc_mir::interpret={0}", var),
90 env::set_var("RUSTC_LOG", &var);
92 rustc_driver::init_rustc_env_logger();
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(var) = env::var("MIRI_BACKTRACE") {
99 if env::var("RUSTC_CTFE_BACKTRACE") == Err(env::VarError::NotPresent) {
100 env::set_var("RUSTC_CTFE_BACKTRACE", &var);
105 /// Returns the "default sysroot" that Miri will use if no `--sysroot` flag is set.
106 /// Should be a compile-time constant.
107 fn compile_time_sysroot() -> Option<String> {
108 if option_env!("RUSTC_STAGE").is_some() {
109 // This is being built as part of rustc, and gets shipped with rustup.
110 // We can rely on the sysroot computation in librustc.
113 // For builds outside rustc, we need to ensure that we got a sysroot
114 // that gets used as a default. The sysroot computation in librustc would
115 // end up somewhere in the build dir.
116 // Taken from PR <https://github.com/Manishearth/rust-clippy/pull/911>.
117 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
118 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
119 Some(match (home, toolchain) {
120 (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
121 _ => option_env!("RUST_SYSROOT")
122 .expect("To build Miri without rustup, set the `RUST_SYSROOT` env var at build time")
128 init_early_loggers();
130 // Parse our arguments and split them across `rustc` and `miri`.
131 let mut validate = 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 rustc_args = vec![];
137 let mut miri_args = vec![];
138 let mut after_dashdash = false;
139 let mut excluded_env_vars = vec![];
140 for arg in std::env::args() {
141 if rustc_args.is_empty() {
142 // Very first arg: for `rustc`.
143 rustc_args.push(arg);
144 } else if after_dashdash {
145 // Everything that comes after are `miri` args.
149 "-Zmiri-disable-validation" => {
152 "-Zmiri-disable-isolation" => {
155 "-Zmiri-ignore-leaks" => {
159 after_dashdash = true;
161 arg if arg.starts_with("-Zmiri-seed=") => {
163 panic!("Cannot specify -Zmiri-seed multiple times!");
165 let seed_raw = hex::decode(arg.trim_start_matches("-Zmiri-seed="))
166 .unwrap_or_else(|err| match err {
167 FromHexError::InvalidHexCharacter { .. } => panic!(
168 "-Zmiri-seed should only contain valid hex digits [0-9a-fA-F]"
170 FromHexError::OddLength =>
171 panic!("-Zmiri-seed should have an even number of digits"),
172 err => panic!("Unknown error decoding -Zmiri-seed as hex: {:?}", err),
174 if seed_raw.len() > 8 {
176 "-Zmiri-seed must be at most 8 bytes, was {}",
181 let mut bytes = [0; 8];
182 bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
183 seed = Some(u64::from_be_bytes(bytes));
185 arg if arg.starts_with("-Zmiri-env-exclude=") => {
187 .push(arg.trim_start_matches("-Zmiri-env-exclude=").to_owned());
189 arg if arg.starts_with("-Zmiri-track-pointer-tag=") => {
190 let id: u64 = match arg.trim_start_matches("-Zmiri-track-pointer-tag=").parse()
194 "-Zmiri-track-pointer-tag requires a valid `u64` as the argument: {}",
198 if let Some(id) = miri::PtrId::new(id) {
199 tracked_pointer_tag = Some(id);
201 panic!("-Zmiri-track-pointer-tag must be a nonzero id");
205 rustc_args.push(arg);
211 // Determine sysroot if needed. Make sure we always call `compile_time_sysroot`
212 // as that also does some sanity-checks of the environment we were built in.
213 // FIXME: Ideally we'd turn a bad build env into a compile-time error, but
214 // CTFE does not seem powerful enough for that yet.
215 if let Some(sysroot) = compile_time_sysroot() {
216 let sysroot_flag = "--sysroot";
217 if !rustc_args.iter().any(|e| e == sysroot_flag) {
218 // We need to overwrite the default that librustc would compute.
219 rustc_args.push(sysroot_flag.to_owned());
220 rustc_args.push(sysroot);
224 // Finally, add the default flags all the way in the beginning, but after the binary name.
225 rustc_args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
227 debug!("rustc arguments: {:?}", rustc_args);
228 debug!("miri arguments: {:?}", miri_args);
229 let miri_config = miri::MiriConfig {
238 rustc_driver::install_ice_hook();
239 let result = rustc_driver::catch_fatal_errors(move || {
240 rustc_driver::run_compiler(&rustc_args, &mut MiriCompilerCalls { miri_config }, None, None)
242 .and_then(|result| result);
243 std::process::exit(result.is_err() as i32);