]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
rustup
[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 function [ABI](Abi) checking.
82     pub check_abi: bool,
83     /// Action for an op requiring communication with the host.
84     pub isolated_op: IsolatedOp,
85     /// Determines if memory leaks should be ignored.
86     pub ignore_leaks: bool,
87     /// Environment variables that should always be isolated from the host.
88     pub excluded_env_vars: Vec<String>,
89     /// Environment variables that should always be forwarded from the host.
90     pub forwarded_env_vars: Vec<String>,
91     /// Command-line arguments passed to the interpreted program.
92     pub args: Vec<String>,
93     /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
94     pub seed: Option<u64>,
95     /// The stacked borrows pointer ids to report about
96     pub tracked_pointer_tags: HashSet<SbTag>,
97     /// The stacked borrows call IDs to report about
98     pub tracked_call_ids: HashSet<CallId>,
99     /// The allocation ids to report about.
100     pub tracked_alloc_ids: HashSet<AllocId>,
101     /// Determine if data race detection should be enabled
102     pub data_race_detector: bool,
103     /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled
104     pub weak_memory_emulation: bool,
105     /// Rate of spurious failures for compare_exchange_weak atomic operations,
106     /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
107     pub cmpxchg_weak_failure_rate: f64,
108     /// If `Some`, enable the `measureme` profiler, writing results to a file
109     /// with the specified prefix.
110     pub measureme_out: Option<String>,
111     /// Panic when unsupported functionality is encountered.
112     pub panic_on_unsupported: bool,
113     /// Which style to use for printing backtraces.
114     pub backtrace_style: BacktraceStyle,
115     /// Which provenance to use for int2ptr casts
116     pub provenance_mode: ProvenanceMode,
117     /// Whether to ignore any output by the program. This is helpful when debugging miri
118     /// as its messages don't get intermingled with the program messages.
119     pub mute_stdout_stderr: bool,
120     /// The probability of the active thread being preempted at the end of each basic block.
121     pub preemption_rate: f64,
122     /// Report the current instruction being executed every N basic blocks.
123     pub report_progress: Option<u32>,
124     /// Whether Stacked Borrows retagging should recurse into fields of datatypes.
125     pub retag_fields: bool,
126 }
127
128 impl Default for MiriConfig {
129     fn default() -> MiriConfig {
130         MiriConfig {
131             validate: true,
132             stacked_borrows: true,
133             check_alignment: AlignmentCheck::Int,
134             check_abi: true,
135             isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
136             ignore_leaks: false,
137             excluded_env_vars: vec![],
138             forwarded_env_vars: vec![],
139             args: vec![],
140             seed: None,
141             tracked_pointer_tags: HashSet::default(),
142             tracked_call_ids: HashSet::default(),
143             tracked_alloc_ids: HashSet::default(),
144             data_race_detector: true,
145             weak_memory_emulation: true,
146             cmpxchg_weak_failure_rate: 0.8, // 80%
147             measureme_out: None,
148             panic_on_unsupported: false,
149             backtrace_style: BacktraceStyle::Short,
150             provenance_mode: ProvenanceMode::Default,
151             mute_stdout_stderr: false,
152             preemption_rate: 0.01, // 1%
153             report_progress: None,
154             retag_fields: false,
155         }
156     }
157 }
158
159 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
160 /// the location where the return value of the `start` function will be
161 /// written to.
162 /// Public because this is also used by `priroda`.
163 pub fn create_ecx<'mir, 'tcx: 'mir>(
164     tcx: TyCtxt<'tcx>,
165     entry_id: DefId,
166     entry_type: EntryFnType,
167     config: &MiriConfig,
168 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Provenance>)> {
169     let param_env = ty::ParamEnv::reveal_all();
170     let layout_cx = LayoutCx { tcx, param_env };
171     let mut ecx = InterpCx::new(
172         tcx,
173         rustc_span::source_map::DUMMY_SP,
174         param_env,
175         Evaluator::new(config, layout_cx),
176     );
177
178     // Capture the current interpreter stack state (which should be empty) so that we can emit
179     // allocation-tracking and tag-tracking diagnostics for allocations which are part of the
180     // early runtime setup.
181     let info = ecx.preprocess_diagnostics();
182
183     // Some parts of initialization require a full `InterpCx`.
184     Evaluator::late_init(&mut ecx, config)?;
185
186     // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore.
187     let sentinel = ecx.try_resolve_path(&["core", "ascii", "escape_default"]);
188     if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
189         tcx.sess.fatal(
190             "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
191             Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
192         );
193     }
194
195     // Setup first stack frame.
196     let entry_instance = ty::Instance::mono(tcx, entry_id);
197
198     // First argument is constructed later, because it's skipped if the entry function uses #[start].
199
200     // Second argument (argc): length of `config.args`.
201     let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
202     // Third argument (`argv`): created from `config.args`.
203     let argv = {
204         // Put each argument in memory, collect pointers.
205         let mut argvs = Vec::<Immediate<Provenance>>::new();
206         for arg in config.args.iter() {
207             // Make space for `0` terminator.
208             let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
209             let arg_type = tcx.mk_array(tcx.types.u8, size);
210             let arg_place =
211                 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
212             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
213             ecx.mark_immutable(&arg_place);
214             argvs.push(arg_place.to_ref(&ecx));
215         }
216         // Make an array with all these pointers, in the Miri memory.
217         let argvs_layout = ecx.layout_of(
218             tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
219         )?;
220         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
221         for (idx, arg) in argvs.into_iter().enumerate() {
222             let place = ecx.mplace_field(&argvs_place, idx)?;
223             ecx.write_immediate(arg, &place.into())?;
224         }
225         ecx.mark_immutable(&argvs_place);
226         // A pointer to that place is the 3rd argument for main.
227         let argv = argvs_place.to_ref(&ecx);
228         // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
229         {
230             let argc_place =
231                 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
232             ecx.write_scalar(argc, &argc_place.into())?;
233             ecx.mark_immutable(&argc_place);
234             ecx.machine.argc = Some(*argc_place);
235
236             let argv_place = ecx.allocate(
237                 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
238                 MiriMemoryKind::Machine.into(),
239             )?;
240             ecx.write_immediate(argv, &argv_place.into())?;
241             ecx.mark_immutable(&argv_place);
242             ecx.machine.argv = Some(*argv_place);
243         }
244         // Store command line as UTF-16 for Windows `GetCommandLineW`.
245         {
246             // Construct a command string with all the aguments.
247             let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
248
249             let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
250             let cmd_place =
251                 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
252             ecx.machine.cmd_line = Some(*cmd_place);
253             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
254             for (idx, &c) in cmd_utf16.iter().enumerate() {
255                 let place = ecx.mplace_field(&cmd_place, idx)?;
256                 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
257             }
258             ecx.mark_immutable(&cmd_place);
259         }
260         argv
261     };
262
263     // Return place (in static memory so that it does not count as leak).
264     let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
265     // Call start function.
266
267     match entry_type {
268         EntryFnType::Main => {
269             let start_id = tcx.lang_items().start_fn().unwrap();
270             let main_ret_ty = tcx.fn_sig(entry_id).output();
271             let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
272             let start_instance = ty::Instance::resolve(
273                 tcx,
274                 ty::ParamEnv::reveal_all(),
275                 start_id,
276                 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
277             )
278             .unwrap()
279             .unwrap();
280
281             let main_ptr = ecx.create_fn_alloc_ptr(FnVal::Instance(entry_instance));
282
283             ecx.call_function(
284                 start_instance,
285                 Abi::Rust,
286                 &[Scalar::from_pointer(main_ptr, &ecx).into(), argc.into(), argv],
287                 Some(&ret_place.into()),
288                 StackPopCleanup::Root { cleanup: true },
289             )?;
290         }
291         EntryFnType::Start => {
292             ecx.call_function(
293                 entry_instance,
294                 Abi::Rust,
295                 &[argc.into(), argv],
296                 Some(&ret_place.into()),
297                 StackPopCleanup::Root { cleanup: true },
298             )?;
299         }
300     }
301
302     // Emit any diagnostics related to the setup process for the runtime, so that when the
303     // interpreter loop starts there are no unprocessed diagnostics.
304     ecx.process_diagnostics(info);
305
306     Ok((ecx, ret_place))
307 }
308
309 /// Evaluates the entry function specified by `entry_id`.
310 /// Returns `Some(return_code)` if program executed completed.
311 /// Returns `None` if an evaluation error occured.
312 pub fn eval_entry<'tcx>(
313     tcx: TyCtxt<'tcx>,
314     entry_id: DefId,
315     entry_type: EntryFnType,
316     config: MiriConfig,
317 ) -> Option<i64> {
318     // Copy setting before we move `config`.
319     let ignore_leaks = config.ignore_leaks;
320
321     let (mut ecx, ret_place) = match create_ecx(tcx, entry_id, entry_type, &config) {
322         Ok(v) => v,
323         Err(err) => {
324             err.print_backtrace();
325             panic!("Miri initialization error: {}", err.kind())
326         }
327     };
328
329     // Perform the main execution.
330     let res: thread::Result<InterpResult<'_, i64>> = panic::catch_unwind(AssertUnwindSafe(|| {
331         // Main loop.
332         loop {
333             let info = ecx.preprocess_diagnostics();
334             match ecx.schedule()? {
335                 SchedulingAction::ExecuteStep => {
336                     assert!(ecx.step()?, "a terminated thread was scheduled for execution");
337                 }
338                 SchedulingAction::ExecuteTimeoutCallback => {
339                     assert!(
340                         ecx.machine.communicate(),
341                         "scheduler callbacks require disabled isolation, but the code \
342                         that created the callback did not check it"
343                     );
344                     ecx.run_timeout_callback()?;
345                 }
346                 SchedulingAction::ExecuteDtors => {
347                     // This will either enable the thread again (so we go back
348                     // to `ExecuteStep`), or determine that this thread is done
349                     // for good.
350                     ecx.schedule_next_tls_dtor_for_active_thread()?;
351                 }
352                 SchedulingAction::Stop => {
353                     break;
354                 }
355             }
356             ecx.process_diagnostics(info);
357         }
358         let return_code = ecx.read_scalar(&ret_place.into())?.to_machine_isize(&ecx)?;
359         Ok(return_code)
360     }));
361     let res = res.unwrap_or_else(|panic_payload| {
362         ecx.handle_ice();
363         panic::resume_unwind(panic_payload)
364     });
365
366     // Machine cleanup. Only do this if all threads have terminated; threads that are still running
367     // might cause data races (https://github.com/rust-lang/miri/issues/2020) or Stacked Borrows
368     // errors (https://github.com/rust-lang/miri/issues/2396) if we deallocate here.
369     if ecx.have_all_terminated() {
370         EnvVars::cleanup(&mut ecx).unwrap();
371     }
372
373     // Process the result.
374     match res {
375         Ok(return_code) => {
376             if !ignore_leaks {
377                 // Check for thread leaks.
378                 if !ecx.have_all_terminated() {
379                     tcx.sess.err(
380                         "the main thread terminated without waiting for all remaining threads",
381                     );
382                     tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
383                     return None;
384                 }
385                 // Check for memory leaks.
386                 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
387                 let leaks = ecx.leak_report(&ecx.machine.static_roots);
388                 if leaks != 0 {
389                     tcx.sess.err("the evaluated program leaked memory");
390                     tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
391                     // Ignore the provided return code - let the reported error
392                     // determine the return code.
393                     return None;
394                 }
395             }
396             Some(return_code)
397         }
398         Err(e) => report_error(&ecx, e),
399     }
400 }
401
402 /// Turns an array of arguments into a Windows command line string.
403 ///
404 /// The string will be UTF-16 encoded and NUL terminated.
405 ///
406 /// Panics if the zeroth argument contains the `"` character because doublequotes
407 /// in `argv[0]` cannot be encoded using the standard command line parsing rules.
408 ///
409 /// Further reading:
410 /// * [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)
411 /// * [The C/C++ Parameter Parsing Rules](https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES)
412 fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
413 where
414     I: Iterator<Item = T>,
415     T: AsRef<str>,
416 {
417     // Parse argv[0]. Slashes aren't escaped. Literal double quotes are not allowed.
418     let mut cmd = {
419         let arg0 = if let Some(arg0) = args.next() {
420             arg0
421         } else {
422             return vec![0];
423         };
424         let arg0 = arg0.as_ref();
425         if arg0.contains('"') {
426             panic!("argv[0] cannot contain a doublequote (\") character");
427         } else {
428             // Always surround argv[0] with quotes.
429             let mut s = String::new();
430             s.push('"');
431             s.push_str(arg0);
432             s.push('"');
433             s
434         }
435     };
436
437     // Build the other arguments.
438     for arg in args {
439         let arg = arg.as_ref();
440         cmd.push(' ');
441         if arg.is_empty() {
442             cmd.push_str("\"\"");
443         } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
444             // No quote, tab, or space -- no escaping required.
445             cmd.push_str(arg);
446         } else {
447             // Spaces and tabs are escaped by surrounding them in quotes.
448             // Quotes are themselves escaped by using backslashes when in a
449             // quoted block.
450             // Backslashes only need to be escaped when one or more are directly
451             // followed by a quote. Otherwise they are taken literally.
452
453             cmd.push('"');
454             let mut chars = arg.chars().peekable();
455             loop {
456                 let mut nslashes = 0;
457                 while let Some(&'\\') = chars.peek() {
458                     chars.next();
459                     nslashes += 1;
460                 }
461
462                 match chars.next() {
463                     Some('"') => {
464                         cmd.extend(iter::repeat('\\').take(nslashes * 2 + 1));
465                         cmd.push('"');
466                     }
467                     Some(c) => {
468                         cmd.extend(iter::repeat('\\').take(nslashes));
469                         cmd.push(c);
470                     }
471                     None => {
472                         cmd.extend(iter::repeat('\\').take(nslashes * 2));
473                         break;
474                     }
475                 }
476             }
477             cmd.push('"');
478         }
479     }
480
481     if cmd.contains('\0') {
482         panic!("interior null in command line arguments");
483     }
484     cmd.encode_utf16().chain(iter::once(0)).collect()
485 }
486
487 #[cfg(test)]
488 mod tests {
489     use super::*;
490     #[test]
491     #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
492     fn windows_argv0_panic_on_quote() {
493         args_to_utf16_command_string(["\""].iter());
494     }
495     #[test]
496     fn windows_argv0_no_escape() {
497         // Ensure that a trailing backslash in argv[0] is not escaped.
498         let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
499             [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
500         ));
501         assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);
502     }
503 }