0

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

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Kenneth Cox
  • 84
  • 1
  • 6

1 Answers1

3

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.

teapot418
  • 1,239
  • 1
  • 3
  • 9
  • 1
    If the `add esp, 4` were to be replaced by `pop eax`, precaution would be in order so as to move the `mov [ebp+var_4], eax` instruction one line up (before the `pop eax`) – Sep Roland Jun 04 '23 at 21:01
  • 1
    yeah, eax is probably a bad example, because C typically uses it for return value, so imagine some other register (and then the value you don't actually care about would clobber that register...) – teapot418 Jun 04 '23 at 21:10
  • 1
    For the record, other calling conventions exist, like MSVC's stdcall and fastcall, which are "callee pops"; the `checkResults` function would use `ret 4` instead of `ret` to clear the args as it returned. But "caller pops" conventions are also widespread (e.g. i386 System V, and cdecl on Windows, and all mainstream x86-64 calling conventions.) – Peter Cordes Jun 04 '23 at 21:56
  • really appreciate the timely answer from @teapot418 and further elaboration from everyone else! – Kenneth Cox Jun 05 '23 at 11:38