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;
}
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
retinstruction at the end. Once the control is transferred toasmfunc, 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
asmfuncworks as a label somewhere in the middle of the program code. And when you call your function, you are essentially doing agoto asmfunc, i.e. you transfer control somewhere without any hope of return.For this reason, a minimal naked function should look as
It is your responsibility to place
retinstructions into a naked function.