2022-03-02 14:50:16 -08:00
|
|
|
#![allow(clippy::integer_arithmetic)]
|
|
|
|
|
2021-12-03 09:00:31 -08:00
|
|
|
use {
|
|
|
|
crate::alloc,
|
|
|
|
alloc::{Alloc, AllocErr},
|
|
|
|
solana_rbpf::aligned_memory::AlignedMemory,
|
|
|
|
std::alloc::Layout,
|
|
|
|
};
|
2019-05-24 16:21:42 -07:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
2021-02-18 23:42:09 -08:00
|
|
|
pub struct BpfAllocator {
|
2021-10-05 22:24:48 -07:00
|
|
|
#[allow(dead_code)]
|
2021-04-20 11:07:30 -07:00
|
|
|
heap: AlignedMemory,
|
2019-08-23 11:03:53 -07:00
|
|
|
start: u64,
|
|
|
|
len: u64,
|
|
|
|
pos: u64,
|
2019-05-24 16:21:42 -07:00
|
|
|
}
|
|
|
|
|
2021-02-18 23:42:09 -08:00
|
|
|
impl BpfAllocator {
|
2021-04-20 11:07:30 -07:00
|
|
|
pub fn new(heap: AlignedMemory, virtual_address: u64) -> Self {
|
2019-08-23 11:03:53 -07:00
|
|
|
let len = heap.len() as u64;
|
|
|
|
Self {
|
|
|
|
heap,
|
|
|
|
start: virtual_address,
|
|
|
|
len,
|
|
|
|
pos: 0,
|
|
|
|
}
|
2019-05-24 16:21:42 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-18 23:42:09 -08:00
|
|
|
impl Alloc for BpfAllocator {
|
2019-08-23 11:03:53 -07:00
|
|
|
fn alloc(&mut self, layout: Layout) -> Result<u64, AllocErr> {
|
2020-08-17 09:49:21 -07:00
|
|
|
let bytes_to_align = (self.pos as *const u8).align_offset(layout.align()) as u64;
|
|
|
|
if self
|
|
|
|
.pos
|
|
|
|
.saturating_add(layout.size() as u64)
|
|
|
|
.saturating_add(bytes_to_align)
|
|
|
|
<= self.len
|
|
|
|
{
|
|
|
|
self.pos += bytes_to_align;
|
2019-08-23 11:03:53 -07:00
|
|
|
let addr = self.start + self.pos;
|
|
|
|
self.pos += layout.size() as u64;
|
|
|
|
Ok(addr)
|
2019-05-24 16:21:42 -07:00
|
|
|
} else {
|
|
|
|
Err(AllocErr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-23 11:03:53 -07:00
|
|
|
fn dealloc(&mut self, _addr: u64, _layout: Layout) {
|
2019-05-24 16:21:42 -07:00
|
|
|
// It's a bump allocator, free not supported
|
|
|
|
}
|
|
|
|
}
|