System Server进程启动过程源码分析

本文详细解读了SystemServer进程在Zygote进程中的创建、属性配置、fork系统服务器的过程,直至SystemServer进程启动执行的主要操作。包括进程名称设置、权限与能力配置、进程初始化与线程管理等关键步骤,以及SystemServer进程内部启动流程,如Socket关闭、系统输出流设置、进程名称设置、应用执行与Binder初始化等。

SystemServer进程创建过程

SystemServer进程名称为System_Server,在Zygote进程启动过程源码分析一文中介绍了zygote进程通过startSystemServer函数调用将启动一个SystemServer子进程:

private static boolean startSystemServer()
		throws MethodAndArgsCaller, RuntimeException {
	/* 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,3001,3002,3003,3006,3007",
		"--capabilities=130104352,130104352",
		"--runtime-init",
		"--nice-name=system_server",
		"com.android.server.SystemServer",
	};
	ZygoteConnection.Arguments parsedArgs = null;
	int pid;
	try {
		//参数解析
		parsedArgs = new ZygoteConnection.Arguments(args);
		//打开系统调试属性
		ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
		ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

		/* 请求fork SystemServer进程*/
		pid = Zygote.forkSystemServer(
				parsedArgs.uid, parsedArgs.gid,
				parsedArgs.gids,
				parsedArgs.debugFlags,
				null,
				parsedArgs.permittedCapabilities,
				parsedArgs.effectiveCapabilities);
	} catch (IllegalArgumentException ex) {
		throw new RuntimeException(ex);
	}

	/* pid为0表示子进程,即SystemServer进程,从此SystemServer进程与Zygote进程分道扬镳*/
	if (pid == 0) {
		handleSystemServerProcess(parsedArgs);
	}
	return true;
}

参数解析

private void parseArgs(String args[])throws IllegalArgumentException {
	int curArg = 0;
	//遍历所有的命令参数
	for ( /* curArg */ ; curArg < args.length; curArg++) {
		String arg = args[curArg];
	
		if (arg.equals("--")) {
			curArg++;  
			break;
		} else if (arg.startsWith("--setuid=")) {
			if (uidSpecified) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			uidSpecified = true;
			//uid = 1000
			uid = Integer.parseInt(arg.substring(arg.indexOf('=') + 1));
		} else if (arg.startsWith("--setgid=")) {
			if (gidSpecified) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			gidSpecified = true;
			//gid =1000
			gid = Integer.parseInt(arg.substring(arg.indexOf('=') + 1));
		} else if (arg.startsWith("--target-sdk-version=")) {
			if (targetSdkVersionSpecified) {
				throw new IllegalArgumentException("Duplicate target-sdk-version specified");
			}
			targetSdkVersionSpecified = true;
			targetSdkVersion = Integer.parseInt(arg.substring(arg.indexOf('=') + 1));
		} else if (arg.equals("--enable-debugger")) {
			debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
		} else if (arg.equals("--enable-safemode")) {
			debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
		} else if (arg.equals("--enable-checkjni")) {
			debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
		} else if (arg.equals("--enable-jni-logging")) {
			debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
		} else if (arg.equals("--enable-assert")) {
			debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
		} else if (arg.equals("--peer-wait")) {
			peerWait = true;
		} else if (arg.equals("--runtime-init")) {
			//runtimeInit = true
			runtimeInit = true;
		} else if (arg.startsWith("--capabilities=")) {
			if (capabilitiesSpecified) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			capabilitiesSpecified = true;
			String capString = arg.substring(arg.indexOf('=')+1);
			String[] capStrings = capString.split(",", 2);
			if (capStrings.length == 1) {
				effectiveCapabilities = Long.decode(capStrings[0]);
				permittedCapabilities = effectiveCapabilities;
			} else {
				//permittedCapabilities = 130104352
				//effectiveCapabilities = 130104352
				permittedCapabilities = Long.decode(capStrings[0]);
				effectiveCapabilities = Long.decode(capStrings[1]);
			}
		} else if (arg.startsWith("--rlimit=")) {
			// Duplicate --rlimit arguments are specifically allowed.
			String[] limitStrings = arg.substring(arg.indexOf('=')+1).split(",");
			if (limitStrings.length != 3) {
				throw new IllegalArgumentException("--rlimit= should have 3 comma-delimited ints");
			}
			int[] rlimitTuple = new int[limitStrings.length];

			for(int i=0; i < limitStrings.length; i++) {
				rlimitTuple[i] = Integer.parseInt(limitStrings[i]);
			}

			if (rlimits == null) {
				rlimits = new ArrayList();
			}
			rlimits.add(rlimitTuple);
		} else if (arg.equals("-classpath")) {
			if (classpath != null) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			try {
				classpath = args[++curArg];
			} catch (IndexOutOfBoundsException ex) {
				throw new IllegalArgumentException("-classpath requires argument");
			}
		} else if (arg.startsWith("--setgroups=")) {
			if (gids != null) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			//1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007
			String[] params= arg.substring(arg.indexOf('=') + 1).split(",");
			gids = new int[params.length];
			for (int i = params.length - 1; i >= 0 ; i--) {
				gids[i] = Integer.parseInt(params[i]);
			}
		} else if (arg.equals("--invoke-with")) {
			if (invokeWith != null) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			try {
				invokeWith = args[++curArg];
			} catch (IndexOutOfBoundsException ex) {
				throw new IllegalArgumentException("--invoke-with requires argument");
			}
		} else if (arg.startsWith("--nice-name=")) {
			if (niceName != null) {
				throw new IllegalArgumentException("Duplicate arg specified");
			}
			//niceName = system_server
			niceName = arg.substring(arg.indexOf('=') + 1);
		} else {
			break;
		}
	}
	//runtimeInit = true  classpath == null
	if (runtimeInit && classpath != null) {
		throw new IllegalArgumentException("--runtime-init and -classpath are incompatible");
	}
	remainingArgs = new String[args.length - curArg];
	//remainingArgs = "com.android.server.SystemServer"
	System.arraycopy(args, curArg, remainingArgs, 0,remainingArgs.length);
}

属性配置

public static void applyDebuggerSystemProperty(Arguments args) {
	if ("1".equals(SystemProperties.get("ro.debuggable"))) {
		args.debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
	}
}

public static void applyInvokeWithSystemProperty(Arguments args) {
	if (args.invokeWith == null && args.niceName != null) { //true
		if (args.niceName != null) {
			String property = "wrap." + args.niceName; //wrap.system_server
			if (property.length() > 31) {
				property = property.substring(0, 31);
			}
			args.invokeWith = SystemProperties.get(property);
			if (args.invokeWith != null && args.invokeWith.length() == 0) {
				args.invokeWith = null;
			}
		}
	}
}

fork SystemServer进程

通过调用forkSystemServer函数来完成的

public static int forkSystemServer(int uid, int gid, int[] gids,
		int debugFlags, int[][] rlimits,
		long permittedCapabilities, long effectiveCapabilities) {
	//停止Zygote进程中的其他线程,保证单线程
	preFork();
	int pid = nativeForkSystemServer(uid, gid, gids, debugFlags, rlimits,
									 permittedCapabilities,
									 effectiveCapabilities);
	//启动垃圾回收后台线程
	postFork();
	return pid;
}

private static void preFork() {
	Daemons.stop(); //停止进程内的其他后台线程
	waitUntilAllThreadsStopped(); //等待
}

/**
 * We must not fork until we're single-threaded again. Wait until /proc shows we're
 * down to just one thread.
 */
private static void waitUntilAllThreadsStopped() {
	File tasks = new File("/proc/self/task");//如果/proc/self/task目录下的文件个数大于1,说明还有其他线程在运行
	while (tasks.list().length > 1) {
		try {
			// Experimentally, booting and playing about with a stingray, I never saw us
			// go round this loop more than once with a 10ms sleep.
			Thread.sleep(10);
		} catch (InterruptedException ignored) {
		}
	}
}

private static void postFork() {
	Daemons.start();
}

最后调用native函数nativeForkAndSpecialize来fork出systemserver进程

native public static int nativeForkSystemServer(int uid, int gid,int[] gids, int debugFlags, int[][] rlimits,
            long permittedCapabilities, long effectiveCapabilities);
{ "nativeForkSystemServer", "(II[II[[IJJ)I", Dalvik_dalvik_system_Zygote_forkSystemServer },

根据JNI函数映射关系,最终会调用C++的Dalvik_dalvik_system_Zygote_forkSystemServer函数,在dalvik_system_Zygote.c文件中实现:

static void Dalvik_dalvik_system_Zygote_forkSystemServer(const u4* args, JValue* pResult)
{
    pid_t pid;
    //根据参数,fork一个子进程
    pid = forkAndSpecializeCommon(args, true);

    /* The zygote process checks whether the child process has died or not. */
    if (pid > 0) {
        int status;
     
        ALOGI("System server process %d has been created", pid);
        gDvm.systemServerPid = pid;
        /* There is a slight window that the system server process has crashed
         * but it went unnoticed because we haven't published its pid yet. So
         * we recheck here just to make sure that all is well.
         */
        if (waitpid(pid, &status, WNOHANG) == pid) {
            ALOGE("System server process %d has died. Restarting Zygote!", pid);
            /*kill(getpid(), SIGKILL);*/
            sleep(15);
	  //如果SystemServer进程退出,zygote将杀死自身进程
#ifdef HOST_DALVIK
            reboot(RB_AUTOBOOT);
#else
            android_reboot(ANDROID_RB_RESTART2, 0, (char *)"special-systemserver-died");
#endif
        }
    }
    RETURN_INT(pid);
}

真正创建进程的核心函数:

static pid_t forkAndSpecializeCommon(const u4* args, bool isSystemServer)
{
    ..........
    pid = fork(); //使用Linux 系统调用fork来创建进程

    if (pid == 0) {
		//设置子进程的uid,gid等参数

    } else if (pid > 0) {
        /* the parent process */
    }
    return pid;
}

SystemServer进程启动过程


新创建的进程会执行handleSystemServerProcess函数,来完成自己的使命。

private static void handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs)
		throws ZygoteInit.MethodAndArgsCaller {
          //因为SystemServer是从Zygote进程中复制过来的,所有需要关闭从zygote继承下来的socket
	closeServerSocket();
	// set umask to 0077 so new files and directories will default to owner-only permissions.
	FileUtils.setUMask(FileUtils.S_IRWXG | FileUtils.S_IRWXO);
          //设置进程名称
	if (parsedArgs.niceName != null) {
		Process.setArgV0(parsedArgs.niceName);
	}
         //parsedArgs.invokeWith == null
	if (parsedArgs.invokeWith != null) {
		WrapperInit.execApplication(parsedArgs.invokeWith,
				parsedArgs.niceName, parsedArgs.targetSdkVersion,
				null, parsedArgs.remainingArgs);
	} else {
         		//传递剩余参数给SystemServer并调用zygoteInit函数
           	// "--nice-name=system_server com.android.server.SystemServer"
		RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs);
	}
}
由于由Zygote进程创建的子进程会继承Zygote进程在前面创建的Socket文件描述符,而这里的子进程又不会用到它,因此,这里就调用closeServerSocket函数来关闭它。这个函数接着调用RuntimeInit.zygoteInit函数来进一步执行启动SystemServer组件的操作。
RuntimeInit.java

public static final void zygoteInit(String[] argv)
            throws ZygoteInit.MethodAndArgsCaller {
        //设置系统输出流
        System.setOut(new AndroidPrintStream(Log.INFO, "System.out"));
        System.setErr(new AndroidPrintStream(Log.WARN, "System.err"));
        //常规初始化
        commonInit();
        //执行一个Binder进程间通信机制的初始化工作,这个工作完成之后,这个进程中的Binder对象就可以方便地进行进程间通信了
        zygoteInitNative();

        int curArg = 0;
        //argv = ["--nice-name=system_server, com.android.server.SystemServer"]
        for ( ; curArg < argv.length; curArg++) {
            String arg = argv[curArg];

            if (arg.equals("--")) {
                curArg++;
                break;
            } else if (!arg.startsWith("--")) {
                break;
            } else if (arg.startsWith("--nice-name=")) {
                String niceName = arg.substring(arg.indexOf('=') + 1);
                Process.setArgV0(niceName);//设置进程名称为system_server
            }
        }

        if (curArg == argv.length) {
            Slog.e(TAG, "Missing classname argument to RuntimeInit!");
            // let the process exit
            return;
        }

        // Remaining arguments are passed to the start class's static main
        String startClass = argv[curArg++];//startClass =“com.android.server.SystemServer”
        String[] startArgs = new String[argv.length - curArg];

        System.arraycopy(argv, curArg, startArgs, 0, startArgs.length);
        //调用SystemServer类中的main函数
        invokeStaticMain(startClass, startArgs);
    }

这个函数会执行两个操作:

一个是调用zygoteInitNative函数来执行一个Binder进程间通信机制的初始化工作;

一个是调用com.android.server.SystemServer类的main函数;

public static final native void zygoteInitNative();
static JNINativeMethod gMethods[] = 
{
    { "finishInit", "()V",(void*) com_android_internal_os_RuntimeInit_finishInit },
    { "zygoteInitNative", "()V",(void*) com_android_internal_os_RuntimeInit_zygoteInit },
    { "isComputerOn", "()I",(void*) com_android_internal_os_RuntimeInit_isComputerOn },
    { "turnComputerOn", "()V",(void*) com_android_internal_os_RuntimeInit_turnComputerOn },    
    { "getQwertyKeyboard", "()I",(void*) com_android_internal_os_RuntimeInit_getQwertyKeyboard },
};
static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}
由于SystemServer 是由zygote fork出来,因此它也拥有zygote进程中的gCurRuntime,也就是AppRuntime

virtual void onZygoteInit()
{
   sp<ProcessState> proc = ProcessState::self();
   if (proc->supportsProcesses()) {
      LOGV("App process: starting thread pool.\n");
      proc->startThreadPool(); //启动一个线程,用于binder通信
   }       
}
因此通过调用zygoteInitNative函数,将建立Binder通信。

调用invokeStaticMain函数:

private static void invokeStaticMain(String className, String[] argv)
            throws ZygoteInit.MethodAndArgsCaller {

        // We want to be fairly aggressive about heap utilization, to avoid
        // holding on to a lot of memory that isn't needed.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);

        Class<?> cl;

        try {
            //com.android.server.SystemServer,通过反射加载SystemServer类
            cl = Class.forName(className);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Missing class when invoking static main " + className,ex);
        }

        Method m;
        try {
            m = cl.getMethod("main", new Class[] { String[].class });//获取SystemServer类的main方法
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException("Missing static main on " + className, ex);
        } catch (SecurityException ex) {
            throw new RuntimeException("Problem getting static main on " + className, ex);
        }

        int modifiers = m.getModifiers();
        if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
            throw new RuntimeException("Main method is not public and static on " + className);
        }

        /*
         * This throw gets caught in ZygoteInit.main(), which responds
         * by invoking the exception's run() method. This arrangement
         * clears up all the stack frames that were required in setting
         * up the process. 抛出MethodAndArgsCaller异常,并在ZygoteInit.main()函数里铺货
         */
        throw new ZygoteInit.MethodAndArgsCaller(m, argv);
    }
抛出的MethodAndArgsCaller异常会在ZygoteInit.java 中的main函数捕获:

public static void main(String argv[]) {
        try {
            VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024);

            // Start profiling the zygote initialization.
            SamplingProfilerIntegration.start();

            registerZygoteSocket();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            preloadClasses();
            //cacheRegisterMaps();
            preloadResources();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());

            // Finish profiling the zygote initialization.
            SamplingProfilerIntegration.writeZygoteSnapshot();

            // Do an initial gc to clean up after startup
            gc();

            // If requested, start system server directly from Zygote
            if (argv.length != 2) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }

            if (argv[1].equals("true")) {
                startSystemServer();
            } else if (!argv[1].equals("false")) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }

            Log.i(TAG, "Accepting command socket connections");

            if (ZYGOTE_FORK_MODE) {
                runForkMode();
            } else {
                runSelectLoopMode();
            }

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }
public void run() {
    try {
   //mMethod 是SystemServer类的main方法   
   mMethod.invoke(null, new Object[] { mArgs });
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        }
        throw new RuntimeException(ex);
    }
}
SystemServer.java

public static void main(String[] args) {
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            // If a device's clock is before 1970 (before 0), a lot of
            // APIs crash dealing with negative numbers, notably
            // java.io.File#setLastModified, so instead we fake it and
            // hope that time from cell towers or NTP fixes it
            // shortly.
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

        if (SamplingProfilerIntegration.isEnabled()) {
            //启动性能统计
            SamplingProfilerIntegration.start();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
		    //输出性能统计结果
                    SamplingProfilerIntegration.writeSnapshot("system_server");
                }
            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
        }

        // The system server has to run all of the time, so it needs to be
        // as efficient as possible with its memory usage.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        //加载android_servers.so库
        System.loadLibrary("android_servers");
        init1(args);
    }

抛出MethodAndArgsCaller异常会导致com.android.server.SystemServer类的main函数被调用。为什么采用这种方式来调用呢,读者可以自行研究!

native public static void init1(String[] args);
com_android_server_SystemServer.cpp

static JNINativeMethod gMethods[] = {
    /* name, signature, funcPtr */
    { "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },
};

extern "C" int system_init();

static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
    system_init();
}
System_init.cpp

extern "C" status_t system_init()
{
    LOGI("Entered system_init()");
    
    sp<ProcessState> proc(ProcessState::self());
    //获取Service manager的远程调用接口
    sp<IServiceManager> sm = defaultServiceManager();
    LOGI("ServiceManager: %p\n", sm.get());
    
    sp<GrimReaper> grim = new GrimReaper();
    sm->asBinder()->linkToDeath(grim, grim.get(), 0);
    
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsurfaceflinger", propBuf, "1");
    //在SystemServer中启动各种服务
    if (strcmp(propBuf, "1") == 0) {
        // Start the SurfaceFlinger
        SurfaceFlinger::instantiate();
    }

    // Start the sensor service
    SensorService::instantiate();

    // On the simulator, audioflinger et al don't get started the
    // same way as on the device, and we need to start them here
    if (!proc->supportsProcesses()) {

        // Start the AudioFlinger
        AudioFlinger::instantiate();

        // Start the media playback service
        MediaPlayerService::instantiate();

        // Start the camera service
        CameraService::instantiate();

        // Start the audio policy service
        AudioPolicyService::instantiate();
    }

    // And now start the Android runtime.  We have to do this bit
    // of nastiness because the Android runtime initialization requires
    // some of the core system services to already be started.
    // All other servers should just start the Android runtime at
    // the beginning of their processes's main(), before calling
    // the init function.
    LOGI("System server: starting Android runtime.\n");
    
    AndroidRuntime* runtime = AndroidRuntime::getRuntime();

    LOGI("System server: starting Android services.\n");
    //调用SystemServer.java 类中的init2函数
    runtime->callStatic("com/android/server/SystemServer", "init2");
        
    // If running in our own process, just go into the thread
    // pool.  Otherwise, call the initialization finished
    // func to let this process continue its initilization.
  //将SystemServer进程的主线程加入Binder通信中
  if (proc->supportsProcesses()) {
        LOGI("System server: entering thread pool.\n");
        ProcessState::self()->startThreadPool();
        IPCThreadState::self()->joinThreadPool();
        LOGI("System server: exiting thread pool.\n");
    }
    return NO_ERROR;
}
这里的main函数首先会执行JNI方法init1,然后init1会调用这里的init2函数,在init2函数里面,会创建一个ServerThread线程对象来执行一些系统关键服务的启动操作:

public static final void init2() {
        Slog.i(TAG, "Entered the Android system server!");
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
	//启动一个线程
        thr.start();
}
init2只是简单创建一个线程,在该ServerThread线程中启动各种系统服务:

    @Override
    public void run() {
        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
            SystemClock.uptimeMillis());

        Looper.prepare();

        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);

        BinderInternal.disableBackgroundScheduling(true);
        android.os.Process.setCanSelfBackground(false);

        // Check whether we failed to shut down last time we tried.
        {
            final String shutdownAction = SystemProperties.get(
                    ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
            if (shutdownAction != null && shutdownAction.length() > 0) {
                boolean reboot = (shutdownAction.charAt(0) == '1');

                final String reason;
                if (shutdownAction.length() > 1) {
                    reason = shutdownAction.substring(1, shutdownAction.length());
                } else {
                    reason = null;
                }

                ShutdownThread.rebootOrShutdown(reboot, reason);
            }
        }

        String factoryTestStr = SystemProperties.get("ro.factorytest");
        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
                : Integer.parseInt(factoryTestStr);

        LightsService lights = null;
        PowerManagerService power = null;
        BatteryService battery = null;
        ConnectivityService connectivity = null;
        IPackageManager pm = null;
        Context context = null;
        WindowManagerService wm = null;
        BluetoothService bluetooth = null;
        BluetoothA2dpService bluetoothA2dp = null;
        HeadsetObserver headset = null;
        DockObserver dock = null;
        UsbService usb = null;
        UiModeManagerService uiMode = null;
        RecognitionManagerService recognition = null;
        ThrottleService throttle = null;

        // Critical services...
        try {
            Slog.i(TAG, "Entropy Service");
            ServiceManager.addService("entropy", new EntropyService());

            Slog.i(TAG, "Power Manager");
            power = new PowerManagerService();
            ServiceManager.addService(Context.POWER_SERVICE, power);

            Slog.i(TAG, "Activity Manager");
            context = ActivityManagerService.main(factoryTest);

            Slog.i(TAG, "Telephony Registry");
            if (PhoneFactory.isMultiSim()) {
                TelephonyRegistry[] telephonyRegistry = new TelephonyRegistry[PhoneFactory.getPhoneCount()];
                for (int i = 0; i < PhoneFactory.getPhoneCount(); i++) {
                    telephonyRegistry[i] = new TelephonyRegistry(context, i);
                    ServiceManager.addService(PhoneFactory.getServiceName("telephony.registry", i),
                            telephonyRegistry[i]);
                }
                ServiceManager.addService("telephony.registry",
                        new CompositeTelephonyRegistry(context, telephonyRegistry));
            } else {
                ServiceManager.addService("telephony.registry",
                        new TelephonyRegistry(context, 0));
            }

            AttributeCache.init(context);

            Slog.i(TAG, "Package Manager");
            pm = PackageManagerService.main(context,
                    factoryTest != SystemServer.FACTORY_TEST_OFF);

            ActivityManagerService.setSystemProcess();

            mContentResolver = context.getContentResolver();

            // The AccountManager must come before the ContentService
            try {
                Slog.i(TAG, "Account Manager");
                ServiceManager.addService(Context.ACCOUNT_SERVICE,
                        new AccountManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Account Manager", e);
            }

            Slog.i(TAG, "Content Manager");
            ContentService.main(context,
                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);

            Slog.i(TAG, "System Content Providers");
            ActivityManagerService.installSystemProviders();

            Slog.i(TAG, "Battery Service");
            battery = new BatteryService(context);
            ServiceManager.addService("battery", battery);

            Slog.i(TAG, "Lights Service");
            lights = new LightsService(context);

            Slog.i(TAG, "Vibrator Service");
            ServiceManager.addService("vibrator", new VibratorService(context));

            // only initialize the power service after we have started the
            // lights service, content providers and the battery service.
            power.init(context, lights, ActivityManagerService.getDefault(), battery);

            Slog.i(TAG, "Alarm Manager");
            AlarmManagerService alarm = new AlarmManagerService(context);
            ServiceManager.addService(Context.ALARM_SERVICE, alarm);

            Slog.i(TAG, "Init Watchdog");
            Watchdog.getInstance().init(context, battery, power, alarm,
                    ActivityManagerService.self());

            Slog.i(TAG, "Window Manager");
            wm = WindowManagerService.main(context, power,
                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);

            ((ActivityManagerService)ServiceManager.getService("activity"))
                    .setWindowManager(wm);

            // Skip Bluetooth if we have an emulator kernel
            // TODO: Use a more reliable check to see if this product should
            // support Bluetooth - see bug 988521
            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
                Slog.i(TAG, "Registering null Bluetooth Service (emulator)");
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
                Slog.i(TAG, "Registering null Bluetooth Service (factory test)");
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
            } else {
                Slog.i(TAG, "Bluetooth Service");
                bluetooth = new BluetoothService(context);
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
                bluetooth.initAfterRegistration();
                bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
                ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
                                          bluetoothA2dp);

                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
                    Settings.Secure.BLUETOOTH_ON, 0);
                if (bluetoothOn > 0) {
                    bluetooth.enable();
                }
            }

        } catch (RuntimeException e) {
            Slog.e("System", "Failure starting core service", e);
        }

        DevicePolicyManagerService devicePolicy = null;
        StatusBarManagerService statusBar = null;
        InputMethodManagerService imm = null;
        AppWidgetService appWidget = null;
        NotificationManagerService notification = null;
        WallpaperManagerService wallpaper = null;
        LocationManagerService location = null;

        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
            try {
                Slog.i(TAG, "Device Policy");
                devicePolicy = new DevicePolicyManagerService(context);
                ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DevicePolicyService", e);
            }

            try {
                Slog.i(TAG, "Status Bar");
                statusBar = new StatusBarManagerService(context);
                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting StatusBarManagerService", e);
            }

            try {
                Slog.i(TAG, "Clipboard Service");
                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
                        new ClipboardService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Clipboard Service", e);
            }

            try {
                Slog.i(TAG, "Input Method Service");
                imm = new InputMethodManagerService(context, statusBar);
                ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Input Manager Service", e);
            }

            try {
                Slog.i(TAG, "NetStat Service");
                ServiceManager.addService("netstat", new NetStatService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting NetStat Service", e);
            }

            try {
                Slog.i(TAG, "NetworkManagement Service");
                ServiceManager.addService(
                        Context.NETWORKMANAGEMENT_SERVICE,
                        NetworkManagementService.create(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting NetworkManagement Service", e);
            }

            try {
                Slog.i(TAG, "Connectivity Service");
                connectivity = ConnectivityService.getInstance(context);
                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Connectivity Service", e);
            }

            try {
                Slog.i(TAG, "Throttle Service");
                throttle = new ThrottleService(context);
                ServiceManager.addService(
                        Context.THROTTLE_SERVICE, throttle);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting ThrottleService", e);
            }

            try {
              Slog.i(TAG, "Accessibility Manager");
              ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
                      new AccessibilityManagerService(context));
            } catch (Throwable e) {
              Slog.e(TAG, "Failure starting Accessibility Manager", e);
            }

            try {
                /*
                 * NotificationManagerService is dependant on MountService,
                 * (for media / usb notifications) so we must start MountService first.
                 */
                Slog.i(TAG, "Mount Service");
                ServiceManager.addService("mount", new MountService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Mount Service", e);
            }

            try {
                Slog.i(TAG, "Notification Manager");
                notification = new NotificationManagerService(context, statusBar, lights);
                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Notification Manager", e);
            }

            try {
                Slog.i(TAG, "Device Storage Monitor");
                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
                        new DeviceStorageMonitorService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DeviceStorageMonitor service", e);
            }

            try {
                Slog.i(TAG, "Location Manager");
                location = new LocationManagerService(context);
                ServiceManager.addService(Context.LOCATION_SERVICE, location);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Location Manager", e);
            }

            try {
                Slog.i(TAG, "Search Service");
                ServiceManager.addService(Context.SEARCH_SERVICE,
                        new SearchManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Search Service", e);
            }

            if (INCLUDE_DEMO) {
                Slog.i(TAG, "Installing demo data...");
                (new DemoThread(context)).start();
            }

            try {
                Slog.i(TAG, "DropBox Service");
                ServiceManager.addService(Context.DROPBOX_SERVICE,
                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DropBoxManagerService", e);
            }

            try {
                Slog.i(TAG, "Wallpaper Service");
                wallpaper = new WallpaperManagerService(context);
                ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Wallpaper Service", e);
            }

            try {
                Slog.i(TAG, "Audio Service");
                ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Audio Service", e);
            }

            try {
                Slog.i(TAG, "Headset Observer");
                // Listen for wired headset changes
                headset = new HeadsetObserver(context);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting HeadsetObserver", e);
            }

            try {
                Slog.i(TAG, "Dock Observer");
                // Listen for dock station changes
                dock = new DockObserver(context, power);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DockObserver", e);
            }

            try {
                Slog.i(TAG, "USB Service");
                // Listen for USB changes
                usb = new UsbService(context);
                ServiceManager.addService(Context.USB_SERVICE, usb);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting UsbService", e);
            }

            try {
                Slog.i(TAG, "UI Mode Manager Service");
                // Listen for UI mode changes
                uiMode = new UiModeManagerService(context);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting UiModeManagerService", e);
            }

            try {
                Slog.i(TAG, "Backup Service");
                ServiceManager.addService(Context.BACKUP_SERVICE,
                        new BackupManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Backup Service", e);
            }

            try {
                Slog.i(TAG, "AppWidget Service");
                appWidget = new AppWidgetService(context);
                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting AppWidget Service", e);
            }

            try {
                Slog.i(TAG, "Recognition Service");
                recognition = new RecognitionManagerService(context);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Recognition Service", e);
            }
            
            try {
                Slog.i(TAG, "DiskStats Service");
                ServiceManager.addService("diskstats", new DiskStatsService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DiskStats Service", e);
            }

            try {
                Slog.i(TAG, "AnotherWatchdog Service");
                ServiceManager.addService("another_watchdog", new AnotherWatchdogService());
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting AnotherWatchdog Service", e);
            }
        }

        // make sure the ADB_ENABLED setting value matches the secure property value
        Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
                "1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);

        // register observer to listen for settings changes
        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
                false, new AdbSettingsObserver());

        // Before things start rolling, be sure we have decided whether
        // we are in safe mode.
        final boolean safeMode = wm.detectSafeMode();
        if (safeMode) {
            try {
                ActivityManagerNative.getDefault().enterSafeMode();
                // Post the safe mode state in the Zygote class
                Zygote.systemInSafeMode = true;
                // Disable the JIT for the system_server process
                VMRuntime.getRuntime().disableJitCompilation();
            } catch (RemoteException e) {
            }
        } else {
            // Enable the JIT for the system_server process
            VMRuntime.getRuntime().startJitCompilation();
        }

        // It is now time to start up the app processes...

        if (devicePolicy != null) {
            devicePolicy.systemReady();
        }

        if (notification != null) {
            notification.systemReady();
        }

        if (statusBar != null) {
            statusBar.systemReady();
        }
        wm.systemReady();
        power.systemReady();
        try {
            pm.systemReady();
        } catch (RemoteException e) {
        }

        // These are needed to propagate to the runnable below.
        final StatusBarManagerService statusBarF = statusBar;
        final BatteryService batteryF = battery;
        final ConnectivityService connectivityF = connectivity;
        final DockObserver dockF = dock;
        final UsbService usbF = usb;
        final ThrottleService throttleF = throttle;
        final UiModeManagerService uiModeF = uiMode;
        final AppWidgetService appWidgetF = appWidget;
        final WallpaperManagerService wallpaperF = wallpaper;
        final InputMethodManagerService immF = imm;
        final RecognitionManagerService recognitionF = recognition;
        final LocationManagerService locationF = location;

        // We now tell the activity manager it is okay to run third party
        // code.  It will call back into us once it has gotten to the state
        // where third party code can really run (but before it has actually
        // started launching the initial applications), for us to complete our
        // initialization.
        ((ActivityManagerService)ActivityManagerNative.getDefault())
                .systemReady(new Runnable() {
            public void run() {
                Slog.i(TAG, "Making services ready");

                if (statusBarF != null) statusBarF.systemReady2();
                if (batteryF != null) batteryF.systemReady();
                if (connectivityF != null) connectivityF.systemReady();
                if (dockF != null) dockF.systemReady();
                if (usbF != null) usbF.systemReady();
                if (uiModeF != null) uiModeF.systemReady();
                if (recognitionF != null) recognitionF.systemReady();
                Watchdog.getInstance().start();

                // It is now okay to let the various system services start their
                // third party code...

                if (appWidgetF != null) appWidgetF.systemReady(safeMode);
                if (wallpaperF != null) wallpaperF.systemReady();
                if (immF != null) immF.systemReady();
                if (locationF != null) locationF.systemReady();
                if (throttleF != null) throttleF.systemReady();
            }
        });

	(new Thread(new WakelockMonitor(power))).start();
        // For debug builds, log event loop stalls to dropbox for analysis.
        if (StrictMode.conditionallyEnableDebugLogging()) {
            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
        }

        Looper.loop();
        Slog.d(TAG, "System ServerThread is exiting!");
    }

在run函数中启动Java中的各种Service。至此SystemServer进程启动过程分析完毕!启动过程序列图如下所示:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值