3 use rustc::ty::{self, layout::{self, Size, Align}};
4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
11 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
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();
20 .find(|&&krate| this.tcx.original_crate_name(krate).as_str() == path[0])
24 index: CRATE_DEF_INDEX,
26 let mut items = this.tcx.item_children(krate);
27 let mut path_it = path.iter().skip(1).peekable();
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()));
36 items = this.tcx.item_children(item.res.def_id());
44 let path = path.iter().map(|&s| s.to_owned()).collect();
45 err_unsup!(PathNotFound(path)).into()
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)
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)
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)? {
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: Box::new([]) };
75 this.eval_place(&place)
78 /// Generate some random bytes, and write them to `dest`.
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.
92 let this = self.eval_context_mut();
94 let ptr = this.memory().check_ptr_access(
96 Size::from_bytes(len as u64),
97 Align::from_bytes(1).unwrap()
98 )?.expect("we already checked for size 0");
100 let mut data = vec![0; len];
102 if this.machine.communicate {
103 // Fill the buffer using the host's rng.
104 getrandom::getrandom(&mut data)
105 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
108 let rng = this.memory_mut().extra.rng.get_mut();
109 rng.fill_bytes(&mut data);
112 let tcx = &{this.tcx.tcx};
113 this.memory_mut().get_mut(ptr.alloc_id)?.write_bytes(tcx, ptr, &data)
116 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
117 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
118 fn visit_freeze_sensitive(
120 place: MPlaceTy<'tcx, Tag>,
122 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
123 ) -> InterpResult<'tcx> {
124 let this = self.eval_context_ref();
125 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
126 debug_assert_eq!(size,
127 this.size_and_align_of_mplace(place)?
128 .map(|(size, _)| size)
129 .unwrap_or_else(|| place.layout.size)
131 // Store how far we proceeded into the place so far. Everything to the left of
132 // this offset has already been handled, in the sense that the frozen parts
133 // have had `action` called on them.
134 let mut end_ptr = place.ptr.assert_ptr();
135 // Called when we detected an `UnsafeCell` at the given offset and size.
136 // Calls `action` and advances `end_ptr`.
137 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
138 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
139 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
140 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
141 // We assume that we are given the fields in increasing offset order,
142 // and nothing else changes.
143 let unsafe_cell_offset = unsafe_cell_ptr.offset;
144 let end_offset = end_ptr.offset;
145 assert!(unsafe_cell_offset >= end_offset);
146 let frozen_size = unsafe_cell_offset - end_offset;
147 // Everything between the end_ptr and this `UnsafeCell` is frozen.
148 if frozen_size != Size::ZERO {
149 action(end_ptr, frozen_size, /*frozen*/true)?;
151 // This `UnsafeCell` is NOT frozen.
152 if unsafe_cell_size != Size::ZERO {
153 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
155 // Update end end_ptr.
156 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
162 let mut visitor = UnsafeCellVisitor {
164 unsafe_cell_action: |place| {
165 trace!("unsafe_cell_action on {:?}", place.ptr);
166 // We need a size to go on.
167 let unsafe_cell_size = this.size_and_align_of_mplace(place)?
168 .map(|(size, _)| size)
169 // for extern types, just cover what we can
170 .unwrap_or_else(|| place.layout.size);
171 // Now handle this `UnsafeCell`, unless it is empty.
172 if unsafe_cell_size != Size::ZERO {
173 unsafe_cell_action(place.ptr, unsafe_cell_size)
179 visitor.visit_value(place)?;
181 // The part between the end_ptr and the end of the place is also frozen.
182 // So pretend there is a 0-sized `UnsafeCell` at the end.
183 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
187 /// Visiting the memory covered by a `MemPlace`, being aware of
188 /// whether we are inside an `UnsafeCell` or not.
189 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
190 where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
192 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
193 unsafe_cell_action: F,
196 impl<'ecx, 'mir, 'tcx, F>
197 ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
199 UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
201 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
203 type V = MPlaceTy<'tcx, Tag>;
206 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
210 // Hook to detect `UnsafeCell`.
211 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
213 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
214 let is_unsafe_cell = match v.layout.ty.kind {
215 ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
219 // We do not have to recurse further, this is an `UnsafeCell`.
220 (self.unsafe_cell_action)(v)
221 } else if self.ecx.type_is_freeze(v.layout.ty) {
222 // This is `Freeze`, there cannot be an `UnsafeCell`
225 // We want to not actually read from memory for this visit. So, before
226 // walking this value, we have to make sure it is not a
227 // `Variants::Multiple`.
228 match v.layout.variants {
229 layout::Variants::Multiple { .. } => {
230 // A multi-variant enum, or generator, or so.
231 // Treat this like a union: without reading from memory,
232 // we cannot determine the variant we are in. Reading from
233 // memory would be subject to Stacked Borrows rules, leading
234 // to all sorts of "funny" recursion.
235 // We only end up here if the type is *not* freeze, so we just call the
236 // `UnsafeCell` action.
237 (self.unsafe_cell_action)(v)
239 layout::Variants::Single { .. } => {
240 // Proceed further, try to find where exactly that `UnsafeCell`
248 // Make sure we visit aggregrates in increasing offset order.
251 place: MPlaceTy<'tcx, Tag>,
252 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
253 ) -> InterpResult<'tcx> {
254 match place.layout.fields {
255 layout::FieldPlacement::Array { .. } => {
256 // For the array layout, we know the iterator will yield sorted elements so
257 // we can avoid the allocation.
258 self.walk_aggregate(place, fields)
260 layout::FieldPlacement::Arbitrary { .. } => {
261 // Gather the subplaces and sort them before visiting.
262 let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
263 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
264 self.walk_aggregate(place, places.into_iter().map(Ok))
266 layout::FieldPlacement::Union { .. } => {
268 bug!("a union is not an aggregate we should ever visit")
273 // We have to do *something* for unions.
274 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
276 // With unions, we fall back to whatever the type says, to hopefully be consistent
278 // FIXME: are we consistent, and is this really the behavior we want?
279 let frozen = self.ecx.type_is_freeze(v.layout.ty);
283 (self.unsafe_cell_action)(v)
287 // We should never get to a primitive, but always short-circuit somewhere above.
288 fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
290 bug!("we should always short-circuit before coming to a primitive")