1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
8 use rand::rngs::StdRng;
10 use rustc::hir::def_id::DefId;
14 layout::{LayoutOf, Size},
17 use syntax::{attr, source_map::Span, symbol::sym};
21 // Some global facts about the emulated machine.
22 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
23 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
24 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
25 pub const NUM_CPUS: u64 = 1;
27 /// Extra data stored with each stack frame
29 pub struct FrameData<'tcx> {
30 /// Extra data for Stacked Borrows.
31 pub call_id: stacked_borrows::CallId,
33 /// If this is Some(), then this is a special "catch unwind" frame (the frame of the closure
34 /// called by `__rustc_maybe_catch_panic`). When this frame is popped during unwinding a panic,
35 /// we stop unwinding, use the `CatchUnwindData` to
36 /// store the panic payload, and continue execution in the parent frame.
37 pub catch_panic: Option<CatchUnwindData<'tcx>>,
40 /// Extra memory kinds
41 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
42 pub enum MiriMemoryKind {
43 /// `__rust_alloc` memory.
47 /// Windows `HeapAlloc` memory.
49 /// Memory for env vars and args, errno and other parts of the machine-managed environment.
55 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
57 fn into(self) -> MemoryKind<MiriMemoryKind> {
58 MemoryKind::Machine(self)
62 /// Extra per-allocation data
63 #[derive(Debug, Clone)]
64 pub struct AllocExtra {
65 /// Stacked Borrows state is only added if validation is enabled.
66 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
69 /// Extra global memory data
70 #[derive(Clone, Debug)]
71 pub struct MemoryExtra {
72 pub stacked_borrows: stacked_borrows::MemoryExtra,
73 pub intptrcast: intptrcast::MemoryExtra,
75 /// The random number generator used for resolving non-determinism.
76 pub(crate) rng: RefCell<StdRng>,
78 /// Whether to enforce the validity invariant.
79 pub(crate) validate: bool,
83 pub fn new(rng: StdRng, validate: bool, tracked_pointer_tag: Option<PtrId>) -> Self {
85 stacked_borrows: Rc::new(RefCell::new(GlobalState::new(tracked_pointer_tag))),
86 intptrcast: Default::default(),
87 rng: RefCell::new(rng),
93 /// The machine itself.
94 pub struct Evaluator<'tcx> {
95 /// Environment variables set by `setenv`.
96 /// Miri does not expose env vars from the host to the emulated program.
97 pub(crate) env_vars: EnvVars,
99 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
100 /// These are *pointers* to argc/argv because macOS.
101 /// We also need the full command line as one string because of Windows.
102 pub(crate) argc: Option<Scalar<Tag>>,
103 pub(crate) argv: Option<Scalar<Tag>>,
104 pub(crate) cmd_line: Option<Scalar<Tag>>,
106 /// Last OS error location in memory. It is a 32-bit integer.
107 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
110 pub(crate) tls: TlsData<'tcx>,
112 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
113 /// and random number generation is delegated to the host.
114 pub(crate) communicate: bool,
116 pub(crate) file_handler: FileHandler,
118 /// The temporary used for storing the argument of
119 /// the call to `miri_start_panic` (the panic payload) when unwinding.
120 pub(crate) panic_payload: Option<ImmTy<'tcx, Tag>>,
123 impl<'tcx> Evaluator<'tcx> {
124 pub(crate) fn new(communicate: bool) -> Self {
126 // `env_vars` could be initialized properly here if `Memory` were available before
127 // calling this method.
128 env_vars: EnvVars::default(),
133 tls: TlsData::default(),
135 file_handler: Default::default(),
141 /// A rustc InterpCx for Miri.
142 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
144 /// A little trait that's useful to be inherited by extension traits.
145 pub trait MiriEvalContextExt<'mir, 'tcx> {
146 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
147 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
149 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
151 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
155 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
160 /// Machine hook implementations.
161 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
162 type MemoryKinds = MiriMemoryKind;
164 type FrameExtra = FrameData<'tcx>;
165 type MemoryExtra = MemoryExtra;
166 type AllocExtra = AllocExtra;
167 type PointerTag = Tag;
168 type ExtraFnVal = Dlsym;
171 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
173 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
175 const CHECK_ALIGN: bool = true;
178 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
179 ecx.memory.extra.validate
183 fn find_mir_or_eval_fn(
184 ecx: &mut InterpCx<'mir, 'tcx, Self>,
185 instance: ty::Instance<'tcx>,
186 args: &[OpTy<'tcx, Tag>],
187 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
188 unwind: Option<mir::BasicBlock>,
189 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
190 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
195 ecx: &mut InterpCx<'mir, 'tcx, Self>,
197 args: &[OpTy<'tcx, Tag>],
198 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
199 _unwind: Option<mir::BasicBlock>,
200 ) -> InterpResult<'tcx> {
201 ecx.call_dlsym(fn_val, args, ret)
206 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
208 instance: ty::Instance<'tcx>,
209 args: &[OpTy<'tcx, Tag>],
210 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
211 unwind: Option<mir::BasicBlock>,
212 ) -> InterpResult<'tcx> {
213 ecx.call_intrinsic(span, instance, args, ret, unwind)
218 ecx: &mut InterpCx<'mir, 'tcx, Self>,
220 msg: &AssertMessage<'tcx>,
221 unwind: Option<mir::BasicBlock>,
222 ) -> InterpResult<'tcx> {
223 ecx.assert_panic(span, msg, unwind)
228 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
230 left: ImmTy<'tcx, Tag>,
231 right: ImmTy<'tcx, Tag>,
232 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
233 ecx.binary_ptr_op(bin_op, left, right)
237 ecx: &mut InterpCx<'mir, 'tcx, Self>,
238 dest: PlaceTy<'tcx, Tag>,
239 ) -> InterpResult<'tcx> {
240 trace!("box_alloc for {:?}", dest.layout.ty);
241 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
242 // First argument: `size`.
243 // (`0` is allowed here -- this is expected to be handled by the lang item).
244 let size = Scalar::from_uint(layout.size.bytes(), ecx.pointer_size());
246 // Second argument: `align`.
247 let align = Scalar::from_uint(layout.align.abi.bytes(), ecx.pointer_size());
249 // Call the `exchange_malloc` lang item.
250 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
251 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
254 &[size.into(), align.into()],
256 // Don't do anything when we are done. The `statement()` function will increment
257 // the old stack frame's stmt counter to the next statement, which means that when
258 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
259 StackPopCleanup::None { cleanup: true },
264 fn find_foreign_static(
267 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
268 let attrs = tcx.get_attrs(def_id);
269 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
270 Some(name) => name.as_str(),
271 None => tcx.item_name(def_id).as_str(),
274 let alloc = match &*link_name {
275 "__cxa_thread_atexit_impl" => {
276 // This should be all-zero, pointer-sized.
277 let size = tcx.data_layout.pointer_size;
278 let data = vec![0; size.bytes() as usize];
279 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
281 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
283 Ok(Cow::Owned(alloc))
287 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
288 // We are not interested in detecting loops.
292 fn init_allocation_extra<'b>(
293 memory_extra: &MemoryExtra,
295 alloc: Cow<'b, Allocation>,
296 kind: Option<MemoryKind<Self::MemoryKinds>>,
297 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
298 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
299 let alloc = alloc.into_owned();
300 let (stacks, base_tag) = if memory_extra.validate {
301 let (stacks, base_tag) = Stacks::new_allocation(
304 Rc::clone(&memory_extra.stacked_borrows),
307 (Some(stacks), base_tag)
309 // No stacks, no tag.
310 (None, Tag::Untagged)
312 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
313 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
315 if !memory_extra.validate {
318 // Only statics may already contain pointers at this point
319 assert_eq!(kind, MiriMemoryKind::Static.into());
320 stacked_borrows.static_base_ptr(alloc)
323 AllocExtra { stacked_borrows: stacks },
325 (Cow::Owned(alloc), base_tag)
329 fn tag_static_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
330 if !memory_extra.validate {
333 memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
339 ecx: &mut InterpCx<'mir, 'tcx, Self>,
340 kind: mir::RetagKind,
341 place: PlaceTy<'tcx, Tag>,
342 ) -> InterpResult<'tcx> {
343 if !Self::enforce_validity(ecx) {
347 ecx.retag(kind, place)
352 fn stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, FrameData<'tcx>> {
354 call_id: ecx.memory.extra.stacked_borrows.borrow_mut().new_call(),
361 ecx: &mut InterpCx<'mir, 'tcx, Self>,
362 extra: FrameData<'tcx>,
364 ) -> InterpResult<'tcx, StackPopInfo> {
365 ecx.handle_stack_pop(extra, unwinding)
370 memory: &Memory<'mir, 'tcx, Self>,
372 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
373 intptrcast::GlobalState::int_to_ptr(int, memory)
378 memory: &Memory<'mir, 'tcx, Self>,
379 ptr: Pointer<Self::PointerTag>,
380 ) -> InterpResult<'tcx, u64> {
381 intptrcast::GlobalState::ptr_to_int(ptr, memory)
385 impl AllocationExtra<Tag> for AllocExtra {
387 fn memory_read<'tcx>(
388 alloc: &Allocation<Tag, AllocExtra>,
391 ) -> InterpResult<'tcx> {
392 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
393 stacked_borrows.memory_read(ptr, size)
400 fn memory_written<'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_written(ptr, size)
413 fn memory_deallocated<'tcx>(
414 alloc: &mut Allocation<Tag, AllocExtra>,
417 ) -> InterpResult<'tcx> {
418 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
419 stacked_borrows.memory_deallocated(ptr, size)
426 impl MayLeak for MiriMemoryKind {
428 fn may_leak(self) -> bool {
429 use self::MiriMemoryKind::*;
431 Rust | C | WinHeap => false,
432 Env | Static => true,