Android ProGuard how to hide/obfuscate source code of exported library - android

I'm developing Android library and I want to hide/obfuscate the source code implementation of the library.
The way the user project app will use the library is:
startActivity( new Intent(context, LibraryActivityName.class) );
So I need to keep just the name of entry point Activity inside the library project, That's all.
When I used the default ProGuard settings:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
as well as the suggested example for library - Nothing happened, and by clicking on the Activity name inside the user app (when he imports it) - One can see the source code.
Thanks,

As you do not have a typical library, you should not include the typical library example.
First of all, you need to enable Proguard execution, change this line:
minifyEnabled true
Second, you do not want to keep all public classes, but only the activity:
-keep class LibraryActivityName { public protected <methods>; }
The remaining classes can be fully obfuscated if I understand your question correctly, so there should be no need for further configuration, unless you use reflection somewhere.
It would also be good if you repackage the obfuscated classes into an internal package or something using
-repackageclasses my.library.package.internal
which might also required
-allowaccessmodification
btw. ProGuard will not obfuscate the code itself, only the class / method names.

Related

using R8 to hide private and internal methods from android library

i have written android library. but when i integrate aar into client app. i can actually see private/internal/public methods of "public" classes.
what i expect is: it should show only "public" methods of "public" classes.
i am using R8, for release build i have following settings in library gradle file.
buildTypes {
release {
minifyEnabled true
proguardFiles 'proguard-rules.pro'
}
}
proguard-rules.pro file contents:
-keep class com.comp.sdk.UserManager {
public *;
}
here UserManager is 'object' in kotlin.
after building aar file. distributing to client app. client app can still see
private/public/internal methods for UserManager object.
my question is how can i write r8 rules for showing only public methods/variables of User object in kotlin?

Undo from enable minify after release the app

At some point of devlopment I changed minifyEnabled to true without any rules in proguard then release the app to google play with v.1.4.0.
many of bugs occured to uses when updated the app, I knew the problem because the obfuscated of classes.
and some of users removed the app and reinstall to work well partially.
WebView, Camera, Gson, File Picker all this features have problems on version 1.4.0
It was my first experience with minifyEnabled, now I'm knowing that there are alot of rules should I write in the proguard to keep classes.
My question about make undo of minifyEnabled and set it to false, when I debug it, also a new problem occurs and one of them from the code below with NullPointerException.
abstract class LiveCoroutinesViewModel : ViewModel() {
inline fun <T> launchOnViewModelScope(crossinline block: suspend () -> LiveData<T>): LiveData<T> {
return liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emitSource(block())
}
}
}
note: I don't need to keep minifyEnabled = true, becuase I have alittle bit experinces and I think there are alot of keeping rules should I understand before I write them and I don't have the time now for that.
So, what is the optimal soultion (strategy) to do minifyEnabled = false for users which already working on minifyEnabled = true
The answer is not possible in my way. Because you don't have an option to handle your released app code.
My Suggestion:
Do you think that you have to write rules for Proguard? But not, Android proguard is R8 Guard not proguard. Proguard is another company guard(DexGuard). You can use the R8 guard without adding any rules because these rules are already included in all libraries(read library github and check R8 is included or not). If you enabled R8 guard then just add this line #Keep in your Model class to prevent R8 Guard to shrink that file. Add #Keep which file you don't want to minify.
Like this
#Keep // use to prevent R8 to minify this class.
public class ModelClass {
String id;
String text;
String image;
public String getImage() {
return image;
}
In new version of android, You can test your app by enabling R8 guard in debug mode by adding these below lines in your build.gradle(:app); // in module level
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug { // add this line after release and make ninify true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
It may take some time to build but it is a very good method to test if the app is caching or not (in app build time).
PS
minifyEnabled true helps to reduce app size. Very helpful if you enabled it.
It helps you in the future.

Proguard (R8) obfuscate custom view names

I am using R8 in my app and have several custom views (which are referenced in xml layouts) tho their names are not obfuscated at all. Is there any way to achieve this? I am using the standard Gradle rules:
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
And also tried with android.enableR8.fullMode=true but it's the same.
I am using R8 in my app and have several custom views (which are referenced in xml layouts) tho their names are not obfuscated at all.
This is because the proguard-android-optimize.txt has the following rule:
# keep setters in Views so that animations can still work.
-keepclassmembers public class * extends android.view.View {
void set*(***);
*** get*();
}
So your custom views, or any views, will not have their names obfuscated by default.
Now the question is can you still have R8 rename the custom views in your app? And the answer is not really.
You could add an -applymapping myCustomMapping.txt by copying the contents of
<root_dir>/app/build/outputs/mapping/<build_variant>/mapping.txt and replacing all references to your custom views that are NOT obfuscated with obfuscated names.
Like this:
Copy contents of <root_dir>/app/build/outputs/mapping/<build_variant>/mapping.txt into a new file <root_dir>/app/myCustomMapping.txt
Before changing anything, it will look like this:
my.app.package.CustomView -> my.app.package.CustomView :
13:34:void <init>(android.content.Context,android.util.AttributeSet,int) -> <init>
15:16:void <init>(android.content.Context,android.util.AttributeSet,int,int,kotlin.jvm.internal.DefaultConstructorMarker) -> <init>
43:46:void customMethod() -> c
You need to change only this line, that has the top level class mapping. Notice that it is unchanged because of the android proguard rules. Change it to whatever obfuscated name you want, like this:
my.app.package.CustomView -> my.app.package.youcantseemeatall :
13:34:void <init>(android.content.Context,android.util.AttributeSet,int) -> <init>
15:16:void <init>(android.content.Context,android.util.AttributeSet,int,int,kotlin.jvm.internal.DefaultConstructorMarker) -> <init>
43:46:void customMethod() -> c
Finally, add these lines to your proguard-rules.pro file
-applymapping myCustomMapping.txt
-printmapping mapping.txt
Those above steps will change your .class files to obfuscate CustomView to youcantseemeatall, BUT your resource files will still reference the original CustomView name and your app will crash at runtime.
Conclusion:
Unfortunately there really isn't a way to do what your asking with proguard or any tooling that comes with Android Studio. There may be a custom Gradle Plugin that changes all custom view names before the app is assembled, but I couldn't find one just googling it now.

R8 changes "protected" methods of abstract class to "public" without -allowaccessmodification flag

I have an issue with R8. In MyLib I have public abstract MyLibsClass in which I have protected methods. MyChildClass extends from MyLibsClass in MyApp and after R8's magic all protected methods (including protected abstract) in MyLibsClass are changed into public ones, and of course in MyChildClass I'm getting "attempting to assign weaker access privileges ('protected'); was 'public') issue as trying to override protected abstract methods.
Additional info
gradle-6.0.1
MyLib's build.gradle
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
}
proguard-rules.pro
-keep class com.example.mylib.*{
public protected *; }
-keep class com.example.mylib.*$*{
public protected *; }
Anyone had this kind of issue or know a way to fix this?
So based on discussion here ,
DON'T USE DEFAULT PROGUARD SETTINGS FOR LIBRARIES
as allowAccessModification is enabled in default proguard settings, which is located in Android SDK (\Android\Sdk\tools\proguard\proguard-android-optimize.txt) and my mistake was using this for my libraries.
Citation from proguard manual
you probably shouldn't use this option when processing code that is to
be used as a library, since classes and class members that weren't
designed to be public in the API may become public.
So if anyone has the same issue I will suggest to create your own base config file for proguard and copy past whole default configs without "allowAccessModification" into it.
Also if someone interested more, you can track this issue. Hopefully will get separate config file for libraries in near feature.
I faced the same problem, and thanks to #Hayk Nahapetyan's answer, I could resolve it.
Here is my solution with a little more detail.
In the library module's build.gradle, remove the default file from the buildTypes's release closure:
release {
minifyEnabled true
proguardFiles 'proguard-rules.pro'
}
R8 no longer uses the default file that is provided in the Android SDK. It generates one at build time, and puts it in the module's build directory at build/intermediates/default_proguard_files/global.
Copy the contents of proguard-android-optimize.txt-a.b.c (where a.b.c is the library version, if set) from that location to the top of the module's proguard-rules.pro. Then remove -allowaccessmodification; two times, if it originally appeared in both files.
This was also reported on the R8 bug tracker, and resolved there. See http://issuetracker.google.com/147447502.

Android Proguard does not inline

I am using the latest Android SDK (4.1) and I tried exporting a signed jar with Proguard enabled. However, after decompiling the optimized APK, I noticed that methods that I would have expected to be inlined were not.
I know that Proguard ran because the code was correctly obfuscated. So to confirm this, I added this method to my Activity:
private void testInlining()
{
mConfig = null;
}
This private method is called only once in my activity, and because it is private, it should be very obvious to the optimizer that it is called only once and that it should be inlined.
The documentation says that all optimizations are enabled by default, and that Proguard "Inline methods that are short or only called once".
Is there a specific flag I should give to Proguard to enable inlining?
EDIT
My proguard configuration file contains
-optimizationpasses 5
-allowaccessmodification
-overloadaggressively
-repackageclasses ''
-dontskipnonpubliclibraryclasses
EDIT
After using
-whyareyoukeeping class com.templatecompany.templateappname.EntryPointActivity {*;}
I get the reason why the method is not inlined:
[proguard] com.templatecompany.templateappname.EntryPointActivity: void testInlining() (20:21)
[proguard] is invoked by com.templatecompany.templateappname.EntryPointActivity: com.td.media.ivConnection.IvConfig getIvConfig() (14:15)
[proguard] implements com.td.widget.MainActivity: com.td.media.ivConnection.IvConfig getIvConfig()
[proguard] is invoked by com.td.widget.MainActivity: void onCreate(android.os.Bundle) (140:175)
[proguard] implements android.app.Activity: void onCreate(android.os.Bundle)
[proguard] is a library method.
But I am not sure to see how the fact that the method testInlining is used in the method getIvConfig which is in turn used by another method prevents the inlining on testInlining in getIvConfig.
This recent Android SDK disables all optimizations by default, see ${sdk.dir}/tools/proguard/proguard-android.txt:
-dontoptimize
The alternative optimizing configuration only disables a few optimizations, see ${sdk.dir}/tools/proguard/proguard-android-optimize.txt:
-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
You can specify your preferred configuration file in project.properties.
You can verify which complete configuration ProGuard is using by adding the option -printconfiguration.
Some optimizations have been disabled in order to avoid bugs in older versions of the Dalvik VM (!code/simplification/arithmetic,!code/simplification/cast), and some optimizations may have been disabled to avoid bugs in older versions of ProGuard (!field/*,!class/merging/*).
Note that -whyareyoukeeping refers to the shrinking step, which removes unnecessary classes/fields/methods as a whole. Methods that are not removed may be inlined in the optimization step (unless explicitly specified otherwise with -keep).
In your module's build.gradle file, you should look at:
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), file('proguard-project.txt')
signingConfig signingConfigs.release
}
}
and replace proguard-android.txt with proguard-android-optimize.txt, which doesn't include the -dontoptimize line while keeping the dalvik problems away (see Eric Lafortune's answer).

Categories

Resources