]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Auto merge of #856 - RalfJung:type_dispatch_first, r=RalfJung
[rust.git] / src / machine.rs
1 //! Global machine state as well as implementation of the interpreter engine
2 //! `Machine` trait.
3
4 use std::rc::Rc;
5 use std::borrow::Cow;
6 use std::collections::HashMap;
7 use std::cell::RefCell;
8
9 use rand::rngs::StdRng;
10
11 use syntax::attr;
12 use syntax::symbol::sym;
13 use rustc::hir::def_id::DefId;
14 use rustc::ty::{self, layout::{Size, LayoutOf}, TyCtxt};
15 use rustc::mir;
16
17 use crate::*;
18
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;
24
25 /// Extra memory kinds
26 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
27 pub enum MiriMemoryKind {
28     /// `__rust_alloc` memory.
29     Rust,
30     /// `malloc` memory.
31     C,
32     /// Windows `HeapAlloc` memory.
33     WinHeap,
34     /// Part of env var emulation.
35     Env,
36     /// Statics.
37     Static,
38 }
39
40 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
41     #[inline(always)]
42     fn into(self) -> MemoryKind<MiriMemoryKind> {
43         MemoryKind::Machine(self)
44     }
45 }
46
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>,
52 }
53
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,
59
60     /// The random number generator used for resolving non-determinism.
61     pub(crate) rng: RefCell<StdRng>,
62
63     /// Whether to enforce the validity invariant.
64     pub(crate) validate: bool,
65 }
66
67 impl MemoryExtra {
68     pub fn new(rng: StdRng, validate: bool) -> Self {
69         MemoryExtra {
70             stacked_borrows: Default::default(),
71             intptrcast: Default::default(),
72             rng: RefCell::new(rng),
73             validate,
74         }
75     }
76 }
77
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>>,
83
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>>,
90
91     /// Last OS error.
92     pub(crate) last_error: u32,
93
94     /// TLS state.
95     pub(crate) tls: TlsData<'tcx>,
96 }
97
98 impl<'tcx> Evaluator<'tcx> {
99     pub(crate) fn new() -> Self {
100         Evaluator {
101             env_vars: HashMap::default(),
102             argc: None,
103             argv: None,
104             cmd_line: None,
105             last_error: 0,
106             tls: TlsData::default(),
107         }
108     }
109 }
110
111 /// A rustc InterpCx for Miri.
112 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
113
114 /// A little trait that's useful to be inherited by extension traits.
115 pub trait MiriEvalContextExt<'mir, 'tcx> {
116     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
117     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
118 }
119 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
120     #[inline(always)]
121     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
122         self
123     }
124     #[inline(always)]
125     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
126         self
127     }
128 }
129
130 /// Machine hook implementations.
131 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
132     type MemoryKinds = MiriMemoryKind;
133
134     type FrameExtra = stacked_borrows::CallId;
135     type MemoryExtra = MemoryExtra;
136     type AllocExtra = AllocExtra;
137     type PointerTag = Tag;
138     type ExtraFnVal = Dlsym;
139
140     type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
141
142     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
143
144     #[inline(always)]
145     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
146         ecx.memory().extra.validate
147     }
148
149     #[inline(always)]
150     fn find_fn(
151         ecx: &mut InterpCx<'mir, 'tcx, Self>,
152         instance: ty::Instance<'tcx>,
153         args: &[OpTy<'tcx, Tag>],
154         dest: Option<PlaceTy<'tcx, Tag>>,
155         ret: Option<mir::BasicBlock>,
156     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
157         ecx.find_fn(instance, args, dest, ret)
158     }
159
160     #[inline(always)]
161     fn call_extra_fn(
162         ecx: &mut InterpCx<'mir, 'tcx, Self>,
163         fn_val: Dlsym,
164         args: &[OpTy<'tcx, Tag>],
165         dest: Option<PlaceTy<'tcx, Tag>>,
166         ret: Option<mir::BasicBlock>,
167     ) -> InterpResult<'tcx> {
168         ecx.call_dlsym(fn_val, args, dest, ret)
169     }
170
171     #[inline(always)]
172     fn call_intrinsic(
173         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
174         instance: ty::Instance<'tcx>,
175         args: &[OpTy<'tcx, Tag>],
176         dest: PlaceTy<'tcx, Tag>,
177     ) -> InterpResult<'tcx> {
178         ecx.call_intrinsic(instance, args, dest)
179     }
180
181     #[inline(always)]
182     fn binary_ptr_op(
183         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
184         bin_op: mir::BinOp,
185         left: ImmTy<'tcx, Tag>,
186         right: ImmTy<'tcx, Tag>,
187     ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
188         ecx.binary_ptr_op(bin_op, left, right)
189     }
190
191     fn box_alloc(
192         ecx: &mut InterpCx<'mir, 'tcx, Self>,
193         dest: PlaceTy<'tcx, Tag>,
194     ) -> InterpResult<'tcx> {
195         trace!("box_alloc for {:?}", dest.layout.ty);
196         // Call the `exchange_malloc` lang item.
197         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
198         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
199         let malloc_mir = ecx.load_mir(malloc.def)?;
200         ecx.push_stack_frame(
201             malloc,
202             malloc_mir.span,
203             malloc_mir,
204             Some(dest),
205             // Don't do anything when we are done. The `statement()` function will increment
206             // the old stack frame's stmt counter to the next statement, which means that when
207             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
208             StackPopCleanup::None { cleanup: true },
209         )?;
210
211         let mut args = ecx.frame().body.args_iter();
212         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
213
214         // First argument: `size`.
215         // (`0` is allowed here -- this is expected to be handled by the lang item).
216         let arg = ecx.local_place(args.next().unwrap())?;
217         let size = layout.size.bytes();
218         ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
219
220         // Second argument: `align`.
221         let arg = ecx.local_place(args.next().unwrap())?;
222         let align = layout.align.abi.bytes();
223         ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
224
225         // No more arguments.
226         assert!(
227             args.next().is_none(),
228             "`exchange_malloc` lang item has more arguments than expected"
229         );
230         Ok(())
231     }
232
233     fn find_foreign_static(
234         tcx: TyCtxt<'tcx>,
235         def_id: DefId,
236     ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
237         let attrs = tcx.get_attrs(def_id);
238         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
239             Some(name) => name.as_str(),
240             None => tcx.item_name(def_id).as_str(),
241         };
242
243         let alloc = match link_name.get() {
244             "__cxa_thread_atexit_impl" => {
245                 // This should be all-zero, pointer-sized.
246                 let size = tcx.data_layout.pointer_size;
247                 let data = vec![0; size.bytes() as usize];
248                 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
249             }
250             _ => throw_unsup!(Unimplemented(
251                     format!("can't access foreign static: {}", link_name),
252                 )),
253         };
254         Ok(Cow::Owned(alloc))
255     }
256
257     #[inline(always)]
258     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
259     {
260         // We are not interested in detecting loops.
261         Ok(())
262     }
263
264     fn tag_allocation<'b>(
265         memory_extra: &MemoryExtra,
266         id: AllocId,
267         alloc: Cow<'b, Allocation>,
268         kind: Option<MemoryKind<Self::MemoryKinds>>,
269     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
270         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
271         let alloc = alloc.into_owned();
272         let (stacks, base_tag) = if !memory_extra.validate {
273             (None, Tag::Untagged)
274         } else {
275             let (stacks, base_tag) = Stacks::new_allocation(
276                 id,
277                 Size::from_bytes(alloc.bytes.len() as u64),
278                 Rc::clone(&memory_extra.stacked_borrows),
279                 kind,
280             );
281             (Some(stacks), base_tag)
282         };
283         if kind != MiriMemoryKind::Static.into() {
284             assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
285             // Now we can rely on the inner pointers being static, too.
286         }
287         let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
288         let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
289             bytes: alloc.bytes,
290             relocations: Relocations::from_presorted(
291                 alloc.relocations.iter()
292                     // The allocations in the relocations (pointers stored *inside* this allocation)
293                     // all get the base pointer tag.
294                     .map(|&(offset, ((), alloc))| {
295                         let tag = if !memory_extra.validate {
296                             Tag::Untagged
297                         } else {
298                             stacked_borrows.static_base_ptr(alloc)
299                         };
300                         (offset, (tag, alloc))
301                     })
302                     .collect()
303             ),
304             undef_mask: alloc.undef_mask,
305             align: alloc.align,
306             mutability: alloc.mutability,
307             extra: AllocExtra {
308                 stacked_borrows: stacks,
309             },
310         };
311         (Cow::Owned(alloc), base_tag)
312     }
313
314     #[inline(always)]
315     fn tag_static_base_pointer(
316         memory_extra: &MemoryExtra,
317         id: AllocId,
318     ) -> Self::PointerTag {
319         if !memory_extra.validate {
320             Tag::Untagged
321         } else {
322             memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
323         }
324     }
325
326     #[inline(always)]
327     fn retag(
328         ecx: &mut InterpCx<'mir, 'tcx, Self>,
329         kind: mir::RetagKind,
330         place: PlaceTy<'tcx, Tag>,
331     ) -> InterpResult<'tcx> {
332         if !Self::enforce_validity(ecx) {
333             // No tracking.
334              Ok(())
335         } else {
336             ecx.retag(kind, place)
337         }
338     }
339
340     #[inline(always)]
341     fn stack_push(
342         ecx: &mut InterpCx<'mir, 'tcx, Self>,
343     ) -> InterpResult<'tcx, stacked_borrows::CallId> {
344         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
345     }
346
347     #[inline(always)]
348     fn stack_pop(
349         ecx: &mut InterpCx<'mir, 'tcx, Self>,
350         extra: stacked_borrows::CallId,
351     ) -> InterpResult<'tcx> {
352         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
353     }
354
355     #[inline(always)]
356     fn int_to_ptr(
357         memory: &Memory<'mir, 'tcx, Self>,
358         int: u64,
359     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
360         intptrcast::GlobalState::int_to_ptr(int, memory)
361     }
362
363     #[inline(always)]
364     fn ptr_to_int(
365         memory: &Memory<'mir, 'tcx, Self>,
366         ptr: Pointer<Self::PointerTag>,
367     ) -> InterpResult<'tcx, u64> {
368         intptrcast::GlobalState::ptr_to_int(ptr, memory)
369     }
370 }
371
372 impl AllocationExtra<Tag> for AllocExtra {
373     #[inline(always)]
374     fn memory_read<'tcx>(
375         alloc: &Allocation<Tag, AllocExtra>,
376         ptr: Pointer<Tag>,
377         size: Size,
378     ) -> InterpResult<'tcx> {
379         if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
380             stacked_borrows.memory_read(ptr, size)
381         } else {
382             Ok(())
383         }
384     }
385
386     #[inline(always)]
387     fn memory_written<'tcx>(
388         alloc: &mut Allocation<Tag, AllocExtra>,
389         ptr: Pointer<Tag>,
390         size: Size,
391     ) -> InterpResult<'tcx> {
392         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
393             stacked_borrows.memory_written(ptr, size)
394         } else {
395             Ok(())
396         }
397     }
398
399     #[inline(always)]
400     fn memory_deallocated<'tcx>(
401         alloc: &mut Allocation<Tag, AllocExtra>,
402         ptr: Pointer<Tag>,
403         size: Size,
404     ) -> InterpResult<'tcx> {
405         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
406             stacked_borrows.memory_deallocated(ptr, size)
407         } else {
408             Ok(())
409         }
410     }
411 }
412
413 impl MayLeak for MiriMemoryKind {
414     #[inline(always)]
415     fn may_leak(self) -> bool {
416         use self::MiriMemoryKind::*;
417         match self {
418             Rust | C | WinHeap => false,
419             Env | Static => true,
420         }
421     }
422 }