0

Compiling a simple C code into assembly using GCC will have the following output:

...
 13         xorl    %eax, %eax
 14         movl    $0, -4(%rbp)
 15         movl    $5, -8(%rbp)
 16         movl    $6, -12(%rbp)
 17         movl    -8(%rbp), %ecx
 18         addl    -12(%rbp), %ecx
 19         movl    %ecx, -16(%rbp)
 20         popq    %rbp
 21         retq

My question is, why an offset to the frame base pointer (rbp) is being used instead of manipulating the stack pointer (rsp). Isn't that the whole point of having a stack pointer?

What if the stack of this process gets overwritten by some other process (Garbage collection as an example) which doesn't even know the stack is being used, since rsp isn't decremented when writing values.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Josh
  • 43
  • 1
  • 4
  • 1
    The stack pointer allows you to manipulate data as you use it. If you want to have variables that persist for an entire scope, that's the point of the stack frame. You make space on the stack (or not if it fits in the red zone, and you don't call anything), and manipulate data relative to the frame pointer. – Thomas Jager Jul 24 '19 at 15:10
  • re: using space below RSP: [Why is there no "sub rsp" instruction in this function prologue and why are function parameters stored at negative rbp offsets?](//stackoverflow.com/q/28693863) And no, garbage-collection doesn't happen on stack memory. Plus, this is C compiler output so code-gen isn't assuming any kind of garbage collection! – Peter Cordes Jul 24 '19 at 15:22
  • IDK, it's not a bad question other than perhaps lack of research effort. I was already looking for appropriate duplicates; there are several. Note that `gcc -O2` implies `-fomit-frame-pointer` which avoids wasting instructions making a stack frame. Use `gcc -O3` (with maybe `-fno-tree-vectorize`) if you want efficient code to read. Wondering why un-optimized / debug-mode code is inefficient doesn't make much sense. – Peter Cordes Jul 24 '19 at 15:22
  • 1
    @ecm: I think you based your edit on the original, overwriting my tag edit. The appropriate tag for the call stack specifically is `[callstack]`. The `[stack]` tag usage guidelines say this; it's for generic stack data structures. – Peter Cordes Jul 24 '19 at 15:46
  • @Peter Cordes: Thanks, I'll keep that in mind. – ecm Jul 24 '19 at 16:02
  • (Update: `[stack-memory]` is probably a better tag for the asm stack. [callstack] is more about the actual nesting of function calls, not other stuff we do with stack memory.) – Peter Cordes Jul 02 '22 at 06:54

0 Answers0