From fcbaf990f222cdfbfcd89f639793290bba1fed23 Mon Sep 17 00:00:00 2001 From: Oliver Schneider Date: Mon, 26 Sep 2016 11:37:23 +0200 Subject: [PATCH] check `Pointer::to_int` for non-integer pointers --- src/interpreter/cast.rs | 11 ++++++++++- src/memory.rs | 8 ++++++-- src/primval.rs | 4 ++-- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/interpreter/cast.rs b/src/interpreter/cast.rs index 4f31cc210339..a924d59782ad 100644 --- a/src/interpreter/cast.rs +++ b/src/interpreter/cast.rs @@ -8,7 +8,7 @@ use primval::PrimVal; use memory::Pointer; use rustc::ty::Ty; -use syntax::ast; +use syntax::ast::{self, IntTy, UintTy}; impl<'a, 'tcx> EvalContext<'a, 'tcx> { pub(super) fn cast_primval(&self, val: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx, PrimVal> { @@ -38,6 +38,15 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> { ty::TyRef(..) | ty::TyRawPtr(_) => Ok(Ptr(ptr)), ty::TyFnPtr(_) => Ok(FnPtr(ptr)), + // FIXME: can truncation happen here? + ty::TyInt(IntTy::I8) => Ok(I8(ptr.to_int()? as i8)), + ty::TyInt(IntTy::I16) => Ok(I16(ptr.to_int()? as i16)), + ty::TyInt(IntTy::I32) => Ok(I32(ptr.to_int()? as i32)), + ty::TyInt(IntTy::I64) => Ok(I64(ptr.to_int()? as i64)), + ty::TyUint(UintTy::U8) => Ok(U8(ptr.to_int()? as u8)), + ty::TyUint(UintTy::U16) => Ok(U16(ptr.to_int()? as u16)), + ty::TyUint(UintTy::U32) => Ok(U32(ptr.to_int()? as u32)), + ty::TyUint(UintTy::U64) => Ok(U64(ptr.to_int()? as u64)), _ => Err(EvalError::Unimplemented(format!("ptr to {:?} cast", ty))), } } diff --git a/src/memory.rs b/src/memory.rs index d1c0c7408433..bdd9cd2fa0f4 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -55,8 +55,12 @@ impl Pointer { pub fn points_to_zst(&self) -> bool { self.alloc_id == ZST_ALLOC_ID } - pub fn to_int(&self) -> usize { - self.offset + pub fn to_int<'tcx>(&self) -> EvalResult<'tcx, usize> { + if self.points_to_zst() { + Ok(self.offset) + } else { + Err(EvalError::ReadPointerAsBytes) + } } pub fn from_int(i: usize) -> Self { Pointer { diff --git a/src/primval.rs b/src/primval.rs index 82e261625249..7d88e2ee7b14 100644 --- a/src/primval.rs +++ b/src/primval.rs @@ -46,7 +46,7 @@ impl PrimVal { U16(u) => u as u64, U32(u) => u as u64, U64(u) => u, - Ptr(ptr) => ptr.to_int() as u64, + Ptr(ptr) => ptr.to_int().expect("non abstract ptr") as u64, _ => bug!("{}", error_msg), } } @@ -58,7 +58,7 @@ impl PrimVal { I16(i) => i as i64, I32(i) => i as i64, I64(i) => i, - Ptr(ptr) => ptr.to_int() as i64, + Ptr(ptr) => ptr.to_int().expect("non abstract ptr") as i64, _ => bug!("{}", error_msg), } }