use std::borrow::Cow;
use std::convert::TryFrom;
use std::iter;
use std::ops::{Deref, DerefMut, Range};
use rustc_ast::Mutability;
use rustc_data_structures::sorted_map::SortedMap;
use rustc_target::abi::{Align, HasDataLayout, Size};
use super::{
read_target_uint, write_target_uint, AllocId, InterpResult, Pointer, Scalar, ScalarMaybeUninit,
UninitBytesAccess,
};
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub struct Allocation<Tag = (), Extra = ()> {
bytes: Vec<u8>,
relocations: Relocations<Tag>,
init_mask: InitMask,
pub size: Size,
pub align: Align,
pub mutability: Mutability,
pub extra: Extra,
}
pub trait AllocationExtra<Tag>: std::fmt::Debug + Clone {
#[inline(always)]
fn memory_read(
_alloc: &Allocation<Tag, Self>,
_ptr: Pointer<Tag>,
_size: Size,
) -> InterpResult<'tcx> {
Ok(())
}
#[inline(always)]
fn memory_written(
_alloc: &mut Allocation<Tag, Self>,
_ptr: Pointer<Tag>,
_size: Size,
) -> InterpResult<'tcx> {
Ok(())
}
#[inline(always)]
fn memory_deallocated(
_alloc: &mut Allocation<Tag, Self>,
_ptr: Pointer<Tag>,
_size: Size,
) -> InterpResult<'tcx> {
Ok(())
}
}
impl AllocationExtra<()> for () {}
impl<Tag> Allocation<Tag> {
pub fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, align: Align) -> Self {
let bytes = slice.into().into_owned();
let size = Size::from_bytes(bytes.len());
Self {
bytes,
relocations: Relocations::new(),
init_mask: InitMask::new(size, true),
size,
align,
mutability: Mutability::Not,
extra: (),
}
}
pub fn from_byte_aligned_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>) -> Self {
Allocation::from_bytes(slice, Align::from_bytes(1).unwrap())
}
pub fn uninit(size: Size, align: Align) -> Self {
Allocation {
bytes: vec![0; size.bytes_usize()],
relocations: Relocations::new(),
init_mask: InitMask::new(size, false),
size,
align,
mutability: Mutability::Mut,
extra: (),
}
}
}
impl Allocation<(), ()> {
pub fn with_tags_and_extra<T, E>(
self,
mut tagger: impl FnMut(AllocId) -> T,
extra: E,
) -> Allocation<T, E> {
Allocation {
bytes: self.bytes,
size: self.size,
relocations: Relocations::from_presorted(
self.relocations
.iter()
.map(|&(offset, ((), alloc))| {
let tag = tagger(alloc);
(offset, (tag, alloc))
})
.collect(),
),
init_mask: self.init_mask,
align: self.align,
mutability: self.mutability,
extra,
}
}
}
impl<Tag, Extra> Allocation<Tag, Extra> {
pub fn len(&self) -> usize {
self.size.bytes_usize()
}
pub fn inspect_with_uninit_and_ptr_outside_interpreter(&self, range: Range<usize>) -> &[u8] {
&self.bytes[range]
}
pub fn init_mask(&self) -> &InitMask {
&self.init_mask
}
pub fn relocations(&self) -> &Relocations<Tag> {
&self.relocations
}
}
impl<'tcx, Tag: Copy, Extra: AllocationExtra<Tag>> Allocation<Tag, Extra> {
#[inline]
fn check_bounds(&self, offset: Size, size: Size) -> Range<usize> {
let end = offset + size;
let end = usize::try_from(end.bytes()).expect("access too big for this host architecture");
assert!(
end <= self.len(),
"Out-of-bounds access at offset {}, size {} in allocation of size {}",
offset.bytes(),
size.bytes(),
self.len()
);
offset.bytes_usize()..end
}
fn get_bytes_internal(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
check_init_and_ptr: bool,
) -> InterpResult<'tcx, &[u8]> {
let range = self.check_bounds(ptr.offset, size);
if check_init_and_ptr {
self.check_init(ptr, size)?;
self.check_relocations(cx, ptr, size)?;
} else {
self.check_relocation_edges(cx, ptr, size)?;
}
AllocationExtra::memory_read(self, ptr, size)?;
Ok(&self.bytes[range])
}
#[inline]
pub fn get_bytes(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx, &[u8]> {
self.get_bytes_internal(cx, ptr, size, true)
}
#[inline]
pub fn get_bytes_with_uninit_and_ptr(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx, &[u8]> {
self.get_bytes_internal(cx, ptr, size, false)
}
pub fn get_bytes_mut(
&mut self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx, &mut [u8]> {
let range = self.check_bounds(ptr.offset, size);
self.mark_init(ptr, size, true);
self.clear_relocations(cx, ptr, size)?;
AllocationExtra::memory_written(self, ptr, size)?;
Ok(&mut self.bytes[range])
}
}
impl<'tcx, Tag: Copy, Extra: AllocationExtra<Tag>> Allocation<Tag, Extra> {
pub fn read_c_str(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
) -> InterpResult<'tcx, &[u8]> {
let offset = ptr.offset.bytes_usize();
Ok(match self.bytes[offset..].iter().position(|&c| c == 0) {
Some(size) => {
let size_with_null = Size::from_bytes(size) + Size::from_bytes(1);
&self.get_bytes(cx, ptr, size_with_null)?[..size]
}
None => throw_ub!(UnterminatedCString(ptr.erase_tag())),
})
}
pub fn check_bytes(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
allow_uninit_and_ptr: bool,
) -> InterpResult<'tcx> {
self.get_bytes_with_uninit_and_ptr(cx, ptr, size)?;
if !allow_uninit_and_ptr {
self.check_init(ptr, size)?;
self.check_relocations(cx, ptr, size)?;
}
Ok(())
}
pub fn write_bytes(
&mut self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
src: impl IntoIterator<Item = u8>,
) -> InterpResult<'tcx> {
let mut src = src.into_iter();
let (lower, upper) = src.size_hint();
let len = upper.expect("can only write bounded iterators");
assert_eq!(lower, len, "can only write iterators with a precise length");
let bytes = self.get_bytes_mut(cx, ptr, Size::from_bytes(len))?;
for dest in bytes {
*dest = src.next().expect("iterator was shorter than it said it would be");
}
src.next().expect_none("iterator was longer than it said it would be");
Ok(())
}
pub fn read_scalar(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
let bytes = self.get_bytes_with_uninit_and_ptr(cx, ptr, size)?;
if self.is_init(ptr, size).is_err() {
return Ok(ScalarMaybeUninit::Uninit);
}
let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap();
if size != cx.data_layout().pointer_size {
self.check_relocations(cx, ptr, size)?;
} else {
if let Some(&(tag, alloc_id)) = self.relocations.get(&ptr.offset) {
let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits), tag);
return Ok(ScalarMaybeUninit::Scalar(ptr.into()));
}
}
Ok(ScalarMaybeUninit::Scalar(Scalar::from_uint(bits, size)))
}
pub fn read_ptr_sized(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
self.read_scalar(cx, ptr, cx.data_layout().pointer_size)
}
pub fn write_scalar(
&mut self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
val: ScalarMaybeUninit<Tag>,
type_size: Size,
) -> InterpResult<'tcx> {
let val = match val {
ScalarMaybeUninit::Scalar(scalar) => scalar,
ScalarMaybeUninit::Uninit => {
self.mark_init(ptr, type_size, false);
return Ok(());
}
};
let bytes = match val.to_bits_or_ptr(type_size, cx) {
Err(val) => u128::from(val.offset.bytes()),
Ok(data) => data,
};
let endian = cx.data_layout().endian;
let dst = self.get_bytes_mut(cx, ptr, type_size)?;
write_target_uint(endian, dst, bytes).unwrap();
if let Scalar::Ptr(val) = val {
self.relocations.insert(ptr.offset, (val.tag, val.alloc_id));
}
Ok(())
}
pub fn write_ptr_sized(
&mut self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
val: ScalarMaybeUninit<Tag>,
) -> InterpResult<'tcx> {
let ptr_size = cx.data_layout().pointer_size;
self.write_scalar(cx, ptr, val, ptr_size)
}
}
impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
pub fn get_relocations(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> &[(Size, (Tag, AllocId))] {
let start = ptr.offset.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1);
let end = ptr.offset + size;
self.relocations.range(Size::from_bytes(start)..end)
}
#[inline(always)]
fn check_relocations(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx> {
if self.get_relocations(cx, ptr, size).is_empty() {
Ok(())
} else {
throw_unsup!(ReadPointerAsBytes)
}
}
fn clear_relocations(
&mut self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx> {
let (first, last) = {
let relocations = self.get_relocations(cx, ptr, size);
if relocations.is_empty() {
return Ok(());
}
(
relocations.first().unwrap().0,
relocations.last().unwrap().0 + cx.data_layout().pointer_size,
)
};
let start = ptr.offset;
let end = start + size;
if first < start {
self.init_mask.set_range(first, start, false);
}
if last > end {
self.init_mask.set_range(end, last, false);
}
self.relocations.remove_range(first..last);
Ok(())
}
#[inline]
fn check_relocation_edges(
&self,
cx: &impl HasDataLayout,
ptr: Pointer<Tag>,
size: Size,
) -> InterpResult<'tcx> {
self.check_relocations(cx, ptr, Size::ZERO)?;
self.check_relocations(cx, ptr.offset(size, cx)?, Size::ZERO)?;
Ok(())
}
}
impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
fn is_init(&self, ptr: Pointer<Tag>, size: Size) -> Result<(), Range<Size>> {
self.init_mask.is_range_initialized(ptr.offset, ptr.offset + size)
}
fn check_init(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
self.is_init(ptr, size).or_else(|idx_range| {
throw_ub!(InvalidUninitBytes(Some(Box::new(UninitBytesAccess {
access_ptr: ptr.erase_tag(),
access_size: size,
uninit_ptr: Pointer::new(ptr.alloc_id, idx_range.start),
uninit_size: idx_range.end - idx_range.start,
}))))
})
}
pub fn mark_init(&mut self, ptr: Pointer<Tag>, size: Size, is_init: bool) {
if size.bytes() == 0 {
return;
}
self.init_mask.set_range(ptr.offset, ptr.offset + size, is_init);
}
}
pub struct InitMaskCompressed {
initial: bool,
ranges: smallvec::SmallVec<[u64; 1]>,
}
impl InitMaskCompressed {
pub fn no_bytes_init(&self) -> bool {
!self.initial && self.ranges.len() == 1
}
}
impl<Tag, Extra> Allocation<Tag, Extra> {
pub fn compress_uninit_range(&self, src: Pointer<Tag>, size: Size) -> InitMaskCompressed {
let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
let initial = self.init_mask.get(src.offset);
let mut cur_len = 1;
let mut cur = initial;
for i in 1..size.bytes() {
if self.init_mask.get(src.offset + Size::from_bytes(i)) == cur {
cur_len += 1;
} else {
ranges.push(cur_len);
cur_len = 1;
cur = !cur;
}
}
ranges.push(cur_len);
InitMaskCompressed { ranges, initial }
}
pub fn mark_compressed_init_range(
&mut self,
defined: &InitMaskCompressed,
dest: Pointer<Tag>,
size: Size,
repeat: u64,
) {
if defined.ranges.len() <= 1 {
self.init_mask.set_range_inbounds(
dest.offset,
dest.offset + size * repeat,
defined.initial,
);
return;
}
for mut j in 0..repeat {
j *= size.bytes();
j += dest.offset.bytes();
let mut cur = defined.initial;
for range in &defined.ranges {
let old_j = j;
j += range;
self.init_mask.set_range_inbounds(
Size::from_bytes(old_j),
Size::from_bytes(j),
cur,
);
cur = !cur;
}
}
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
pub struct Relocations<Tag = (), Id = AllocId>(SortedMap<Size, (Tag, Id)>);
impl<Tag, Id> Relocations<Tag, Id> {
pub fn new() -> Self {
Relocations(SortedMap::new())
}
pub fn from_presorted(r: Vec<(Size, (Tag, Id))>) -> Self {
Relocations(SortedMap::from_presorted_elements(r))
}
}
impl<Tag> Deref for Relocations<Tag> {
type Target = SortedMap<Size, (Tag, AllocId)>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<Tag> DerefMut for Relocations<Tag> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub struct AllocationRelocations<Tag> {
relative_relocations: Vec<(Size, (Tag, AllocId))>,
}
impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
pub fn prepare_relocation_copy(
&self,
cx: &impl HasDataLayout,
src: Pointer<Tag>,
size: Size,
dest: Pointer<Tag>,
length: u64,
) -> AllocationRelocations<Tag> {
let relocations = self.get_relocations(cx, src, size);
if relocations.is_empty() {
return AllocationRelocations { relative_relocations: Vec::new() };
}
let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
for i in 0..length {
new_relocations.extend(relocations.iter().map(|&(offset, reloc)| {
let dest_offset = dest.offset + size * i;
(
(offset + dest_offset) - src.offset,
reloc,
)
}));
}
AllocationRelocations { relative_relocations: new_relocations }
}
pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations<Tag>) {
self.relocations.insert_presorted(relocations.relative_relocations);
}
}
type Block = u64;
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub struct InitMask {
blocks: Vec<Block>,
len: Size,
}
impl InitMask {
pub const BLOCK_SIZE: u64 = 64;
pub fn new(size: Size, state: bool) -> Self {
let mut m = InitMask { blocks: vec![], len: Size::ZERO };
m.grow(size, state);
m
}
#[inline]
pub fn is_range_initialized(&self, start: Size, end: Size) -> Result<(), Range<Size>> {
if end > self.len {
return Err(self.len..end);
}
let idx = (start.bytes()..end.bytes()).map(Size::from_bytes).find(|&i| !self.get(i));
match idx {
Some(idx) => {
let uninit_end = (idx.bytes()..end.bytes())
.map(Size::from_bytes)
.find(|&i| self.get(i))
.unwrap_or(end);
Err(idx..uninit_end)
}
None => Ok(()),
}
}
pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) {
let len = self.len;
if end > len {
self.grow(end - len, new_state);
}
self.set_range_inbounds(start, end, new_state);
}
pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
let (blocka, bita) = bit_index(start);
let (blockb, bitb) = bit_index(end);
if blocka == blockb {
let range = if bitb == 0 {
u64::MAX << bita
} else {
(u64::MAX << bita) & (u64::MAX >> (64 - bitb))
};
if new_state {
self.blocks[blocka] |= range;
} else {
self.blocks[blocka] &= !range;
}
return;
}
if new_state {
self.blocks[blocka] |= u64::MAX << bita;
if bitb != 0 {
self.blocks[blockb] |= u64::MAX >> (64 - bitb);
}
for block in (blocka + 1)..blockb {
self.blocks[block] = u64::MAX;
}
} else {
self.blocks[blocka] &= !(u64::MAX << bita);
if bitb != 0 {
self.blocks[blockb] &= !(u64::MAX >> (64 - bitb));
}
for block in (blocka + 1)..blockb {
self.blocks[block] = 0;
}
}
}
#[inline]
pub fn get(&self, i: Size) -> bool {
let (block, bit) = bit_index(i);
(self.blocks[block] & (1 << bit)) != 0
}
#[inline]
pub fn set(&mut self, i: Size, new_state: bool) {
let (block, bit) = bit_index(i);
self.set_bit(block, bit, new_state);
}
#[inline]
fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) {
if new_state {
self.blocks[block] |= 1 << bit;
} else {
self.blocks[block] &= !(1 << bit);
}
}
pub fn grow(&mut self, amount: Size, new_state: bool) {
if amount.bytes() == 0 {
return;
}
let unused_trailing_bits =
u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes();
if amount.bytes() > unused_trailing_bits {
let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1;
self.blocks.extend(
iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()),
);
}
let start = self.len;
self.len += amount;
self.set_range_inbounds(start, start + amount, new_state);
}
}
#[inline]
fn bit_index(bits: Size) -> (usize, usize) {
let bits = bits.bytes();
let a = bits / InitMask::BLOCK_SIZE;
let b = bits % InitMask::BLOCK_SIZE;
(usize::try_from(a).unwrap(), usize::try_from(b).unwrap())
}