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 used for resolving non-determinism.
61 pub(crate) rng: RefCell<StdRng>,
63 /// Whether to enforce the validity invariant.
64 pub(crate) validate: bool,
68 pub fn new(rng: StdRng, validate: bool) -> Self {
70 stacked_borrows: Default::default(),
71 intptrcast: Default::default(),
72 rng: RefCell::new(rng),
78 /// The machine itself.
79 pub struct Evaluator<'tcx> {
80 /// Environment variables set by `setenv`.
81 /// Miri does not expose env vars from the host to the emulated program.
82 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
84 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
85 /// These are *pointers* to argc/argv because macOS.
86 /// We also need the full command line as one string because of Windows.
87 pub(crate) argc: Option<Pointer<Tag>>,
88 pub(crate) argv: Option<Pointer<Tag>>,
89 pub(crate) cmd_line: Option<Pointer<Tag>>,
92 pub(crate) last_error: u32,
95 pub(crate) tls: TlsData<'tcx>,
98 impl<'tcx> Evaluator<'tcx> {
99 pub(crate) fn new() -> Self {
101 env_vars: HashMap::default(),
106 tls: TlsData::default(),
111 /// A rustc InterpCx for Miri.
112 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
114 /// A little trait that's useful to be inherited by extension traits.
115 pub trait MiriEvalContextExt<'mir, 'tcx> {
116 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
117 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
119 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
121 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
125 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
130 /// Machine hook implementations.
131 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
132 type MemoryKinds = MiriMemoryKind;
134 type FrameExtra = stacked_borrows::CallId;
135 type MemoryExtra = MemoryExtra;
136 type AllocExtra = AllocExtra;
137 type PointerTag = Tag;
138 type ExtraFnVal = Dlsym;
140 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
142 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
144 const CHECK_ALIGN: bool = true;
147 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
148 ecx.memory().extra.validate
153 ecx: &mut InterpCx<'mir, 'tcx, Self>,
154 instance: ty::Instance<'tcx>,
155 args: &[OpTy<'tcx, Tag>],
156 dest: Option<PlaceTy<'tcx, Tag>>,
157 ret: Option<mir::BasicBlock>,
158 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
159 ecx.find_fn(instance, args, dest, ret)
164 ecx: &mut InterpCx<'mir, 'tcx, Self>,
166 args: &[OpTy<'tcx, Tag>],
167 dest: Option<PlaceTy<'tcx, Tag>>,
168 ret: Option<mir::BasicBlock>,
169 ) -> InterpResult<'tcx> {
170 ecx.call_dlsym(fn_val, args, dest, ret)
175 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
176 instance: ty::Instance<'tcx>,
177 args: &[OpTy<'tcx, Tag>],
178 dest: PlaceTy<'tcx, Tag>,
179 ) -> InterpResult<'tcx> {
180 ecx.call_intrinsic(instance, args, dest)
185 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
187 left: ImmTy<'tcx, Tag>,
188 right: ImmTy<'tcx, Tag>,
189 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
190 ecx.binary_ptr_op(bin_op, left, right)
194 ecx: &mut InterpCx<'mir, 'tcx, Self>,
195 dest: PlaceTy<'tcx, Tag>,
196 ) -> InterpResult<'tcx> {
197 trace!("box_alloc for {:?}", dest.layout.ty);
198 // Call the `exchange_malloc` lang item.
199 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
200 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
201 let malloc_mir = ecx.load_mir(malloc.def)?;
202 ecx.push_stack_frame(
207 // Don't do anything when we are done. The `statement()` function will increment
208 // the old stack frame's stmt counter to the next statement, which means that when
209 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
210 StackPopCleanup::None { cleanup: true },
213 let mut args = ecx.frame().body.args_iter();
214 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
216 // First argument: `size`.
217 // (`0` is allowed here -- this is expected to be handled by the lang item).
218 let arg = ecx.local_place(args.next().unwrap())?;
219 let size = layout.size.bytes();
220 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
222 // Second argument: `align`.
223 let arg = ecx.local_place(args.next().unwrap())?;
224 let align = layout.align.abi.bytes();
225 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
227 // No more arguments.
229 args.next().is_none(),
230 "`exchange_malloc` lang item has more arguments than expected"
235 fn find_foreign_static(
238 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
239 let attrs = tcx.get_attrs(def_id);
240 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
241 Some(name) => name.as_str(),
242 None => tcx.item_name(def_id).as_str(),
245 let alloc = match link_name.get() {
246 "__cxa_thread_atexit_impl" => {
247 // This should be all-zero, pointer-sized.
248 let size = tcx.data_layout.pointer_size;
249 let data = vec![0; size.bytes() as usize];
250 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
252 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
254 Ok(Cow::Owned(alloc))
258 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
260 // We are not interested in detecting loops.
264 fn tag_allocation<'b>(
265 memory_extra: &MemoryExtra,
267 alloc: Cow<'b, Allocation>,
268 kind: Option<MemoryKind<Self::MemoryKinds>>,
269 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
270 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
271 let alloc = alloc.into_owned();
272 let (stacks, base_tag) = if !memory_extra.validate {
273 (None, Tag::Untagged)
275 let (stacks, base_tag) = Stacks::new_allocation(
277 Size::from_bytes(alloc.bytes.len() as u64),
278 Rc::clone(&memory_extra.stacked_borrows),
281 (Some(stacks), base_tag)
283 if kind != MiriMemoryKind::Static.into() {
284 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
285 // Now we can rely on the inner pointers being static, too.
287 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
288 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
290 relocations: Relocations::from_presorted(
291 alloc.relocations.iter()
292 // The allocations in the relocations (pointers stored *inside* this allocation)
293 // all get the base pointer tag.
294 .map(|&(offset, ((), alloc))| {
295 let tag = if !memory_extra.validate {
298 stacked_borrows.static_base_ptr(alloc)
300 (offset, (tag, alloc))
304 undef_mask: alloc.undef_mask,
306 mutability: alloc.mutability,
308 stacked_borrows: stacks,
311 (Cow::Owned(alloc), base_tag)
315 fn tag_static_base_pointer(
316 memory_extra: &MemoryExtra,
318 ) -> Self::PointerTag {
319 if !memory_extra.validate {
322 memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
328 ecx: &mut InterpCx<'mir, 'tcx, Self>,
329 kind: mir::RetagKind,
330 place: PlaceTy<'tcx, Tag>,
331 ) -> InterpResult<'tcx> {
332 if !Self::enforce_validity(ecx) {
336 ecx.retag(kind, place)
342 ecx: &mut InterpCx<'mir, 'tcx, Self>,
343 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
344 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
349 ecx: &mut InterpCx<'mir, 'tcx, Self>,
350 extra: stacked_borrows::CallId,
351 ) -> InterpResult<'tcx> {
352 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
357 memory: &Memory<'mir, 'tcx, Self>,
359 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
360 intptrcast::GlobalState::int_to_ptr(int, memory)
365 memory: &Memory<'mir, 'tcx, Self>,
366 ptr: Pointer<Self::PointerTag>,
367 ) -> InterpResult<'tcx, u64> {
368 intptrcast::GlobalState::ptr_to_int(ptr, memory)
372 impl AllocationExtra<Tag> for AllocExtra {
374 fn memory_read<'tcx>(
375 alloc: &Allocation<Tag, AllocExtra>,
378 ) -> InterpResult<'tcx> {
379 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
380 stacked_borrows.memory_read(ptr, size)
387 fn memory_written<'tcx>(
388 alloc: &mut Allocation<Tag, AllocExtra>,
391 ) -> InterpResult<'tcx> {
392 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
393 stacked_borrows.memory_written(ptr, size)
400 fn memory_deallocated<'tcx>(
401 alloc: &mut Allocation<Tag, AllocExtra>,
404 ) -> InterpResult<'tcx> {
405 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
406 stacked_borrows.memory_deallocated(ptr, size)
413 impl MayLeak for MiriMemoryKind {
415 fn may_leak(self) -> bool {
416 use self::MiriMemoryKind::*;
418 Rust | C | WinHeap => false,
419 Env | Static => true,