1 #![feature(rustc_private, stmt_expr_attributes)]
3 clippy::manual_range_contains,
4 clippy::useless_format,
5 clippy::field_reassign_with_default
8 extern crate rustc_data_structures;
9 extern crate rustc_driver;
10 extern crate rustc_hir;
11 extern crate rustc_interface;
12 extern crate rustc_metadata;
13 extern crate rustc_middle;
14 extern crate rustc_session;
17 use std::num::NonZeroU64;
18 use std::path::PathBuf;
19 use std::str::FromStr;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_driver::Compilation;
25 use rustc_hir::{self as hir, def_id::LOCAL_CRATE, Node};
26 use rustc_interface::interface::Config;
28 middle::exported_symbols::{
29 ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
31 ty::{query::ExternProviders, TyCtxt},
33 use rustc_session::{config::CrateType, search_paths::PathKind, CtfeBacktrace};
35 use miri::{BacktraceStyle, ProvenanceMode, RetagFields};
37 struct MiriCompilerCalls {
38 miri_config: miri::MiriConfig,
41 impl rustc_driver::Callbacks for MiriCompilerCalls {
42 fn config(&mut self, config: &mut Config) {
43 config.override_queries = Some(|_, _, external_providers| {
44 external_providers.used_crate_source = |tcx, cnum| {
45 let mut providers = ExternProviders::default();
46 rustc_metadata::provide_extern(&mut providers);
47 let mut crate_source = (providers.used_crate_source)(tcx, cnum);
48 // HACK: rustc will emit "crate ... required to be available in rlib format, but
49 // was not found in this form" errors once we use `tcx.dependency_formats()` if
50 // there's no rlib provided, so setting a dummy path here to workaround those errors.
51 Lrc::make_mut(&mut crate_source).rlib = Some((PathBuf::new(), PathKind::All));
57 fn after_analysis<'tcx>(
59 compiler: &rustc_interface::interface::Compiler,
60 queries: &'tcx rustc_interface::Queries<'tcx>,
62 compiler.session().abort_if_errors();
64 queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
65 init_late_loggers(tcx);
66 if !tcx.sess.crate_types().contains(&CrateType::Executable) {
67 tcx.sess.fatal("miri only makes sense on bin crates");
70 let (entry_def_id, entry_type) = if let Some(entry_def) = tcx.entry_fn(()) {
73 tcx.sess.fatal("miri can only run programs that have a main function");
75 let mut config = self.miri_config.clone();
77 // Add filename to `miri` arguments.
78 config.args.insert(0, compiler.input().filestem().to_string());
80 // Adjust working directory for interpretation.
81 if let Some(cwd) = env::var_os("MIRI_CWD") {
82 env::set_current_dir(cwd).unwrap();
85 if let Some(return_code) = miri::eval_entry(tcx, entry_def_id, entry_type, config) {
87 i32::try_from(return_code).expect("Return value was too large!"),
92 compiler.session().abort_if_errors();
98 struct MiriBeRustCompilerCalls {
102 impl rustc_driver::Callbacks for MiriBeRustCompilerCalls {
103 #[allow(rustc::potential_query_instability)] // rustc_codegen_ssa (where this code is copied from) also allows this lint
104 fn config(&mut self, config: &mut Config) {
105 if config.opts.prints.is_empty() && self.target_crate {
106 // Queries overriden here affect the data stored in `rmeta` files of dependencies,
107 // which will be used later in non-`MIRI_BE_RUSTC` mode.
108 config.override_queries = Some(|_, local_providers, _| {
109 // `exported_symbols` and `reachable_non_generics` provided by rustc always returns
110 // an empty result if `tcx.sess.opts.output_types.should_codegen()` is false.
111 local_providers.exported_symbols = |tcx, cnum| {
112 assert_eq!(cnum, LOCAL_CRATE);
113 tcx.arena.alloc_from_iter(
115 // https://github.com/rust-lang/rust/blob/2962e7c0089d5c136f4e9600b7abccfbbde4973d/compiler/rustc_codegen_ssa/src/back/symbol_export.rs#L62-L63
116 // https://github.com/rust-lang/rust/blob/2962e7c0089d5c136f4e9600b7abccfbbde4973d/compiler/rustc_codegen_ssa/src/back/symbol_export.rs#L174
117 tcx.reachable_set(()).iter().filter_map(|&local_def_id| {
118 // Do the same filtering that rustc does:
119 // https://github.com/rust-lang/rust/blob/2962e7c0089d5c136f4e9600b7abccfbbde4973d/compiler/rustc_codegen_ssa/src/back/symbol_export.rs#L84-L102
120 // Otherwise it may cause unexpected behaviours and ICEs
121 // (https://github.com/rust-lang/rust/issues/86261).
122 let is_reachable_non_generic = matches!(
123 tcx.hir().get(tcx.hir().local_def_id_to_hir_id(local_def_id)),
124 Node::Item(&hir::Item {
125 kind: hir::ItemKind::Static(..) | hir::ItemKind::Fn(..),
127 }) | Node::ImplItem(&hir::ImplItem {
128 kind: hir::ImplItemKind::Fn(..),
131 if !tcx.generics_of(local_def_id).requires_monomorphization(tcx)
133 (is_reachable_non_generic
134 && tcx.codegen_fn_attrs(local_def_id).contains_extern_indicator())
136 ExportedSymbol::NonGeneric(local_def_id.to_def_id()),
137 // Some dummy `SymbolExportInfo` here. We only use
138 // `exported_symbols` in shims/foreign_items.rs and the export info
141 level: SymbolExportLevel::C,
142 kind: SymbolExportKind::Text,
154 fn show_error(msg: &impl std::fmt::Display) -> ! {
155 eprintln!("fatal error: {msg}");
156 std::process::exit(1)
159 macro_rules! show_error {
160 ($($tt:tt)*) => { show_error(&format_args!($($tt)*)) };
163 fn init_early_loggers() {
164 // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
165 // initialize them both, and we always initialize `miri`'s first.
166 let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
167 env_logger::init_from_env(env);
168 // Enable verbose entry/exit logging by default if MIRI_LOG is set.
169 if env::var_os("MIRI_LOG").is_some() && env::var_os("RUSTC_LOG_ENTRY_EXIT").is_none() {
170 env::set_var("RUSTC_LOG_ENTRY_EXIT", "1");
172 // We only initialize `rustc` if the env var is set (so the user asked for it).
173 // If it is not set, we avoid initializing now so that we can initialize
174 // later with our custom settings, and *not* log anything for what happens before
175 // `miri` gets started.
176 if env::var_os("RUSTC_LOG").is_some() {
177 rustc_driver::init_rustc_env_logger();
181 fn init_late_loggers(tcx: TyCtxt<'_>) {
182 // We initialize loggers right before we start evaluation. We overwrite the `RUSTC_LOG`
183 // env var if it is not set, control it based on `MIRI_LOG`.
184 // (FIXME: use `var_os`, but then we need to manually concatenate instead of `format!`.)
185 if let Ok(var) = env::var("MIRI_LOG") {
186 if env::var_os("RUSTC_LOG").is_none() {
187 // We try to be a bit clever here: if `MIRI_LOG` is just a single level
188 // used for everything, we only apply it to the parts of rustc that are
189 // CTFE-related. Otherwise, we use it verbatim for `RUSTC_LOG`.
190 // This way, if you set `MIRI_LOG=trace`, you get only the right parts of
191 // rustc traced, but you can also do `MIRI_LOG=miri=trace,rustc_const_eval::interpret=debug`.
192 if log::Level::from_str(&var).is_ok() {
195 format!("rustc_middle::mir::interpret={var},rustc_const_eval::interpret={var}"),
198 env::set_var("RUSTC_LOG", &var);
200 rustc_driver::init_rustc_env_logger();
204 // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.
205 // Do this late, so we ideally only apply this to Miri's errors.
206 if let Some(val) = env::var_os("MIRI_BACKTRACE") {
207 let ctfe_backtrace = match &*val.to_string_lossy() {
208 "immediate" => CtfeBacktrace::Immediate,
209 "0" => CtfeBacktrace::Disabled,
210 _ => CtfeBacktrace::Capture,
212 *tcx.sess.ctfe_backtrace.borrow_mut() = ctfe_backtrace;
216 /// Execute a compiler with the given CLI arguments and callbacks.
218 mut args: Vec<String>,
220 callbacks: &mut (dyn rustc_driver::Callbacks + Send),
223 // Miri needs a custom sysroot for target crates.
224 // If no `--sysroot` is given, the `MIRI_SYSROOT` env var is consulted to find where
225 // that sysroot lives, and that is passed to rustc.
226 let sysroot_flag = "--sysroot";
227 if !args.iter().any(|e| e == sysroot_flag) {
228 // Using the built-in default here would be plain wrong, so we *require*
229 // the env var to make sure things make sense.
230 let miri_sysroot = env::var("MIRI_SYSROOT").unwrap_or_else(|_| {
232 "Miri was invoked in 'target' mode without `MIRI_SYSROOT` or `--sysroot` being set"
236 args.push(sysroot_flag.to_owned());
237 args.push(miri_sysroot);
241 // Don't insert `MIRI_DEFAULT_ARGS`, in particular, `--cfg=miri`, if we are building
242 // a "host" crate. That may cause procedural macros (and probably build scripts) to
243 // depend on Miri-only symbols, such as `miri_resolve_frame`:
244 // https://github.com/rust-lang/miri/issues/1760
246 // Some options have different defaults in Miri than in plain rustc; apply those by making
247 // them the first arguments after the binary name (but later arguments can overwrite them).
248 args.splice(1..1, miri::MIRI_DEFAULT_ARGS.iter().map(ToString::to_string));
251 // Invoke compiler, and handle return code.
252 let exit_code = rustc_driver::catch_with_exit_code(move || {
253 rustc_driver::RunCompiler::new(&args, callbacks).run()
255 std::process::exit(exit_code)
258 /// Parses a comma separated list of `T` from the given string:
260 /// `<value1>,<value2>,<value3>,...`
261 fn parse_comma_list<T: FromStr>(input: &str) -> Result<Vec<T>, T::Err> {
262 input.split(',').map(str::parse::<T>).collect()
266 // Snapshot a copy of the environment before `rustc` starts messing with it.
267 // (`install_ice_hook` might change `RUST_BACKTRACE`.)
268 let env_snapshot = env::vars_os().collect::<Vec<_>>();
270 // Earliest rustc setup.
271 rustc_driver::install_ice_hook();
273 // If the environment asks us to actually be rustc, then do that.
274 if let Some(crate_kind) = env::var_os("MIRI_BE_RUSTC") {
275 rustc_driver::init_rustc_env_logger();
277 let target_crate = if crate_kind == "target" {
279 } else if crate_kind == "host" {
282 panic!("invalid `MIRI_BE_RUSTC` value: {crate_kind:?}")
285 // We cannot use `rustc_driver::main` as we need to adjust the CLI arguments.
287 env::args().collect(),
289 &mut MiriBeRustCompilerCalls { target_crate },
293 // Init loggers the Miri way.
294 init_early_loggers();
296 // Parse our arguments and split them across `rustc` and `miri`.
297 let mut miri_config = miri::MiriConfig::default();
298 miri_config.env = env_snapshot;
300 let mut rustc_args = vec![];
301 let mut after_dashdash = false;
303 // If user has explicitly enabled/disabled isolation
304 let mut isolation_enabled: Option<bool> = None;
305 for arg in env::args() {
306 if rustc_args.is_empty() {
307 // Very first arg: binary name.
308 rustc_args.push(arg);
309 } else if after_dashdash {
310 // Everything that comes after `--` is forwarded to the interpreted crate.
311 miri_config.args.push(arg);
312 } else if arg == "--" {
313 after_dashdash = true;
314 } else if arg == "-Zmiri-disable-validation" {
315 miri_config.validate = false;
316 } else if arg == "-Zmiri-disable-stacked-borrows" {
317 miri_config.borrow_tracker = None;
318 } else if arg == "-Zmiri-disable-data-race-detector" {
319 miri_config.data_race_detector = false;
320 miri_config.weak_memory_emulation = false;
321 } else if arg == "-Zmiri-disable-alignment-check" {
322 miri_config.check_alignment = miri::AlignmentCheck::None;
323 } else if arg == "-Zmiri-symbolic-alignment-check" {
324 miri_config.check_alignment = miri::AlignmentCheck::Symbolic;
325 } else if arg == "-Zmiri-check-number-validity" {
327 "WARNING: the flag `-Zmiri-check-number-validity` no longer has any effect \
328 since it is now enabled by default"
330 } else if arg == "-Zmiri-disable-abi-check" {
331 miri_config.check_abi = false;
332 } else if arg == "-Zmiri-disable-isolation" {
333 if matches!(isolation_enabled, Some(true)) {
335 "-Zmiri-disable-isolation cannot be used along with -Zmiri-isolation-error"
338 isolation_enabled = Some(false);
340 miri_config.isolated_op = miri::IsolatedOp::Allow;
341 } else if arg == "-Zmiri-disable-weak-memory-emulation" {
342 miri_config.weak_memory_emulation = false;
343 } else if arg == "-Zmiri-track-weak-memory-loads" {
344 miri_config.track_outdated_loads = true;
345 } else if let Some(param) = arg.strip_prefix("-Zmiri-isolation-error=") {
346 if matches!(isolation_enabled, Some(false)) {
348 "-Zmiri-isolation-error cannot be used along with -Zmiri-disable-isolation"
351 isolation_enabled = Some(true);
354 miri_config.isolated_op = match param {
355 "abort" => miri::IsolatedOp::Reject(miri::RejectOpWith::Abort),
356 "hide" => miri::IsolatedOp::Reject(miri::RejectOpWith::NoWarning),
357 "warn" => miri::IsolatedOp::Reject(miri::RejectOpWith::Warning),
358 "warn-nobacktrace" =>
359 miri::IsolatedOp::Reject(miri::RejectOpWith::WarningWithoutBacktrace),
362 "-Zmiri-isolation-error must be `abort`, `hide`, `warn`, or `warn-nobacktrace`"
365 } else if arg == "-Zmiri-ignore-leaks" {
366 miri_config.ignore_leaks = true;
367 } else if arg == "-Zmiri-panic-on-unsupported" {
368 miri_config.panic_on_unsupported = true;
369 } else if arg == "-Zmiri-tag-raw-pointers" {
370 eprintln!("WARNING: `-Zmiri-tag-raw-pointers` has no effect; it is enabled by default");
371 } else if arg == "-Zmiri-strict-provenance" {
372 miri_config.provenance_mode = ProvenanceMode::Strict;
373 } else if arg == "-Zmiri-permissive-provenance" {
374 miri_config.provenance_mode = ProvenanceMode::Permissive;
375 } else if arg == "-Zmiri-mute-stdout-stderr" {
376 miri_config.mute_stdout_stderr = true;
377 } else if arg == "-Zmiri-retag-fields" {
378 miri_config.retag_fields = RetagFields::Yes;
379 } else if let Some(retag_fields) = arg.strip_prefix("-Zmiri-retag-fields=") {
380 miri_config.retag_fields = match retag_fields {
381 "all" => RetagFields::Yes,
382 "none" => RetagFields::No,
383 "scalar" => RetagFields::OnlyScalar,
384 _ => show_error!("`-Zmiri-retag-fields` can only be `all`, `none`, or `scalar`"),
386 } else if arg == "-Zmiri-track-raw-pointers" {
388 "WARNING: `-Zmiri-track-raw-pointers` has no effect; it is enabled by default"
390 } else if let Some(param) = arg.strip_prefix("-Zmiri-seed=") {
391 if miri_config.seed.is_some() {
392 show_error!("Cannot specify -Zmiri-seed multiple times!");
394 let seed = param.parse::<u64>().unwrap_or_else(|_| {
395 show_error!("-Zmiri-seed must be an integer that fits into u64")
397 miri_config.seed = Some(seed);
398 } else if let Some(_param) = arg.strip_prefix("-Zmiri-env-exclude=") {
400 "`-Zmiri-env-exclude` has been removed; unset env vars before starting Miri instead"
402 } else if let Some(param) = arg.strip_prefix("-Zmiri-env-forward=") {
403 miri_config.forwarded_env_vars.push(param.to_owned());
404 } else if let Some(param) = arg.strip_prefix("-Zmiri-track-pointer-tag=") {
405 let ids: Vec<u64> = match parse_comma_list(param) {
409 "-Zmiri-track-pointer-tag requires a comma separated list of valid `u64` arguments: {}",
413 for id in ids.into_iter().map(miri::BorTag::new) {
414 if let Some(id) = id {
415 miri_config.tracked_pointer_tags.insert(id);
417 show_error!("-Zmiri-track-pointer-tag requires nonzero arguments");
420 } else if let Some(param) = arg.strip_prefix("-Zmiri-track-call-id=") {
421 let ids: Vec<u64> = match parse_comma_list(param) {
425 "-Zmiri-track-call-id requires a comma separated list of valid `u64` arguments: {}",
429 for id in ids.into_iter().map(miri::CallId::new) {
430 if let Some(id) = id {
431 miri_config.tracked_call_ids.insert(id);
433 show_error!("-Zmiri-track-call-id requires a nonzero argument");
436 } else if let Some(param) = arg.strip_prefix("-Zmiri-track-alloc-id=") {
437 let ids: Vec<miri::AllocId> = match parse_comma_list::<NonZeroU64>(param) {
438 Ok(ids) => ids.into_iter().map(miri::AllocId).collect(),
441 "-Zmiri-track-alloc-id requires a comma separated list of valid non-zero `u64` arguments: {}",
445 miri_config.tracked_alloc_ids.extend(ids);
446 } else if let Some(param) = arg.strip_prefix("-Zmiri-compare-exchange-weak-failure-rate=") {
447 let rate = match param.parse::<f64>() {
448 Ok(rate) if rate >= 0.0 && rate <= 1.0 => rate,
451 "-Zmiri-compare-exchange-weak-failure-rate must be between `0.0` and `1.0`"
455 "-Zmiri-compare-exchange-weak-failure-rate requires a `f64` between `0.0` and `1.0`: {}",
459 miri_config.cmpxchg_weak_failure_rate = rate;
460 } else if let Some(param) = arg.strip_prefix("-Zmiri-preemption-rate=") {
461 let rate = match param.parse::<f64>() {
462 Ok(rate) if rate >= 0.0 && rate <= 1.0 => rate,
463 Ok(_) => show_error!("-Zmiri-preemption-rate must be between `0.0` and `1.0`"),
466 "-Zmiri-preemption-rate requires a `f64` between `0.0` and `1.0`: {}",
470 miri_config.preemption_rate = rate;
471 } else if arg == "-Zmiri-report-progress" {
472 // This makes it take a few seconds between progress reports on my laptop.
473 miri_config.report_progress = Some(1_000_000);
474 } else if let Some(param) = arg.strip_prefix("-Zmiri-report-progress=") {
475 let interval = match param.parse::<u32>() {
477 Err(err) => show_error!("-Zmiri-report-progress requires a `u32`: {}", err),
479 miri_config.report_progress = Some(interval);
480 } else if let Some(param) = arg.strip_prefix("-Zmiri-tag-gc=") {
481 let interval = match param.parse::<u32>() {
483 Err(err) => show_error!("-Zmiri-tag-gc requires a `u32`: {}", err),
485 miri_config.gc_interval = interval;
486 } else if let Some(param) = arg.strip_prefix("-Zmiri-measureme=") {
487 miri_config.measureme_out = Some(param.to_string());
488 } else if let Some(param) = arg.strip_prefix("-Zmiri-backtrace=") {
489 miri_config.backtrace_style = match param {
490 "0" => BacktraceStyle::Off,
491 "1" => BacktraceStyle::Short,
492 "full" => BacktraceStyle::Full,
493 _ => show_error!("-Zmiri-backtrace may only be 0, 1, or full"),
495 } else if let Some(param) = arg.strip_prefix("-Zmiri-extern-so-file=") {
496 let filename = param.to_string();
497 if std::path::Path::new(&filename).exists() {
498 if let Some(other_filename) = miri_config.external_so_file {
500 "-Zmiri-extern-so-file is already set to {}",
501 other_filename.display()
504 miri_config.external_so_file = Some(filename.into());
506 show_error!("-Zmiri-extern-so-file `{}` does not exist", filename);
508 } else if let Some(param) = arg.strip_prefix("-Zmiri-num-cpus=") {
509 let num_cpus = match param.parse::<u32>() {
511 Err(err) => show_error!("-Zmiri-num-cpus requires a `u32`: {}", err),
514 miri_config.num_cpus = num_cpus;
515 } else if let Some(param) = arg.strip_prefix("-Zmiri-force-page-size=") {
516 let page_size = match param.parse::<u64>() {
518 if i.is_power_of_two() {
521 show_error!("-Zmiri-force-page-size requires a power of 2: {}", i)
523 Err(err) => show_error!("-Zmiri-force-page-size requires a `u64`: {}", err),
526 miri_config.page_size = Some(page_size);
529 rustc_args.push(arg);
533 debug!("rustc arguments: {:?}", rustc_args);
534 debug!("crate arguments: {:?}", miri_config.args);
535 run_compiler(rustc_args, /* target_crate: */ true, &mut MiriCompilerCalls { miri_config })