type
status
date
slug
summary
tags
category
icon
password
Naked Function
A naked function in C and C++ is a function that is declared without a prolog or epilog code. This means that the programmer is responsible for managing the function's stack frame, entry, and exit code. Naked functions are generally used in low-level programming or when working with assembly language code, allowing the programmer to have full control over the function's behavior.
While GCC and Clang use the
__attribute__((naked))
attribute for declaring naked functions, Microsoft-specific storage-class specifier __declspec(naked)
can be used for the same purpose in Visual Studio. Here is an example using __declrspec(naked)
:Note that if we do not use the
__asm
keyword to manually insert the prolog or epilog code into the assembly, the C++ compiler will not do this for us since the function is defined as a naked function, and any call to this function will end up with runtime errors.calling convention
Calling conventions define how functions are called and how arguments are passed between functions in a programming language. They specify the order in which arguments are pushed onto the stack, how the return value is retrieved, and how the stack is cleaned up after the function call. In C and C++, there are several calling conventions, some of which are platform and compiler specific. Here are some common calling conventions:
calling convention | how function parameters are passed / pushed into stack frame | who cleans up the stack | comment |
__cdecl | from right to left | function caller | default in C/C++ |
__stdcall | from right to left | callee (function itself) | default in Windows APIs |
__fastcall | The first two arguments are passed in CPU registers (typically ECX and EDX), and the rest are passed on the stack (right → left) | callee (function itself) | more efficient when parameter list is short (≤2) |
__thiscall | this pointer of the object is passed in CPU register ECX; Other parameters are passed into stack frame from right to left. | callee (function itself) | C++ non-static member functions only |
Here we give an example for each calling conventions, together with their generated assembly code:
__cdecl
Now let’s take a look at the generated assembly code:
__stdcall
the generated assembly code:
__fastcall
the generated assembly code:
- 作者:Zack Yang
- 链接:https://zackyang.blog/article/x86-naked-function-and-calling-conventions
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章
C++ Virtual Table Implementation Details
Injecting a DLL into a Windows Executable By Modifying PE Import Table
IAT Table
Injecting a Simple Message Box at the Startup of a Windows Application
How C/C++ Compiler Generate Assembly Code For Switch Statement
How C/C++ Compiler Generate x86 Assembly Code For Large Return Values