Arguments and return values
Passing a value on the stack, finding it at [ebp + 8], and returning in eax — the cdecl calling convention.
- Find a function's arguments relative to ebp
- Return a value in eax, as cdecl requires
- Explain who removes the arguments afterwards, and what happens if nobody does
To pass an argument, the caller pushes it before the call. 09_pass_and_return_value.asm doubles 21:
_start:
push 21 ; the argument
call times2 ; pushes the return address
mov ebx, eax ; the result becomes the exit status
mov eax, 1
int 0x80
times2:
push ebp
mov ebp, esp
mov eax, [ebp + 8] ; the argument
add eax, eax
mov esp, ebp
pop ebp
ret
and exits with 42.
Why [ebp + 8]
After the prologue, the stack holds three things above ebp, each 4 bytes:
[ebp] is the saved ebp, [ebp + 4] the return address that call pushed, and [ebp + 8] the first argument. A second argument would sit at [ebp + 12]. The layout is fixed by the cdecl calling convention that 32-bit C compilers on Linux follow, which is what lets assembly and C call each other (the next lesson).
Who cleans up
cdecl returns the result in eax and leaves the argument on the stack: the caller must remove it, usually with add esp, 4 right after the call. This program never does — at the end, esp is 4 bytes lower than at the start, as the stepper shows. Here that is harmless, because the next thing the program does is exit. Inside a loop it would not be: every iteration would leave 4 more bytes behind until the stack overflowed.
The comments in the script’s epilogue (esp=ebp=20 address, ebp = 123) follow an imagined example with made-up addresses; the real values depend on where the kernel places the stack, which changes on every run.
Try it yourself. Add add esp, 4 after call times2 and work out, row by row, why esp is now back at its starting value when the program exits. Then write add3(a, b, c) returning their sum: push the three arguments in reverse order, read them at [ebp + 8], [ebp + 12] and [ebp + 16], and clean up with one add esp, 12.