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>>,
94 /// Last OS error location in memory. It is a 32-bit integer.
95 pub(crate) last_error: Option<MPlaceTy<'tcx, 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.
247 args.next().expect_none("`exchange_malloc` lang item has more arguments than expected");
251 fn find_foreign_static(
254 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
255 let attrs = tcx.get_attrs(def_id);
256 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
257 Some(name) => name.as_str(),
258 None => tcx.item_name(def_id).as_str(),
261 let alloc = match &*link_name {
262 "__cxa_thread_atexit_impl" => {
263 // This should be all-zero, pointer-sized.
264 let size = tcx.data_layout.pointer_size;
265 let data = vec![0; size.bytes() as usize];
266 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
268 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
270 Ok(Cow::Owned(alloc))
274 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
275 // We are not interested in detecting loops.
279 fn tag_allocation<'b>(
280 memory_extra: &MemoryExtra,
282 alloc: Cow<'b, Allocation>,
283 kind: Option<MemoryKind<Self::MemoryKinds>>,
285 Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>,
288 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
289 let alloc = alloc.into_owned();
290 let (stacks, base_tag) = if !memory_extra.validate {
291 (None, Tag::Untagged)
293 let (stacks, base_tag) = Stacks::new_allocation(
296 Rc::clone(&memory_extra.stacked_borrows),
299 (Some(stacks), base_tag)
301 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
302 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
304 if !memory_extra.validate {
307 // Only statics may already contain pointers at this point
308 assert_eq!(kind, MiriMemoryKind::Static.into());
309 stacked_borrows.static_base_ptr(alloc)
313 stacked_borrows: stacks,
316 (Cow::Owned(alloc), base_tag)
320 fn tag_static_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
321 if !memory_extra.validate {
333 ecx: &mut InterpCx<'mir, 'tcx, Self>,
334 kind: mir::RetagKind,
335 place: PlaceTy<'tcx, Tag>,
336 ) -> InterpResult<'tcx> {
337 if !Self::enforce_validity(ecx) {
341 ecx.retag(kind, place)
347 ecx: &mut InterpCx<'mir, 'tcx, Self>,
348 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
349 Ok(ecx.memory.extra.stacked_borrows.borrow_mut().new_call())
354 ecx: &mut InterpCx<'mir, 'tcx, Self>,
355 extra: stacked_borrows::CallId,
356 ) -> InterpResult<'tcx> {
367 memory: &Memory<'mir, 'tcx, Self>,
369 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
370 intptrcast::GlobalState::int_to_ptr(int, memory)
375 memory: &Memory<'mir, 'tcx, Self>,
376 ptr: Pointer<Self::PointerTag>,
377 ) -> InterpResult<'tcx, u64> {
378 intptrcast::GlobalState::ptr_to_int(ptr, memory)
382 impl AllocationExtra<Tag> for AllocExtra {
384 fn memory_read<'tcx>(
385 alloc: &Allocation<Tag, AllocExtra>,
388 ) -> InterpResult<'tcx> {
389 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
390 stacked_borrows.memory_read(ptr, size)
397 fn memory_written<'tcx>(
398 alloc: &mut Allocation<Tag, AllocExtra>,
401 ) -> InterpResult<'tcx> {
402 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
403 stacked_borrows.memory_written(ptr, size)
410 fn memory_deallocated<'tcx>(
411 alloc: &mut Allocation<Tag, AllocExtra>,
414 ) -> InterpResult<'tcx> {
415 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
416 stacked_borrows.memory_deallocated(ptr, size)
423 impl MayLeak for MiriMemoryKind {
425 fn may_leak(self) -> bool {
426 use self::MiriMemoryKind::*;
428 Rust | C | WinHeap => false,
429 Env | Static => true,