Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mir-interpret: add method to read wide strings from Memory #69326

Merged
merged 1 commit into from
Mar 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/librustc/mir/interpret/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,11 @@ impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
self.not_undef()?.to_u8()
}

#[inline(always)]
pub fn to_u16(self) -> InterpResult<'tcx, u16> {
self.not_undef()?.to_u16()
}
JOE1994 marked this conversation as resolved.
Show resolved Hide resolved

#[inline(always)]
pub fn to_u32(self) -> InterpResult<'tcx, u32> {
self.not_undef()?.to_u32()
Expand All @@ -610,6 +615,11 @@ impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
self.not_undef()?.to_i8()
}

#[inline(always)]
pub fn to_i16(self) -> InterpResult<'tcx, i16> {
self.not_undef()?.to_i16()
}

#[inline(always)]
pub fn to_i32(self) -> InterpResult<'tcx, i32> {
self.not_undef()?.to_i32()
Expand Down
27 changes: 27 additions & 0 deletions src/librustc_mir/interpret/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,33 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
self.get_raw(ptr.alloc_id)?.read_c_str(self, ptr)
}

/// Reads a 0x0000-terminated u16-sequence from memory. Returns them as a Vec<u16>.
/// Terminator 0x0000 is not included in the returned Vec<u16>.
///
/// Performs appropriate bounds checks.
pub fn read_wide_str(&self, ptr: Scalar<M::PointerTag>) -> InterpResult<'tcx, Vec<u16>> {
let size_2bytes = Size::from_bytes(2);
let align_2bytes = Align::from_bytes(2).unwrap();
// We need to read at least 2 bytes, so we *need* a ptr.
let mut ptr = self.force_ptr(ptr)?;
RalfJung marked this conversation as resolved.
Show resolved Hide resolved
let allocation = self.get_raw(ptr.alloc_id)?;
let mut u16_seq = Vec::new();

loop {
ptr = self
.check_ptr_access(ptr.into(), size_2bytes, align_2bytes)?
.expect("cannot be a ZST");
let single_u16 = allocation.read_scalar(self, ptr, size_2bytes)?.to_u16()?;
if single_u16 != 0x0000 {
u16_seq.push(single_u16);
ptr = ptr.offset(size_2bytes, self)?;
} else {
break;
}
}
Ok(u16_seq)
}

/// Writes the given stream of bytes into memory.
///
/// Performs appropriate bounds checks.
Expand Down