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