gdb列印結構體memberoffset

stormbm發表於2018-01-24

linux的crash有個好處就是可以方便列印結構體成員變數的offset, 有時候對彙編的時候, 需要偏移, 可惜crash需要一個活體才行, 不能單純的vmlinux, 因為它就是這麼設計的

gdb天生沒有這個功能, 不過python可以實現

cat offset.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(`struct %s` % argv[0])

    print argv[0], `{`
    for field in stype.fields():
        print `    [0x%x] %s` % (field.bitpos//8, field.name)
    print `}`

Offsets()

gdb vmlinux -x ~/offset.py
(gdb) offsets-of task_struct
task_struct {

[0x0] thread_info
[0x8] state
[0x10] stack
[0x18] usage
[0x1c] flags
[0x20] ptrace
[0x28] wake_entry
[0x30] on_cpu
[0x34] cpu
[0x38] wakee_flips
[0x40] wakee_flip_decay_ts

其實還是挺方便的, 省得用0指標來轉

從這裡來
https://stackoverflow.com/questions/9788679/how-to-get-the-relative-address-of-a-field-in-a-structure-dump-c


相關文章