主题
app_process(应用进程入口) · 源码分析
逐文件注释源码
以下为 app_process.cpp 全文(frameworks/base/cmds/app_process,共 519 行)。源码已含详细的中文行注释、方法注释与类注释——包括文件/类级说明、每个方法前的 Javadoc 块(含参数、返回值与处理逻辑)、以及代码行尾的 // 行内注释。按逻辑结构分为 6 节展示:
一、文件说明与头文件导入
文件头注释说明了 app_process 的定位:启动解释型运行时(虚拟机),然后启动应用程序。随后是一组头文件导入——binder/hwbinder 的 IPCThreadState(线程池启停)、cutils/properties(读系统属性)、AndroidRuntime(虚拟机生命周期框架)等,并进入 android 命名空间。
cpp
/*
* Main entry of app process.
* 应用进程的主入口。
*
* Starts the interpreted runtime, then starts up the application.
* 启动解释型运行时(虚拟机),然后启动应用程序。
*
* 本文件是 Android 系统中 app_process 进程的入口点,负责:
* 1. 解析命令行参数,区分 Zygote 模式与普通应用模式
* 2. 初始化 Dalvik/ART 虚拟机
* 3. 根据模式启动 ZygoteInit 或 RuntimeInit
*/
#define LOG_TAG "appproc"
#include <stdio.h>
#include <stdlib.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <android-base/macros.h>
#include <binder/IPCThreadState.h>
#include <hwbinder/IPCThreadState.h>
#include <utils/Log.h>
#include <cutils/memory.h>
#include <cutils/properties.h>
#include <cutils/trace.h>
#include <android_runtime/AndroidRuntime.h>
#include <private/android_filesystem_config.h> // for AID_SYSTEM
namespace android {二、app_usage 与 AppRuntime 类(构造函数 / setClassNameAndArgs)
app_usage 在参数错误时打印用法。AppRuntime 继承 AndroidRuntime,是 app_process 专用的运行时封装:构造函数把参数块起始地址与大小交给父类保存(供 setArgv0 改进程名用);setClassNameAndArgs 保存主类名与传给 Java main 的参数列表。
cpp
/**
* 打印 app_process 命令行用法信息。
*
* 当用户未提供必要的启动参数(既未指定 --zygote 也未指定主类名)时,
* 向标准错误输出打印正确的命令行格式提示。
*
* @return void 无返回值
* @note 该函数仅在启动参数错误时被调用
*/
static void app_usage()
{
fprintf(stderr,
"Usage: app_process [java-options] cmd-dir start-class-name [options]\n");
}
/**
* AppRuntime 类 - 应用运行时环境封装类。
*
* 继承自 AndroidRuntime,专门用于 app_process 进程的启动管理。
* 该类封装了应用启动所需的关键信息(类名、参数列表、JNI 类引用),
* 并重写了父类的多个生命周期回调方法,以处理不同启动阶段的事务。
*
* 主要功能:
* 1. 在虚拟机创建时预加载目标类(解决 JNI FindClass 类加载器限制问题)
* 2. 在运行时启动后初始化 Binder 线程池并调用 Java main 方法
* 3. 处理 Zygote 模式的特殊初始化逻辑
* 4. 管理进程退出时的资源清理
*
* @see AndroidRuntime 父类,提供虚拟机初始化的基础框架
*/
class AppRuntime : public AndroidRuntime
{
public:
/**
* 构造函数。
*
* 初始化 AppRuntime 实例,调用父类构造函数保存原始参数块信息,
* 并将目标类引用初始化为 NULL。
*
* @param argBlockStart char* 指向参数块起始地址的指针(通常为 argv[0])
* @param argBlockLength size_t 参数块的总长度(字节数)
* @return 无返回值(构造函数)
*/
AppRuntime(char* argBlockStart, const size_t argBlockLength)
: AndroidRuntime(argBlockStart, argBlockLength) // 调用父类构造函数,保存参数块信息
, mClass(NULL) // 初始化 JNI 类引用为 NULL,表示尚未加载目标类
{
}
/**
* 设置目标类名及传递给该类的命令行参数。
*
* 将解析得到的主类名和剩余参数保存到成员变量中,
* 供后续 onStarted 阶段调用 Java main 方法时使用。
*
* @param className const String8& 要启动的 Java 主类全限定名(如 com.android.commands.am.Am)
* @param argc int 参数个数
* @param argv char* const* 参数数组指针
* @return void 无返回值
*/
void setClassNameAndArgs(const String8& className, int argc, char * const *argv) {
mClassName = className; // 保存类名到成员变量
for (int i = 0; i < argc; ++i) { // 遍历所有参数
mArgs.add(String8(argv[i])); // 将每个参数转换为 String8 并添加到参数列表
}
}三、AppRuntime 的四个生命周期回调(onVmCreated / onStarted / onZygoteInit / onExit)
AndroidRuntime.start() 在虚拟机生命周期的关键节点回调这四个虚函数,AppRuntime 重写它们挂上自己的逻辑:onVmCreated 提前 FindClass 加载主类(避开 JNI 类加载器限制);onStarted 启动 Binder 线程池后 callMain 进 Java;onZygoteInit 只起 Binder 线程池;onExit 做退出清理。
cpp
/**
* 虚拟机创建完成后的回调方法(重写自 AndroidRuntime)。
*
* 关键说明:这里需要提前调用 FindClass 查找目标类,是因为 JNI 的 FindClass
* 使用的是与当前正在执行 native 方法关联的类加载器。如果在 onStarted 阶段
* (从 RuntimeInit.finishInit 调用,例如启动 "am" 命令时)调用 FindClass,
* 它会认为我们是从启动类(boot class)的 native 方法中调用的,
* 因此不会在 CLASSPATH 中查找我们要找的类。不幸的是,它需要在 CLASSPATH 中查找,
* 因为 "am" 等类不是启动类。
*
* 最简单的修复方法是在这里(onVmCreated)尽早调用 FindClass,
* 在我们开始执行启动类 Java 代码并因此失去对非启动类的访问权限之前。
*
* @param env JNIEnv* JNI 环境指针,用于调用 JNI 函数
* @return void 无返回值
* @note 如果是 Zygote 模式(mClassName 为空),直接返回不做任何操作
*/
virtual void onVmCreated(JNIEnv* env)
{
if (mClassName.empty()) { // 检查类名是否为空
return; // Zygote. Nothing to do here. // Zygote 模式无需在此加载类,直接返回
}
/*
* This is a little awkward because the JNI FindClass call uses the
* class loader associated with the native method we're executing in.
* If called in onStarted (from RuntimeInit.finishInit because we're
* launching "am", for example), FindClass would see that we're calling
* from a boot class' native method, and so wouldn't look for the class
* we're trying to look up in CLASSPATH. Unfortunately it needs to,
* because the "am" classes are not boot classes.
*
* The easiest fix is to call FindClass here, early on before we start
* executing boot class Java code and thereby deny ourselves access to
* non-boot classes.
*/
// 将类名中的点号(.)转换为斜杠(/),得到 JNI 内部类名格式
char* slashClassName = toSlashClassName(mClassName.c_str());
// 使用 JNI FindClass 查找目标类,返回局部引用
mClass = env->FindClass(slashClassName);
if (mClass == NULL) { // 检查类是否查找成功
ALOGE("ERROR: could not find class '%s'\n", mClassName.c_str()); // 打印错误日志
}
free(slashClassName); // 释放转换后的类名字符串内存
// 将局部引用转换为全局引用,防止在后续调用中被 GC 回收
mClass = reinterpret_cast<jclass>(env->NewGlobalRef(mClass));
}
/**
* 运行时启动完成后的回调方法(重写自 AndroidRuntime)。
*
* 执行以下操作:
* 1. 获取 ProcessState 单例并启动 Binder 线程池,使进程具备 Binder IPC 能力
* 2. 获取 AndroidRuntime 实例并调用 Java 层 main 方法
* 3. main 方法执行完毕后,停止 Binder 和 HwBinder 的 IPC 线程
*
* @return void 无返回值
* @note 此方法执行完成后,进程通常会退出
*/
virtual void onStarted()
{
sp<ProcessState> proc = ProcessState::self(); // 获取当前进程的 ProcessState 单例对象
ALOGV("App process: starting thread pool.\n"); // 打印日志:正在启动线程池
proc->startThreadPool(); // 启动 Binder 线程池,开始监听 Binder 事务
AndroidRuntime* ar = AndroidRuntime::getRuntime(); // 获取 AndroidRuntime 运行时实例
ar->callMain(mClassName, mClass, mArgs); // 调用 Java 层指定类的 main 方法
IPCThreadState::self()->stopProcess(); // 停止 Binder IPC 线程
hardware::IPCThreadState::self()->stopProcess(); // 停止 HwBinder(硬件 Binder)IPC 线程
}
/**
* Zygote 初始化完成后的回调方法(重写自 AndroidRuntime)。
*
* 在 Zygote 模式下,当虚拟机创建并初始化完成后调用。
* 主要任务是启动 Binder 线程池,使 Zygote 进程具备 Binder IPC 能力,
* 以便后续 fork 出的应用进程能够继承这一能力。
*
* @return void 无返回值
* @note 与 onStarted 不同,此方法不会调用 Java main 方法,因为 Zygote 会进入循环等待状态
*/
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self(); // 获取当前进程的 ProcessState 单例对象
ALOGV("App process: starting thread pool.\n"); // 打印日志:正在启动线程池
proc->startThreadPool(); // 启动 Binder 线程池
}
/**
* 进程退出前的回调方法(重写自 AndroidRuntime)。
*
* 在进程即将退出时调用,负责清理资源:
* - 如果是 Zygote 模式(mClassName 为空),需要停止 Binder 和 HwBinder 的 IPC 线程
* - 最后调用父类的 onExit 方法执行标准清理流程
*
* @param code int 进程退出码
* @return void 无返回值
*/
virtual void onExit(int code)
{
if (mClassName.empty()) { // 检查是否为 Zygote 模式(类名为空表示 Zygote)
// if zygote // 如果是 Zygote 进程
IPCThreadState::self()->stopProcess(); // 停止 Binder IPC 线程
hardware::IPCThreadState::self()->stopProcess(); // 停止 HwBinder IPC 线程
}
AndroidRuntime::onExit(code); // 调用父类的退出处理方法
}
String8 mClassName; // 要启动的 Java 主类全限定名(如 com.android.commands.am.Am)
Vector<String8> mArgs; // 传递给 Java main 方法的命令行参数列表
jclass mClass; // 指向已加载 Java 类的 JNI 全局引用
};
}
using namespace android;四、computeArgBlockSize 与 maybeCreateDalvikCache
computeArgBlockSize 计算 argv 参数块的总字节数(依赖内核把参数放在连续内存的事实,见 fs/exec.c),供后续原地覆盖进程名。maybeCreateDalvikCache 在 zygote 模式下确保 /data/dalvik-cache/ 目录存在、属主 root:root、权限 0711。
c
/**
* 计算命令行参数块的总大小。
*
* 计算从 argv[0] 起始地址到 argv[argc-1] 结束地址(包含字符串结束符)的总字节数。
* 该大小用于后续通过覆盖参数块起始位置来修改进程名(nice name)。
*
* 注意:这里假设所有参数都分配在连续的内存中。虽然没有文档化的保证这一定是这样,
* 但内核确实是这样做的(参见 fs/exec.c)。
*
* 另外,对于"正常"的 Android 应用来说,这是一个常量。因为它们是从 zygote fork 出来的,
* 所以它们的命令行大小就是 zygote 命令行的大小。
*
* 我们通过用新的进程名覆盖参数块的起始部分(argv[0])来更改进程名,
* 所以如果 zygote 命令行大小减小,我们会神秘地开始得到被截断的进程名。
*
* @param argc int 参数个数
* @param argv char* const[] 参数数组
* @return size_t 参数块的总字节数
*/
static size_t computeArgBlockSize(int argc, char* const argv[]) {
// TODO: This assumes that all arguments are allocated in
// contiguous memory. There isn't any documented guarantee
// that this is the case, but this is how the kernel does it
// (see fs/exec.c).
//
// Also note that this is a constant for "normal" android apps.
// Since they're forked from zygote, the size of their command line
// is the size of the zygote command line.
//
// We change the process name of the process by over-writing
// the start of the argument block (argv[0]) with the new name of
// the process, so we'd mysteriously start getting truncated process
// names if the zygote command line decreases in size.
uintptr_t start = reinterpret_cast<uintptr_t>(argv[0]); // 获取参数块起始地址(argv[0] 的地址)
uintptr_t end = reinterpret_cast<uintptr_t>(argv[argc - 1]); // 获取最后一个参数的地址
end += strlen(argv[argc - 1]) + 1; // 加上最后一个参数字符串的长度(包含结束符 '\0')
return (end - start); // 返回参数块总大小(结束地址 - 起始地址)
}
/**
* 创建 Dalvik 缓存目录。
*
* 确保 Dalvik/ART 虚拟机的缓存目录存在且权限正确。
* 执行以下操作:
* 1. 获取 ANDROID_DATA 环境变量(通常是 /data)
* 2. 构建 dalvik-cache 目录路径(如 /data/dalvik-cache/arm64)
* 3. 创建目录(如果不存在),权限设置为 0711(所有者可读写执行,其他用户可执行)
* 4. 设置目录所有者为 root:root
* 5. 再次确保权限为 0711
*
* 我们总是执行这些步骤,因为目录可能已经存在,但权限过宽或所有者不是我们期望的。
*
* @return void 无返回值
* @note 如果 ANDROID_DATA 未设置或目录操作失败,将触发致命错误(LOG_ALWAYS_FATAL)
*/
static void maybeCreateDalvikCache() {
const char* androidRoot = getenv("ANDROID_DATA"); // 获取 ANDROID_DATA 环境变量值(通常是 /data)
LOG_ALWAYS_FATAL_IF(androidRoot == NULL, "ANDROID_DATA environment variable unset"); // 如果未设置则触发致命错误
char dalvikCacheDir[PATH_MAX]; // 定义缓存目录路径缓冲区
const int numChars = snprintf(dalvikCacheDir, PATH_MAX,
"%s/dalvik-cache/" ABI_STRING, androidRoot); // 构建缓存目录路径,如 /data/dalvik-cache/arm64
LOG_ALWAYS_FATAL_IF((numChars >= PATH_MAX || numChars < 0),
"Error constructing dalvik cache : %s", strerror(errno)); // 如果路径过长或构建失败则触发致命错误
int result = mkdir(dalvikCacheDir, 0711); // 创建缓存目录,权限为 0711(rwx--x--x)
LOG_ALWAYS_FATAL_IF((result < 0 && errno != EEXIST),
"Error creating cache dir %s : %s", dalvikCacheDir, strerror(errno)); // 如果创建失败(且不是因为已存在)则触发致命错误
// We always perform these steps because the directory might
// already exist, with wider permissions and a different owner
// than we'd like.
// 我们总是执行这些步骤,因为目录可能已经存在,但权限过宽或所有者不是我们期望的
result = chown(dalvikCacheDir, AID_ROOT, AID_ROOT); // 设置目录所有者为 root:root
LOG_ALWAYS_FATAL_IF((result < 0), "Error changing dalvik-cache ownership : %s", strerror(errno)); // 如果设置所有者失败则触发致命错误
result = chmod(dalvikCacheDir, 0711); // 设置目录权限为 0711
LOG_ALWAYS_FATAL_IF((result < 0),
"Error changing dalvik-cache permissions : %s", strerror(errno)); // 如果设置权限失败则触发致命错误
}五、ABI 常量与 main 函数(参数解析)
由 __LP64__ 决定 64/32 位的 ABI 列表属性名与 zygote 进程名。main 函数前半段解析命令行:'--' 或第一个非 '-' 参数之前的全部作为 VM 选项(-cp/-classpath 是带空格值的特例),随后跳过未使用的 parent dir,再识别 --zygote / --start-system-server / --application / --nice-name= 四个内部参数,遇到主类名停止。
c
#if defined(__LP64__) // 如果是 64 位系统(Long Pointer 64)
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64"; // 64 位 ABI 列表属性名
static const char ZYGOTE_NICE_NAME[] = "zygote64"; // 64 位 Zygote 的进程名
#else // 如果是 32 位系统
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32"; // 32 位 ABI 列表属性名
static const char ZYGOTE_NICE_NAME[] = "zygote"; // 32 位 Zygote 的进程名
#endif
/**
* app_process 主函数 - 应用进程入口点。
*
* 执行流程:
* 1. 解析命令行参数,区分虚拟机参数和应用参数
* 2. 识别启动模式:Zygote 模式(--zygote)、应用模式(--application)或工具模式
* 3. 处理特殊参数:--start-system-server、--nice-name 等
* 4. 根据模式准备参数:
* - 非 Zygote 模式:准备 "application" 或 "tool" 参数,设置类名和剩余参数
* - Zygote 模式:创建 Dalvik 缓存,添加 ABI 列表参数,传递所有剩余参数
* 5. 设置进程名(nice name)
* 6. 启动运行时:
* - Zygote 模式:启动 com.android.internal.os.ZygoteInit
* - 其他模式:启动 com.android.internal.os.RuntimeInit
*
* @param argc int 命令行参数个数
* @param argv char* const[] 命令行参数数组
* @return int 进程退出码(通常不会返回,因为 runtime.start 不会返回)
*/
int main(int argc, char* const argv[])
{
if (!LOG_NDEBUG) { // 如果处于调试模式(非发布版本)
String8 argv_String; // 创建字符串用于拼接所有参数
for (int i = 0; i < argc; ++i) { // 遍历所有命令行参数
argv_String.append("\""); // 添加起始引号
argv_String.append(argv[i]); // 添加参数内容
argv_String.append("\" "); // 添加结束引号和空格
}
ALOGV("app_process main with argv: %s", argv_String.c_str()); // 打印所有参数的日志
}
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv)); // 创建 AppRuntime 实例,传入参数块起始地址和大小
// Process command line arguments // 开始处理命令行参数
// ignore argv[0] // 忽略 argv[0](程序名本身)
argc--; // 参数个数减一
argv++; // 参数指针后移,跳过 argv[0]
// Everything up to '--' or first non '-' arg goes to the vm.
//
// The first argument after the VM args is the "parent dir", which
// is currently unused.
//
// After the parent dir, we expect one or more the following internal
// arguments :
//
// --zygote : Start in zygote mode
// --start-system-server : Start the system server.
// --application : Start in application (stand alone, non zygote) mode.
// --nice-name : The nice name for this process.
//
// For non zygote starts, these arguments will be followed by
// the main class name. All remaining arguments are passed to the
// main method of this class.
//
// For zygote starts, all remaining arguments are passed to the zygote.
// main function.
//
// Note that we must copy argument string values since we will rewrite the
// entire argument block when we apply the nice name to argv0.
//
// As an exception to the above rule, anything in "spaced commands"
// goes to the vm even though it has a space in it.
// 说明:'--' 或第一个非 '-' 参数之前的所有内容都传给虚拟机
// 虚拟机参数后的第一个参数是"父目录",目前未使用
// 父目录之后,我们期望以下一个或多个内部参数:
// --zygote:以 zygote 模式启动
// --start-system-server:启动系统服务器
// --application:以应用模式启动(独立、非 zygote 模式)
// --nice-name:该进程的友好名称
// 对于非 zygote 启动,这些参数后将跟主类名,所有剩余参数都传给该类的 main 方法
// 对于 zygote 启动,所有剩余参数都传给 zygote 的 main 函数
// 注意:我们必须复制参数字符串值,因为当我们将 nice name 应用到 argv0 时,
// 会重写整个参数块
// 作为上述规则的例外,"spaced commands" 中的任何内容都传给虚拟机,即使其中包含空格
const char* spaced_commands[] = { "-cp", "-classpath" }; // 定义需要特殊处理的带空格命令(类路径参数)
// Allow "spaced commands" to be succeeded by exactly 1 argument (regardless of -s).
// 允许"spaced commands"后面恰好跟 1 个参数(无论是否有 -s)
bool known_command = false; // 标记当前参数是否为已知命令(-cp 或 -classpath)
int i; // 循环索引变量
for (i = 0; i < argc; i++) { // 遍历所有参数,处理虚拟机参数
if (known_command == true) { // 如果当前参数是已知命令(-cp/-classpath)的后继参数
runtime.addOption(strdup(argv[i])); // 将该参数作为虚拟机选项添加(复制字符串)
// The static analyzer gets upset that we don't ever free the above
// string. Since the allocation is from main, leaking it doesn't seem
// problematic. NOLINTNEXTLINE
// 静态分析器对我们从不释放上述字符串感到不满。由于分配来自 main,泄漏它似乎不是问题
ALOGV("app_process main add known option '%s'", argv[i]); // 打印日志:添加已知选项
known_command = false; // 重置标记,继续正常处理
continue; // 跳过本次循环的剩余部分
}
for (int j = 0;
j < static_cast<int>(sizeof(spaced_commands) / sizeof(spaced_commands[0]));
++j) { // 遍历 spaced_commands 数组
if (strcmp(argv[i], spaced_commands[j]) == 0) { // 如果当前参数匹配 -cp 或 -classpath
known_command = true; // 设置标记,表示下一个参数需要特殊处理
ALOGV("app_process main found known command '%s'", argv[i]); // 打印日志:发现已知命令
}
}
if (argv[i][0] != '-') { // 如果当前参数不以 '-' 开头(即不是选项)
break; // 跳出循环,进入运行时参数解析阶段
}
if (argv[i][1] == '-' && argv[i][2] == 0) { // 如果当前参数是 "--"(两个横杠且字符串结束)
++i; // Skip --. // 跳过后缀的 "--",指向下一个参数
break; // 跳出循环
}
runtime.addOption(strdup(argv[i])); // 将当前参数作为虚拟机选项添加(复制字符串)
// The static analyzer gets upset that we don't ever free the above
// string. Since the allocation is from main, leaking it doesn't seem
// problematic. NOLINTNEXTLINE
// 静态分析器对我们从不释放上述字符串感到不满。由于分配来自 main,泄漏它似乎不是问题
ALOGV("app_process main add option '%s'", argv[i]); // 打印日志:添加选项
}
// Parse runtime arguments. Stop at first unrecognized option.
// 解析运行时参数。在第一个无法识别的选项处停止。
bool zygote = false; // 标记是否为 Zygote 模式
bool startSystemServer = false; // 标记是否启动系统服务器
bool application = false; // 标记是否为应用模式(独立应用,非 Zygote fork)
String8 niceName; // 存储进程友好名称(用于设置进程名)
String8 className; // 存储要启动的主类名
++i; // Skip unused "parent dir" argument. // 跳过未使用的"父目录"参数
while (i < argc) { // 遍历剩余参数,解析运行时参数
const char* arg = argv[i++]; // 获取当前参数并递增索引
if (strcmp(arg, "--zygote") == 0) { // 如果参数是 --zygote
zygote = true; // 设置 Zygote 模式标记
niceName = ZYGOTE_NICE_NAME; // 设置进程名为 zygote 或 zygote64
} else if (strcmp(arg, "--start-system-server") == 0) { // 如果参数是 --start-system-server
startSystemServer = true; // 设置启动系统服务器标记
} else if (strcmp(arg, "--application") == 0) { // 如果参数是 --application
application = true; // 设置应用模式标记
} else if (strncmp(arg, "--nice-name=", 12) == 0) { // 如果参数以 --nice-name= 开头
niceName = (arg + 12); // 提取等号后的进程名
} else if (strncmp(arg, "--", 2) != 0) { // 如果参数不以 -- 开头(即为主类名)
className = arg; // 保存主类名
break; // 跳出循环
} else { // 如果是其他未识别的 -- 开头的参数
--i; // 回退索引,使该参数在后续处理中可见
break; // 跳出循环
}
}六、main 函数(模式分支与 runtime.start)
main 后半段按模式准备参数并启动运行时:非 zygote 模式把 application/tool 标记传给 RuntimeInit 并设置主类与剩余参数;zygote 模式创建 dalvik-cache、从 ro.product.cpu.abilist64/32 读 ABI 列表拼 --abi-list= 参数、透传剩余参数。最后用 setArgv0 改写进程名,zygote 模式 start ZygoteInit,普通模式 start RuntimeInit,两者皆缺则致命退出。
c
Vector<String8> args; // 创建参数列表,用于传递给 ZygoteInit 或 RuntimeInit
if (!className.empty()) { // 如果不是 Zygote 模式(指定了主类名)
// We're not in zygote mode, the only argument we need to pass
// to RuntimeInit is the application argument.
// 我们不在 zygote 模式,需要传给 RuntimeInit 的唯一参数是 application 参数
//
// The Remainder of args get passed to startup class main(). Make
// copies of them before we overwrite them with the process name.
// 剩余参数传给启动类的 main()。在我们用进程名覆盖它们之前,先制作副本。
args.add(application ? String8("application") : String8("tool")); // 根据模式添加 "application" 或 "tool" 参数
runtime.setClassNameAndArgs(className, argc - i, argv + i); // 设置类名和剩余参数(argc-i 个参数,从 argv+i 开始)
if (!LOG_NDEBUG) { // 如果处于调试模式
String8 restOfArgs; // 创建字符串用于拼接剩余参数
char* const* argv_new = argv + i; // 获取剩余参数的起始指针
int argc_new = argc - i; // 获取剩余参数的个数
for (int k = 0; k < argc_new; ++k) { // 遍历所有剩余参数
restOfArgs.append("\""); // 添加起始引号
restOfArgs.append(argv_new[k]); // 添加参数内容
restOfArgs.append("\" "); // 添加结束引号和空格
}
ALOGV("Class name = %s, args = %s", className.c_str(), restOfArgs.c_str()); // 打印类名和参数的日志
}
} else { // 如果是 Zygote 模式(未指定主类名)
// We're in zygote mode. // 我们处于 zygote 模式
maybeCreateDalvikCache(); // 创建 Dalvik 缓存目录
if (startSystemServer) { // 如果需要启动系统服务器
args.add(String8("start-system-server")); // 添加启动系统服务器参数
}
char prop[PROP_VALUE_MAX]; // 定义属性值缓冲区
if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) { // 获取 ABI 列表属性,如果获取失败
LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
ABI_LIST_PROPERTY); // 触发致命错误:无法从属性确定 ABI 列表
return 11; // 返回错误码 11(实际上 LOG_ALWAYS_FATAL 不会返回)
}
String8 abiFlag("--abi-list="); // 创建 ABI 列表参数前缀
abiFlag.append(prop); // 追加属性值,形成完整参数如 --abi-list=arm64-v8a,armeabi-v7a
args.add(abiFlag); // 将 ABI 列表参数添加到参数列表
// In zygote mode, pass all remaining arguments to the zygote
// main() method.
// 在 zygote 模式下,将所有剩余参数传给 zygote 的 main() 方法
for (; i < argc; ++i) { // 遍历所有剩余参数
args.add(String8(argv[i])); // 将每个参数添加到参数列表
}
}
if (!niceName.empty()) { // 如果设置了进程友好名称
runtime.setArgv0(niceName.c_str(), true /* setProcName */); // 设置 argv[0] 为新的进程名,并更新进程名
}
if (zygote) { // 如果是 Zygote 模式
runtime.start("com.android.internal.os.ZygoteInit", args, zygote); // 启动 ZygoteInit 类,进入 Zygote 初始化流程
} else if (!className.empty()) { // 如果指定了主类名(非 Zygote 模式)
runtime.start("com.android.internal.os.RuntimeInit", args, zygote); // 启动 RuntimeInit 类,进入应用初始化流程
} else { // 如果既未指定 --zygote 也未指定主类名
fprintf(stderr, "Error: no class name or --zygote supplied.\n"); // 向标准错误输出打印错误信息
app_usage(); // 打印用法信息
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); // 触发致命错误
}
}