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

Android 5.0 之後,系統如何決定一個 apk 跑 32 位還是 64 位

編輯:關於 Android 開發

問題從哪裡來

Android 5.0 開始支援 64 位,於是同一顆 apk 到底跑在哪個位數的進程裡,就變成一件需要被明確決定的事。這篇文章從編譯配置一路追到 PackageManagerService 的掃描流程,把整條判定鏈攤開來看。

一、編譯階段:先宣告系統支援哪些位數

產品的 core_64_bit.mk 裡做了幾件事。首先是繼承硬體相關配置與通用配置:

$(call inherit-product, device/skyworth/sky828_8s70/device.mk)
$(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
$(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_base.mk)

接著把 64 位為主、32 位為輔的 zygote 啟動腳本複製進來,並設定屬性:

PRODUCT_COPY_FILES += system/core/rootdir/init.zygote64_32.rc:root/init.zygote64_32.rc
PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.zygote=zygote64_32

TARGET_SUPPORTS_32_BIT_APPS := true
TARGET_SUPPORTS_64_BIT_APPS := true

這裡有個關鍵轉變。在 L 之前,zygote 是直接在 init.rc 裡啟動的:

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
    class main
    socket zygote stream 660 root system

但 L 之後可能有兩個 zygote,於是啟動腳本被抽成獨立檔案,由 init.rc 依 ro.zygote 的值動態 include:

import /init.environ.rc
import /init.usb.rc
import /init.${ro.hardware}.rc
import /init.${ro.zygote}.rc
import /init.trace.rc

而 zygote64_32.rc 裡則定義了兩個服務:

service zygote /system/bin/app_process64 -Xzygote /system/bin \
    --zygote --start-system-server --socket-name=zygote
    class main
    socket zygote stream 660 root system

service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin \
    --zygote --socket-name=zygote_secondary
    class main
    socket zygote_secondary stream 660 root system

一個用 64 位的 app_process64,一個用 32 位的 app_process32,socket 名稱分別是 zygote 與 zygote_secondary,前者是 primary。

由於所有應用進程都是從 zygote fork 出來的,而 fork 會繼承父進程的屬性,子進程的位數必然與父進程一致。這也給了我們一個實用的檢查方法:想知道某個 apk 跑幾位,看它的父進程是哪個 zygote 就知道了。

二、啟動進程:abi 決定一切

最終啟動應用的入口是 ActivityManagerService.startProcessLocked,開頭就是這幾行:

String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;

if (requiredAbi == null) {
    requiredAbi = Build.SUPPORTED_ABIS[0];
}

這裡藏著一個很多人不知道的結論。primaryCpuAbi 是安裝 apk 時就計算並記錄下來的:如果 apk 帶有符合規範的 native 庫,這個值就有內容;但如果是一個純 Java、完全沒有 native lib 的 apk,它就是 null。

而 null 的時候,系統會拿 Build.SUPPORTED_ABIS[0] 來用。在以 64 位為主的系統上,這個清單是:

shell@sky828_8s70:/ # getprop ro.product.cpu.abilist
arm64-v8a,armeabi-v7a,armeabi

第一位是 arm64-v8a。所以純 Java 的 apk 在 64 位系統上一定跑 64 位進程,這不是巧合,而是這個 fallback 邏輯的直接結果。

接著由 abi 換算出指令集:

String instructionSet = null;
if (app.info.primaryCpuAbi != null) {
    instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
}

兩者的對應關係很單純:arm64-v8a → arm64;armeabi-v7a 與 armeabi → arm。

然後才真正呼叫 Process.start,把 abi 與 instructionSet 一起帶下去:

Process.ProcessStartResult startResult = Process.start(entryPoint,
        app.processName, uid, uid, gids, debugFlags, mountExternal,
        app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
        app.info.dataDir, entryPointArgs);

往下會走到 zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote),而 openZygoteSocketIfNeeded 就是挑選 zygote 的地方:

private static ZygoteState openZygoteSocketIfNeeded(String abi)
        throws ZygoteStartFailedEx {

    if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
        primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
    }
    if (primaryZygoteState.matches(abi)) {
        return primaryZygoteState;      // primary 支援這個 abi,就用它
    }

    if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
        secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET);
    }
    if (secondaryZygoteState.matches(abi)) {
        return secondaryZygoteState;
    }

    throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}

邏輯一目了然:先問 primary,不支援才問 secondary,兩邊都不行就拋例外。

三、zygote 怎麼知道自己支援哪些 abi

判斷的依據是 matches:

boolean matches(String abi) {
    return abiList.contains(abi);
}

而 abiList 是透過 socket 向 zygote 問出來的:

public static ZygoteState connect(String socketAddress) throws IOException {
    final LocalSocket zygoteSocket = new LocalSocket();
    zygoteSocket.connect(new LocalSocketAddress(socketAddress,
            LocalSocketAddress.Namespace.RESERVED));

    DataInputStream zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
    BufferedWriter zygoteWriter = new BufferedWriter(
            new OutputStreamWriter(zygoteSocket.getOutputStream()), 256);

    String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
    return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
            Arrays.asList(abiListString.split(",")));
}

private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
        throws IOException {
    writer.write("1"); writer.newLine();              // 參數個數
    writer.write("--query-abi-list"); writer.newLine(); // 唯一參數
    writer.flush();

    int numBytes = inputStream.readInt();
    byte[] bytes = new byte[numBytes];
    inputStream.readFully(bytes);
    return new String(bytes, StandardCharsets.US_ASCII);
}

而服務端在 zygote 啟動時,會依自身位數讀取不同的系統屬性:

#ifdef __LP64
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64";
static const char ZYGOTE_NICE_NAME[]  = "zygote64";
#else
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32";
static const char ZYGOTE_NICE_NAME[]  = "zygote";
#endif

在以 64 位為主的系統上,這兩個屬性的值是:

shell@sky828_8s70:/ # getprop ro.product.cpu.abilist64
arm64-v8a
shell@sky828_8s70:/ # getprop ro.product.cpu.abilist32
armeabi-v7a,armeabi

在 app_process 的 main 函式中,zygote 模式會把屬性讀出來,組裝成 --abi-list= 參數傳進 Java 層:

char prop[PROP_VALUE_MAX];
if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
    LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
                     ABI_LIST_PROPERTY);
    return 11;
}
String8 abiFlag("--abi-list=");
abiFlag.append(prop);
args.add(abiFlag);

最後透過 runtime.start("com.android.internal.os.ZygoteInit", args) 進入 Java 層,在 ZygoteInit.main 中把這個參數解析出來並註冊 socket:

boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;

for (int i = 1; i < argv.length; i++) {
    if ("start-system-server".equals(argv[i])) {
        startSystemServer = true;
    } else if (argv[i].startsWith(ABI_LIST_ARG)) {
        abiList = argv[i].substring(ABI_LIST_ARG.length());
    } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
        socketName = argv[i].substring(SOCKET_NAME_ARG.length());
    }
}
if (abiList == null) {
    throw new RuntimeException("No ABI list supplied.");
}
registerZygoteSocket(socketName);

至此,客戶端透過 socket 查到的那串 abi,來源就是這裡。整個迴路閉合了。

四、安裝階段:PackageManagerService 的解析流程

另一個關鍵環節是安裝。PMS 在 system_server 中啟動:

mPackageManagerService = PackageManagerService.main(mSystemContext, mInstaller,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();

這裡的 isFirstBoot 判斷系統是否首次啟動(恢復出廠設定後再開機也算首次)。為什麼首次開機安裝 apk 時沒有那種一個個最佳化的等待畫面?就是因為掃描時用了延遲策略:

// 掃描安裝目錄時不逐一最佳化,先收集到待處理清單
final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;

掃描系統 app 目錄的入口:

final File systemAppDir = new File(Environment.getRootDirectory(), "app");
scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
        | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);

注意 L 之後 apk 的存放形式多了一層目錄,例如 /system/app/helloworld/helloworld.apk。所以 scanDirLI 列出來的其實是目錄而非檔案,判斷條件也相應調整:

final File[] files = dir.listFiles();
for (File file : files) {
    final boolean isPackage = (isApkFile(file) || file.isDirectory())
            && !PackageInstallerService.isStageName(file.getName());
    if (!isPackage) continue;
    scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
                  scanFlags, currentTime, null);
}

五、parsePackage:從檔案到 Package 物件

進入 scanPackageLI 後,會先建立 PackageParser 並呼叫 pp.parsePackage(scanFile, parseFlags)。這個方法開頭就分岔了:

public Package parsePackage(File packageFile, int flags) throws PackageParserException {
    if (packageFile.isDirectory()) {
        return parseClusterPackage(packageFile, flags);   // 我們走這裡
    } else {
        return parseMonolithicPackage(packageFile, flags);
    }
}

因為傳進來的是目錄,所以走 cluster 分支:

private Package parseClusterPackage(File packageDir, int flags)
        throws PackageParserException {

    final PackageLite lite = parseClusterPackageLite(packageDir, 0);

    final AssetManager assets = new AssetManager();
    try {
        loadApkIntoAssetManager(assets, lite.baseCodePath, flags);
        for (String path : lite.splitCodePaths) {
            loadApkIntoAssetManager(assets, path, flags);
        }

        final Package pkg = parseBaseApk(new File(lite.baseCodePath), assets, flags);
        pkg.codePath = packageDir.getAbsolutePath();
        return pkg;
    } finally {
        IoUtils.closeQuietly(assets);
    }
}

這裡出現了兩個容易混淆的型別,值得說清楚:

PackageLite 是輕量級的套件資訊,只保存套件名、版本號、安裝位置、base apk 路徑、split 相關資訊、是否 core app、是否 multiArch 等少數欄位。Package 則是完整資訊,包含四大元件的完整清單:

public static final class Package {
    public String packageName;
    public String codePath;
    public String baseCodePath;
    public final ApplicationInfo applicationInfo = new ApplicationInfo();
    public final ArrayList<Activity> activities = new ArrayList<>(0);
    public final ArrayList<Activity> receivers  = new ArrayList<>(0);
    public final ArrayList<Service>  services   = new ArrayList<>(0);
    public final ArrayList<Provider> providers  = new ArrayList<>(0);
    // 還有權限、instrumentation、requestedPermissions 等
}

parseClusterPackageLite 做的事是遍歷目錄、逐一解析每個 apk 的精簡資訊,並驗證它們的套件名與版本號一致,最後組出 PackageLite:

for (File file : files) {
    if (isApkFile(file)) {
        final ApkLite lite = parseApkLite(file, flags);
        // 所有 split 的 packageName 與 versionCode 必須一致
        if (apks.put(lite.splitName, lite) != null) {
            throw new PackageParserException(..., "Split name defined more than once");
        }
    }
}
final ApkLite baseApk = apks.remove(null);   // splitName 為 null 的就是 base
return new PackageLite(codePath, baseApk, splitNames, splitCodePaths);

對一般的 apk 來說,splitNames 與 splitCodePaths 都是 null,因為沒有做 split。

而 parseBaseApk 才是真正解析 AndroidManifest 的地方,權限、四大元件都在這裡被讀出來。核心的元件分派邏輯在 parseBaseApplication 中:

String tagName = parser.getName();
if (tagName.equals("activity")) {
    Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false,
                               owner.baseHardwareAccelerated);
    owner.activities.add(a);
} else if (tagName.equals("receiver")) {
    owner.receivers.add(parseActivity(owner, res, parser, attrs, flags, outError, true, false));
} else if (tagName.equals("service")) {
    owner.services.add(parseService(owner, res, parser, attrs, flags, outError));
} else if (tagName.equals("provider")) {
    owner.providers.add(parseProvider(owner, res, parser, attrs, flags, outError));
}

四個分支分別把解析結果加進 Package 物件對應的四個清單裡,manifest 的解析到此完成。

整理一下這條鏈

把整個判定串起來:編譯階段透過 mk 檔決定系統支援的 abi 清單與要啟動哪個 zygote 腳本;啟動階段 zygote 讀取 abilist64 或 abilist32 屬性,透過 --abi-list 參數告知 Java 層;安裝階段 PMS 解析 manifest 並記下每個 apk 的 primaryCpuAbi;運行階段 AMS 取用這個 abi,先問 primary zygote、再問 secondary,fork 出對應位數的子進程。

而最實用的一條結論是:純 Java 的 apk 因為 primaryCpuAbi 為 null,會 fallback 到 SUPPORTED_ABIS[0],在 64 位系統上必然跑 64 位進程。如果你的專案裡有假設「自己是 32 位」的程式碼,在 64 位裝置上就該重新檢查一遍。

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