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 // Don't forget the bounds check.
98 let ptr = this.memory.check_ptr_access(
100 Size::from_bytes(len as u64),
101 Align::from_bytes(1).unwrap()
102 )?.expect("we already checked for size 0");
104 let mut data = vec![0; len];
106 if this.machine.communicate {
107 // Fill the buffer using the host's rng.
108 getrandom::getrandom(&mut data)
109 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
112 let rng = this.memory.extra.rng.get_mut();
113 rng.fill_bytes(&mut data);
116 this.memory.get_mut(ptr.alloc_id)?.write_bytes(&*this.tcx, ptr, &data)
119 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
120 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
121 fn visit_freeze_sensitive(
123 place: MPlaceTy<'tcx, Tag>,
125 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
126 ) -> InterpResult<'tcx> {
127 let this = self.eval_context_ref();
128 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
129 debug_assert_eq!(size,
130 this.size_and_align_of_mplace(place)?
131 .map(|(size, _)| size)
132 .unwrap_or_else(|| place.layout.size)
134 // Store how far we proceeded into the place so far. Everything to the left of
135 // this offset has already been handled, in the sense that the frozen parts
136 // have had `action` called on them.
137 let mut end_ptr = place.ptr.assert_ptr();
138 // Called when we detected an `UnsafeCell` at the given offset and size.
139 // Calls `action` and advances `end_ptr`.
140 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
141 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
142 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
143 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
144 // We assume that we are given the fields in increasing offset order,
145 // and nothing else changes.
146 let unsafe_cell_offset = unsafe_cell_ptr.offset;
147 let end_offset = end_ptr.offset;
148 assert!(unsafe_cell_offset >= end_offset);
149 let frozen_size = unsafe_cell_offset - end_offset;
150 // Everything between the end_ptr and this `UnsafeCell` is frozen.
151 if frozen_size != Size::ZERO {
152 action(end_ptr, frozen_size, /*frozen*/true)?;
154 // This `UnsafeCell` is NOT frozen.
155 if unsafe_cell_size != Size::ZERO {
156 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
158 // Update end end_ptr.
159 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
165 let mut visitor = UnsafeCellVisitor {
167 unsafe_cell_action: |place| {
168 trace!("unsafe_cell_action on {:?}", place.ptr);
169 // We need a size to go on.
170 let unsafe_cell_size = this.size_and_align_of_mplace(place)?
171 .map(|(size, _)| size)
172 // for extern types, just cover what we can
173 .unwrap_or_else(|| place.layout.size);
174 // Now handle this `UnsafeCell`, unless it is empty.
175 if unsafe_cell_size != Size::ZERO {
176 unsafe_cell_action(place.ptr, unsafe_cell_size)
182 visitor.visit_value(place)?;
184 // The part between the end_ptr and the end of the place is also frozen.
185 // So pretend there is a 0-sized `UnsafeCell` at the end.
186 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
190 /// Visiting the memory covered by a `MemPlace`, being aware of
191 /// whether we are inside an `UnsafeCell` or not.
192 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
193 where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
195 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
196 unsafe_cell_action: F,
199 impl<'ecx, 'mir, 'tcx, F>
200 ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
202 UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
204 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
206 type V = MPlaceTy<'tcx, Tag>;
209 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
213 // Hook to detect `UnsafeCell`.
214 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
216 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
217 let is_unsafe_cell = match v.layout.ty.kind {
218 ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
222 // We do not have to recurse further, this is an `UnsafeCell`.
223 (self.unsafe_cell_action)(v)
224 } else if self.ecx.type_is_freeze(v.layout.ty) {
225 // This is `Freeze`, there cannot be an `UnsafeCell`
228 // We want to not actually read from memory for this visit. So, before
229 // walking this value, we have to make sure it is not a
230 // `Variants::Multiple`.
231 match v.layout.variants {
232 layout::Variants::Multiple { .. } => {
233 // A multi-variant enum, or generator, or so.
234 // Treat this like a union: without reading from memory,
235 // we cannot determine the variant we are in. Reading from
236 // memory would be subject to Stacked Borrows rules, leading
237 // to all sorts of "funny" recursion.
238 // We only end up here if the type is *not* freeze, so we just call the
239 // `UnsafeCell` action.
240 (self.unsafe_cell_action)(v)
242 layout::Variants::Single { .. } => {
243 // Proceed further, try to find where exactly that `UnsafeCell`
251 // Make sure we visit aggregrates in increasing offset order.
254 place: MPlaceTy<'tcx, Tag>,
255 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
256 ) -> InterpResult<'tcx> {
257 match place.layout.fields {
258 layout::FieldPlacement::Array { .. } => {
259 // For the array layout, we know the iterator will yield sorted elements so
260 // we can avoid the allocation.
261 self.walk_aggregate(place, fields)
263 layout::FieldPlacement::Arbitrary { .. } => {
264 // Gather the subplaces and sort them before visiting.
265 let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
266 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
267 self.walk_aggregate(place, places.into_iter().map(Ok))
269 layout::FieldPlacement::Union { .. } => {
271 bug!("a union is not an aggregate we should ever visit")
276 // We have to do *something* for unions.
277 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
279 // With unions, we fall back to whatever the type says, to hopefully be consistent
281 // FIXME: are we consistent, and is this really the behavior we want?
282 let frozen = self.ecx.type_is_freeze(v.layout.ty);
286 (self.unsafe_cell_action)(v)
290 // We should never get to a primitive, but always short-circuit somewhere above.
291 fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
293 bug!("we should always short-circuit before coming to a primitive")
298 /// Helper function to get a `libc` constant as a `Scalar`.
299 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
300 self.eval_context_mut()
301 .eval_path_scalar(&["libc", name])?
302 .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
306 /// Helper function to get a `libc` constant as an `i32`.
307 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
308 self.eval_libc(name)?.to_i32()
311 /// Helper function to get the `TyLayout` of a `libc` type
312 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
313 let this = self.eval_context_mut();
314 let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
318 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
319 // different values into a struct.
320 fn write_packed_immediates(
322 place: &MPlaceTy<'tcx, Tag>,
323 imms: &[ImmTy<'tcx, Tag>],
324 ) -> InterpResult<'tcx> {
325 let this = self.eval_context_mut();
327 let mut offset = Size::from_bytes(0);
330 this.write_immediate_to_mplace(
332 place.offset(offset, None, imm.layout, &*this.tcx)?,
334 offset += imm.layout.size;
339 /// Helper function used inside the shims of foreign functions to check that isolation is
340 /// disabled. It returns an error using the `name` of the foreign function if this is not the
342 fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
343 if !self.eval_context_mut().machine.communicate {
344 throw_unsup_format!("`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.", name)
349 /// Sets the last error variable
350 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
351 let this = self.eval_context_mut();
352 let errno_place = this.machine.last_error.unwrap();
353 this.write_scalar(scalar, errno_place.into())
356 /// Gets the last error variable
357 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
358 let this = self.eval_context_mut();
359 let errno_place = this.machine.last_error.unwrap();
360 this.read_scalar(errno_place.into())?.not_undef()
363 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
364 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
365 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
366 use std::io::ErrorKind::*;
367 let this = self.eval_context_mut();
368 let target = &this.tcx.tcx.sess.target.target;
369 let last_error = if target.options.target_family == Some("unix".to_owned()) {
370 this.eval_libc(match e.kind() {
371 ConnectionRefused => "ECONNREFUSED",
372 ConnectionReset => "ECONNRESET",
373 PermissionDenied => "EPERM",
374 BrokenPipe => "EPIPE",
375 NotConnected => "ENOTCONN",
376 ConnectionAborted => "ECONNABORTED",
377 AddrNotAvailable => "EADDRNOTAVAIL",
378 AddrInUse => "EADDRINUSE",
379 NotFound => "ENOENT",
380 Interrupted => "EINTR",
381 InvalidInput => "EINVAL",
382 TimedOut => "ETIMEDOUT",
383 AlreadyExists => "EEXIST",
384 WouldBlock => "EWOULDBLOCK",
385 _ => throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
388 // FIXME: we have to implement the windows' equivalent of this.
389 throw_unsup_format!("Setting the last OS error from an io::Error is unsupported for {}.", target.target_os)
391 this.set_last_error(last_error)
394 /// Helper function that consumes an `std::io::Result<T>` and returns an
395 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
396 /// `Ok(-1)` and sets the last OS error accordingly.
398 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
399 /// functions return different integer types (like `read`, that returns an `i64`)
400 fn try_unwrap_io_result<T: From<i32>>(
402 result: std::io::Result<T>,
403 ) -> InterpResult<'tcx, T> {
407 self.eval_context_mut().set_last_error_from_io_error(e)?;