assemblyx86calling-conventionstack-pointer

Stack pointer add on loop


Learning some reverse engineering and I came across some examples of loops in x86 assembly

00401036        mov     [ebp+var_4], 0
0040103D        mov     [ebp+var_8], 0
00401044 loc_401044:
00401044        cmp     [ebp+var_4], 0
00401048        jnz     short loc_401063 
0040104A        call    performAction
0040104F        mov     [ebp+var_8], eax
00401052        mov     eax, [ebp+var_8]
00401055        push    eax
00401056        call    checkResult
0040105B        add     esp, 4
0040105E        mov     [ebp+var_4], eax
00401061        jmp     short loc_401044

From my understanding, esp is the stack pointer so: Why is 4 being added to the stack? It would make sense if this was a recursive call but it’s just a loop


Solution

  • This is likely using C calling convention, which is "caller cleans up". This convention allows for variable-argument functions like printf where the callee does not know how many arguments are on the stack.

    The whole bit you should look at is:

    00401055        push    eax // argument for checkResult
    00401056        call    checkResult
    0040105B        add     esp, 4 // clean up the argument
    

    the add could have been a pop eax, except the code is not interested in the value, so it just moves the stack pointer.