Hind Forsum Hind Forsum - 2 months ago 8
Linux Question

C program stores function parameters from $rbp+4 in memory? My check failed

I was trying to learn how to use rbp/ebp to visit function parameters and local variables on ubuntu1604, 64bit. I've got a simply c file:

#include<stdio.h>
int main(int argc,char*argv[])
{
printf("hello\n");
return argc;
}


I compiled it with:


gcc -g my.c


Then debug it with argument parameters:


gdb --args my 01 02


Here I know the "argc" should be 3, so I tried to check:

(gdb) b main
Breakpoint 1 at 0x400535: file ret.c, line 5.
(gdb) r
Starting program: /home/a/cpp/my 01 02

Breakpoint 1, main (argc=3, argv=0x7fffffffde98) at ret.c:5
5 printf("hello\n");
(gdb) x $rbp+4
0x7fffffffddb4: 0x00000000
(gdb) x $rbp+8
0x7fffffffddb8: 0xf7a2e830
(gdb) x/1xw $rbp+8
0x7fffffffddb8: 0xf7a2e830
(gdb) x/1xw $rbp+4
0x7fffffffddb4: 0x00000000
(gdb) x/1xw $rbp
0x7fffffffddb0: 0x00400550


I don't find any clue that a dword of "3" is saved in any of bytes in $rbp+xBytes. Did I get anything wrong in my understanding or commands?

Thanks!

Answer

I was trying to learn how to use rbp/ebp to visit function parameters and local variables

The x86_64 ABI does not use stack to pass parameters; they are passed in registers. Because of that, you wouldn't find them at any offset off $rbp (this is different from ix86 calling convention).

To find the parameters, you'll need to look at the $rdi and $rsi regusters:

Breakpoint 1, main (argc=3, argv=0x7fffffffe3a8) at my.c:4
4     printf("hello\n");

(gdb) p/x $rdi
$1 = 0x3                   # matches argc
(gdb) p/x $rsi
$2 = 0x7fffffffe3a8        # matches argv

x $rbp+4

You almost certainly wouldn't find anything useful at $rbp+4, because it is usually incremented or decremented by 8, in order to store the entire 64-bit value.