Android Binder机制学习总结(三)-ServiceManager部分
扫描二维码
随时随地手机看文章
接上篇的内容,分析下ServiceManager的实现。
ServiceManager的实现位于:
4.2:/frameworks/base/cmds/servicemanager/
4.3:frameworks/native/cmds/servicemanager/
ServiceManager的启动 ServiceManager的的启动由init进程根据init.rc文件的配置执行,从时间顺序上来说,ServiceManager的启动优先于Zygote进程
service servicemanager /system/bin/servicemanager class core //core类服务 user system //用户名 group system //用户组 critical //重要service, 如果4分钟内crush4次以上,则重启系统并进入recovery onrestart restart zygote //servicemanager重启以后,自动重启zygote onrestart restart media //同上 onrestart restart surfaceflinger //同上 onrestart restart drm //同上
ServiceManager是一个可执行文件,所以,我们从main函数看起(frameworks/base/cmds/servicemanager/servicemanager.c):
int main(int argc, char **argv) { struct binder_state *bs; void *svcmgr = BINDER_SERVICE_MANAGER; bs = binder_open(128*1024); if (binder_become_context_manager(bs)) { ALOGE("cannot become context manager (%s)n", strerror(errno)); return -1; } svcmgr_handle = svcmgr; binder_loop(bs, svcmgr_handler);//svcmgr_handle为具体的请求处理逻辑 return 0; }
简单来说,ServiceManager的启动分为三个步骤: 打开dev/binder,并创建binder缓冲区注册当前进程为上下文管理者(ServiceManager)进入处理循环,等待Service/Client的请求 步骤一 步骤一,由binder_open函数实现(frameworks/base/cmds/servicemanager/binder.c):
struct binder_state *binder_open(unsigned mapsize) { struct binder_state *bs; bs = malloc(sizeof(*bs)); if (!bs) { errno = ENOMEM; return 0; } bs->fd = open("/dev/binder", O_RDWR);//上一节讲过,这里会转入内核态,执行binder_open,创建binder_proc if (bs->fd < 0) { fprintf(stderr,"binder: cannot open device (%s)n", strerror(errno)); goto fail_open; } bs->mapsize = mapsize;//mapsize = 128KB bs->mapped = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, bs->fd, 0);//上一节讲过,这里会转入内核态,执行binder_mmap //在内核态创建相同size的缓冲区,并分配第一个物理页面,计算内核缓冲区地址和用户缓冲区地址的偏移量 if (bs->mapped == MAP_FAILED) { fprintf(stderr,"binder: cannot map device (%s)n", strerror(errno)); goto fail_map; } /* TODO: check version */ return bs; fail_map: close(bs->fd); fail_open: free(bs); return 0; }
如果上一节binder driver部分的内容有比较好的理解的话,这边的代码应该比较好理解的,顺便看看binder_state的实现:
struct binder_state { int fd; void *mapped; unsigned mapsize; };
步骤二 步骤二,由binder_become_context_manager函数实现:
int binder_become_context_manager(struct binder_state *bs) { return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0); }
灰常简单的实现,有木有? 让我们来回忆一下,上一节的内容,ioctl的调用会转入到binder driver的binder_ioctl函数来处理BINDER_SET_CONTEXT_MGR:
case BINDER_SET_CONTEXT_MGR: if (binder_context_mgr_node != NULL) { printk(KERN_ERR "binder: BINDER_SET_CONTEXT_MGR already setn"); ret = -EBUSY; goto err; } ret = security_binder_set_context_mgr(proc->tsk); if (ret < 0) goto err; if (binder_context_mgr_uid != -1) { if (binder_context_mgr_uid != current->cred->euid) { printk(KERN_ERR "binder: BINDER_SET_" "CONTEXT_MGR bad uid %d != %dn", current->cred->euid, binder_context_mgr_uid); ret = -EPERM; goto err; } } else binder_context_mgr_uid = current->cred->euid; binder_context_mgr_node = binder_new_node(proc, NULL, NULL);//binder_context_mgr_node->proc = servicemanager if (binder_context_mgr_node == NULL) { ret = -ENOMEM; goto err; } binder_context_mgr_node->local_weak_refs++; binder_context_mgr_node->local_strong_refs++; binder_context_mgr_node->has_strong_ref = 1; binder_context_mgr_node->has_weak_ref = 1; break;
忽略安全检查等代码,上面的代码就是设定了全局变量binder_context_mgr_node,并增加引用计数。 步骤三 处理循环的实现在binder_loop函数中:
void binder_loop(struct binder_state *bs, binder_handler func) { int res; struct binder_write_read bwr; unsigned readbuf[32]; bwr.write_size = 0; bwr.write_consumed = 0; bwr.write_buffer = 0; readbuf[0] = BC_ENTER_LOOPER; binder_write(bs, readbuf, sizeof(unsigned));//binder driver会通过binder_thread_write函数处理BC_ENTER_LOOPER指令 for (;;) { bwr.read_size = sizeof(readbuf); bwr.read_consumed = 0; bwr.read_buffer = (unsigned) readbuf; res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);//读取client/service的请求 if (res < 0) { ALOGE("binder_loop: ioctl failed (%s)n", strerror(errno)); break; } res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func);//处理请求 if (res == 0) { ALOGE("binder_loop: unexpected reply?!n"); break; } if (res < 0) { ALOGE("binder_loop: io error %d %sn", res, strerror(errno)); break; } } }
ServiceManager客户端代理 ServiceManager运行在自己的进程中,为了向Client/Service进程提供服务,ServiceManager为自己准备了客户端代理,方便Client/Service调用。 IServiceManager和BpServiceManager IServiceManager是ServiceManager在native层的接口(framework/native/include/binder/IServiceManager.h):
class IServiceManager : public IInterface { public: DECLARE_META_INTERFACE(ServiceManager); /** * Retrieve an existing service, blocking for a few seconds * if it doesn't yet exist. */ virtual spgetService( const String16& name) const = 0; /** * Retrieve an existing service, non-blocking. */ virtual spcheckService( const String16& name) const = 0; /** * Register a service. */ virtual status_t addService( const String16& name, const sp& service, bool allowIsolated = false) = 0; /** * Return list of all existing services. */ virtual VectorlistServices() = 0; enum { GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION, CHECK_SERVICE_TRANSACTION, ADD_SERVICE_TRANSACTION, LIST_SERVICES_TRANSACTION, }; };
从接口中,我们看到SeviceManager提供了4个功能: getService,同checkServicecheckService,供Client获取Service的binderaddService, 供Service注册binderlistService,用于枚举所有已经注册的binder 而BpServiceManager是IServiceManager的一个子类,提供了IServiceManager的实现(frameworks/native/libs/binder/IServiceManager.cpp):
class BpServiceManager : public BpInterface{ public: BpServiceManager(const sp& impl) : BpInterface(impl) { } virtual spgetService(const String16& name) const { ...... //实现啥的,我们后面再看 } virtual spcheckService( const String16& name) const { ...... } virtual status_t addService(const String16& name, const sp& service, bool allowIsolated) { ...... } virtual VectorlistServices() { ...... } };
前缀Bp可以理解为Binder Proxy,即BpServiceManager实际上是ServiceManager在客户进程中的一个代理,所以BpServiceManager并不负责实现真正的功能,而是通过Binder通信发送请求到前面启动的ServiceManager进程。上一节中我们讲到过,Binder通信的前提是客户端进程需要有BpBinder,那么BpBinder从何而来呢? defaultServiceManager 作为一个特殊的“Service”,Android系统为ServiceManager准备了“快捷方式”,这个快捷方式就是defaultServiceManager(frameworks/native/libs/binder/IServiceManager.cpp):
spdefaultServiceManager() { if (gDefaultServiceManager != NULL) return gDefaultServiceManager;//单例模式 { AutoMutex _l(gDefaultServiceManagerLock); if (gDefaultServiceManager == NULL) { gDefaultServiceManager = interface_cast( ProcessState::self()->getContextObject(NULL)); } } return gDefaultServiceManager; }
这里可以把defaultServiceManager分解为三个步骤: ProcessState::self()ProcessState->getContextObject(NULL)interface_cast