Android Self-modifying code - NDK

2019-08-12 15:19发布

问题:

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)();