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