1 //! Main evaluator loop and setting up the initial stack frame.
3 use std::convert::TryFrom;
6 use rand::rngs::StdRng;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::ty::{self, layout::LayoutCx, TyCtxt};
11 use rustc_target::abi::LayoutOf;
15 /// Configuration needed to spawn a Miri instance.
17 pub struct MiriConfig {
18 /// Determine if validity checking is enabled.
20 /// Determines if Stacked Borrows is enabled.
21 pub stacked_borrows: bool,
22 /// Determines if communication with the host environment is enabled.
23 pub communicate: bool,
24 /// Determines if memory leaks should be ignored.
25 pub ignore_leaks: bool,
26 /// Environment variables that should always be isolated from the host.
27 pub excluded_env_vars: Vec<String>,
28 /// Command-line arguments passed to the interpreted program.
29 pub args: Vec<String>,
30 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
31 pub seed: Option<u64>,
32 /// The stacked borrow id to report about
33 pub tracked_pointer_tag: Option<PtrId>,
34 /// The allocation id to report about.
35 pub tracked_alloc_id: Option<AllocId>,
38 impl Default for MiriConfig {
39 fn default() -> MiriConfig {
42 stacked_borrows: true,
45 excluded_env_vars: vec![],
48 tracked_pointer_tag: None,
49 tracked_alloc_id: None,
54 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
55 /// the location where the return value of the `start` lang item will be
57 /// Public because this is also used by `priroda`.
58 pub fn create_ecx<'mir, 'tcx: 'mir>(
62 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
63 let tcx_at = tcx.at(rustc_span::source_map::DUMMY_SP);
64 let param_env = ty::ParamEnv::reveal_all();
65 let layout_cx = LayoutCx { tcx, param_env };
66 let mut ecx = InterpCx::new(
69 Evaluator::new(config.communicate, config.validate, layout_cx),
71 StdRng::seed_from_u64(config.seed.unwrap_or(0)),
72 config.stacked_borrows,
73 config.tracked_pointer_tag,
74 config.tracked_alloc_id,
77 // Complete initialization.
78 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
79 MemoryExtra::init_extern_statics(&mut ecx)?;
81 // Setup first stack-frame
82 let main_instance = ty::Instance::mono(tcx, main_id);
83 let main_mir = ecx.load_mir(main_instance.def, None)?;
84 if main_mir.arg_count != 0 {
85 bug!("main function must not take any arguments");
88 let start_id = tcx.lang_items().start_fn().unwrap();
89 let main_ret_ty = tcx.fn_sig(main_id).output();
90 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
91 let start_instance = ty::Instance::resolve(
93 ty::ParamEnv::reveal_all(),
95 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
99 // First argument: pointer to `main()`.
100 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
101 // Second argument (argc): length of `config.args`.
102 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
103 // Third argument (`argv`): created from `config.args`.
105 // Put each argument in memory, collect pointers.
106 let mut argvs = Vec::<Scalar<Tag>>::new();
107 for arg in config.args.iter() {
108 // Make space for `0` terminator.
109 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
110 let arg_type = tcx.mk_array(tcx.types.u8, size);
111 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
112 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
113 argvs.push(arg_place.ptr);
115 // Make an array with all these pointers, in the Miri memory.
117 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
118 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
119 for (idx, arg) in argvs.into_iter().enumerate() {
120 let place = ecx.mplace_field(argvs_place, idx)?;
121 ecx.write_scalar(arg, place.into())?;
123 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
124 // A pointer to that place is the 3rd argument for main.
125 let argv = argvs_place.ptr;
126 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
129 ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Machine.into());
130 ecx.write_scalar(argc, argc_place.into())?;
131 ecx.machine.argc = Some(argc_place.ptr);
133 let argv_place = ecx.allocate(
134 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
135 MiriMemoryKind::Machine.into(),
137 ecx.write_scalar(argv, argv_place.into())?;
138 ecx.machine.argv = Some(argv_place.ptr);
140 // Store command line as UTF-16 for Windows `GetCommandLineW`.
142 // Construct a command string with all the aguments.
143 let mut cmd = String::new();
144 for arg in config.args.iter() {
148 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
150 // Don't forget `0` terminator.
151 cmd.push(std::char::from_u32(0).unwrap());
153 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
154 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
155 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
156 ecx.machine.cmd_line = Some(cmd_place.ptr);
157 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
158 for (idx, &c) in cmd_utf16.iter().enumerate() {
159 let place = ecx.mplace_field(cmd_place, idx)?;
160 ecx.write_scalar(Scalar::from_u16(c), place.into())?;
166 // Return place (in static memory so that it does not count as leak).
167 let ret_place = ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Machine.into());
168 // Call start function.
171 &[main_ptr.into(), argc.into(), argv.into()],
172 Some(ret_place.into()),
173 StackPopCleanup::None { cleanup: true },
176 // Set the last_error to 0
177 let errno_layout = ecx.layout_of(tcx.types.u32)?;
178 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Machine.into());
179 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
180 ecx.machine.last_error = Some(errno_place);
185 /// Evaluates the main function specified by `main_id`.
186 /// Returns `Some(return_code)` if program executed completed.
187 /// Returns `None` if an evaluation error occured.
188 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
189 // FIXME: on Windows, locks and TLS dtor management allocate and leave that memory in `static`s.
190 // So we need https://github.com/rust-lang/miri/issues/940 to fix the leaks there.
191 let ignore_leaks = config.ignore_leaks || tcx.sess.target.target.target_os == "windows";
193 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
196 err.print_backtrace();
197 panic!("Miri initialization error: {}", err.kind)
201 // Perform the main execution.
202 let res: InterpResult<'_, i64> = (|| {
205 ecx.process_diagnostics();
207 // Read the return code pointer *before* we run TLS destructors, to assert
208 // that it was written to by the time that `start` lang item returned.
209 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
210 // Global destructors.
211 ecx.run_tls_dtors()?;
216 EnvVars::cleanup(&mut ecx).unwrap();
218 // Process the result.
222 let leaks = ecx.memory.leak_report();
224 tcx.sess.err("the evaluated program leaked memory");
225 // Ignore the provided return code - let the reported error
226 // determine the return code.
232 Err(e) => report_error(&ecx, e),