Add memory allocation support for C programs (#12254)
This commit is contained in:
57
programs/bpf/c/src/alloc/alloc.c
Normal file
57
programs/bpf/c/src/alloc/alloc.c
Normal file
@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @brief Example C-based BPF sanity rogram that prints out the parameters
|
||||
* passed to it
|
||||
*/
|
||||
#include <solana_sdk.h>
|
||||
|
||||
extern uint64_t entrypoint(const uint8_t *input) {
|
||||
{
|
||||
// Confirm large allocation fails
|
||||
void *ptr = sol_calloc(1, UINT64_MAX); // TODO use max
|
||||
if (ptr != NULL) {
|
||||
sol_log("Error: Alloc of very larger buffer should fail");
|
||||
sol_panic();
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// Confirm large allocation fails
|
||||
void *ptr = sol_calloc(18446744073709551615U, 1); // TODO use max
|
||||
if (ptr != NULL) {
|
||||
sol_log("Error: Alloc of very larger buffer should fail");
|
||||
sol_panic();
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// Test modest allocation and de-allocation
|
||||
void *ptr = sol_calloc(1, 100);
|
||||
if (ptr == NULL) {
|
||||
sol_log("Error: Alloc of 100 bytes failed");
|
||||
sol_panic();
|
||||
}
|
||||
sol_free(ptr);
|
||||
}
|
||||
|
||||
{
|
||||
// Test allocated memory read and write
|
||||
|
||||
const uint64_t iters = 100;
|
||||
uint8_t *ptr = sol_calloc(1, iters);
|
||||
if (ptr == NULL) {
|
||||
sol_log("Error: Alloc failed");
|
||||
sol_panic();
|
||||
}
|
||||
for (int i = 0; i < iters; i++) {
|
||||
*(ptr + i) = i;
|
||||
}
|
||||
for (int i = 0; i < iters; i++) {
|
||||
sol_assert(*(ptr + i) == i);
|
||||
}
|
||||
sol_log_64(0x3, 0, 0, 0, *(ptr + 42));
|
||||
sol_assert(*(ptr + 42) == 42);
|
||||
sol_free(ptr);
|
||||
}
|
||||
|
||||
return SUCCESS;
|
||||
}
|
@ -35,7 +35,7 @@ pub extern "C" fn entrypoint(_input: *mut u8) -> u64 {
|
||||
// Test allocated memory read and write
|
||||
|
||||
const ITERS: usize = 100;
|
||||
let layout = Layout::from_size_align(100, mem::align_of::<u8>()).unwrap();
|
||||
let layout = Layout::from_size_align(ITERS, mem::align_of::<u8>()).unwrap();
|
||||
let ptr = alloc::alloc::alloc(layout);
|
||||
if ptr.is_null() {
|
||||
info!("Error: Alloc failed");
|
||||
|
@ -107,6 +107,7 @@ fn test_program_bpf_sanity() {
|
||||
#[cfg(feature = "bpf_c")]
|
||||
{
|
||||
programs.extend_from_slice(&[
|
||||
("alloc", true),
|
||||
("bpf_to_bpf", true),
|
||||
("multiple_static", true),
|
||||
("noop", true),
|
||||
|
Reference in New Issue
Block a user