]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
adjust for typed binary/unary_op
[rust.git] / src / machine.rs
1 //! Global machine state as well as implementation of the interpreter engine
2 //! `Machine` trait.
3
4 use std::rc::Rc;
5 use std::borrow::Cow;
6 use std::cell::RefCell;
7
8 use rand::rngs::StdRng;
9
10 use syntax::attr;
11 use syntax::symbol::sym;
12 use rustc::hir::def_id::DefId;
13 use rustc::ty::{self, Ty, TyCtxt, layout::{Size, LayoutOf}};
14 use rustc::mir;
15
16 use crate::*;
17
18 // Some global facts about the emulated machine.
19 pub const PAGE_SIZE: u64 = 4*1024; // FIXME: adjust to target architecture
20 pub const STACK_ADDR: u64 = 32*PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
21 pub const STACK_SIZE: u64 = 16*PAGE_SIZE; // whatever
22 pub const NUM_CPUS: u64 = 1;
23
24 /// Extra memory kinds
25 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
26 pub enum MiriMemoryKind {
27     /// `__rust_alloc` memory.
28     Rust,
29     /// `malloc` memory.
30     C,
31     /// Windows `HeapAlloc` memory.
32     WinHeap,
33     /// Part of env var emulation.
34     Env,
35     /// Statics.
36     Static,
37 }
38
39 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
40     #[inline(always)]
41     fn into(self) -> MemoryKind<MiriMemoryKind> {
42         MemoryKind::Machine(self)
43     }
44 }
45
46 /// Extra per-allocation data
47 #[derive(Debug, Clone)]
48 pub struct AllocExtra {
49     /// Stacked Borrows state is only added if validation is enabled.
50     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
51 }
52
53 /// Extra global memory data
54 #[derive(Clone, Debug)]
55 pub struct MemoryExtra {
56     pub stacked_borrows: stacked_borrows::MemoryExtra,
57     pub intptrcast: intptrcast::MemoryExtra,
58
59     /// The random number generator used for resolving non-determinism.
60     pub(crate) rng: RefCell<StdRng>,
61
62     /// Whether to enforce the validity invariant.
63     pub(crate) validate: bool,
64 }
65
66 impl MemoryExtra {
67     pub fn new(rng: StdRng, validate: bool) -> Self {
68         MemoryExtra {
69             stacked_borrows: Default::default(),
70             intptrcast: Default::default(),
71             rng: RefCell::new(rng),
72             validate,
73         }
74     }
75 }
76
77 /// The machine itself.
78 pub struct Evaluator<'tcx> {
79     /// Environment variables set by `setenv`.
80     /// Miri does not expose env vars from the host to the emulated program.
81     pub(crate) env_vars: EnvVars,
82
83     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
84     /// These are *pointers* to argc/argv because macOS.
85     /// We also need the full command line as one string because of Windows.
86     pub(crate) argc: Option<Pointer<Tag>>,
87     pub(crate) argv: Option<Pointer<Tag>>,
88     pub(crate) cmd_line: Option<Pointer<Tag>>,
89
90     /// Last OS error.
91     pub(crate) last_error: u32,
92
93     /// TLS state.
94     pub(crate) tls: TlsData<'tcx>,
95
96     /// If enabled, the `env_vars` field is populated with the host env vars during initialization.
97     pub(crate) communicate: bool,
98 }
99
100 impl<'tcx> Evaluator<'tcx> {
101     pub(crate) fn new(communicate: bool) -> Self {
102         Evaluator {
103             // `env_vars` could be initialized properly here if `Memory` were available before
104             // calling this method.
105             env_vars: EnvVars::default(),
106             argc: None,
107             argv: None,
108             cmd_line: None,
109             last_error: 0,
110             tls: TlsData::default(),
111             communicate,
112         }
113     }
114 }
115
116 /// A rustc InterpCx for Miri.
117 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
118
119 /// A little trait that's useful to be inherited by extension traits.
120 pub trait MiriEvalContextExt<'mir, 'tcx> {
121     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
122     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
123 }
124 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
125     #[inline(always)]
126     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
127         self
128     }
129     #[inline(always)]
130     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
131         self
132     }
133 }
134
135 /// Machine hook implementations.
136 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
137     type MemoryKinds = MiriMemoryKind;
138
139     type FrameExtra = stacked_borrows::CallId;
140     type MemoryExtra = MemoryExtra;
141     type AllocExtra = AllocExtra;
142     type PointerTag = Tag;
143     type ExtraFnVal = Dlsym;
144
145     type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
146
147     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
148
149     const CHECK_ALIGN: bool = true;
150
151     #[inline(always)]
152     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
153         ecx.memory().extra.validate
154     }
155
156     #[inline(always)]
157     fn find_fn(
158         ecx: &mut InterpCx<'mir, 'tcx, Self>,
159         instance: ty::Instance<'tcx>,
160         args: &[OpTy<'tcx, Tag>],
161         dest: Option<PlaceTy<'tcx, Tag>>,
162         ret: Option<mir::BasicBlock>,
163     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
164         ecx.find_fn(instance, args, dest, ret)
165     }
166
167     #[inline(always)]
168     fn call_extra_fn(
169         ecx: &mut InterpCx<'mir, 'tcx, Self>,
170         fn_val: Dlsym,
171         args: &[OpTy<'tcx, Tag>],
172         dest: Option<PlaceTy<'tcx, Tag>>,
173         ret: Option<mir::BasicBlock>,
174     ) -> InterpResult<'tcx> {
175         ecx.call_dlsym(fn_val, args, dest, ret)
176     }
177
178     #[inline(always)]
179     fn call_intrinsic(
180         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
181         instance: ty::Instance<'tcx>,
182         args: &[OpTy<'tcx, Tag>],
183         dest: PlaceTy<'tcx, Tag>,
184     ) -> InterpResult<'tcx> {
185         ecx.call_intrinsic(instance, args, dest)
186     }
187
188     #[inline(always)]
189     fn binary_ptr_op(
190         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
191         bin_op: mir::BinOp,
192         left: ImmTy<'tcx, Tag>,
193         right: ImmTy<'tcx, Tag>,
194     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
195         ecx.binary_ptr_op(bin_op, left, right)
196     }
197
198     fn box_alloc(
199         ecx: &mut InterpCx<'mir, 'tcx, Self>,
200         dest: PlaceTy<'tcx, Tag>,
201     ) -> InterpResult<'tcx> {
202         trace!("box_alloc for {:?}", dest.layout.ty);
203         // Call the `exchange_malloc` lang item.
204         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
205         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
206         let malloc_mir = ecx.load_mir(malloc.def)?;
207         ecx.push_stack_frame(
208             malloc,
209             malloc_mir.span,
210             malloc_mir,
211             Some(dest),
212             // Don't do anything when we are done. The `statement()` function will increment
213             // the old stack frame's stmt counter to the next statement, which means that when
214             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
215             StackPopCleanup::None { cleanup: true },
216         )?;
217
218         let mut args = ecx.frame().body.args_iter();
219         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
220
221         // First argument: `size`.
222         // (`0` is allowed here -- this is expected to be handled by the lang item).
223         let arg = ecx.local_place(args.next().unwrap())?;
224         let size = layout.size.bytes();
225         ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
226
227         // Second argument: `align`.
228         let arg = ecx.local_place(args.next().unwrap())?;
229         let align = layout.align.abi.bytes();
230         ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
231
232         // No more arguments.
233         assert!(
234             args.next().is_none(),
235             "`exchange_malloc` lang item has more arguments than expected"
236         );
237         Ok(())
238     }
239
240     fn find_foreign_static(
241         tcx: TyCtxt<'tcx>,
242         def_id: DefId,
243     ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
244         let attrs = tcx.get_attrs(def_id);
245         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
246             Some(name) => name.as_str(),
247             None => tcx.item_name(def_id).as_str(),
248         };
249
250         let alloc = match link_name.get() {
251             "__cxa_thread_atexit_impl" => {
252                 // This should be all-zero, pointer-sized.
253                 let size = tcx.data_layout.pointer_size;
254                 let data = vec![0; size.bytes() as usize];
255                 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
256             }
257             _ => throw_unsup_format!("can't access foreign static: {}", link_name),
258         };
259         Ok(Cow::Owned(alloc))
260     }
261
262     #[inline(always)]
263     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
264     {
265         // We are not interested in detecting loops.
266         Ok(())
267     }
268
269     fn tag_allocation<'b>(
270         memory_extra: &MemoryExtra,
271         id: AllocId,
272         alloc: Cow<'b, Allocation>,
273         kind: Option<MemoryKind<Self::MemoryKinds>>,
274     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
275         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
276         let alloc = alloc.into_owned();
277         let (stacks, base_tag) = if !memory_extra.validate {
278             (None, Tag::Untagged)
279         } else {
280             let (stacks, base_tag) = Stacks::new_allocation(
281                 id,
282                 Size::from_bytes(alloc.bytes.len() as u64),
283                 Rc::clone(&memory_extra.stacked_borrows),
284                 kind,
285             );
286             (Some(stacks), base_tag)
287         };
288         if kind != MiriMemoryKind::Static.into() {
289             assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
290             // Now we can rely on the inner pointers being static, too.
291         }
292         let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
293         let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
294             bytes: alloc.bytes,
295             relocations: Relocations::from_presorted(
296                 alloc.relocations.iter()
297                     // The allocations in the relocations (pointers stored *inside* this allocation)
298                     // all get the base pointer tag.
299                     .map(|&(offset, ((), alloc))| {
300                         let tag = if !memory_extra.validate {
301                             Tag::Untagged
302                         } else {
303                             stacked_borrows.static_base_ptr(alloc)
304                         };
305                         (offset, (tag, alloc))
306                     })
307                     .collect()
308             ),
309             undef_mask: alloc.undef_mask,
310             align: alloc.align,
311             mutability: alloc.mutability,
312             extra: AllocExtra {
313                 stacked_borrows: stacks,
314             },
315         };
316         (Cow::Owned(alloc), base_tag)
317     }
318
319     #[inline(always)]
320     fn tag_static_base_pointer(
321         memory_extra: &MemoryExtra,
322         id: AllocId,
323     ) -> Self::PointerTag {
324         if !memory_extra.validate {
325             Tag::Untagged
326         } else {
327             memory_extra.stacked_borrows.borrow_mut().static_base_ptr(id)
328         }
329     }
330
331     #[inline(always)]
332     fn retag(
333         ecx: &mut InterpCx<'mir, 'tcx, Self>,
334         kind: mir::RetagKind,
335         place: PlaceTy<'tcx, Tag>,
336     ) -> InterpResult<'tcx> {
337         if !Self::enforce_validity(ecx) {
338             // No tracking.
339              Ok(())
340         } else {
341             ecx.retag(kind, place)
342         }
343     }
344
345     #[inline(always)]
346     fn stack_push(
347         ecx: &mut InterpCx<'mir, 'tcx, Self>,
348     ) -> InterpResult<'tcx, stacked_borrows::CallId> {
349         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().new_call())
350     }
351
352     #[inline(always)]
353     fn stack_pop(
354         ecx: &mut InterpCx<'mir, 'tcx, Self>,
355         extra: stacked_borrows::CallId,
356     ) -> InterpResult<'tcx> {
357         Ok(ecx.memory().extra.stacked_borrows.borrow_mut().end_call(extra))
358     }
359
360     #[inline(always)]
361     fn int_to_ptr(
362         memory: &Memory<'mir, 'tcx, Self>,
363         int: u64,
364     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
365         intptrcast::GlobalState::int_to_ptr(int, memory)
366     }
367
368     #[inline(always)]
369     fn ptr_to_int(
370         memory: &Memory<'mir, 'tcx, Self>,
371         ptr: Pointer<Self::PointerTag>,
372     ) -> InterpResult<'tcx, u64> {
373         intptrcast::GlobalState::ptr_to_int(ptr, memory)
374     }
375 }
376
377 impl AllocationExtra<Tag> for AllocExtra {
378     #[inline(always)]
379     fn memory_read<'tcx>(
380         alloc: &Allocation<Tag, AllocExtra>,
381         ptr: Pointer<Tag>,
382         size: Size,
383     ) -> InterpResult<'tcx> {
384         if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
385             stacked_borrows.memory_read(ptr, size)
386         } else {
387             Ok(())
388         }
389     }
390
391     #[inline(always)]
392     fn memory_written<'tcx>(
393         alloc: &mut Allocation<Tag, AllocExtra>,
394         ptr: Pointer<Tag>,
395         size: Size,
396     ) -> InterpResult<'tcx> {
397         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
398             stacked_borrows.memory_written(ptr, size)
399         } else {
400             Ok(())
401         }
402     }
403
404     #[inline(always)]
405     fn memory_deallocated<'tcx>(
406         alloc: &mut Allocation<Tag, AllocExtra>,
407         ptr: Pointer<Tag>,
408         size: Size,
409     ) -> InterpResult<'tcx> {
410         if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
411             stacked_borrows.memory_deallocated(ptr, size)
412         } else {
413             Ok(())
414         }
415     }
416 }
417
418 impl MayLeak for MiriMemoryKind {
419     #[inline(always)]
420     fn may_leak(self) -> bool {
421         use self::MiriMemoryKind::*;
422         match self {
423             Rust | C | WinHeap => false,
424             Env | Static => true,
425         }
426     }
427 }