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