Search code examples
gccassemblycdecl

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


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?


Solution

  • 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.