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},
18 use syntax::symbol::sym;
22 // Some global facts about the emulated machine.
23 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
24 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
25 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
26 pub const NUM_CPUS: u64 = 1;
28 /// Extra memory kinds
29 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
30 pub enum MiriMemoryKind {
31 /// `__rust_alloc` memory.
35 /// Windows `HeapAlloc` memory.
37 /// Part of env var emulation.
43 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
45 fn into(self) -> MemoryKind<MiriMemoryKind> {
46 MemoryKind::Machine(self)
50 /// Extra per-allocation data
51 #[derive(Debug, Clone)]
52 pub struct AllocExtra {
53 /// Stacked Borrows state is only added if validation is enabled.
54 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
57 /// Extra global memory data
58 #[derive(Clone, Debug)]
59 pub struct MemoryExtra {
60 pub stacked_borrows: stacked_borrows::MemoryExtra,
61 pub intptrcast: intptrcast::MemoryExtra,
63 /// The random number generator used for resolving non-determinism.
64 pub(crate) rng: RefCell<StdRng>,
66 /// Whether to enforce the validity invariant.
67 pub(crate) validate: bool,
71 pub fn new(rng: StdRng, validate: bool) -> Self {
73 stacked_borrows: Default::default(),
74 intptrcast: Default::default(),
75 rng: RefCell::new(rng),
81 /// The machine itself.
82 pub struct Evaluator<'tcx> {
83 /// Environment variables set by `setenv`.
84 /// Miri does not expose env vars from the host to the emulated program.
85 pub(crate) env_vars: EnvVars,
87 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
88 /// These are *pointers* to argc/argv because macOS.
89 /// We also need the full command line as one string because of Windows.
90 pub(crate) argc: Option<Pointer<Tag>>,
91 pub(crate) argv: Option<Pointer<Tag>>,
92 pub(crate) cmd_line: Option<Pointer<Tag>>,
95 pub(crate) last_error: Option<Pointer<Tag>>,
98 pub(crate) tls: TlsData<'tcx>,
100 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
101 /// and random number generation is delegated to the host.
102 pub(crate) communicate: bool,
104 pub(crate) file_handler: FileHandler,
107 impl<'tcx> Evaluator<'tcx> {
108 pub(crate) fn new(communicate: bool) -> Self {
110 // `env_vars` could be initialized properly here if `Memory` were available before
111 // calling this method.
112 env_vars: EnvVars::default(),
117 tls: TlsData::default(),
119 file_handler: Default::default(),
124 /// A rustc InterpCx for Miri.
125 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
127 /// A little trait that's useful to be inherited by extension traits.
128 pub trait MiriEvalContextExt<'mir, 'tcx> {
129 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
130 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
132 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
134 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
138 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
143 /// Machine hook implementations.
144 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
145 type MemoryKinds = MiriMemoryKind;
147 type FrameExtra = stacked_borrows::CallId;
148 type MemoryExtra = MemoryExtra;
149 type AllocExtra = AllocExtra;
150 type PointerTag = Tag;
151 type ExtraFnVal = Dlsym;
153 type MemoryMap = MonoHashMap<
156 MemoryKind<MiriMemoryKind>,
157 Allocation<Tag, Self::AllocExtra>,
161 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
163 const CHECK_ALIGN: bool = true;
166 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
167 ecx.memory.extra.validate
172 ecx: &mut InterpCx<'mir, 'tcx, Self>,
173 instance: ty::Instance<'tcx>,
174 args: &[OpTy<'tcx, Tag>],
175 dest: Option<PlaceTy<'tcx, Tag>>,
176 ret: Option<mir::BasicBlock>,
177 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
178 ecx.find_fn(instance, args, dest, ret)
183 ecx: &mut InterpCx<'mir, 'tcx, Self>,
185 args: &[OpTy<'tcx, Tag>],
186 dest: Option<PlaceTy<'tcx, Tag>>,
187 ret: Option<mir::BasicBlock>,
188 ) -> InterpResult<'tcx> {
189 ecx.call_dlsym(fn_val, args, dest, ret)
194 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
195 instance: ty::Instance<'tcx>,
196 args: &[OpTy<'tcx, Tag>],
197 dest: PlaceTy<'tcx, Tag>,
198 ) -> InterpResult<'tcx> {
199 ecx.call_intrinsic(instance, args, dest)
204 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
206 left: ImmTy<'tcx, Tag>,
207 right: ImmTy<'tcx, Tag>,
208 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
209 ecx.binary_ptr_op(bin_op, left, right)
213 ecx: &mut InterpCx<'mir, 'tcx, Self>,
214 dest: PlaceTy<'tcx, Tag>,
215 ) -> InterpResult<'tcx> {
216 trace!("box_alloc for {:?}", dest.layout.ty);
217 // Call the `exchange_malloc` lang item.
218 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
219 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
220 let malloc_mir = ecx.load_mir(malloc.def, None)?;
221 ecx.push_stack_frame(
226 // Don't do anything when we are done. The `statement()` function will increment
227 // the old stack frame's stmt counter to the next statement, which means that when
228 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
229 StackPopCleanup::None { cleanup: true },
232 let mut args = ecx.frame().body.args_iter();
233 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
235 // First argument: `size`.
236 // (`0` is allowed here -- this is expected to be handled by the lang item).
237 let arg = ecx.local_place(args.next().unwrap())?;
238 let size = layout.size.bytes();
239 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
241 // Second argument: `align`.
242 let arg = ecx.local_place(args.next().unwrap())?;
243 let align = layout.align.abi.bytes();
244 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
246 // No more arguments.
248 args.next().is_none(),
249 "`exchange_malloc` lang item has more arguments than expected"
254 fn find_foreign_static(
257 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
258 let attrs = tcx.get_attrs(def_id);
259 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
260 Some(name) => name.as_str(),
261 None => tcx.item_name(def_id).as_str(),
264 let alloc = match &*link_name {
265 "__cxa_thread_atexit_impl" => {
266 // This should be all-zero, pointer-sized.
267 let size = tcx.data_layout.pointer_size;
268 let data = vec![0; size.bytes() as usize];
269 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
271 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
273 Ok(Cow::Owned(alloc))
277 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
278 // We are not interested in detecting loops.
282 fn tag_allocation<'b>(
283 memory_extra: &MemoryExtra,
285 alloc: Cow<'b, Allocation>,
286 kind: Option<MemoryKind<Self::MemoryKinds>>,
288 Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>,
291 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
292 let alloc = alloc.into_owned();
293 let (stacks, base_tag) = if !memory_extra.validate {
294 (None, Tag::Untagged)
296 let (stacks, base_tag) = Stacks::new_allocation(
299 Rc::clone(&memory_extra.stacked_borrows),
302 (Some(stacks), base_tag)
304 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
305 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
307 if !memory_extra.validate {
310 // Only statics may already contain pointers at this point
311 assert_eq!(kind, MiriMemoryKind::Static.into());
312 stacked_borrows.static_base_ptr(alloc)
316 stacked_borrows: stacks,
319 (Cow::Owned(alloc), base_tag)
323 fn tag_static_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
324 if !memory_extra.validate {
336 ecx: &mut InterpCx<'mir, 'tcx, Self>,
337 kind: mir::RetagKind,
338 place: PlaceTy<'tcx, Tag>,
339 ) -> InterpResult<'tcx> {
340 if !Self::enforce_validity(ecx) {
344 ecx.retag(kind, place)
350 ecx: &mut InterpCx<'mir, 'tcx, Self>,
351 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
352 Ok(ecx.memory.extra.stacked_borrows.borrow_mut().new_call())
357 ecx: &mut InterpCx<'mir, 'tcx, Self>,
358 extra: stacked_borrows::CallId,
359 ) -> InterpResult<'tcx> {
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,