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