Reputation:
I am trying to learn ASM, and want to try a few things combined with C++. The ASM part is done in a naked function. But whenever I call the function (empty) the application crashes in the next function. What should I do in the naked function to make it work, do I need to pop esp or something? An example could be helpfull.
_declspec(naked) void asmfunc()
{
_asm
{
}
}
int _tmain(int argc, _TCHAR* argv[])
{
i = 1;
asmfunc();
cout << i << endl; // <-- crash
system("pause");
return 0;
}
Upvotes: 7
Views: 7456
Reputation: 513
The naked function in c language programs doesn't contain prologue and epilogue code which prepare a function to do a task. so this is your job to make prologue and epilogue code. in the following code, you see I define prologue and epilogue and you can define your assembly code there.
__declspec(naked) void NakedFunction() {
__asm {
push ebp
mov ebp, esp
}
__asm {
// write your code here
}
__asm {
leave
ret
}
}
int main() {
NakedFunction();
return 0x0;
}
Upvotes: 2
Reputation: 320541
Naked function will not contain any compiler-generated prologue and epilogue code. That applies to the implicit return statement at the end of the function as well.
That means that the function you declared has no ret
instruction at the end. Once the control is transferred to asmfunc
, it never returns. The function continues to execute whatever code exists at that location until it hits something that makes it crash.
Basically, your original implementation of asmfunc
works as a label somewhere in the middle of the program code. And when you call your function, you are essentially doing a goto asmfunc
, i.e. you transfer control somewhere without any hope of return.
For this reason, a minimal naked function should look as
_declspec(naked) void asmfunc()
{
_asm
{
ret
}
}
It is your responsibility to place ret
instructions into a naked function.
Upvotes: 16