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