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