使用radare2 进行函数调用跟踪或中断所有函数调用

逆向工程 调试 雷达2 断点 追踪
2021-06-17 00:02:09

我想使用 r2pipe 用 python 编写脚本。有没有办法在调试时我可以中断每个调用函数,从而获得参数?更重要的是,我不会跳入系统库。或者有没有办法进行函数跟踪,只是在程序的地址空间中,而不是在系统库中?

1个回答

是的,你可以这样做。执行此操作的 python 脚本附在下面并附有适当的注释。

#!/usr/bin/env python3
import r2pipe

r = r2pipe.open('programName', flags=['-d'])
r.cmd('aei')

modules = r.cmd('dmm') #list all modules along with start and end addresses
modules2 = [] #modules' start addresses
moduleNames = []
#since modules is just one big string, we need to extract relevant information from it
i = 0
j = 0
while i < len(modules):
    modules2.append('')
    while modules[i] != ' ':
        modules2[j] += modules[i]
        i += 1
    while modules[i] == ' ':
        i += 1
    while modules[i] != ' ':
        i += 1
    while modules[i] == ' ':
        i += 1
    moduleNames.append('')
    while modules[i] != '\n':
        moduleNames[j] += modules[i]
        i += 1
    i += 1
    j += 1

moduleNames = [x.split('/')[len(x.split('/')) - 1] for x in moduleNames]

systemModules = {} #put here all libraries you don't want breakpoints in
systemModules['ld-2.27.so'] = 1

for i in range(len(moduleNames)):
    if moduleNames[i] not in systemModules:
        r.cmd('s ' + modules2[i]) #go to start of module i
        calls = r.cmd('/am call') #find all call instructions in this module; you can use other commands of type /a for more flexibility
        calls2 = [] #all addresses in module i where we want to put breakpoints
        k = 0
        j = 0
        while k < len(calls):
            calls2.append('')
            while calls[k] != ' ':
                calls2[j] += calls[k]
                k += 1
            while calls[k] != '\n':
                k += 1
            k += 1
            j += 1
        for k in range(len(calls2)):
            r.cmd('db ' + calls2[k]) #put breakpoint at given address
#all breakpoints set; you can now continue execution and do what you want to do at each breakpoint
print(r.cmd('db')) #list all breakpoints set

不是很优雅的脚本,但可以完成工作。它搜索call相关模块中的所有指令并在每个指令处放置断点。

为了获得更大的灵活性,/am您可以使用radare2 中提供的其他搜索命令,而不是执行,以/a?获取更多信息。