3

I am total newbie to assembly, I learning assembly by compiling c code to assembly.

For this c++ code


int foo() {
    bool x = true;
    return 1;
} 

This is the generated assembly code (intel syntax)

foo():
        push    rbp
        mov     rbp, rsp
        mov     BYTE PTR [rbp-1], 1
        mov     eax, 1
        pop     rbp
        ret

You can check compiler explorer link here

In this instruction

        mov     BYTE PTR [rbp-1], 1

we are storing 1 in stack and its address is [rbp - 1]

  mov    eax, 1
  pop    rbp
  ret

Here we are setting the return value to be 1 and popping stack and storing its value in rbp.

My doubt is how we are storing 1 in address in [rbp - 1] since rsp should always point at top (in this case down) of stack, after this instruction mov BYTE PTR [rbp-1], 1 the top should be [rbp-1] but rsp still be pointing to rbp.

Isnt the correct code should be something like this

   sub rsp, 1
   mov BYTE PTR [rbp - 1], 1

In this way the rsp will always point to the top.

My second doubt is what happens to the value stored in [rbp-1] after ret. Is it somehow gets automatically cleaned up.

fuz
  • 88,405
  • 25
  • 200
  • 352
Nivekithan
  • 953
  • 1
  • 6
  • 10
  • 4
    Because you compiled without optimizations it stored TRUE(1) on the stack and then threw it away. The compiler also took advantage of the fact thar in 64-bit Linux the ABI has the [red zone](https://en.wikipedia.org/wiki/Red_zone_(computing)) (the protected 128 bytes below RSP) which can be used without adjusting RSP. – Michael Petch Jul 23 '21 at 11:08
  • 1
    @MichaelPetch If I were to turn on the optimization then compiler just ignores the statement `bool x = true;` since I am not using the variable but I wanted to learn to how it stores `true` in stack thats why I turned off optimization. Thanks for information regarding red zone it cleared my doubts – Nivekithan Jul 23 '21 at 11:15
  • 1
    The use of rsp register in this case is to preserve the base address of the call stack. If there is no function call or any other operation that changes the call stack, there is no need to adjust rsp register. You can try calling a function within foo() to see if rsp is correct or not. – Furkan Çetinkaya Jul 23 '21 at 11:32
  • 2
    Use `volatile bool x = true;` if you want to look at it with optimization enabled, or pass `&x` to a function. [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116). Or use an inline asm statement to force the compiler to materialize it somehow. (maybe `Benchmark::DoNotOptimize`) – Peter Cordes Jul 23 '21 at 18:02

0 Answers0