The following code
int _main() {return 0;}
Compiled using the command:
gcc -s -nostdlib -nostartfiles 01-simple.c -o01-simple.exe
gcc version 4.4.1 (TDM-1 mingw32)
OllyDbg produced开发者_C百科 this output:
Can you explain what happens here? Analysis so far:
// these two seems to be an idiom:
PUSH EBP // places EBP on stack
MOV EBP, ESP // overwrites EBP with ESP
MOV EAX, 0 // EAX = 0
LEAVE // == mov esp, ebp
// pop ebp
// according to
// http://en.wikipedia.org/wiki/X86_instruction_listings
What is the meaning of all this?
This creates a stack frame.
PUSH EBP
MOV EBP, ESP
In the calling convention being used, the return value is sent back via EAX
(so the 0
is there because you wrote return 0;
- try changing that to return 1;
and see how that affects the code).
MOV EAX, 0
And this tells the processor to clean up the stack frame (it's the equivalent of MOV ESP, EBP
followed by POP EBP
which is the opposite of what was done when creating the stack frame):
LEAVE
The instructions sets up the stack frame upon the runtime loader entering the int _main()
function,
PUSH EBP MOV EBP, ESP
Stack frame is set up and to access the parameters if any were supplied would be offset from EBP
+ the size of the parameter (WORD, BYTE, LONG, etc).
Usually the EAX
register is the normal register to return an exit status from the runtime environment to the operating system loader,
MOV EAX, 0 LEAVE
in other words, to say the program has exited successfully returning a 0 to the Operating system.
Where a return is used, the stack frame is restored upon runtime execution prior to handing control back to the Operating system.
POP EBP
The general consensus is, if an error has occurred, the value would be non-zero, and can be used both from batch files (harking back to the old DOS days) and unix scripts where it checks if the program ran successfully or not and proceed onwards depending on the nature of the batch file or script.
The 'MOV EAX,0' instruction is the body of your function. The header code is for setting up space for your code to run in.
The 'LEAVE' instruction returns your code to where it came. Even though you said no standard libraries, there is plenty of other code in there that the linker puts into place.
精彩评论