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