Zygote 服务概论:
Zygote 是android 系统中最重要的一个服务,它将一步一步完成下面的任务:
start Android Java Runtime and start system server. It’s the most important service. The source is in device/servers/app.
1. 创建JAVA 虚拟机
2. 为JAVA 虚拟机注册android 本地函数
3. 调用 com.android.internal.os.ZygoteInit 类中的main函数,android/com/android/internal/os/ZygoteInit.java.
a) 装载ZygoteInit类
b) 注册zygote socket
c) 装载preload classes(the default file is device/java/android/preloaded-classes)
d) 装载Load preload 资源
e) 调用 Zygote::forkSystemServer (定义在./dalvik/vm/InternalNative.c)来fork一个新的进程,在新进程中调用 com.android.server.SystemServer 的main函数。
a) 装载 libandroid_servers.so库
bb) 调用JNI native init1 函数 (device/libs/android_servers/com_android_server_SystemServers)
Load libandroid_servers.so
Call JNI native init1 function implemented in device/libs/android_servers/com_android_server_SystemServers. It only calls system_init implemented in device/servers/system/library/system_init.cpp.
If running on simulator, instantiate AudioFlinger, MediaPlayerService and CameraService here.
Call init2 function in JAVA class named com.android.server.SystemServer, whose source is in device/java/services/com/android/server. This function is very critical for Android because it start all of Android JAVA services.
If not running on simulator, call IPCThreadState::self()->joinThreadPool() to enter into service dispatcher.
SystemServer::init2 将会启动一个新的线程来启动下面的所有JAVA服务:
Core 服务:
1. Starting Power Manager(电源管理)
2. Creating Activity Manager(活动服务)
3. Starting Telephony Registry(电话注册服务)
4. Starting Package Manager(包管理器)
5. Set Activity Manager Service as System Process
6. Starting Context Manager
7. Starting System Context Providers
8. Starting Battery Service(电池服务)
9. Starting Alarm Manager(闹钟服务)
10. Starting Sensor Service
11. Starting Window Manager(启动窗口管理器)
12. Starting Bluetooth Service(蓝牙服务)
13. Starting Mount Service
其他services:
1. Starting Status Bar Service(状态服务)
2. Starting Hardware Service(硬件服务)
3. Starting NetStat Service(网络状态服务)
4. Starting Connectivity Service
5. Starting Notification Manager
6. Starting DeviceStorageMonitor Service
7. Starting Location Manager
8. Starting Search Service(查询服务)
9. Starting Clipboard Service
10. Starting Checkin Service
11. Starting Wallpaper Service
12. Starting Audio Service
13. Starting HeadsetObserver
14. Starting AdbSettingsObserver
最后SystemServer::init2 将会调用 ActivityManagerService.systemReady 通过发送
Intent.CATEGORY_HOME intent来启动第一个 activity.还有另外一种启动system server的方法是:
通过名为 system_server的程序(源代码:device/servers/system/system_main.cpp)它也是通过
调用 system_init 来启动 system services,这时候就有个问题:为什么android 有两种方式启动system services?
我的猜想是:
My guess is that directly start system_server may have synchronous problem with zygote because system_server will call JNI to start SystemServer::init2, while at that time zygote may not start JAVA VM yet. So Android uses another method. After zynote is initialized, fork a new process to start system services.
Zygote服务启动的详细过程:
通过启动服务列表的 app_process 进程,实际上进入的是
App_main.cpp (frameworks/base/cmds/app_process)
main()
根据 init.rc 中的 --zygote --start-system-server
分别调用的是
runtime.start("com.android.internal.os.ZygoteInit",startSystemServer);
或者
runtime.start();
start()函数在 AndroidRuntime.cpp (frameworks/base/core/jni)文件中
从打印信息:
D/AndroidRuntime( 56): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
也可以看出调用的是:
AndroidRuntime::start(const char* className, const bool startSystemServer)
JNI_CreateJavaVM()
startReg()
LOGD("--- registering native functions ---/n");
startMeth = env->GetStaticMethodID(startClass, "main","([Ljava/lang/String;)V");
从上面的调用可以看出一类引用的过程都是从 main方法
所以接着调用了 ZygoteInit 类的main方法
main方法主要完成:
1.Register zygote socket, Registers a server socket for zygote command connections
2.Load preload classes(the default file is device/java/android/preloaded-classes).
3.Load preload resources, Load in commonly used resources, so they can be shared across processes.
4.Start SystemServer, Prepare the arguments and fork for the system server process.
具体执行过程如下:
ZygoteInit.java (frameworks/base/core/java/com/android/internal/os)中的mian
main()
registerZygoteSocket()
preloadClasses()
loadLibrary()
Log.i(TAG, "Preloading classes...");
Runtime.loadLibrary
Dalvik_java_lang_Runtime_nativeLoad()
dvmLoadNativeCode()
LOGD("Trying to load lib %s %p/n", pathName, classLoader);
System.loadLibrary("media_jni");
preloadResources();
startSystemServer()
Zygote.forkSystemServer(parsedArgs.uid, parsedArgs.gid,parsedArgs.gids, debugFlags, null);
//Zygote.java (dalvik/libcore/dalvik/src/main/java/dalvik/system)
forkSystemServer()
forkAndSpecialize() //Zygote.java (dalvik/libcore/dalvik/src/main/java/dalvik/system)
Dalvik_dalvik_system_Zygote_forkAndSpecialize() //dalvik_system_Zygote.c (dalvik/vm/native)
Dalvik_dalvik_system_Zygote_forkAndSpecialize()
setSignalHandler()
fork()
handleSystemServerProcess() //handleChildProc(parsedArgs, descriptors, newStderr);
closeServerSocket();
RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
zygoteInit() //RuntimeInit.java (frameworks/base/core/java/com/android/internal/os)
zygoteInitNative()
invokeStaticMain()
System.loadLibrary("android_servers");
//com.android.server.SystemServer startSystemServer() 函数中
m = cl.getMethod("main", new Class[] { String[].class });
//执行的是SystemServer 类的main函数 SystemServer.java (frameworks/base/services/java/com/android/server)
init1() //SystemServer.java (frameworks/base/services/java/com/android/server)
//init1()实际上是调用android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
//com_android_server_SystemServer.cpp (frameworks/base/services/jni)
android_server_SystemServer_init1()//JNI 调用
system_init() //System_init.cpp (frameworks/base/cmds/system_server/library)
// Start the SurfaceFlinger
SurfaceFlinger::instantiate();
//Start the AudioFlinger media playback camera service
AudioFlinger::instantiate();
MediaPlayerService::instantiate();
CameraService::instantiate();
//调用 SystemServer 类的init2
runtime->callStatic("com/android/server/SystemServer", "init2");
init2()//SystemServer.java (frameworks/base/services/java/com/android/server)
ServerThread()
run()//在run中启动电源管理,蓝牙,等核心服务以及状态,查找等其他服务
((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);
...
ActivityManagerNative.getDefault().systemReady();
runSelectLoopMode();
done = peers.get(index).runOnce();
forkAndSpecialize() //Zygote.java (dalvik/libcore/dalvik/src/main/java/dalvik/system)
Dalvik_dalvik_system_Zygote_forkAndSpecialize() //dalvik_system_Zygote.c (dalvik/vm/native)
forkAndSpecializeCommon()
setSignalHandler()
RETURN_INT(pid);
closeServerSocket();
见附A
主進程runSelectLoopMode()
5.Runs the zygote process's select loop runSelectLoopMode(), Accepts new connections as they happen, and reads commands from connections one spawn-request's worth at a time.
如果运行正常,则zygote进程会在runSelectLoopMode()中循环:
zygote 被siganl(11)终止
在 dalvik_system_Zygote.c (dalvik/vm/native)
的 static void sigchldHandler(int s) 函数中打印:
"Process %d terminated by signal (%d)/n",
"Exit zygote because system server (%d) has terminated/n",
startSystemServer() ZygoteInit.java (frameworks/base/core/java/com/android/internal/os)
SystemServer 的mian()函数会调用
SystemServer.java (frameworks/base/services/java/com/android/server)中的 init1()函数。
init1()实际执行的是com_android_server_SystemServer.cpp (frameworks/base/services/jni)
中的 android_server_SystemServer_init1()。
android_server_SystemServer_init1()调用的是
System_init.cpp (frameworks/base/cmds/system_server/library) 中的 system_init()函数
system_init()函数定义如下:
extern "C" status_t system_init()
{
...
sp<IServiceManager> sm = defaultServiceManager();
...
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
//读取属性服务器,开启启动 SurfaceFlinger服务
//接着会开始显示机器人图标
//BootAnimation.cpp (frameworks/base/libs/surfaceflinger):status_t BootAnimation::readyToRun()
SurfaceFlinger::instantiate();
}
//在模拟器上 audioflinger 等几个服务与设备上的启动过程不一样,所以
//我们在这里启动他们。
if (!proc->supportsProcesses()) {
//启动 AudioFlinger,media playback service,camera service服务
AudioFlinger::instantiate();
MediaPlayerService::instantiate();
CameraService::instantiate();
}
//现在开始运行 the Android runtime ,我们这样做的目的是因为必须在 core system services
//起来以后才能 Android runtime initialization,其他服务在调用他们自己的main()时,都会
//调用 Android runtime
//before calling the init function.
LOGI("System server: starting Android runtime./n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services./n");
//调用 SystemServer.java (frameworks/base/services/java/com/android/server)
//中的init2函数
runtime->callStatic("com/android/server/SystemServer", "init2");
// If running in our own process, just go into the thread
// pool. Otherwise, call the initialization finished
// func to let this process continue its initilization.
if (proc->supportsProcesses()) {
LOGI("System server: entering thread pool./n");
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
LOGI("System server: exiting thread pool./n");
}
return NO_ERROR;
}
System server: entering thread pool 表明已经进入服务线程 ServerThread
在 ServerThread 类的run 服务中开启核心服务:
@Override
public void run() {
EventLog.writeEvent(LOG_BOOT_PROGRESS_SYSTEM_RUN,
SystemClock.uptimeMillis());
ActivityManagerService.prepareTraceFile(false); // create dir
Looper.prepare();
//设置线程的优先级
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
...
//关键(核心)服务
try {
Log.i(TAG, "Starting Power Manager.");
Log.i(TAG, "Starting activity Manager.");
Log.i(TAG, "Starting telephony registry");
Log.i(TAG, "Starting Package Manager.");
Log.i(TAG, "tarting Content Manager.");
Log.i(TAG, "Starting System Content Providers.");
Log.i(TAG, "Starting Battery Service.");
Log.i(TAG, "Starting Alarm Manager.");
Log.i(TAG, "Starting Sensor Service.");
Log.i(TAG, "Starting Window Manager.");
Log.i(TAG, "Starting Bluetooth Service.");
//如果是模拟器,那么跳过蓝牙服务。
// Skip Bluetooth if we have an emulator kernel
//其他的服务
Log.i(TAG, "Starting Status Bar Service.");
Log.i(TAG, "Starting Clipboard Service.");
Log.i(TAG, "Starting Input Method Service.");
Log.i(TAG, "Starting Hardware Service.");
Log.i(TAG, "Starting NetStat Service.");
Log.i(TAG, "Starting Connectivity Service.");
Log.i(TAG, "Starting Notification Manager.");
// MountService must start after NotificationManagerService
Log.i(TAG, "Starting Mount Service.");
Log.i(TAG, "Starting DeviceStorageMonitor service");
Log.i(TAG, "Starting Location Manager.");
Log.i(TAG, "Starting Search Service.");
...
if (INCLUDE_DEMO) {
Log.i(TAG, "Installing demo data...");
(new DemoThread(context)).start();
}
try {
Log.i(TAG, "Starting Checkin Service.");
Intent intent = new Intent().setComponent(new ComponentName(
"com.google.android.server.checkin",
"com.google.android.server.checkin.CheckinService"));
if (context.startService(intent) == null) {
Log.w(TAG, "Using fallback Checkin Service.");
ServiceManager.addService("checkin", new FallbackCheckinService(context));
}
} catch (Throwable e) {
Log.e(TAG, "Failure starting Checkin Service", e);
}
Log.i(TAG, "Starting Wallpaper Service");
Log.i(TAG, "Starting Audio Service");
Log.i(TAG, "Starting HeadsetObserver");
Log.i(TAG, "Starting AppWidget Service");
...
try {
com.android.server.status.StatusBarPolicy.installIcons(context, statusBar);
} catch (Throwable e) {
Log.e(TAG, "Failure installing status bar icons", e);
}
}
// make sure the ADB_ENABLED setting value matches the secure property value
Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
"1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);
// register observer to listen for settings changes
mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
false, new AdbSettingsObserver());
// It is now time to start up the app processes...
boolean safeMode = wm.detectSafeMode();
if (statusBar != null) {
statusBar.systemReady();
}
if (imm != null) {
imm.systemReady();
}
wm.systemReady();
power.systemReady();
try {
pm.systemReady();
} catch (RemoteException e) {
}
if (appWidget != null) {
appWidget.systemReady(safeMode);
}
// After making the following code, third party code may be running...
try {
ActivityManagerNative.getDefault().systemReady();
} catch (RemoteException e) {
}
Watchdog.getInstance().start();
Looper.loop();
Log.d(TAG, "System ServerThread is exiting!");
}
startActivity()
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
ActivityManagerService.java 3136p (frameworks/base/services/java/com/android/server/am)
startActivity()
startActivityLocked() //3184
int res = startActivityLocked(caller, intent, resolvedType,grantedUriPermissions, grantedMode, aInfo,
resultTo, resultWho, requestCode, -1, -1,
onlyIfNeeded, componentSpecified);
public abstract class ActivityManagerNative extends Binder implements IActivityManager
ActivityManagerService.java 1071p (frameworks/base/services/java/com/android/server/am)
ActivityManagerService.main()
//ActivityManagerService.java 7375p (frameworks/base/services/java/com/android/server/am)
m.startRunning(null, null, null, null);
//ActivityManagerService.java 7421p (frameworks/base/services/java/com/android/server/am)
systemReady();
ActivityManagerService.java 3136p (frameworks/base/services/java/com/android/server/am)
startActivity(IApplicationThread caller,Intent intent,...)
int startActivityLocked(caller, intent,...) //3184L 定义:2691L
void startActivityLocked() //3132L 定义:2445L
resumeTopActivityLocked(null); //2562p 定义:2176L
if(next=NULL)
{
intent.addCategory(Intent.CATEGORY_HOME);
startActivityLocked(null, intent, null, null, 0, aInfo,null, null, 0, 0, 0, false, false);
}
else
{
startSpecificActivityLocked(next, true, false); //2439L 定义:1628L
realStartActivityLocked() //1640L 定义:1524L
//1651L 定义:1654L
startProcessLocked(r.processName, r.info.applicationInfo, true, 0,"activity", r.intent.getComponent());
//1717L 定义:1721L
startProcessLocked(app, hostingType, hostingNameStr);
//1768L 定义:Process.java 222L(frameworks/base/core/java/android/os)
int pid = Process.start("android.app.ActivityThread",...)
startViaZygote(processClass, niceName, uid, gid, gids,debugFlags, zygoteArgs);
pid = zygoteSendArgsAndGetPid(argsForZygote);
sZygoteWriter.write(Integer.toString(args.size()));
}
runSelectLoopMode();
done = peers.get(index).runOnce();
forkAndSpecialize() //Zygote.java (dalvik/libcore/dalvik/src/main/java/dalvik/system)
Dalvik_dalvik_system_Zygote_forkAndSpecialize() //dalvik_system_Zygote.c (dalvik/vm/native)
forkAndSpecializeCommon()
setSignalHandler()
RETURN_INT(pid);
ActivityThread main()
ActivityThread attach() //ActivityThread.java 3870p (frameworks/base/core/java/android/app)
mgr.attachApplication(mAppThread)
//ActivityManagerService.java 4677p (frameworks/base/services/java/com/android/server/am)
attachApplication()
//ActivityManagerService.java 4677p (frameworks/base/services/java/com/android/server/am)
attachApplicationLocked()
if (realStartActivityLocked(hr, app, true, true)) //ActivityManagerService.java 4609p (frameworks/base/services/java/com/android/server/am)
realStartActivityLocked()
//ActivityManagerService.java (frameworks/base/services/java/com/android/server/am)
app.thread.scheduleLaunchActivity(new Intent(r.intent), r,r.info, r.icicle, results, newIntents, !andResume,isNextTransitionForward());
scheduleLaunchActivity()
queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
ActivityThread.H.handleMessage()
handleLaunchActivity() //ActivityThread.java (frameworks/base/core/java/android/app)
performLaunchActivity() //ActivityThread.java (frameworks/base/core/java/android/app)
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
/
init 守护进程:
//andriod init 函数启动过程分析:
在main循环中会重复调用
drain_action_queue();
restart_processes();
static void restart_processes()
{
process_needs_restart = 0;
service_for_each_flags(SVC_RESTARTING,
restart_service_if_needed);
}
通过循环检测服务列表service_list 中每个服务的 svc->flags 标记,如果为 SVC_RESTARTING,
那么在满足条件的情况下调用:restart_service_if_needed
通过 service_start 来再次启动该服务。
ActivityManagerService.main
I/SystemServer( 45): Starting Power Manager.
I/ServiceManager( 26): service 'SurfaceFlinger' died
D/Zygote ( 30): Process 45 terminated by signal (11)
I/Zygote ( 30): Exit zygote because system server (45) has terminated
通过错误信息发现程序在调用 SurfaceFlinger服务的时候被中止。
Service_manager.c (frameworks/base/cmds/servicemanager):
LOGI("service '%s' died/n", str8(si->name));
Binder.c (frameworks/base/cmds/servicemanager):
death->func(bs, death->ptr);
Binder.c (kernel/drivers/misc)中的函数
binder_thread_read()
struct binder_work *w;
switch (w->type)
为 BINDER_WORK_DEAD_BINDER 的时候
binder_parse()中
当 cmd 为 BR_DEAD_BINDER的时候
执行 death->func(bs, death->ptr)
因为函数
int do_add_service(struct binder_state *bs,
uint16_t *s, unsigned len,
void *ptr, unsigned uid)
的 si->death.func = svcinfo_death;
所以 death->func(bs, death->ptr) 实际上执行的是
svcinfo_death()//Service_manager.c (frameworks/base/cmds/servicemanager)
所以会打印出:service 'SurfaceFlinger' died
I/ServiceManager( 26): service 'SurfaceFlinger' died
Thread::run
_threadLoop() // Threads.cpp (frameworks/base/libs/utils)
status_t SurfaceFlinger::readyToRun()
mBootAnimation = new BootAnimation(this);
资料:
Android init 启动过程分析(2)
最新推荐文章于 2024-05-04 23:10:10 发布