Native self-modifying code on Android

感情迁移 提交于 2019-12-09 05:55:42

问题


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?


回答1:


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:

( (FUNC)(((unsigned int)code)|1) )();

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.



来源:https://stackoverflow.com/questions/4461609/native-self-modifying-code-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!