Android基於Linux2.6+內核,我們看一張圖,以對Android系統的架構有個感性的認識。
我們從Kernel層簡單說明:
1、Kernel層:基於Linux2.6+內核,同時做了一些嵌入式環境做了一些針對性的優化調整。
2、Libraries層:包括Bionic C庫,以及HAL(硬件驅動接口抽象)等API。
3、Android Runtime(ART)層:包含核心應用庫和Dalvik虛擬機。
4、Application Framework層:純JAVA的API框架,包括Activity Manager和Windows Manager等。
5、Application層:顧名思義,應用層,如預裝的電話、短信,遊戲APP等。
下面,我們首先看下一個典型的Android系統APP進程映像:
命令行輸入PS,查看當前進程列表:
我們看看紅圈標註的進程,其中10002爲PID,137爲父進程ID。
可以看到進程號137的進程即爲神祕的“zygote”進程,而zygote的父進程爲init進程。init進程爲Android一切進程的祖先進程,而zygote則爲APP應用的祖先進程。
至此,我們對Android的應用啓動的初始過程有了一個大致的認識,下面,我們結合AOSP(Android Open Source Project)來做更深入的分析。
Android開源代碼庫:點擊打開鏈接
首先我們從app_main.cpp開始(點擊打開鏈接),這個就是/system/bin/app_process的C++源碼,也就是所有APP的父進程。我們直接對照源碼進程閱讀,我添加了註釋:
int main(int argc, char* const argv[])
{
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
// Older kernels don't understand PR_SET_NO_NEW_PRIVS and return
// EINVAL. Don't die on such kernels.
if (errno != EINVAL) {
LOG_ALWAYS_FATAL("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
return 12;
}
}
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
// Process command line arguments
// ignore argv[0]
argc--;
argv++;
// 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.
int i = runtime.addVmArguments(argc, argv);
// Parse runtime arguments. Stop at first unrecognized option.
bool zygote = false;
bool startSystemServer = false;
bool application = false;
const char* niceName = NULL;
String8 className;
++i; // Skip unused "parent dir" argument.
while (i < argc) {
const char* arg = argv[i++];
/*******************
啓動參數包含--zygote
niceName即進程名,在ARM32下,ZYGOTE_NICE_NAME = zygote(ARM64則爲zygote64)
*******************/
if (strcmp(arg, "--zygote") == 0) {
zygote = true;
niceName = ZYGOTE_NICE_NAME;
}
/*******************
啓動參數包含--start-system-server
置startSystemServer爲true,以同時啓動system-server
*******************/
else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;
}
/*******************
啓動參數包含--application
置application爲true,傳遞參數給dalvik
*******************/
else if (strcmp(arg, "--application") == 0) {
application = true;
} else if (strncmp(arg, "--nice-name=", 12) == 0) {
niceName = arg + 12;
} else if (strncmp(arg, "--", 2) != 0) {
className.setTo(arg);
break;
} else {
--i;
break;
}
}
Vector<String8> args;
if (!className.isEmpty()) {
// We're not in zygote mode, the only argument we need to pass
// to RuntimeInit is the application argument.
//
// The Remainder of args get passed to startup class main(). Make
// copies of them before we overwrite them with the process name.
/*******************
非Zygote模式處理
*******************/
args.add(application ? String8("application") : String8("tool"));
runtime.setClassNameAndArgs(className, argc - i, argv + i);
} else {
// We're in zygote mode.
/*******************
Zygote模式啓動處理
*******************/
maybeCreateDalvikCache();
if (startSystemServer) {
args.add(String8("start-system-server"));
}
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);
// In zygote mode, pass all remaining arguments to the zygote
// main() method.
for (; i < argc; ++i) {
args.add(String8(argv[i]));
}
}
if (niceName && *niceName) {
runtime.setArgv0(niceName);
set_process_name(niceName);
}
if (zygote) {
/*******************
Zygote Init,Dalvik啓動
*******************/
runtime.start("com.android.internal.os.ZygoteInit", args);
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit", args);
} else {
fprintf(stderr, "Error: no class name or --zygote supplied.\n");
app_usage();
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
return 10;
}
}
上面代碼的幾個關鍵地方,我都做了註釋,我們看下Android根目錄下的init.rc這個初始化腳本,可以找到如下的行:
其作用就是初始化zygote進程。
zygote啓動過程可以大致描述如下:執行app_process,並修改進程名爲zygote,同時根據傳入的start-system-server參數,啓動system-server服務,同時初始化dalvik虛擬機。我們看看AndroidRuntime這個類的源碼(點擊打開鏈接),其中start函數的作用有兩個,一是啓動dalvik VM,一是執行com.android.internal.os.ZygoteInit的main函數,並傳遞相關參數,實現zygote初始化工作。
我們再看看com.android.internal.os.ZygoteInit這個JAVA類的源碼(點擊打開鏈接),看看究竟都做了什麼。
</pre></p><p style="text-align: left;"><pre name="code" class="java">public static void main(String argv[]) {
try {
// Start profiling the zygote initialization.
SamplingProfilerIntegration.start();
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
/*準備啓動system_server*/
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)) {
/*Zygote監聽的socketname,默認爲/dev/socket/zygote */
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
if (abiList == null) {
throw new RuntimeException("No ABI list supplied.");
}
/**註冊socket*/
registerZygoteSocket(socketName);
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preload();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
// Finish profiling the zygote initialization.
SamplingProfilerIntegration.writeZygoteSnapshot();
// Do an initial gc to clean up after startup
gc();
// Disable tracing so that forked processes do not inherit stale tracing tags from
// Zygote.
Trace.setTracingEnabled(false);
if (startSystemServer) {
startSystemServer(abiList, socketName);
}
Log.i(TAG, "Accepting command socket connections");
runSelectLoop(abiList);
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
Log.e(TAG, "Zygote died with exception", ex);
closeServerSocket();
throw ex;
}
}
ZygoteInit完成實際的system_server啓動,同時初始化Zygote的socket監聽(/dev/socket/zygote這個僞設備文件),至此終於完成了APP啓動的所有準備工作,注意,這只是準備工作,真正的啓動過程如下圖:
1、Launcher(Android的“發射進程”,你能看到的桌面,應用列表等都是Launcher的內容)進程監聽到應用啓動事件,如你點擊了APP圖標;
2、通過Binder(Android跨進程通信框架IPC),跨進程通知Activity Manager服務來啓動Activity。ActivityManager調用Zygote.forkAndSpecialize來fork一個新的APP子進程並返回PID,然後調用APP的啓動Activity的OnStart和OnCreate方法,完成啓動!
我們看看Fork這個函數(點擊打開鏈接):Fork的作用是“克隆”一個和當前進程結構一致的全新子進程(當然,並不是完整的照搬)!這是Android的一個聰明的做法,依據Linux的COW(Copy On Write)理論,新生成的進程會“共享”父進程的所有庫鏈接信息,同時會加載自己應有特定的一些LIB,例如Bionic libc庫是所有APP共享的,由於它是隻讀的,因此所有的APP共享一份“物理存儲”的LIBC庫,而不是每個APP一份拷貝。
我們看看Zygote進程的內存maps片段:
/system/lib下面的這些C庫被所有APP進程共享,雖然在不同的APP進程中可能位於不同的虛擬地址,但“共享”一份物理存儲!其他的APP啓動後的內存映像都是從這個zygote完整“拷貝”過來的!
轉載請註明出處:生活秀
Enjoy IT!