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