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>,
97 /// If enabled, the `env_vars` field is populated with the host env vars during initialization.
98 pub(crate) communicate: bool,
101 impl<'tcx> Evaluator<'tcx> {
102 pub(crate) fn new(communicate: bool) -> Self {
104 env_vars: HashMap::default(),
109 tls: TlsData::default(),
115 /// A rustc InterpCx for Miri.
116 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
118 /// A little trait that's useful to be inherited by extension traits.
119 pub trait MiriEvalContextExt<'mir, 'tcx> {
120 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
121 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
123 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
125 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
129 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
134 /// Machine hook implementations.
135 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
136 type MemoryKinds = MiriMemoryKind;
138 type FrameExtra = stacked_borrows::CallId;
139 type MemoryExtra = MemoryExtra;
140 type AllocExtra = AllocExtra;
141 type PointerTag = Tag;
142 type ExtraFnVal = Dlsym;
144 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
146 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
148 const CHECK_ALIGN: bool = true;
151 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
152 ecx.memory().extra.validate
157 ecx: &mut InterpCx<'mir, 'tcx, Self>,
158 instance: ty::Instance<'tcx>,
159 args: &[OpTy<'tcx, Tag>],
160 dest: Option<PlaceTy<'tcx, Tag>>,
161 ret: Option<mir::BasicBlock>,
162 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
163 ecx.find_fn(instance, args, dest, ret)
168 ecx: &mut InterpCx<'mir, 'tcx, Self>,
170 args: &[OpTy<'tcx, Tag>],
171 dest: Option<PlaceTy<'tcx, Tag>>,
172 ret: Option<mir::BasicBlock>,
173 ) -> InterpResult<'tcx> {
174 ecx.call_dlsym(fn_val, args, dest, ret)
179 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
180 instance: ty::Instance<'tcx>,
181 args: &[OpTy<'tcx, Tag>],
182 dest: PlaceTy<'tcx, Tag>,
183 ) -> InterpResult<'tcx> {
184 ecx.call_intrinsic(instance, args, dest)
189 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
191 left: ImmTy<'tcx, Tag>,
192 right: ImmTy<'tcx, Tag>,
193 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
194 ecx.binary_ptr_op(bin_op, left, right)
198 ecx: &mut InterpCx<'mir, 'tcx, Self>,
199 dest: PlaceTy<'tcx, Tag>,
200 ) -> InterpResult<'tcx> {
201 trace!("box_alloc for {:?}", dest.layout.ty);
202 // Call the `exchange_malloc` lang item.
203 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
204 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
205 let malloc_mir = ecx.load_mir(malloc.def)?;
206 ecx.push_stack_frame(
211 // Don't do anything when we are done. The `statement()` function will increment
212 // the old stack frame's stmt counter to the next statement, which means that when
213 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
214 StackPopCleanup::None { cleanup: true },
217 let mut args = ecx.frame().body.args_iter();
218 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
220 // First argument: `size`.
221 // (`0` is allowed here -- this is expected to be handled by the lang item).
222 let arg = ecx.local_place(args.next().unwrap())?;
223 let size = layout.size.bytes();
224 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
226 // Second argument: `align`.
227 let arg = ecx.local_place(args.next().unwrap())?;
228 let align = layout.align.abi.bytes();
229 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
231 // No more arguments.
233 args.next().is_none(),
234 "`exchange_malloc` lang item has more arguments than expected"
239 fn find_foreign_static(
242 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
243 let attrs = tcx.get_attrs(def_id);
244 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
245 Some(name) => name.as_str(),
246 None => tcx.item_name(def_id).as_str(),
249 let alloc = match link_name.get() {
250 "__cxa_thread_atexit_impl" => {
251 // This should be all-zero, pointer-sized.
252 let size = tcx.data_layout.pointer_size;
253 let data = vec![0; size.bytes() as usize];
254 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
256 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
258 Ok(Cow::Owned(alloc))
262 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
264 // We are not interested in detecting loops.
268 fn tag_allocation<'b>(
269 memory_extra: &MemoryExtra,
271 alloc: Cow<'b, Allocation>,
272 kind: Option<MemoryKind<Self::MemoryKinds>>,
273 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
274 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
275 let alloc = alloc.into_owned();
276 let (stacks, base_tag) = if !memory_extra.validate {
277 (None, Tag::Untagged)
279 let (stacks, base_tag) = Stacks::new_allocation(
281 Size::from_bytes(alloc.bytes.len() as u64),
282 Rc::clone(&memory_extra.stacked_borrows),
285 (Some(stacks), base_tag)
287 if kind != MiriMemoryKind::Static.into() {
288 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
289 // Now we can rely on the inner pointers being static, too.
291 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
292 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
294 relocations: Relocations::from_presorted(
295 alloc.relocations.iter()
296 // The allocations in the relocations (pointers stored *inside* this allocation)
297 // all get the base pointer tag.
298 .map(|&(offset, ((), alloc))| {
299 let tag = if !memory_extra.validate {
302 stacked_borrows.static_base_ptr(alloc)
304 (offset, (tag, alloc))
308 undef_mask: alloc.undef_mask,
310 mutability: alloc.mutability,
312 stacked_borrows: stacks,
315 (Cow::Owned(alloc), base_tag)
319 fn tag_static_base_pointer(
320 memory_extra: &MemoryExtra,
322 ) -> Self::PointerTag {
323 if !memory_extra.validate {
326 memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
332 ecx: &mut InterpCx<'mir, 'tcx, Self>,
333 kind: mir::RetagKind,
334 place: PlaceTy<'tcx, Tag>,
335 ) -> InterpResult<'tcx> {
336 if !Self::enforce_validity(ecx) {
340 ecx.retag(kind, place)
346 ecx: &mut InterpCx<'mir, 'tcx, Self>,
347 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
348 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
353 ecx: &mut InterpCx<'mir, 'tcx, Self>,
354 extra: stacked_borrows::CallId,
355 ) -> InterpResult<'tcx> {
356 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
361 memory: &Memory<'mir, 'tcx, Self>,
363 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
364 intptrcast::GlobalState::int_to_ptr(int, memory)
369 memory: &Memory<'mir, 'tcx, Self>,
370 ptr: Pointer<Self::PointerTag>,
371 ) -> InterpResult<'tcx, u64> {
372 intptrcast::GlobalState::ptr_to_int(ptr, memory)
376 impl AllocationExtra<Tag> for AllocExtra {
378 fn memory_read<'tcx>(
379 alloc: &Allocation<Tag, AllocExtra>,
382 ) -> InterpResult<'tcx> {
383 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
384 stacked_borrows.memory_read(ptr, size)
391 fn memory_written<'tcx>(
392 alloc: &mut Allocation<Tag, AllocExtra>,
395 ) -> InterpResult<'tcx> {
396 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
397 stacked_borrows.memory_written(ptr, size)
404 fn memory_deallocated<'tcx>(
405 alloc: &mut Allocation<Tag, AllocExtra>,
408 ) -> InterpResult<'tcx> {
409 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
410 stacked_borrows.memory_deallocated(ptr, size)
417 impl MayLeak for MiriMemoryKind {
419 fn may_leak(self) -> bool {
420 use self::MiriMemoryKind::*;
422 Rust | C | WinHeap => false,
423 Env | Static => true,