Preface

Many developers think it’s a problem with Xamarin.Android, but they aren’t aware of what really happens with third party libraries and their applications.

To clear up that muck, let’s first talk about the general process.

Typically when you have an external library, those libraries have their own manifests. Those manifests can have various <uses-permission> elements inside, or they can even specify them inside the AssemblyInfo.cs like the following:

Either way, these permissions will get inserted into an AndroidManifest.xml at the end of the day for that library and then eventually into your application’s AndroidManifest.xml.

Manifest Merging

What do we know about Android development thus far? Well we know that each .apk file can only have oneAndroidManifest.xml defined. Thus that means at the end of the day, everything needs to merge into a master AndroidManifest.xml.

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file provides essential information about your app to the Android system, which the system must have before it can run any of the app’s code.

Great! Now we are one step ahead of the game and can understand a little bit about the Android build process. However that brings us to a little rut…Does Xamarin.Android follow the same build process as say native Android?

The answer is no. They both have their own unique build processes and thus not everything we learn about native Android can be converted directly to Xamarin.Android. In this specific case, if we learned about how native Android merges multiple manifest files we would find out that this is done via Gradle and not MSBuild which Xamarin.Android uses under the hood.

Example

Let’s take a File -> New Blank Android Project. Let’s rebuild it from the start and see a final AndroidManifest.xml. We would find this file in the obj\Debug\android\AndroidManifest.xml:

Why ProGuard?

ProGuard detects and removes unused classes, fields, methods, and attributes from your packaged application. It can even do the same for referenced libraries which can help you avoid the 64k reference limit.

The ProGuard tool from the Android SDK will also optimize the bytecode, remove unused code instructions, and obfuscates the remaining classes, fields, and methods with short names.

There are four optional steps that ProGuard uses:

In the shrinking step, ProGuard starts from these seeds and recursively determines which classes and class members are used. All other classes and class members are discarded.

In the optimization step, ProGuard further optimizes the code. Among other optimizations, classes and methods that are not entry points can be made private, static, or final, unused parameters can be removed, and some methods may be inlined.

In the obfuscation step, ProGuard renames classes and class members that are not entry points. In this entire process, keeping the entry points ensures that they can still be accessed by their original names.

The preverification step is the only step that doesn’t have to know the entry points.

ProGuard reads input jars in which it will shrink, optimize, obfuscate, and preverify them. ProGuard will then write these results to one or more output jars.

The Xamarin.Android ProGuard configuration does not obfuscate the .apk and it is not possible to enable obfuscation through ProGuard even through the use of custom configuration files. Thus Xamarin.Android’s ProGuard will only run the shrinking step.

How does ProGuard work with Xamarin.Android

One important item to know ahead of time before using ProGuard is how it works within the Xamarin.Android build process. This can be thought of in two separate steps:

Xamarin Android Linker

Proguard

Xamarin.Android Linker

First, the linker employs static analysis of your application to determine which assemblies are actually used, which types are actually used, and which members are actually used. It will always run before the ProGuard step. Because of this, the linker can strip an assembly/type/member that you might expect ProGuard to run on.

Proguard

Secondly, ProGuard will then run and remove unused Java bytecode to optimize the .apk. (shrinking step)

Enabling ProGuard

ProGuard can be enabled by checking the Enable Proguard option inside of your Packaging Properties. You must also ensure your project is set to the Release configuration as the Linker must run in order for ProGuard to run.

Optional: You can add a custom ProGuard Configuration file for more control with the ProGuard tooling. To do this, you can create a new .cfg file and apply the build action of ProguardConfiguration.

Customize which code to keep

For majority of situations, the default ProGuard configuration file that Xamarin.Android provides will be sufficient to remove all-and only-the unused code.

You can find the default ProGuard Configuration File at obj\Release\proguard\proguard_xamarin.cfg if you wanted to see what by default is added to the configuration.

There was a great question the other day. I figured I’d blog about this for others trying to figure out the answer.

How does one invoke a SIGABRT on a device?

For those unfamiliar with what a SIGABRT is, here’s the definition from wikipedia:

SIGABRT is sent by the process to itself when it calls the abort libc function, defined in stdlib.h. The SIGABRT signal can be caught, but it cannot be blocked; if the signal handler returns then all open streams are closed and flushed and the program terminates (dumping core if appropriate). This means that the abort call never returns. Because of this characteristic, it is often used to signal fatal conditions in support libraries, situations where the current operation cannot be completed but the main program can perform cleanup before exiting. It is used when an assertion fails.

How does one invoke a SIGABRT signal in Xamarin on both iOS and Android?

Seeing that we already found out the answer via these stack overflow links, we might want to dig in a little further to the actual potential library call we want to use. In our case, we want to look at abort():

Aborts the current process, producing an abnormal program termination.

The function raises the SIGABRT signal (as if raise(SIGABRT) was called). This, if uncaught, causes the program to terminate returning a platform-dependent unsuccessful termination error code to the host environment.

Perfect! This is exactly what we need to call into. The next question is…How do we do that?

Based on the Xamarin iOS documentation, we are introduced into the world of P/Invoke(We can assume the same for Xamarin Android as well):

Determine which C function you want to invoke

Determine its signature

The signature for this call is fairly straight forward. It’s void and it has 0 arguments. We can define the structure as the following:

static extern void abort ();

Determine which library it lives in

This is the tough one. Especially for those of us who have not dwelled into the native library side of things for awhile. Let’s use Github as a tool here to see if there’s previous examples. My first search is using DllImport to see examples of this in the Xamarin.iOS / Mac repository.

Certain language features can be hard to port over (Reflection, Anonymous Inner Classes, Enums, etc)

Create a Xamarin.Android Binding Project:

This scenario basically allows the Xamarin.Android Binding Generator do all the work for you. In most simple cases it works quite well, but in more complicated cases, you might end up pulling out your hair.

Pros

Easy to generate a quality binding without writing much code

Ability to transform the binding how you see fit to match C# conventions

Today we are going to talk about the basic mechanics of the classes.dex file and how multidex handles more than 65k methods.

The classes.dex file is used as a main dex list in your application. It houses all of the classes needed for your application. An APK requires at least one classes.dex(DEX) file which has all the executable code of our application stored inside. The size of a DEX file’s method index is 16-bit which means (2^16) or 65,536 total references a single dex list can have.

However we run into scenarios where we surpass the 65,536 reference count. This is when we need to enable multidex which gives us overfill classes.dex files in the form of classes{n}.dex where n >= 1.

Now we can have as many classes/references as we desire since our application can grow over time. Let’s talk about some of the disadvantages to this however:

1) Multidex tries it’s best to know what dependencies are needed at startup. Since it only loads the main dex list classes.dex at first, you will need to ensure any startup classes/references are inside the MainDexList(classes.dex) or you will crash at startup.

2) Secondary DEX files will be added to the classloader after Multidex is initialized via install(Context) or the other two ways I described in the previous blog article - Multidex in Xamarin.Android.

3) Multidex doesn’t efficiently store classes/references to the max count in each list it creates. It’ll try it’s best however.

Okay cool, we have a rundown of what’s going on, but let’s dig a little deeper to the tooling that generates a DEX list. Let’s introduce our friend dx which is a command line tool to generate respective .dex files. There’s a couple parameters we want to keep in mind.

1) --multi-dex: This will enable multidex and create 1 or more classes{n}.dex files.

2) --main-dex-list=<file>: This will parse through a list of class file names in which classes defined will be put in the classes.dex file.

3) --minimal-main-dex: Certain classes selected by --main-dex-list above will be put in the main DEX list(classes.dex)

Typical Issues

1) Custom Application class is not found on dexPathList:

This is very straight forward now that we know what’s going on with multidex. Simply put, our custom application class is not being put on the main classes.dex list. Therefore it cannot even open the entrypoint of the application nor initialize the secondary DEX lists.

2) Other classes needed at startup are not found on dexPathList:

This is also quite straight forward. You might have a framework dependency such as MVVMCROSS or other items that register at startup which need to be on the main classes.dex list.

How to investigate Multidex issues

There is really one tool that is needed now-a-days to investigate the behavior. That tool is classyshark:

This tool can read either .dex or .apk files. Since we are primarily dealing with .dex files, we can directly drag and drop them into classyshark to see all of the classes listed, and also the total method count.

You could technically go further into reading about dx tooling, but it’s not really worth going that far into unless there’s a critical bug. Google recommends: As a general rule, you should rely on the build tools to call them as needed.

Overriding the main dex list(classes.dex)

Xamarin.Android now offers a simple way to override this list. You can do the following:

1) Create a new Text file in your main application root. (Name it multidex.keep)

2) Set the Build Action to MultiDexMainDexList

3) Include any classes you want on the main dex list inside

Note: It’s always a good idea to see a previous multidex.keep file in your obj\Debug folder for a reference.