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