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