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