corevm_memory_test/
lib.rs

1#![cfg_attr(any(target_arch = "riscv32", target_arch = "riscv64"), no_std)]
2
3extern crate alloc;
4
5use alloc::alloc::{GlobalAlloc, Layout};
6use corevm_guest::{free, println};
7use corevm_memory_test_common::{generate_pages, page_checksum, NUM_PAGES};
8use rand::{rngs::SmallRng, Rng, SeedableRng};
9
10// This program pre-allocates more memory pages than can be exported from a work package, and then
11// touches random pages until either the gas runs out or the max. no. of exported segments is
12// reached.
13// The purpose is to test how CoreVM handles programs that use more than `MAX_PAGES` memory pages.
14#[polkavm_derive::polkavm_export]
15pub extern "C" fn main() -> u64 {
16	let mut rng = SmallRng::seed_from_u64(0);
17	let pages = generate_pages(&mut rng);
18	// Touch random pages until we ran out of exported pages.
19	// Compute checksums and append them to the program output.
20	for _ in 0..NUM_PAGES {
21		let j = rng.random_range(0..NUM_PAGES);
22		let (data, expected_checksum) = &pages[j];
23		let actual_checksum = page_checksum(data);
24		println!("{} {} {} {}", j, data.as_ptr() as u64, expected_checksum, actual_checksum);
25	}
26	0
27}
28
29#[cfg_attr(any(target_arch = "riscv32", target_arch = "riscv64"), global_allocator)]
30#[cfg_attr(not(any(target_arch = "riscv32", target_arch = "riscv64")), allow(unused))]
31static ALLOCATOR: NaiveAlloc = NaiveAlloc;
32
33/// The allocator that allocates and frees memory using CoreVM-specific `alloc` and `free`
34/// host-calls.
35///
36/// Each allocation is rounded up to the multiple of the page size.
37pub struct NaiveAlloc;
38
39unsafe impl GlobalAlloc for NaiveAlloc {
40	#[inline]
41	unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
42		let size = layout.size() as u64;
43		corevm_guest::alloc(size)
44	}
45
46	#[inline]
47	unsafe fn dealloc(&self, address: *mut u8, layout: Layout) {
48		let size = layout.size() as u64;
49		free(address, size)
50	}
51}
52
53#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
54#[panic_handler]
55fn panic(info: &core::panic::PanicInfo) -> ! {
56	corevm_guest::panic(info)
57}