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