android也是基於linux的系統,所以全部的進程都是從init進程開始的(直接或間接的從init進程fock出來的)。Zygote是受精卵進程,也是系統啓動過程當中由init進程建立的,具體的看下啓動腳本/system/core/rootdir/init.zygote64.rc:java
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server class main priority -20 user root group root readproc socket zygote stream 660 root system onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart audioserver onrestart restart cameraserver onrestart restart media onrestart restart netd onrestart restart wificond writepid /dev/cpuset/foreground/tasks
能夠看出,要執行的進程是/system/bin/app_process64。代碼在/frameworks/base/cmds/app_process/app_main.cpp。入口函數是main:linux
...... // 建立AppRuntime AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv)); ...... while (i < argc) { const char* arg = argv[i++]; if (strcmp(arg, "--zygote") == 0) { // 確認是zygote進程 zygote = true; niceName = ZYGOTE_NICE_NAME; } else if (strcmp(arg, "--start-system-server") == 0) { startSystemServer = true; } else if (strcmp(arg, "--application") == 0) { application = true; } else if (strncmp(arg, "--nice-name=", 12) == 0) { niceName.setTo(arg + 12); } else if (strncmp(arg, "--", 2) != 0) { className.setTo(arg); break; } else { --i; break; } } ...... if (zygote) { // 執行zygote進程 runtime.start("com.android.internal.os.ZygoteInit", args, zygote); } else if (className) { runtime.start("com.android.internal.os.RuntimeInit", args, zygote); } else { fprintf(stderr, "Error: no class name or --zygote supplied.\n"); app_usage(); LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); } ......
若是忽略掉參數這些細節,剩下的就是AppRuntime的創建和調用AppRuntime的start方法了,啓動的是com.android.internal.os.ZygoteInit。
看下AppRuntime:android
class AppRuntime : public AndroidRuntime { public: AppRuntime(char* argBlockStart, const size_t argBlockLength) : AndroidRuntime(argBlockStart, argBlockLength) , mClass(NULL) { } ...... };
構造函數中調用了基類的構造方法,基類在/frameworks/base/core/jni/AndroidRuntime.cpp:ios
AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) : mExitWithoutCleanup(false), mArgBlockStart(argBlockStart), mArgBlockLength(argBlockLength) { SkGraphics::Init(); // There is also a global font cache, but its budget is specified by // SK_DEFAULT_FONT_CACHE_COUNT_LIMIT and SK_DEFAULT_FONT_CACHE_LIMIT. // Pre-allocate enough space to hold a fair number of options. mOptions.setCapacity(20); assert(gCurRuntime == NULL); // one per process gCurRuntime = this; }
保留了本身做爲全局gCurRuntime。
直接看start方法:web
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote) { ...... JniInvocation jni_invocation; jni_invocation.Init(NULL); JNIEnv* env; // 啓動虛擬機 if (startVm(&mJavaVM, &env, zygote) != 0) { return; } // 回調虛擬機的建立 onVmCreated(env); /* * Register android functions. */ // 註冊函數 if (startReg(env) < 0) { ALOGE("Unable to register all android natives\n"); return; } ...... jclass stringClass; jobjectArray strArray; jstring classNameStr; // 得到一個string的對象的引用 stringClass = env->FindClass("java/lang/String"); assert(stringClass != NULL); // 建立一個String數組對象 strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL); assert(strArray != NULL); classNameStr = env->NewStringUTF(className); assert(classNameStr != NULL); // 設置第一個string數組的第一個元素是classNameStr,在這裏就是ZygoteInit的全名 env->SetObjectArrayElement(strArray, 0, classNameStr); // 設置其餘參數 for (size_t i = 0; i < options.size(); ++i) { jstring optionsStr = env->NewStringUTF(options.itemAt(i).string()); assert(optionsStr != NULL); env->SetObjectArrayElement(strArray, i + 1, optionsStr); } /* * Start VM. This thread becomes the main thread of the VM, and will * not return until the VM exits. */ // 轉換類中間的.爲/,這裏是轉換格式 char* slashClassName = toSlashClassName(className); // 從jni環境中找到這個類 jclass startClass = env->FindClass(slashClassName); if (startClass == NULL) { ALOGE("JavaVM unable to locate class '%s'\n", slashClassName); /* keep going */ } else { // 調用找到的類的main方法,這裏就是調用ZygoteInit的main方法 jmethodID startMeth = env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { ALOGE("JavaVM unable to find main() in '%s'\n", className); /* keep going */ } else { env->CallStaticVoidMethod(startClass, startMeth, strArray); #if 0 if (env->ExceptionCheck()) threadExitUncaughtException(env); #endif } } free(slashClassName); ...... }
關鍵部分已經給出了註釋。總結一下:
1.啓動虛擬機startVM;
2.經過startReg註冊jni方法;
3.調用ZygoteInit類的main方法;
startVm基本上就是爲這個進程創建一個Dalvik虛擬機環境,爲當前線程初始化一個jni環境。startReg基本上是註冊一大堆的jni方法,以供後面調用。不是本文重點,所以這裏再也不累述。數組
下面咱們要關注的是ZygoteInit類的main方法了。
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:網絡
public static void main(String argv[]) { ZygoteServer zygoteServer = new ZygoteServer(); ...... zygoteServer.registerServerSocket(socketName); ...... preload(); ...... if (startSystemServer) { startSystemServer(abiList, socketName, zygoteServer); } ...... zygoteServer.runSelectLoop(abiList); ...... }
1.建立ZygoteServer(能夠看出是個cs架構的東西);
2.註冊socket(使用socket進行通信方式);
3.預加載;
4.啓動SystemServer;
5.運行select循環體;
裏面涉及到ZygoteHooks的運轉,爲了避免影響總體,暫時作個標記,後面再閱讀。
這裏能夠看到Zygote基本上是個cs架構的狀況,而且經過socket進行這種架構的通信。先來看看預加載過程:架構
static void preload() { Log.d(TAG, "begin preload"); Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "BeginIcuCachePinning"); beginIcuCachePinning(); Trace.traceEnd(Trace.TRACE_TAG_DALVIK); Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadClasses"); //預加載位於framework/base/preload-classes文件中的類 preloadClasses(); Trace.traceEnd(Trace.TRACE_TAG_DALVIK); Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadResources"); // 預加載資源 preloadResources(); Trace.traceEnd(Trace.TRACE_TAG_DALVIK); Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL"); // 預加載資源 preloadOpenGL(); Trace.traceEnd(Trace.TRACE_TAG_DALVIK); //經過System.loadLibrary()方法,預加載"android","compiler_rt","jnigraphics"這3個共享庫 preloadSharedLibraries(); //預加載文本鏈接符資源 preloadTextResources(); // webview的初始化 // Ask the WebViewFactory to do any initialization that must run in the zygote process, // for memory sharing purposes. WebViewFactory.prepareWebViewInZygote(); endIcuCachePinning(); warmUpJcaProviders(); Log.d(TAG, "end preload"); }
看到了吧,都是android自己的一些資源的初始化過程,就是在這裏完成的。
下面再看下startSystemServer:app
private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) throws Zygote.MethodAndArgsCaller, RuntimeException { long capabilities = posixCapabilitiesAsBits( OsConstants.CAP_IPC_LOCK, OsConstants.CAP_KILL, OsConstants.CAP_NET_ADMIN, OsConstants.CAP_NET_BIND_SERVICE, OsConstants.CAP_NET_BROADCAST, OsConstants.CAP_NET_RAW, OsConstants.CAP_SYS_MODULE, OsConstants.CAP_SYS_NICE, OsConstants.CAP_SYS_RESOURCE, OsConstants.CAP_SYS_TIME, OsConstants.CAP_SYS_TTY_CONFIG, OsConstants.CAP_WAKE_ALARM ); /* Containers run without this capability, so avoid setting it in that case */ if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) { capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND); } /* Hardcoded command line to start the system server */ String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "com.android.server.SystemServer", }; ZygoteConnection.Arguments parsedArgs = null; int pid; try { parsedArgs = new ZygoteConnection.Arguments(args); ZygoteConnection.applyDebuggerSystemProperty(parsedArgs); ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs); /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } zygoteServer.closeServerSocket(); handleSystemServerProcess(parsedArgs); } return true; }
其實主要的就是Zygote.forkSystemServer這句話,前面的都是參數的配置。再向下看一層/frameworks/base/core/java/com/android/internal/os/Zygote.java:socket
public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) { VM_HOOKS.preFork(); int pid = nativeForkSystemServer( uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities); // Enable tracing as soon as we enter the system_server. if (pid == 0) { Trace.setTracingEnabled(true); } VM_HOOKS.postForkCommon(); return pid; }
根據傳遞進來的uid,gid等調用函數nativeForkSystemServer,最終會在/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp下的ForkAndSpecializeCommon中調用fork函數,那麼實際上就能夠知道,就是在c層fork分裂出一個進程來做爲SystemServer。
如今咱們回來看java層的ZygoteInit.java,繼續看看與socket相關的部分,首先是registerServerSocket:
void registerServerSocket(String socketName) { if (mServerSocket == null) { int fileDesc; final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName; try { String env = System.getenv(fullSocketName); fileDesc = Integer.parseInt(env); } catch (RuntimeException ex) { throw new RuntimeException(fullSocketName + " unset or invalid", ex); } try { FileDescriptor fd = new FileDescriptor(); fd.setInt$(fileDesc); mServerSocket = new LocalServerSocket(fd); } catch (IOException ex) { throw new RuntimeException( "Error binding to local socket '" + fileDesc + "'", ex); } } }
這裏設置了文件描述符,而後建立了LocalServerSocket賦值給了mServerSocket。/frameworks/base/core/java/android/net/LocalServerSocket.java:
public LocalServerSocket(FileDescriptor fd) throws IOException { impl = new LocalSocketImpl(fd); impl.listen(LISTEN_BACKLOG); localAddress = impl.getSockAddress(); }
new出LocalSocketImpl後,直接就開始listen了。下面暫時不用特別看了吧,就是一個走的正常的網絡socket了。這裏應該就能夠證實是以socket的方法進行的通信。而後再來看看runSelectLoop:
void runSelectLoop(String abiList) throws Zygote.MethodAndArgsCaller { ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>(); ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>(); fds.add(mServerSocket.getFileDescriptor()); peers.add(null); while (true) { StructPollfd[] pollFds = new StructPollfd[fds.size()]; for (int i = 0; i < pollFds.length; ++i) { pollFds[i] = new StructPollfd(); pollFds[i].fd = fds.get(i); pollFds[i].events = (short) POLLIN; } try { Os.poll(pollFds, -1); } catch (ErrnoException ex) { throw new RuntimeException("poll failed", ex); } for (int i = pollFds.length - 1; i >= 0; --i) { if ((pollFds[i].revents & POLLIN) == 0) { continue; } if (i == 0) { ZygoteConnection newPeer = acceptCommandPeer(abiList); peers.add(newPeer); fds.add(newPeer.getFileDesciptor()); } else { boolean done = peers.get(i).runOnce(this); if (done) { peers.remove(i); fds.remove(i); } } } } }
進入一個死循環,每次都將全部要觀察的fd創建成數組,而後調用Os.poll(pollFds, -1)阻塞等待fd的變化。後面一個for循環是當fd有變化(即有客戶端鏈接,也就是說有其餘進程想要與ZygoteServer通信),此時調用ZygoteConnection的runOnce方法。這個方法若是簡單看下的話,最終是要調用Zygote.forkAndSpecialize分裂出進程來的,也就是說這個方法是一旦有鏈接創建後就表示有app啓動了,此時就要fork分裂出新的進程來,代碼暫時就不貼了。
至此爲止,Zygote的過程基本分析完畢。總結一下:
1.系統啓動,經過init進程會啓動Zygote進程。確切的將是經過runtime調用了ZygoteInit,這個初始化過程;
2.Zygote是cs架構的,基於socket通信機制的,在ZygoteInit過程當中會啓動ZygoteServer,爲了等待接收socket的通信來進行啓動app進程的處理;
3.分裂出SystemServer進程,負責啓動系統的一些關鍵服務。包括3類(廣播類、核心類、其餘類);
最後附圖一張便於理解: