views:

237

answers:

2

From:

http://en.wikipedia.org/wiki/X86%5Fcalling%5Fconventions

push c
push b
push a
call function_name
add esp, 12 ;Stack clearing
mov x, eax

Why do we need to explicitly add 12 to ESP to clear the stack since the called function should have poped the parameters off the stack therefore restoring the stack pointer...?

Another question:

Theoretically, it would be possible to implement variable parameter functions with the callee taking care of the cleanup right (for instance if you pass the number of arguments on the stack in a register)?

+10  A: 

Because, with the C calling convention, the called function will not pop the parameters. That's the point of this calling convention.

It allows things like variable arguments.

sbi
Exactly. With C functions, the caller can push as many arguments on the stack as it likes before calling a function. The called function simply doesn't know how many should be cleaned up.
Andy Ross
how does the callee know how many parameters it was called with so that it can safely access them? In the case of printf() it can parse the format string but otherwise how does it do it?
anon
http://en.wikipedia.org/wiki/Stdarg.h
Kevin Panko
@anon: There's no standard way. The other common trick other than printf-style format strings is to pull a NULL at the end of a list. c.f. execl(), Gtk constructor functions, etc...
Andy Ross
anon: It doesn't know. It has to trust it was called with (at least) the number of arguments specified in its declaration.
sbi
+3  A: 

It was right there on the wikipedia page above the _cdecl header

In these conventions the caller cleans the arguments from the stack, which allows for variable argument lists, eg. printf().

sylvanaar