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