How do I get the integer argument in calllee?

I have the following code (caller.c):

#include <stdio.h>

extern int callee(int);

int main(int argc, char *argv[]){
  callee(4);
  return 1;
}

      

and (callee.s):

.globl callee

callee:
  pop %eax
  add $4, %eax
  ret

      

I am compiling with: gcc -m32 caller.c callee.s

and run:

./a.out

Segmentation fault (core dump)

I am wondering what my error (s) are as I figured that the main one should now push 32 bites the stack number. I didn't use the modified stack so that the caller can now pop this number from the same stack. Maybe I should add (add $ 4,% esp) before the pop (if the callee's address is in "mode" / actually popped out). I've tried this too with no success. the callee should now get the number from the stack and add 4 to it. The eax register should be where the return value from the callee should be stored (calling convention), but here I am ignoring the return value.

Can anyone help me?

related question:   calling build function from c

call: https://en.wikipedia.org/wiki/X86_calling_conventions

+3


source to share


1 answer


(Using the x86-32 calling convention) the function arguments are pushed onto the stack first, followed by the return address. So your team pop

pulled the return address and the subsequent one ret

tried to go back to address 0x00000004, which is untagged memory, causing a crash.

Also, in this convention, the callee must not expose its arguments. The call will do it.

The code you had to write is

callee:
    movl 4(%esp), %eax
    addl $4, %eax
    ret

      



You can confirm this yourself by compiling

unsigned int callee(unsigned int x) { return x + 4; }

      

with parameters -m32 -O2 -S -fomit-frame-pointer

and verification of the created file .s

; you should get the same assembly code as above.

+4


source







All Articles