Android学习(八)Zygote

Stella981
• 阅读 732

Zygote

Zygote同ServiceManager都是由init解析rc脚本时启动的,相关脚本如下:

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server

class main

socket zygote stream 660 root system

onrestart write /sys/android_power/request_state wake

onrestart write /sys/power/state on

onrestart restart media

onrestart restart netd

Zygote的class所属为main,而不是core,和其同属组的系统进程有netd、debuggerd、rild等。

app_process的实现代码:

\Android4.4\frameworks\base\cmds\app_process\app_main.cpp

int main(int argc, char* const argv[])

{

mArgC = argc;

mArgV = argv;

mArgLen = 0;

for (int i=0; i<argc; i++) {

mArgLen += strlen(argv[i]) + 1;

}

mArgLen--;

AppRuntime runtime;

const char* argv0 = argv[0];

// Process command line arguments

// ignore argv[0]

argc--;

argv++;

// Everything up to '--' or first non '-' arg goes to the vm

int i = runtime.addVmArguments(argc, argv);

// Parse runtime arguments.  Stop at first unrecognized option.

bool zygote = false;

bool startSystemServer = false;

bool application = false;

const char* parentDir = NULL;

const char* niceName = NULL;

const char* className = NULL;

while (i < argc) {

const char* arg = argv[i++];

if (!parentDir) {

parentDir = arg;

} else if (strcmp(arg, "--zygote") == 0) {

zygote = true;

niceName = "zygote";

} 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 = arg + 12;

} else {

className = arg;

break;

}

}

if (niceName && *niceName) {

setArgv0(argv0, niceName);

set_process_name(niceName);

}

runtime.mParentDir = parentDir;

if (zygote) {

runtime.start("com.android.internal.os.ZygoteInit",

startSystemServer ? "start-system-server" : "");

} else if (className) {

// Remainder of args get passed to startup class main()

runtime.mClassName = className;

runtime.mArgC = argc - i;

runtime.mArgV = argv + i;

runtime.start("com.android.internal.os.RuntimeInit",

application ? "application" : "tool");

} 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;

}

}

init.rc指定了—zygote选项,因此app_process会启动ZygoteInit并传入"start-system-server"参数。

AppRuntime runtime;的定义:class AppRuntime : public AndroidRuntime

runtime.start("com.android.internal.os.ZygoteInit",

startSystemServer ? "start-system-server" : "");

void AndroidRuntime::start(const char* className, const char* options)

{

/* start the virtual machine */

JniInvocation jni_invocation;

jni_invocation.Init(NULL);

JNIEnv* env;

if (startVm(&mJavaVM, &env) != 0) {

return;

}

onVmCreated(env);

/*

* Register android functions.

*/

if (startReg(env) < 0) {

ALOGE("Unable to register all android natives\n");

return;

}

/*

* We want to call main() with a String array with arguments in it.

* At present we have two arguments, the class name and an option string.

* Create an array to hold them.

*/

jclass stringClass;

jobjectArray strArray;

jstring classNameStr;

jstring optionsStr;

stringClass = env->FindClass("java/lang/String");

assert(stringClass != NULL);

strArray = env->NewObjectArray(2, stringClass, NULL);

assert(strArray != NULL);

classNameStr = env->NewStringUTF(className);

assert(classNameStr != NULL);

env->SetObjectArrayElement(strArray, 0, classNameStr);

optionsStr = env->NewStringUTF(options);

env->SetObjectArrayElement(strArray, 1, optionsStr);

/*

* Start VM.  This thread becomes the main thread of the VM, and will

* not return until the VM exits.

*/

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

}

}

free(slashClassName);

ALOGD("Shutting down VM\n");

if (mJavaVM->DetachCurrentThread() != JNI_OK)

ALOGW("Warning: unable to detach main thread\n");

if (mJavaVM->DestroyJavaVM() != 0)

ALOGW("Warning: VM did not shut down cleanly\n");

}

com.android.internal.os.ZygoteInit运行在java虚拟机状态。

看ZygoteInit.java:

public static void main(String argv[]) {

try {

// Start profiling the zygote initialization.

SamplingProfilerIntegration.start();

registerZygoteSocket();

EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,

SystemClock.uptimeMillis());

preload();

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();

// Disable tracing so that forked processes do not inherit stale tracing tags from

// Zygote.

Trace.setTracingEnabled(false);

// If requested, start system server directly from Zygote

if (argv.length != 2) {

throw new RuntimeException(argv[0] + USAGE_STRING);

}

if (argv[1].equals("start-system-server")) {

startSystemServer();

} else if (!argv[1].equals("")) {

throw new RuntimeException(argv[0] + USAGE_STRING);

}

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

runSelectLoop();

closeServerSocket();

} catch (MethodAndArgsCaller caller) {

caller.run();

} catch (RuntimeException ex) {

Log.e(TAG, "Zygote died with exception", ex);

closeServerSocket();

throw ex;

}

}

刚才传入了参数"start-system-server"所以会调用startSystemServer();来启动SystemServer。

private static boolean startSystemServer()

throws MethodAndArgsCaller, RuntimeException {

long capabilities = posixCapabilitiesAsBits(

OsConstants.CAP_KILL,

OsConstants.CAP_NET_ADMIN,

OsConstants.CAP_NET_BIND_SERVICE,

OsConstants.CAP_NET_BROADCAST,

OsConstants.CAP_NET_RAW,

OsConstants.CAP_SYS_MODULE,

OsConstants.CAP_SYS_NICE,

OsConstants.CAP_SYS_RESOURCE,

OsConstants.CAP_SYS_TIME,

OsConstants.CAP_SYS_TTY_CONFIG

);

/* 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,1032,3001,3002,3003,3006,3007",

"--capabilities=" + capabilities + "," + capabilities,

"--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);

/* 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);

}

/* For child process */

if (pid == 0) {

handleSystemServerProcess(parsedArgs);

}

return true;

}

"com.android.server.SystemServer"作为子进程被创建:

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", null);

}

}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);

}

// Mmmmmm... more memory!

dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();

// 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);

Environment.setUserRequired(true);

System.loadLibrary("android_servers");

Slog.i(TAG, "Entered the Android system server!");

// Initialize native services.

nativeInit();

// This used to be its own separate thread, but now it is

// just the loop we run on the main thread.

ServerThread thr = new ServerThread();

thr.initAndLoop();

}

这个地方4.4的代码与2.3的代码有些区别,4.4代码中不再system_init.cpp文件,其他服务的初始化都是在ServerThread thr = new ServerThread();中进行的。

SystemServer中加载android_servers.so库文件,nativeInit是一个jni调用:

\Android4.4\frameworks\base\services\jni\ com_android_server_SystemServer.cpp

#include <jni.h>

#include <JNIHelp.h>

#include <sensorservice/SensorService.h>

#include <cutils/properties.h>

#include <utils/Log.h>

#include <utils/misc.h>

namespace android {

static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {

char propBuf[PROPERTY_VALUE_MAX];

property_get("system_init.startsensorservice", propBuf, "1");

if (strcmp(propBuf, "1") == 0) {

// Start the sensor service

SensorService::instantiate();

}

}

/*

* JNI registration.

*/

static JNINativeMethod gMethods[] = {

/* name, signature, funcPtr */

{ "nativeInit", "()V", (void*) android_server_SystemServer_nativeInit },

};

int register_android_server_SystemServer(JNIEnv* env)

{

return jniRegisterNativeMethods(env, "com/android/server/SystemServer",

gMethods, NELEM(gMethods));

}

}; // namespace android

可见4.4中的nativeInit中只做了SensorService的初始化。

这里只看到了Zygote的启动流程,对一系列系统服务做了初始操作,4.4的代码和2.3的代码在结构上有些差别,进一步的学习,后面继续。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Java修道之路,问鼎巅峰,我辈代码修仙法力齐天
<center<fontcolor00FF7Fsize5face"黑体"代码尽头谁为峰,一见秃头道成空。</font<center<fontcolor00FF00size5face"黑体"编程修真路破折,一步一劫渡飞升。</font众所周知,编程修真有八大境界:1.Javase练气筑基2.数据库结丹3.web前端元婴4.Jav
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这