Tools for inspecting stack usage

Hello, Rust, especially async, is quite hungry to the stack usage. With gdb I can extract size of the whole frame, but still I'm getting surprised and struggle to understand why that amount of stack is used.

Is there any tool to give me information on what precisely is inside the stack frame? Ideally I would like to extract that information for every function (modulo inlines) from the binary, but using gdb would be fine too.

I'm aware that gdb is able to print local variables, but at least in my hands I don't find it useful.

Additionally, can I look inside the futures somehow?

I don't have any tips for inspecting actual stack usage (if anyone else does, I'd like to hear them too!), but since you mention async code, something I've learned:

async blocks and async fns can sometimes produce very large Future types. These Futures don't themselves live on the stack when actually in use, but they may be on the stack temporarily when constructed. You can discover how big your async block/fn Futures are by running

cargo +nightly rustc -- -Zprint-type-sizes

which will dump the size and layout of every type in your program, including async block future types. There will likely be opportunities to reduce their size by adding blocks (or moving code into non-async functions) to reduce the number of local variables that cross await points.

There's a clippy lint for large future sizes.

Change f().await to Box::pin(f()).await where you're getting large futures, or just sprinkle that all over less-hot paths.

In my situation (embedded) I would rather give more bytes to the stack rather than heap, so this is not a suitable solution for me.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.