Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ClassLoader 源碼剖析:它和你以為的 Java ClassLoader 並不一樣

編輯:關於 Android 程式設計

1. 前言

讀這篇之前,請先具備 Java ClassLoader 的基本認知:雙親委派機制,以及 JDK 的三級 ClassLoader 結構。原因很簡單——Android 沿用了委派機制,卻沒有沿用那三級結構,而是自己改了一套。如果拿 Java 的直覺去套 Android,就會踩到一些怎么想都想不通的坑(作者本人就踩過)。

先看一段程式碼,加在 Application 的 onCreate() 裡:

PathClassLoader classLoader = (PathClassLoader) getApplicationContext().getClassLoader();
Log.d("mytest", "classLoader : " + classLoader + "\n"
        + "parent : " + classLoader.getParent() + "\n"
        + "grandParent : " + classLoader.getParent().getParent() + "\n"
        + "system classloader : " + ClassLoader.getSystemClassLoader() + "\n"
        + "system parent : " + ClassLoader.getSystemClassLoader().getParent());

輸出的結果:

classLoader : dalvik.system.PathClassLoader[dexPath=/data/app/com.gavin.demo2application-1.apk,libraryPath=/data/app-lib/com.gavin.demo2application-1]
parent : java.lang.BootClassLoader@41099128
grandParent : null
system classloader : dalvik.system.PathClassLoader[dexPath=.,libraryPath=null]
system parent : java.lang.BootClassLoader@41099128

這段輸出藏著四個值得追問的細節:

  • 專案實際使用的 ClassLoader 是自訂的 PathClassLoader,而它的 dexPath 決定了要載入哪些位置的類別。
  • 它的 parent 是 BootClassLoader——這是什麼?
  • ClassLoader.getSystemClassLoader() 回傳的也是 PathClassLoader,但 dexPath 是 .。在 Java 中,這個方法回傳的是載入 classpath 的「第三級」ClassLoader,內部是呼叫 sun.misc.Launcher 取得的。Android 顯然不是這麼運作。
  • 它的 parent 同樣是 BootClassLoader。這個類別出現率這麼高,必須查清。

2. Context.getClassLoader() 回傳的是 PathClassLoader

Android 可用的 ClassLoader 有兩種:PathClassLoader 只能載入 dex;DexClassLoader 則可載入 apk、dex、jar。

安裝 APK 之後,系統會在 /data/dalvik-cache 下產生一個 data@app@com.hujiang.xxx-1.apk@classes.dex 的 ODEX 檔(經過最佳化的 dex)。PathClassLoader 載入 APK 時就是到這裡找對應的 dex,而這也正是我們自己撰寫的專案所使用的 ClassLoader。

DexClassLoader 則被用來實作動態載入:直接載入外部 APK,達成完全解耦的模組化開發。開源方案如 DynamicLoadApk(以代理方式實現,實際載入的不是外掛中的類別)與 Drozer/DroidPlugin 系列(hook AMS 與 PMS)都建立在它之上。目前熱門的熱修復方案也與此相關:AndFix 在執行期把 Java 方法換成 native 方法,再修改呼叫該方法的指標指向修復版本;Nuwa(手Q 空間的方案)基於 dex 分包,透過調整 ClassLoader 中 dexElements 的順序來生效;美團的 Robust 則基於 Android Studio 的 Instant Run 原理,為每個類別建立代理類。

PathClassLoader 與 DexClassLoader 的源碼

public class PathClassLoader extends BaseDexClassLoader {
    public PathClassLoader(String dexPath, ClassLoader parent) {
        super(dexPath, null, null, parent);
    }

    public PathClassLoader(String dexPath, String libraryPath, ClassLoader parent) {
        super(dexPath, null, libraryPath, parent);
    }
}
public class DexClassLoader extends BaseDexClassLoader {
    public DexClassLoader(String dexPath, String optimizedDirectory,
                          String libraryPath, ClassLoader parent) {
        super(dexPath, new File(optimizedDirectory), libraryPath, parent);
    }
}

兩者都只是改寫了建構子,所有實作都在 BaseDexClassLoader 裡。四個參數的意義:

  • dexPath:要載入的 apk 或 jar 路徑。
  • optimizedDirectory:從 apk 解析出的 dex 存放位置(只有 DexClassLoader 需要,PathClassLoader 傳 null)。
  • libraryPath:類別所需的 C/C++ 原生庫路徑。
  • parent:真正的委派對象。
public BaseDexClassLoader(String dexPath, File optimizedDirectory,
                         String libraryPath, ClassLoader parent) {
    super(parent);
    this.pathList = new DexPathList(this, dexPath, libraryPath, optimizedDirectory);
}

super() 走的是一般 ClassLoader 設定 parent 的方式。重點是 pathList——它保存 dex 集合。由於 APK 支援 dex 分包,裡面會含有一組 DexElement,每個 Element 對應一個 dex 檔。

this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory, suppressedExceptions);

makeDexElements() 負責把 dex 檔解析成对应的 Element:

private static Element[] makeDexElements(ArrayList<File> files, File optimizedDirectory,
                                         ArrayList<IOException> suppressedExceptions) {
    ArrayList<Element> elements = new ArrayList<Element>();

    /*
     * 先將所有檔案(直接或內含的)dex 一口氣開啟並載入
     */
    for (File file : files) {   // 遍歷所有 dex 檔
        File zip = null;
        DexFile dex = null;     // 核心類別,負責把 dex 檔轉成 DexFile 物件
        String name = file.getName();

        if (name.endsWith(DEX_SUFFIX)) {
            // 純 dex 檔(不在 zip/jar 內)——對應 PathClassLoader 的情況
            try {
                dex = loadDexFile(file, optimizedDirectory);
            } catch (IOException ex) {
                System.logE("Unable to load dex file: " + file, ex);
            }
        } else if (name.endsWith(APK_SUFFIX) || name.endsWith(JAR_SUFFIX)
                || name.endsWith(ZIP_SUFFIX)) {
            // 對應 DexClassLoader 的情況
            zip = file;
            try {
                dex = loadDexFile(file, optimizedDirectory);
            } catch (IOException suppressed) {
                /*
                 * 若該 zip 其實只是資源檔(內含沒有 classes.dex),
                 * DexFile 建構子會拋 IOException,這是合理情況。
                 * 讓 dex == null,並保留例外,等 findClass 回傳 null 時一併處理。
                 */
                suppressedExceptions.add(suppressed);
            }
        } else if (file.isDirectory()) {
            // 僅支援用於查找資源的目錄,主要給 libcore 測試使用
            elements.add(new Element(file, true, null, null));
        } else {
            System.logW("Unknown file type for: " + file);
        }

        if ((zip != null) || (dex != null)) {
            elements.add(new Element(file, false, zip, dex));
        }
    }

    return elements.toArray(new Element[elements.size()]);
}

這段邏輯就是:遍歷所有 dex 檔,呼叫 DexFile 的 loadDex() 建立 DexFile 物件;其建構子內部會呼叫 openDexFile() 解析 dex,那是個 native 方法,由 C 實作,此處不展開。

順帶一提,AndFix 就是直接使用 DexFile 載入 dex,而沒有經過 DexClassLoader,有興趣可以對照它的源碼。

3. 為什麼 Context.getClassLoader() 回傳 PathClassLoader

getApplicationContext() 回傳的實作類是 ContextImpl,來看它的 getClassLoader():

public ClassLoader getClassLoader() {
    return mPackageInfo != null
            ? mPackageInfo.getClassLoader()
            : ClassLoader.getSystemClassLoader();
}

如果 mPackageInfo 不為 null 就呼叫它的同名方法,否則退回 getSystemClassLoader()。重點在 mPackageInfo 這個物件——它是一個 LoadedApk。官方文件的描述是「目前己載入 apk 的本地狀態」,也就是 APK 在記憶體中的表示。透過它能取得 apk 內的程式碼與資源,甚至 Activity、Service 等資訊。

它何時建立?如果你了解 Activity 的啟動流程就不難回答。在 ActivityThread 中有一個 mPackages 的 Map 成員,以 packageName 為索引快取 LoadedApk。啟動 Activity 時需要呼叫 LoadedApk.getClassLoader() 載入對應的 class,再以反射建立 Activity 實例;取得該物件時會先查快取,未命中才建立新的。

public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai, CompatibilityInfo compatInfo) {
    return getPackageInfo(ai, compatInfo, null, false, true, false);
}
private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
                                 ClassLoader baseLoader, boolean securityViolation,
                                 boolean includeCode, boolean registerPackage) {
    final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
    synchronized (mResourcesManager) {
        WeakReference<LoadedApk> ref;
        if (differentUser) {
            ref = null;     // 跨使用者不支援快取
        } else if (includeCode) {
            ref = mPackages.get(aInfo.packageName);
        } else {
            ref = mResourcePackages.get(aInfo.packageName);
        }
        LoadedApk packageInfo = ref != null ? ref.get() : null;
        if (packageInfo == null || (packageInfo.mResources != null
                && !packageInfo.mResources.getAssets().isUpToDate())) {
            // 快取未命中,直接建立新的
            packageInfo = new LoadedApk(this, aInfo, compatInfo, baseLoader,
                    securityViolation,
                    includeCode && (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0,
                    registerPackage);
            // 其餘程式碼省略:更新快取
            return packageInfo;
        }
        // ...
    }
}

接著看 LoadedApk 的建構子(另一個建構子在 ContextImpl 建立自身實例時會用到):

public LoadedApk(ActivityThread activityThread, ApplicationInfo aInfo,
                 CompatibilityInfo compatInfo, ActivityThread mainThread,
                 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
    // ...(省略)

    if (mAppDir == null) {
        if (ActivityThread.mSystemContext == null) {
            // 一個 ActivityThread 只有一個 mSystemContext,靜態全域
            ActivityThread.mSystemContext = ContextImpl.createSystemContext(mainThread);
            ActivityThread.mSystemContext.getResources().updateConfiguration(
                    mainThread.getConfiguration(),
                    mainThread.getDisplayMetricsLocked(compatInfo, false),
                    compatInfo);
        }
        mClassLoader = ActivityThread.mSystemContext.getClassLoader();
        mResources = ActivityThread.mSystemContext.getResources();
    }
}

可見 ClassLoader 最終來自 ActivityThread.mSystemContext。它的建立過程是:

static ContextImpl createSystemContext(ActivityThread mainThread) {
    ContextImpl context = new ContextImpl();
    context.init(Resources.getSystem(), mainThread);   // 此 init 並未建立 LoadedApk 成員
    return context;
}

於是又回到最初的 ContextImpl.getClassLoader(),而此時 mPackageInfo 為 null,因此走的是 ClassLoader.getSystemClassLoader() 這條路。結論:系統 ClassLoader 是由 getSystemClassLoader() 產生的。

4. 揭開 getSystemClassLoader() 在 Android 中的面紗

public static ClassLoader getSystemClassLoader() {
    return SystemClassLoader.loader;
}
static private class SystemClassLoader {
    public static ClassLoader loader = ClassLoader.createSystemClassLoader();
}
private static ClassLoader createSystemClassLoader() {
    String classPath = System.getProperty("java.class.path", ".");
    return new PathClassLoader(classPath, BootClassLoader.getInstance());
}

官方對最後這個方法的說明值得細讀:這不是 bootstrap ClassLoader(由虛擬機管理),而系統以 null 作為 parent 表達「bootstrap 才是我們的 parent」。

換句話說,Android 沒有採用 Java 原生的 bootstrap 來載入,而是自建了一套機制:以 null 取代 bootstrap(bootstrap 本身不是 ClassLoader 物件,所以其子級呼叫 getParent() 得到 null),並以 Android 自己建立的 BootClassLoader 取代 Java 的第二級。這個 BootClassLoader 是單例,全域只有一個:

public BootClassLoader() {
    super(null, true);   // parent 為 null,模擬其父級是 bootstrap
}

因此系統中所有載入類別的動作,最終都會走到這個物件。

最後一個問題:createSystemClassLoader() 傳入的第一個參數就是先前印出的 dexPath,為什麼系統自己建立的 PathClassLoader 指向當前 APK 的安裝路徑,而我們透過 getSystemClassLoader() 拿到的卻是 .?答案在 System.getProperty("java.class.path", ".") 這行——有 get 就有 set。這個值是在 Android framework 的 System 類的 initSystemProperties() 中設定的,來源是 VMRuntime.getRuntime().classPath(),也就是當前 APK 的安裝路徑:

// 路徑:libcore/luni/src/main/java/java/lang/System.java(4.0.4)
private static void initSystemProperties() {
    VMRuntime runtime = VMRuntime.getRuntime();
    Properties p = new Properties();
    p.put("java.boot.class.path", runtime.bootClassPath());
    p.put("java.class.path", runtime.classPath());
}

那為什麼我們自己呼叫時拿到的是 .?個人推測是系統在建立好對應的 ClassLoader 之後,把这个屬性改回了 .,但確切原因仍有待查證。

5. 總結

  1. Android 系統最頂層的 ClassLoader 是 BootClassLoader(取代 Java 的第二級 ext ClassLoader),而載入系統類別的是以它為 parent 的 PathClassLoader(取代 Java 第三級、負責載入 classpath 的那一層)。
  2. 系統 PathClassLoader 的 dexPath 指向當前 APK 安裝路徑,再由 DexFile 解析該 dex 並載入其中的類別。
  3. DexClassLoader 主要用於載入外部外掛,可以直接載入 APK。當前的外掛化動態載入、熱修復都依賴這個特性;當然,直接用 DexFile 載入 dex 也行(AndFix 就是這樣做)。
  4. 作者親身踩過的坑:學習動態化時,自己建立了一個 DexClassLoader,並把 parent 設為系統的 PathClassLoader(也就是 context.getClassLoader()),結果載入外部 APK 中的類別時拋出 ClassNotFoundException,訊息指在系統 APK 產生的 ODEX 中找不到該類別。原因就在於傳入的 parent 的 dexPath 指向系統 APK 路徑,自然會往那裡找。若改傳 ClassLoader.getSystemClassLoader(),因為它的 dexPath 是 .(一個目錄而非檔案),不會建立 DexFile,也就不會走 loadDexFile(),而是直接委派給 parent 也就是 BootClassLoader 的 findClass()。

理解這條委派鏈之後,動態載入與熱修復的各種方案為什麼那樣設計,基本都能自行推導出來。文章難免有疏漏,歡迎指正。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved