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