Android 11 SystemServer启动流程

本文详细解析了Android11中Zygote如何通过forkSystemServer进程,执行handleSystemServerProcess生成Runnable,进而启动SystemServer,涉及Odex优化、ClassLoader创建和系统服务的初始化过程。
摘要由CSDN通过智能技术生成

Android 11 Zygote启动流程有提到,Zygote通过forkSystemServer,fork出SystemServer进程,并在SystemServer进程中调用handleSystemServerProcess 返回一个 Runnable

	//......
		/* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            zygoteServer.closeServerSocket();
            //这里返回一个Runnable ,然后在ZygoteInit的main函数中调用此Runnable 的run方法,启动systemserver
            return handleSystemServerProcess(parsedArgs);
        }

然后调用Runnable 的run方法

	//......
		if (startSystemServer) {
                Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

                // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
                // child (system_server) process.
                if (r != null) {
                    r.run();
                    return;
                }
            }
	//......

那就由handleSystemServerProcess开始分析,看看返回的Runnable是什么类型

/*env |grep SYSTEMSERVERCLASSPATH
SYSTEMSERVERCLASSPATH=/system/framework/com.android.location.provider.jar:/system/framework/services.jar:/system/framework/ethernet-service.jar:/apex/com.android.permission/javalib/service-permission.jar:/apex/com.android.ipsec/javalib/android.net.ipsec.ike.jar*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
       //......
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
        
        if (systemServerClasspath != null) {
        	
            performSystemServerDexOpt(systemServerClasspath);//做odex
            
            //......
        }
	if (parsedArgs.mInvokeWith != null) {
	
            //......

            throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
        } else {
            ClassLoader cl = null;
            if (systemServerClasspath != null) {
                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);
        }

先对相关文件夹下的包做odex,然后创建ClassLoader,执行zygoteInit方法

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(); //主要是设置默认的异常捕获方法
        ZygoteInit.nativeZygoteInit();//开启binder线程池
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
                classLoader);
    }

在zygoteInit方法中,主演完成三个工作:

  1. 调用RuntimeInit的commonInit方法
  2. 调用ZygoteInit的nativeZygoteInit方法
  3. 调用RuntimeInit的applicationInit方法

RuntimeInit.commonInit

@UnsupportedAppUsage
    protected static final void commonInit() {
        if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");

        /*
         * set handlers; these apply to all threads in the VM. Apps can replace
         * the default handler, but not the pre handler.
         */
        LoggingHandler loggingHandler = new LoggingHandler();
        RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
        Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));

	//......

通过调用setDefaultUncaughtExceptionHandler,设置线程默认的异常捕获方法

ZygoteInit.nativeZygoteInit
nativeZygoteInit对应的JNI函数为com_android_internal_os_ZygoteInit_nativeZygoteInit

//frameworks\base\core\jni\AndroidRuntime.cpp
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
    const JNINativeMethod methods[] = {
        { "nativeZygoteInit", "()V",
            (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
        methods, NELEM(methods));
}
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}

调用gCurRuntime的onZygoteInit函数,gCurRuntime是AppRuntime对象(AppRuntime继承自AndroidRuntime,在app_main.cpp的main函数中初始化),在onZygoteInit 函数中开启线程池

virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        proc->startThreadPool();
    }

RuntimeInit.applicationInit

protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        //......

        final Arguments args = new Arguments(argv);

        // The end of of the RuntimeInit event (see #zygoteInit).
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

        // Remaining arguments are passed to the start class's static main
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }

通过findStaticMain查找 startClass中的main函数。追溯函数调用,这个startClass是 com.android.server.SystemServer

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

        try {
            cl = Class.forName(className, true, classLoader);
        } 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 });//查找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);
        }

      	//......
        return new MethodAndArgsCaller(m, argv);
    }

封装成MethodAndArgsCaller 对象返回。所以前面提的返回的Runnable是什么类型,这里就知道了,是MethodAndArgsCaller类型

public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }

调用 Runnable的run方法即调用MethodAndArgsCaller的run方法

public void run() {
            try {
                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);
            }
        }

然后就执行到了 com.android.server.SystemServer的 main方法

//frameworks\base\services\java\com\android\server\SystemServer.java
public static void main(String[] args) {
        new SystemServer().run();
   }
private void run() {
	try {
     	t.traceBegin("InitBeforeStartServices");
		//......
		Looper.prepareMainLooper();
		Looper.getMainLooper().setSlowLogThresholdMs(
                    SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

        // Initialize native services.
        System.loadLibrary("android_servers");

		//......
		// Initialize the system context.
        createSystemContext();
		
		//......

	} finally {
            t.traceEnd();  // InitBeforeStartServices
    }

	// Start services.
        try {
            t.traceBegin("StartServices");
            startBootstrapServices(t);
            startCoreServices(t);
            startOtherServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }

	// Loop forever.
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

run方法中主要完成以下工作

  1. 开启消息队列
  2. 加载libandroid_servers库
  3. 创建上下文对象
  4. 开启服务

总结

在SystemServer的启动过程中,主要完成以下工作

  1. 对特定目录下的包做odex
  2. 设置默认的异常捕获器
  3. 开启binder线程池
  4. 启动服务
try {
            t.traceBegin("StartServices");
            startBootstrapServices(t);
            startCoreServices(t);
            startOtherServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
  • 37
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 12 SystemServer启动流程如下: 1. 引导加载:系统启动时,先加载引导程序,进行硬件初始化、内核加载等操作。 2. Zygote 进程启动:Zygote 是 Android 系统中的一个特殊进程,负责孵化其他应用进程。Zygote 进程会预加载一些常用的类和资源,以加快应用的启动速度。 3. SystemServer 进程启动:Zygote 进程会 fork 出 SystemServer 进程,该进程是 Android 系统中的核心服务进程。SystemServer 进程负责启动和管理系统级别的服务,例如 ActivityManagerService、PackageManagerService、WindowManagerService 等。 4. SystemServer 初始化:SystemServer 进程启动后,会进行一系列的初始化操作。首先会创建 Looper 线程,用于接收消息并处理各个服务的初始化工作。然后依次创建各个系统服务,并调用它们的启动方法。 5. 启动系统服务:SystemServer 进程会按照一定顺序启动各个系统服务。每个系统服务都有自己的初始化流程,例如 PackageManagerService 会加载应用程序列表、数据目录等;ActivityManagerService 会初始化进程间通信机制等。 6. 启动应用进程:在系统服务启动完成后,SystemServer 进程会通过 Zygote 孵化出其他应用进程。应用进程会根据 AndroidManifest.xml 中的配置进行初始化,包括创建 Application、加载资源等。 总结来说,Android 12 SystemServer启动流程包括引导加载、Zygote 进程启动SystemServer 进程启动SystemServer 初始化、启动系统服务和启动应用进程等步骤。这些步骤都是为了在系统启动时提供必要的服务和资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值