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