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