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