Get address of a global symbol from symbol name with GDB Python API
Asked Answered
C

2

3

Is there a way by which I can get the address of a global symbol in my binary if I know its name with the GDB Python API ?

Is python print(gdb.parse_and_eval('symbol').address) the correct method t o obtain this value ?

Cliffhanger answered 7/1, 2019 at 7:23 Comment(1)
I guess that there could be a simpler way. I am sadly not familiar enough with Python bindings to gdb internals.Demob
B
1

Well, you answered yourself already correctly. Easy enough to verify:

(gdb) p &t
$2 = (time_t *) 0x562076476018 <t>
(gdb) python print(gdb.parse_and_eval('t').address)
0x562076476018 <t>
(gdb)
Boom answered 12/9, 2019 at 19:34 Comment(0)
W
1

The accepted answer is not entirely correct. It only works when there is no local symbol with the same name in the current scope.

Take this example:

int foo = 0;

int main(int argc, char **argv) {
    int foo = 0;
    return 0;
}

If you break at main(), gdb.parse_and_eval("foo") will find the local variable foo instead of the global symbol.

You can get the global symbol with gdb.lookup_global_symbol("foo").

import gdb

gdb.execute("break main")
gdb.execute("run")

print("Global symbol:")
print(gdb.lookup_global_symbol("foo").value().address)

print("Local symbol:")
print(gdb.parse_and_eval("foo").address)

The result:

Breakpoint 1 at 0x1124: file symbol-tests.c, line 6.

Breakpoint 1, main (argc=1, argv=0x7fffffffdb68) at symbol-tests.c:6
6       int foo = 0;
Global symbol:
0x55555555802c <foo>
Local symbol:
0x7fffffffda6c
Wildee answered 27/1, 2022 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.