3 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
7 layout::{self, Align, LayoutOf, Size, TyLayout},
14 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
16 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
17 /// Gets an instance for a path.
18 fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
19 let this = self.eval_context_ref();
23 .find(|&&krate| this.tcx.original_crate_name(krate).as_str() == path[0])
27 index: CRATE_DEF_INDEX,
29 let mut items = this.tcx.item_children(krate);
30 let mut path_it = path.iter().skip(1).peekable();
32 while let Some(segment) = path_it.next() {
33 for item in mem::replace(&mut items, Default::default()).iter() {
34 if item.ident.name.as_str() == *segment {
35 if path_it.peek().is_none() {
36 return Some(ty::Instance::mono(this.tcx.tcx, item.res.def_id()));
39 items = this.tcx.item_children(item.res.def_id());
47 let path = path.iter().map(|&s| s.to_owned()).collect();
48 err_unsup!(PathNotFound(path)).into()
52 /// Write a 0 of the appropriate size to `dest`.
53 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
54 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
57 /// Test if this immediate equals 0.
58 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
59 let this = self.eval_context_ref();
60 let null = Scalar::from_int(0, this.memory.pointer_size());
61 this.ptr_eq(val, null)
64 /// Turn a Scalar into an Option<NonNullScalar>
65 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
66 let this = self.eval_context_ref();
67 Ok(if this.is_null(val)? {
74 /// Get the `Place` for a local
75 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
76 let this = self.eval_context_mut();
77 let place = mir::Place { base: mir::PlaceBase::Local(local), projection: Box::new([]) };
78 this.eval_place(&place)
81 /// Generate some random bytes, and write them to `dest`.
86 ) -> InterpResult<'tcx> {
87 // Some programs pass in a null pointer and a length of 0
88 // to their platform's random-generation function (e.g. getrandom())
89 // on Linux. For compatibility with these programs, we don't perform
90 // any additional checks - it's okay if the pointer is invalid,
91 // since we wouldn't actually be writing to it.
95 let this = self.eval_context_mut();
97 let ptr = this.memory.check_ptr_access(
99 Size::from_bytes(len as u64),
100 Align::from_bytes(1).unwrap()
101 )?.expect("we already checked for size 0");
103 let mut data = vec![0; len];
105 if this.machine.communicate {
106 // Fill the buffer using the host's rng.
107 getrandom::getrandom(&mut data)
108 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
111 let rng = this.memory.extra.rng.get_mut();
112 rng.fill_bytes(&mut data);
115 this.memory.get_mut(ptr.alloc_id)?.write_bytes(&*this.tcx, ptr, &data)
118 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
119 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
120 fn visit_freeze_sensitive(
122 place: MPlaceTy<'tcx, Tag>,
124 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
125 ) -> InterpResult<'tcx> {
126 let this = self.eval_context_ref();
127 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
128 debug_assert_eq!(size,
129 this.size_and_align_of_mplace(place)?
130 .map(|(size, _)| size)
131 .unwrap_or_else(|| place.layout.size)
133 // Store how far we proceeded into the place so far. Everything to the left of
134 // this offset has already been handled, in the sense that the frozen parts
135 // have had `action` called on them.
136 let mut end_ptr = place.ptr.assert_ptr();
137 // Called when we detected an `UnsafeCell` at the given offset and size.
138 // Calls `action` and advances `end_ptr`.
139 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
140 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
141 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
142 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
143 // We assume that we are given the fields in increasing offset order,
144 // and nothing else changes.
145 let unsafe_cell_offset = unsafe_cell_ptr.offset;
146 let end_offset = end_ptr.offset;
147 assert!(unsafe_cell_offset >= end_offset);
148 let frozen_size = unsafe_cell_offset - end_offset;
149 // Everything between the end_ptr and this `UnsafeCell` is frozen.
150 if frozen_size != Size::ZERO {
151 action(end_ptr, frozen_size, /*frozen*/true)?;
153 // This `UnsafeCell` is NOT frozen.
154 if unsafe_cell_size != Size::ZERO {
155 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
157 // Update end end_ptr.
158 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
164 let mut visitor = UnsafeCellVisitor {
166 unsafe_cell_action: |place| {
167 trace!("unsafe_cell_action on {:?}", place.ptr);
168 // We need a size to go on.
169 let unsafe_cell_size = this.size_and_align_of_mplace(place)?
170 .map(|(size, _)| size)
171 // for extern types, just cover what we can
172 .unwrap_or_else(|| place.layout.size);
173 // Now handle this `UnsafeCell`, unless it is empty.
174 if unsafe_cell_size != Size::ZERO {
175 unsafe_cell_action(place.ptr, unsafe_cell_size)
181 visitor.visit_value(place)?;
183 // The part between the end_ptr and the end of the place is also frozen.
184 // So pretend there is a 0-sized `UnsafeCell` at the end.
185 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
189 /// Visiting the memory covered by a `MemPlace`, being aware of
190 /// whether we are inside an `UnsafeCell` or not.
191 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
192 where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
194 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
195 unsafe_cell_action: F,
198 impl<'ecx, 'mir, 'tcx, F>
199 ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
201 UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
203 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
205 type V = MPlaceTy<'tcx, Tag>;
208 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
212 // Hook to detect `UnsafeCell`.
213 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
215 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
216 let is_unsafe_cell = match v.layout.ty.kind {
217 ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
221 // We do not have to recurse further, this is an `UnsafeCell`.
222 (self.unsafe_cell_action)(v)
223 } else if self.ecx.type_is_freeze(v.layout.ty) {
224 // This is `Freeze`, there cannot be an `UnsafeCell`
227 // We want to not actually read from memory for this visit. So, before
228 // walking this value, we have to make sure it is not a
229 // `Variants::Multiple`.
230 match v.layout.variants {
231 layout::Variants::Multiple { .. } => {
232 // A multi-variant enum, or generator, or so.
233 // Treat this like a union: without reading from memory,
234 // we cannot determine the variant we are in. Reading from
235 // memory would be subject to Stacked Borrows rules, leading
236 // to all sorts of "funny" recursion.
237 // We only end up here if the type is *not* freeze, so we just call the
238 // `UnsafeCell` action.
239 (self.unsafe_cell_action)(v)
241 layout::Variants::Single { .. } => {
242 // Proceed further, try to find where exactly that `UnsafeCell`
250 // Make sure we visit aggregrates in increasing offset order.
253 place: MPlaceTy<'tcx, Tag>,
254 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
255 ) -> InterpResult<'tcx> {
256 match place.layout.fields {
257 layout::FieldPlacement::Array { .. } => {
258 // For the array layout, we know the iterator will yield sorted elements so
259 // we can avoid the allocation.
260 self.walk_aggregate(place, fields)
262 layout::FieldPlacement::Arbitrary { .. } => {
263 // Gather the subplaces and sort them before visiting.
264 let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
265 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
266 self.walk_aggregate(place, places.into_iter().map(Ok))
268 layout::FieldPlacement::Union { .. } => {
270 bug!("a union is not an aggregate we should ever visit")
275 // We have to do *something* for unions.
276 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
278 // With unions, we fall back to whatever the type says, to hopefully be consistent
280 // FIXME: are we consistent, and is this really the behavior we want?
281 let frozen = self.ecx.type_is_freeze(v.layout.ty);
285 (self.unsafe_cell_action)(v)
289 // We should never get to a primitive, but always short-circuit somewhere above.
290 fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
292 bug!("we should always short-circuit before coming to a primitive")
297 /// Helper function to get a `libc` constant as a `Scalar`.
298 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
299 self.eval_context_mut()
300 .eval_path_scalar(&["libc", name])?
301 .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
305 /// Helper function to get a `libc` constant as an `i32`.
306 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
307 self.eval_libc(name)?.to_i32()
310 /// Helper function to get the `TyLayout` of a `libc` type
311 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
312 let this = self.eval_context_mut();
313 let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
317 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
318 // different values into a struct.
319 fn write_packed_immediates(
321 place: &MPlaceTy<'tcx, Tag>,
322 imms: &[ImmTy<'tcx, Tag>],
323 ) -> InterpResult<'tcx> {
324 let this = self.eval_context_mut();
326 let mut offset = Size::from_bytes(0);
329 this.write_immediate_to_mplace(
331 place.offset(offset, None, imm.layout, &*this.tcx)?,
333 offset += imm.layout.size;
338 /// Helper function used inside the shims of foreign functions to check that isolation is
339 /// disabled. It returns an error using the `name` of the foreign function if this is not the
341 fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
342 if !self.eval_context_mut().machine.communicate {
343 throw_unsup_format!("`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.", name)