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