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