]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
Split error reporting from main eval function
[rust.git] / src / eval.rs
1 //! Main evaluator loop and setting up the initial stack frame.
2
3 use std::ffi::OsStr;
4
5 use rand::rngs::StdRng;
6 use rand::SeedableRng;
7
8 use rustc_hir::def_id::DefId;
9 use rustc::ty::layout::{LayoutOf, Size};
10 use rustc::ty::{self, TyCtxt};
11 use rustc_mir::interpret::InterpErrorInfo;
12
13 use crate::*;
14
15 /// Configuration needed to spawn a Miri instance.
16 #[derive(Clone)]
17 pub struct MiriConfig {
18     /// Determine if validity checking and Stacked Borrows are enabled.
19     pub validate: bool,
20     /// Determines if communication with the host environment is enabled.
21     pub communicate: bool,
22     /// Determines if memory leaks should be ignored.
23     pub ignore_leaks: bool,
24     /// Environment variables that should always be isolated from the host.
25     pub excluded_env_vars: Vec<String>,
26     /// Command-line arguments passed to the interpreted program.
27     pub args: Vec<String>,
28     /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
29     pub seed: Option<u64>,
30     /// The stacked borrow id to report about
31     pub tracked_pointer_tag: Option<PtrId>,
32 }
33
34 /// Details of premature program termination.
35 pub enum TerminationInfo {
36     Exit(i64),
37     PoppedTrackedPointerTag(Item),
38     Abort,
39 }
40
41 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
42 /// the location where the return value of the `start` lang item will be
43 /// written to.
44 /// Public because this is also used by `priroda`.
45 pub fn create_ecx<'mir, 'tcx: 'mir>(
46     tcx: TyCtxt<'tcx>,
47     main_id: DefId,
48     config: MiriConfig,
49 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
50     let mut ecx = InterpCx::new(
51         tcx.at(rustc_span::source_map::DUMMY_SP),
52         ty::ParamEnv::reveal_all(),
53         Evaluator::new(config.communicate),
54         MemoryExtra::new(
55             StdRng::seed_from_u64(config.seed.unwrap_or(0)),
56             config.validate,
57             config.tracked_pointer_tag,
58         ),
59     );
60     // Complete initialization.
61     EnvVars::init(&mut ecx, config.excluded_env_vars);
62
63     // Setup first stack-frame
64     let main_instance = ty::Instance::mono(tcx, main_id);
65     let main_mir = ecx.load_mir(main_instance.def, None)?;
66     if main_mir.arg_count != 0 {
67         bug!("main function must not take any arguments");
68     }
69
70     let start_id = tcx.lang_items().start_fn().unwrap();
71     let main_ret_ty = tcx.fn_sig(main_id).output();
72     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
73     let start_instance = ty::Instance::resolve(
74         tcx,
75         ty::ParamEnv::reveal_all(),
76         start_id,
77         tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
78     )
79     .unwrap();
80
81     // First argument: pointer to `main()`.
82     let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
83     // Second argument (argc): length of `config.args`.
84     let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
85     // Third argument (`argv`): created from `config.args`.
86     let argv = {
87         // Put each argument in memory, collect pointers.
88         let mut argvs = Vec::<Scalar<Tag>>::new();
89         for arg in config.args.iter() {
90             // Make space for `0` terminator.
91             let size = arg.len() as u64 + 1;
92             let arg_type = tcx.mk_array(tcx.types.u8, size);
93             let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Env.into());
94             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
95             argvs.push(arg_place.ptr);
96         }
97         // Make an array with all these pointers, in the Miri memory.
98         let argvs_layout =
99             ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64))?;
100         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
101         for (idx, arg) in argvs.into_iter().enumerate() {
102             let place = ecx.mplace_field(argvs_place, idx as u64)?;
103             ecx.write_scalar(arg, place.into())?;
104         }
105         ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
106         // A pointer to that place is the 3rd argument for main.
107         let argv = argvs_place.ptr;
108         // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
109         {
110             let argc_place =
111                 ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Env.into());
112             ecx.write_scalar(argc, argc_place.into())?;
113             ecx.machine.argc = Some(argc_place.ptr);
114
115             let argv_place = ecx.allocate(
116                 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
117                 MiriMemoryKind::Env.into(),
118             );
119             ecx.write_scalar(argv, argv_place.into())?;
120             ecx.machine.argv = Some(argv_place.ptr);
121         }
122         // Store command line as UTF-16 for Windows `GetCommandLineW`.
123         {
124             // Construct a command string with all the aguments.
125             let mut cmd = String::new();
126             for arg in config.args.iter() {
127                 if !cmd.is_empty() {
128                     cmd.push(' ');
129                 }
130                 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
131             }
132             // Don't forget `0` terminator.
133             cmd.push(std::char::from_u32(0).unwrap());
134
135             let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
136             let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
137             let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Env.into());
138             ecx.machine.cmd_line = Some(cmd_place.ptr);
139             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
140             let char_size = Size::from_bytes(2);
141             for (idx, &c) in cmd_utf16.iter().enumerate() {
142                 let place = ecx.mplace_field(cmd_place, idx as u64)?;
143                 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
144             }
145         }
146         argv
147     };
148
149     // Return place (in static memory so that it does not count as leak).
150     let ret_place = ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Env.into());
151     // Call start function.
152     ecx.call_function(
153         start_instance,
154         &[main_ptr.into(), argc.into(), argv.into()],
155         Some(ret_place.into()),
156         StackPopCleanup::None { cleanup: true },
157     )?;
158
159     // Set the last_error to 0
160     let errno_layout = ecx.layout_of(tcx.types.u32)?;
161     let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Env.into());
162     ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
163     ecx.machine.last_error = Some(errno_place);
164
165     Ok((ecx, ret_place))
166 }
167
168 /// Evaluates the main function specified by `main_id`.
169 /// Returns `Some(return_code)` if program executed completed.
170 /// Returns `None` if an evaluation error occured.
171 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
172     // FIXME: We always ignore leaks on some platforms where we do not
173     // correctly implement TLS destructors.
174     let target_os = tcx.sess.target.target.target_os.to_lowercase();
175     let ignore_leaks = config.ignore_leaks || target_os == "windows" || target_os == "macos";
176
177     let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
178         Ok(v) => v,
179         Err(mut err) => {
180             err.print_backtrace();
181             panic!("Miri initialziation error: {}", err.kind)
182         }
183     };
184
185     // Perform the main execution.
186     let res: InterpResult<'_, i64> = (|| {
187         ecx.run()?;
188         // Read the return code pointer *before* we run TLS destructors, to assert
189         // that it was written to by the time that `start` lang item returned.
190         let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
191         ecx.run_tls_dtors()?;
192         Ok(return_code)
193     })();
194
195     // Process the result.
196     match res {
197         Ok(return_code) => {
198             if !ignore_leaks {
199                 let leaks = ecx.memory.leak_report();
200                 if leaks != 0 {
201                     tcx.sess.err("the evaluated program leaked memory");
202                     // Ignore the provided return code - let the reported error
203                     // determine the return code.
204                     return None;
205                 }
206             }
207             return Some(return_code);
208         }
209         Err(e) => report_err(&ecx, e),
210     }
211 }
212
213 fn report_err<'tcx, 'mir>(
214     ecx: &InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
215     mut e: InterpErrorInfo<'tcx>,
216 ) -> Option<i64> {
217     // Special treatment for some error kinds
218     let msg = match e.kind {
219         InterpError::MachineStop(ref info) => {
220             let info = info.downcast_ref::<TerminationInfo>().expect("invalid MachineStop payload");
221             match info {
222                 TerminationInfo::Exit(code) => return Some(*code),
223                 TerminationInfo::PoppedTrackedPointerTag(item) =>
224                     format!("popped tracked tag for item {:?}", item),
225                 TerminationInfo::Abort => format!("the evaluated program aborted execution"),
226             }
227         }
228         err_unsup!(NoMirFor(..)) => format!(
229             "{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.",
230             e
231         ),
232         InterpError::InvalidProgram(_) => bug!("This error should be impossible in Miri: {}", e),
233         _ => e.to_string(),
234     };
235     e.print_backtrace();
236     if let Some(frame) = ecx.stack().last() {
237         let span = frame.current_source_info().unwrap().span;
238
239         let msg = format!("Miri evaluation error: {}", msg);
240         let mut err = ecx.tcx.sess.struct_span_err(span, msg.as_str());
241         let frames = ecx.generate_stacktrace(None);
242         err.span_label(span, msg);
243         // We iterate with indices because we need to look at the next frame (the caller).
244         for idx in 0..frames.len() {
245             let frame_info = &frames[idx];
246             let call_site_is_local = frames
247                 .get(idx + 1)
248                 .map_or(false, |caller_info| caller_info.instance.def_id().is_local());
249             if call_site_is_local {
250                 err.span_note(frame_info.call_site, &frame_info.to_string());
251             } else {
252                 err.note(&frame_info.to_string());
253             }
254         }
255         err.emit();
256     } else {
257         ecx.tcx.sess.err(&msg);
258     }
259
260     for (i, frame) in ecx.stack().iter().enumerate() {
261         trace!("-------------------");
262         trace!("Frame {}", i);
263         trace!("    return: {:?}", frame.return_place.map(|p| *p));
264         for (i, local) in frame.locals.iter().enumerate() {
265             trace!("    local {}: {:?}", i, local.value);
266         }
267     }
268     // Let the reported error determine the return code.
269     return None;
270 }