In the CDECL calling convention, can I reuse the arguments I pushed onto the stack?
Asked Answered
Y

1

7

In the GCC cdecl calling convention, can I rely on the arguments I pushed onto the stack to be the same after the call has returned? Even when mixing ASM and C and with optimization (-O2) enabled?

Ynez answered 9/8, 2016 at 6:53 Comment(2)
It's perfectly fine for a C-function to modify its non-const arguments, so no.Guberniya
@Michael: The ABI doesn't say anything about const args. It's a source-level compile-time thing, not part of the ABI. This is somewhat unfortunate, since compilers hardly ever seem to take advantage of arg-passing slots as scratch space, but always assume that the data is clobbered.Lemures
G
7

In a word: No.

Consider this code:

__cdecl int foo(int a, int b)
{
   a = 5;
   b = 6;
   return a + b;
}

int main()
{
   return foo(1, 2);
}

This produced this asm output (compiled with -O0):

movl    $5, 8(%ebp)
movl    $6, 12(%ebp)
movl    8(%ebp), %edx
movl    12(%ebp), %eax
addl    %edx, %eax
popl    %ebp
ret

So it is quite possible for a __cdecl function to stomp on the stack values.

That's not even counting the possibility of inlining or other optimization magic where things may not end up on the stack in the first place.

Guarneri answered 9/8, 2016 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.