Binder学习笔记(二)——defaultServiceManager()返回了什么?
不管是客户端还是服务端,头部都要先调用
sp < IServiceManager > sm = defaultServiceManager();
defaultServiceManager()都干了什么,它返回的是什么实例呢?
该函数定义在frameworks/native/libs/binder/IserviceManager.cpp:33
sp<IServiceManager> defaultServiceManager()
{
if (gDefaultServiceManager != NULL) return gDefaultServiceManager; {
AutoMutex _l(gDefaultServiceManagerLock);
while (gDefaultServiceManager == NULL) {
gDefaultServiceManager = interface_cast<IServiceManager>(
ProcessState::self()->getContextObject(NULL)); // 这里才是关键步骤
if (gDefaultServiceManager == NULL)
sleep();
}
} return gDefaultServiceManager;
}
关键步骤可以分解为几步:1、ProcessState::self(),2、ProcessState::getContextObject(…),3、interface_cast<IserviceManager>(…)
1 ProcessState::self()
frameworks/native/libs/binder/ProcessState.cpp:70
sp<ProcessState> ProcessState::self() // 这又是一个进程单体
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
gProcess = new ProcessState; // 首次创建在这里
return gProcess;
}
ProcessState的构造函数很简单,frameworks/native/libs/binder/ProcessState.cpp:339
ProcessState::ProcessState()
: mDriverFD(open_driver()) // 这里打开了/dev/binder文件,并返回文件描述符
, mVMStart(MAP_FAILED)
, mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
, mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
, mExecutingThreadsCount()
, mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
, mManagesContexts(false)
, mBinderContextCheckFunc(NULL)
, mBinderContextUserData(NULL)
, mThreadPoolStarted(false)
, mThreadPoolSeq()
{
if (mDriverFD >= ) {
// XXX Ideally, there should be a specific define for whether we
// have mmap (or whether we could possibly have the kernel module
// availabla).
#if !defined(HAVE_WIN32_IPC)
// mmap the binder, providing a chunk of virtual address space to receive transactions.
mVMStart = mmap(, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, );
if (mVMStart == MAP_FAILED) {
// *sigh*
ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
close(mDriverFD);
mDriverFD = -;
}
#else
mDriverFD = -;
#endif
} LOG_ALWAYS_FATAL_IF(mDriverFD < , "Binder driver could not be opened. Terminating.");
}
ProcessState的构造函数主要完成两件事:1、初始化列表里调用opern_driver(),打开了文件/dev/binder;2、将文件映射到内存。ProcessState::self()返回单体实例。
2 ProcessState::getContextObject(…)
该函数定义在frameworks/native/libs/binder/ProcessState.cpp:85
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
return getStrongProxyForHandle();
}
继续深入,frameworks/native/libs/binder/ProcessState/cpp:179
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result; AutoMutex _l(mLock); handle_entry* e = lookupHandleLocked(handle); //正常情况下总会返回一个非空实例 if (e != NULL) {
// We need to create a new BpBinder if there isn't currently one, OR we
// are unable to acquire a weak reference on this current one. See comment
// in getWeakProxyForHandle() for more info about this.
IBinder* b = e->binder;
if (b == NULL || !e->refs->attemptIncWeak(this)) {
if (handle == ) { // 首次创建b为NULL,handle为0
// Special case for context manager...
// The context manager is the only object for which we create
// a BpBinder proxy without already holding a reference.
// Perform a dummy transaction to ensure the context manager
// is registered before we create the first local reference
// to it (which will occur when creating the BpBinder).
// If a local reference is created for the BpBinder when the
// context manager is not present, the driver will fail to
// provide a reference to the context manager, but the
// driver API does not return status.
//
// Note that this is not race-free if the context manager
// dies while this code runs.
//
// TODO: add a driver API to wait for context manager, or
// stop special casing handle 0 for context manager and add
// a driver API to get a handle to the context manager with
// proper reference counting. Parcel data;
status_t status = IPCThreadState::self()->transact(
, IBinder::PING_TRANSACTION, data, NULL, );
if (status == DEAD_OBJECT)
return NULL;
} b = new BpBinder(handle);
e->binder = b;
if (b) e->refs = b->getWeakRefs();
result = b; // 返回的是BpBinder(0)
} else {
// This little bit of nastyness is to allow us to add a primary
// reference to the remote proxy when this team doesn't have one
// but another team is sending the handle to us.
result.force_set(b);
e->refs->decWeak(this);
}
} return result;
}
因此getStrongProxyForHandle(0)返回的就是new BpBinder(0)。有几处细节可以再回头关注一下:
2.1 ProcessState::lookupHandleLocked(int32_t handle)
该函数定义在frameworks/native/libs/binder/ProcessState.cpp:166
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
{
const size_t N=mHandleToObject.size();
if (N <= (size_t)handle) {
handle_entry e;
e.binder = NULL;
e.refs = NULL;
status_t err = mHandleToObject.insertAt(e, N, handle+-N);
if (err < NO_ERROR) return NULL;
}
return &mHandleToObject.editItemAt(handle);
}
成员变量mHandleToObject是一个数组
Vector<handle_entry>mHandleToObject;
该函数遍历数组查找handle,如果没找到则会向该数组中插入一个新元素,handle是数组下标。新元素的binder、refs成员默认均为NULL,在getStrongProxyForHandle(…)中会被赋值。
3 interface_cast<IserviceManager>(…)
interface_cast(…)函数在binder体系中非常常用,后面还会不断遇见。该函数定义在frameworks/native/include/binder/IInterface.h:41
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
代入模板参数及实参后为:
IServiceManager::asInterface(new BpBinder());
该函数藏在宏IMPLEMENT_META_INTERFACE中,frameworks/native/libs/binder/IServiceManager.cpp:185
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
展开后为:
android::sp< IServiceManager > IServiceManager::asInterface(
const android::sp<android::IBinder>& obj)
{
android::sp< IServiceManager > intr;
if (obj != NULL) {
intr = static_cast< IServiceManager *>(
obj->queryLocalInterface(IServiceManager::descriptor).get());
if (intr == NULL) { // 首次会走这里
intr = new BpServiceManager(obj);
}
}
return intr;
}
因此它返回的就是new BpServiceManager(new BpBinder(0))。经过层层抽丝剥茧之后,defaultServiceManager()的返回值即为new BpServiceManager(new BpBinder(0)),请记住这个结论。
我们再顺道看一下BpServiceManager的继承关系以及构造函数,frameworks/native/libs/binder/IServiceManager.cpp:126
class BpServiceManager : public BpInterface<IServiceManager>
frameworks/native/libs/binder/IInterface.h:62
template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
BpServiceManager继承自BpInterface,后者继承自BpRefBase。
frameworks/native/libs/binder/IServiceManager.cpp:129
BpServiceManager继承自BpInterface,后者继承自BpRefBase。
frameworks/native/libs/binder/IServiceManager.cpp:
frameworks/native/include/binder/IInterface.h:134
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpRefBase(remote)
{
}
frameworks/native/libs/binder/Binder.cpp:241
BpRefBase::BpRefBase(const sp<IBinder>& o)
: mRemote(o.get()), mRefs(NULL), mState()
{
extendObjectLifetime(OBJECT_LIFETIME_WEAK); if (mRemote) {
mRemote->incStrong(this); // Removed on first IncStrong().
mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
}
}
BpServiceManager通过构造函数,沿着继承关系一路将impl参数传递给基类BpRefBase,基类将它赋给数据成员mRemote。在defaultServiceManager()中传给BpServiceManager构造函数的参数是new BpBinder(0)。
Binder学习笔记(二)——defaultServiceManager()返回了什么?的更多相关文章
- python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码
python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码 淘宝IP地址库 http://ip.taobao.com/目前提供的服务包括:1. 根据用户提供的 ...
- Binder学习笔记(十二)—— binder_transaction(...)都干了什么?
binder_open(...)都干了什么? 在回答binder_transaction(...)之前,还有一些基础设施要去探究,比如binder_open(...),binder_mmap(...) ...
- Binder学习笔记(九)—— 服务端如何响应Test()请求 ?
从服务端代码出发,TestServer.cpp int main() { sp < ProcessState > proc(ProcessState::self()); sp < I ...
- AJax 学习笔记二(onreadystatechange的作用)
AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...
- Java IO学习笔记二
Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...
- 《SQL必知必会》学习笔记二)
<SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...
- Redis学习笔记二 (BitMap算法分析与BitCount语法)
Redis学习笔记二 一.BitMap是什么 就是通过一个bit位来表示某个元素对应的值或者状态,其中的key就是对应元素本身.我们知道8个bit可以组成一个Byte,所以bitmap本身会极大的节省 ...
- Django学习笔记二
Django学习笔记二 模型类,字段,选项,查询,关联,聚合函数,管理器, 一 字段属性和选项 1.1 模型类属性命名限制 1)不能是python的保留关键字. 2)不允许使用连续的下划线,这是由dj ...
- Typescript 学习笔记二:数据类型
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- 学习笔记(二)--->《Java 8编程官方参考教程(第9版).pdf》:第七章到九章学习笔记
注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.若有违本之,则本人不负法律责任.违法者自负一切 ...
随机推荐
- MYSQLdump参数详解(转)
mysqldump客户端可用来转储数据库或搜集数据库进行备份或将数据转移到另一个SQL服务器(不一定是一个MySQL服务器).转储包含创建表和/或装载表的SQL语句. 如果你在服务器上进行备份,并且表 ...
- ramfs, rootfs and initramfs
ramfs, rootfs and initramfs October 17, 2005 Rob Landley <rob@landley.net> =================== ...
- SpringBoot自动化配置之一:SpringBoot内部的一些自动化配置原理
springboot用来简化Spring框架带来的大量XML配置以及复杂的依赖管理,让开发人员可以更加关注业务逻辑的开发. 比如不使用springboot而使用SpringMVC作为web框架进行开发 ...
- S2-045漏洞利用工具&解决方案
简单的重复造一个轮子,漏洞危害蛮大的 影响版本:Struts 2.3.5 - Struts 2.3.31,Struts 2.5 - Struts 2.5.10 仅供学习测试使用,严禁非法操作! 下载链 ...
- Python函数(二)-参数传递
位置参数 根据位置顺序来传递参数 # -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" def test(a,b): #a和b为形参 ...
- redis学习三 redis持久化
1,快照持久化 1简介 redis可以通过创建快照来获得某个时间点上的内存内容的数据副本,有了副本之后,就可以将副本发送到其他redis服务器上从而创建相同数据的从服务器,同时快照留在原 ...
- 问题:System.Guid.NewGuid();结果:C# System.Guid.NewGuid()
C# System.Guid.NewGuid() 概念 GUID: 即Globally Unique Identifier(全球唯一标识符) 也称作 UUID(Universally Unique I ...
- ABP模块配置
介绍 我们知道ABP中模块的配置都是通过模块的Configuration属性来设置的.例如在模块的生命周期方法中可以进行一系列的配置 审计 MQ Redis....也可以替换一些ABP默认配置 通常我 ...
- python之特殊方法
特殊方法的定义: 1.定义在某些class当中 2.不需要直接调用 3.Python的某些函数或者是操作符会调用相应的特殊方法 特殊方法很多,我们只需要编写用到的特殊方法,以及有关联性的特殊方法. — ...
- 动态参数 名称空间 作用域 作用域链 加载顺序 函数的嵌套 global nonlocal 等的用法总结
03,动态参数 *args,**kwargs # 用户传入到函数中的实参数量不定时,或者是为了以后拓展,# 此时要用到动态参数*args,**kwargs(万能参数.)# *args接收的是所有的位置 ...