Ameya Savale
Ameya Savale

Reputation: 441

x86 simple function not working

Hi guys I am trying to build the following function

function int Main(){
 return 5;
}

this is my assembly code:

 .globl Main
Main:
pushl %ebp
movl %esp, %ebp
subl $0, %esp
pushl $5
movl %ebp, %esp
popl %ebp
ret

However this always returns 1 it never returns 5 why?

Upvotes: 1

Views: 174

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61388

Summarizing what everyone said: your primary error is that the return value should go into EAX and it does not. Prolog and epilog code are not necessary for simple functions like this, but they won't hurt either (as long as they don't unbalance the stack). So the assembly should go:

(prolog)
movl $5, %eax,
(epilog)
ret

Where prolog and epilog are whatever your compiler generates by default.

Upvotes: 0

Martin
Martin

Reputation: 6697

How about just:

Main:
push byte 5
pop eax
ret

Upvotes: 3

Related Questions