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