Skip to content

2.66 有调试符号的情况下在GDB中获取结构成员的偏移

https://scz.617.cn/unix/201203201430.txt

A: FatalError@stackoverflow 2012-03-20

How to get the relative address of a field in a structure dump - [2012-03-20] https://stackoverflow.com/questions/9788679/how-to-get-the-relative-address-of-a-field-in-a-structure-dump-c

p/x &((struct some *)0)->member

从GDB 8.1开始可以用

ptype /o struct some

如果GDB支持Python,另有解决方案。

$ vi GetOffset.py


import gdb

class Offset ( gdb.Command ) :

def __init__ (self ) :
    super( Offset, self ).__init__ ( 'offsetof', gdb.COMMAND_DATA )

def invoke ( self, arg, from_tty ) :
    arg     = arg.strip()
    stype   = gdb.lookup_type( arg )
    # print( arg, '{' )
    print( "%s %s" % ( arg, '{' ) )
    for field in stype.fields() :
        print( '    %s => %#x' % ( field.name, field.bitpos // 8 ) )
    print( '}' )

Offset()

(gdb) source /tmp/GetOffset.py (gdb) offsetof struct _zend_persistent_script struct _zend_persistent_script { script => 0x0 compiler_halt_offset => 0x148 ping_auto_globals_mask => 0x150 timestamp => 0x158 corrupted => 0x160 is_phar => 0x161 mem => 0x168 size => 0x170 arena_mem => 0x178 arena_size => 0x180 dynamic_members => 0x188 }

在GDB中获取结构成员偏移有现实意义,考虑结构优化对齐对成员偏移的影响。