不管是客户端还是服务端,头部都要先调用

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()返回了什么?的更多相关文章

  1. python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码

    python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码 淘宝IP地址库 http://ip.taobao.com/目前提供的服务包括:1. 根据用户提供的 ...

  2. Binder学习笔记(十二)—— binder_transaction(...)都干了什么?

    binder_open(...)都干了什么? 在回答binder_transaction(...)之前,还有一些基础设施要去探究,比如binder_open(...),binder_mmap(...) ...

  3. Binder学习笔记(九)—— 服务端如何响应Test()请求 ?

    从服务端代码出发,TestServer.cpp int main() { sp < ProcessState > proc(ProcessState::self()); sp < I ...

  4. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

  5. Java IO学习笔记二

    Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...

  6. 《SQL必知必会》学习笔记二)

    <SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...

  7. Redis学习笔记二 (BitMap算法分析与BitCount语法)

    Redis学习笔记二 一.BitMap是什么 就是通过一个bit位来表示某个元素对应的值或者状态,其中的key就是对应元素本身.我们知道8个bit可以组成一个Byte,所以bitmap本身会极大的节省 ...

  8. Django学习笔记二

    Django学习笔记二 模型类,字段,选项,查询,关联,聚合函数,管理器, 一 字段属性和选项 1.1 模型类属性命名限制 1)不能是python的保留关键字. 2)不允许使用连续的下划线,这是由dj ...

  9. Typescript 学习笔记二:数据类型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  10. 学习笔记(二)--->《Java 8编程官方参考教程(第9版).pdf》:第七章到九章学习笔记

    注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.若有违本之,则本人不负法律责任.违法者自负一切 ...

随机推荐

  1. VirtualBox-Debian7.2-share

    1.在VirtualBox(用的版本是4.3.6)中,选择虚拟机->设置-> 共享文件夹, 2.添加一个主机上的文件夹readhat用来作为共享文件夹,选中固定分配和自动挂载, 结果:进入 ...

  2. Java-API:un-java.util.Set

    ylbtech-Java-API:java.util.Set 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部 0. https://docs.oracle.com ...

  3. git教程(远程仓库和管理分支)

    在github上新建了一个仓库,然后相与本地的仓库联系起来 $ Git remote add origin https://github.com/liona329/learngit.git fatal ...

  4. 侯捷STL学习(七)--深度探索vector&&array

    layout: post title: 侯捷STL学习(七) date: 2017-06-13 tag: 侯捷STL --- 第十六节 深度探索vector vector源码剖析 vector内存2倍 ...

  5. hibernate 事务的隔离级别

    脏读不可重复读幻读可序列化(符合事务的四个特性的正常情况 ) 解释: 脏读:事务A对数据1做了更新,但是还没有来得及提交 此时事务B对数据1进行了查询获得了事务A更新后的数据, 但是事务A因为一些原因 ...

  6. 简单的触发黑名单阻断演示 control+c

    #include "stdafx.h"#include <signal.h>#include <windows.h> #include <iostre ...

  7. debian7 安装VMware Tools

    前提:需要安装gcc.kernel 1. apt-get install gcc 2. apt-get install kernel 问题描述: 安装时如果提示更换介质 :请把标有 " de ...

  8. C语言学习笔记--C语言中的宏定义

    1. C 语言中的宏定义 (1)#define 是预处理器处理的单元实体之一(因此,预处理器只是简单的进行替换,并不(2)#define 定义的宏可以出现在程序的任意位置(包括函数体的内部)(3)#d ...

  9. DAY10-MYSQL存储引擎

    一 什么是存储引擎 mysql中建立的库===>文件夹 库中建立的表===>文件 现实生活中我们用来存储数据的文件有不同的类型,每种文件类型对应各自不同的处理机制:比如处理文本用txt类型 ...

  10. Android 自定义格式的对话框

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaoAAADvCAIAAAAsDwfKAAAgAElEQVR4nLy9bZhcVZUofEg0GcURBk ...