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