其他分享
首页 > 其他分享> > zygote启动systemserver流程

zygote启动systemserver流程

作者:互联网

涉及代码路径:
\frameworks\base\cmds\app_process\app_main.cpp
\frameworks\base\core\jni\AndroidRuntime.cpp
\frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
\frameworks\base\core\java\com\android\internal\os\ZygoteConnection.java
\frameworks\base\core\java\com\android\internal\os\Zygote.java
\frameworks\base\core\java\com\android\internal\os\RuntimeInit.java

1、zygote启动:
app_main.cpp中main函数如下:
初始化appruntime

  AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));

其中:

class AppRuntime : public AndroidRuntime

解析参数中是否包含–zygote和–start-system-server

while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            startSystemServer = true;
        } else if (strcmp(arg, "--application") == 0) {
            application = true;
        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
            niceName.setTo(arg + 12);
        } else if (strncmp(arg, "--", 2) != 0) {
            className.setTo(arg);
            break;
        } else {
            --i;
            break;
        }
    }

runtime只是类名,args添加application字段

args.add(application ? String8("application") : String8("tool"));
 runtime.setClassNameAndArgs(className, argc - i, argv + i);

添加参数start-system-server

if (startSystemServer) {
            args.add(String8("start-system-server"));
        }

调用对应的类名中的main函数,在androidruntime类的start方法中,首先分析ZygoteInit

if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {
        runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
    } else {
        fprintf(stderr, "Error: no class name or --zygote supplied.\n");
        app_usage();
        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
        return 10;
    }

2、AndroidRuntime
AndroidRuntime中start方法如下:
启动虚拟机:

JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }
    onVmCreated(env);

注册android方法:

if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }

从传入的参数中获取类名,并且调用该类中的main方法:

   char* slashClassName = toSlashClassName(className);
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
        /* keep going */
    } else {
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in '%s'\n", className);
            /* keep going */
        } else {
            env->CallStaticVoidMethod(startClass, startMeth, strArray);
#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }

传入的是com.android.internal.os.ZygoteInit,接下来进入到ZygoteInit

3、ZygoteInit
ZygoteInit中main方法如下:

registerZygoteSocket(socketName);  //注册socket
preload();  //预加载

预加载按顺序为:1、安装ICU cache reference pinning,2、加载类,3、加载资源,4、加载OpenGL资源,5、加载共享库,6、加载text资源,7、准备webview环境,8、使能ICU cache reference pinning,9、安装AndroidKeyStoreProvider

static void preload() {
        Log.d(TAG, "begin preload");
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "BeginIcuCachePinning");
        beginIcuCachePinning();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadClasses");
        preloadClasses();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadResources");
        preloadResources();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL");
        preloadOpenGL();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        preloadSharedLibraries();
        preloadTextResources();
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        WebViewFactory.prepareWebViewInZygote();
        endIcuCachePinning();
        warmUpJcaProviders();
        Log.d(TAG, "end preload");
    }

启动systemserver进入android世界

if (startSystemServer) {
          startSystemServer(abiList, socketName);
  }
private static boolean startSystemServer(String abiList, String socketName)
            throws MethodAndArgsCaller, RuntimeException {
String args[] = {
            "--setuid=1000",
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,              1021,1032,3001,3002,3003,3006,3007,3009,3010",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",
            "--runtime-args",
            "com.android.server.SystemServer",
        };

解析参数,创建子systemserver子进程。

try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

子进程创建成功后处理子进程

private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
        // set umask to 0077 so new files and directories will default to owner-only permissions.
        Os.umask(S_IRWXG | S_IRWXO);

       //...... 对几个系统路径的jar文件做odex操作
        if (parsedArgs.invokeWith != null) {
           // 由上可知parsedArgs.invokeWith为空,此处不会进入
        } else {
            ClassLoader cl = null;
            if (systemServerClasspath != null) {
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);

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

            /*
             * Pass the remaining arguments to SystemServer.
             */
            return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
        }

        /* should never reach here */
    }
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
       
        RuntimeInit.redirectLogStreams(); //重定向logstream
        RuntimeInit.commonInit(); //常规内容初始化,比如bindeath进程crash监听等
        ZygoteInit.nativeZygoteInit();
        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }
 protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) {
        nativeSetExitWithoutCleanup(true);
        VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
        final Arguments args = new Arguments(argv);
        //此处的startClass就是:com.android.server.SystemServer
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }

protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class<?> cl;
        try {
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
        }
        Method m;
        try {
            m = cl.getMethod("main", new Class[] { String[].class });
        } catch (NoSuchMethodException ex) {
        } catch (SecurityException ex) {
        }

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

之后进入到:E:\frameworks\base\services\java\com\android\server\SystemServer.java
的main方法中:

public static void main(String[] args) {
        new SystemServer().run();
    }

至此,从zygote到systemserver启动过程分析完成。

标签:Trace,流程,args,zygote,parsedArgs,main,android,systemserver
来源: https://blog.csdn.net/thh159/article/details/88426902