]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/bin/miri.rs
Rollup merge of #104286 - ozkanonur:fix-doc-bootstrap-recompilation, r=jyn514
[rust.git] / src / tools / miri / src / bin / miri.rs
1 #![feature(rustc_private, stmt_expr_attributes)]
2 #![allow(
3     clippy::manual_range_contains,
4     clippy::useless_format,
5     clippy::field_reassign_with_default
6 )]
7
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;
15
16 use std::env;
17 use std::num::NonZeroU64;
18 use std::path::PathBuf;
19 use std::str::FromStr;
20
21 use log::debug;
22
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;
27 use rustc_middle::{
28     middle::exported_symbols::{
29         ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
30     },
31     ty::{query::ExternProviders, TyCtxt},
32 };
33 use rustc_session::{config::CrateType, search_paths::PathKind, CtfeBacktrace};
34
35 use miri::{BacktraceStyle, ProvenanceMode, RetagFields};
36
37 struct MiriCompilerCalls {
38     miri_config: miri::MiriConfig,
39 }
40
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));
52                 crate_source
53             };
54         });
55     }
56
57     fn after_analysis<'tcx>(
58         &mut self,
59         compiler: &rustc_interface::interface::Compiler,
60         queries: &'tcx rustc_interface::Queries<'tcx>,
61     ) -> Compilation {
62         compiler.session().abort_if_errors();
63
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");
68             }
69
70             let (entry_def_id, entry_type) = if let Some(entry_def) = tcx.entry_fn(()) {
71                 entry_def
72             } else {
73                 tcx.sess.fatal("miri can only run programs that have a main function");
74             };
75             let mut config = self.miri_config.clone();
76
77             // Add filename to `miri` arguments.
78             config.args.insert(0, compiler.input().filestem().to_string());
79
80             // Adjust working directory for interpretation.
81             if let Some(cwd) = env::var_os("MIRI_CWD") {
82                 env::set_current_dir(cwd).unwrap();
83             }
84
85             if let Some(return_code) = miri::eval_entry(tcx, entry_def_id, entry_type, config) {
86                 std::process::exit(
87                     i32::try_from(return_code).expect("Return value was too large!"),
88                 );
89             }
90         });
91
92         compiler.session().abort_if_errors();
93
94         Compilation::Stop
95     }
96 }
97
98 struct MiriBeRustCompilerCalls {
99     target_crate: bool,
100 }
101
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(
114                         // This is based on:
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(..),
126                                     ..
127                                 }) | Node::ImplItem(&hir::ImplItem {
128                                     kind: hir::ImplItemKind::Fn(..),
129                                     ..
130                                 })
131                                 if !tcx.generics_of(local_def_id).requires_monomorphization(tcx)
132                             );
133                             (is_reachable_non_generic
134                                 && tcx.codegen_fn_attrs(local_def_id).contains_extern_indicator())
135                             .then_some((
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
139                                 // is ignored.
140                                 SymbolExportInfo {
141                                     level: SymbolExportLevel::C,
142                                     kind: SymbolExportKind::Text,
143                                     used: false,
144                                 },
145                             ))
146                         }),
147                     )
148                 }
149             });
150         }
151     }
152 }
153
154 fn show_error(msg: &impl std::fmt::Display) -> ! {
155     eprintln!("fatal error: {msg}");
156     std::process::exit(1)
157 }
158
159 macro_rules! show_error {
160     ($($tt:tt)*) => { show_error(&format_args!($($tt)*)) };
161 }
162
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");
171     }
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();
178     }
179 }
180
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() {
193                 env::set_var(
194                     "RUSTC_LOG",
195                     format!(
196                         "rustc_middle::mir::interpret={0},rustc_const_eval::interpret={0}",
197                         var
198                     ),
199                 );
200             } else {
201                 env::set_var("RUSTC_LOG", &var);
202             }
203             rustc_driver::init_rustc_env_logger();
204         }
205     }
206
207     // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.
208     // Do this late, so we ideally only apply this to Miri's errors.
209     if let Some(val) = env::var_os("MIRI_BACKTRACE") {
210         let ctfe_backtrace = match &*val.to_string_lossy() {
211             "immediate" => CtfeBacktrace::Immediate,
212             "0" => CtfeBacktrace::Disabled,
213             _ => CtfeBacktrace::Capture,
214         };
215         *tcx.sess.ctfe_backtrace.borrow_mut() = ctfe_backtrace;
216     }
217 }
218
219 /// Execute a compiler with the given CLI arguments and callbacks.
220 fn run_compiler(
221     mut args: Vec<String>,
222     target_crate: bool,
223     callbacks: &mut (dyn rustc_driver::Callbacks + Send),
224 ) -> ! {
225     if target_crate {
226         // Miri needs a custom sysroot for target crates.
227         // If no `--sysroot` is given, the `MIRI_SYSROOT` env var is consulted to find where
228         // that sysroot lives, and that is passed to rustc.
229         let sysroot_flag = "--sysroot";
230         if !args.iter().any(|e| e == sysroot_flag) {
231             // Using the built-in default here would be plain wrong, so we *require*
232             // the env var to make sure things make sense.
233             let miri_sysroot = env::var("MIRI_SYSROOT").unwrap_or_else(|_| {
234                 show_error!(
235                     "Miri was invoked in 'target' mode without `MIRI_SYSROOT` or `--sysroot` being set"
236                     )
237             });
238
239             args.push(sysroot_flag.to_owned());
240             args.push(miri_sysroot);
241         }
242     }
243
244     // Don't insert `MIRI_DEFAULT_ARGS`, in particular, `--cfg=miri`, if we are building
245     // a "host" crate. That may cause procedural macros (and probably build scripts) to
246     // depend on Miri-only symbols, such as `miri_resolve_frame`:
247     // https://github.com/rust-lang/miri/issues/1760
248     if target_crate {
249         // Some options have different defaults in Miri than in plain rustc; apply those by making
250         // them the first arguments after the binary name (but later arguments can overwrite them).
251         args.splice(1..1, miri::MIRI_DEFAULT_ARGS.iter().map(ToString::to_string));
252     }
253
254     // Invoke compiler, and handle return code.
255     let exit_code = rustc_driver::catch_with_exit_code(move || {
256         rustc_driver::RunCompiler::new(&args, callbacks).run()
257     });
258     std::process::exit(exit_code)
259 }
260
261 /// Parses a comma separated list of `T` from the given string:
262 ///
263 /// `<value1>,<value2>,<value3>,...`
264 fn parse_comma_list<T: FromStr>(input: &str) -> Result<Vec<T>, T::Err> {
265     input.split(',').map(str::parse::<T>).collect()
266 }
267
268 fn main() {
269     // Snapshot a copy of the environment before `rustc` starts messing with it.
270     // (`install_ice_hook` might change `RUST_BACKTRACE`.)
271     let env_snapshot = env::vars_os().collect::<Vec<_>>();
272
273     // Earliest rustc setup.
274     rustc_driver::install_ice_hook();
275
276     // If the environment asks us to actually be rustc, then do that.
277     if let Some(crate_kind) = env::var_os("MIRI_BE_RUSTC") {
278         rustc_driver::init_rustc_env_logger();
279
280         let target_crate = if crate_kind == "target" {
281             true
282         } else if crate_kind == "host" {
283             false
284         } else {
285             panic!("invalid `MIRI_BE_RUSTC` value: {crate_kind:?}")
286         };
287
288         // We cannot use `rustc_driver::main` as we need to adjust the CLI arguments.
289         run_compiler(
290             env::args().collect(),
291             target_crate,
292             &mut MiriBeRustCompilerCalls { target_crate },
293         )
294     }
295
296     // Init loggers the Miri way.
297     init_early_loggers();
298
299     // Parse our arguments and split them across `rustc` and `miri`.
300     let mut miri_config = miri::MiriConfig::default();
301     miri_config.env = env_snapshot;
302
303     let mut rustc_args = vec![];
304     let mut after_dashdash = false;
305
306     // If user has explicitly enabled/disabled isolation
307     let mut isolation_enabled: Option<bool> = None;
308     for arg in env::args() {
309         if rustc_args.is_empty() {
310             // Very first arg: binary name.
311             rustc_args.push(arg);
312         } else if after_dashdash {
313             // Everything that comes after `--` is forwarded to the interpreted crate.
314             miri_config.args.push(arg);
315         } else if arg == "--" {
316             after_dashdash = true;
317         } else if arg == "-Zmiri-disable-validation" {
318             miri_config.validate = false;
319         } else if arg == "-Zmiri-disable-stacked-borrows" {
320             miri_config.stacked_borrows = false;
321         } else if arg == "-Zmiri-disable-data-race-detector" {
322             miri_config.data_race_detector = false;
323             miri_config.weak_memory_emulation = false;
324         } else if arg == "-Zmiri-disable-alignment-check" {
325             miri_config.check_alignment = miri::AlignmentCheck::None;
326         } else if arg == "-Zmiri-symbolic-alignment-check" {
327             miri_config.check_alignment = miri::AlignmentCheck::Symbolic;
328         } else if arg == "-Zmiri-check-number-validity" {
329             eprintln!(
330                 "WARNING: the flag `-Zmiri-check-number-validity` no longer has any effect \
331                         since it is now enabled by default"
332             );
333         } else if arg == "-Zmiri-disable-abi-check" {
334             miri_config.check_abi = false;
335         } else if arg == "-Zmiri-disable-isolation" {
336             if matches!(isolation_enabled, Some(true)) {
337                 show_error!(
338                     "-Zmiri-disable-isolation cannot be used along with -Zmiri-isolation-error"
339                 );
340             } else {
341                 isolation_enabled = Some(false);
342             }
343             miri_config.isolated_op = miri::IsolatedOp::Allow;
344         } else if arg == "-Zmiri-disable-weak-memory-emulation" {
345             miri_config.weak_memory_emulation = false;
346         } else if arg == "-Zmiri-track-weak-memory-loads" {
347             miri_config.track_outdated_loads = true;
348         } else if let Some(param) = arg.strip_prefix("-Zmiri-isolation-error=") {
349             if matches!(isolation_enabled, Some(false)) {
350                 show_error!(
351                     "-Zmiri-isolation-error cannot be used along with -Zmiri-disable-isolation"
352                 );
353             } else {
354                 isolation_enabled = Some(true);
355             }
356
357             miri_config.isolated_op = match param {
358                 "abort" => miri::IsolatedOp::Reject(miri::RejectOpWith::Abort),
359                 "hide" => miri::IsolatedOp::Reject(miri::RejectOpWith::NoWarning),
360                 "warn" => miri::IsolatedOp::Reject(miri::RejectOpWith::Warning),
361                 "warn-nobacktrace" =>
362                     miri::IsolatedOp::Reject(miri::RejectOpWith::WarningWithoutBacktrace),
363                 _ =>
364                     show_error!(
365                         "-Zmiri-isolation-error must be `abort`, `hide`, `warn`, or `warn-nobacktrace`"
366                     ),
367             };
368         } else if arg == "-Zmiri-ignore-leaks" {
369             miri_config.ignore_leaks = true;
370         } else if arg == "-Zmiri-panic-on-unsupported" {
371             miri_config.panic_on_unsupported = true;
372         } else if arg == "-Zmiri-tag-raw-pointers" {
373             eprintln!("WARNING: `-Zmiri-tag-raw-pointers` has no effect; it is enabled by default");
374         } else if arg == "-Zmiri-strict-provenance" {
375             miri_config.provenance_mode = ProvenanceMode::Strict;
376         } else if arg == "-Zmiri-permissive-provenance" {
377             miri_config.provenance_mode = ProvenanceMode::Permissive;
378         } else if arg == "-Zmiri-mute-stdout-stderr" {
379             miri_config.mute_stdout_stderr = true;
380         } else if arg == "-Zmiri-retag-fields" {
381             miri_config.retag_fields = RetagFields::Yes;
382         } else if let Some(retag_fields) = arg.strip_prefix("-Zmiri-retag-fields=") {
383             miri_config.retag_fields = match retag_fields {
384                 "all" => RetagFields::Yes,
385                 "none" => RetagFields::No,
386                 "scalar" => RetagFields::OnlyScalar,
387                 _ => show_error!("`-Zmiri-retag-fields` can only be `all`, `none`, or `scalar`"),
388             };
389         } else if arg == "-Zmiri-track-raw-pointers" {
390             eprintln!(
391                 "WARNING: `-Zmiri-track-raw-pointers` has no effect; it is enabled by default"
392             );
393         } else if let Some(param) = arg.strip_prefix("-Zmiri-seed=") {
394             if miri_config.seed.is_some() {
395                 show_error!("Cannot specify -Zmiri-seed multiple times!");
396             }
397             let seed = param.parse::<u64>().unwrap_or_else(|_| {
398                 show_error!("-Zmiri-seed must be an integer that fits into u64")
399             });
400             miri_config.seed = Some(seed);
401         } else if let Some(_param) = arg.strip_prefix("-Zmiri-env-exclude=") {
402             show_error!(
403                 "`-Zmiri-env-exclude` has been removed; unset env vars before starting Miri instead"
404             );
405         } else if let Some(param) = arg.strip_prefix("-Zmiri-env-forward=") {
406             miri_config.forwarded_env_vars.push(param.to_owned());
407         } else if let Some(param) = arg.strip_prefix("-Zmiri-track-pointer-tag=") {
408             let ids: Vec<u64> = match parse_comma_list(param) {
409                 Ok(ids) => ids,
410                 Err(err) =>
411                     show_error!(
412                         "-Zmiri-track-pointer-tag requires a comma separated list of valid `u64` arguments: {}",
413                         err
414                     ),
415             };
416             for id in ids.into_iter().map(miri::SbTag::new) {
417                 if let Some(id) = id {
418                     miri_config.tracked_pointer_tags.insert(id);
419                 } else {
420                     show_error!("-Zmiri-track-pointer-tag requires nonzero arguments");
421                 }
422             }
423         } else if let Some(param) = arg.strip_prefix("-Zmiri-track-call-id=") {
424             let ids: Vec<u64> = match parse_comma_list(param) {
425                 Ok(ids) => ids,
426                 Err(err) =>
427                     show_error!(
428                         "-Zmiri-track-call-id requires a comma separated list of valid `u64` arguments: {}",
429                         err
430                     ),
431             };
432             for id in ids.into_iter().map(miri::CallId::new) {
433                 if let Some(id) = id {
434                     miri_config.tracked_call_ids.insert(id);
435                 } else {
436                     show_error!("-Zmiri-track-call-id requires a nonzero argument");
437                 }
438             }
439         } else if let Some(param) = arg.strip_prefix("-Zmiri-track-alloc-id=") {
440             let ids: Vec<miri::AllocId> = match parse_comma_list::<NonZeroU64>(param) {
441                 Ok(ids) => ids.into_iter().map(miri::AllocId).collect(),
442                 Err(err) =>
443                     show_error!(
444                         "-Zmiri-track-alloc-id requires a comma separated list of valid non-zero `u64` arguments: {}",
445                         err
446                     ),
447             };
448             miri_config.tracked_alloc_ids.extend(ids);
449         } else if let Some(param) = arg.strip_prefix("-Zmiri-compare-exchange-weak-failure-rate=") {
450             let rate = match param.parse::<f64>() {
451                 Ok(rate) if rate >= 0.0 && rate <= 1.0 => rate,
452                 Ok(_) =>
453                     show_error!(
454                         "-Zmiri-compare-exchange-weak-failure-rate must be between `0.0` and `1.0`"
455                     ),
456                 Err(err) =>
457                     show_error!(
458                         "-Zmiri-compare-exchange-weak-failure-rate requires a `f64` between `0.0` and `1.0`: {}",
459                         err
460                     ),
461             };
462             miri_config.cmpxchg_weak_failure_rate = rate;
463         } else if let Some(param) = arg.strip_prefix("-Zmiri-preemption-rate=") {
464             let rate = match param.parse::<f64>() {
465                 Ok(rate) if rate >= 0.0 && rate <= 1.0 => rate,
466                 Ok(_) => show_error!("-Zmiri-preemption-rate must be between `0.0` and `1.0`"),
467                 Err(err) =>
468                     show_error!(
469                         "-Zmiri-preemption-rate requires a `f64` between `0.0` and `1.0`: {}",
470                         err
471                     ),
472             };
473             miri_config.preemption_rate = rate;
474         } else if arg == "-Zmiri-report-progress" {
475             // This makes it take a few seconds between progress reports on my laptop.
476             miri_config.report_progress = Some(1_000_000);
477         } else if let Some(param) = arg.strip_prefix("-Zmiri-report-progress=") {
478             let interval = match param.parse::<u32>() {
479                 Ok(i) => i,
480                 Err(err) => show_error!("-Zmiri-report-progress requires a `u32`: {}", err),
481             };
482             miri_config.report_progress = Some(interval);
483         } else if let Some(param) = arg.strip_prefix("-Zmiri-tag-gc=") {
484             let interval = match param.parse::<u32>() {
485                 Ok(i) => i,
486                 Err(err) => show_error!("-Zmiri-tag-gc requires a `u32`: {}", err),
487             };
488             miri_config.gc_interval = interval;
489         } else if let Some(param) = arg.strip_prefix("-Zmiri-measureme=") {
490             miri_config.measureme_out = Some(param.to_string());
491         } else if let Some(param) = arg.strip_prefix("-Zmiri-backtrace=") {
492             miri_config.backtrace_style = match param {
493                 "0" => BacktraceStyle::Off,
494                 "1" => BacktraceStyle::Short,
495                 "full" => BacktraceStyle::Full,
496                 _ => show_error!("-Zmiri-backtrace may only be 0, 1, or full"),
497             };
498         } else if let Some(param) = arg.strip_prefix("-Zmiri-extern-so-file=") {
499             let filename = param.to_string();
500             if std::path::Path::new(&filename).exists() {
501                 if let Some(other_filename) = miri_config.external_so_file {
502                     show_error!(
503                         "-Zmiri-extern-so-file is already set to {}",
504                         other_filename.display()
505                     );
506                 }
507                 miri_config.external_so_file = Some(filename.into());
508             } else {
509                 show_error!("-Zmiri-extern-so-file `{}` does not exist", filename);
510             }
511         } else if let Some(param) = arg.strip_prefix("-Zmiri-num-cpus=") {
512             let num_cpus = match param.parse::<u32>() {
513                 Ok(i) => i,
514                 Err(err) => show_error!("-Zmiri-num-cpus requires a `u32`: {}", err),
515             };
516
517             miri_config.num_cpus = num_cpus;
518         } else {
519             // Forward to rustc.
520             rustc_args.push(arg);
521         }
522     }
523
524     debug!("rustc arguments: {:?}", rustc_args);
525     debug!("crate arguments: {:?}", miri_config.args);
526     run_compiler(rustc_args, /* target_crate: */ true, &mut MiriCompilerCalls { miri_config })
527 }