2

As the solana docs state, a solana program is constrained with stack and heap limits, on the former a 4kb stack frame limit is ensured per function meaning i can create several functions (with a limited on the total number of functions) to keep getting fresh 4kb stack frames, but for my usecase where i want to improve the stack space usage of constraints in anchor i need a way to measure the stack space usage at compiletime or runtime , say at line 5 i write this measure code which gives me the stack space remaining/used by the code in the above lines. basically looking for a sysvar similar to get the compute usage but for stack space/stack frame.

1 Answer 1

4

The stack space is computed at compile-time based on all the variables used in the current function. The only way to really see the variables is to read through the byte code and figure out what functions are causing the big allocations.

I toyed around with a sample program:

use solana_program::msg;

#[no_mangle]
pub unsafe extern "C" fn entrypoint(_input: *mut u8) -> u64 {
    let a = do_something();
    msg!("{}", a[0]);
    0
}

#[inline(never)]
fn do_something() -> [u8; 3959] {
    [0u8; 3959]
}

If you increase the 3959 to 3960, the entrypoint function will hit the 4096 limit. If you run cargo build-sbf --dump, you'll get the dumped bytecode. In that disassembly file, right at the limit, the entrypoint function will give you:

Disassembly of section .text

0000000000000120 <entrypoint>
      36        bf a6 00 00 00 00 00 00 r6 = r10
      37        07 06 00 00 01 f0 ff ff r6 += -0xfff
      38        bf 61 00 00 00 00 00 00 r1 = r6
      39        85 10 00 00 20 00 00 00 call 0x20 ; <entrypoint::do_something>

Here we're setting the end of the stack frame to exactly 4095 bytes (0xfff) under the stack frame pointer (r10) before calling into our function, just under the limit of 4096, so the compiler is ok with it.

This is a very simple example, but by dumping your program's bytecode, and tracing offsets from r10, you can see how the stack space is being used.

More information at https://solana.com/docs/programs/faq#stack

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.