]> git.lizzy.rs Git - rust.git/blob - src/eval.rs
audit our bounds checks
[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::{Align, LayoutOf, Size};
8 use rustc::ty::{self, TyCtxt};
9 use syntax::source_map::DUMMY_SP;
10
11 use crate::{
12     struct_error, EnvVars, Evaluator, FnVal, HelpersEvalContextExt, InterpCx, InterpError,
13     InterpResult, MemoryExtra, MiriMemoryKind, Pointer, Scalar, StackPopCleanup, Tag,
14     TlsEvalContextExt,
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 // Used by priroda.
33 pub fn create_ecx<'mir, 'tcx: 'mir>(
34     tcx: TyCtxt<'tcx>,
35     main_id: DefId,
36     config: MiriConfig,
37 ) -> InterpResult<'tcx, InterpCx<'mir, 'tcx, Evaluator<'tcx>>> {
38     let mut ecx = InterpCx::new(
39         tcx.at(syntax::source_map::DUMMY_SP),
40         ty::ParamEnv::reveal_all(),
41         Evaluator::new(config.communicate),
42         MemoryExtra::new(
43             StdRng::seed_from_u64(config.seed.unwrap_or(0)),
44             config.validate,
45         ),
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(ecx.tcx.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         ecx.tcx.tcx,
63         ty::ParamEnv::reveal_all(),
64         start_id,
65         ecx.tcx
66             .mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
67     )
68     .unwrap();
69     let start_mir = ecx.load_mir(start_instance.def, None)?;
70
71     if start_mir.arg_count != 3 {
72         bug!(
73             "'start' lang item should have three arguments, but has {}",
74             start_mir.arg_count
75         );
76     }
77
78     // Return value (in static memory so that it does not count as leak).
79     let ret = ecx.layout_of(start_mir.return_ty())?;
80     let ret_ptr = ecx.allocate(ret, MiriMemoryKind::Static.into());
81
82     // Push our stack frame.
83     ecx.push_stack_frame(
84         start_instance,
85         // There is no call site.
86         DUMMY_SP,
87         start_mir,
88         Some(ret_ptr.into()),
89         StackPopCleanup::None { cleanup: true },
90     )?;
91
92     let mut args = ecx.frame().body.args_iter();
93
94     // First argument: pointer to `main()`.
95     let main_ptr = ecx
96         .memory
97         .create_fn_alloc(FnVal::Instance(main_instance));
98     let dest = ecx.local_place(args.next().unwrap())?;
99     ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
100
101     // Second argument (argc): `1`.
102     let dest = ecx.local_place(args.next().unwrap())?;
103     let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
104     ecx.write_scalar(argc, dest)?;
105     // Store argc for macOS's `_NSGetArgc`.
106     {
107         let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
108         ecx.write_scalar(argc, argc_place.into())?;
109         ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
110     }
111
112     // Third argument (`argv`): created from `config.args`.
113     let dest = ecx.local_place(args.next().unwrap())?;
114     // For Windows, construct a command string with all the aguments.
115     let mut cmd = String::new();
116     for arg in config.args.iter() {
117         if !cmd.is_empty() {
118             cmd.push(' ');
119         }
120         cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
121     }
122     // Don't forget `0` terminator.
123     cmd.push(std::char::from_u32(0).unwrap());
124     // Collect the pointers to the individual strings.
125     let mut argvs = Vec::<Pointer<Tag>>::new();
126     for arg in config.args {
127         // Add `0` terminator.
128         let mut arg = arg.into_bytes();
129         arg.push(0);
130         argvs.push(
131             ecx.memory
132                 .allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()),
133         );
134     }
135     // Make an array with all these pointers, in the Miri memory.
136     let argvs_layout = ecx.layout_of(
137         ecx.tcx
138             .mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64),
139     )?;
140     let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
141     for (idx, arg) in argvs.into_iter().enumerate() {
142         let place = ecx.mplace_field(argvs_place, idx as u64)?;
143         ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
144     }
145     ecx.memory
146         .mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
147     // Write a pointer to that place as the argument.
148     let argv = argvs_place.ptr;
149     ecx.write_scalar(argv, dest)?;
150     // Store `argv` for macOS `_NSGetArgv`.
151     {
152         let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
153         ecx.write_scalar(argv, argv_place.into())?;
154         ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
155     }
156     // Store command line as UTF-16 for Windows `GetCommandLineW`.
157     {
158         let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
159         let cmd_ptr = ecx.memory.allocate(
160             Size::from_bytes(cmd_utf16.len() as u64 * 2),
161             Align::from_bytes(2).unwrap(),
162             MiriMemoryKind::Env.into(),
163         );
164         ecx.machine.cmd_line = Some(cmd_ptr);
165         // Store the UTF-16 string. We just allocated so we know the bounds are fine.
166         let char_size = Size::from_bytes(2);
167         let cmd_alloc = ecx.memory.get_mut(cmd_ptr.alloc_id)?;
168         let mut cur_ptr = cmd_ptr;
169         for &c in cmd_utf16.iter() {
170             cmd_alloc.write_scalar(
171                 &*ecx.tcx,
172                 cur_ptr,
173                 Scalar::from_uint(c, char_size).into(),
174                 char_size,
175             )?;
176             cur_ptr = cur_ptr.offset(char_size, &*ecx.tcx)?;
177         }
178     }
179
180     assert!(
181         args.next().is_none(),
182         "start lang item has more arguments than expected"
183     );
184
185     // Set the last_error to 0
186     let errno_layout = ecx.layout_of(ecx.tcx.types.u32)?;
187     let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Static.into());
188     ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
189     let errno_ptr = ecx.check_mplace_access(errno_place.into(), Some(Size::from_bits(32)))?;
190     ecx.machine.last_error = errno_ptr;
191
192     Ok(ecx)
193 }
194
195 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) {
196     let mut ecx = match create_ecx(tcx, main_id, config) {
197         Ok(ecx) => ecx,
198         Err(mut err) => {
199             err.print_backtrace();
200             panic!("Miri initialziation error: {}", err.kind)
201         }
202     };
203
204     // Perform the main execution.
205     let res: InterpResult<'_> = (|| {
206         ecx.run()?;
207         ecx.run_tls_dtors()
208     })();
209
210     // Process the result.
211     match res {
212         Ok(()) => {
213             let leaks = ecx.memory.leak_report();
214             // Disable the leak test on some platforms where we do not
215             // correctly implement TLS destructors.
216             let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
217             let ignore_leaks = target_os == "windows" || target_os == "macos";
218             if !ignore_leaks && leaks != 0 {
219                 tcx.sess.err("the evaluated program leaked memory");
220             }
221         }
222         Err(mut e) => {
223             // Special treatment for some error kinds
224             let msg = match e.kind {
225                 InterpError::Exit(code) => std::process::exit(code),
226                 err_unsup!(NoMirFor(..)) =>
227                     format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
228                 _ => e.to_string()
229             };
230             e.print_backtrace();
231             if let Some(frame) = ecx.stack().last() {
232                 let block = &frame.body.basic_blocks()[frame.block];
233                 let span = if frame.stmt < block.statements.len() {
234                     block.statements[frame.stmt].source_info.span
235                 } else {
236                     block.terminator().source_info.span
237                 };
238
239                 let msg = format!("Miri evaluation error: {}", msg);
240                 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
241                 let frames = ecx.generate_stacktrace(None);
242                 err.span_label(span, msg);
243                 // We iterate with indices because we need to look at the next frame (the caller).
244                 for idx in 0..frames.len() {
245                     let frame_info = &frames[idx];
246                     let call_site_is_local = frames.get(idx + 1).map_or(false, |caller_info| {
247                         caller_info.instance.def_id().is_local()
248                     });
249                     if call_site_is_local {
250                         err.span_note(frame_info.call_site, &frame_info.to_string());
251                     } else {
252                         err.note(&frame_info.to_string());
253                     }
254                 }
255                 err.emit();
256             } else {
257                 ecx.tcx.sess.err(&msg);
258             }
259
260             for (i, frame) in ecx.stack().iter().enumerate() {
261                 trace!("-------------------");
262                 trace!("Frame {}", i);
263                 trace!("    return: {:?}", frame.return_place.map(|p| *p));
264                 for (i, local) in frame.locals.iter().enumerate() {
265                     trace!("    local {}: {:?}", i, local.value);
266                 }
267             }
268         }
269     }
270 }