Search code examples
androidcandroid-ndkself-modifyingandroid-runtime

Android self-modifying code in ART


I'm trying to implement self-modifying code in my Android application using JNI.

I have the following method in MainActivity class of my application:

public int methodToModify()
{       
    return 42;
}

And this is a bytecode of this method:

const/16 v0, 0x2A
return v0

That's how this method is represented in classes.dex file:

13 00 2A 00 0F 00

My goal here is to change the return value of method methodToModify in a runtime from a native code. So, this is the algorithm of JNI method which implements self-modifying code:

  1. Read process memory(here's a more information about this Understanding Linux /proc/id/maps):

    FILE *fp; fp = fopen("/proc/self/maps", "r");

  2. Detect the addresses of the beginning and the end of a .dex file(or an .oat file in a case of ART):

    while (fgets(line, 2048, fp) != NULL) { // search for 'dex' or 'oat' if (strstr(line, ".oat") != NULL || strstr(line, ".dex") != NULL) // get starting and ending addresses of the DEX file region

  3. Find bytes of methodToModify in the .dex or .oat file.

  4. Use mprotect function to set permission to write a file.

  5. Modify the return value method.

My issue is that this approach perfectly works on my Nexus 7 with Android 4.2, but it doesn't work on Nexus 5 with Android 5.1. I'm able to implement self-modifying code with Dalvik, but I can't do the same with ART.

So, is it possible to implement self-modifying code with ART?


Solution

  • Given that ART is using Ahead of Time Compilation, https://source.android.com/devices/tech/dalvik/

    I'm not sure how you expected this to work since at runtime it is already in CPU architecture code and not DEX bytecode.

    more details here: https://source.android.com/devices/tech/dalvik/configure.html

    Google IO 2014 video on ART runtime: https://youtu.be/EBlTzQsUoOw