Android modifying code in ART
I am trying to implement self-modifying code in my android application using JNI.
I have the following method in my MainActivity class for my application:
public int methodToModify()
{
return 42;
}
And this is the bytecode of this method:
const/16 v0, 0x2A
return v0
The way this method is represented in the classes.dex file:
13 00 2A 00 0F 00
My goal here is to change the return value of a method methodToModify
at runtime from native code. So, this is a JNI method algorithm that implements self-modifying code:
-
Read the process memory (here's more info on this Understanding Linux / proc / id / maps ):
FILE *fp; fp = fopen("/proc/self/maps", "r");
-
Determine the start and end addresses of the .dex file (or the .oat file in the 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
-
Find bytes
methodToModify
in .dex or .oat files. -
Use the function
mprotect
to set the permission to write the file. -
Modify the return method.
My problem is this approach works fine on my Nexus 7 running Android 4.2, but it doesn't work on a Nexus 5 running Android 5.1. I can implement self-modifying code with Dalvik, but I cannot do the same with ART.
So, is it possible to implement self-modifying code with ART?
source to share
Considering that ART uses Ahead of Time Compilation, https://source.android.com/devices/tech/dalvik/
I'm not sure how you expected this to work, as at runtime it is already in the processor architecture code and not in the DEX bytes.
more details here: https://source.android.com/devices/tech/dalvik/configure.html
Google IO 2014 video on ART runtime: https://youtu.be/EBlTzQsUoOw
source to share