前言

今天简单的记录一下App进程的启动过程。

继之前startActivity源码分析(《startActivity源码分析1》和《startActivity源码分析2》)中的进程启动是一带而过的,聪明的你会发现,进程启动的大部分跟《Zygote的启动之二ZygoteInit》重合了。

正文

回到《startActivity源码分析1》文章末尾的startProcessLocked()。

ActivityManagerService.java

PS: 大部分内容都略了

startProcessLocked()
  1. @GuardedBy("this")
  2. final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
  3.       boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
  4.       boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
  5.       String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
  6. //略
  7. final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
  8. //略
  9. }
复制
startProcessLocked()
  1. @GuardedBy("this")
  2. private final boolean startProcessLocked(ProcessRecord app,
  3.       String hostingType, String hostingNameStr, String abiOverride) {
  4.   return startProcessLocked(app, hostingType, hostingNameStr,
  5.           false /* disableHiddenApiChecks */, abiOverride);
  6. }
复制
startProcessLocked()
  1. @GuardedBy("this")
  2. private final boolean startProcessLocked(ProcessRecord app, String hostingType,
  3.       String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
  4. //日志显示,前面几个startProcessLocked()会被调用2次
  5. //第一次app.pendingStart=false;第二次app.pendingStart=true;
  6. //因此第二次直接返回
  7.   if (app.pendingStart) {
  8.       return true;
  9.   }
  10. //略
  11.   try {
  12.       try {
  13.           final int userId = UserHandle.getUserId(app.uid);
  14. //PackageManagerService.java中检测
  15. //(1)判断是否存在(2)判断是否安装等,如果有问题就抛出异常
  16.           AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId);
  17.       } catch (RemoteException e) {
  18.           throw e.rethrowAsRuntimeException();
  19.       }
  20. //略
  21. //false
  22.       if (!app.isolated) {
  23.       }
  24. //略
  25. //注意,这里传入了android.app.ActivityThread
  26. final String entryPoint = "android.app.ActivityThread";
  27. //进入下一个startProcessLocked()
  28.       return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
  29.               runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
  30.               startTime);
  31.   } catch (RuntimeException e) {
  32.       forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
  33.               false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
  34.       return false;
  35.   }
  36. }
复制

这里有个重点,参数中传入了entryPoint,而entryPoint是

  1. final String entryPoint = "android.app.ActivityThread";
复制

fork出子进程后会启动android.app.ActivityThread

startProcessLocked()
  1. @GuardedBy("this")
  2. private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
  3.       ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
  4.       String seInfo, String requiredAbi, String instructionSet, String invokeWith,
  5.       long startTime) {
  6. //略
  7. //异步启动 true
  8.   if (mConstants.FLAG_PROCESS_START_ASYNC) {
  9. //使用Handler的post,也就是异步执行。
  10. //会先返回return
  11.       mProcStartHandler.post(() -> {
  12.           try {
  13.               synchronized (ActivityManagerService.this) {
  14.                   final String reason = isProcStartValidLocked(app, startSeq);
  15. //reason为null
  16.                   if (reason != null) {
  17.                       app.pendingStart = false;
  18.                       return;
  19.                   }
  20.                   app.usingWrapper = invokeWith != null
  21.                           || SystemProperties.get("wrap." + app.processName) != null;
  22.                   mPendingStarts.put(startSeq, app);
  23.               }
  24. //启动进程startProcess,关键点
  25.               final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
  26.                       app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
  27.                       requiredAbi, instructionSet, invokeWith, app.startTime);
  28.               synchronized (ActivityManagerService.this) {
  29.                   handleProcessStartedLocked(app, startResult, startSeq);
  30.               }
  31.           } catch (RuntimeException e) {
  32.               synchronized (ActivityManagerService.this) {
  33.                   mPendingStarts.remove(startSeq);
  34.                   app.pendingStart = false;
  35.                   forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
  36.                           false, false, true, false, false,
  37.                           UserHandle.getUserId(app.userId), "start failure");
  38.               }
  39.           }
  40.       });
  41.       return true;
  42.   } else {
  43.       try {
  44.           final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
  45.                   uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
  46.                   invokeWith, startTime);
  47.           handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
  48.                   startSeq, false);
  49.       } catch (RuntimeException e) {
  50.           app.pendingStart = false;
  51.           forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
  52.                   false, false, true, false, false,
  53.                   UserHandle.getUserId(app.userId), "start failure");
  54.       }
  55.       return app.pid > 0;
  56.   }
  57. }
复制
startProcess()
  1. private ProcessStartResult startProcess(String hostingType, String entryPoint,
  2.       ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
  3.       String seInfo, String requiredAbi, String instructionSet, String invokeWith,
  4.       long startTime) {
  5.   try {
  6.       Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
  7.               app.processName);
  8. //hostingType这里是启动activity,
  9.       if (hostingType.equals("webview_service")) {
  10.           startResult = startWebView(entryPoint,
  11.                   app.processName, uid, uid, gids, runtimeFlags, mountExternal,
  12.                   app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
  13.                   app.info.dataDir, null,
  14.                   new String[] {PROC_START_SEQ_IDENT + app.startSeq});
  15.       } else {
  16. //走这里,进入了Process
  17.           startResult = Process.start(entryPoint,
  18.                   app.processName, uid, uid, gids, runtimeFlags, mountExternal,
  19.                   app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
  20.                   app.info.dataDir, invokeWith,
  21.                   new String[] {PROC_START_SEQ_IDENT + app.startSeq});
  22.       }
  23.       checkTime(startTime, "startProcess: returned from zygote!");
  24.       return startResult;
  25.   } finally {
  26.       Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  27.   }
  28. }
复制

Process.java

start()
  1. public static final ProcessStartResult start(final String processClass,
  2.                             final String niceName,
  3.                             int uid, int gid, int[] gids,
  4.                             int runtimeFlags, int mountExternal,
  5.                             int targetSdkVersion,
  6.                             String seInfo,
  7.                             String abi,
  8.                             String instructionSet,
  9.                             String appDataDir,
  10.                             String invokeWith,
  11.                             String[] zygoteArgs) {
  12.   return zygoteProcess.start(processClass, niceName, uid, gid, gids,
  13.               runtimeFlags, mountExternal, targetSdkVersion, seInfo,
  14.               abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
  15. }
复制

ZygoteProcess.java

start()
  1. public final Process.ProcessStartResult start(final String processClass,
  2.                                             final String niceName,
  3.                                             int uid, int gid, int[] gids,
  4.                                             int runtimeFlags, int mountExternal,
  5.                                             int targetSdkVersion,
  6.                                             String seInfo,
  7.                                             String abi,
  8.                                             String instructionSet,
  9.                                             String appDataDir,
  10.                                             String invokeWith,
  11.                                             String[] zygoteArgs) {
  12.   try {
  13.       return startViaZygote(processClass, niceName, uid, gid, gids,
  14.               runtimeFlags, mountExternal, targetSdkVersion, seInfo,
  15.               abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
  16.               zygoteArgs);
  17.   } catch (ZygoteStartFailedEx ex) {
  18.       throw new RuntimeException(
  19.               "Starting VM process through Zygote failed", ex);
  20.   }
  21. }
复制
startViaZygote()
  1. private Process.ProcessStartResult startViaZygote(final String processClass,
  2.                                                 final String niceName,
  3.                                                 final int uid, final int gid,
  4.                                                 final int[] gids,
  5.                                                 int runtimeFlags, int mountExternal,
  6.                                                 int targetSdkVersion,
  7.                                                 String seInfo,
  8.                                                 String abi,
  9.                                                 String instructionSet,
  10.                                                 String appDataDir,
  11.                                                 String invokeWith,
  12.                                                 boolean startChildZygote,
  13.                                                 String[] extraArgs)
  14.                                                 throws ZygoteStartFailedEx {
  15.   ArrayList<String> argsForZygote = new ArrayList<String>();
  16. //argsForZygote保存相关信息,进程uid,gid等等
  17.   argsForZygote.add("--runtime-args");
  18.   argsForZygote.add("--setuid=" + uid);
  19.   argsForZygote.add("--setgid=" + gid);
  20.   argsForZygote.add("--runtime-flags=" + runtimeFlags);
  21.   if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
  22.       argsForZygote.add("--mount-external-default");
  23.   } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
  24.       argsForZygote.add("--mount-external-read");
  25.   } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
  26.       argsForZygote.add("--mount-external-write");
  27.   }
  28.   argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
  29.   if (gids != null && gids.length > 0) {
  30.       StringBuilder sb = new StringBuilder();
  31.       sb.append("--setgroups=");
  32.       int sz = gids.length;
  33.       for (int i = 0; i < sz; i++) {
  34.           if (i != 0) {
  35.               sb.append(',');
  36.           }
  37.           sb.append(gids[i]);
  38.       }
  39.       argsForZygote.add(sb.toString());
  40.   }
  41. //niceName是应用包名
  42.   if (niceName != null) {
  43.       argsForZygote.add("--nice-name=" + niceName);
  44.   }
  45.   if (seInfo != null) {
  46.       argsForZygote.add("--seinfo=" + seInfo);
  47.   }
  48.   if (instructionSet != null) {
  49.       argsForZygote.add("--instruction-set=" + instructionSet);
  50.   }
  51.   if (appDataDir != null) {
  52.       argsForZygote.add("--app-data-dir=" + appDataDir);
  53.   }
  54. //invokeWith为null
  55.   if (invokeWith != null) {
  56.       argsForZygote.add("--invoke-with");
  57.       argsForZygote.add(invokeWith);
  58.   }
  59. //startChildZygote = false
  60.   if (startChildZygote) {
  61.       argsForZygote.add("--start-child-zygote");
  62.   }
  63.   argsForZygote.add(processClass);
  64.   if (extraArgs != null) {
  65.       for (String arg : extraArgs) {
  66.           argsForZygote.add(arg);
  67.       }
  68.   }
  69.   synchronized(mLock) {
  70. //abi是平台架构类型,比如arm64-v8a,x86等,我这里是arm64-v8a
  71. //[重]openZygoteSocketIfNeeded()
  72. //[重]zygoteSendArgsAndGetResult()进程跟Zygote数据传输和读取返回结果
  73.       return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
  74.   }
  75. }
复制
openZygoteSocketIfNeeded()
  1. @GuardedBy("mLock")
  2. private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
  3.   Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
  4. //primaryZygoteState不为null
  5.   if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
  6.       try {
  7. //看过Zygote启动的知道,Zygote存在主辅模式
  8. //比如我设备是以Zygote64位主(secondary),Zygote32位辅(secondary)模式
  9. //连接socket,这个是Zygote中创建的,
  10.           primaryZygoteState = ZygoteState.connect(mSocket);
  11.       } catch (IOException ioe) {
  12.           throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
  13.       }
  14.       maybeSetApiBlacklistExemptions(primaryZygoteState, false);
  15.       maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
  16.   }
  17. //具体使用哪种模式,跟abi有关
  18.   if (primaryZygoteState.matches(abi)) {
  19.       return primaryZygoteState;
  20.   }
  21. //下面类型,但如果上面符合,就不会执行下面了。
  22.   if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
  23.       try {
  24.           secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
  25.       } catch (IOException ioe) {
  26.           throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
  27.       }
  28.       maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
  29.       maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
  30.   }
  31.   if (secondaryZygoteState.matches(abi)) {
  32.       return secondaryZygoteState;
  33.   }
  34.   throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
  35. }
复制

回归一下之前介绍的,不同设备使用的配置不一样。

下面是几个zygote相关的rc文件。

  1. init.zygote32.rc

    Zygote 进程对应的执行程序是 app_process,也就是纯32位模式。

  2. init.zygote32_64.rc

    启动两个 Zygote 进程(zygote 和 zygote_secondary),对应的执行程序分别是 app_process32(主模式)和app_process64。

  3. init.zygote64.rc

    Zygote 进程对应的执行程序是app_process64,也就是纯64位模式

  4. init.zygote64_32.rc

    启动两个 Zygote 进程(zygote 和 zygote_secondary),对应的执行程序分别是 app_process64(主模式)和app_process32。

会根据primaryZygoteState和secondaryZygoteState的初始化,进程判断,如果都不满足(启动失败了或重启中),就抛出异常!

理论上,至少有一个满足条件。

因此,经过上面执行,已建成跟Zygote进行通信了,并返回ZygoteState。

zygoteSendArgsAndGetResult()
  1. @GuardedBy("mLock")
  2. private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
  3.       ZygoteState zygoteState, ArrayList<String> args)
  4.       throws ZygoteStartFailedEx {
  5.   try {
  6. //略
  7.       //ZygoteState就是上面openZygoteSocketIfNeeded()获取的
  8. //获取writer和inputStream
  9.       final BufferedWriter writer = zygoteState.writer;
  10.       final DataInputStream inputStream = zygoteState.inputStream;
  11. //写启动上面组合的启动参数信息
  12. //此时就进入ZygoteServer.java中runSelectLoop()的死循环中啦
  13.       writer.write(Integer.toString(args.size()));
  14.       writer.newLine();
  15.       for (int i = 0; i < sz; i++) {
  16.           String arg = args.get(i);
  17.           writer.write(arg);
  18.           writer.newLine();
  19.       }
  20.       writer.flush();
  21. //创建ProcessStartResult对象
  22.       Process.ProcessStartResult result = new Process.ProcessStartResult();
  23.       //等待,zygote启动进程结构
  24.       result.pid = inputStream.readInt();
  25.       result.usingWrapper = inputStream.readBoolean();
  26.       if (result.pid < 0) {
  27.           throw new ZygoteStartFailedEx("fork() failed");
  28.       }
  29.       return result;
  30.   } catch (IOException ex) {
  31.       zygoteState.close();
  32.       throw new ZygoteStartFailedEx(ex);
  33.   }
  34. }
复制

上面就是通过socket进程传输启动应用的新,因此,进入了ZygoteServer.java中runSelectLoop()中。

对于Zygote的socket的那块,推荐可以看参考文,之前我有跟过。

ZygoteServer.java

通过socket发送消息,runSelectLoop()会一直不断的循环并进行处理。

runSelectLoop()
  1. Runnable runSelectLoop(String abiList) {
  2. //这部分第一次进入才执行,后面的进入了死循环了。
  3. //死循环
  4.   while (true) {
  5. //略
  6.       for (int i = pollFds.length - 1; i >= 0; --i) {
  7. //采用I/O多路复用机制,当客户端发出连接请求或者数据处理请求时,则执行continue
  8.           if ((pollFds[i].revents & POLLIN) == 0) {
  9.               continue;
  10.           }
  11.           if (i == 0) {
  12.   //有socket客户端连接上
  13.               ZygoteConnection newPeer = acceptCommandPeer(abiList);
  14.               peers.add(newPeer);
  15.               fds.add(newPeer.getFileDesciptor());
  16.           } else {
  17.               try {
  18. //客户端发送了请求,获取connection
  19.                   ZygoteConnection connection = peers.get(i);
  20. //[重]处理发送来的消息,其实这里就处理fork出子进程
  21. //切记,返回的是Runnable,这里进入
  22.                   final Runnable command = connection.processOneCommand(this);
  23. //这里要对fork有一定了解,创建子进程就是Zygote的分裂
  24. //下面的if语句都会执行
  25. //一个是走父进程流程关闭socket;一个是子进程流程,启动进程ActivityThread
  26.                   if (mIsForkChild) {
  27. //如果在子进程,command不为null
  28.                       if (command == null) {
  29.                           throw new IllegalStateException("command == null");
  30.                       }
  31.                       return command;
  32.                   } else {
  33. //父进程,command为null
  34.                       if (command != null) {
  35.                           throw new IllegalStateException("command != null");
  36.                       }
  37.                       //关闭socket等
  38.                       if (connection.isClosedByPeer()) {
  39.                           connection.closeSocket();
  40.                           peers.remove(i);
  41.                           fds.remove(i);
  42.                       }
  43.                   }
  44.               } catch (Exception e) {
  45. //略
  46.               } finally {
  47.                   mIsForkChild = false;
  48.               }
  49.           }
  50.       }
  51.   }
  52. }
复制

从socket中接收消息,然后进程fork出子进程(也就是从zygote中分裂而来)。

然后主进程流程关闭socket,子进程流程启动ActivityThread。

我们先挂住processOneCommand()这块。

ZygoteConnection.java

processOneCommand()
  1. Runnable processOneCommand(ZygoteServer zygoteServer) {
  2.   String args[];
  3.   Arguments parsedArgs = null;
  4.   FileDescriptor[] descriptors;
  5.   try {
  6. //从socket读取命令
  7.       args = readArgumentList();
  8.       descriptors = mSocket.getAncillaryFileDescriptors();
  9.   } catch (IOException ex) {
  10.       throw new IllegalStateException("IOException on command socket", ex);
  11.   }
  12. //如果没有参数,直接结束
  13.   if (args == null) {
  14.       isEof = true;
  15.       return null;
  16.   }
  17.   int pid = -1;
  18.   FileDescriptor childPipeFd = null;
  19.   FileDescriptor serverPipeFd = null;
  20. //创建Arguments对象,这里会解析args中的命令
  21.   parsedArgs = new Arguments(args);
  22. //根据参数值进行处理
  23.   if (parsedArgs.abiListQuery) {
  24.       handleAbiListQuery();
  25.       return null;
  26.   }
  27. //略
  28. //fork出子进程
  29. pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
  30.           parsedArgs.runtimeFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
  31.           parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.startChildZygote,
  32.           parsedArgs.instructionSet, parsedArgs.appDataDir);
  33.   try {
  34.       if (pid == 0) {
  35. //子进程流程
  36.           zygoteServer.setForkChild();
  37.           zygoteServer.closeServerSocket();
  38.           IoUtils.closeQuietly(serverPipeFd);
  39.           serverPipeFd = null;
  40. //[重]返回Runnable
  41.           return handleChildProc(parsedArgs, descriptors, childPipeFd,
  42.                   parsedArgs.startChildZygote);
  43.       } else {
  44.           IoUtils.closeQuietly(childPipeFd);
  45.           childPipeFd = null;
  46. //如果是父进程流程
  47.           handleParentProc(pid, descriptors, serverPipeFd);
  48.           return null;
  49.       }
  50.   } finally {
  51.       IoUtils.closeQuietly(childPipeFd);
  52.       IoUtils.closeQuietly(serverPipeFd);
  53.   }
  54. }
复制
handleChildProc()
  1. private Runnable handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors,
  2.       FileDescriptor pipeFd, boolean isZygote) {
  3. //关闭socket
  4.   closeSocket();
  5. //根据之前传入参数,invokeWith=null
  6.   if (parsedArgs.invokeWith != null) {
  7.       WrapperInit.execApplication(parsedArgs.invokeWith,
  8.               parsedArgs.niceName, parsedArgs.targetSdkVersion,
  9.               VMRuntime.getCurrentInstructionSet(),
  10.               pipeFd, parsedArgs.remainingArgs);
  11.       throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");
  12.   } else {
  13. //走这里
  14. //isZygote为false,是依赖parsedArgs.startChildZygote
  15.       if (!isZygote) {
  16.           return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs,
  17.                   null /* classLoader */);
  18.       } else {
  19.           return ZygoteInit.childZygoteInit(parsedArgs.targetSdkVersion,
  20.                   parsedArgs.remainingArgs, null /* classLoader */);
  21.       }
  22.   }
  23. }
复制

ZygoteInit.java

zygoteInit()
  1. public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
  2. //这参数是ActivityManagerService.java中startProcessLocked()中[上面倒数第二个]传入的
  3. //argv中带有android.app.ActivityThread参数。
  4.   Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
  5.   RuntimeInit.redirectLogStreams();
  6.   RuntimeInit.commonInit();
  7.   ZygoteInit.nativeZygoteInit();
  8.   return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
  9. }
复制

RuntimeInit.java

applicationInit()
  1. protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
  2.       ClassLoader classLoader) {
  3.   nativeSetExitWithoutCleanup(true);
  4.   VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
  5.   VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
  6.   final Arguments args = new Arguments(argv);
  7.   Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  8. //[重]看方法名就知道,找到main方法入口
  9. //args.startClass = android.app.ActivityThread
  10.   return findStaticMain(args.startClass, args.startArgs, classLoader);
  11. }
复制
findStaticMain()
  1. protected static Runnable findStaticMain(String className, String[] argv,
  2.       ClassLoader classLoader) {
  3.   Class<?> cl;
  4. //是不是很熟悉,反射
  5.   try {
  6.       cl = Class.forName(className, true, classLoader);
  7.   } catch (ClassNotFoundException ex) {
  8.       throw new RuntimeException(
  9.               "Missing class when invoking static main " + className,
  10.               ex);
  11.   }
  12.   Method m;
  13.   try {
  14. //查找main函数入口
  15.       m = cl.getMethod("main", new Class[] { String[].class });
  16.   } catch (NoSuchMethodException ex) {
  17.       throw new RuntimeException(
  18.               "Missing static main on " + className, ex);
  19.   } catch (SecurityException ex) {
  20.       throw new RuntimeException(
  21.               "Problem getting static main on " + className, ex);
  22.   }
  23.   int modifiers = m.getModifiers();
  24.   if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
  25.       throw new RuntimeException(
  26.               "Main method is not public and static on " + className);
  27.   }
  28. //创建MethodAndArgsCaller,MethodAndArgsCaller实现于Runnable
  29.   return new MethodAndArgsCaller(m, argv);
  30. }
复制
MethodAndArgsCaller
  1. static class MethodAndArgsCaller implements Runnable {
  2.   private final Method mMethod;
  3.   private final String[] mArgs;
  4.   public MethodAndArgsCaller(Method method, String[] args) {
  5.       mMethod = method;
  6.       mArgs = args;
  7.   }
  8.   public void run() {
  9.       try {
  10. //Method = com.android.server.SystemServer的main函数
  11. //这里会启动ActivityThread并执行main()方法
  12.           mMethod.invoke(null, new Object[] { mArgs });
  13.       } catch (IllegalAccessException ex) {
  14. //略
  15.       }
  16.   }
  17. }
复制

到这里,Runnable已经创建了,但之前仅仅是创建了Runnable,但没有执行run(),因此我们要回到runSelectLoop()中。

ZygoteServer.java

再次回答runSelectLoop()中,里面有这段代码[只是部分]

  1. try {
  2. //客户端发送了请求,获取connection
  3.   ZygoteConnection connection = peers.get(i);
  4. //[重]处理发送来的消息,其实这里就处理fork出子进程
  5. //切记,返回的是Runnable,这里进入
  6.   final Runnable command = connection.processOneCommand(this);
  7.   //这里要对fork有一定了解,创建子进程就是Zygote的分裂
  8.   //下面的if语句都会执行
  9.   //一个是走父进程流程关闭socket;一个是子进程流程,启动进程ActivityThread
  10.   if (mIsForkChild) {
  11. //如果在子进程,command不为null
  12.       if (command == null) {
  13.           throw new IllegalStateException("command == null");
  14.       }
  15.       return command;
  16.   } else {
  17. //父进程,command为null
  18.       if (command != null) {
  19.           throw new IllegalStateException("command != null");
  20.       }
  21.       //关闭socket等
  22.       if (connection.isClosedByPeer()) {
  23.           connection.closeSocket();
  24.           peers.remove(i);
  25.           fds.remove(i);
  26.       }
  27.   }
  28. } catch (Exception e) {
  29. //略
  30. } finally {
  31.   mIsForkChild = false;
  32. }
复制

上面也说了fork后,会有两个执行流程,一个是父进程流程,一个是子进程流程。我们关注子进程流程。

也就是mIsForkChild为true时,此时command不为null,而是

  1. command = new MethodAndArgsCaller(m, argv);
复制

也就是runSelectLoop()执行结束,并返回Runnable。

fork是把父类所有的资源都拷贝一份给子进程,因此,上面退出的runSelectLoop()循环是子类的。

子类用户父类Zygote一样的代码流程。ZygoteInit.java是进入Java世界的第一扇大门!

runSelectLoop()也是在ZygoteInit.java中main()方法中的。

ZygoteInit.java

  1. public static void main(String argv[]) {
  2.   //创建ZygoteServer
  3.   ZygoteServer zygoteServer = new ZygoteServer();
  4.   final Runnable caller;
  5.   try {
  6.       //略
  7.       //[重]循环中。对于zygote不会退出,至于fork的子进程,是会退出的
  8.       caller = zygoteServer.runSelectLoop(abiList);
  9.   } catch (Throwable ex) {
  10.       throw ex;
  11.   } finally {
  12.       //关闭socket
  13.       zygoteServer.closeServerSocket();
  14.   }
  15.   //子进程退出的caller不为null
  16.   if (caller != null) {
  17.       caller.run();
  18.   }
  19. }
复制

fork出的子进程才会退出runSelectLoop()循环,因此上面的call就是返回的Runnable对象,也就是这里main()方法结束后执行了

  1. MethodAndArgsCaller.run();
复制

然后进入了ActivityThread.java的main(),至于后面的,可以看《startActivity源码分析2》。

参考文章

  1. Zygote的启动之二ZygoteInit

  2. Zygote的启动之一app_main

  3. startActivity源码分析1

  4. startActivity源码分析2

  5. 《Android进阶解密-刘望舒》

相关文章

暂无评论

none
暂无评论...