1 //! Main evaluator loop and setting up the initial stack frame.
4 use std::convert::TryFrom;
6 use rand::rngs::StdRng;
9 use rustc::ty::layout::{LayoutOf, Size};
10 use rustc::ty::{self, TyCtxt};
11 use rustc_hir::def_id::DefId;
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 /// Details of premature program termination.
55 pub enum TerminationInfo {
60 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
61 /// the location where the return value of the `start` lang item will be
63 /// Public because this is also used by `priroda`.
64 pub fn create_ecx<'mir, 'tcx: 'mir>(
68 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
69 let mut ecx = InterpCx::new(
70 tcx.at(rustc_span::source_map::DUMMY_SP),
71 ty::ParamEnv::reveal_all(),
72 Evaluator::new(config.communicate, config.validate),
74 StdRng::seed_from_u64(config.seed.unwrap_or(0)),
75 config.stacked_borrows,
76 config.tracked_pointer_tag,
77 config.tracked_alloc_id,
80 // Complete initialization.
81 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
82 MemoryExtra::init_extern_statics(&mut ecx)?;
84 // Setup first stack-frame
85 let main_instance = ty::Instance::mono(tcx, main_id);
86 let main_mir = ecx.load_mir(main_instance.def, None)?;
87 if main_mir.arg_count != 0 {
88 bug!("main function must not take any arguments");
91 let start_id = tcx.lang_items().start_fn().unwrap();
92 let main_ret_ty = tcx.fn_sig(main_id).output();
93 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
94 let start_instance = ty::Instance::resolve(
96 ty::ParamEnv::reveal_all(),
98 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
102 // First argument: pointer to `main()`.
103 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
104 // Second argument (argc): length of `config.args`.
105 let argc = Scalar::from_uint(u64::try_from(config.args.len()).unwrap(), ecx.pointer_size());
106 // Third argument (`argv`): created from `config.args`.
108 // Put each argument in memory, collect pointers.
109 let mut argvs = Vec::<Scalar<Tag>>::new();
110 for arg in config.args.iter() {
111 // Make space for `0` terminator.
112 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
113 let arg_type = tcx.mk_array(tcx.types.u8, size);
114 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
115 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
116 argvs.push(arg_place.ptr);
118 // Make an array with all these pointers, in the Miri memory.
120 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
121 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
122 for (idx, arg) in argvs.into_iter().enumerate() {
123 let place = ecx.mplace_field(argvs_place, u64::try_from(idx).unwrap())?;
124 ecx.write_scalar(arg, place.into())?;
126 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
127 // A pointer to that place is the 3rd argument for main.
128 let argv = argvs_place.ptr;
129 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
132 ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Machine.into());
133 ecx.write_scalar(argc, argc_place.into())?;
134 ecx.machine.argc = Some(argc_place.ptr);
136 let argv_place = ecx.allocate(
137 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
138 MiriMemoryKind::Machine.into(),
140 ecx.write_scalar(argv, argv_place.into())?;
141 ecx.machine.argv = Some(argv_place.ptr);
143 // Store command line as UTF-16 for Windows `GetCommandLineW`.
145 // Construct a command string with all the aguments.
146 let mut cmd = String::new();
147 for arg in config.args.iter() {
151 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
153 // Don't forget `0` terminator.
154 cmd.push(std::char::from_u32(0).unwrap());
156 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
157 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
158 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
159 ecx.machine.cmd_line = Some(cmd_place.ptr);
160 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
161 let char_size = Size::from_bytes(2);
162 for (idx, &c) in cmd_utf16.iter().enumerate() {
163 let place = ecx.mplace_field(cmd_place, u64::try_from(idx).unwrap())?;
164 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
170 // Return place (in static memory so that it does not count as leak).
171 let ret_place = ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Machine.into());
172 // Call start function.
175 &[main_ptr.into(), argc.into(), argv.into()],
176 Some(ret_place.into()),
177 StackPopCleanup::None { cleanup: true },
180 // Set the last_error to 0
181 let errno_layout = ecx.layout_of(tcx.types.u32)?;
182 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Machine.into());
183 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
184 ecx.machine.last_error = Some(errno_place);
189 /// Evaluates the main function specified by `main_id`.
190 /// Returns `Some(return_code)` if program executed completed.
191 /// Returns `None` if an evaluation error occured.
192 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
193 // FIXME: We always ignore leaks on some platforms where we do not
194 // correctly implement TLS destructors.
195 let target_os = tcx.sess.target.target.target_os.as_str();
196 let ignore_leaks = config.ignore_leaks || target_os == "windows" || target_os == "macos";
198 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
201 err.print_backtrace();
202 panic!("Miri initialization error: {}", err.kind)
206 // Perform the main execution.
207 let res: InterpResult<'_, i64> = (|| {
209 ecx.process_diagnostics();
211 // Read the return code pointer *before* we run TLS destructors, to assert
212 // that it was written to by the time that `start` lang item returned.
213 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
214 ecx.run_tls_dtors()?;
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_diagnostic(&ecx, e),