首页 > 解决方案 > 为什么这个简单的 Frida 跟踪 C 代码行为不规律?

问题描述

我正在尝试使用 Frida,我发现的一些最简单的示例在 macOS 上无法正常工作。这是一个例子。

考虑这个 C 代码:

#include <stdio.h>
#include <unistd.h>

void print_hello(int n, char a, float f) {
    printf("hello %d %c %f\n", n, a, f);
}

int main(int argc, char *argv[]) {
    while (1) {
        print_hello(10, 'a', 3.141f);
        sleep(1);
    }
    return 0;
}

很明显它的作用。

现在这是一个 Frida python 启动器:

#!/usr/bin/env python3

import frida

def on_message(message, data):
    print(message)

pid = frida.spawn('./a.out')
session = frida.attach(pid)
script = session.create_script("""
    Interceptor.attach(Module.findExportByName(null, 'print_hello'), {
        onEnter(args) {
            send('enter')
        },
        onLeave(retval) {
            send('leave')
        }
    })
""")
script.on('message', on_message)
script.load()
frida.resume(pid)

人们会期望它每秒打印一次进入/离开。相反,这是我得到的一些结果:


% ./trace.py 
hello 10 a 3.141000
{'type': 'send', 'payload': 'enter'}
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
^C

% ./trace.py 
hello 10 a 3.141000
{'type': 'send', 'payload': 'enter'}
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
^C

% ./trace.py 
hello 10 a 3.141000
{'type': 'send', 'payload': 'enter'}
hello 10 a 3.141000
^C

% ./trace.py 
hello 10 a 3.141000
{'type': 'send', 'payload': 'enter'}
{'type': 'send', 'payload': 'leave'}

% ./trace.py 
hello 10 a 3.141000
{'type': 'send', 'payload': 'enter'}
hello 10 a 3.141000
hello 10 a 3.141000
^C

% ./trace.py 
hello 10 a 3.141000
{'type': 'send', 'payload': 'enter'}
hello 10 a 3.141000
hello 10 a 3.141000
hello 10 a 3.141000
^C

在第三次调用中,它退出 w/o ^C。

标签: frida

解决方案


没有什么可以保持trace.py活动状态,因此一旦到达脚本末尾,仪器就会恢复 - 作为 Python 解释器关闭的一部分。sys.stdin.read()您可以在脚本末尾添加调用以避免这种情况。


推荐阅读