2 use std::ffi::{OsStr, OsString};
4 use syntax::source_map::DUMMY_SP;
5 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
11 layout::{self, LayoutOf, Size, TyLayout},
18 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
20 /// Gets an instance for a path.
21 fn resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> InterpResult<'tcx, DefId> {
25 .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
29 index: CRATE_DEF_INDEX,
31 let mut items = tcx.item_children(krate);
32 let mut path_it = path.iter().skip(1).peekable();
34 while let Some(segment) = path_it.next() {
35 for item in mem::replace(&mut items, Default::default()).iter() {
36 if item.ident.name.as_str() == *segment {
37 if path_it.peek().is_none() {
38 return Some(item.res.def_id())
41 items = tcx.item_children(item.res.def_id());
49 let path = path.iter().map(|&s| s.to_owned()).collect();
50 err_unsup!(PathNotFound(path)).into()
55 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
57 /// Gets an instance for a path.
58 fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
59 Ok(ty::Instance::mono(self.eval_context_ref().tcx.tcx, resolve_did(self.eval_context_ref().tcx.tcx, path)?))
62 /// Write a 0 of the appropriate size to `dest`.
63 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
64 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
67 /// Test if this immediate equals 0.
68 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
69 let this = self.eval_context_ref();
70 let null = Scalar::from_int(0, this.memory.pointer_size());
71 this.ptr_eq(val, null)
74 /// Turn a Scalar into an Option<NonNullScalar>
75 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
76 let this = self.eval_context_ref();
77 Ok(if this.is_null(val)? {
84 /// Get the `Place` for a local
85 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
86 let this = self.eval_context_mut();
87 let place = mir::Place { base: mir::PlaceBase::Local(local), projection: List::empty() };
88 this.eval_place(&place)
91 /// Generate some random bytes, and write them to `dest`.
96 ) -> InterpResult<'tcx> {
97 // Some programs pass in a null pointer and a length of 0
98 // to their platform's random-generation function (e.g. getrandom())
99 // on Linux. For compatibility with these programs, we don't perform
100 // any additional checks - it's okay if the pointer is invalid,
101 // since we wouldn't actually be writing to it.
105 let this = self.eval_context_mut();
107 let mut data = vec![0; len];
109 if this.machine.communicate {
110 // Fill the buffer using the host's rng.
111 getrandom::getrandom(&mut data)
112 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
115 let rng = this.memory.extra.rng.get_mut();
116 rng.fill_bytes(&mut data);
119 this.memory.write_bytes(ptr, data.iter().copied())
122 /// Call a function: Push the stack frame and pass the arguments.
123 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
126 f: ty::Instance<'tcx>,
127 args: &[Immediate<Tag>],
128 dest: Option<PlaceTy<'tcx, Tag>>,
129 stack_pop: StackPopCleanup,
130 ) -> InterpResult<'tcx> {
131 let this = self.eval_context_mut();
134 let mir = this.load_mir(f.def, None)?;
135 let span = this.stack().last()
136 .and_then(Frame::current_source_info)
138 .unwrap_or(DUMMY_SP);
139 this.push_stack_frame(
147 // Initialize arguments.
148 let mut callee_args = this.frame().body.args_iter();
150 let callee_arg = this.local_place(
151 callee_args.next().expect("callee has fewer arguments than expected")
153 this.write_immediate(*arg, callee_arg)?;
155 callee_args.next().expect_none("callee has more arguments than expected");
160 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
161 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
162 fn visit_freeze_sensitive(
164 place: MPlaceTy<'tcx, Tag>,
166 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
167 ) -> InterpResult<'tcx> {
168 let this = self.eval_context_ref();
169 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
170 debug_assert_eq!(size,
171 this.size_and_align_of_mplace(place)?
172 .map(|(size, _)| size)
173 .unwrap_or_else(|| place.layout.size)
175 // Store how far we proceeded into the place so far. Everything to the left of
176 // this offset has already been handled, in the sense that the frozen parts
177 // have had `action` called on them.
178 let mut end_ptr = place.ptr.assert_ptr();
179 // Called when we detected an `UnsafeCell` at the given offset and size.
180 // Calls `action` and advances `end_ptr`.
181 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
182 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
183 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
184 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
185 // We assume that we are given the fields in increasing offset order,
186 // and nothing else changes.
187 let unsafe_cell_offset = unsafe_cell_ptr.offset;
188 let end_offset = end_ptr.offset;
189 assert!(unsafe_cell_offset >= end_offset);
190 let frozen_size = unsafe_cell_offset - end_offset;
191 // Everything between the end_ptr and this `UnsafeCell` is frozen.
192 if frozen_size != Size::ZERO {
193 action(end_ptr, frozen_size, /*frozen*/true)?;
195 // This `UnsafeCell` is NOT frozen.
196 if unsafe_cell_size != Size::ZERO {
197 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
199 // Update end end_ptr.
200 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
206 let mut visitor = UnsafeCellVisitor {
208 unsafe_cell_action: |place| {
209 trace!("unsafe_cell_action on {:?}", place.ptr);
210 // We need a size to go on.
211 let unsafe_cell_size = this.size_and_align_of_mplace(place)?
212 .map(|(size, _)| size)
213 // for extern types, just cover what we can
214 .unwrap_or_else(|| place.layout.size);
215 // Now handle this `UnsafeCell`, unless it is empty.
216 if unsafe_cell_size != Size::ZERO {
217 unsafe_cell_action(place.ptr, unsafe_cell_size)
223 visitor.visit_value(place)?;
225 // The part between the end_ptr and the end of the place is also frozen.
226 // So pretend there is a 0-sized `UnsafeCell` at the end.
227 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
231 /// Visiting the memory covered by a `MemPlace`, being aware of
232 /// whether we are inside an `UnsafeCell` or not.
233 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
234 where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
236 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
237 unsafe_cell_action: F,
240 impl<'ecx, 'mir, 'tcx, F>
241 ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
243 UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
245 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
247 type V = MPlaceTy<'tcx, Tag>;
250 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
254 // Hook to detect `UnsafeCell`.
255 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
257 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
258 let is_unsafe_cell = match v.layout.ty.kind {
259 ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
263 // We do not have to recurse further, this is an `UnsafeCell`.
264 (self.unsafe_cell_action)(v)
265 } else if self.ecx.type_is_freeze(v.layout.ty) {
266 // This is `Freeze`, there cannot be an `UnsafeCell`
269 // We want to not actually read from memory for this visit. So, before
270 // walking this value, we have to make sure it is not a
271 // `Variants::Multiple`.
272 match v.layout.variants {
273 layout::Variants::Multiple { .. } => {
274 // A multi-variant enum, or generator, or so.
275 // Treat this like a union: without reading from memory,
276 // we cannot determine the variant we are in. Reading from
277 // memory would be subject to Stacked Borrows rules, leading
278 // to all sorts of "funny" recursion.
279 // We only end up here if the type is *not* freeze, so we just call the
280 // `UnsafeCell` action.
281 (self.unsafe_cell_action)(v)
283 layout::Variants::Single { .. } => {
284 // Proceed further, try to find where exactly that `UnsafeCell`
292 // Make sure we visit aggregrates in increasing offset order.
295 place: MPlaceTy<'tcx, Tag>,
296 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
297 ) -> InterpResult<'tcx> {
298 match place.layout.fields {
299 layout::FieldPlacement::Array { .. } => {
300 // For the array layout, we know the iterator will yield sorted elements so
301 // we can avoid the allocation.
302 self.walk_aggregate(place, fields)
304 layout::FieldPlacement::Arbitrary { .. } => {
305 // Gather the subplaces and sort them before visiting.
306 let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
307 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
308 self.walk_aggregate(place, places.into_iter().map(Ok))
310 layout::FieldPlacement::Union { .. } => {
312 bug!("a union is not an aggregate we should ever visit")
317 // We have to do *something* for unions.
318 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
320 // With unions, we fall back to whatever the type says, to hopefully be consistent
322 // FIXME: are we consistent, and is this really the behavior we want?
323 let frozen = self.ecx.type_is_freeze(v.layout.ty);
327 (self.unsafe_cell_action)(v)
331 // We should never get to a primitive, but always short-circuit somewhere above.
332 fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
334 bug!("we should always short-circuit before coming to a primitive")
339 /// Helper function to get a `libc` constant as a `Scalar`.
340 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
341 self.eval_context_mut()
342 .eval_path_scalar(&["libc", name])?
343 .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
347 /// Helper function to get a `libc` constant as an `i32`.
348 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
349 self.eval_libc(name)?.to_i32()
352 /// Helper function to get the `TyLayout` of a `libc` type
353 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
354 let this = self.eval_context_mut();
355 let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
359 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
360 // different values into a struct.
361 fn write_packed_immediates(
363 place: &MPlaceTy<'tcx, Tag>,
364 imms: &[ImmTy<'tcx, Tag>],
365 ) -> InterpResult<'tcx> {
366 let this = self.eval_context_mut();
368 let mut offset = Size::from_bytes(0);
371 this.write_immediate_to_mplace(
373 place.offset(offset, None, imm.layout, &*this.tcx)?,
375 offset += imm.layout.size;
380 /// Helper function used inside the shims of foreign functions to check that isolation is
381 /// disabled. It returns an error using the `name` of the foreign function if this is not the
383 fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
384 if !self.eval_context_mut().machine.communicate {
385 throw_unsup_format!("`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.", name)
390 /// Sets the last error variable.
391 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
392 let this = self.eval_context_mut();
393 let errno_place = this.machine.last_error.unwrap();
394 this.write_scalar(scalar, errno_place.into())
397 /// Gets the last error variable.
398 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
399 let this = self.eval_context_mut();
400 let errno_place = this.machine.last_error.unwrap();
401 this.read_scalar(errno_place.into())?.not_undef()
404 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
405 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
406 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
407 use std::io::ErrorKind::*;
408 let this = self.eval_context_mut();
409 let target = &this.tcx.tcx.sess.target.target;
410 let last_error = if target.options.target_family == Some("unix".to_owned()) {
411 this.eval_libc(match e.kind() {
412 ConnectionRefused => "ECONNREFUSED",
413 ConnectionReset => "ECONNRESET",
414 PermissionDenied => "EPERM",
415 BrokenPipe => "EPIPE",
416 NotConnected => "ENOTCONN",
417 ConnectionAborted => "ECONNABORTED",
418 AddrNotAvailable => "EADDRNOTAVAIL",
419 AddrInUse => "EADDRINUSE",
420 NotFound => "ENOENT",
421 Interrupted => "EINTR",
422 InvalidInput => "EINVAL",
423 TimedOut => "ETIMEDOUT",
424 AlreadyExists => "EEXIST",
425 WouldBlock => "EWOULDBLOCK",
426 _ => throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
429 // FIXME: we have to implement the Windows equivalent of this.
430 throw_unsup_format!("Setting the last OS error from an io::Error is unsupported for {}.", target.target_os)
432 this.set_last_error(last_error)
435 /// Helper function that consumes an `std::io::Result<T>` and returns an
436 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
437 /// `Ok(-1)` and sets the last OS error accordingly.
439 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
440 /// functions return different integer types (like `read`, that returns an `i64`).
441 fn try_unwrap_io_result<T: From<i32>>(
443 result: std::io::Result<T>,
444 ) -> InterpResult<'tcx, T> {
448 self.eval_context_mut().set_last_error_from_io_error(e)?;
454 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
455 /// the Unix APIs usually handle.
456 fn read_os_string_from_c_string(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString> {
457 let bytes = self.eval_context_mut().memory.read_c_str(scalar)?;
458 Ok(bytes_to_os_str(bytes)?.into())
461 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
462 /// the Unix APIs usually handle. This function returns `Ok(false)` without trying to write if
463 /// `size` is not large enough to fit the contents of `os_string` plus a null terminator. It
464 /// returns `Ok(true)` if the writing process was successful.
465 fn write_os_str_to_c_string(
470 ) -> InterpResult<'tcx, bool> {
471 let bytes = os_str_to_bytes(os_str)?;
472 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
473 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
474 if size <= bytes.len() as u64 {
477 self.eval_context_mut().memory.write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
482 #[cfg(target_os = "unix")]
483 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
484 std::os::unix::ffi::OsStringExt::into_bytes(os_str)
487 #[cfg(target_os = "unix")]
488 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a[u8]) -> InterpResult<'tcx, &'a OsStr> {
489 Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
492 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
493 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
495 #[cfg(not(target_os = "unix"))]
496 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
499 .map(|s| s.as_bytes())
500 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
503 #[cfg(not(target_os = "unix"))]
504 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a[u8]) -> InterpResult<'tcx, &'a OsStr> {
505 let s = std::str::from_utf8(bytes)
506 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;