1 //! Global machine state as well as implementation of the interpreter engine
6 use std::collections::HashMap;
8 use rand::rngs::StdRng;
11 use syntax::symbol::sym;
12 use rustc::hir::def_id::DefId;
13 use rustc::ty::{self, layout::{Size, LayoutOf}, query::TyCtxtAt};
18 /// Extra memory kinds
19 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
20 pub enum MiriMemoryKind {
21 /// `__rust_alloc` memory.
25 /// Part of env var emulation.
31 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
33 fn into(self) -> MemoryKind<MiriMemoryKind> {
34 MemoryKind::Machine(self)
38 /// Extra per-allocation data
39 #[derive(Debug, Clone)]
40 pub struct AllocExtra {
41 pub stacked_borrows: stacked_borrows::AllocExtra,
42 pub intptrcast: intptrcast::AllocExtra,
45 /// Extra global memory data
46 #[derive(Clone, Debug)]
47 pub struct MemoryExtra {
48 pub stacked_borrows: stacked_borrows::MemoryExtra,
49 pub intptrcast: intptrcast::MemoryExtra,
50 /// The random number generator to use if Miri is running in non-deterministic mode and to
52 pub(crate) rng: Option<StdRng>
56 pub fn with_rng(rng: Option<StdRng>) -> Self {
58 stacked_borrows: Default::default(),
59 intptrcast: Default::default(),
65 /// The machine itself.
66 pub struct Evaluator<'tcx> {
67 /// Environment variables set by `setenv`.
68 /// Miri does not expose env vars from the host to the emulated program.
69 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
71 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
72 /// These are *pointers* to argc/argv because macOS.
73 /// We also need the full command line as one string because of Windows.
74 pub(crate) argc: Option<Pointer<Tag>>,
75 pub(crate) argv: Option<Pointer<Tag>>,
76 pub(crate) cmd_line: Option<Pointer<Tag>>,
79 pub(crate) last_error: u32,
82 pub(crate) tls: TlsData<'tcx>,
84 /// Whether to enforce the validity invariant.
85 pub(crate) validate: bool,
88 impl<'tcx> Evaluator<'tcx> {
89 pub(crate) fn new(validate: bool) -> Self {
91 env_vars: HashMap::default(),
96 tls: TlsData::default(),
102 /// A rustc InterpretCx for Miri.
103 pub type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
105 /// A little trait that's useful to be inherited by extension traits.
106 pub trait MiriEvalContextExt<'mir, 'tcx> {
107 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
108 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
110 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
112 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
116 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
121 /// Machine hook implementations.
122 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
123 type MemoryKinds = MiriMemoryKind;
125 type FrameExtra = stacked_borrows::CallId;
126 type MemoryExtra = MemoryExtra;
127 type AllocExtra = AllocExtra;
128 type PointerTag = Tag;
130 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
132 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
135 fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
139 /// Returns `Ok()` when the function was handled; fail otherwise.
142 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
143 instance: ty::Instance<'tcx>,
144 args: &[OpTy<'tcx, Tag>],
145 dest: Option<PlaceTy<'tcx, Tag>>,
146 ret: Option<mir::BasicBlock>,
147 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
148 ecx.find_fn(instance, args, dest, ret)
153 ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
154 instance: ty::Instance<'tcx>,
155 args: &[OpTy<'tcx, Tag>],
156 dest: PlaceTy<'tcx, Tag>,
157 ) -> InterpResult<'tcx> {
158 ecx.call_intrinsic(instance, args, dest)
163 ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
165 left: ImmTy<'tcx, Tag>,
166 right: ImmTy<'tcx, Tag>,
167 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
168 ecx.ptr_op(bin_op, left, right)
172 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
173 dest: PlaceTy<'tcx, Tag>,
174 ) -> InterpResult<'tcx> {
175 trace!("box_alloc for {:?}", dest.layout.ty);
176 // Call the `exchange_malloc` lang item.
177 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
178 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
179 let malloc_mir = ecx.load_mir(malloc.def)?;
180 ecx.push_stack_frame(
185 // Don't do anything when we are done. The `statement()` function will increment
186 // the old stack frame's stmt counter to the next statement, which means that when
187 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
188 StackPopCleanup::None { cleanup: true },
191 let mut args = ecx.frame().body.args_iter();
192 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
194 // First argument: `size`.
195 // (`0` is allowed here -- this is expected to be handled by the lang item).
196 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
197 let size = layout.size.bytes();
198 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
200 // Second argument: `align`.
201 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
202 let align = layout.align.abi.bytes();
203 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
205 // No more arguments.
207 args.next().is_none(),
208 "`exchange_malloc` lang item has more arguments than expected"
213 fn find_foreign_static(
216 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
217 let attrs = tcx.get_attrs(def_id);
218 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
219 Some(name) => name.as_str(),
220 None => tcx.item_name(def_id).as_str(),
223 let alloc = match link_name.get() {
224 "__cxa_thread_atexit_impl" => {
225 // This should be all-zero, pointer-sized.
226 let size = tcx.data_layout.pointer_size;
227 let data = vec![0; size.bytes() as usize];
228 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
230 _ => return err!(Unimplemented(
231 format!("can't access foreign static: {}", link_name),
234 Ok(Cow::Owned(alloc))
238 fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
240 // We are not interested in detecting loops.
244 fn tag_allocation<'b>(
246 alloc: Cow<'b, Allocation>,
247 kind: Option<MemoryKind<Self::MemoryKinds>>,
248 memory: &Memory<'mir, 'tcx, Self>,
249 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
250 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
251 let alloc = alloc.into_owned();
252 let (stacks, base_tag) = Stacks::new_allocation(
254 Size::from_bytes(alloc.bytes.len() as u64),
255 Rc::clone(&memory.extra.stacked_borrows),
258 if kind != MiriMemoryKind::Static.into() {
259 assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
260 // Now we can rely on the inner pointers being static, too.
262 let mut memory_extra = memory.extra.stacked_borrows.borrow_mut();
263 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
265 relocations: Relocations::from_presorted(
266 alloc.relocations.iter()
267 // The allocations in the relocations (pointers stored *inside* this allocation)
268 // all get the base pointer tag.
269 .map(|&(offset, ((), alloc))| (offset, (memory_extra.static_base_ptr(alloc), alloc)))
272 undef_mask: alloc.undef_mask,
274 mutability: alloc.mutability,
276 stacked_borrows: stacks,
277 intptrcast: Default::default(),
280 (Cow::Owned(alloc), base_tag)
284 fn tag_static_base_pointer(
286 memory: &Memory<'mir, 'tcx, Self>,
287 ) -> Self::PointerTag {
288 memory.extra.stacked_borrows.borrow_mut().static_base_ptr(id)
293 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
294 kind: mir::RetagKind,
295 place: PlaceTy<'tcx, Tag>,
296 ) -> InterpResult<'tcx> {
297 if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag || !Self::enforce_validity(ecx) {
298 // No tracking, or no retagging. The latter is possible because a dependency of ours
299 // might be called with different flags than we are, so there are `Retag`
300 // statements but we do not want to execute them.
301 // Also, honor the whitelist in `enforce_validity` because otherwise we might retag
302 // uninitialized data.
305 ecx.retag(kind, place)
311 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
312 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
313 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
318 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
319 extra: stacked_borrows::CallId,
320 ) -> InterpResult<'tcx> {
321 Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
326 memory: &Memory<'mir, 'tcx, Self>,
327 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
329 err!(InvalidNullPointerUsage)
330 } else if memory.extra.rng.is_none() {
331 err!(ReadBytesAsPointer)
333 intptrcast::GlobalState::int_to_ptr(int, memory)
338 ptr: Pointer<Self::PointerTag>,
339 memory: &Memory<'mir, 'tcx, Self>,
340 ) -> InterpResult<'tcx, u64> {
341 if memory.extra.rng.is_none() {
342 err!(ReadPointerAsBytes)
344 intptrcast::GlobalState::ptr_to_int(ptr, memory)
349 impl AllocationExtra<Tag> for AllocExtra {
351 fn memory_read<'tcx>(
352 alloc: &Allocation<Tag, AllocExtra>,
355 ) -> InterpResult<'tcx> {
356 alloc.extra.stacked_borrows.memory_read(ptr, size)
360 fn memory_written<'tcx>(
361 alloc: &mut Allocation<Tag, AllocExtra>,
364 ) -> InterpResult<'tcx> {
365 alloc.extra.stacked_borrows.memory_written(ptr, size)
369 fn memory_deallocated<'tcx>(
370 alloc: &mut Allocation<Tag, AllocExtra>,
373 ) -> InterpResult<'tcx> {
374 alloc.extra.stacked_borrows.memory_deallocated(ptr, size)
378 impl MayLeak for MiriMemoryKind {
380 fn may_leak(self) -> bool {
381 use self::MiriMemoryKind::*;
384 Env | Static => true,