1 //! Main evaluator loop and setting up the initial stack frame.
3 use std::convert::TryFrom;
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::ty::{self, layout::LayoutCx, TyCtxt};
10 use rustc_target::abi::LayoutOf;
14 #[derive(Copy, Clone, Debug, PartialEq)]
15 pub enum AlignmentCheck {
16 /// Do not check alignment.
18 /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
20 /// Check alignment on the actual physical integer address.
24 /// Configuration needed to spawn a Miri instance.
26 pub struct MiriConfig {
27 /// Determine if validity checking is enabled.
29 /// Determines if Stacked Borrows is enabled.
30 pub stacked_borrows: bool,
31 /// Controls alignment checking.
32 pub check_alignment: AlignmentCheck,
33 /// Determines if communication with the host environment is enabled.
34 pub communicate: bool,
35 /// Determines if memory leaks should be ignored.
36 pub ignore_leaks: bool,
37 /// Environment variables that should always be isolated from the host.
38 pub excluded_env_vars: Vec<String>,
39 /// Command-line arguments passed to the interpreted program.
40 pub args: Vec<String>,
41 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
42 pub seed: Option<u64>,
43 /// The stacked borrows pointer id to report about
44 pub tracked_pointer_tag: Option<PtrId>,
45 /// The stacked borrows call ID to report about
46 pub tracked_call_id: Option<CallId>,
47 /// The allocation id to report about.
48 pub tracked_alloc_id: Option<AllocId>,
49 /// Whether to track raw pointers in stacked borrows.
51 /// Determine if data race detection should be enabled
52 pub data_race_detector: bool,
55 impl Default for MiriConfig {
56 fn default() -> MiriConfig {
59 stacked_borrows: true,
60 check_alignment: AlignmentCheck::Int,
63 excluded_env_vars: vec![],
66 tracked_pointer_tag: None,
67 tracked_call_id: None,
68 tracked_alloc_id: None,
70 data_race_detector: true,
75 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
76 /// the location where the return value of the `start` lang item will be
78 /// Public because this is also used by `priroda`.
79 pub fn create_ecx<'mir, 'tcx: 'mir>(
83 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
84 let param_env = ty::ParamEnv::reveal_all();
85 let layout_cx = LayoutCx { tcx, param_env };
86 let mut ecx = InterpCx::new(
88 rustc_span::source_map::DUMMY_SP,
90 Evaluator::new(config.communicate, config.validate, layout_cx),
91 MemoryExtra::new(&config),
93 // Complete initialization.
94 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
95 MemoryExtra::init_extern_statics(&mut ecx)?;
97 // Setup first stack-frame
98 let main_instance = ty::Instance::mono(tcx, main_id);
99 let main_mir = ecx.load_mir(main_instance.def, None)?;
100 if main_mir.arg_count != 0 {
101 bug!("main function must not take any arguments");
104 let start_id = tcx.lang_items().start_fn().unwrap();
105 let main_ret_ty = tcx.fn_sig(main_id).output();
106 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
107 let start_instance = ty::Instance::resolve(
109 ty::ParamEnv::reveal_all(),
111 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
116 // First argument: pointer to `main()`.
117 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
118 // Second argument (argc): length of `config.args`.
119 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
120 // Third argument (`argv`): created from `config.args`.
122 // Put each argument in memory, collect pointers.
123 let mut argvs = Vec::<Scalar<Tag>>::new();
124 for arg in config.args.iter() {
125 // Make space for `0` terminator.
126 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
127 let arg_type = tcx.mk_array(tcx.types.u8, size);
128 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
129 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
130 argvs.push(arg_place.ptr);
132 // Make an array with all these pointers, in the Miri memory.
134 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
135 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
136 for (idx, arg) in argvs.into_iter().enumerate() {
137 let place = ecx.mplace_field(argvs_place, idx)?;
138 ecx.write_scalar(arg, place.into())?;
140 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
141 // A pointer to that place is the 3rd argument for main.
142 let argv = argvs_place.ptr;
143 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
146 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
147 ecx.write_scalar(argc, argc_place.into())?;
148 ecx.machine.argc = Some(argc_place.ptr);
150 let argv_place = ecx.allocate(
151 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
152 MiriMemoryKind::Machine.into(),
154 ecx.write_scalar(argv, argv_place.into())?;
155 ecx.machine.argv = Some(argv_place.ptr);
157 // Store command line as UTF-16 for Windows `GetCommandLineW`.
159 // Construct a command string with all the aguments.
160 let mut cmd = String::new();
161 for arg in config.args.iter() {
165 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
167 // Don't forget `0` terminator.
168 cmd.push(std::char::from_u32(0).unwrap());
170 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
171 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
172 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
173 ecx.machine.cmd_line = Some(cmd_place.ptr);
174 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
175 for (idx, &c) in cmd_utf16.iter().enumerate() {
176 let place = ecx.mplace_field(cmd_place, idx)?;
177 ecx.write_scalar(Scalar::from_u16(c), place.into())?;
183 // Return place (in static memory so that it does not count as leak).
184 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
185 // Call start function.
188 &[main_ptr.into(), argc.into(), argv.into()],
189 Some(ret_place.into()),
190 StackPopCleanup::None { cleanup: true },
196 /// Evaluates the main function specified by `main_id`.
197 /// Returns `Some(return_code)` if program executed completed.
198 /// Returns `None` if an evaluation error occured.
199 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
200 // Copy setting before we move `config`.
201 let ignore_leaks = config.ignore_leaks;
203 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
206 err.print_backtrace();
207 panic!("Miri initialization error: {}", err.kind)
211 // Perform the main execution.
212 let res: InterpResult<'_, i64> = (|| {
215 let info = ecx.preprocess_diagnostics();
216 match ecx.schedule()? {
217 SchedulingAction::ExecuteStep => {
218 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
220 SchedulingAction::ExecuteTimeoutCallback => {
221 assert!(ecx.machine.communicate,
222 "scheduler callbacks require disabled isolation, but the code \
223 that created the callback did not check it");
224 ecx.run_timeout_callback()?;
226 SchedulingAction::ExecuteDtors => {
227 // This will either enable the thread again (so we go back
228 // to `ExecuteStep`), or determine that this thread is done
230 ecx.schedule_next_tls_dtor_for_active_thread()?;
232 SchedulingAction::Stop => {
236 ecx.process_diagnostics(info);
238 let return_code = ecx.read_scalar(ret_place.into())?.check_init()?.to_machine_isize(&ecx)?;
243 EnvVars::cleanup(&mut ecx).unwrap();
245 // Process the result.
249 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
250 let leaks = ecx.memory.leak_report(&ecx.machine.static_roots);
252 tcx.sess.err("the evaluated program leaked memory");
253 // Ignore the provided return code - let the reported error
254 // determine the return code.
260 Err(e) => report_error(&ecx, e),