版权归作者所有,如有转发,请注明文章出处:https://cyrus-studio.github.io/blog/
Android 示例代码
编写一个 jni 方法 add 进行简单的加法运算 ,代码如下:
#include <jni.h>
// 实现加法运算
extern "C"
JNIEXPORT jint JNICALL
Java_com_cyrus_example_unicorn_UnicornActivity_add(JNIEnv *env, jobject thiz, jint a, jint b) {
return a + b;
}
配置 CMakeLists.txt
add_library( # 设置库的名称
unicorn
# 设置库的类型
SHARED
# 设置源文件路径
unicorn.cpp)
target_link_libraries( # 将 log 库链接到目标库
unicorn
${log-lib})
完整源码地址:https://github.com/CYRUS-STUDIO/AndroidExample
编译运行 Android 项目后在 build 目录找打 apk 并解压 libunicorn.so。
加载 so 并反汇编
通过 IDA 打开 so 文件可以看到 add 方法的开始地址为 0x0608,结束地址为 0x063C
加载 so 文件并使用 capstone 反汇编 so 中机器码
import capstone
# 加载 libunicorn.so
so_file = "libunicorn.so"
# 指定 add 方法的开始和结束地址
start_address = 0x0608
end_address = 0x063C
# 读取 .so 文件内容
with open(so_file, "rb") as f:
binary_data = f.read()
# 提取需要反汇编的字节码(包括结束地址)
add_function_data = binary_data[start_address:end_address]
# 初始化 Capstone 反汇编器 (针对 ARM64 架构)
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
# 反汇编字节码
for instruction in md.disasm(add_function_data, start_address):
print(f"0x{instruction.address:x}:\t{instruction.mnemonic}\t{instruction.op_str}")
运行输出如下:
0x608:subsp, sp, #0x20
0x60c:strx0, [sp, #0x18]
0x610:strx1, [sp, #0x10]
0x614:strw2, [sp, #0xc]
0x618:strw3, [sp, #8]
0x61c:ldrw9, [sp, #0xc]
0x620:ldrw10, [sp, #8]
0x624:movw8, wzr
0x628:subsw9, w8, w9
0x62c:subsw10, w8, w10
0x630:addw9, w9, w10
0x634:subsw0, w8, w9
0x638:addsp, sp, #0x20
汇编代码分析
add 方法的汇编代码分析如下:
SUB SP, SP, #0x20 ; 分配栈空间 0x20 (32 字节)
STR X0, [SP,#0x20+var_8] ; 保存 X0(env 指针)
STR X1, [SP,#0x20+var_10] ; 保存 X1(thiz 对象)
STR W2