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