Android應(yīng)用程序啟動分析

概述

啟動一個應(yīng)用程序要通過AMS,而AMS在啟動應(yīng)用程序時,會先判斷該應(yīng)用程序所需要的進程是否存在,若不存在,則需先創(chuàng)建進程。創(chuàng)建進程的工作由Zygote來完成。AMS向Zygote在Java層創(chuàng)建的Socket發(fā)送創(chuàng)建應(yīng)用請求,Zygote通過fock自身創(chuàng)建。


時序圖.png

過程詳解

1.AMS的startProcessLocked
 private final void startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
            //此處省略N行.......
           //獲取要創(chuàng)建的進程的用戶Id
            int uid = app.uid;
            int[] gids = null;
            int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
            if (!app.isolated) {
                int[] permGids = null;
                 //此處省略N行
                if (ArrayUtils.isEmpty(permGids)) {
                    gids = new int[3];
                } else {
                    gids = new int[permGids.length + 3];
                    System.arraycopy(permGids, 0, gids, 3, permGids.length);
                }
                gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
                gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid));
                gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid));
            }
                 //此處省略N行
            if (hostingType.equals("webview_service")) {
                startResult = startWebView(entryPoint,
                        app.processName, uid, uid, gids, debugFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, null, entryPointArgs);
            } else {
             //啟動應(yīng)用程序進程
                startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, debugFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, invokeWith, entryPointArgs);
            }
            //此處省略N行.......
    }
2.Process的start()

內(nèi)部持有ZygoteProcess對象,調(diào)用了它的start()方法

 public static final ProcessStartResult start(final String processClass,
                                  final String niceName,
                                  int uid, int gid, int[] gids,
                                  int debugFlags, int mountExternal,
                                  int targetSdkVersion,
                                  String seInfo,
                                  String abi,
                                  String instructionSet,
                                  String appDataDir,
                                  String invokeWith,
                                  String[] zygoteArgs) {
    //processClass是前面AMS傳進來的entryPonit,而entryPoint實際上是
    // if (entryPoint == null) entryPoint = "android.app.ActivityThread";
        return zygoteProcess.start(processClass, niceName, uid, gid, gids,
                    debugFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, zygoteArgs);

3.ZygoteProcess的start()
public final Process.ProcessStartResult start(final String processClass,
                                                  final String niceName,
                                                  int uid, int gid, int[] gids,
                                                  int debugFlags, int mountExternal,
                                                  int targetSdkVersion,
                                                  String seInfo,
                                                  String abi,
                                                  String instructionSet,
                                                  String appDataDir,
                                                  String invokeWith,
                                                  String[] zygoteArgs) {
        try {
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    debugFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
            Log.e(LOG_TAG,
                    "Starting VM process through Zygote failed");
            throw new RuntimeException(
                    "Starting VM process through Zygote failed", ex);
        }
    }

調(diào)用起內(nèi)部startViaZygote()

private Process.ProcessStartResult startViaZygote(final String processClass,
final String niceName, final int uid, final int gid,  final int[] gids,
 int debugFlags, int mountExternal, int targetSdkVersion, String seInfo,
String abi,String instructionSet,String appDataDir, 
String invokeWith,String[] extraArgs)throws ZygoteStartFailedEx {
        ArrayList<String> argsForZygote = new ArrayList<String>();
        argsForZygote.add("--runtime-args");
        argsForZygote.add("--setuid=" + uid);
        argsForZygote.add("--setgid=" + gid);
      
        synchronized(mLock) {
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
        }
    }

這里主要保存了一些進程啟動的參數(shù),最終調(diào)用zygoteSendArgsAndGetResult(),該方法將應(yīng)用程序啟動參數(shù)寫入ZygoteProcess的靜態(tài)內(nèi)部類,表示與Zygote進程通信的狀態(tài),
【openZygoteSocketIfNeeded(abi)獲取zygoteState對象?!?/p>

@GuardedBy("mLock")
   private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
       Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
       if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
           try {
              //通過ZygoteState與Zygote建立連接
               primaryZygoteState = ZygoteState.connect(mSocket);
           } catch (IOException ioe) {
               throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
           }
       }
       if (primaryZygoteState.matches(abi)) {
           return primaryZygoteState;
       }
       if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
           try {
               secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
           } catch (IOException ioe) {
               throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
           }
       }
       if (secondaryZygoteState.matches(abi)) {
           return secondaryZygoteState;
       }
       throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
   }

該方法通過與Zygote進程建立的Server端的Sokcet建立連接,獲取ZygoteState類型的primaryZygoteServer對象,判斷其與啟動應(yīng)用進程所需的ABI是否匹配,若不匹配,則嘗試連接Zygote的輔模式。在判斷輔模式返回ZygoteState與啟動應(yīng)用程序進程的ABI是否匹配,匹配則連接,不匹配則拋出異常ZygoteStartFailedEx。

最終若連接成功且匹配ABI成功返回ZygoteState對象
回到 zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
我們繼續(xù)看下面:拿到ZygoteState對象,下面這個對象做了什么?

 private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
            ZygoteState zygoteState, ArrayList<String> args)
            throws ZygoteStartFailedEx {
        try {
            int sz = args.size();
            for (int i = 0; i < sz; i++) {
                if (args.get(i).indexOf('\n') >= 0) {
                    throw new ZygoteStartFailedEx("embedded newlines not allowed");
                }
            }
         //將傳入攜帶應(yīng)用程序進程啟動參數(shù)的args寫入zygoteState
            final BufferedWriter writer = zygoteState.writer;
            final DataInputStream inputStream = zygoteState.inputStream;
            writer.write(Integer.toString(args.size()));
            writer.newLine();
            for (int i = 0; i < sz; i++) {
                String arg = args.get(i);
                writer.write(arg);
                writer.newLine();
            }
            writer.flush();
            Process.ProcessStartResult result = new Process.ProcessStartResult();
            result.pid = inputStream.readInt();
            result.usingWrapper = inputStream.readBoolean();

            if (result.pid < 0) {
                throw new ZygoteStartFailedEx("fork() failed");
            }
            return result;
        } catch (IOException ex) {
            zygoteState.close();
            throw new ZygoteStartFailedEx(ex);
        }
    }

該方法內(nèi)將攜帶應(yīng)用程序進程啟動參數(shù)的args寫入zygoteState,那么Zygote進程就會接收到創(chuàng)建應(yīng)用程序進程的請求。
這是為什么呢?---我們回顧下Zygote進程創(chuàng)建的時候干了什么?

 public static void main(String argv[]) {
        ZygoteServer zygoteServer = new ZygoteServer();
        //創(chuàng)建一個Server端的Socket
        String socketName = "zygote";
        zygoteServer.registerServerSocket(socketName); 
            if (!enableLazyPreload) {
                bootTimingsTraceLog.traceBegin("ZygotePreload");
                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                    SystemClock.uptimeMillis());
                preload(bootTimingsTraceLog);
                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                    SystemClock.uptimeMillis());
                bootTimingsTraceLog.traceEnd(); // ZygotePreload
            } else {
                Zygote.resetNicePriority();
            }
           //啟動SystemServer進程
            if (startSystemServer) {
                startSystemServer(abiList, socketName, zygoteServer);
            }
           //等待AMS的請求
            zygoteServer.runSelectLoop(abiList);
            zygoteServer.closeServerSocket();
        } catch (Zygote.MethodAndArgsCaller caller) {
            caller.run();
        } catch (Throwable ex) {
            zygoteServer.closeServerSocket();
            throw ex;
        }
    }

1.創(chuàng)建名為“zygote”一個Server端的Socket
2.啟動SystemServer進程:startSystemServer
3.開啟等待AMS請求:runSelectLoop

4.SystemServer的runSelectLoop

這是一個while(true)循環(huán),初次執(zhí)行,先完成SystemServer與Socket連接,監(jiān)聽Socket是否有可讀數(shù)據(jù),若有則執(zhí)行tunOnce()

 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 {
     //監(jiān)聽 socket 是否數(shù)據(jù)可讀,如果沒有那么 會在此處等待
                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) {
              //SystemServer 啟動時,首次與Zygote 連接, 此處將其端的連接對象
       //ZygoteConnection存儲下來,以便之后讀取ams 寫入socket的參數(shù)
                    ZygoteConnection newPeer = acceptCommandPeer(abiList); 
                    peers.add(newPeer);
                    fds.add(newPeer.getFileDesciptor());
                } else {
           //當(dāng)有數(shù)據(jù)傳入時,獲取ams寫入socket的參數(shù)
                    boolean done = peers.get(i).runOnce(this);
                    if (done) {
                        peers.remove(i);
                        fds.remove(i);
                    }
                }
            }
        }
    }
  boolean runOnce(ZygoteServer zygoteServer) throws Zygote.MethodAndArgsCaller {

        String args[];
        Arguments parsedArgs = null;
        FileDescriptor[] descriptors;
        try {
           //獲取應(yīng)用程序啟動參數(shù)
            args = readArgumentList();
            descriptors = mSocket.getAncillaryFileDescriptors();
        } catch (IOException ex) {
            closeSocket();
            return true;
        }
     //.........
        try {
            parsedArgs = new Arguments(args);
      //Zygote通過fock自身創(chuàng)建進程,并返回進程號
            pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
                    parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
                    parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.instructionSet,
                    parsedArgs.appDataDir);
        } catch (ErrnoException ex) {
            logAndPrintError(newStderr, "Exception creating pipe", ex);
        } catch (IllegalArgumentException ex) {
            logAndPrintError(newStderr, "Invalid zygote arguments", ex);
        } catch (ZygoteSecurityException ex) {
            logAndPrintError(newStderr,
                    "Zygote security policy prevents request: ", ex);
        }
          try {
            if (pid == 0) {
       //pid為0,表示當(dāng)前代碼執(zhí)行邏輯運行在新創(chuàng)建的進程中,調(diào)用handleChildProc處理進程
                zygoteServer.closeServerSocket();
                IoUtils.closeQuietly(serverPipeFd);
                serverPipeFd = null;
                handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
                return true;
            } else {
                IoUtils.closeQuietly(childPipeFd);
                childPipeFd = null;
                return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
            }
        } finally {
            IoUtils.closeQuietly(childPipeFd);
            IoUtils.closeQuietly(serverPipeFd);
        }
    }

handleChildProc()內(nèi)調(diào)用了
ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion,
parsedArgs.remainingArgs, null /* classLoader */);

5.ZygoteInit的zygoteInit()
 public static final void zygoteInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();
        ZygoteInit.nativeZygoteInit();
        RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }

ZygoteInit.nativeZygoteInit()為應(yīng)用程序進程創(chuàng)建Binder線程池
RuntimeInit.applicationIni()創(chuàng)建ActivityThread類,通過反射調(diào)用起入口main方法

ActivityThread的main

ActivityThread是應(yīng)用程序主線程的管理類:
1.創(chuàng)建主線程的Looper
2.創(chuàng)建主線程H類(Handler),處理組件生命周期,如啟動Activity
3.開啟Looper循環(huán)

 public static void main(String[] args) {      
        SamplingProfilerIntegration.start();
        EventLogger.setReporter(new EventLoggingReporter());
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容