Android Binder 详解(4) Binder 线程池
Android Binder详解【5】 ServiceManager
Android Binder 详解(6) Binder 客户端的创建
以 SurfaceComposerClient 的mComposerService为例 的完整创建流程,我会把从获取 ServiceManager、拿到 SF 的 Binder 句柄、创建 BpBinder,到最终生成业务层客户端对象 BpSurfaceComposer 的全链路逻辑梳理清楚,让整个过程更易理解。
一、整体架构背景
App(客户端)<-> Binder 驱动 <-> SurfaceFlinger(SF,服务端)的 Binder 通信核心规则:
- 两端统一实现
ISurfaceComposer接口(客户端侧为BpSurfaceComposer,服务端侧为BnSurfaceComposer); - App 侧的交互逻辑封装在
SurfaceComposerClient.cpp中,核心成员sp<ISurfaceComposer> mComposerService是 SF 的客户端代理,实际指向BpSurfaceComposer实例; - 整个创建过程的核心是:先拿到底层通信管道(BpBinder),再封装为业务层客户端(BpSurfaceComposer)。
二、mComposerService 创建全流程拆解
步骤 1:触发创建入口 ------ComposerService::connectLocked()
这是客户端发起 SF 服务连接的起点,目标是获取 SF 的 Binder 客户端引用:
//SurfaceComposerClient.cpp
bool ComposerService::connectLocked() {
const String16 name("SurfaceFlinger");
// 核心调用:通过waitForService获取SF的客户端代理
mComposerService = waitForService<ISurfaceComposer>(name);
}
步骤 2:waitForService模板函数 ------ 串联 SM 和接口转换
该函数完成两个核心动作,是连接 "ServiceManager" 和 "业务客户端" 的桥梁:
template<typename INTERFACE>
sp<INTERFACE> waitForService(const String16& name) {
// 1. 获取系统ServiceManager(SM)的引用(SM是所有Binder服务的"大管家")
const sp<IServiceManager> sm = defaultServiceManager();
// 2. 两步核心操作:
// - sm->waitForService(name):向SM请求SF的IBinder(实际是BpBinder)
// - interface_cast<INTERFACE>:将BpBinder转换为业务层客户端(BpSurfaceComposer)
return interface_cast<INTERFACE>(sm->waitForService(name));
}
步骤 3:从 SM 获取 SF 的 handle 并创建 BpBinder
SM 的waitForService最终调用getService,完成 "跨进程请求 handle → 用 handle 创建 BpBinder" 的核心动作:
-
跨进程请求 SF 的 handle :
BpServiceManager::getService通过 Binder 驱动向 SM 服务端发送请求,SM 返回 SF 在 Binder 驱动中的唯一标识 ------handle(整数,Binder 驱动维护 handle 与 SF 服务端的映射关系); -
解析 handle 并创建 BpBinder :
Parcel::unflattenBinder识别到flat_binder_object类型为BINDER_TYPE_HANDLE,调用ProcessState::getStrongProxyForHandle(handle)创建 BpBinder:sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle) { // 缓存检查 + 创建BpBinder(核心:用handle初始化BpBinder) sp<BpBinder> b = BpBinder::create(handle); // ... 缓存逻辑 ... return b; }//完整的BpBinder 是如何创建的 代码如下
sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
{sp<IBinder> out; if (!mTheRealServiceManager->getService(name, &out).isOk()) { return nullptr; } return out;}
//AIDL 工具生成的代码 IServiceManager.cpp
android::binder::Status BpServiceManager::getService(const ::std::string& name, ::android::sp<::android::IBinder>* _aidl_return){
//binder 调用 调用IPCThreadState的binder 封装, 数据发送给Binder驱动, SM service端getService(), 返回SF IBinder 信息给Binder驱动, Binder 驱动返回SF的ibinder信息(handle)
_aidl_ret_status = remote()->transact(BnServiceManager::TRANSACTION_getService, _aidl_data, &_aidl_reply, 0);//返回数据处理,这里用返回的数据(handle)生成了一个BpBinder对象 _aidl_ret_status = _aidl_reply.readNullableStrongBinder(_aidl_return);}
//Parcel.cpp
status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
{
return unflattenBinder(val);
}status_t Parcel::unflattenBinder(sp<IBinder>* out) const
{const flat_binder_object* flat = readObject(false); if (flat) { switch (flat->hdr.type) { case BINDER_TYPE_BINDER: { sp<IBinder> binder = sp<IBinder>::fromExisting(reinterpret_cast<IBinder*>(flat->cookie)); return finishUnflattenBinder(binder, out); } case BINDER_TYPE_HANDLE: { //类型是handle, 走这里 sp<IBinder> binder = ProcessState::self()->getStrongProxyForHandle(flat->handle); return finishUnflattenBinder(binder, out); } } }}
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;AutoMutex _l(mLock); handle_entry* e = lookupHandleLocked(handle); if (e != nullptr) { IBinder* b = e->binder; if (b == nullptr || !e->refs->attemptIncWeak(this)) { // //通过handle 创建BpBinder sp<BpBinder> b = BpBinder::create(handle); e->binder = b.get(); if (b) e->refs = b->getWeakRefs(); result = b; } else { result.force_set(b); e->refs->decWeak(this); } }}
关键说明 :BpBinder 仅封装与 Binder 驱动的底层交互(如transact方法),只负责 "发 / 收数据",不包含任何 SF 的业务逻辑,是纯粹的 "通信管道"。
步骤 4:interface_cast + 宏机制 ------BpBinder 转换为 BpSurfaceComposer
这是从 "底层通信管道" 到 "业务层客户端" 的核心转换,依赖两个宏和interface_cast模板函数:
-
interface_cast 触发转换 :模板函数调用
ISurfaceComposer::asInterface(obj)(obj 是 BpBinder);template<typename INTERFACE> inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj) { return INTERFACE::asInterface(obj); } -
宏生成 asInterface 方法 :
-
DECLARE_META_INTERFACE(SurfaceComposer):在ISurfaceComposer类中声明asInterface等方法; -
IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer"):实现asInterface核心逻辑:::android::sp<ISurfaceComposer> ISurfaceComposer::asInterface( const ::android::sp<::android::IBinder>& obj) { ::android::sp<ISurfaceComposer> intr; if (obj != nullptr) { // 检查是否是本地进程的SF实例(跨进程时为null) intr = ::android::sp<ISurfaceComposer>::cast( obj->queryLocalInterface(ISurfaceComposer::descriptor)); // 跨进程场景:用BpBinder创建BpSurfaceComposer(业务客户端) if (intr == nullptr) { intr = ::android::sp<BpSurfaceComposer>::make(obj); } } return intr; }
-
完整的宏代码:
//完整的宏代码
//Android frameworks\base\include\utils\IInterface.h
#define DECLARE_META_INTERFACE(INTERFACE) \
public: \
static const ::android::String16 descriptor; \
static ::android::sp<I##INTERFACE> asInterface( \
const ::android::sp<::android::IBinder>& obj); \
virtual const ::android::String16& getInterfaceDescriptor() const; \
I##INTERFACE(); \
virtual ~I##INTERFACE(); \
static bool setDefaultImpl(std::unique_ptr<I##INTERFACE> impl); \
static const std::unique_ptr<I##INTERFACE>& getDefaultImpl(); \
private: \
static std::unique_ptr<I##INTERFACE> default_impl; \
public: \
#define __IINTF_CONCAT(x, y) (x ## y)
#ifndef DO_NOT_CHECK_MANUAL_BINDER_INTERFACES
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
static_assert(internal::allowedManualInterface(NAME), \
"b/64223827: Manually written binder interfaces are " \
"considered error prone and frequently have bugs. " \
"The preferred way to add interfaces is to define " \
"an .aidl file to auto-generate the interface. If " \
"an interface must be manually written, add its " \
"name to the whitelist."); \
DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
#else
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
#endif
#define DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)\
const ::android::StaticString16 \
I##INTERFACE##_descriptor_static_str16(__IINTF_CONCAT(u, NAME));\
const ::android::String16 I##INTERFACE::descriptor( \
I##INTERFACE##_descriptor_static_str16); \
const ::android::String16& \
I##INTERFACE::getInterfaceDescriptor() const { \
return I##INTERFACE::descriptor; \
} \
::android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const ::android::sp<::android::IBinder>& obj) \
{ \
::android::sp<I##INTERFACE> intr; \
if (obj != nullptr) { \
intr = ::android::sp<I##INTERFACE>::cast( \
obj->queryLocalInterface(I##INTERFACE::descriptor)); \
if (intr == nullptr) { \
intr = ::android::sp<Bp##INTERFACE>::make(obj); \
} \
} \
return intr; \
} \
std::unique_ptr<I##INTERFACE> I##INTERFACE::default_impl; \
bool I##INTERFACE::setDefaultImpl(std::unique_ptr<I##INTERFACE> impl)\
{ \
/* Only one user of this interface can use this function */ \
/* at a time. This is a heuristic to detect if two different */ \
/* users in the same process use this function. */ \
assert(!I##INTERFACE::default_impl); \
if (impl) { \
I##INTERFACE::default_impl = std::move(impl); \
return true; \
} \
return false; \
} \
const std::unique_ptr<I##INTERFACE>& I##INTERFACE::getDefaultImpl() \
{ \
return I##INTERFACE::default_impl; \
} \
I##INTERFACE::I##INTERFACE() { } \
I##INTERFACE::~I##INTERFACE() { } \
#define CHECK_INTERFACE(interface, data, reply) \
do { \
if (!(data).checkInterface(this)) { return PERMISSION_DENIED; } \
} while (false) \
和
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
SF 客户端这两个宏完整展开后的代码
用ISurfaceComposer 举例解析这两个宏
ISurfaceComposer.h
class ISurfaceComposer: public IInterface {
public:
DECLARE_META_INTERFACE(SurfaceComposer)
}
ISurfaceComposer.cpp
IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer");
解析 DECLARE_META_INTERFACE(SurfaceComposer)
当在 ISurfaceComposer 类中调用 DECLARE_META_INTERFACE(SurfaceComposer) 时,预编译阶段会将宏直接展开为以下代码(对应宏的声明逻辑,仅做声明,无实现):
lass ISurfaceComposer: public IInterface {
public:
// 从 DECLARE_META_INTERFACE(SurfaceComposer) 展开的内容
static const ::android::String16 descriptor; // 接口唯一描述符
static ::android::sp<ISurfaceComposer> asInterface( // 核心转换方法
const ::android::sp<::android::IBinder>& obj);
virtual const ::android::String16& getInterfaceDescriptor() const; // 获取描述符的虚方法
ISurfaceComposer(); // 构造函数声明
virtual ~ISurfaceComposer(); // 虚析构函数声明
static bool setDefaultImpl(std::unique_ptr<ISurfaceComposer> impl); // 设置默认实现
static const std::unique_ptr<ISurfaceComposer>& getDefaultImpl(); // 获取默认实现
private:
static std::unique_ptr<ISurfaceComposer> default_impl; // 存储默认实现的静态成员
public:
// 其他业务接口(如屏幕合成、显示控制等)
// ...
};
解析 IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer")
预编译阶段,该宏会跳过白名单校验(或通过校验),最终展开为 DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE 的逻辑,针对 ISurfaceComposer 的核心展开代码如下(关键部分提取):
// 1. 初始化 ISurfaceComposer 的接口描述符(descriptor)
const ::android::StaticString16
ISurfaceComposer_descriptor_static_str16(u"android.ui.ISurfaceComposer"); // 拼接为 Unicode 字符串
const ::android::String16 ISurfaceComposer::descriptor(
ISurfaceComposer_descriptor_static_str16);
// 2. 实现 getInterfaceDescriptor 虚方法
const ::android::String16&
ISurfaceComposer::getInterfaceDescriptor() const {
return ISurfaceComposer::descriptor; // 直接返回唯一描述符
}
// 3. 实现核心转换方法 asInterface
::android::sp<ISurfaceComposer> ISurfaceComposer::asInterface(
const ::android::sp<::android::IBinder>& obj)
{
::android::sp<ISurfaceComposer> intr;
if (obj != nullptr) {
// 步骤1:查询本地 ISurfaceComposer 实例(同一进程内,如 SurfaceFlinger 内部调用)
intr = ::android::sp<ISurfaceComposer>::cast(
obj->queryLocalInterface(ISurfaceComposer::descriptor));
// 步骤2:若本地实例不存在(跨进程调用,如 App 调用 SurfaceFlinger),创建代理对象 BpSurfaceComposer
if (intr == nullptr) {
intr = ::android::sp<BpSurfaceComposer>::make(obj);
}
}
return intr;
}
// 4. 初始化默认实现成员并实现相关方法
std::unique_ptr<ISurfaceComposer> ISurfaceComposer::default_impl;
bool ISurfaceComposer::setDefaultImpl(std::unique_ptr<ISurfaceComposer> impl)
{
assert(!ISurfaceComposer::default_impl); // 保证仅能设置一次
if (impl) {
ISurfaceComposer::default_impl = std::move(impl);
return true;
}
return false;
}
const std::unique_ptr<ISurfaceComposer>& ISurfaceComposer::getDefaultImpl()
{
return ISurfaceComposer::default_impl;
}
// 5. 实现构造函数和析构函数(空实现,因 ISurfaceComposer 是接口类)
ISurfaceComposer::ISurfaceComposer() { }
ISurfaceComposer::~ISurfaceComposer() { }
这里通过BpBinder 创建了BpSurfaceComposer
mComposerService = interface_cast<ISurfaceComposer>(BpBinder){
return android::sp<BpSurfaceComposer>::make(obj);
}
步骤 5:最终结果
mComposerService(sp<ISurfaceComposer>)最终指向BpSurfaceComposer实例。App 调用mComposerService的业务方法(如屏幕合成)时,BpSurfaceComposer会通过持有的 BpBinder 调用transact,将请求发给 Binder 驱动,再由驱动转发给 SF 服务端。
三、核心角色分工
| 组件 | 核心作用 |
|---|---|
| ServiceManager(SM) | 系统 Binder 服务的 "管家",管理 Service 注册 / 查询,返回目标 Service 的 handle |
| handle | Binder 驱动中标识服务端(SF)的唯一整数,是客户端与服务端的 "通信索引" |
| BpBinder | 底层通信管道,仅封装 Binder 驱动的transact交互,无业务逻辑 |
| DECLARE/IMPLEMENT_META_INTERFACE | 自动生成asInterface方法,标准化 BpBinder 到业务客户端(BpXXX)的转换 |
| BpSurfaceComposer | 业务层客户端,封装 SF 的所有业务接口,基于 BpBinder 完成跨进程通信 |
总结
- 核心流程:App 创建 SF 客户端对象的完整链路是「触发 connectLocked → 获取 SM 引用 → 拿到 SF 的 handle 并创建 BpBinder → 宏 + interface_cast 转换为 BpSurfaceComposer → 赋值给 mComposerService」。
- 两层封装:BpBinder 负责底层 Binder 驱动交互(通信层),BpSurfaceComposer 负责 SF 业务逻辑封装(业务层),实现通信与业务解耦。
- 宏的价值:DECLARE/IMPLEMENT_META_INTERFACE 宏标准化了 "BpBinder→业务客户端" 的转换逻辑,避免重复开发,是 Android Binder 框架的核心设计模式。