gdb---结合python自动化调试
gdb支持通过python自动化调试,实现循环、读写内存、保存内容等复杂逻辑,不需要安装模块。
官方文档: https://sourceware.org/gdb/current/onlinedocs/gdb.html/Python.html
官方文档直接看不太容易理解,可以结合chatgpt、文心一言等工具使用。
简单使用
核心函数:
1 | gdb.execute(command [, from_tty [, to_string]]) |
脚本示例 test.py:
1 2 3 4 5 6 7 | import gdbgdb.execute("break *0x12345678")gdb.execute("continue")# 指定 to_string=True 可以让脚本接收输出并做后续处理,这是能让gdb和脚本交互的重要参数the_line = gdb.execute("info registers eip", to_string=True)gdb.execute("dump memory /root/memory.dump $ebx $ebx+0x100") |
启动gdb,执行如下命令调用脚本:
source ./test.py
或者直接启动时指定脚本
gdb -x test.py
获取寄存器值和内存数据的方法
hello.c
1 2 3 4 5 6 7 | // gcc -o hello hello.c#include <stdio.h>int main(){ printf("Hello World!\n"); return 0;} |
python脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # gdb -x test.pyimport gdbgdb.execute("file hello")gdb.execute("break main")gdb.execute("run")gdb.execute("nexti 2")# 获取当前被调试程序的栈帧frame = gdb.selected_frame()# 获取寄存器'rax'的值rax = frame.read_register("rax")# 打印寄存器的值print("rax的值是: 0x%x" % rax)# 获取当前GDB中的被调试程序(也称为“下级”)inferior = gdb.selected_inferior()# 从地址rax开始读取32个字节(即0x20字节)的内存数据the_mem = inferior.read_memory(rax, 0x20)# 打印内存数据print("the_mem: ", the_mem.tobytes()) |
参考链接
- https://segmentfault.com/a/1190000005718889
- https://sourceware.org/gdb/onlinedocs/gdb/Basic-Python.html#Basic-Python
- 文心一言
- chatgpt
2023/5/3