1 //! Global machine state as well as implementation of the interpreter engine
6 use std::collections::HashMap;
7 use std::cell::RefCell;
9 use rand::rngs::StdRng;
12 use syntax::symbol::sym;
13 use rustc::hir::def_id::DefId;
14 use rustc::ty::{self, layout::{Size, LayoutOf}, query::TyCtxtAt};
19 /// Extra memory kinds
20 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
21 pub enum MiriMemoryKind {
22 /// `__rust_alloc` memory.
26 /// Part of env var emulation.
32 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
34 fn into(self) -> MemoryKind<MiriMemoryKind> {
35 MemoryKind::Machine(self)
39 /// Extra per-allocation data
40 #[derive(Debug, Clone)]
41 pub struct AllocExtra {
42 pub stacked_borrows: stacked_borrows::AllocExtra,
43 pub intptrcast: intptrcast::AllocExtra,
46 /// Extra global memory data
47 #[derive(Clone, Debug)]
48 pub struct MemoryExtra {
49 pub stacked_borrows: stacked_borrows::MemoryExtra,
50 pub intptrcast: intptrcast::MemoryExtra,
51 /// The random number generator to use if Miri is running in non-deterministic mode and to
53 pub(crate) rng: Option<RefCell<StdRng>>
57 pub fn with_rng(rng: Option<StdRng>) -> Self {
59 stacked_borrows: Default::default(),
60 intptrcast: Default::default(),
61 rng: rng.map(RefCell::new),
66 /// The machine itself.
67 pub struct Evaluator<'tcx> {
68 /// Environment variables set by `setenv`.
69 /// Miri does not expose env vars from the host to the emulated program.
70 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
72 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
73 /// These are *pointers* to argc/argv because macOS.
74 /// We also need the full command line as one string because of Windows.
75 pub(crate) argc: Option<Pointer<Tag>>,
76 pub(crate) argv: Option<Pointer<Tag>>,
77 pub(crate) cmd_line: Option<Pointer<Tag>>,
80 pub(crate) last_error: u32,
83 pub(crate) tls: TlsData<'tcx>,
85 /// Whether to enforce the validity invariant.
86 pub(crate) validate: bool,
89 impl<'tcx> Evaluator<'tcx> {
90 pub(crate) fn new(validate: bool) -> Self {
92 env_vars: HashMap::default(),
97 tls: TlsData::default(),
103 /// A rustc InterpretCx for Miri.
104 pub type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
106 /// A little trait that's useful to be inherited by extension traits.
107 pub trait MiriEvalContextExt<'mir, 'tcx> {
108 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
109 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
111 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
113 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
117 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
122 /// Machine hook implementations.
123 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
124 type MemoryKinds = MiriMemoryKind;
126 type FrameExtra = stacked_borrows::CallId;
127 type MemoryExtra = MemoryExtra;
128 type AllocExtra = AllocExtra;
129 type PointerTag = Tag;
131 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
133 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
136 fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
140 /// Returns `Ok()` when the function was handled; fail otherwise.
143 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
144 instance: ty::Instance<'tcx>,
145 args: &[OpTy<'tcx, Tag>],
146 dest: Option<PlaceTy<'tcx, Tag>>,
147 ret: Option<mir::BasicBlock>,
148 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
149 ecx.find_fn(instance, args, dest, ret)
154 ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
155 instance: ty::Instance<'tcx>,
156 args: &[OpTy<'tcx, Tag>],
157 dest: PlaceTy<'tcx, Tag>,
158 ) -> InterpResult<'tcx> {
159 ecx.call_intrinsic(instance, args, dest)
164 ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
166 left: ImmTy<'tcx, Tag>,
167 right: ImmTy<'tcx, Tag>,
168 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
169 ecx.ptr_op(bin_op, left, right)
173 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
174 dest: PlaceTy<'tcx, Tag>,
175 ) -> InterpResult<'tcx> {
176 trace!("box_alloc for {:?}", dest.layout.ty);
177 // Call the `exchange_malloc` lang item.
178 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
179 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
180 let malloc_mir = ecx.load_mir(malloc.def)?;
181 ecx.push_stack_frame(
186 // Don't do anything when we are done. The `statement()` function will increment
187 // the old stack frame's stmt counter to the next statement, which means that when
188 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
189 StackPopCleanup::None { cleanup: true },
192 let mut args = ecx.frame().body.args_iter();
193 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
195 // First argument: `size`.
196 // (`0` is allowed here -- this is expected to be handled by the lang item).
197 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
198 let size = layout.size.bytes();
199 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
201 // Second argument: `align`.
202 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
203 let align = layout.align.abi.bytes();
204 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
206 // No more arguments.
208 args.next().is_none(),
209 "`exchange_malloc` lang item has more arguments than expected"
214 fn find_foreign_static(
217 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
218 let attrs = tcx.get_attrs(def_id);
219 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
220 Some(name) => name.as_str(),
221 None => tcx.item_name(def_id).as_str(),
224 let alloc = match link_name.get() {
225 "__cxa_thread_atexit_impl" => {
226 // This should be all-zero, pointer-sized.
227 let size = tcx.data_layout.pointer_size;
228 let data = vec![0; size.bytes() as usize];
229 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
231 _ => return err!(Unimplemented(
232 format!("can't access foreign static: {}", link_name),
235 Ok(Cow::Owned(alloc))
239 fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
241 // We are not interested in detecting loops.
245 fn tag_allocation<'b>(
247 alloc: Cow<'b, Allocation>,
248 kind: Option<MemoryKind<Self::MemoryKinds>>,
249 memory: &Memory<'mir, 'tcx, Self>,
250 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
251 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
252 let alloc = alloc.into_owned();
253 let (stacks, base_tag) = Stacks::new_allocation(
255 Size::from_bytes(alloc.bytes.len() as u64),
256 Rc::clone(&memory.extra.stacked_borrows),
259 if kind != MiriMemoryKind::Static.into() {
260 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
261 // Now we can rely on the inner pointers being static, too.
263 let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
264 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
266 relocations: Relocations::from_presorted(
267 alloc.relocations.iter()
268 // The allocations in the relocations (pointers stored *inside* this allocation)
269 // all get the base pointer tag.
270 .map(|&(offset, ((), alloc))| (offset, (memory_extra.static_base_ptr(alloc), alloc)))
273 undef_mask: alloc.undef_mask,
275 mutability: alloc.mutability,
277 stacked_borrows: stacks,
278 intptrcast: Default::default(),
281 (Cow::Owned(alloc), base_tag)
285 fn tag_static_base_pointer(
287 memory: &Memory<'mir, 'tcx, Self>,
288 ) -> Self::PointerTag {
289 memory.extra.stacked_borrows.borrow_mut().static_base_ptr(id)
294 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
295 kind: mir::RetagKind,
296 place: PlaceTy<'tcx, Tag>,
297 ) -> InterpResult<'tcx> {
298 if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag || !Self::enforce_validity(ecx) {
299 // No tracking, or no retagging. The latter is possible because a dependency of ours
300 // might be called with different flags than we are, so there are `Retag`
301 // statements but we do not want to execute them.
302 // Also, honor the whitelist in `enforce_validity` because otherwise we might retag
303 // uninitialized data.
306 ecx.retag(kind, place)
312 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
313 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
314 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
319 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
320 extra: stacked_borrows::CallId,
321 ) -> InterpResult<'tcx> {
322 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
327 memory: &Memory<'mir, 'tcx, Self>,
328 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
330 err!(InvalidNullPointerUsage)
331 } else if memory.extra.rng.is_none() {
332 err!(ReadBytesAsPointer)
334 intptrcast::GlobalState::int_to_ptr(int, memory)
339 ptr: Pointer<Self::PointerTag>,
340 memory: &Memory<'mir, 'tcx, Self>,
341 ) -> InterpResult<'tcx, u64> {
342 if memory.extra.rng.is_none() {
343 err!(ReadPointerAsBytes)
345 intptrcast::GlobalState::ptr_to_int(ptr, memory)
350 impl AllocationExtra<Tag> for AllocExtra {
352 fn memory_read<'tcx>(
353 alloc: &Allocation<Tag, AllocExtra>,
356 ) -> InterpResult<'tcx> {
357 alloc.extra.stacked_borrows.memory_read(ptr, size)
361 fn memory_written<'tcx>(
362 alloc: &mut Allocation<Tag, AllocExtra>,
365 ) -> InterpResult<'tcx> {
366 alloc.extra.stacked_borrows.memory_written(ptr, size)
370 fn memory_deallocated<'tcx>(
371 alloc: &mut Allocation<Tag, AllocExtra>,
374 ) -> InterpResult<'tcx> {
375 alloc.extra.stacked_borrows.memory_deallocated(ptr, size)
379 impl MayLeak for MiriMemoryKind {
381 fn may_leak(self) -> bool {
382 use self::MiriMemoryKind::*;
385 Env | Static => true,