]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
Do nothing when we try to generate random data of length 0
[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                 err_unsup!(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         ptr: Scalar<Tag>,
82         len: usize,
83     ) -> InterpResult<'tcx>  {
84         // Some programs pass in a null pointer and a length of 0
85         // to their platform's random-generation function (e.g. getrandom())
86         // on Linux. For compatibility with these programs, we don't perform
87         // any additional checks - it's okay if the pointer is invalid,
88         // since we wouldn't actually be writing to it.
89         if len == 0 {
90             return Ok(())
91         }
92         let this = self.eval_context_mut();
93
94         let ptr = match this.memory().check_ptr_access(ptr, Size::from_bytes(len as u64), Align::from_bytes(1).unwrap())? {
95             Some(ptr) => ptr,
96             None => return Ok(()), // zero-sized access
97         };
98
99         let rng = this.memory_mut().extra.rng.get_mut();
100         let mut data = vec![0; len];
101         rng.fill_bytes(&mut data);
102
103         let tcx = &{this.tcx.tcx};
104         this.memory_mut().get_mut(ptr.alloc_id)?.write_bytes(tcx, ptr, &data)
105     }
106
107     /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
108     /// will be true if this is frozen, false if this is in an `UnsafeCell`.
109     fn visit_freeze_sensitive(
110         &self,
111         place: MPlaceTy<'tcx, Tag>,
112         size: Size,
113         mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
114     ) -> InterpResult<'tcx> {
115         let this = self.eval_context_ref();
116         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
117         debug_assert_eq!(size,
118             this.size_and_align_of_mplace(place)?
119             .map(|(size, _)| size)
120             .unwrap_or_else(|| place.layout.size)
121         );
122         // Store how far we proceeded into the place so far. Everything to the left of
123         // this offset has already been handled, in the sense that the frozen parts
124         // have had `action` called on them.
125         let mut end_ptr = place.ptr.assert_ptr();
126         // Called when we detected an `UnsafeCell` at the given offset and size.
127         // Calls `action` and advances `end_ptr`.
128         let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
129             let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
130             debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
131             debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
132             // We assume that we are given the fields in increasing offset order,
133             // and nothing else changes.
134             let unsafe_cell_offset = unsafe_cell_ptr.offset;
135             let end_offset = end_ptr.offset;
136             assert!(unsafe_cell_offset >= end_offset);
137             let frozen_size = unsafe_cell_offset - end_offset;
138             // Everything between the end_ptr and this `UnsafeCell` is frozen.
139             if frozen_size != Size::ZERO {
140                 action(end_ptr, frozen_size, /*frozen*/true)?;
141             }
142             // This `UnsafeCell` is NOT frozen.
143             if unsafe_cell_size != Size::ZERO {
144                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
145             }
146             // Update end end_ptr.
147             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
148             // Done
149             Ok(())
150         };
151         // Run a visitor
152         {
153             let mut visitor = UnsafeCellVisitor {
154                 ecx: this,
155                 unsafe_cell_action: |place| {
156                     trace!("unsafe_cell_action on {:?}", place.ptr);
157                     // We need a size to go on.
158                     let unsafe_cell_size = this.size_and_align_of_mplace(place)?
159                         .map(|(size, _)| size)
160                         // for extern types, just cover what we can
161                         .unwrap_or_else(|| place.layout.size);
162                     // Now handle this `UnsafeCell`, unless it is empty.
163                     if unsafe_cell_size != Size::ZERO {
164                         unsafe_cell_action(place.ptr, unsafe_cell_size)
165                     } else {
166                         Ok(())
167                     }
168                 },
169             };
170             visitor.visit_value(place)?;
171         }
172         // The part between the end_ptr and the end of the place is also frozen.
173         // So pretend there is a 0-sized `UnsafeCell` at the end.
174         unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
175         // Done!
176         return Ok(());
177
178         /// Visiting the memory covered by a `MemPlace`, being aware of
179         /// whether we are inside an `UnsafeCell` or not.
180         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
181             where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
182         {
183             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
184             unsafe_cell_action: F,
185         }
186
187         impl<'ecx, 'mir, 'tcx, F>
188             ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
189         for
190             UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
191         where
192             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
193         {
194             type V = MPlaceTy<'tcx, Tag>;
195
196             #[inline(always)]
197             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
198                 &self.ecx
199             }
200
201             // Hook to detect `UnsafeCell`.
202             fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
203             {
204                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
205                 let is_unsafe_cell = match v.layout.ty.sty {
206                     ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
207                     _ => false,
208                 };
209                 if is_unsafe_cell {
210                     // We do not have to recurse further, this is an `UnsafeCell`.
211                     (self.unsafe_cell_action)(v)
212                 } else if self.ecx.type_is_freeze(v.layout.ty) {
213                     // This is `Freeze`, there cannot be an `UnsafeCell`
214                     Ok(())
215                 } else {
216                     // Proceed further
217                     self.walk_value(v)
218                 }
219             }
220
221             // Make sure we visit aggregrates in increasing offset order.
222             fn visit_aggregate(
223                 &mut self,
224                 place: MPlaceTy<'tcx, Tag>,
225                 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
226             ) -> InterpResult<'tcx> {
227                 match place.layout.fields {
228                     layout::FieldPlacement::Array { .. } => {
229                         // For the array layout, we know the iterator will yield sorted elements so
230                         // we can avoid the allocation.
231                         self.walk_aggregate(place, fields)
232                     }
233                     layout::FieldPlacement::Arbitrary { .. } => {
234                         // Gather the subplaces and sort them before visiting.
235                         let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
236                         places.sort_by_key(|place| place.ptr.assert_ptr().offset);
237                         self.walk_aggregate(place, places.into_iter().map(Ok))
238                     }
239                     layout::FieldPlacement::Union { .. } => {
240                         // Uh, what?
241                         bug!("a union is not an aggregate we should ever visit")
242                     }
243                 }
244             }
245
246             // We have to do *something* for unions.
247             fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
248             {
249                 // With unions, we fall back to whatever the type says, to hopefully be consistent
250                 // with LLVM IR.
251                 // FIXME: are we consistent, and is this really the behavior we want?
252                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
253                 if frozen {
254                     Ok(())
255                 } else {
256                     (self.unsafe_cell_action)(v)
257                 }
258             }
259
260             // We should never get to a primitive, but always short-circuit somewhere above.
261             fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
262             {
263                 bug!("we should always short-circuit before coming to a primitive")
264             }
265         }
266     }
267 }