How to get the relative address of a field in a structure dump. [FROM]

We are working on a C program compiled using arm-eabi-gcc for Linux.

We use a dump of a large structure, and we have problems determining which address we should read the various fields of our structure (for example, 50 of them), (memory alignment and indentation are not so predictable for me).

Is there any way to get the memory mapping of the structure created by our compiler. Option in gdb? Or any tool to help us find the correspondence between the fields and the address in the landfill?

+6
source share
3 answers

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.

+23
source

You can do this with the C program using the standard offsetof() macro defined in stddef.h . However, I'm not sure if this is what you want, since you won’t be able to start it (compiling on the host will most likely return the wrong offsets).

 #include <stdio.h> #include <stddef.h> struct A { int a; char b; short c; }; int main() { printf("Offset of b in A is %zu\n", offsetof(struct A, b)); return 0; } 

However, you can use some hacks to get the offset from the compiled binary without executing it. It is possible to assign a static variable an offset value and find a way to get its value.

+2
source

I think you could write some code like this for required fields

 struct MyStruct S; int Offset_of_X=((long)&(SX))-((long)&S); 

to calculate the offset in bytes in this compilation situation.

This should take into account any alignment problems that the compiler has.

-1
source

Source: https://habr.com/ru/post/911205/


All Articles