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

Runtime Alloc #190

Merged
merged 23 commits into from
Sep 10, 2024
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
6 changes: 3 additions & 3 deletions ceno_emul/src/vm_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ impl VMState {
self.succeeded
}

pub fn tracer(&mut self) -> &mut Tracer {
&mut self.tracer
pub fn tracer(&self) -> &Tracer {
&self.tracer
}

/// Set a word in memory without side-effects.
Expand All @@ -75,7 +75,7 @@ impl VMState {

fn step(&mut self, emu: &Emulator) -> Result<StepRecord> {
emu.step(self)?;
let step = self.tracer().advance();
let step = self.tracer.advance();
if step.is_busy_loop() && !self.succeeded() {
Err(anyhow!("Stuck in loop {}", "{}"))
} else {
Expand Down
2 changes: 1 addition & 1 deletion ceno_emul/tests/data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
```bash
cd ceno_rt
cargo build --release --examples
cp ../target/riscv32im-unknown-none-elf/release/examples/ceno_rt_{mini,panic,mem} ../ceno_emul/tests/data/
cp ../target/riscv32im-unknown-none-elf/release/examples/ceno_rt_{mini,panic,mem,alloc} ../ceno_emul/tests/data/
```
Binary file added ceno_emul/tests/data/ceno_rt_alloc
Binary file not shown.
27 changes: 26 additions & 1 deletion ceno_emul/tests/test_elf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,36 @@ fn test_ceno_rt_mem() -> Result<()> {
let mut state = VMState::new_from_elf(CENO_PLATFORM, program_elf)?;
let _steps = run(&mut state)?;

let value = state.peek_memory(ByteAddr(CENO_PLATFORM.ram_start()).waddr());
let value = state.peek_memory(CENO_PLATFORM.ram_start().into());
assert_eq!(value, 6765, "Expected Fibonacci 20, got {}", value);
Ok(())
}

#[test]
fn test_ceno_rt_alloc() -> Result<()> {
let program_elf = include_bytes!("./data/ceno_rt_alloc");
let mut state = VMState::new_from_elf(CENO_PLATFORM, program_elf)?;
let _steps = run(&mut state)?;

// Search for the RAM action of the test program.
let mut found = (false, false);
for &addr in state.tracer().final_accesses().keys() {
if !CENO_PLATFORM.is_ram(addr.into()) {
continue;
}
let value = state.peek_memory(addr);
if value == 0xf00d {
found.0 = true;
}
if value == 0xbeef {
found.1 = true;
}
}
assert!(found.0);
assert!(found.1);
Ok(())
}

#[test]
fn test_ceno_rt_io() -> Result<()> {
let program_elf = include_bytes!("./data/ceno_rt_io");
Expand Down
30 changes: 30 additions & 0 deletions ceno_rt/examples/ceno_rt_alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#![no_main]
#![no_std]
use core::ptr::{addr_of, read_volatile};

#[allow(unused_imports)]
use ceno_rt;

extern crate alloc;
use alloc::{vec, vec::Vec};

static mut OUTPUT: u32 = 0;

#[no_mangle]
fn main() {
// Test writing to a global variable.
unsafe {
OUTPUT = 0xf00d;
black_box(addr_of!(OUTPUT));
}

// Test writing to the heap.
let mut v: Vec<u32> = vec![];
v.push(0xbeef);
black_box(&v[0]);
}

/// Prevent compiler optimizations.
fn black_box<T>(x: *const T) -> T {
unsafe { read_volatile(x) }
}
51 changes: 51 additions & 0 deletions ceno_rt/src/allocator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//! A bump allocator.
//! Based on https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html

use core::{
alloc::{GlobalAlloc, Layout},
cell::UnsafeCell,
ptr::null_mut,
};

const ARENA_SIZE: usize = 128 * 1024;
const MAX_SUPPORTED_ALIGN: usize = 4096;
#[repr(C, align(4096))] // 4096 == MAX_SUPPORTED_ALIGN
struct SimpleAllocator {
arena: UnsafeCell<[u8; ARENA_SIZE]>,
remaining: UnsafeCell<usize>, // we allocate from the top, counting down
}

#[global_allocator]
static ALLOCATOR: SimpleAllocator = SimpleAllocator {
arena: UnsafeCell::new([0; ARENA_SIZE]),
remaining: UnsafeCell::new(ARENA_SIZE),
};

unsafe impl Sync for SimpleAllocator {}

unsafe impl GlobalAlloc for SimpleAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let size = layout.size();
let align = layout.align();

// `Layout` contract forbids making a `Layout` with align=0, or align not power of 2.
// So we can safely use a mask to ensure alignment without worrying about UB.
let align_mask_to_round_down = !(align - 1);

if align > MAX_SUPPORTED_ALIGN {
return null_mut();
}

let remaining = self.remaining.get();
if size > *remaining {
return null_mut();
}
*remaining -= size;
*remaining &= align_mask_to_round_down;

self.arena.get().cast::<u8>().add(*remaining)
}

/// Never deallocate.
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
}
6 changes: 4 additions & 2 deletions ceno_rt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#![no_std]

use core::arch::{asm, global_asm};

mod allocator;

mod io;
pub use io::info_out;

use core::arch::{asm, global_asm};

mod params;
pub use params::*;

Expand Down
Loading