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