Skip to content

Commit 334c7ec

Browse files
authored
program-entrypoint: Add a BumpAllocator constructor (#284)
* program-entrypoint: Add a BumpAllocator constructor #### Problem The current version of program-entrypoint doesn't work because the allocator can't be instantiated in the macros. The start and len fields are private, and so can't be written to in the macro, which exists in the scope of the program. #### Summary of changes Add a new constructor that can be used by the macro. * Make function const, call from unsafe block * Rename
1 parent d47ab5a commit 334c7ec

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

program-entrypoint/src/lib.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,9 +221,11 @@ macro_rules! custom_heap_default {
221221
() => {
222222
#[cfg(all(not(feature = "custom-heap"), target_os = "solana"))]
223223
#[global_allocator]
224-
static A: $crate::BumpAllocator = $crate::BumpAllocator {
225-
start: $crate::HEAP_START_ADDRESS as usize,
226-
len: $crate::HEAP_LENGTH,
224+
static A: $crate::BumpAllocator = unsafe {
225+
$crate::BumpAllocator::with_fixed_address_range(
226+
$crate::HEAP_START_ADDRESS as usize,
227+
$crate::HEAP_LENGTH,
228+
)
227229
};
228230
};
229231
}
@@ -333,6 +335,19 @@ impl BumpAllocator {
333335
len: arena.len(),
334336
}
335337
}
338+
339+
/// Creates the allocator tied to specific range of addresses.
340+
///
341+
/// # Safety
342+
/// This is unsafe in most situations, unless you are totally sure that the
343+
/// provided start address and length can be written to by the allocator,
344+
/// and that the memory will be usable for the lifespan of the allocator.
345+
///
346+
/// For Solana on-chain programs, a certain address range is reserved, so
347+
/// the allocator can be given those addresses.
348+
pub const unsafe fn with_fixed_address_range(start: usize, len: usize) -> Self {
349+
Self { start, len }
350+
}
336351
}
337352

338353
/// Integer arithmetic in this global allocator implementation is safe when

0 commit comments

Comments
 (0)