example-greenthreads icon indicating copy to clipboard operation
example-greenthreads copied to clipboard

Consoder improving naked function explanation

Open cfsamson opened this issue 3 years ago • 0 comments

While it will get very detailed pretty quickly I found this explanation of naked functions to be a pretty good starting point if I were to add additional details in the subject:

Because naked functions aren't functions.

You don't "enter" a naked function. When you enter a function you save registers, push a return address to stack, align the stack, and tidy things up for the next function.

With naked functions none of this happens. The stack pointer isn't saved, registers aren't perserved, etc. If you blindly ret from a naked function (without writing a proper ABI specific prolog and epilog yourself), you get into undefined behavior territory. Likely ending up in the caller's caller with horribly wrong values in the registers.

Naked functions are just assembly GOTO labels that C (C++ and Rust by legacy compatibility) can play nicely with. They're useful when you need to do low level hardware stuff like "modify program state" in essoteric ways, or speak directly to hardware in a manner that makes no sense to C/C++/Rust.

If you want to return from a naked function you need to write the function's epilog & prolog yourself (in assembly (and compatible with the caller's ABI)), as well as include the ret instruction yourself to properly return.

From reddit user https://www.reddit.com/u/valarauca14/?utm_source=share&utm_medium=ios_app&utm_name=iossmf in https://www.reddit.com/r/rust/comments/kwn43k/why_must_naked_functions_not_return/gj59yqn/?utm_source=share&utm_medium=ios_app&utm_name=iossmf&context=3

cfsamson avatar Jan 13 '21 21:01 cfsamson