0

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Dank_Hill
  • 19
  • 2

2 Answers2

4

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.

mevets
  • 10,070
  • 1
  • 21
  • 33
  • Thank you for the quick reply, yeah the intended function is supposed to be basically that. I still don't really understand what this is doing: ```movl (%edx), %edx``` – Dank_Hill Sep 12 '21 at 17:03
  • 1
    *%edx* contains a pointer (*from*), so that de-references the pointer to get the value at its location. compile the "C" version with -S to see what your compiler generates; then play with options like -O4 and see what it can reduce it to. – mevets Sep 12 '21 at 17:39
1

Why is the sp being reset to the base pointer before the rest of the function?

In GNU Assembler syntax, movl %esp,%ebp means that esp is moved to ebp. (GNU asm syntax has always the opposite order of two and more args from Intel asm syntax).

This creates stack frame: local variables and parameters can be referenced relative to %ebp, as in movl 8(%ebp),%edx.

popl %ebp restores the original %ebp, saved by pushl %ebp.


Why is the value in %edx being moved back into itself?

In GNU Assembler syntax, (%edx) is an indirection of the pointer in %edx; note that it is again the source operand.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • VLAs were new in C99. C11 still has them, of course, but we normally say C99 VLAs. – Peter Cordes Sep 16 '21 at 06:36
  • 1
    @PeterCordes, actually removed that partl. `%esp` in this function does not change at all. – Alex Guteniev Sep 16 '21 at 07:42
  • Right, other than via push/pop of course, so the `movl %ebp,%esp` is just a missed optimization (because optimization was presumably not enabled), not necessary for `-fno-omit-frame-pointer`. – Peter Cordes Sep 16 '21 at 07:54