JAVA CODE
class JniTest... public void test() { //some code } public void runJniCode() { //here I call native code }
本地代码
JNIEXPORT void JNICALL Java_path_to_class_test(JNIEnv* env,jobject obj) { //here I call test method from Java }
一切正常,直到我想发布一个混淆版本.此类中的Java类名称(例如JniTest)和方法测试由proguard重命名为“a”和“a()”(这可能并不总是相同),但在本机代码中,方法的原始名称和类保持不变,因为它被硬编码为字符串,如:
jmethodID mid = env->GetMethodID(cls,"test","someSignature");
解决方法
从来源引用:
I present here a simple trick which allows obfuscation of the JNI layer,renaming the method names to meaningless names on both the Java and native side,while keeping the source code relatively readable and maintainable and without affecting performance.
Let’s consider an example,initial situation:
class Native { native static int rotateRGBA(int rgb,int w,int h); } extern "C" int Java_pakage_Native_rotateRGBA(JNIEnv *env,jclass,int rgb,int h);
In the example above Proguard can’t obfuscate the method name rotateRGBA,which remains visible on the Java side and on the native side.
The solution is to use directly a meaningless method name in the source,while taking care to minimally disrupt the readability and maintainability of the code.
class Native { private native static int a(int rgb,int h); //rotateRGBA static int rotateRGBA(int rgb,int h) { return a(rgb,w,h); } } // rotateRGBA extern "C" int Java_pakage_Native_a(JNIEnv *env,int h);
The JNI method is renamed to a meaningless a. But the call on the Java side is wrapped by the meaningfully named method rotateRGBA. The Java clients continue to invoke Native.rotateRGBA() as before,without being affected at all by the rename.
What is interesting is that the new Native.rotateRGBA method is not native anymore,and thus can be renamed by Proguard at will. The result is that the name rotateRGBA completely disappears from the obfuscated code,on both Dalvik and native side. What’s more,Proguard optimizes away the wrapper method,thus removing the (negligible) performance impact of wrapping the native call.
Conclusion: eliminated the JNI method name from the obfuscated code (both Dalvik bytecode and native library),with minimal impact to readability and no performance impact.