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