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 /// 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 mut ecx = InterpCx::new(
64 tcx.at(rustc_span::source_map::DUMMY_SP),
65 ty::ParamEnv::reveal_all(),
66 Evaluator::new(config.communicate, config.validate),
68 StdRng::seed_from_u64(config.seed.unwrap_or(0)),
69 config.stacked_borrows,
70 config.tracked_pointer_tag,
71 config.tracked_alloc_id,
74 // Complete initialization.
75 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
76 MemoryExtra::init_extern_statics(&mut ecx)?;
78 // Setup first stack-frame
79 let main_instance = ty::Instance::mono(tcx, main_id);
80 let main_mir = ecx.load_mir(main_instance.def, None)?;
81 if main_mir.arg_count != 0 {
82 bug!("main function must not take any arguments");
85 let start_id = tcx.lang_items().start_fn().unwrap();
86 let main_ret_ty = tcx.fn_sig(main_id).output();
87 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
88 let start_instance = ty::Instance::resolve(
90 ty::ParamEnv::reveal_all(),
92 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
96 // First argument: pointer to `main()`.
97 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
98 // Second argument (argc): length of `config.args`.
99 let argc = Scalar::from_uint(u64::try_from(config.args.len()).unwrap(), ecx.pointer_size());
100 // Third argument (`argv`): created from `config.args`.
102 // Put each argument in memory, collect pointers.
103 let mut argvs = Vec::<Scalar<Tag>>::new();
104 for arg in config.args.iter() {
105 // Make space for `0` terminator.
106 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
107 let arg_type = tcx.mk_array(tcx.types.u8, size);
108 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
109 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
110 argvs.push(arg_place.ptr);
112 // Make an array with all these pointers, in the Miri memory.
114 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
115 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
116 for (idx, arg) in argvs.into_iter().enumerate() {
117 let place = ecx.mplace_field(argvs_place, u64::try_from(idx).unwrap())?;
118 ecx.write_scalar(arg, place.into())?;
120 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
121 // A pointer to that place is the 3rd argument for main.
122 let argv = argvs_place.ptr;
123 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
126 ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Machine.into());
127 ecx.write_scalar(argc, argc_place.into())?;
128 ecx.machine.argc = Some(argc_place.ptr);
130 let argv_place = ecx.allocate(
131 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
132 MiriMemoryKind::Machine.into(),
134 ecx.write_scalar(argv, argv_place.into())?;
135 ecx.machine.argv = Some(argv_place.ptr);
137 // Store command line as UTF-16 for Windows `GetCommandLineW`.
139 // Construct a command string with all the aguments.
140 let mut cmd = String::new();
141 for arg in config.args.iter() {
145 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
147 // Don't forget `0` terminator.
148 cmd.push(std::char::from_u32(0).unwrap());
150 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
151 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
152 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
153 ecx.machine.cmd_line = Some(cmd_place.ptr);
154 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
155 let char_size = Size::from_bytes(2);
156 for (idx, &c) in cmd_utf16.iter().enumerate() {
157 let place = ecx.mplace_field(cmd_place, u64::try_from(idx).unwrap())?;
158 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
164 // Return place (in static memory so that it does not count as leak).
165 let ret_place = ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Machine.into());
166 // Call start function.
169 &[main_ptr.into(), argc.into(), argv.into()],
170 Some(ret_place.into()),
171 StackPopCleanup::None { cleanup: true },
174 // Set the last_error to 0
175 let errno_layout = ecx.layout_of(tcx.types.u32)?;
176 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Machine.into());
177 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
178 ecx.machine.last_error = Some(errno_place);
183 /// Evaluates the main function specified by `main_id`.
184 /// Returns `Some(return_code)` if program executed completed.
185 /// Returns `None` if an evaluation error occured.
186 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
187 // FIXME: We always ignore leaks on some OSs where we do not
188 // correctly implement TLS destructors.
189 let target_os = tcx.sess.target.target.target_os.as_str();
190 let ignore_leaks = config.ignore_leaks || target_os == "windows" || target_os == "macos";
192 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
195 err.print_backtrace();
196 panic!("Miri initialization error: {}", err.kind)
200 // Perform the main execution.
201 let res: InterpResult<'_, i64> = (|| {
203 ecx.process_diagnostics();
205 // Read the return code pointer *before* we run TLS destructors, to assert
206 // that it was written to by the time that `start` lang item returned.
207 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
208 ecx.run_tls_dtors()?;
212 // Process the result.
216 let leaks = ecx.memory.leak_report();
218 tcx.sess.err("the evaluated program leaked memory");
219 // Ignore the provided return code - let the reported error
220 // determine the return code.
226 Err(e) => report_error(&ecx, e),