接上一篇 走ZygoteInit
1.进入ZygoteInit的main
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) { 522 try { 523 // Start profiling the zygote initialization. 524 SamplingProfilerIntegration.start(); 525 526 registerZygoteSocket();//注册zygote的socket 527 EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, 528 SystemClock.uptimeMillis()); 529 preload(); //加载各种类、res、公共库、openGL、文本 ... 535 536 // Do an initial gc to clean up after startup 537 gc();//先来个初始化gc 538 539 // If requested, start system server directly from Zygote 540 if (argv.length != 2) { 541 throw new RuntimeException(argv[0] + USAGE_STRING); 542 } 543 544 if (argv[1].equals("start-system-server")) { 545 startSystemServer();//启动sysytemserver了(init.rc里面的参数) 546 } else if (!argv[1].equals("")) { 547 throw new RuntimeException(argv[0] + USAGE_STRING); 548 } 549 550 Log.i(TAG, "Accepting command socket connections"); 551 552 if (ZYGOTE_FORK_MODE) { 553 runForkMode(); /*ZYGOTE_FORK_MODE默认为false,如果为true的话,每收到一个连接请求, *就会建立一个新进程,然后再运行连接请求所要求执行的命令,此时会建立另一个新进程 */ 554 } else { 555 runSelectLoopMode(); //使用Select poll的方式来建立新进程,收到连接请求后,也会建立进程启动某个程序,使用loop循环。等待创建进程的socket请求 556 } 557 558 closeServerSocket();//关闭socket 559 } catch (MethodAndArgsCaller caller) { 560 caller.run();//执行新进程的main 561 } catch (RuntimeException ex) { 562 Log.e(TAG, "Zygote died with exception", ex); 563 closeServerSocket(); 564 throw ex; 565 } 566 }
2.主要看systemserver启动
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
/** 478 * Prepare the arguments and fork for the system server process. 479 */ 480 private static boolean startSystemServer() 481 throws MethodAndArgsCaller, RuntimeException { 482 /* Hardcoded command line to start the system server */ 483 String args[] = { 484 "--setuid=1000", 485 "--setgid=1000", 486 "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007", 487 "--capabilities=130104352,130104352", 488 "--runtime-init", 489 "--nice-name=system_server", 490 "com.android.server.SystemServer", 491 };//systemserver的默认参数 可以改变进程名字 492 ZygoteConnection.Arguments parsedArgs = null; 493 494 int pid; 495 496 try { 497 parsedArgs = new ZygoteConnection.Arguments(args); ... 501 /* Request to fork the system server process */ 502 pid = Zygote.forkSystemServer( 503 parsedArgs.uid, parsedArgs.gid, 504 parsedArgs.gids, 505 parsedArgs.debugFlags, 506 null, 507 parsedArgs.permittedCapabilities, 508 parsedArgs.effectiveCapabilities); 509 } catch (IllegalArgumentException ex) { 510 throw new RuntimeException(ex); 511 } 512 513 /* For child process */ 514 if (pid == 0) { 515 handleSystemServerProcess(parsedArgs); 516 } 517 518 return true; 519 }
@return 0 if this is the child, pid of the child if this is the parent, or -1 on error.
public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags, 162 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) { 163 preFork(); 164 int pid = nativeForkSystemServer( 165 uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities); 166 postFork(); 167 return pid; 168 }
nativeForkSystemServer方法,它对应的是Native方法是com_android_internal_os_Zygote_nativeForkSystemServer
dalvik/vm/native/dalvik_system_Zygote.cpp
static void Dalvik_dalvik_system_Zygote_forkSystemServer( 696 const u4* args, JValue* pResult) 697{ 698 pid_t pid; 699 pid = forkAndSpecializeCommon(args, true);//fork systemserver了 700 701 /* The zygote process checks whether the child process has died or not. */ 702 if (pid > 0) { 703 int status; 704 705 ALOGI("System server process %d has been created", pid); 706 gDvm.systemServerPid = pid; 707 /* There is a slight window that the system server process has crashed 708 * but it went unnoticed because we haven't published its pid yet. So 709 * we recheck here just to make sure that all is well. 710 */ 711 if (waitpid(pid, &status, WNOHANG) == pid) { 712 ALOGE("System server process %d has died. Restarting Zygote!", pid); 713 kill(getpid(), SIGKILL); 714 }//需要对子进程进行检查,判断system server进程是否died,如果died,则会终止runtime,并重启Zygote进程 715 } 716 RETURN_INT(pid); 717}
/dalvik/vm/native/dalvik_system_Zygote.cpp
487/* 488 * Utility routine to fork zygote and specialize the child process. 489 */ 490static pid_t forkAndSpecializeCommon(const u4* args, bool isSystemServer) 491{ ... 554 pid = fork(); 555 556 if (pid == 0) { 557 int err; 558 /* The child process */ 559 560#ifdef HAVE_ANDROID_OS 561 extern int gMallocLeakZygoteChild; 562 gMallocLeakZygoteChild = 1; 563 564 /* keep caps across UID change, unless we're staying root */ 565 if (uid != 0) { 566 err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); 567 568 if (err < 0) { 569 ALOGE("cannot PR_SET_KEEPCAPS: %s", strerror(errno)); 570 dvmAbort(); 571 } 572 } 573 574#endif /* HAVE_ANDROID_OS */ 575 576 if (mountMode != MOUNT_EXTERNAL_NONE) { 577 err = mountEmulatedStorage(uid, mountMode); 578 if (err < 0) { 579 ALOGE("cannot mountExternalStorage(): %s", strerror(errno)); 580 581 if (errno == ENOTCONN || errno == EROFS) { 582 // When device is actively encrypting, we get ENOTCONN here 583 // since FUSE was mounted before the framework restarted. 584 // When encrypted device is booting, we get EROFS since 585 // FUSE hasn't been created yet by init. 586 // In either case, continue without external storage. 587 } else { 588 dvmAbort(); 589 } 590 } 591 } 592 593 err = setgroupsIntarray(gids); 594 if (err < 0) { 595 ALOGE("cannot setgroups(): %s", strerror(errno)); 596 dvmAbort(); 597 } 598 599 err = setrlimitsFromArray(rlimits); 600 if (err < 0) { 601 ALOGE("cannot setrlimit(): %s", strerror(errno)); 602 dvmAbort(); 603 } 604 605 err = setgid(gid); 606 if (err < 0) { 607 ALOGE("cannot setgid(%d): %s", gid, strerror(errno)); 608 dvmAbort(); 609 } 610 611 err = setuid(uid); 612 if (err < 0) { 613 ALOGE("cannot setuid(%d): %s", uid, strerror(errno)); 614 dvmAbort(); 615 } 616 617 int current = personality(0xffffFFFF); 618 int success = personality((ADDR_NO_RANDOMIZE | current)); 619 if (success == -1) { 620 ALOGW("Personality switch failed. current=%d error=%d\n", current, errno); 621 } 622 623 err = setCapabilities(permittedCapabilities, effectiveCapabilities); 624 if (err != 0) { 625 ALOGE("cannot set capabilities (%llx,%llx): %s", 626 permittedCapabilities, effectiveCapabilities, strerror(err)); 627 dvmAbort(); 628 } 629 630 err = set_sched_policy(0, SP_DEFAULT); 631 if (err < 0) { 632 ALOGE("cannot set_sched_policy(0, SP_DEFAULT): %s", strerror(-err)); 633 dvmAbort(); 634 } 635 636#ifdef HAVE_SELINUX 637 err = setSELinuxContext(uid, isSystemServer, seInfo, niceName); 638 if (err < 0) { 639 ALOGE("cannot set SELinux context: %s\n", strerror(errno)); 640 dvmAbort(); 641 } 642 // These free(3) calls are safe because we know we're only ever forking 643 // a single-threaded process, so we know no other thread held the heap 644 // lock when we forked. 645 free(seInfo); 646 free(niceName); 647#endif 648 649 /* 650 * Our system thread ID has changed. Get the new one. 651 */ 652 Thread* thread = dvmThreadSelf(); 653 thread->systemTid = dvmGetSysThreadId(); 654 655 /* configure additional debug options */ 656 enableDebugFeatures(debugFlags); 657 658 unsetSignalHandler(); 659 gDvm.zygote = false; 660 if (!dvmInitAfterZygote()) { 661 ALOGE("error in post-zygote initialization"); 662 dvmAbort(); 663 } 664 } else if (pid > 0) { 665 /* the parent process */ 666#ifdef HAVE_SELINUX 667 free(seInfo); 668 free(niceName); 669#endif 670 } 671 672 return pid; 673}
3.看完forkSystemserver,再看handleSystemServerProcess
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static void handleSystemServerProcess( 451 ZygoteConnection.Arguments parsedArgs) 452 throws ZygoteInit.MethodAndArgsCaller { 453 454 closeServerSocket(); 455 456 // set umask to 0077 so new files and directories will default to owner-only permissions. 457 Libcore.os.umask(S_IRWXG | S_IRWXO); 458 459 if (parsedArgs.niceName != null) { 460 Process.setArgV0(parsedArgs.niceName); 461 } 462 463 if (parsedArgs.invokeWith != null) { 464 WrapperInit.execApplication(parsedArgs.invokeWith, 465 parsedArgs.niceName, parsedArgs.targetSdkVersion, 466 null, parsedArgs.remainingArgs); 467 } else { 468 /* 469 * Pass the remaining arguments to SystemServer. 470 */ 471 RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs);//启动systemServer 472 } 473 474 /* should never reach here */ 475 }
而zygoteInit里面调用nativeZygoteInit,又调用onZygoteInit,这里主要是为SystemServer开启线程池
看下applictionInit
frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
private static void applicationInit(int targetSdkVersion, String[] argv) 284 throws ZygoteInit.MethodAndArgsCaller { 285 // If the application calls System.exit(), terminate the process 286 // immediately without running any shutdown hooks. It is not possible to 287 // shutdown an Android application gracefully. Among other things, the 288 // Android runtime shutdown hooks close the Binder driver, which can cause 289 // leftover running threads to crash before the process actually exits. 290 nativeSetExitWithoutCleanup(true); 291 292 // We want to be fairly aggressive about heap utilization, to avoid 293 // holding on to a lot of memory that isn't needed. 294 VMRuntime.getRuntime().setTargetHeapUtilization(0.75f); 295 VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion); 296 297 final Arguments args; 298 try { 299 args = new Arguments(argv); 300 } catch (IllegalArgumentException ex) { 301 Slog.e(TAG, ex.getMessage()); 302 // let the process exit 303 return; 304 } 305 306 // Remaining arguments are passed to the start class's static main 307 invokeStaticMain(args.startClass, args.startArgs); 308 }
通过Java的反射机制,借助传入的参数以及类加载器,从而获取systemserver进程的main方法,最后再抛出一个MethodAndArgsCaller的异常
这个异常在ZygoteInit的main方法的最后会进行截取,调用caller.run(),ercaller就是MethodandArgsCller,run()就是运行这个class的main方法,而class在startSystemServer时定义的com.android.server.SystemServer
public void run() { 792 try { 793 mMethod.invoke(null, new Object[] { mArgs }); 794 } catch (IllegalAccessException ex) { 795 throw new RuntimeException(ex); 796 } catch (InvocationTargetException ex) { 797 Throwable cause = ex.getCause(); 798 if (cause instanceof RuntimeException) { 799 throw (RuntimeException) cause; 800 } else if (cause instanceof Error) { 801 throw (Error) cause; 802 } 803 throw new RuntimeException(ex); 804 } 805 }