Search code examples
androidreverse-engineeringsmaliapktool

ApkTool splits java files in to multiple files


Im using ApkTool to dessasemble DEX files from an APK to recover smali code. I have noticed that the .java file has been splitted in different files.

For example:

  • MainActivity.java -> MainActivity.smali, MainActivity$1.smali
  • FirstFragment.java -> FirstFragment.smali, FirstFragment$1.smali, FirstFragment$2.smali

Is there a reason for why this happens?

I have an additional question in relation to that: why do the first lines of those files have different content if they reference the same file? They both reference the source "MainActivity.java" but have different classes.

MainActivity$1.smali

.class Lcom/example/testapp/MainActivity$1;
.super Ljava/lang/Object;
.source "MainActivity.java"

MainActivity.smali

.class public Lcom/example/testapp/MainActivity;
.super Landroidx/appcompat/app/AppCompatActivity;
.source "MainActivity.java"

Solution

  • A .smali file is created for a single Java class. A .java file can include several Java classes either explicitly, or implicitly. Explicitly - can be for an inner class; implicitly - e.g. to create a Thread (with an anonymous class). Consider:

    package Abc;
    
    class Foo {
      class Bar {}
    }
    

    Internally, fully resolved class names would be Abc/Foo and Abc/Foo$Bar. Note the $ sign that separates inner class name. It can go on, like Abc/Foo$Bar$Func. Anonymous classes simply get numbers for names, like Abc/Foo$1 and Abc/Foo$1$1.

    Now Apktool and baksmali behind the scene use the fully resolved class name for a file path and name.


    (*) Usually, every Java class is put into a file of its own with file name and path matching the package name and self name of that class. This is a convention. Given only one class is public, other can appear in the same file - Multiple classes in single file.