]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/eval.rs
Auto merge of #99099 - Stargateur:phantomdata_debug, r=joshtriplett
[rust.git] / src / tools / miri / src / eval.rs
1 //! Main evaluator loop and setting up the initial stack frame.
2
3 use std::ffi::{OsStr, OsString};
4 use std::iter;
5 use std::panic::{self, AssertUnwindSafe};
6 use std::path::PathBuf;
7 use std::thread;
8
9 use log::info;
10
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_hir::def_id::DefId;
13 use rustc_middle::ty::{
14     self,
15     layout::{LayoutCx, LayoutOf},
16     TyCtxt,
17 };
18 use rustc_target::spec::abi::Abi;
19
20 use rustc_session::config::EntryFnType;
21
22 use crate::*;
23
24 #[derive(Copy, Clone, Debug, PartialEq)]
25 pub enum AlignmentCheck {
26     /// Do not check alignment.
27     None,
28     /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
29     Symbolic,
30     /// Check alignment on the actual physical integer address.
31     Int,
32 }
33
34 #[derive(Copy, Clone, Debug, PartialEq)]
35 pub enum RejectOpWith {
36     /// Isolated op is rejected with an abort of the machine.
37     Abort,
38
39     /// If not Abort, miri returns an error for an isolated op.
40     /// Following options determine if user should be warned about such error.
41     /// Do not print warning about rejected isolated op.
42     NoWarning,
43
44     /// Print a warning about rejected isolated op, with backtrace.
45     Warning,
46
47     /// Print a warning about rejected isolated op, without backtrace.
48     WarningWithoutBacktrace,
49 }
50
51 #[derive(Copy, Clone, Debug, PartialEq)]
52 pub enum IsolatedOp {
53     /// Reject an op requiring communication with the host. By
54     /// default, miri rejects the op with an abort. If not, it returns
55     /// an error code, and prints a warning about it. Warning levels
56     /// are controlled by `RejectOpWith` enum.
57     Reject(RejectOpWith),
58
59     /// Execute op requiring communication with the host, i.e. disable isolation.
60     Allow,
61 }
62
63 #[derive(Copy, Clone, PartialEq, Eq)]
64 pub enum BacktraceStyle {
65     /// Prints a terser backtrace which ideally only contains relevant information.
66     Short,
67     /// Prints a backtrace with all possible information.
68     Full,
69     /// Prints only the frame that the error occurs in.
70     Off,
71 }
72
73 /// Configuration needed to spawn a Miri instance.
74 #[derive(Clone)]
75 pub struct MiriConfig {
76     /// The host environment snapshot to use as basis for what is provided to the interpreted program.
77     /// (This is still subject to isolation as well as `forwarded_env_vars`.)
78     pub env: Vec<(OsString, OsString)>,
79     /// Determine if validity checking is enabled.
80     pub validate: bool,
81     /// Determines if Stacked Borrows is enabled.
82     pub stacked_borrows: bool,
83     /// Controls alignment checking.
84     pub check_alignment: AlignmentCheck,
85     /// Controls function [ABI](Abi) checking.
86     pub check_abi: bool,
87     /// Action for an op requiring communication with the host.
88     pub isolated_op: IsolatedOp,
89     /// Determines if memory leaks should be ignored.
90     pub ignore_leaks: bool,
91     /// Environment variables that should always be forwarded from the host.
92     pub forwarded_env_vars: Vec<String>,
93     /// Command-line arguments passed to the interpreted program.
94     pub args: Vec<String>,
95     /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
96     pub seed: Option<u64>,
97     /// The stacked borrows pointer ids to report about
98     pub tracked_pointer_tags: FxHashSet<SbTag>,
99     /// The stacked borrows call IDs to report about
100     pub tracked_call_ids: FxHashSet<CallId>,
101     /// The allocation ids to report about.
102     pub tracked_alloc_ids: FxHashSet<AllocId>,
103     /// Determine if data race detection should be enabled
104     pub data_race_detector: bool,
105     /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled
106     pub weak_memory_emulation: bool,
107     /// Track when an outdated (weak memory) load happens.
108     pub track_outdated_loads: bool,
109     /// Rate of spurious failures for compare_exchange_weak atomic operations,
110     /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
111     pub cmpxchg_weak_failure_rate: f64,
112     /// If `Some`, enable the `measureme` profiler, writing results to a file
113     /// with the specified prefix.
114     pub measureme_out: Option<String>,
115     /// Panic when unsupported functionality is encountered.
116     pub panic_on_unsupported: bool,
117     /// Which style to use for printing backtraces.
118     pub backtrace_style: BacktraceStyle,
119     /// Which provenance to use for int2ptr casts
120     pub provenance_mode: ProvenanceMode,
121     /// Whether to ignore any output by the program. This is helpful when debugging miri
122     /// as its messages don't get intermingled with the program messages.
123     pub mute_stdout_stderr: bool,
124     /// The probability of the active thread being preempted at the end of each basic block.
125     pub preemption_rate: f64,
126     /// Report the current instruction being executed every N basic blocks.
127     pub report_progress: Option<u32>,
128     /// Whether Stacked Borrows retagging should recurse into fields of datatypes.
129     pub retag_fields: bool,
130     /// The location of a shared object file to load when calling external functions
131     /// FIXME! consider allowing users to specify paths to multiple SO files, or to a directory
132     pub external_so_file: Option<PathBuf>,
133     /// Run a garbage collector for SbTags every N basic blocks.
134     pub gc_interval: u32,
135 }
136
137 impl Default for MiriConfig {
138     fn default() -> MiriConfig {
139         MiriConfig {
140             env: vec![],
141             validate: true,
142             stacked_borrows: true,
143             check_alignment: AlignmentCheck::Int,
144             check_abi: true,
145             isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
146             ignore_leaks: false,
147             forwarded_env_vars: vec![],
148             args: vec![],
149             seed: None,
150             tracked_pointer_tags: FxHashSet::default(),
151             tracked_call_ids: FxHashSet::default(),
152             tracked_alloc_ids: FxHashSet::default(),
153             data_race_detector: true,
154             weak_memory_emulation: true,
155             track_outdated_loads: false,
156             cmpxchg_weak_failure_rate: 0.8, // 80%
157             measureme_out: None,
158             panic_on_unsupported: false,
159             backtrace_style: BacktraceStyle::Short,
160             provenance_mode: ProvenanceMode::Default,
161             mute_stdout_stderr: false,
162             preemption_rate: 0.01, // 1%
163             report_progress: None,
164             retag_fields: false,
165             external_so_file: None,
166             gc_interval: 10_000,
167         }
168     }
169 }
170
171 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
172 /// the location where the return value of the `start` function will be
173 /// written to.
174 /// Public because this is also used by `priroda`.
175 pub fn create_ecx<'mir, 'tcx: 'mir>(
176     tcx: TyCtxt<'tcx>,
177     entry_id: DefId,
178     entry_type: EntryFnType,
179     config: &MiriConfig,
180 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>, MPlaceTy<'tcx, Provenance>)>
181 {
182     let param_env = ty::ParamEnv::reveal_all();
183     let layout_cx = LayoutCx { tcx, param_env };
184     let mut ecx = InterpCx::new(
185         tcx,
186         rustc_span::source_map::DUMMY_SP,
187         param_env,
188         MiriMachine::new(config, layout_cx),
189     );
190
191     // Some parts of initialization require a full `InterpCx`.
192     MiriMachine::late_init(&mut ecx, config)?;
193
194     // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore.
195     let sentinel = ecx.try_resolve_path(&["core", "ascii", "escape_default"]);
196     if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
197         tcx.sess.fatal(
198             "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
199             Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
200         );
201     }
202
203     // Setup first stack frame.
204     let entry_instance = ty::Instance::mono(tcx, entry_id);
205
206     // First argument is constructed later, because it's skipped if the entry function uses #[start].
207
208     // Second argument (argc): length of `config.args`.
209     let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
210     // Third argument (`argv`): created from `config.args`.
211     let argv = {
212         // Put each argument in memory, collect pointers.
213         let mut argvs = Vec::<Immediate<Provenance>>::new();
214         for arg in config.args.iter() {
215             // Make space for `0` terminator.
216             let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
217             let arg_type = tcx.mk_array(tcx.types.u8, size);
218             let arg_place =
219                 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
220             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
221             ecx.mark_immutable(&arg_place);
222             argvs.push(arg_place.to_ref(&ecx));
223         }
224         // Make an array with all these pointers, in the Miri memory.
225         let argvs_layout = ecx.layout_of(
226             tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
227         )?;
228         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
229         for (idx, arg) in argvs.into_iter().enumerate() {
230             let place = ecx.mplace_field(&argvs_place, idx)?;
231             ecx.write_immediate(arg, &place.into())?;
232         }
233         ecx.mark_immutable(&argvs_place);
234         // A pointer to that place is the 3rd argument for main.
235         let argv = argvs_place.to_ref(&ecx);
236         // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
237         {
238             let argc_place =
239                 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
240             ecx.write_scalar(argc, &argc_place.into())?;
241             ecx.mark_immutable(&argc_place);
242             ecx.machine.argc = Some(*argc_place);
243
244             let argv_place = ecx.allocate(
245                 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
246                 MiriMemoryKind::Machine.into(),
247             )?;
248             ecx.write_immediate(argv, &argv_place.into())?;
249             ecx.mark_immutable(&argv_place);
250             ecx.machine.argv = Some(*argv_place);
251         }
252         // Store command line as UTF-16 for Windows `GetCommandLineW`.
253         {
254             // Construct a command string with all the arguments.
255             let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
256
257             let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
258             let cmd_place =
259                 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
260             ecx.machine.cmd_line = Some(*cmd_place);
261             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
262             for (idx, &c) in cmd_utf16.iter().enumerate() {
263                 let place = ecx.mplace_field(&cmd_place, idx)?;
264                 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
265             }
266             ecx.mark_immutable(&cmd_place);
267         }
268         argv
269     };
270
271     // Return place (in static memory so that it does not count as leak).
272     let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
273     // Call start function.
274
275     match entry_type {
276         EntryFnType::Main { .. } => {
277             let start_id = tcx.lang_items().start_fn().unwrap();
278             let main_ret_ty = tcx.fn_sig(entry_id).output();
279             let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
280             let start_instance = ty::Instance::resolve(
281                 tcx,
282                 ty::ParamEnv::reveal_all(),
283                 start_id,
284                 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
285             )
286             .unwrap()
287             .unwrap();
288
289             let main_ptr = ecx.create_fn_alloc_ptr(FnVal::Instance(entry_instance));
290
291             // Inlining of `DEFAULT` from
292             // https://github.com/rust-lang/rust/blob/master/compiler/rustc_session/src/config/sigpipe.rs.
293             // Alaways using DEFAULT is okay since we don't support signals in Miri anyway.
294             let sigpipe = 2;
295
296             ecx.call_function(
297                 start_instance,
298                 Abi::Rust,
299                 &[
300                     Scalar::from_pointer(main_ptr, &ecx).into(),
301                     argc.into(),
302                     argv,
303                     Scalar::from_u8(sigpipe).into(),
304                 ],
305                 Some(&ret_place.into()),
306                 StackPopCleanup::Root { cleanup: true },
307             )?;
308         }
309         EntryFnType::Start => {
310             ecx.call_function(
311                 entry_instance,
312                 Abi::Rust,
313                 &[argc.into(), argv],
314                 Some(&ret_place.into()),
315                 StackPopCleanup::Root { cleanup: true },
316             )?;
317         }
318     }
319
320     Ok((ecx, ret_place))
321 }
322
323 /// Evaluates the entry function specified by `entry_id`.
324 /// Returns `Some(return_code)` if program executed completed.
325 /// Returns `None` if an evaluation error occurred.
326 #[allow(clippy::needless_lifetimes)]
327 pub fn eval_entry<'tcx>(
328     tcx: TyCtxt<'tcx>,
329     entry_id: DefId,
330     entry_type: EntryFnType,
331     config: MiriConfig,
332 ) -> Option<i64> {
333     // Copy setting before we move `config`.
334     let ignore_leaks = config.ignore_leaks;
335
336     let (mut ecx, ret_place) = match create_ecx(tcx, entry_id, entry_type, &config) {
337         Ok(v) => v,
338         Err(err) => {
339             err.print_backtrace();
340             panic!("Miri initialization error: {}", err.kind())
341         }
342     };
343
344     // Perform the main execution.
345     let res: thread::Result<InterpResult<'_, i64>> = panic::catch_unwind(AssertUnwindSafe(|| {
346         // Main loop.
347         loop {
348             match ecx.schedule()? {
349                 SchedulingAction::ExecuteStep => {
350                     assert!(ecx.step()?, "a terminated thread was scheduled for execution");
351                 }
352                 SchedulingAction::ExecuteTimeoutCallback => {
353                     ecx.run_timeout_callback()?;
354                 }
355                 SchedulingAction::ExecuteDtors => {
356                     // This will either enable the thread again (so we go back
357                     // to `ExecuteStep`), or determine that this thread is done
358                     // for good.
359                     ecx.schedule_next_tls_dtor_for_active_thread()?;
360                 }
361                 SchedulingAction::Stop => {
362                     break;
363                 }
364             }
365         }
366         let return_code = ecx.read_scalar(&ret_place.into())?.to_machine_isize(&ecx)?;
367         Ok(return_code)
368     }));
369     let res = res.unwrap_or_else(|panic_payload| {
370         ecx.handle_ice();
371         panic::resume_unwind(panic_payload)
372     });
373
374     // Machine cleanup. Only do this if all threads have terminated; threads that are still running
375     // might cause Stacked Borrows errors (https://github.com/rust-lang/miri/issues/2396).
376     if ecx.have_all_terminated() {
377         // Even if all threads have terminated, we have to beware of data races since some threads
378         // might not have joined the main thread (https://github.com/rust-lang/miri/issues/2020,
379         // https://github.com/rust-lang/miri/issues/2508).
380         ecx.allow_data_races_all_threads_done();
381         EnvVars::cleanup(&mut ecx).expect("error during env var cleanup");
382     }
383
384     // Process the result.
385     match res {
386         Ok(return_code) => {
387             if !ignore_leaks {
388                 // Check for thread leaks.
389                 if !ecx.have_all_terminated() {
390                     tcx.sess.err(
391                         "the main thread terminated without waiting for all remaining threads",
392                     );
393                     tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
394                     return None;
395                 }
396                 // Check for memory leaks.
397                 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
398                 let leaks = ecx.leak_report(&ecx.machine.static_roots);
399                 if leaks != 0 {
400                     tcx.sess.err("the evaluated program leaked memory");
401                     tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
402                     // Ignore the provided return code - let the reported error
403                     // determine the return code.
404                     return None;
405                 }
406             }
407             Some(return_code)
408         }
409         Err(e) => report_error(&ecx, e),
410     }
411 }
412
413 /// Turns an array of arguments into a Windows command line string.
414 ///
415 /// The string will be UTF-16 encoded and NUL terminated.
416 ///
417 /// Panics if the zeroth argument contains the `"` character because doublequotes
418 /// in `argv[0]` cannot be encoded using the standard command line parsing rules.
419 ///
420 /// Further reading:
421 /// * [Parsing C++ command-line arguments](https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments)
422 /// * [The C/C++ Parameter Parsing Rules](https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES)
423 fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
424 where
425     I: Iterator<Item = T>,
426     T: AsRef<str>,
427 {
428     // Parse argv[0]. Slashes aren't escaped. Literal double quotes are not allowed.
429     let mut cmd = {
430         let arg0 = if let Some(arg0) = args.next() {
431             arg0
432         } else {
433             return vec![0];
434         };
435         let arg0 = arg0.as_ref();
436         if arg0.contains('"') {
437             panic!("argv[0] cannot contain a doublequote (\") character");
438         } else {
439             // Always surround argv[0] with quotes.
440             let mut s = String::new();
441             s.push('"');
442             s.push_str(arg0);
443             s.push('"');
444             s
445         }
446     };
447
448     // Build the other arguments.
449     for arg in args {
450         let arg = arg.as_ref();
451         cmd.push(' ');
452         if arg.is_empty() {
453             cmd.push_str("\"\"");
454         } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
455             // No quote, tab, or space -- no escaping required.
456             cmd.push_str(arg);
457         } else {
458             // Spaces and tabs are escaped by surrounding them in quotes.
459             // Quotes are themselves escaped by using backslashes when in a
460             // quoted block.
461             // Backslashes only need to be escaped when one or more are directly
462             // followed by a quote. Otherwise they are taken literally.
463
464             cmd.push('"');
465             let mut chars = arg.chars().peekable();
466             loop {
467                 let mut nslashes = 0;
468                 while let Some(&'\\') = chars.peek() {
469                     chars.next();
470                     nslashes += 1;
471                 }
472
473                 match chars.next() {
474                     Some('"') => {
475                         cmd.extend(iter::repeat('\\').take(nslashes * 2 + 1));
476                         cmd.push('"');
477                     }
478                     Some(c) => {
479                         cmd.extend(iter::repeat('\\').take(nslashes));
480                         cmd.push(c);
481                     }
482                     None => {
483                         cmd.extend(iter::repeat('\\').take(nslashes * 2));
484                         break;
485                     }
486                 }
487             }
488             cmd.push('"');
489         }
490     }
491
492     if cmd.contains('\0') {
493         panic!("interior null in command line arguments");
494     }
495     cmd.encode_utf16().chain(iter::once(0)).collect()
496 }
497
498 #[cfg(test)]
499 mod tests {
500     use super::*;
501     #[test]
502     #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
503     fn windows_argv0_panic_on_quote() {
504         args_to_utf16_command_string(["\""].iter());
505     }
506     #[test]
507     fn windows_argv0_no_escape() {
508         // Ensure that a trailing backslash in argv[0] is not escaped.
509         let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
510             [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
511         ));
512         assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);
513     }
514 }