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 pub stacked_borrows: stacked_borrows::AllocExtra,
47 /// Extra global memory data
48 #[derive(Default, Clone, Debug)]
49 pub struct MemoryExtra {
50 pub stacked_borrows: stacked_borrows::MemoryExtra,
51 pub intptrcast: intptrcast::MemoryExtra,
52 /// The random number generator to use if Miri is running in non-deterministic mode and to
54 pub(crate) rng: Option<RefCell<StdRng>>
58 pub fn with_rng(rng: Option<StdRng>) -> Self {
60 stacked_borrows: Default::default(),
61 intptrcast: Default::default(),
62 rng: rng.map(RefCell::new),
67 /// The machine itself.
68 pub struct Evaluator<'tcx> {
69 /// Environment variables set by `setenv`.
70 /// Miri does not expose env vars from the host to the emulated program.
71 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
73 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
74 /// These are *pointers* to argc/argv because macOS.
75 /// We also need the full command line as one string because of Windows.
76 pub(crate) argc: Option<Pointer<Tag>>,
77 pub(crate) argv: Option<Pointer<Tag>>,
78 pub(crate) cmd_line: Option<Pointer<Tag>>,
81 pub(crate) last_error: u32,
84 pub(crate) tls: TlsData<'tcx>,
86 /// Whether to enforce the validity invariant.
87 pub(crate) validate: bool,
90 impl<'tcx> Evaluator<'tcx> {
91 pub(crate) fn new(validate: bool) -> Self {
93 env_vars: HashMap::default(),
98 tls: TlsData::default(),
104 /// A rustc InterpretCx for Miri.
105 pub type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
107 /// A little trait that's useful to be inherited by extension traits.
108 pub trait MiriEvalContextExt<'mir, 'tcx> {
109 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
110 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
112 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
114 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
118 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
123 /// Machine hook implementations.
124 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
125 type MemoryKinds = MiriMemoryKind;
127 type FrameExtra = stacked_borrows::CallId;
128 type MemoryExtra = MemoryExtra;
129 type AllocExtra = AllocExtra;
130 type PointerTag = Tag;
132 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
134 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
137 fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
141 /// Returns `Ok()` when the function was handled; fail otherwise.
144 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
145 instance: ty::Instance<'tcx>,
146 args: &[OpTy<'tcx, Tag>],
147 dest: Option<PlaceTy<'tcx, Tag>>,
148 ret: Option<mir::BasicBlock>,
149 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
150 ecx.find_fn(instance, args, dest, ret)
155 ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
156 instance: ty::Instance<'tcx>,
157 args: &[OpTy<'tcx, Tag>],
158 dest: PlaceTy<'tcx, Tag>,
159 ) -> InterpResult<'tcx> {
160 ecx.call_intrinsic(instance, args, dest)
165 ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
167 left: ImmTy<'tcx, Tag>,
168 right: ImmTy<'tcx, Tag>,
169 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
170 ecx.ptr_op(bin_op, left, right)
174 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
175 dest: PlaceTy<'tcx, Tag>,
176 ) -> InterpResult<'tcx> {
177 trace!("box_alloc for {:?}", dest.layout.ty);
178 // Call the `exchange_malloc` lang item.
179 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
180 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
181 let malloc_mir = ecx.load_mir(malloc.def)?;
182 ecx.push_stack_frame(
187 // Don't do anything when we are done. The `statement()` function will increment
188 // the old stack frame's stmt counter to the next statement, which means that when
189 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
190 StackPopCleanup::None { cleanup: true },
193 let mut args = ecx.frame().body.args_iter();
194 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
196 // First argument: `size`.
197 // (`0` is allowed here -- this is expected to be handled by the lang item).
198 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
199 let size = layout.size.bytes();
200 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
202 // Second argument: `align`.
203 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
204 let align = layout.align.abi.bytes();
205 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
207 // No more arguments.
209 args.next().is_none(),
210 "`exchange_malloc` lang item has more arguments than expected"
215 fn find_foreign_static(
218 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
219 let attrs = tcx.get_attrs(def_id);
220 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
221 Some(name) => name.as_str(),
222 None => tcx.item_name(def_id).as_str(),
225 let alloc = match link_name.get() {
226 "__cxa_thread_atexit_impl" => {
227 // This should be all-zero, pointer-sized.
228 let size = tcx.data_layout.pointer_size;
229 let data = vec![0; size.bytes() as usize];
230 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
232 _ => return err!(Unimplemented(
233 format!("can't access foreign static: {}", link_name),
236 Ok(Cow::Owned(alloc))
240 fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
242 // We are not interested in detecting loops.
246 fn tag_allocation<'b>(
248 alloc: Cow<'b, Allocation>,
249 kind: Option<MemoryKind<Self::MemoryKinds>>,
250 memory: &Memory<'mir, 'tcx, Self>,
251 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
252 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
253 let alloc = alloc.into_owned();
254 let (stacks, base_tag) = Stacks::new_allocation(
256 Size::from_bytes(alloc.bytes.len() as u64),
257 Rc::clone(&memory.extra.stacked_borrows),
260 if kind != MiriMemoryKind::Static.into() {
261 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
262 // Now we can rely on the inner pointers being static, too.
264 let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
265 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
267 relocations: Relocations::from_presorted(
268 alloc.relocations.iter()
269 // The allocations in the relocations (pointers stored *inside* this allocation)
270 // all get the base pointer tag.
271 .map(|&(offset, ((), alloc))| (offset, (memory_extra.static_base_ptr(alloc), alloc)))
274 undef_mask: alloc.undef_mask,
276 mutability: alloc.mutability,
278 stacked_borrows: stacks,
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,