user12050586
user12050586

Reputation:

Seeing data stored on the stack

I have the following src:

 1  #include<stdio.h>
 2  
 3  int main(void) {
 4      int i= 1337; // breakpoint after this value is assigned
!5      return 0;
 6  }

In the asm from gdb I get:

!0x00000000004004f1  main+4  movl   $0x539,-0x4(%rbp)

And I verified that $0x539 = 1337. How can I see the memory address where the value 1337 is stored? The value of the rbp memory address shows:

rbp 0x00007fffffffeb20

My thought was the rbp register would show the value 0x539, so where would I be able to find that in gdb (what command to use, etc)?

One interesting things I found was in doing:

>>> print i
$16 = 1337
>>> print &i
$17 = (int *) 0x7fffffffeb1c # how is this arrived at?

Upvotes: 0

Views: 74

Answers (1)

robthebloke
robthebloke

Reputation: 9682

0x00007fffffffeb20 - 0x4 == 0x7fffffffeb1c

on x86 almost all constants will be addressed as a relative offset from a register. In this case the register is rbp [the frame address], and the relative offset is -4 bytes. i.e. the constant appears prior to the first instruction in main.

x64 addressing modes typically involve one of 3 possibilities:

  • a zero byte offset from a register address
  • a signed 8bit offset from a register address
  • a signed 32bit offset from a register address

(there is a 4th addressing mode, which is to load the value from a register - just for completeness!). In general, a compiler would prefer to emit those modes in the order I have listed them above (because they result in the Op code + an offset which will be either: 0bytes, 1byte, or 4bytes respectively - so the smaller the offset, the smaller the generated machine code will be).

Upvotes: 1

Related Questions