Android Self-modifying code - NDK

拥有回忆 提交于 2019-12-13 00:19:47

问题


I am trying to make a self-modifying code library and I have scowered all over and I have the follow code:

typedef int (*FUNC) (void);
int test();

JNIEXPORT int Java_com_example_untitled_MyActivity_decrypt( JNIEnv* env, jobject thiz)
{
    void *code = mmap(NULL, 4, PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    if (code != MAP_FAILED) {
        memcpy(code, test, 4);

        return ( (FUNC)code)();
    }

    return 0;
}

int test()
{
    return 100;
}

Please help...I used Native self-modifying code on Android as my starting point and they said something about compiling with "-marm" and thumb bit...

My issue I'm having is, it's just crashing. I have tried using the cacheflush function, didn't seem to help. I am at a loss.


回答1:


On ARM, you need to flush the CPU caches in order to ensure that the instructions you just copied are visible to the CPU before they are executed. A simple way to do this is:

#include <unistd.h>  // for cacheflush()

...

// Copy the instructions to the destination address.
memcpy(dest, original_intructions, size_of_instructions);

// Clear the CPU cache
cacheflush((uintptr_t)dest, (uintptr_t)dest + size_of_instructions, 0);

// Run them.
return ((FUNC)dest)();


来源:https://stackoverflow.com/questions/21176037/android-self-modifying-code-ndk

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