You can do this with gdb
. As an example, I will use this source:
struct A { int a; char b; short c; }; int main() { struct A a; }
Uploading a binary file to gdb
:
(gdb) print (int)&((struct A*)0)->a $1 = 0 (gdb) print (int)&((struct A*)0)->b $2 = 4 (gdb) print (int)&((struct A*)0)->c $3 = 6
UPDATE:
If you need to do this for a large number of fields, you may find it convenient to use the new python GDB interface (to use it you will need the latest version of GDB, I use 7.4). I created offsets.py:
import gdb class Offsets(gdb.Command): def __init__(self): super (Offsets, self).__init__ ('offsets-of', gdb.COMMAND_DATA) def invoke(self, arg, from_tty): argv = gdb.string_to_argv(arg) if len(argv) != 1: raise gdb.GdbError('offsets-of takes exactly 1 argument.') stype = gdb.lookup_type(argv[0]) print argv[0], '{' for field in stype.fields(): print ' %s => %d' % (field.name, field.bitpos//8) print '}' Offsets()
Then you can add to your .gdbinit:
python sys.path.insert(0, '/path/to/script/dir') import offsets end
Then using it in GDB, for example:
(gdb) offsets-of "struct A" struct A { a => 0 b => 4 c => 6 }
This script makes some simplifying assumptions, for example, that you do not use bit fields and it does not delve into nested structures, but these changes3 are pretty simple if you need them.
source share