Android Framework学习启动流程(三)-SyetemServer

588 阅读2分钟

Android 系统9.0.0 启动-SyetemServer

1. forkSystemServer->handleSystemServerProcess

 /**
  * Finish remaining work for the newly forked system server process.
  */
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
   
     /*
      * Pass the remaining arguments to SystemServer.
      */
      return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}

2. 通过jni 启动binder线程池

 public static final Runnable zygoteInit(int targetSdkVersion, 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();
        //调用native方法初始化 1
        ZygoteInit.nativeZygoteInit();
        //初始化应用信息 2
        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}

3. nativeZygoteInit函数对用的JNI ( 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是AndroidRuntime类型的指针
    //AndroidRuntime的子类AppRuntime在app_main.cpp中定义
    gCurRuntime->onZygoteInit();
}

4. 启动一个Binder线程池,SyetemServer进程就可以使用Binder来与其他进程进行通信

AppRuntime的onZygoteInit函数 (frameworks/base/cmds/app_process/app_main.cpp)

virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        //启动一个Binder线程池
        proc->startThreadPool();
    }

5. 通过反射SystemServer类调用它的main函数

protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) {
    ...
    // Remaining arguments are passed to the start class's static main
    return findStaticMain(args.startClass, args.startArgs, classLoader);
}
 protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class<?> cl;

        //反射获取SystemServer 类
        try {
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }
        Method m;
        //通过反射调用SystemServier的main函数
        try {
            m = cl.getMethod("main", new Class[] { String[].class });
        } 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);
        }
        ...
        /*
         * 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.
         */
         //返回runnable对象 里面执行SystemServier的初始化main函数
        return new MethodAndArgsCaller(m, argv);
    }

6. 通过一个Runnable线程反射调用SystemServer的main函数

 static class MethodAndArgsCaller implements Runnable {
        /** method to call */
        private final Method mMethod;

        /** argument array */
        private final String[] mArgs;

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

        public void run() {
            try {
                //调用SystemServier的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);
            }
        }
    }

回到ZygoteInit.java 中 main函数 在这里进行主动调用触发SystemServer启动

/**
 * ZygoteInit.java 
 */
public static void main(String argv[]) {
    ...
    final Runnable caller;
    try {
        if (startSystemServer) {
            Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
                // child (system_server) process.
                if (r != null) {
                    //在此处调用Runnable对象的run方法 最终调用反射被动动态调用了main函数
                    r.run();
                    return;
                }
         }
         ...
         caller = zygoteServer.runSelectLoop(abiList);
     }catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
     } finally {
            zygoteServer.closeServerSocket();
     }
     ...
     if (caller != null) {
         caller.run();
     }
}

流程总结

SystemServer