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