【1000个GDB技巧之】GDB中使用python脚本的方法以及4个注意事项(define、python、end、gdb.execute、to_string=True)

要点

  • 使用define 定义函数
  • 在define中使用python … end包围python使用的代码(python代码也可以不在包围中)
  • 在python中使用gdb命令用gdb.execute,并且需要指定to_strings
  • gdb可以单独写成文件然后source进来

坑:

坑1:python和gdb的end都不值直接注释,需要另起一行
坑2:gdb.execute执行后的输出结果包括$xxx 获取需要做转换
坑3:python代码必须定格严格按照table格式撰写(还有一个方法就是写成纯gdb文件然后import
坑4:gdb.execute代码中必须写to_string才能正确输出到返回值,进一步提供给gdb使用

代码:

# define macro
define csj_pv_vm_numa_stat
        core-file /proc/kcore
        p vm_numa_stat
        p vm_numa_stat[3].counter
end

define csj_pv_jiffies
        core-file /proc/kcore
        p jiffies_64

python
gv_jiffies_64=gdb.execute("p jiffies_64", to_string=True).replace("\n", "").split(" ")[-1]
print(gv_jiffies_64)
print("Current jiffies:\t" + str(gv_jiffies_64))
print("jiffies to sec :\t" + str(int(gv_jiffies_64)/1000) + " s")
#python end
end

p jiffies_64
#csj_pv_jiffies end
end

实战:

【1000个GDB技巧之】GDB中使用python脚本的方法以及4个注意事项(define、python、end、gdb.execute、to_string=True)_第1张图片
执行效果:
【1000个GDB技巧之】GDB中使用python脚本的方法以及4个注意事项(define、python、end、gdb.execute、to_string=True)_第2张图片

另外一种将python脚本写到单独文件调用

  • 单独文件定义函数
  • 在gdb中命令行或者脚本使用source 导入python文件
  • 使用python xxx() 类似python中调用方式调用脚本,注意python执行的时候需要打括号
    举例:
    【1000个GDB技巧之】GDB中使用python脚本的方法以及4个注意事项(define、python、end、gdb.execute、to_string=True)_第3张图片

参考链接

https://sourceware.org/gdb/current/onlinedocs/gdb.html/Python-Commands.html#Python-Commands

你可能感兴趣的:(Linux调试方法,python,调试,gdb)