3 use std::collections::HashMap;
4 use std::cell::RefCell;
6 use rand::rngs::StdRng;
9 use syntax::symbol::sym;
10 use rustc::hir::def_id::DefId;
11 use rustc::ty::{self, layout::{Size, LayoutOf}, query::TyCtxtAt};
16 // Some global facts about the emulated machine.
17 pub const PAGE_SIZE: u64 = 4*1024; // FIXME: adjust to target architecture
18 pub const STACK_ADDR: u64 = 16*PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
19 pub const NUM_CPUS: u64 = 1;
21 /// Extra memory kinds
22 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
23 pub enum MiriMemoryKind {
24 /// `__rust_alloc` memory.
28 /// Windows `HeapAlloc` memory.
30 /// Part of env var emulation.
36 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
38 fn into(self) -> MemoryKind<MiriMemoryKind> {
39 MemoryKind::Machine(self)
43 /// Extra per-allocation data
44 #[derive(Debug, Clone)]
45 pub struct AllocExtra {
46 /// Stacked Borrows state is only added if validation is enabled.
47 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
50 /// Extra global memory data
51 #[derive(Default, Clone, Debug)]
52 pub struct MemoryExtra {
53 pub stacked_borrows: stacked_borrows::MemoryExtra,
54 pub intptrcast: intptrcast::MemoryExtra,
56 /// The random number generator to use if Miri is running in non-deterministic mode and to
58 pub(crate) rng: Option<RefCell<StdRng>>,
60 /// Whether to enforce the validity invariant.
61 pub(crate) validate: bool,
65 pub fn new(rng: Option<StdRng>, validate: bool) -> Self {
67 stacked_borrows: Default::default(),
68 intptrcast: Default::default(),
69 rng: rng.map(RefCell::new),
75 /// The machine itself.
76 pub struct Evaluator<'tcx> {
77 /// Environment variables set by `setenv`.
78 /// Miri does not expose env vars from the host to the emulated program.
79 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
81 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
82 /// These are *pointers* to argc/argv because macOS.
83 /// We also need the full command line as one string because of Windows.
84 pub(crate) argc: Option<Pointer<Tag>>,
85 pub(crate) argv: Option<Pointer<Tag>>,
86 pub(crate) cmd_line: Option<Pointer<Tag>>,
89 pub(crate) last_error: u32,
92 pub(crate) tls: TlsData<'tcx>,
95 impl<'tcx> Evaluator<'tcx> {
96 pub(crate) fn new() -> Self {
98 env_vars: HashMap::default(),
103 tls: TlsData::default(),
108 /// A rustc InterpCx for Miri.
109 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
111 /// A little trait that's useful to be inherited by extension traits.
112 pub trait MiriEvalContextExt<'mir, 'tcx> {
113 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
114 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
116 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
118 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
122 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
127 /// Machine hook implementations.
128 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
129 type MemoryKinds = MiriMemoryKind;
131 type FrameExtra = stacked_borrows::CallId;
132 type MemoryExtra = MemoryExtra;
133 type AllocExtra = AllocExtra;
134 type PointerTag = Tag;
136 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
138 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
141 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
142 ecx.memory().extra.validate
145 /// Returns `Ok()` when the function was handled; fail otherwise.
148 ecx: &mut InterpCx<'mir, 'tcx, Self>,
149 instance: ty::Instance<'tcx>,
150 args: &[OpTy<'tcx, Tag>],
151 dest: Option<PlaceTy<'tcx, Tag>>,
152 ret: Option<mir::BasicBlock>,
153 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
154 ecx.find_fn(instance, args, dest, ret)
159 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
160 instance: ty::Instance<'tcx>,
161 args: &[OpTy<'tcx, Tag>],
162 dest: PlaceTy<'tcx, Tag>,
163 ) -> InterpResult<'tcx> {
164 ecx.call_intrinsic(instance, args, dest)
169 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
171 left: ImmTy<'tcx, Tag>,
172 right: ImmTy<'tcx, Tag>,
173 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
174 ecx.ptr_op(bin_op, left, right)
178 ecx: &mut InterpCx<'mir, 'tcx, Self>,
179 dest: PlaceTy<'tcx, Tag>,
180 ) -> InterpResult<'tcx> {
181 trace!("box_alloc for {:?}", dest.layout.ty);
182 // Call the `exchange_malloc` lang item.
183 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
184 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
185 let malloc_mir = ecx.load_mir(malloc.def)?;
186 ecx.push_stack_frame(
191 // Don't do anything when we are done. The `statement()` function will increment
192 // the old stack frame's stmt counter to the next statement, which means that when
193 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
194 StackPopCleanup::None { cleanup: true },
197 let mut args = ecx.frame().body.args_iter();
198 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
200 // First argument: `size`.
201 // (`0` is allowed here -- this is expected to be handled by the lang item).
202 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
203 let size = layout.size.bytes();
204 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
206 // Second argument: `align`.
207 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
208 let align = layout.align.abi.bytes();
209 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
211 // No more arguments.
213 args.next().is_none(),
214 "`exchange_malloc` lang item has more arguments than expected"
219 fn find_foreign_static(
222 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
223 let attrs = tcx.get_attrs(def_id);
224 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
225 Some(name) => name.as_str(),
226 None => tcx.item_name(def_id).as_str(),
229 let alloc = match link_name.get() {
230 "__cxa_thread_atexit_impl" => {
231 // This should be all-zero, pointer-sized.
232 let size = tcx.data_layout.pointer_size;
233 let data = vec![0; size.bytes() as usize];
234 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
236 _ => return err!(Unimplemented(
237 format!("can't access foreign static: {}", link_name),
240 Ok(Cow::Owned(alloc))
244 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
246 // We are not interested in detecting loops.
250 fn tag_allocation<'b>(
252 alloc: Cow<'b, Allocation>,
253 kind: Option<MemoryKind<Self::MemoryKinds>>,
254 memory: &Memory<'mir, 'tcx, Self>,
255 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
256 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
257 let alloc = alloc.into_owned();
258 let (stacks, base_tag) = if !memory.extra.validate {
259 (None, Tag::Untagged)
261 let (stacks, base_tag) = Stacks::new_allocation(
263 Size::from_bytes(alloc.bytes.len() as u64),
264 Rc::clone(&memory.extra.stacked_borrows),
267 (Some(stacks), base_tag)
269 if kind != MiriMemoryKind::Static.into() {
270 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
271 // Now we can rely on the inner pointers being static, too.
273 let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
274 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
276 relocations: Relocations::from_presorted(
277 alloc.relocations.iter()
278 // The allocations in the relocations (pointers stored *inside* this allocation)
279 // all get the base pointer tag.
280 .map(|&(offset, ((), alloc))| {
281 let tag = if !memory.extra.validate {
284 memory_extra.static_base_ptr(alloc)
286 (offset, (tag, alloc))
290 undef_mask: alloc.undef_mask,
292 mutability: alloc.mutability,
294 stacked_borrows: stacks,
297 (Cow::Owned(alloc), base_tag)
301 fn tag_static_base_pointer(
303 memory: &Memory<'mir, 'tcx, Self>,
304 ) -> Self::PointerTag {
305 if !memory.extra.validate {
308 memory.extra.stacked_borrows.borrow_mut().static_base_ptr(id)
314 ecx: &mut InterpCx<'mir, 'tcx, Self>,
315 kind: mir::RetagKind,
316 place: PlaceTy<'tcx, Tag>,
317 ) -> InterpResult<'tcx> {
318 if !Self::enforce_validity(ecx) {
322 ecx.retag(kind, place)
328 ecx: &mut InterpCx<'mir, 'tcx, Self>,
329 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
330 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
335 ecx: &mut InterpCx<'mir, 'tcx, Self>,
336 extra: stacked_borrows::CallId,
337 ) -> InterpResult<'tcx> {
338 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
343 memory: &Memory<'mir, 'tcx, Self>,
344 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
346 err!(InvalidNullPointerUsage)
347 } else if memory.extra.rng.is_none() {
348 err!(ReadBytesAsPointer)
350 intptrcast::GlobalState::int_to_ptr(int, memory)
355 ptr: Pointer<Self::PointerTag>,
356 memory: &Memory<'mir, 'tcx, Self>,
357 ) -> InterpResult<'tcx, u64> {
358 if memory.extra.rng.is_none() {
359 err!(ReadPointerAsBytes)
361 intptrcast::GlobalState::ptr_to_int(ptr, memory)
366 impl AllocationExtra<Tag> for AllocExtra {
368 fn memory_read<'tcx>(
369 alloc: &Allocation<Tag, AllocExtra>,
372 ) -> InterpResult<'tcx> {
373 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
374 stacked_borrows.memory_read(ptr, size)
381 fn memory_written<'tcx>(
382 alloc: &mut Allocation<Tag, AllocExtra>,
385 ) -> InterpResult<'tcx> {
386 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
387 stacked_borrows.memory_written(ptr, size)
394 fn memory_deallocated<'tcx>(
395 alloc: &mut Allocation<Tag, AllocExtra>,
398 ) -> InterpResult<'tcx> {
399 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
400 stacked_borrows.memory_deallocated(ptr, size)
407 impl MayLeak for MiriMemoryKind {
409 fn may_leak(self) -> bool {
410 use self::MiriMemoryKind::*;
412 Rust | C | WinHeap => false,
413 Env | Static => true,