Search code examples
assemblyx86reverse-engineeringstack-frame

Prematurely resetting the stack pointer? Confusing assembly code


Im trying to make sense of a small bit of assembly.

pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%edx
movl 12(%ebp),%eax
movl %ebp,%esp
movl (%edx),%edx
addl %edx,(%eax)
movl %edx,%eax
popl %ebp
ret

Why is the sp being reset to the base pointer before the rest of the function? Why is the value in %edx being moved back into itself?


Solution

  • A shorter version of this would be:

    mov 4(%esp), %eax
    mov 8(%esp), %edx
    mov (%edx), %edx
    add  %edx, (%eax)
    ret
    

    or, a rough C equiv:

    void add(int *from, int *to) {
      *to += *from;
    }
    

    The compiler likely plays with %ebp go ensure debug-able stack frames; and restoring %esp from %ebp does nothing -- they are the same value.