1 #![feature(rustc_private)]
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;
9 use std::convert::TryFrom;
11 use std::str::FromStr;
13 use hex::FromHexError;
16 use rustc_session::CtfeBacktrace;
17 use rustc_driver::Compilation;
18 use rustc_hir::def_id::LOCAL_CRATE;
19 use rustc_middle::ty::TyCtxt;
21 struct MiriCompilerCalls {
22 miri_config: miri::MiriConfig,
25 impl rustc_driver::Callbacks for MiriCompilerCalls {
26 fn after_analysis<'tcx>(
28 compiler: &rustc_interface::interface::Compiler,
29 queries: &'tcx rustc_interface::Queries<'tcx>,
31 compiler.session().abort_if_errors();
33 queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
34 init_late_loggers(tcx);
35 let (entry_def_id, _) = tcx.entry_fn(LOCAL_CRATE).expect("no main function found!");
36 let mut config = self.miri_config.clone();
38 // Add filename to `miri` arguments.
39 config.args.insert(0, compiler.input().filestem().to_string());
41 if let Some(return_code) = miri::eval_main(tcx, entry_def_id.to_def_id(), config) {
43 i32::try_from(return_code).expect("Return value was too large!"),
48 compiler.session().abort_if_errors();
54 fn init_early_loggers() {
55 // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
56 // initialize them both, and we always initialize `miri`'s first.
57 let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
58 env_logger::init_from_env(env);
59 // We only initialize `rustc` if the env var is set (so the user asked for it).
60 // If it is not set, we avoid initializing now so that we can initialize
61 // later with our custom settings, and *not* log anything for what happens before
62 // `miri` gets started.
63 if env::var_os("RUSTC_LOG").is_some() {
64 rustc_driver::init_rustc_env_logger();
68 fn init_late_loggers(tcx: TyCtxt<'_>) {
69 // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
70 // env var if it is not set, control it based on `MIRI_LOG`.
71 // (FIXE: use `var_os`, but then we need to manually concatenate instead of `format!`.)
72 if let Ok(var) = env::var("MIRI_LOG") {
73 if env::var_os("RUSTC_LOG").is_none() {
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() {
82 &format!("rustc_middle::mir::interpret={0},rustc_mir::interpret={0}", var),
85 env::set_var("RUSTC_LOG", &var);
87 rustc_driver::init_rustc_env_logger();
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 Some(val) = env::var_os("MIRI_BACKTRACE") {
94 let ctfe_backtrace = match &*val.to_string_lossy() {
95 "immediate" => CtfeBacktrace::Immediate,
96 "0" => CtfeBacktrace::Disabled,
97 _ => CtfeBacktrace::Capture,
99 *tcx.sess.ctfe_backtrace.borrow_mut() = ctfe_backtrace;
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_session.
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_session would
113 // end up somewhere in the build dir (see `get_or_default_sysroot`).
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")
125 /// Execute a compiler with the given CLI arguments and callbacks.
126 fn run_compiler(mut args: Vec<String>, callbacks: &mut (dyn rustc_driver::Callbacks + Send)) {
127 // Make sure we use the right default sysroot. The default sysroot is wrong,
128 // because `get_or_default_sysroot` in `librustc_session` bases that on `current_exe`.
130 // Make sure we always call `compile_time_sysroot` as that also does some sanity-checks
131 // of the environment we were built in.
132 // FIXME: Ideally we'd turn a bad build env into a compile-time error via CTFE or so.
133 if let Some(sysroot) = compile_time_sysroot() {
134 let sysroot_flag = "--sysroot";
135 if !args.iter().any(|e| e == sysroot_flag) {
136 // We need to overwrite the default that librustc_session would compute.
137 args.push(sysroot_flag.to_owned());
142 // Invoke compiler, and handle return code.
143 let result = rustc_driver::catch_fatal_errors(move || {
144 rustc_driver::run_compiler(&args, callbacks, None, None)
146 .and_then(|result| result);
147 let exit_code = match result {
148 Ok(()) => rustc_driver::EXIT_SUCCESS,
149 Err(_) => rustc_driver::EXIT_FAILURE,
151 std::process::exit(exit_code);
155 rustc_driver::install_ice_hook();
157 // If the environment asks us to actually be rustc, then do that.
158 if env::var_os("MIRI_BE_RUSTC").is_some() {
159 rustc_driver::init_rustc_env_logger();
160 // We cannot use `rustc_driver::main` as we need to adjust the CLI arguments.
161 let mut callbacks = rustc_driver::TimePassesCallbacks::default();
162 return run_compiler(env::args().collect(), &mut callbacks);
165 // Init loggers the Miri way.
166 init_early_loggers();
168 // Parse our arguments and split them across `rustc` and `miri`.
169 let mut validate = true;
170 let mut stacked_borrows = true;
171 let mut check_alignment = true;
172 let mut communicate = false;
173 let mut ignore_leaks = false;
174 let mut seed: Option<u64> = None;
175 let mut tracked_pointer_tag: Option<miri::PtrId> = None;
176 let mut tracked_alloc_id: Option<miri::AllocId> = None;
177 let mut rustc_args = vec![];
178 let mut crate_args = vec![];
179 let mut after_dashdash = false;
180 let mut excluded_env_vars = vec![];
181 for arg in env::args() {
182 if rustc_args.is_empty() {
183 // Very first arg: binary name.
184 rustc_args.push(arg);
185 // After this, push Miri default args (before everything else so they can be overwritten).
186 for arg in miri::miri_default_args().iter() {
187 rustc_args.push(arg.to_string());
189 } else if after_dashdash {
190 // Everything that comes after `--` is forwarded to the interpreted crate.
191 crate_args.push(arg);
194 "-Zmiri-disable-validation" => {
197 "-Zmiri-disable-stacked-borrows" => {
198 stacked_borrows = false;
200 "-Zmiri-disable-alignment-check" => {
201 check_alignment = false;
203 "-Zmiri-disable-isolation" => {
206 "-Zmiri-ignore-leaks" => {
210 after_dashdash = true;
212 arg if arg.starts_with("-Zmiri-seed=") => {
214 panic!("Cannot specify -Zmiri-seed multiple times!");
216 let seed_raw = hex::decode(arg.trim_start_matches("-Zmiri-seed="))
217 .unwrap_or_else(|err| match err {
218 FromHexError::InvalidHexCharacter { .. } => panic!(
219 "-Zmiri-seed should only contain valid hex digits [0-9a-fA-F]"
221 FromHexError::OddLength =>
222 panic!("-Zmiri-seed should have an even number of digits"),
223 err => panic!("Unknown error decoding -Zmiri-seed as hex: {:?}", err),
225 if seed_raw.len() > 8 {
227 "-Zmiri-seed must be at most 8 bytes, was {}",
232 let mut bytes = [0; 8];
233 bytes[..seed_raw.len()].copy_from_slice(&seed_raw);
234 seed = Some(u64::from_be_bytes(bytes));
236 arg if arg.starts_with("-Zmiri-env-exclude=") => {
238 .push(arg.trim_start_matches("-Zmiri-env-exclude=").to_owned());
240 arg if arg.starts_with("-Zmiri-track-pointer-tag=") => {
241 let id: u64 = match arg.trim_start_matches("-Zmiri-track-pointer-tag=").parse()
245 "-Zmiri-track-pointer-tag requires a valid `u64` as the argument: {}",
249 if let Some(id) = miri::PtrId::new(id) {
250 tracked_pointer_tag = Some(id);
252 panic!("-Zmiri-track-pointer-tag must be a nonzero id");
255 arg if arg.starts_with("-Zmiri-track-alloc-id=") => {
256 let id: u64 = match arg.trim_start_matches("-Zmiri-track-alloc-id=").parse()
260 "-Zmiri-track-alloc-id requires a valid `u64` as the argument: {}",
264 tracked_alloc_id = Some(miri::AllocId(id));
268 rustc_args.push(arg);
274 debug!("rustc arguments: {:?}", rustc_args);
275 debug!("crate arguments: {:?}", crate_args);
276 let miri_config = miri::MiriConfig {
288 return run_compiler(rustc_args, &mut MiriCompilerCalls { miri_config });