摘要:入口函數是創建確認是進程執行進程如果忽略掉參數這些細節,剩下的就是的建立和調用的方法了,啟動的是。下面再看下其實主要的就是這句話,前面的都是參數的配置。至此為止,的過程基本分析完畢。
android也是基于linux的系統,因此所有的進程都是從init進程開始的(直接或間接的從init進程fock出來的)。Zygote是受精卵進程,也是系統啟動過程中由init進程創建的,具體的看下啟動腳本/system/core/rootdir/init.zygote64.rc:
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:
...... // 創建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. "); app_usage(); LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); } ......
如果忽略掉參數這些細節,剩下的就是AppRuntime的建立和調用AppRuntime的start方法了,啟動的是com.android.internal.os.ZygoteInit。
看下AppRuntime:
class AppRuntime : public AndroidRuntime { public: AppRuntime(char* argBlockStart, const size_t argBlockLength) : AndroidRuntime(argBlockStart, argBlockLength) , mClass(NULL) { } ...... };
構造函數中調用了基類的構造方法,基類在/frameworks/base/core/jni/AndroidRuntime.cpp:
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方法:
void AndroidRuntime::start(const char* className, const Vector& 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 "); 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" ", 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" ", 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:
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:
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 { ArrayListfds = new ArrayList (); ArrayList peers = new ArrayList (); 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類(廣播類、核心類、其他類);
最后附圖一張便于理解:
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/66824.html
摘要:注此次分析以源碼為例。孵化器受精卵名字是受精卵,其實就是幫助或其他進程啟動的一個玩意兒。啟動系統服務是系統的大核心之一,和一并重要,專管所有的系統服務。每個進程都走這一步這個分支到此先不往下跟蹤了,和啟動的過程關系不大了。 注:此次分析以6.0源碼為例。 android系統是從linux改過來的,因此這里從init進程開始進行分析。 init初始化過程 讓我們進入init.cpp來看看...
閱讀 623·2023-04-26 01:53
閱讀 2749·2021-11-17 17:00
閱讀 2880·2021-09-04 16:40
閱讀 1983·2021-09-02 15:41
閱讀 830·2019-08-26 11:34
閱讀 1222·2019-08-26 10:16
閱讀 1335·2019-08-23 17:51
閱讀 815·2019-08-23 16:50