views:

123

answers:

3

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 this output:

alt text

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?

+4  A: 

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
R Samuel Klatchko
A: 

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.

samoz
`leave` does not return anything anywhere. `leave` un-setups the current function's stack frame. In order to return a separate `ret` instruction is still necessary.
AndreyT
+1  A: 

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.

tommieb75