为何针对C代码的简单Frida trace在macOS系统上表现异常?
问题根因
你遇到的不稳定、崩溃问题由两个核心原因导致:
- macOS下clang默认不会导出普通C函数的符号,
Module.findExportByName()无法稳定定位print_hello的内存地址,偶尔匹配到非法地址就会触发进程崩溃,就是你遇到的自动退出情况 - 未放开SIP的调试限制时,macOS系统会拦截Frida的注入、hook操作,导致hook行为随机失效
修复步骤
1. 强制导出目标函数符号
两种方案二选一即可:
方案A:修改C代码给目标函数加导出属性
修改print_hello的定义:
#include <stdio.h> #include <unistd.h> __attribute__((visibility("default"))) 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; }
之后正常编译即可:clang test.c -o a.out
方案B:编译时指定导出符号
不用修改C代码,编译时加参数强制导出print_hello:clang test.c -o a.out -Wl,-exported_symbol,_print_hello
2. 放开SIP调试限制
如果你的macOS SIP处于完全开启状态,重启进入恢复模式,打开终端执行:csrutil enable --without debug
重启后即可生效,该配置不会关闭SIP的其他安全能力,仅放开调试相关限制,不影响系统安全性。
3. 优化Frida脚本避免异常
给符号查找加判空逻辑,同时给Python脚本加进程保活逻辑,避免主进程提前退出导致hook中断:
修改后的Python脚本:
#!/usr/bin/env python3 import frida import sys def on_message(message, data): print(message) pid = frida.spawn('./a.out') session = frida.attach(pid) script = session.create_script(""" const printHelloAddr = Module.findExportByName(null, 'print_hello'); if (!printHelloAddr) { send('print_hello 符号未找到'); return; } Interceptor.attach(printHelloAddr, { onEnter(args) { send('enter'); }, onLeave(retval) { send('leave'); } }) """) script.on('message', on_message) script.load() frida.resume(pid) sys.stdin.read()
修改完成后重新运行脚本,即可稳定每秒输出enter和leave日志,不会再出现崩溃、hook随机失效的问题。
内容的提问来源于stack exchange,提问作者user3909192
相关产品推荐
相关产品推荐

