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}, TyCtxt};
19 // Some global facts about the emulated machine.
20 pub const PAGE_SIZE: u64 = 4*1024; // FIXME: adjust to target architecture
21 pub const STACK_ADDR: u64 = 32*PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
22 pub const STACK_SIZE: u64 = 16*PAGE_SIZE; // whatever
23 pub const NUM_CPUS: u64 = 1;
25 /// Extra memory kinds
26 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
27 pub enum MiriMemoryKind {
28 /// `__rust_alloc` memory.
32 /// Windows `HeapAlloc` memory.
34 /// Part of env var emulation.
40 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
42 fn into(self) -> MemoryKind<MiriMemoryKind> {
43 MemoryKind::Machine(self)
47 /// Extra per-allocation data
48 #[derive(Debug, Clone)]
49 pub struct AllocExtra {
50 /// Stacked Borrows state is only added if validation is enabled.
51 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
54 /// Extra global memory data
55 #[derive(Clone, Debug)]
56 pub struct MemoryExtra {
57 pub stacked_borrows: stacked_borrows::MemoryExtra,
58 pub intptrcast: intptrcast::MemoryExtra,
60 /// The random number generator to use if Miri is running in non-deterministic mode and to
62 pub(crate) rng: Option<RefCell<StdRng>>,
64 /// Whether to enforce the validity invariant.
65 pub(crate) validate: bool,
69 pub fn new(rng: Option<StdRng>, validate: bool) -> Self {
71 stacked_borrows: Default::default(),
72 intptrcast: Default::default(),
73 rng: rng.map(RefCell::new),
79 /// The machine itself.
80 pub struct Evaluator<'tcx> {
81 /// Environment variables set by `setenv`.
82 /// Miri does not expose env vars from the host to the emulated program.
83 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
85 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
86 /// These are *pointers* to argc/argv because macOS.
87 /// We also need the full command line as one string because of Windows.
88 pub(crate) argc: Option<Pointer<Tag>>,
89 pub(crate) argv: Option<Pointer<Tag>>,
90 pub(crate) cmd_line: Option<Pointer<Tag>>,
93 pub(crate) last_error: u32,
96 pub(crate) tls: TlsData<'tcx>,
99 impl<'tcx> Evaluator<'tcx> {
100 pub(crate) fn new() -> Self {
102 env_vars: HashMap::default(),
107 tls: TlsData::default(),
112 /// A rustc InterpCx for Miri.
113 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
115 /// A little trait that's useful to be inherited by extension traits.
116 pub trait MiriEvalContextExt<'mir, 'tcx> {
117 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
118 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
120 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
122 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
126 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
131 /// Machine hook implementations.
132 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
133 type MemoryKinds = MiriMemoryKind;
135 type FrameExtra = stacked_borrows::CallId;
136 type MemoryExtra = MemoryExtra;
137 type AllocExtra = AllocExtra;
138 type PointerTag = Tag;
139 type ExtraFnVal = Dlsym;
141 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
143 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
146 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
147 ecx.memory().extra.validate
152 ecx: &mut InterpCx<'mir, 'tcx, Self>,
153 instance: ty::Instance<'tcx>,
154 args: &[OpTy<'tcx, Tag>],
155 dest: Option<PlaceTy<'tcx, Tag>>,
156 ret: Option<mir::BasicBlock>,
157 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
158 ecx.find_fn(instance, args, dest, ret)
163 ecx: &mut InterpCx<'mir, 'tcx, Self>,
165 args: &[OpTy<'tcx, Tag>],
166 dest: Option<PlaceTy<'tcx, Tag>>,
167 ret: Option<mir::BasicBlock>,
168 ) -> InterpResult<'tcx> {
169 ecx.call_dlsym(fn_val, args, dest, ret)
174 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
175 instance: ty::Instance<'tcx>,
176 args: &[OpTy<'tcx, Tag>],
177 dest: PlaceTy<'tcx, Tag>,
178 ) -> InterpResult<'tcx> {
179 ecx.call_intrinsic(instance, args, dest)
184 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
186 left: ImmTy<'tcx, Tag>,
187 right: ImmTy<'tcx, Tag>,
188 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
189 ecx.ptr_op(bin_op, left, right)
193 ecx: &mut InterpCx<'mir, 'tcx, Self>,
194 dest: PlaceTy<'tcx, Tag>,
195 ) -> InterpResult<'tcx> {
196 trace!("box_alloc for {:?}", dest.layout.ty);
197 // Call the `exchange_malloc` lang item.
198 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
199 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
200 let malloc_mir = ecx.load_mir(malloc.def)?;
201 ecx.push_stack_frame(
206 // Don't do anything when we are done. The `statement()` function will increment
207 // the old stack frame's stmt counter to the next statement, which means that when
208 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
209 StackPopCleanup::None { cleanup: true },
212 let mut args = ecx.frame().body.args_iter();
213 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
215 // First argument: `size`.
216 // (`0` is allowed here -- this is expected to be handled by the lang item).
217 let arg = ecx.local_place(args.next().unwrap())?;
218 let size = layout.size.bytes();
219 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
221 // Second argument: `align`.
222 let arg = ecx.local_place(args.next().unwrap())?;
223 let align = layout.align.abi.bytes();
224 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
226 // No more arguments.
228 args.next().is_none(),
229 "`exchange_malloc` lang item has more arguments than expected"
234 fn find_foreign_static(
237 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
238 let attrs = tcx.get_attrs(def_id);
239 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
240 Some(name) => name.as_str(),
241 None => tcx.item_name(def_id).as_str(),
244 let alloc = match link_name.get() {
245 "__cxa_thread_atexit_impl" => {
246 // This should be all-zero, pointer-sized.
247 let size = tcx.data_layout.pointer_size;
248 let data = vec![0; size.bytes() as usize];
249 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
251 _ => return err!(Unimplemented(
252 format!("can't access foreign static: {}", link_name),
255 Ok(Cow::Owned(alloc))
259 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
261 // We are not interested in detecting loops.
265 fn tag_allocation<'b>(
266 memory_extra: &MemoryExtra,
268 alloc: Cow<'b, Allocation>,
269 kind: Option<MemoryKind<Self::MemoryKinds>>,
270 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
271 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
272 let alloc = alloc.into_owned();
273 let (stacks, base_tag) = if !memory_extra.validate {
274 (None, Tag::Untagged)
276 let (stacks, base_tag) = Stacks::new_allocation(
278 Size::from_bytes(alloc.bytes.len() as u64),
279 Rc::clone(&memory_extra.stacked_borrows),
282 (Some(stacks), base_tag)
284 if kind != MiriMemoryKind::Static.into() {
285 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
286 // Now we can rely on the inner pointers being static, too.
288 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
289 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
291 relocations: Relocations::from_presorted(
292 alloc.relocations.iter()
293 // The allocations in the relocations (pointers stored *inside* this allocation)
294 // all get the base pointer tag.
295 .map(|&(offset, ((), alloc))| {
296 let tag = if !memory_extra.validate {
299 stacked_borrows.static_base_ptr(alloc)
301 (offset, (tag, alloc))
305 undef_mask: alloc.undef_mask,
307 mutability: alloc.mutability,
309 stacked_borrows: stacks,
312 (Cow::Owned(alloc), base_tag)
316 fn tag_static_base_pointer(
317 memory_extra: &MemoryExtra,
319 ) -> Self::PointerTag {
320 if !memory_extra.validate {
323 memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
329 ecx: &mut InterpCx<'mir, 'tcx, Self>,
330 kind: mir::RetagKind,
331 place: PlaceTy<'tcx, Tag>,
332 ) -> InterpResult<'tcx> {
333 if !Self::enforce_validity(ecx) {
337 ecx.retag(kind, place)
343 ecx: &mut InterpCx<'mir, 'tcx, Self>,
344 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
345 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
350 ecx: &mut InterpCx<'mir, 'tcx, Self>,
351 extra: stacked_borrows::CallId,
352 ) -> InterpResult<'tcx> {
353 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
357 memory: &Memory<'mir, 'tcx, Self>,
359 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
361 err!(InvalidNullPointerUsage)
362 } else if memory.extra.rng.is_none() {
363 err!(ReadBytesAsPointer)
365 intptrcast::GlobalState::int_to_ptr(int, memory)
370 memory: &Memory<'mir, 'tcx, Self>,
371 ptr: Pointer<Self::PointerTag>,
372 ) -> InterpResult<'tcx, u64> {
373 if memory.extra.rng.is_none() {
374 err!(ReadPointerAsBytes)
376 intptrcast::GlobalState::ptr_to_int(ptr, memory)
381 impl AllocationExtra<Tag> for AllocExtra {
383 fn memory_read<'tcx>(
384 alloc: &Allocation<Tag, AllocExtra>,
387 ) -> InterpResult<'tcx> {
388 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
389 stacked_borrows.memory_read(ptr, size)
396 fn memory_written<'tcx>(
397 alloc: &mut Allocation<Tag, AllocExtra>,
400 ) -> InterpResult<'tcx> {
401 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
402 stacked_borrows.memory_written(ptr, size)
409 fn memory_deallocated<'tcx>(
410 alloc: &mut Allocation<Tag, AllocExtra>,
413 ) -> InterpResult<'tcx> {
414 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
415 stacked_borrows.memory_deallocated(ptr, size)
422 impl MayLeak for MiriMemoryKind {
424 fn may_leak(self) -> bool {
425 use self::MiriMemoryKind::*;
427 Rust | C | WinHeap => false,
428 Env | Static => true,