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