2 use std::ffi::{OsStr, OsString};
4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
8 layout::{self, LayoutOf, Size, TyLayout},
15 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
17 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
18 /// Gets an instance for a path.
19 fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
20 let this = self.eval_context_ref();
24 .find(|&&krate| this.tcx.original_crate_name(krate).as_str() == path[0])
28 index: CRATE_DEF_INDEX,
30 let mut items = this.tcx.item_children(krate);
31 let mut path_it = path.iter().skip(1).peekable();
33 while let Some(segment) = path_it.next() {
34 for item in mem::replace(&mut items, Default::default()).iter() {
35 if item.ident.name.as_str() == *segment {
36 if path_it.peek().is_none() {
37 return Some(ty::Instance::mono(this.tcx.tcx, item.res.def_id()));
40 items = this.tcx.item_children(item.res.def_id());
48 let path = path.iter().map(|&s| s.to_owned()).collect();
49 err_unsup!(PathNotFound(path)).into()
53 /// Write a 0 of the appropriate size to `dest`.
54 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
55 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
58 /// Test if this immediate equals 0.
59 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
60 let this = self.eval_context_ref();
61 let null = Scalar::from_int(0, this.memory.pointer_size());
62 this.ptr_eq(val, null)
65 /// Turn a Scalar into an Option<NonNullScalar>
66 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
67 let this = self.eval_context_ref();
68 Ok(if this.is_null(val)? {
75 /// Get the `Place` for a local
76 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
77 let this = self.eval_context_mut();
78 let place = mir::Place { base: mir::PlaceBase::Local(local), projection: Box::new([]) };
79 this.eval_place(&place)
82 /// Generate some random bytes, and write them to `dest`.
87 ) -> InterpResult<'tcx> {
88 // Some programs pass in a null pointer and a length of 0
89 // to their platform's random-generation function (e.g. getrandom())
90 // on Linux. For compatibility with these programs, we don't perform
91 // any additional checks - it's okay if the pointer is invalid,
92 // since we wouldn't actually be writing to it.
96 let this = self.eval_context_mut();
98 let mut data = vec![0; len];
100 if this.machine.communicate {
101 // Fill the buffer using the host's rng.
102 getrandom::getrandom(&mut data)
103 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
106 let rng = this.memory.extra.rng.get_mut();
107 rng.fill_bytes(&mut data);
110 this.memory.write_bytes(ptr, data.iter().copied())
113 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
114 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
115 fn visit_freeze_sensitive(
117 place: MPlaceTy<'tcx, Tag>,
119 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
120 ) -> InterpResult<'tcx> {
121 let this = self.eval_context_ref();
122 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
123 debug_assert_eq!(size,
124 this.size_and_align_of_mplace(place)?
125 .map(|(size, _)| size)
126 .unwrap_or_else(|| place.layout.size)
128 // Store how far we proceeded into the place so far. Everything to the left of
129 // this offset has already been handled, in the sense that the frozen parts
130 // have had `action` called on them.
131 let mut end_ptr = place.ptr.assert_ptr();
132 // Called when we detected an `UnsafeCell` at the given offset and size.
133 // Calls `action` and advances `end_ptr`.
134 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
135 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
136 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
137 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
138 // We assume that we are given the fields in increasing offset order,
139 // and nothing else changes.
140 let unsafe_cell_offset = unsafe_cell_ptr.offset;
141 let end_offset = end_ptr.offset;
142 assert!(unsafe_cell_offset >= end_offset);
143 let frozen_size = unsafe_cell_offset - end_offset;
144 // Everything between the end_ptr and this `UnsafeCell` is frozen.
145 if frozen_size != Size::ZERO {
146 action(end_ptr, frozen_size, /*frozen*/true)?;
148 // This `UnsafeCell` is NOT frozen.
149 if unsafe_cell_size != Size::ZERO {
150 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
152 // Update end end_ptr.
153 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
159 let mut visitor = UnsafeCellVisitor {
161 unsafe_cell_action: |place| {
162 trace!("unsafe_cell_action on {:?}", place.ptr);
163 // We need a size to go on.
164 let unsafe_cell_size = this.size_and_align_of_mplace(place)?
165 .map(|(size, _)| size)
166 // for extern types, just cover what we can
167 .unwrap_or_else(|| place.layout.size);
168 // Now handle this `UnsafeCell`, unless it is empty.
169 if unsafe_cell_size != Size::ZERO {
170 unsafe_cell_action(place.ptr, unsafe_cell_size)
176 visitor.visit_value(place)?;
178 // The part between the end_ptr and the end of the place is also frozen.
179 // So pretend there is a 0-sized `UnsafeCell` at the end.
180 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
184 /// Visiting the memory covered by a `MemPlace`, being aware of
185 /// whether we are inside an `UnsafeCell` or not.
186 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
187 where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
189 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
190 unsafe_cell_action: F,
193 impl<'ecx, 'mir, 'tcx, F>
194 ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
196 UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
198 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
200 type V = MPlaceTy<'tcx, Tag>;
203 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
207 // Hook to detect `UnsafeCell`.
208 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
210 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
211 let is_unsafe_cell = match v.layout.ty.kind {
212 ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
216 // We do not have to recurse further, this is an `UnsafeCell`.
217 (self.unsafe_cell_action)(v)
218 } else if self.ecx.type_is_freeze(v.layout.ty) {
219 // This is `Freeze`, there cannot be an `UnsafeCell`
222 // We want to not actually read from memory for this visit. So, before
223 // walking this value, we have to make sure it is not a
224 // `Variants::Multiple`.
225 match v.layout.variants {
226 layout::Variants::Multiple { .. } => {
227 // A multi-variant enum, or generator, or so.
228 // Treat this like a union: without reading from memory,
229 // we cannot determine the variant we are in. Reading from
230 // memory would be subject to Stacked Borrows rules, leading
231 // to all sorts of "funny" recursion.
232 // We only end up here if the type is *not* freeze, so we just call the
233 // `UnsafeCell` action.
234 (self.unsafe_cell_action)(v)
236 layout::Variants::Single { .. } => {
237 // Proceed further, try to find where exactly that `UnsafeCell`
245 // Make sure we visit aggregrates in increasing offset order.
248 place: MPlaceTy<'tcx, Tag>,
249 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
250 ) -> InterpResult<'tcx> {
251 match place.layout.fields {
252 layout::FieldPlacement::Array { .. } => {
253 // For the array layout, we know the iterator will yield sorted elements so
254 // we can avoid the allocation.
255 self.walk_aggregate(place, fields)
257 layout::FieldPlacement::Arbitrary { .. } => {
258 // Gather the subplaces and sort them before visiting.
259 let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
260 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
261 self.walk_aggregate(place, places.into_iter().map(Ok))
263 layout::FieldPlacement::Union { .. } => {
265 bug!("a union is not an aggregate we should ever visit")
270 // We have to do *something* for unions.
271 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
273 // With unions, we fall back to whatever the type says, to hopefully be consistent
275 // FIXME: are we consistent, and is this really the behavior we want?
276 let frozen = self.ecx.type_is_freeze(v.layout.ty);
280 (self.unsafe_cell_action)(v)
284 // We should never get to a primitive, but always short-circuit somewhere above.
285 fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
287 bug!("we should always short-circuit before coming to a primitive")
292 /// Helper function to get a `libc` constant as a `Scalar`.
293 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
294 self.eval_context_mut()
295 .eval_path_scalar(&["libc", name])?
296 .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
300 /// Helper function to get a `libc` constant as an `i32`.
301 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
302 self.eval_libc(name)?.to_i32()
305 /// Helper function to get the `TyLayout` of a `libc` type
306 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
307 let this = self.eval_context_mut();
308 let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
312 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
313 // different values into a struct.
314 fn write_packed_immediates(
316 place: &MPlaceTy<'tcx, Tag>,
317 imms: &[ImmTy<'tcx, Tag>],
318 ) -> InterpResult<'tcx> {
319 let this = self.eval_context_mut();
321 let mut offset = Size::from_bytes(0);
324 this.write_immediate_to_mplace(
326 place.offset(offset, None, imm.layout, &*this.tcx)?,
328 offset += imm.layout.size;
333 /// Helper function used inside the shims of foreign functions to check that isolation is
334 /// disabled. It returns an error using the `name` of the foreign function if this is not the
336 fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
337 if !self.eval_context_mut().machine.communicate {
338 throw_unsup_format!("`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.", name)
343 /// Sets the last error variable.
344 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
345 let this = self.eval_context_mut();
346 let errno_place = this.machine.last_error.unwrap();
347 this.write_scalar(scalar, errno_place.into())
350 /// Gets the last error variable.
351 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
352 let this = self.eval_context_mut();
353 let errno_place = this.machine.last_error.unwrap();
354 this.read_scalar(errno_place.into())?.not_undef()
357 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
358 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
359 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
360 use std::io::ErrorKind::*;
361 let this = self.eval_context_mut();
362 let target = &this.tcx.tcx.sess.target.target;
363 let last_error = if target.options.target_family == Some("unix".to_owned()) {
364 this.eval_libc(match e.kind() {
365 ConnectionRefused => "ECONNREFUSED",
366 ConnectionReset => "ECONNRESET",
367 PermissionDenied => "EPERM",
368 BrokenPipe => "EPIPE",
369 NotConnected => "ENOTCONN",
370 ConnectionAborted => "ECONNABORTED",
371 AddrNotAvailable => "EADDRNOTAVAIL",
372 AddrInUse => "EADDRINUSE",
373 NotFound => "ENOENT",
374 Interrupted => "EINTR",
375 InvalidInput => "EINVAL",
376 TimedOut => "ETIMEDOUT",
377 AlreadyExists => "EEXIST",
378 WouldBlock => "EWOULDBLOCK",
379 _ => throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
382 // FIXME: we have to implement the windows' equivalent of this.
383 throw_unsup_format!("Setting the last OS error from an io::Error is unsupported for {}.", target.target_os)
385 this.set_last_error(last_error)
388 /// Helper function that consumes an `std::io::Result<T>` and returns an
389 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
390 /// `Ok(-1)` and sets the last OS error accordingly.
392 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
393 /// functions return different integer types (like `read`, that returns an `i64`)
394 fn try_unwrap_io_result<T: From<i32>>(
396 result: std::io::Result<T>,
397 ) -> InterpResult<'tcx, T> {
401 self.eval_context_mut().set_last_error_from_io_error(e)?;
407 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
408 /// the Unix APIs usually handle.
409 fn read_os_string_from_c_string(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString> {
410 let bytes = self.eval_context_mut().memory.read_c_str(scalar)?;
411 Ok(bytes_to_os_str(bytes)?.into())
414 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
415 /// the Unix APIs usually handle.
416 fn write_os_str_to_c_string(&mut self, os_str: &OsStr, scalar: Scalar<Tag>, size: u64) -> InterpResult<'tcx> {
417 let bytes = os_str_to_bytes(os_str)?;
418 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
419 // terminator to memory using the `ptr` pointer would cause an overflow.
420 if size <= bytes.len() as u64 {
421 throw_unsup_format!("OsString of length {} is too large for destination buffer of size {}", bytes.len(), size)
423 // FIXME: We should use `Iterator::chain` instead when rust-lang/rust#65704 lands.
424 self.eval_context_mut().memory.write_bytes(scalar, [bytes, &[0]].concat())
428 #[cfg(target_os = "unix")]
429 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
430 std::os::unix::ffi::OsStringExt::into_bytes(os_str)
433 #[cfg(target_os = "unix")]
434 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a[u8]) -> InterpResult<'tcx, &'a OsStr> {
435 Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
438 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
439 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
441 #[cfg(not(target_os = "unix"))]
442 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
445 .map(|s| s.as_bytes())
446 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
449 #[cfg(not(target_os = "unix"))]
450 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a[u8]) -> InterpResult<'tcx, &'a OsStr> {
451 let s = std::str::from_utf8(bytes)
452 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;