Android 上原生自修改代码
我正在尝试在 Android 上制作一些自修改本机代码并在模拟器中运行它。我的示例基于 android-ndk 中的 HelloJNI 示例。它看起来像这样:
#define NOPE_LENGTH 4
typedef void (*FUNC) (void);
// 00000be4 <nope>:
// be4: 46c0 nop (mov r8, r8)
// be6: 4770 bx lr
void nope(void) {
__asm__ __volatile__ ("nop");
}
void execute(void){
void *code = mmap(NULL, NOPE_LENGTH, PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (code != MAP_FAILED) {
memcpy(code, nope, NOPE_LENGTH);
((FUNC)code)();
}
}
问题是这段代码正在崩溃。怎么了?
I am trying to make some self-modifing native code on Android and run it in the emulator. My sample is based on the HelloJNI sample from the android-ndk. It looks like this:
#define NOPE_LENGTH 4
typedef void (*FUNC) (void);
// 00000be4 <nope>:
// be4: 46c0 nop (mov r8, r8)
// be6: 4770 bx lr
void nope(void) {
__asm__ __volatile__ ("nop");
}
void execute(void){
void *code = mmap(NULL, NOPE_LENGTH, PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (code != MAP_FAILED) {
memcpy(code, nope, NOPE_LENGTH);
((FUNC)code)();
}
}
The problem is that this code is crashing. What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据猜测,
nope()
被编译为 Thumb,但您将其称为 ARM(假设 mmap 返回字对齐指针)。要调用 Thumb 代码,应设置地址的低位。尝试这样的操作:要正确执行此操作,您应该确保分配的内存对齐(Thumb 为 2,ARM 为 4),确保您尝试运行的代码是 Thumb(或 ARM)并将位设置为 0因此。
At a guess,
nope()
was compiled as Thumb, but you're calling it as ARM (assuming mmap returns a word-aligned pointer). To call Thumb code, the low bit of the address should be set. Try something like this:To do it properly, you should ensure alignment of the allocated memory (2 for Thumb and 4 for ARM), make sure that the code you're trying to run is Thumb (or ARM) and set the bit 0 accordingly.