Android系统启动流程--system_server进程的启动流程

     紧接上一篇zygote进程的启动流程,上一篇的结尾提到zygote进程中会fock出一个system_server进程,用于启动和管理Android系统中大部分的系统服务,本篇就来分析system_server进程是如何创建并运行的以及它都做了哪些重要的工作。

//文件路径:frameworks\base\core\java\com\android\internal\os\ZygoteInit.java	
public static void main(String argv[]) {
    
            //创建服务端的socket,等待AMS发出的创建应用进程的消息   (ZygoteServer.java)
            zygoteServer = new ZygoteServer(isPrimaryZygote);

            if (startSystemServer) {
				//创建SystemServer进程的入口
                Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

                // child (system_server) process.
                if (r != null) {
                    //执行runnable的run方法
                    r.run();
                    return;
                }
            }
}
        

继续跟入forkSystemServer()方法:


private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {

            /* Hardcoded command line to start the system server */
        //启动systemserver的参数
        String args[] = {
                "--setuid=1000",
                "--setgid=1000",
                "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
                        + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011",
                "--capabilities=" + capabilities + "," + capabilities,
                "--nice-name=system_server", //进程名
                "--runtime-args",
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                "com.android.server.SystemServer",  //这里留个印象,fork出进程后,会调到这个文件中。
        };
        
        ZygoteArguments parsedArgs = null;
        try {
            //解析上面写死的参数
            parsedArgs = new ZygoteArguments(args);

            //fork SystemServer进程
            //需要注意的是,返回值pid不是当前进程的id,而是当前进程的子进程的id,若pid=0说明当前进程是systemserver进程,因为它没有子进程所以返回0
			//而pid>0,说明当前进程是zygote进程,因为它有子进程,且子进程是systemserver
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
          //从这里开始,下面的代码会在两个进程中执行,fork操作可理解为将zygote进程复制了一个称作systemserver进程
          if (pid == 0) {   //pid=0,就是systemserver进程,下文会看到
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            //因为zygote中创建的socket在systemServer进程中用不到,所以关闭socket资源
            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs); //将上面的参数传入
        }



}

继续跟入Zygote.forkSystemServer():

//文件路径:frameworks\base\core\java\com\android\internal\os\Zygote.java

static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
        ZygoteHooks.preFork();
        //这里转到native层去fork进程
        int pid = nativeForkSystemServer(
                uid, gid, gids, runtimeFlags, rlimits,
                permittedCapabilities, effectiveCapabilities);

        // Set the Java Language thread priority to the default value for new apps.
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

        ZygoteHooks.postForkCommon();
        return pid;
    }

上一篇中,zygote进程中做的比较重要事儿之一就是注册jni方法,趁热打铁来看下java层的native方法是怎么找到对应的native层的方法的。

//文件路径:sframeworks/base/core/jni/AndroidRuntime.cpp

void AndroidRuntime::start(const char* className, const Vector& options, bool zygote)
{ 
    /*
     * Register android functions.注册jni的入口在这里
     */
    if (startReg(env) < 0) {  //注册JNI方法,系统api中涉及的native方法都是在这里注册的
        ALOGE("Unable to register all android natives\n");
        return;
    }

}


int AndroidRuntime::startReg(JNIEnv* env)
{
   if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
        env->PopLocalFrame(NULL);
        return -1;
    }

}

//这个数组中保存了,注册android系统中各个部分注册jni的函数指针
static const RegJNIRec gRegJNI[] = {
    ...
    //和本次native方法相关的是这个,其实也比较好找,是对应的Zygote.java文件的包名
    REG_JNI(register_com_android_internal_os_Zygote),
}

继续跟进register_com_android_internal_os_Zygote():

//文件路径: frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

int register_com_android_internal_os_Zygote(JNIEnv* env) {
  gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
  gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
                                                          "callPostForkSystemServerHooks",
                                                          "(I)V");
  gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
                                                   "(IZZLjava/lang/String;)V");

  return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
}

//其中gMethods这个数组是线索,它定义了Zygote.java中所有的native方法与c++中方法的对应关系
static const JNINativeMethod gMethods[] = {
        //这个就是此次寻找的目标
        {"nativeForkSystemServer", "(II[II[[IJJ)I",
         (void*)com_android_internal_os_Zygote_nativeForkSystemServer},
        ...
}




static jint com_android_internal_os_Zygote_nativeForkSystemServer(
        JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
        jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
        jlong effective_capabilities) {

      //进一步进行fork操作,此方法中就会调用系统的fork函数,到此就不再深入分析了
      pid_t pid = ForkCommon(env, true,
                         fds_to_close,
                         fds_to_ignore,
                         true);

       // 从这个注释可得知 pid=0的是system_server进程
      if (pid == 0) {
          // System server prcoess does not need data isolation so no need to
          // know pkg_data_info_list.
     
      } else if (pid > 0) { //pid>0的是zygote进程
          // The zygote process checks whether the child process has died or not.
          ALOGI("System server process %d has been created", pid);
          gSystemServerPid = pid;

      }

}


回到最开始的地方,forkSystemServer()中fork出了system_server进程后,执行了handleSystemServerProcess(parsedArgs)方法。

//文件路径:frameworks\base\core\java\com\android\internal\os\ZygoteInit.java	
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {

     ...
     ClassLoader cl = null;
            if (systemServerClasspath != null) {
				//创建pathclassLoader,类加载器
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);

                Thread.currentThread().setContextClassLoader(cl);
            }

            /*
             * Pass the remaining arguments to SystemServer.
             */
            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mDisabledCompatChanges,
                    parsedArgs.mRemainingArgs, cl);

}

继续跟入ZygoteInit.zygoteInit():

//frameworks\base\core\java\com\android\internal\os\ZygoteInit.java	


public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();
        //初始化运行环境
        RuntimeInit.commonInit();
		//开启binder线程池
        ZygoteInit.nativeZygoteInit();
        
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
                classLoader);
    }

继续跟入RuntimeInit.applicationInit():

//文件路径:	frameworks\base\core\java\com\android\internal\os\RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {


      ...
      return findStaticMain(args.startClass, args.startArgs, classLoader);
}


 protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class cl;

        try {
            //这里关键点就来了,还记得在fork进程前有个String[]里面定义的启动systemserver的多个参数吗?
            //classname就是一层层传递进来的 "com.android.server.SystemServer" 
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }

        Method m;
        try {
            // 通过反射拿到SystemServer类的main()
            m = cl.getMethod("main", new Class[] { String[].class });
        } 

        //将runnable返回
        return new MethodAndArgsCaller(m, argv);
}


还记得上面在pid=0,也就是在systemserver进程中会执行r.run();这个r就是MethodAndArgsCaller,因此打开run():

//文件路径:	frameworks\base\core\java\com\android\internal\os\RuntimeInit.java	


public void run() {
            try {
                //很简单,通过反射执行SystemServer的main()
                mMethod.invoke(null, new Object[] { mArgs });
            } 
}

到此,zygote进程fork出了systemserver进程,android系统启动流程也从zygote阶段过渡到了systemserver阶段,下面我们就可以看看在systemserver进程中主要都做了哪些事儿。

//文件路径 frameworks/base/services/java/com/android/server/systemServer.java
 /**
  * The main entry point from zygote. zygote fork出systemserver进程后,systemserver部分代码的入口
  */
  public static void main(String[] args) {
      new SystemServer().run();
  }

  //主要操作在run方法中
  private void run() {
        //创建looper
        Looper.prepareMainLooper();
        
        // Initialize native services. 加载动态库libandroid_servers.so
        System.loadLibrary("android_servers");

        //step1:创建系统上下文
        createSystemContext();
       
        // Create the system service manager. 用于启动和管理下面的服务
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // 准备一个线程池,用于并行执行systemserver进程初始化中的多个任务
        SystemServerInitThreadPool.start();


        // Start services. systemserver进程中最重要的事,启动一下三种类型中的各个服务
        try {
            t.traceBegin("StartServices");
            startBootstrapServices(t);  //引导服务 AMS PMS
            startCoreServices(t);  //核心服务(主要是系统自己用到的服务)
            startOtherServices(t);  //其他服务 WMS 
        }

        // looper循环,保证此进程不会退出(结束)
        Looper.loop();

  }


---------------------------step1-----------------------------------
private void createSystemContext() {
        //通过ActivityThread创建上下文,ActivityThread相对于进程的关系,就好像CEO相对于公司的关系
        // 它掌握着公司(进程)的资源以及调度执行的权利
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
		//设置默认主题
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

        final Context systemUiContext = activityThread.getSystemUiContext();
        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    }

  

下面我们来具体看下SystemServiceManager是如何管理这些系统服务的?

在此之前,我们先总结一下几个名称相近的概念:

  • systemserver:是一个进程,用来管理众多系统服务
  • SystemServiceManager:systemserver管理服务的具体实现类
  • SystemService:是系统服务的标准,即系统服务想要被SystemServiceManager管理,就必须实现这个标准,各个系统都是SystemService的扩展。
  • serviceManager:是一个进程,binder驱动的管理者,所有系统服务的Binder,都要注册进来

OK,分清这些概念后,我们以ATMS(ActivityManagerTaskService),这个与应用层开发者最密切的系统服务为例,来看SystemServiceManager是如何管理系统服务的。


private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
      //mSystemServiceManager已经在上一步进行创建
      ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
      ...
}

//------------------------- 我们先看前半句startService()--------------------------------
//	frameworks\base\services\core\java\com\android\server\SystemServiceManager.java
public  T startService(Class serviceClass) {
        try {
            //得到对应的类名,此处为ActivityTaskManagerService.Lifecycle
            final String name = serviceClass.getName();
            
            final T service;
            try {
                //通过反射创建ActivityTaskManagerService.Lifecycle对象
                Constructor constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            }
            //继续调用重载方法
            startService(service);
            //将ActivityTaskManagerService.Lifecycle实例返回
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

 private final ArrayList mServices = new ArrayList();
 public void startService(@NonNull final SystemService service) {
        // 将service(这里是ActivityTaskManagerService.Lifecycle对象)存入list集合
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            //调用ActivityTaskManagerService.Lifecycle的onStart()
            service.onStart();
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
 }


//文件路径:	frameworks\base\services\core\java\com\android\server\wm\ActivityTaskManagerService.java

public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            //创建ActivityTaskManagerService实例
            mService = new ActivityTaskManagerService(context);
        }

        @Override
        public void onStart() {
            //将ActivityTaskManagerService注册到serviceManager进程,(serviceManager进程是在init进程中解析init.rc文件后启动的,不熟悉的小伙伴可以去翻下我的另一篇:serviceManager进程的启动流程)     //这个流程在下面单独展开,以免妨碍我们跟踪主线流程
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            //调用ActivityTaskManagerService的start()
            mService.start();
        }
}

private void start() {
        //mInternal 是在ActivityTaskManagerService的构造方法中创建的,它是LocalService类型
        //LocalServices中维护了一个ArrayMap,用于存储LocalService,LocalService封装了一些ATMS能提供的服务的具体实现逻辑,后面可能专门写一篇来分析ATMS。
        LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
    }

//到这里我们知道前半句反回了ActivityTaskManagerService.Lifecycle实例

//-------------------------后半句getService()--------------------------------------------
//后半句非常简单,就是将上面创建的ActivityTaskManagerService实例返回了出去

public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;
        public ActivityTaskManagerService getService() {
            return mService;
        }
}



    

上面还留了一个问题,即服务创建后怎么注册到serviceManager进程?

//调用入口ActivityTaskManagerService.Lifecycle.onStart()
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);

//文件路径:frameworks\base\services\core\java\com\android\server\SystemService.java	
//重载方法调用,最终走到这个方法
// name: "activity_task"
// service: ActivityTaskManagerService对象
// allowIsolated:false
// dumpPriority: DUMP_FLAG_PRIORITY_DEFAULT
protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated, int dumpPriority) {
        ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}


//文件路径:frameworks\base\core\java\android\os\ServiceManager.java	
public static void addService(String name, IBinder service, boolean allowIsolated,
            int dumpPriority) {
        try {
            getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
        } catch (RemoteException e) {
            Log.e(TAG, "error in addService", e);
        }
}


private static IServiceManager getIServiceManager() {
        if (sServiceManager != null) {
            return sServiceManager;
        }

        // Find the service manager
        sServiceManager = ServiceManagerNative
                .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
        return sServiceManager;
    }


getIServiceManager()这个流程在Android IPC Binder机制学习(一)中分析过,这是个跨进程通信,最终会调到以下位置:

//文件位置:frameworks\native\cmds\servicemanage\ServiceManager.cpp	

Status ServiceManager::addService(const std::string& name, const sp& binder, bool allowIsolated, int32_t dumpPriority) {
    
    ...
    // Overwrite the old service if it exists
    // ServiceMap mNameToService; 定义在ServiceManager.h中,这样serviceManager进程就保存了ATMS的binder对象。
    mNameToService[name] = Service {
        .binder = binder,
        .allowIsolated = allowIsolated,
        .dumpPriority = dumpPriority,
        .debugPid = ctx.debugPid,
    };
    ...

}

还有一个点简单提一下,上面提到所有的系统服务都扩展自SystemService类,具体实现分为两类:

  1. 直接继承SystemService,如PowerManagerService
  2. 写一个内部类,让内部类继承SystemService,内部类再持有外部类service,如ATMS,主要原因在于java的单继承,某些service需要继承IBinder。

Android系统启动流程--system_server进程的启动流程_第1张图片

到这里对SystemServer进程的分析就结束了。

总结:systemserver进程主要做了哪些事儿

  1. 创建系统上下文,设置默认主题
  2. 创建SystemServiceManager,用于管理众多系统服务
  3. 启动三大类系统服务,并将服务注册到serviceManager进程

你可能感兴趣的:(android,java,开发语言)