]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
adjust for rustc changes
[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_format!("can't access foreign static: {}", link_name),
251         };
252         Ok(Cow::Owned(alloc))
253     }
254
255     #[inline(always)]
256     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
257     {
258         // We are not interested in detecting loops.
259         Ok(())
260     }
261
262     fn tag_allocation<'b>(
263         memory_extra: &MemoryExtra,
264         id: AllocId,
265         alloc: Cow<'b, Allocation>,
266         kind: Option<MemoryKind<Self::MemoryKinds>>,
267     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
268         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
269         let alloc = alloc.into_owned();
270         let (stacks, base_tag) = if !memory_extra.validate {
271             (None, Tag::Untagged)
272         } else {
273             let (stacks, base_tag) = Stacks::new_allocation(
274                 id,
275                 Size::from_bytes(alloc.bytes.len() as u64),
276                 Rc::clone(&memory_extra.stacked_borrows),
277                 kind,
278             );
279             (Some(stacks), base_tag)
280         };
281         if kind != MiriMemoryKind::Static.into() {
282             assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
283             // Now we can rely on the inner pointers being static, too.
284         }
285         let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
286         let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
287             bytes: alloc.bytes,
288             relocations: Relocations::from_presorted(
289                 alloc.relocations.iter()
290                     // The allocations in the relocations (pointers stored *inside* this allocation)
291                     // all get the base pointer tag.
292                     .map(|&(offset, ((), alloc))| {
293                         let tag = if !memory_extra.validate {
294                             Tag::Untagged
295                         } else {
296                             stacked_borrows.static_base_ptr(alloc)
297                         };
298                         (offset, (tag, alloc))
299                     })
300                     .collect()
301             ),
302             undef_mask: alloc.undef_mask,
303             align: alloc.align,
304             mutability: alloc.mutability,
305             extra: AllocExtra {
306                 stacked_borrows: stacks,
307             },
308         };
309         (Cow::Owned(alloc), base_tag)
310     }
311
312     #[inline(always)]
313     fn tag_static_base_pointer(
314         memory_extra: &MemoryExtra,
315         id: AllocId,
316     ) -> Self::PointerTag {
317         if !memory_extra.validate {
318             Tag::Untagged
319         } else {
320             memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
321         }
322     }
323
324     #[inline(always)]
325     fn retag(
326         ecx: &mut InterpCx<'mir, 'tcx, Self>,
327         kind: mir::RetagKind,
328         place: PlaceTy<'tcx, Tag>,
329     ) -> InterpResult<'tcx> {
330         if !Self::enforce_validity(ecx) {
331             // No tracking.
332              Ok(())
333         } else {
334             ecx.retag(kind, place)
335         }
336     }
337
338     #[inline(always)]
339     fn stack_push(
340         ecx: &mut InterpCx<'mir, 'tcx, Self>,
341     ) -> InterpResult<'tcx, stacked_borrows::CallId> {
342         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
343     }
344
345     #[inline(always)]
346     fn stack_pop(
347         ecx: &mut InterpCx<'mir, 'tcx, Self>,
348         extra: stacked_borrows::CallId,
349     ) -> InterpResult<'tcx> {
350         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
351     }
352
353     #[inline(always)]
354     fn int_to_ptr(
355         memory: &Memory<'mir, 'tcx, Self>,
356         int: u64,
357     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
358         intptrcast::GlobalState::int_to_ptr(int, memory)
359     }
360
361     #[inline(always)]
362     fn ptr_to_int(
363         memory: &Memory<'mir, 'tcx, Self>,
364         ptr: Pointer<Self::PointerTag>,
365     ) -> InterpResult<'tcx, u64> {
366         intptrcast::GlobalState::ptr_to_int(ptr, memory)
367     }
368 }
369
370 impl AllocationExtra<Tag> for AllocExtra {
371     #[inline(always)]
372     fn memory_read<'tcx>(
373         alloc: &Allocation<Tag, AllocExtra>,
374         ptr: Pointer<Tag>,
375         size: Size,
376     ) -> InterpResult<'tcx> {
377         if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
378             stacked_borrows.memory_read(ptr, size)
379         } else {
380             Ok(())
381         }
382     }
383
384     #[inline(always)]
385     fn memory_written<'tcx>(
386         alloc: &mut Allocation<Tag, AllocExtra>,
387         ptr: Pointer<Tag>,
388         size: Size,
389     ) -> InterpResult<'tcx> {
390         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
391             stacked_borrows.memory_written(ptr, size)
392         } else {
393             Ok(())
394         }
395     }
396
397     #[inline(always)]
398     fn memory_deallocated<'tcx>(
399         alloc: &mut Allocation<Tag, AllocExtra>,
400         ptr: Pointer<Tag>,
401         size: Size,
402     ) -> InterpResult<'tcx> {
403         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
404             stacked_borrows.memory_deallocated(ptr, size)
405         } else {
406             Ok(())
407         }
408     }
409 }
410
411 impl MayLeak for MiriMemoryKind {
412     #[inline(always)]
413     fn may_leak(self) -> bool {
414         use self::MiriMemoryKind::*;
415         match self {
416             Rust | C | WinHeap => false,
417             Env | Static => true,
418         }
419     }
420 }