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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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)
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...)
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.)
really appreciate the timely answer from @teapot418 and further elaboration from everyone else!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.