]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
Auto merge of #849 - RalfJung:rustup, r=RalfJung
[rust.git] / src / helpers.rs
1 use std::mem;
2
3 use rustc::ty::{self, layout::{self, Size, Align}};
4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
5 use rustc::mir;
6
7 use rand::RngCore;
8
9 use crate::*;
10
11 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
12
13 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
14     /// Gets an instance for a path.
15     fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
16         let this = self.eval_context_ref();
17         this.tcx
18             .crates()
19             .iter()
20             .find(|&&krate| this.tcx.original_crate_name(krate).as_str() == path[0])
21             .and_then(|krate| {
22                 let krate = DefId {
23                     krate: *krate,
24                     index: CRATE_DEF_INDEX,
25                 };
26                 let mut items = this.tcx.item_children(krate);
27                 let mut path_it = path.iter().skip(1).peekable();
28
29                 while let Some(segment) = path_it.next() {
30                     for item in mem::replace(&mut items, Default::default()).iter() {
31                         if item.ident.name.as_str() == *segment {
32                             if path_it.peek().is_none() {
33                                 return Some(ty::Instance::mono(this.tcx.tcx, item.res.def_id()));
34                             }
35
36                             items = this.tcx.item_children(item.res.def_id());
37                             break;
38                         }
39                     }
40                 }
41                 None
42             })
43             .ok_or_else(|| {
44                 let path = path.iter().map(|&s| s.to_owned()).collect();
45                 InterpError::PathNotFound(path).into()
46             })
47     }
48
49     /// Write a 0 of the appropriate size to `dest`.
50     fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
51         self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
52     }
53
54     /// Test if this immediate equals 0.
55     fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
56         let this = self.eval_context_ref();
57         let null = Scalar::from_int(0, this.memory().pointer_size());
58         this.ptr_eq(val, null)
59     }
60
61     /// Turn a Scalar into an Option<NonNullScalar>
62     fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
63         let this = self.eval_context_ref();
64         Ok(if this.is_null(val)? {
65             None
66         } else {
67             Some(val)
68         })
69     }
70
71     /// Get the `Place` for a local
72     fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
73         let this = self.eval_context_mut();
74         let place = mir::Place { base: mir::PlaceBase::Local(local), projection: None };
75         this.eval_place(&place)
76     }
77
78     /// Generate some random bytes, and write them to `dest`.
79     fn gen_random(
80         &mut self,
81         len: usize,
82         ptr: Scalar<Tag>,
83     ) -> InterpResult<'tcx>  {
84         let this = self.eval_context_mut();
85
86         let ptr = match this.memory().check_ptr_access(ptr, Size::from_bytes(len as u64), Align::from_bytes(1).unwrap())? {
87             Some(ptr) => ptr,
88             None => return Ok(()), // zero-sized access
89         };
90
91         let data = match &mut this.memory_mut().extra.rng {
92             Some(rng) => {
93                 let mut rng = rng.borrow_mut();
94                 let mut data = vec![0; len];
95                 rng.fill_bytes(&mut data);
96                 data
97             }
98             None => {
99                 return err!(Unimplemented(
100                     "miri does not support gathering system entropy in deterministic mode!
101                     Use '-Zmiri-seed=<seed>' to enable random number generation.
102                     WARNING: Miri does *not* generate cryptographically secure entropy -
103                     do not use Miri to run any program that needs secure random number generation".to_owned(),
104                 ));
105             }
106         };
107         let tcx = &{this.tcx.tcx};
108         this.memory_mut().get_mut(ptr.alloc_id)?
109             .write_bytes(tcx, ptr, &data)
110     }
111
112     /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
113     /// will be true if this is frozen, false if this is in an `UnsafeCell`.
114     fn visit_freeze_sensitive(
115         &self,
116         place: MPlaceTy<'tcx, Tag>,
117         size: Size,
118         mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
119     ) -> InterpResult<'tcx> {
120         let this = self.eval_context_ref();
121         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
122         debug_assert_eq!(size,
123             this.size_and_align_of_mplace(place)?
124             .map(|(size, _)| size)
125             .unwrap_or_else(|| place.layout.size)
126         );
127         // Store how far we proceeded into the place so far. Everything to the left of
128         // this offset has already been handled, in the sense that the frozen parts
129         // have had `action` called on them.
130         let mut end_ptr = place.ptr.assert_ptr();
131         // Called when we detected an `UnsafeCell` at the given offset and size.
132         // Calls `action` and advances `end_ptr`.
133         let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
134             let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
135             debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
136             debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
137             // We assume that we are given the fields in increasing offset order,
138             // and nothing else changes.
139             let unsafe_cell_offset = unsafe_cell_ptr.offset;
140             let end_offset = end_ptr.offset;
141             assert!(unsafe_cell_offset >= end_offset);
142             let frozen_size = unsafe_cell_offset - end_offset;
143             // Everything between the end_ptr and this `UnsafeCell` is frozen.
144             if frozen_size != Size::ZERO {
145                 action(end_ptr, frozen_size, /*frozen*/true)?;
146             }
147             // This `UnsafeCell` is NOT frozen.
148             if unsafe_cell_size != Size::ZERO {
149                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
150             }
151             // Update end end_ptr.
152             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
153             // Done
154             Ok(())
155         };
156         // Run a visitor
157         {
158             let mut visitor = UnsafeCellVisitor {
159                 ecx: this,
160                 unsafe_cell_action: |place| {
161                     trace!("unsafe_cell_action on {:?}", place.ptr);
162                     // We need a size to go on.
163                     let unsafe_cell_size = this.size_and_align_of_mplace(place)?
164                         .map(|(size, _)| size)
165                         // for extern types, just cover what we can
166                         .unwrap_or_else(|| place.layout.size);
167                     // Now handle this `UnsafeCell`, unless it is empty.
168                     if unsafe_cell_size != Size::ZERO {
169                         unsafe_cell_action(place.ptr, unsafe_cell_size)
170                     } else {
171                         Ok(())
172                     }
173                 },
174             };
175             visitor.visit_value(place)?;
176         }
177         // The part between the end_ptr and the end of the place is also frozen.
178         // So pretend there is a 0-sized `UnsafeCell` at the end.
179         unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
180         // Done!
181         return Ok(());
182
183         /// Visiting the memory covered by a `MemPlace`, being aware of
184         /// whether we are inside an `UnsafeCell` or not.
185         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
186             where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
187         {
188             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
189             unsafe_cell_action: F,
190         }
191
192         impl<'ecx, 'mir, 'tcx, F>
193             ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
194         for
195             UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
196         where
197             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
198         {
199             type V = MPlaceTy<'tcx, Tag>;
200
201             #[inline(always)]
202             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
203                 &self.ecx
204             }
205
206             // Hook to detect `UnsafeCell`.
207             fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
208             {
209                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
210                 let is_unsafe_cell = match v.layout.ty.sty {
211                     ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
212                     _ => false,
213                 };
214                 if is_unsafe_cell {
215                     // We do not have to recurse further, this is an `UnsafeCell`.
216                     (self.unsafe_cell_action)(v)
217                 } else if self.ecx.type_is_freeze(v.layout.ty) {
218                     // This is `Freeze`, there cannot be an `UnsafeCell`
219                     Ok(())
220                 } else {
221                     // Proceed further
222                     self.walk_value(v)
223                 }
224             }
225
226             // Make sure we visit aggregrates in increasing offset order.
227             fn visit_aggregate(
228                 &mut self,
229                 place: MPlaceTy<'tcx, Tag>,
230                 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
231             ) -> InterpResult<'tcx> {
232                 match place.layout.fields {
233                     layout::FieldPlacement::Array { .. } => {
234                         // For the array layout, we know the iterator will yield sorted elements so
235                         // we can avoid the allocation.
236                         self.walk_aggregate(place, fields)
237                     }
238                     layout::FieldPlacement::Arbitrary { .. } => {
239                         // Gather the subplaces and sort them before visiting.
240                         let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
241                         places.sort_by_key(|place| place.ptr.assert_ptr().offset);
242                         self.walk_aggregate(place, places.into_iter().map(Ok))
243                     }
244                     layout::FieldPlacement::Union { .. } => {
245                         // Uh, what?
246                         bug!("a union is not an aggregate we should ever visit")
247                     }
248                 }
249             }
250
251             // We have to do *something* for unions.
252             fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
253             {
254                 // With unions, we fall back to whatever the type says, to hopefully be consistent
255                 // with LLVM IR.
256                 // FIXME: are we consistent, and is this really the behavior we want?
257                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
258                 if frozen {
259                     Ok(())
260                 } else {
261                     (self.unsafe_cell_action)(v)
262                 }
263             }
264
265             // We should never get to a primitive, but always short-circuit somewhere above.
266             fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
267             {
268                 bug!("we should always short-circuit before coming to a primitive")
269             }
270         }
271     }
272 }