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