Search code examples
assemblyatt

understanding assembly return to main


I have the following code :

0x401050    <main>:         push   %ebp
0x401051    <main+1>:       mov    %esp,%ebp
0x401053    <main+3>:       sub    $0x8,%esp
0x401056    <main+6>:       and    $0xfffffff0,%esp
0x401059    <main+9>:       mov    $0x0,%eax
0x40105e    <main+14>:      mov    %eax,0xfffffffc(%ebp)
0x401061    <main+17>:      mov    0xfffffffc(%ebp),%eax
0x401064    <main+20>:      call   0x4013a0 <_alloca>
0x401069    <main+25>:      call   0x401430 <__main>
0x40106e    <main+30>:      mov    $0x0,%edx
0x401073    <main+35>:      add    0x8(%ebp),%edx
0x401076    <main+38>:      mov    %edx,%eax
0x401078    <main+40>:      leave  
0x401079    <main+41>:      ret  

I'm trying to understand what value returns from main(register eax). I don't really understand what is the purpose of storing 0 in 0xfffffffc(%ebp) and then back to eax :

0x40105e    <main+14>:      mov    %eax,0xfffffffc(%ebp)
0x401061    <main+17>:      mov    0xfffffffc(%ebp),%eax

and what is going to be in 0x8(%ebp), so what is going to be after adding it to eax

0x401073    <main+35>:      add    0x8(%ebp),%edx

Thanks!


Solution

  • This code has clearly been compiled with optimizations off, which is why you see strange things. The return value is going to be the first argument of main which is argc. The original C code might have looked like:

    int main(int argc, char** argv)
    {
        size_t size = 0;        // local variable at -4(%ebp) = 0xfffffffc(%ebp)
        _alloca(size);
        __main();
        return 0 + argc;        // argc at 8(%ebp)
    }