0. 以下分析的是systemservice如何启动
1. init.rc 中有
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
socket zygote stream 666
onrestart write /proc/sysrq-trigger c
2. service zygote在frameworks/base/cmds/app_process/app_main.cpp--> main启动 --> runtime.start("com.android.internal.os.ZygoteInit",startSystemServer); 启动ZygoteInit进程,以后所有的java进程均须通过此进程fork而成。
3. frameworks/base/core/jni/AndroidRuntime.cpp中函数start(...)非常重要,virtual machine在这启动和android function在这注册;最后env->CallStaticVoidMethod(startClass, startMeth, strArray); //调用com.android.internal.os.ZygoteInit的main()方法
4. frameworks/base/core/java/com/android/internal/os/ZygoteInit.java; 启动main函数中有,其中gc()也在这启动
if (argv[1].equals("true")) { //只支持true参数
startSystemServer(); //此处启动systemserver
}
if (ZYGOTE_FORK_MODE) { //进入死循环,zygote进程由此建立,并一直运行;利用Socket通讯,接收ActivityManangerService的请求,Fork应用程序
runForkMode();
} else {
runSelectLoopMode();
}
在startSystemServer();中有
pid = Zygote.forkSystemServer( //fork出进程
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
if (pid == 0) {
handleSystemServerProcess(parsedArgs);//parsedArgs的参数中包含有"com.android.server.SystemServer"
5. 进程fork出来后,关闭socket并初始化进程handleSystemServerProcess
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
closeServerSocket();
/*
* Pass the remaining arguments to SystemServer.
* "--nice-name=system_server com.android.server.SystemServer"
*/
RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
/* should never reach here */
}
最后调用 所有java进程的共同入口zygoteInit()。
6. frameworks/base/core/java/com/android/internal/os/RuntimeInit.java中函数zygoteInit(String[] argv)
public static final void zygoteInit(String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
...
commonInit(); //初始化时区,设置agent
zygoteInitNative(); //调用到com_android_internal_os_RuntimeInit_zygoteInit@AndroidRuntime.cpp -> gCurRuntime->onZygoteInit(),此处启动ThreadPool
...
invokeStaticMain(startClass, startArgs); //调用com.android.server.SystemServer的main方法
}
7. frameworks/base/core/jni/androidruntime.cpp中
static JNINativeMethod gMethods[] = {"zygoteInitNative", "()V",(void*) com_android_internal_os_RuntimeInit_zygoteInit}
static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
8. frameworks/base/cmds/app_process; 是class AppRuntime : public AndroidRuntime;所以onZygoteInit被重载
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
if (proc->supportsProcesses()) {
LOGV("App process: starting thread pool.\n");
proc->startThreadPool(); //启动线程池处理Binder事件,需要进一步分析,有啥用处?
}
}
9. 继续分析前面invokeStaticMain的运行路径,frameworks/base/services/java/com/android/server/SystemServer.java;
public static void main(String[] args) {
// 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);
System.loadLibrary("android_servers"); //Load JNI library here that is used by SystemServer,位于手机中/system/lib
init1(args); //这里调用到com_android_server_SystemServer.cpp/android_server_SystemServer_init1
}
10. frameworks/base/services/jni/com_android_server_SystemServer.cpp中有
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },
};
调用路径android_server_SystemServer_init1-->frameworks/base/cmds/system_server/library/system_init.cpp中函数system_init
extern "C" status_t system_init()
{
...
// Start the sensor service
SensorService::instantiate();//sensor service在这启动,意外收获
if (!proc->supportsProcesses()) { //在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建
// Start the AudioFlinger
AudioFlinger::instantiate();
// Start the media playback service
MediaPlayerService::instantiate();
// Start the camera service
CameraService::instantiate();
// Start the audio policy service
AudioPolicyService::instantiate();
}
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services.\n");
runtime->callStatic("com/android/server/SystemServer", "init2");//调用init2@SystemServer.java,在这里创建工作线程以启动各java服务并进入循环处理各service请求
}
11. 从上分析来看,frameworks/base/services/java/com/android/server/SystemServer.java, main函数中-->init1-->init2 如此关联起来的-->ServerThread-->run实现Java Service注册初始化及进入SystemServer事件处理循环;在run中通过addservice注册很多sevice,另外还有启动 ActivityManagerService.main(factoryTest);和((ActivityManagerService)ActivityManagerNative.getDefault()).systemReady(new Runnable()...)
12. frameworks/base/services/java/com/android/server/am/ActivityManagerService.java; 中main函数
public static final Context main(int factoryTest) {
AThread thr = new AThread();//作为ActivityManager的工作线程,在其中处理ActivityManager相关的消息
thr.start();
...
ActivityThread at = ActivityThread.systemMain();//加载system应用,并把此线程作为SystemServer进程的system线程
...
m.startRunning(null, null, null, null); //初始化变量并设置system ready为true
}
13. systemReady@ActivityManagerService.java--> mMainStack.resumeTopActivityLocked(null);-->mService.startHomeActivityLocked();-->mMainStack.startActivityLocked ,由此启动了Home apk;
14. frameworks/base/core/java/android/app/activitythread.java; 中systemMain()、startRunning和systemReady函数
15. 以下分析的是servicemanager如何管理service???
16. init.rc 中有
service servicemanager /system/bin/servicemanager //
user system
critical
onrestart restart zygote
onrestart restart media
17. 该源代码位于 frameworks/base/cmds/servicemanager/
18. service_manager.c 中main函数
a. 函数binder_open,打开"/dev/binder"设备,并在内存中映射128K的空间。
b. 函数binder_become_context_manager,通知Binder设备,执行ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0)把自己变成context_manager ;
c. 函数binder_loop,进入循环,不停的去读Binder设备,看是否有对service的请求,如果有BR_TRANSACTION请求的话,就去调用binder_parse->svcmgr_handler函数回调处理请求
19. 比如注册service, binder_loop会读到对binder的请求,binder_parse会分析是啥请求,如果是BR_TRANSACTION类别,会调用svcmgr_handler@service_manager.c;再加以分析具体的操作,如果是SVC_MGR_ADD_SERVICE,则调用do_add_service注册该service,并且通过binder_send_reply返回结果。
20. do_add_service首先会去检查是否有权限注册service(一般service的uid == AID_SYSTEM,表示可以register),如果都没什么问题,会注册该service,加入到svcList中来, 注意,在ServiceManager中维护service信息的地方就是svclist,里面存了service的name和handler!!!!!
21. 如果是获取service, 则在svcmgr_handler函数中的操作是SVC_MGR_CHECK_SERVICE,然后调用 do_find_service, 如果查找到则把返回的数据写入reply,返回给客户端。
22. 以下分析如何实现addService@frameworks/base/core/java/android/os/servicemanager.java 到do_add_service@frameworks/base/cmds/servicemanager/service_manager.c, 我们知道在SystemServer中,将可以看到它建立了android中的大部分服务,并通过ServerManager的add_service方法把这些服务加入到了ServiceManager的svclist中,从而完成ServcieManager对服务的管理。
23. run@frameworks/base/services/java/com/android/server/systemserver.java中 ServiceManager.addService("battery", battery);
a. --> getIServiceManager().addService(name, service);
b. --> sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
c. 分析BinderInternal.getContextObject()@frameworks/base/core/java/com/android/internal/os/binderinternal.java -->android_os_BinderInternal_getContextObject@frameworks/base/core/jni/android_util_binder.cpp.
d. ProcessState::self()->getContextObject(NULL)@frameworks/base/libs/binder/processstate.cpp,--> getStrongProxyForHandle(0)->lookupHandleLocked(0)-->
e. 分析processstate.cpp主要函数,open_driver函数会打开"/dev/binder",其文件handle报存在mDriverFD;
e. 分析asInterface@frameworks/base/core/java/androids/ServiceManagerNative.java,
f. ....太复杂,分析不下去了, 总而言之binder机制是基于操作"/dev/binder"建立起来的
1. init.rc 中有
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
socket zygote stream 666
onrestart write /proc/sysrq-trigger c
2. service zygote在frameworks/base/cmds/app_process/app_main.cpp--> main启动 --> runtime.start("com.android.internal.os.ZygoteInit",startSystemServer); 启动ZygoteInit进程,以后所有的java进程均须通过此进程fork而成。
3. frameworks/base/core/jni/AndroidRuntime.cpp中函数start(...)非常重要,virtual machine在这启动和android function在这注册;最后env->CallStaticVoidMethod(startClass, startMeth, strArray); //调用com.android.internal.os.ZygoteInit的main()方法
4. frameworks/base/core/java/com/android/internal/os/ZygoteInit.java; 启动main函数中有,其中gc()也在这启动
if (argv[1].equals("true")) { //只支持true参数
startSystemServer(); //此处启动systemserver
}
if (ZYGOTE_FORK_MODE) { //进入死循环,zygote进程由此建立,并一直运行;利用Socket通讯,接收ActivityManangerService的请求,Fork应用程序
runForkMode();
} else {
runSelectLoopMode();
}
在startSystemServer();中有
pid = Zygote.forkSystemServer( //fork出进程
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
if (pid == 0) {
handleSystemServerProcess(parsedArgs);//parsedArgs的参数中包含有"com.android.server.SystemServer"
5. 进程fork出来后,关闭socket并初始化进程handleSystemServerProcess
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
closeServerSocket();
/*
* Pass the remaining arguments to SystemServer.
* "--nice-name=system_server com.android.server.SystemServer"
*/
RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
/* should never reach here */
}
最后调用 所有java进程的共同入口zygoteInit()。
6. frameworks/base/core/java/com/android/internal/os/RuntimeInit.java中函数zygoteInit(String[] argv)
public static final void zygoteInit(String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
...
commonInit(); //初始化时区,设置agent
zygoteInitNative(); //调用到com_android_internal_os_RuntimeInit_zygoteInit@AndroidRuntime.cpp -> gCurRuntime->onZygoteInit(),此处启动ThreadPool
...
invokeStaticMain(startClass, startArgs); //调用com.android.server.SystemServer的main方法
}
7. frameworks/base/core/jni/androidruntime.cpp中
static JNINativeMethod gMethods[] = {"zygoteInitNative", "()V",(void*) com_android_internal_os_RuntimeInit_zygoteInit}
static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
8. frameworks/base/cmds/app_process; 是class AppRuntime : public AndroidRuntime;所以onZygoteInit被重载
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
if (proc->supportsProcesses()) {
LOGV("App process: starting thread pool.\n");
proc->startThreadPool(); //启动线程池处理Binder事件,需要进一步分析,有啥用处?
}
}
9. 继续分析前面invokeStaticMain的运行路径,frameworks/base/services/java/com/android/server/SystemServer.java;
public static void main(String[] args) {
// 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);
System.loadLibrary("android_servers"); //Load JNI library here that is used by SystemServer,位于手机中/system/lib
init1(args); //这里调用到com_android_server_SystemServer.cpp/android_server_SystemServer_init1
}
10. frameworks/base/services/jni/com_android_server_SystemServer.cpp中有
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },
};
调用路径android_server_SystemServer_init1-->frameworks/base/cmds/system_server/library/system_init.cpp中函数system_init
extern "C" status_t system_init()
{
...
// Start the sensor service
SensorService::instantiate();//sensor service在这启动,意外收获
if (!proc->supportsProcesses()) { //在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建
// Start the AudioFlinger
AudioFlinger::instantiate();
// Start the media playback service
MediaPlayerService::instantiate();
// Start the camera service
CameraService::instantiate();
// Start the audio policy service
AudioPolicyService::instantiate();
}
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services.\n");
runtime->callStatic("com/android/server/SystemServer", "init2");//调用init2@SystemServer.java,在这里创建工作线程以启动各java服务并进入循环处理各service请求
}
11. 从上分析来看,frameworks/base/services/java/com/android/server/SystemServer.java, main函数中-->init1-->init2 如此关联起来的-->ServerThread-->run实现Java Service注册初始化及进入SystemServer事件处理循环;在run中通过addservice注册很多sevice,另外还有启动 ActivityManagerService.main(factoryTest);和((ActivityManagerService)ActivityManagerNative.getDefault()).systemReady(new Runnable()...)
12. frameworks/base/services/java/com/android/server/am/ActivityManagerService.java; 中main函数
public static final Context main(int factoryTest) {
AThread thr = new AThread();//作为ActivityManager的工作线程,在其中处理ActivityManager相关的消息
thr.start();
...
ActivityThread at = ActivityThread.systemMain();//加载system应用,并把此线程作为SystemServer进程的system线程
...
m.startRunning(null, null, null, null); //初始化变量并设置system ready为true
}
13. systemReady@ActivityManagerService.java--> mMainStack.resumeTopActivityLocked(null);-->mService.startHomeActivityLocked();-->mMainStack.startActivityLocked ,由此启动了Home apk;
14. frameworks/base/core/java/android/app/activitythread.java; 中systemMain()、startRunning和systemReady函数
15. 以下分析的是servicemanager如何管理service???
16. init.rc 中有
service servicemanager /system/bin/servicemanager //
user system
critical
onrestart restart zygote
onrestart restart media
17. 该源代码位于 frameworks/base/cmds/servicemanager/
18. service_manager.c 中main函数
a. 函数binder_open,打开"/dev/binder"设备,并在内存中映射128K的空间。
b. 函数binder_become_context_manager,通知Binder设备,执行ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0)把自己变成context_manager ;
c. 函数binder_loop,进入循环,不停的去读Binder设备,看是否有对service的请求,如果有BR_TRANSACTION请求的话,就去调用binder_parse->svcmgr_handler函数回调处理请求
19. 比如注册service, binder_loop会读到对binder的请求,binder_parse会分析是啥请求,如果是BR_TRANSACTION类别,会调用svcmgr_handler@service_manager.c;再加以分析具体的操作,如果是SVC_MGR_ADD_SERVICE,则调用do_add_service注册该service,并且通过binder_send_reply返回结果。
20. do_add_service首先会去检查是否有权限注册service(一般service的uid == AID_SYSTEM,表示可以register),如果都没什么问题,会注册该service,加入到svcList中来, 注意,在ServiceManager中维护service信息的地方就是svclist,里面存了service的name和handler!!!!!
21. 如果是获取service, 则在svcmgr_handler函数中的操作是SVC_MGR_CHECK_SERVICE,然后调用 do_find_service, 如果查找到则把返回的数据写入reply,返回给客户端。
22. 以下分析如何实现addService@frameworks/base/core/java/android/os/servicemanager.java 到do_add_service@frameworks/base/cmds/servicemanager/service_manager.c, 我们知道在SystemServer中,将可以看到它建立了android中的大部分服务,并通过ServerManager的add_service方法把这些服务加入到了ServiceManager的svclist中,从而完成ServcieManager对服务的管理。
23. run@frameworks/base/services/java/com/android/server/systemserver.java中 ServiceManager.addService("battery", battery);
a. --> getIServiceManager().addService(name, service);
b. --> sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
c. 分析BinderInternal.getContextObject()@frameworks/base/core/java/com/android/internal/os/binderinternal.java -->android_os_BinderInternal_getContextObject@frameworks/base/core/jni/android_util_binder.cpp.
d. ProcessState::self()->getContextObject(NULL)@frameworks/base/libs/binder/processstate.cpp,--> getStrongProxyForHandle(0)->lookupHandleLocked(0)-->
e. 分析processstate.cpp主要函数,open_driver函数会打开"/dev/binder",其文件handle报存在mDriverFD;
e. 分析asInterface@frameworks/base/core/java/androids/ServiceManagerNative.java,
f. ....太复杂,分析不下去了, 总而言之binder机制是基于操作"/dev/binder"建立起来的