Search code examples
javaandroiddexsmali

How to find a java method using a string reference from a dex file


I'm using baksmali and dexlib2 library in Android Studio project. I'm trying to find a method from dex file. Inside method definition, there is a unique string in one of the method body statements. I want to find that method in the fastest possible way.
As example:

public boolean A01() {
    ..........
    return tvar.quals("unique_string") ? false : true;
}

I want to find this method using this "unique_string".

Currently I'm using DexBackedDexFile.getClasses() to get all classes from the dex file and decoding all of them into smali code. Then searching the string inside the generated smali code. I'm able to find my desired method this way, but decoding thousands of class is time consuming. So I'm thinking if there is a quick way to do that.

There is a way to quickly get a string reference from dex file using DexBackedDexFile.getStringReferences(), which returns a DexBackedStringReference object. I can find my desired string reference quickly this way, which contains a stringIndex. I'm wondering if there is a way to find the method using this index number. Thanks


Solution

  • If the app has multiple dex files, using the string table you know which dex file to load and thus you can reduce the number of methods to search in.

    Unfortunately I don't think that there is a different way than just decoding searching in all methods for the string reference. Android does not need any back references from the string pool to the used method so it does not exist in dex format.

    But you can speed-up the search process by distribute the method-decoding and searching for the string reference into multiple threads. As far as I know the Dex decoding library dexlib2 used in baksmali does not use threads at all.

    Modern Android devices have 4-8 cores and decoding a DEX method is a process that can run in parallel without having to synchronize anything, therefore you should be able to nearly get a speed-up e.g. by 400% on a 4-core system.