Skip to content

Commit e1e95a8

Browse files
committed
Use force_bits when casting from a pointer
1 parent d3e2cec commit e1e95a8

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

src/librustc_mir/interpret/cast.rs

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -242,14 +242,31 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpretCx<'mir, 'tcx, M> {
242242
ty: Ty<'tcx>
243243
) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
244244
use rustc::ty::TyKind::*;
245-
match ty.sty {
245+
246+
let size = match ty.sty {
246247
// Casting to a reference or fn pointer is not permitted by rustc,
247248
// no need to support it here.
248-
RawPtr(_) |
249-
Int(IntTy::Isize) |
250-
Uint(UintTy::Usize) => Ok(ptr.into()),
251-
Int(_) | Uint(_) => err!(ReadPointerAsBytes),
252-
_ => err!(Unimplemented(format!("ptr to {:?} cast", ty))),
249+
RawPtr(_) => return Ok(ptr.into()),
250+
Int(IntTy::Isize) | Uint(UintTy::Usize) => {
251+
let size = self.memory.pointer_size();
252+
if let Ok(bits) = self.force_bits(Scalar::Ptr(ptr), size) {
253+
return Ok(Scalar::from_uint(bits, size));
254+
}
255+
return Ok(ptr.into());
256+
}
257+
// If the target type is a sized integer, we need the its size to perform the pointer cast
258+
Int(i) => i.bit_width().unwrap(),
259+
Uint(i) => i.bit_width().unwrap(),
260+
// Casting to any other type is not implemented
261+
_ => return err!(Unimplemented(format!("ptr to {:?} cast", ty))),
262+
};
263+
264+
let size = Size::from_bits(size as u64);
265+
266+
if let Ok(bits) = self.force_bits(Scalar::Ptr(ptr), size) {
267+
Ok(Scalar::from_uint(bits, size))
268+
} else {
269+
err!(ReadPointerAsBytes)
253270
}
254271
}
255272

0 commit comments

Comments
 (0)