gemachain_bpf_loader_program/
allocator_bump.rs1use crate::alloc;
2
3use alloc::{Alloc, AllocErr};
4use gemachain_rbpf::aligned_memory::AlignedMemory;
5use std::alloc::Layout;
6
7#[derive(Debug)]
8pub struct BpfAllocator {
9 heap: AlignedMemory,
10 start: u64,
11 len: u64,
12 pos: u64,
13}
14
15impl BpfAllocator {
16 pub fn new(heap: AlignedMemory, virtual_address: u64) -> Self {
17 let len = heap.len() as u64;
18 Self {
19 heap,
20 start: virtual_address,
21 len,
22 pos: 0,
23 }
24 }
25}
26
27impl Alloc for BpfAllocator {
28 fn alloc(&mut self, layout: Layout) -> Result<u64, AllocErr> {
29 let bytes_to_align = (self.pos as *const u8).align_offset(layout.align()) as u64;
30 if self
31 .pos
32 .saturating_add(layout.size() as u64)
33 .saturating_add(bytes_to_align)
34 <= self.len
35 {
36 self.pos += bytes_to_align;
37 let addr = self.start + self.pos;
38 self.pos += layout.size() as u64;
39 Ok(addr)
40 } else {
41 Err(AllocErr)
42 }
43 }
44
45 fn dealloc(&mut self, _addr: u64, _layout: Layout) {
46 }
48}