In an android Java code like this:
String methodName = "myMethod"
public void myMethod() {
}
Is it possible to figure out the obfuscated name of the method at runtime?
I know I can ask Proguard to not obfuscate that method, but I'm looking for a way to avoid that and still be able to use it through reflection.
I can't find a Proguard configuration for that, but I'm wondering if there could be a gradle task for merging the generated mapping?
If you need the method name from inside the method, you can use
String methodName;
public void myMethod() {
methodName = new Object() {}.getClass().getEnclosingMethod().getName();
}
Or, in newer Java versions
String methodName;
public void myMethod() {
methodName = StackWalker.getInstance(Set.of(), 1)
.walk(s -> s.map(StackWalker.StackFrame::getMethodName).findFirst())
.orElseThrow();
}
When you need the name from the outside, i.e. with calling it, you can mark the method with an annotation and search for it.
#Retention(RetentionPolicy.RUNTIME) #interface Marker {}
#Marker
public void myMethod() {
}
String name = Arrays.stream(ContainingClass.class.getDeclaredMethods())
.filter(m -> m.isAnnotationPresent(Marker.class))
.map(Method::getName)
.findFirst().orElseThrow();
As said by others, not to use Reflection might be the better option. E.g., referring to the method using a matching functional interface, is not a reflective access:
Runnable method = this::myMethod;
public void myMethod() {
}
This will keep working after obfuscation.
Code obfuscation usually just renames classes and variables to short and random text, keeping proper dependencies at the same time. There is no way to get the obfuscated name of the function as it is generated randomly and always different per each run.
Here are some options:
Instead, exclude the class from obfuscation and name your function with random text if you want to keep it unreadable.
-keep class <com.package.DontObfuscate>
After the first obfuscation, keep mapping.txt file and add a line to your proguard-rules.pro
-applymapping mapping.txt
That's will keep from generating new names for classes/variables.
-applymapping - Specifies to reuse the given name mapping that was printed out in a previous obfuscation run of ProGuard. Classes and class members that are listed in the mapping file receive the names specified along with them. Classes and class members that are not mentioned receive new names.
Look for a way to not use reflection in your code with class/interface extensions.
Related
Currently class names are not being obfuscated. I need to find obfuscated package of specific class for use in reflection. Any ideas?
I can think of two approaches:
Read the obfuscated package name of the desired class from the <project_module>/build/outputs/mapping.txt and then write it to a file (asset for example) that you can add to the apk as in a new build step and read in your app. If you don't intend to add new classes/packages before (in lexicographical order) the one you wish to access you might even get away with picking the package name from mapping.txt and storing it in a String field somewhere in the app (but this is highly unstable/undesirable).
Declare a field containing the reference to the class you wish to access via reflection someplace where it's easy to find (the name and package of the Application subclass are not obfuscated because they are referenced in the manifest so that would be a good candidate) and then you simply use that reference:
public class YourApplication extends Application {
//...
public static Class<?> yourReflectiveClass = YourReflectiveClass.class;
}
And then you access that field and use it as you need:
//...
Field[] appFields = YourApplication.class.getDeclaredFields();
Field classField = null;
for (Field f : appFields) {
if (f.getType().equals(Class.class) {
classField = f;
break;
}
}
if (classField != null) {
Object classInstance = classField.get(null);
if (classInstance instanceof Class) {
Class<?> yourReflectiveClass = (Class) classInstance;
// yourReflectiveClass.getPackage().getName()
}
}
You might need to alter proguard-rules.pro to keep your new field(s) in the obfuscated variant.
Also note that this kind of defeats (at least partially) the purpose of obfuscation.
I found elegant solution. I store string constant into environment variable with value of needed class package. I can access any needed obfuscated data via static string key of environment variable. Even class name itself was obfuscated I would get always needed data. It is easy to access this data from any module in application since it is in environment variable.
static {
System.setProperty(Const.NEEDED_PACKAGE, NeededClass.class.getPackage()).getName());
}
Working with an Android project in Android Studio 3.2, having enabled Proguard and some specific rules, I'm not able to figure out the following:
a specific package (and its subpackages) in a library module, used by client code, is preserved through the rule:
-keep public class com.mylib.mypackage.** {
public protected *;
}
Now, within this package there are also a number of package-private classes, which should not be picked by that rule. Some of those classes are effectively obfuscated, both in their own names and their member names, which is fine.
Instead there are some classes, implementing public interfaces, whose class names are not obfuscated, while I'd expect they should. For completeness, their member names, when not part of interface, are effectively obfuscated.
Example:
/* package */ class InternalComponent implements ExternalInterface {
// ExternalInterface is kept: Ok
// InternalComponent is kept: don't like, I'd like it renamed
#Override
public void ExternalMethod() {
// this is kept: Ok
}
public void InternalMethod() {
// this is renamed: Ok
}
}
I'd like to highlight that InternalComponent is created within some other (kept) class and only returned to client code through the ExternalInterface.
How can I also obfuscate their class names as well, if possible?
Edit #1
After #emandt answer on Proguard output files, I double checked and com.mylib.mypackage.InternalComponent is listed in seeds.txt, which according to this blog post lists all items matched by keep rules. So, for some reason, the rule above also picks package-private classes, which still seems wrong to me.
Edit #2
In the meantime, I ended up doing exactly the same approach proposed by #shizhen. For completeness, in order to extend the exclusion to any package named internal, I modified my proguard rule as:
-keep public class !com.mylib.mypackage.**.internal.*, com.mylib.mypackage.** {
public protected *;
}
(note the first part before the comma, prefixed by !)
I'll mark #shizhen answer, though I'd like to be curious as to why the original rule is also picking package-private components.
Are you working on an Android Library project? Probably YES.
In order to achieve your purpose, I am afraid that you need to re-organise your packages into something like below:
Public interfaces
com.my.package.apiforusers
Private/Internal implementations
com.my.package.apiforusers.internal
Then for your obfuscation rules, you can have it like below:
-keep public class com.my.package.apiforusers.** { public *; }
So that only the public classes/interfaces are kept and all those ones inside com.my.package.apiforusers.internal will be obfuscated.
Please note the double-asterisk at the end so that public classes/interface are also kept for the sub-packages.
In "/build/outputs/mapping/release/" folder there are few files ("usage.txt", "seeds.txt", etc..) that contain the REASONS of why and which classes/variables/methods/etc.. are not-processed/not-shrinked/ot-obfuscated via ProGuard utilities.
I created a wrapper class MyLog to do logging for my Android app, which essentially just wraps android.util.Log. I want logging to be completely gone in my release app. I have the following rule defined in my proguard file:
-assumenosideeffects class com.myapp.logging.MyLog {
public static void d(...);
}
I am seeing that lines that have log statements as follows:
MyLog.d("Logging a boolean %b and a string %s parameter", isTrue, stringName);
are being shrunk to:
Object[] objArr = new Object[]{Boolean.valueOf(z), str};
and lines with log statements as follows:
MyLog.d("function call result: " + foo() + " end");
are shrunk to:
new Object[1][0] = foo();
In both cases the leftovers from obfuscation are pretty useless and might as well should've been removed.
Question:
Why would proguard leave unused variables in example #1 above?
Is there a better way to tell proguard - "Assume no side effects when you remove this method declaration and any calls to it, along with the parameters passed to it"?
I have read other answers related to the topic and the closest answer is here. I am not looking for solutions with BuildConfig.IS_LOGGING_ENABLED type solution where every log statement should be wrapped with this check.
I've been using Eclipse as my IDE. I also use it to export my application into a JAR file. When I look at my classes in the JAR file, a few of my classes contain the name of that class, a dollar sign, then a number. For example:
Find$1.class
Find$2.class
Find$3.class
Find.class
I've noticed it does this on bigger classes. Is this because the classes get so big, it compiles it into multiple classes? I've googled and looked on multiple forums, and search the Java documentation but have not found anything even related to it. Could someone explain?
Inner classes, if any present in your class, will be compiled and the class file will be ClassName$InnerClassName. In case of Anonymous inner classes, it will appear as numbers. Size of the Class (Java Code) doesn't lead to generation of multiple classes.
E.g. given this piece of code:
public class TestInnerOuterClass {
class TestInnerChild{
}
Serializable annoymousTest = new Serializable() {
};
}
Classes which will be generated will be:
TestInnerOuterClass.class
TestInnerOuterClass$TestInnerChild.class
TestInnerOuterCasss$1.class
Update:
Using anonymous class is not considered a bad practice ,it just depends on the usage.
Check this discussion on SO
This is because you have anonymous classes within this larger class. They get compiled using this naming convention.
See The Anonymous Class Conundrum
In addition to the above cases presented by #mprabhat, the other cases could be:
if you class contain a enum variable a separate class would be generated for that too. The name of the .class generated would be ClassName$Name_of_enum.
If your class X is inheriting i.e. extending another class Y, then there would be a .class generated with the name ClassName$1.class or ClassName$1$1.class
If your class X is implementing an interface Y, then there would be a .class generated with the name ClassName$1.class or ClassName$1$1.class.
These cases are derivations of my inspection on .class files in jar.
To answer your comment about are anonymous classes bad. They are most definately not.
Consider this to assign an action listener to a JButton:
JButton button = new JButton(...);
button.addActionListener(new ActionListener() { ... });
or this to do a case insensitive sort by the "name" property
Collections.sort( array, new Comparator<Foo>() {
public int compare(Foo f1, Foo f2) {
return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase());
}
});
You'll also see a lot of Runnable and Callable done as anonymous classes.
Class<?> c = Class.forName("co.uk.MyApp.dir.TargetClass");
Method main = c.getDeclaredMethod("main", Report_Holder.class);
Throws a 'java.lang.NoSuchMethodException.main[class co.uk.MyApp.classes.Report_Holder]' error once I've prepared the app for release using Proguard.
I spent hours thinking the problem was in 'co.uk.MyApp.dir.TargetClass', commenting out things, re-releasing the app, and re-testing. But it turns out that the error is right at the root, at:
Method main = c.getDeclaredMethod("main", Report_Holder.class);
I then updated proguard-project.txt to include:
-dontobfuscate
-keeppackagenames
(I am using the Lint suggested method which suggested putting code into project.properties and putting the config in a text file), such as:
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
But adding those 2 lines didn't have any effect.
So now I am wondering if;
a) I should add anything on top of '-keeppackagenames' etc.
b) Is proguard.config set up correctly; should ${sdk.dir} actually be a proper uri to the sdk
The class that it is targeting is like this:
public static void main(Report_Holder args) {
....
}
Edit
Or is it because I have 2 instances of this type of thing, both called 'main' ? But called in different activities.
Method main = c.getDeclaredMethod("main", Report_Holder.class);
Method main = c.getDeclaredMethod("main", OtherReport_Holder.class);
And both targets being like this:
public static void main(Report_Holder args) {
....
}
public static void main(OtherReport_Holder args) {
....
}
Once you know how to use proguard, you should add the option -keepattributes Signature
. this is necesary when using generics (collections).
For all methods beeing called via reflection, you must explictly exclude them from obfsucation. use the option to output the obfuscation map file, to see if your rules had the desired effect.