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 /// Part of env var emulation.
34 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
36 fn into(self) -> MemoryKind<MiriMemoryKind> {
37 MemoryKind::Machine(self)
41 /// Extra per-allocation data
42 #[derive(Debug, Clone)]
43 pub struct AllocExtra {
44 /// Stacked Borrows state is only added if validation is enabled.
45 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
48 /// Extra global memory data
49 #[derive(Default, Clone, Debug)]
50 pub struct MemoryExtra {
51 pub stacked_borrows: stacked_borrows::MemoryExtra,
52 pub intptrcast: intptrcast::MemoryExtra,
54 /// The random number generator to use if Miri is running in non-deterministic mode and to
56 pub(crate) rng: Option<RefCell<StdRng>>,
58 /// Whether to enforce the validity invariant.
59 pub(crate) validate: bool,
63 pub fn new(rng: Option<StdRng>, validate: bool) -> Self {
65 stacked_borrows: Default::default(),
66 intptrcast: Default::default(),
67 rng: rng.map(RefCell::new),
73 /// The machine itself.
74 pub struct Evaluator<'tcx> {
75 /// Environment variables set by `setenv`.
76 /// Miri does not expose env vars from the host to the emulated program.
77 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
79 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
80 /// These are *pointers* to argc/argv because macOS.
81 /// We also need the full command line as one string because of Windows.
82 pub(crate) argc: Option<Pointer<Tag>>,
83 pub(crate) argv: Option<Pointer<Tag>>,
84 pub(crate) cmd_line: Option<Pointer<Tag>>,
87 pub(crate) last_error: u32,
90 pub(crate) tls: TlsData<'tcx>,
93 impl<'tcx> Evaluator<'tcx> {
94 pub(crate) fn new() -> Self {
96 env_vars: HashMap::default(),
101 tls: TlsData::default(),
106 /// A rustc InterpretCx for Miri.
107 pub type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
109 /// A little trait that's useful to be inherited by extension traits.
110 pub trait MiriEvalContextExt<'mir, 'tcx> {
111 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
112 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
114 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
116 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
120 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
125 /// Machine hook implementations.
126 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
127 type MemoryKinds = MiriMemoryKind;
129 type FrameExtra = stacked_borrows::CallId;
130 type MemoryExtra = MemoryExtra;
131 type AllocExtra = AllocExtra;
132 type PointerTag = Tag;
134 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
136 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
139 fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
140 ecx.memory().extra.validate
143 /// Returns `Ok()` when the function was handled; fail otherwise.
146 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
147 instance: ty::Instance<'tcx>,
148 args: &[OpTy<'tcx, Tag>],
149 dest: Option<PlaceTy<'tcx, Tag>>,
150 ret: Option<mir::BasicBlock>,
151 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
152 ecx.find_fn(instance, args, dest, ret)
157 ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
158 instance: ty::Instance<'tcx>,
159 args: &[OpTy<'tcx, Tag>],
160 dest: PlaceTy<'tcx, Tag>,
161 ) -> InterpResult<'tcx> {
162 ecx.call_intrinsic(instance, args, dest)
167 ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
169 left: ImmTy<'tcx, Tag>,
170 right: ImmTy<'tcx, Tag>,
171 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
172 ecx.ptr_op(bin_op, left, right)
176 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
177 dest: PlaceTy<'tcx, Tag>,
178 ) -> InterpResult<'tcx> {
179 trace!("box_alloc for {:?}", dest.layout.ty);
180 // Call the `exchange_malloc` lang item.
181 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
182 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
183 let malloc_mir = ecx.load_mir(malloc.def)?;
184 ecx.push_stack_frame(
189 // Don't do anything when we are done. The `statement()` function will increment
190 // the old stack frame's stmt counter to the next statement, which means that when
191 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
192 StackPopCleanup::None { cleanup: true },
195 let mut args = ecx.frame().body.args_iter();
196 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
198 // First argument: `size`.
199 // (`0` is allowed here -- this is expected to be handled by the lang item).
200 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
201 let size = layout.size.bytes();
202 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
204 // Second argument: `align`.
205 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
206 let align = layout.align.abi.bytes();
207 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
209 // No more arguments.
211 args.next().is_none(),
212 "`exchange_malloc` lang item has more arguments than expected"
217 fn find_foreign_static(
220 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
221 let attrs = tcx.get_attrs(def_id);
222 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
223 Some(name) => name.as_str(),
224 None => tcx.item_name(def_id).as_str(),
227 let alloc = match link_name.get() {
228 "__cxa_thread_atexit_impl" => {
229 // This should be all-zero, pointer-sized.
230 let size = tcx.data_layout.pointer_size;
231 let data = vec![0; size.bytes() as usize];
232 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
234 _ => return err!(Unimplemented(
235 format!("can't access foreign static: {}", link_name),
238 Ok(Cow::Owned(alloc))
242 fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
244 // We are not interested in detecting loops.
248 fn tag_allocation<'b>(
250 alloc: Cow<'b, Allocation>,
251 kind: Option<MemoryKind<Self::MemoryKinds>>,
252 memory: &Memory<'mir, 'tcx, Self>,
253 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
254 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
255 let alloc = alloc.into_owned();
256 let (stacks, base_tag) = if !memory.extra.validate {
257 (None, Tag::Untagged)
259 let (stacks, base_tag) = Stacks::new_allocation(
261 Size::from_bytes(alloc.bytes.len() as u64),
262 Rc::clone(&memory.extra.stacked_borrows),
265 (Some(stacks), base_tag)
267 if kind != MiriMemoryKind::Static.into() {
268 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
269 // Now we can rely on the inner pointers being static, too.
271 let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
272 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
274 relocations: Relocations::from_presorted(
275 alloc.relocations.iter()
276 // The allocations in the relocations (pointers stored *inside* this allocation)
277 // all get the base pointer tag.
278 .map(|&(offset, ((), alloc))| {
279 let tag = if !memory.extra.validate {
282 memory_extra.static_base_ptr(alloc)
284 (offset, (tag, alloc))
288 undef_mask: alloc.undef_mask,
290 mutability: alloc.mutability,
292 stacked_borrows: stacks,
295 (Cow::Owned(alloc), base_tag)
299 fn tag_static_base_pointer(
301 memory: &Memory<'mir, 'tcx, Self>,
302 ) -> Self::PointerTag {
303 if !memory.extra.validate {
306 memory.extra.stacked_borrows.borrow_mut().static_base_ptr(id)
312 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
313 kind: mir::RetagKind,
314 place: PlaceTy<'tcx, Tag>,
315 ) -> InterpResult<'tcx> {
316 if !Self::enforce_validity(ecx) {
320 ecx.retag(kind, place)
326 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
327 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
328 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
333 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
334 extra: stacked_borrows::CallId,
335 ) -> InterpResult<'tcx> {
336 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
341 memory: &Memory<'mir, 'tcx, Self>,
342 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
344 err!(InvalidNullPointerUsage)
345 } else if memory.extra.rng.is_none() {
346 err!(ReadBytesAsPointer)
348 intptrcast::GlobalState::int_to_ptr(int, memory)
353 ptr: Pointer<Self::PointerTag>,
354 memory: &Memory<'mir, 'tcx, Self>,
355 ) -> InterpResult<'tcx, u64> {
356 if memory.extra.rng.is_none() {
357 err!(ReadPointerAsBytes)
359 intptrcast::GlobalState::ptr_to_int(ptr, memory)
364 impl AllocationExtra<Tag> for AllocExtra {
366 fn memory_read<'tcx>(
367 alloc: &Allocation<Tag, AllocExtra>,
370 ) -> InterpResult<'tcx> {
371 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
372 stacked_borrows.memory_read(ptr, size)
379 fn memory_written<'tcx>(
380 alloc: &mut Allocation<Tag, AllocExtra>,
383 ) -> InterpResult<'tcx> {
384 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
385 stacked_borrows.memory_written(ptr, size)
392 fn memory_deallocated<'tcx>(
393 alloc: &mut Allocation<Tag, AllocExtra>,
396 ) -> InterpResult<'tcx> {
397 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
398 stacked_borrows.memory_deallocated(ptr, size)
405 impl MayLeak for MiriMemoryKind {
407 fn may_leak(self) -> bool {
408 use self::MiriMemoryKind::*;
411 Env | Static => true,