本文基于 android-14.0.0_r15 版本讲解。
接下的章节就会开始逐句分析上一节给出的 Native 程序。
本节主要分析 Native App 与 SurfaceFinger 建立 Binger 通信过程分析。
SurfaceFlinger 对外提供了怎样的 Binder 服务?
在分析代码之前,我们需要知道 SurfaceFlinger 对外提供了怎么样的 Binder 服务?
先看 SurfaceFlinger 的主函数:
// frameworks/native/services/surfaceflinger/main_surfaceflinger.cpp
int main(int, char**) {
// ......
sp<SurfaceFlinger> flinger = surfaceflinger::createSurfaceFlinger();
// .....
sp<IServiceManager> sm(defaultServiceManager());
// 注册了一个叫 SurfaceFlinger 的 binder 服务
sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false,
IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
// ......
// publish gui::ISurfaceComposer, the new AIDL interface
sp<SurfaceComposerAIDL> composerAIDL = sp<SurfaceComposerAIDL>::make(flinger);
// 注册了一个叫 SurfaceFlingerAIDL 的 binder 服务
sm->addService(String16("SurfaceFlingerAIDL"), composerAIDL, false,
IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
// ......
}
在主函数中注册了 SurfaceFlinger 和 SurfaceComposerAIDL 两个 Binder 服务。
SurfaceFlinger Binder 服务相关类的关系如下图所示:
SurfaceFlinger Binder 服务对应的接口类是 ISurfaceComposer:
class ISurfaceComposer: public IInterface {
public:
DECLARE_META_INTERFACE(SurfaceComposer)
// flags for setTransactionState()
enum {
eAnimation = 0x02,
// Explicit indication that this transaction and others to follow will likely result in a
// lot of layers being composed, and thus, SurfaceFlinger should wake-up earlier to avoid
// missing frame deadlines. In this case SurfaceFlinger will wake up at
// (sf vsync offset - debug.sf.early_phase_offset_ns). SurfaceFlinger will continue to be
// in the early configuration until it receives eEarlyWakeupEnd. These flags are
// expected to be used by WindowManager only and are guarded by
// android.permission.WAKEUP_SURFACE_FLINGER
eEarlyWakeupStart = 0x08,
eEarlyWakeupEnd = 0x10,
eOneWay = 0x20
};
/* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */
virtual status_t setTransactionState(
const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& state,
const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
InputWindowCommands inputWindowCommands, int64_t desiredPresentTime,
bool isAutoTimestamp, const std::vector<client_cache_t>& uncacheBuffer,
bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
uint64_t transactionId, const std::vector<uint64_t>& mergedTransactionIds) = 0;
};
这里只有一个函数 setTransactionState,应该不是 SurfaceFlinger 对外提供服务的主战场。
我们接着看 SurfaceComposerAIDL Binder 服务,其相关类关系如下图所示:
从名字就可以看出,SurfaceComposerAIDL 是通过 aidl 辅助实现的 binder 服务。
对应的 aidl 文件是:
// /frameworks/native/libs/gui/aidl/android/gui/ISurfaceComposer.aidl
package android.gui;
// ......
/** @hide */
interface ISurfaceComposer {
enum VsyncSource {
eVsyncSourceApp = 0,
eVsyncSourceSurfaceFlinger = 1
}
enum EventRegistration {
modeChanged = 1 << 0,
frameRateOverride = 1 << 1,
}
void bootFinished();
@nullable IDisplayEventConnection createDisplayEventConnection(VsyncSource vsyncSource,
EventRegistration eventRegistration, @nullable IBinder layerHandle);
@nullable ISurfaceComposerClient createConnection();
@nullable IBinder createDisplay(@utf8InCpp String displayName, boolean secure,
float requestedRefreshRate);
void destroyDisplay(IBinder display);
long[] getPhysicalDisplayIds();
@nullable IBinder getPhysicalDisplayToken(long displayId);
FrameEvent[] getSupportedFrameTimestamps();
void setPowerMode(IBinder display, int mode);
DisplayStatInfo getDisplayStats(@nullable IBinder display);
//......
}
aidl 文件中定义了大量的函数,这里只贴出了部分。
aidl 文件主要生成了以下的类:
- gui::ISurfaceComposer:描述 binder 服务的接口
- gui::BnSurfaceComposer:binder 服务端对象
- gui::BpSurfaceComposer:binder 代理端对象
该服务提供了大量的函数供客户端调用。
App 与 SurfaceFlinger 之间的 Binder 通信通道建立
在了解了 SurfaceFlinger 中的 Binder 服务以后,我们就可以开始分析代码了。
int main(int argc, char ** argv) {
sp<SurfaceComposerClient> surfaceComposerClient = new SurfaceComposerClient;
status_t err = surfaceComposerClient->initCheck();
if (err != OK) {
ALOGD("SurfaceComposerClient::initCheck error: %#x\n", err);
return;
}
// ......
}
我们 new 一个 SurfaceComposerClient 对象,SurfaceComposerClient 是 App 与 SurfaceFlinger 通信的辅助类,其构造函数如下:
// frameworks/native/libs/gui/SurfaceComposerClient.cpp
SurfaceComposerClient::SurfaceComposerClient() : mStatus(NO_INIT) {}
构造函数,除了给 mStatus 成员初始化一个值,就没了。
SurfaceComposerClient 中还定义了 onFirstRef 函数,在首次引用时,会被调用:
void SurfaceComposerClient::onFirstRef() {
sp<gui::ISurfaceComposer> sf(ComposerServiceAIDL::getComposerService());
if (sf != nullptr && mStatus == NO_INIT) {
sp<ISurfaceComposerClient> conn;
binder::Status status = sf->createConnection(&conn);
if (status.isOk() && conn != nullptr) {
mClient = conn;
mStatus = NO_ERROR;
}
}
}
onFirstRef 函数会先调用到 ComposerServiceAIDL::getComposerService():
// frameworks/native/libs/gui/include/private/gui/ComposerServiceAIDL.h
class ComposerServiceAIDL : public Singleton<ComposerServiceAIDL> {
sp<gui::ISurfaceComposer> mComposerService;
sp<IBinder::DeathRecipient> mDeathObserver;
mutable std::mutex mMutex;
ComposerServiceAIDL();
bool connectLocked();
void composerServiceDied();
friend class Singleton<ComposerServiceAIDL>;
public:
// Get a connection to the Composer Service. This will block until
// a connection is established. Returns null if permission is denied.
static sp<gui::ISurfaceComposer> getComposerService();
};
// /frameworks/native/libs/gui/SurfaceComposerClient.cpp
/*static*/ sp<gui::ISurfaceComposer> ComposerServiceAIDL::getComposerService() {
// 获取单例对象
ComposerServiceAIDL& instance = ComposerServiceAIDL::getInstance();
std::scoped_lock lock(instance.mMutex);
if (instance.mComposerService == nullptr) {
// 调用 connectLocked 获取 binder 服务
if (ComposerServiceAIDL::getInstance().connectLocked()) {
ALOGD("ComposerServiceAIDL reconnected");
WindowInfosListenerReporter::getInstance()->reconnect(instance.mComposerService);
}
}
return instance.mComposerService;
}
getComposerService 函数中会去获取到 ComposerServiceAIDL 单例对象,然后调用 ComposerServiceAIDL 单例对象的 connectLocked 方法去获取 SurfaceFlingerAIDL binder 服务:
bool ComposerServiceAIDL::connectLocked() {
const String16 name("SurfaceFlingerAIDL");
// 向 sm 获取到 SurfaceFlingerAIDL binder 服务代理端
mComposerService = waitForService<gui::ISurfaceComposer>(name);
if (mComposerService == nullptr) {
return false; // fatal error or permission problem
}
// Create the death listener.
class DeathObserver : public IBinder::DeathRecipient {
ComposerServiceAIDL& mComposerService;
virtual void binderDied(const wp<IBinder>& who) {
ALOGW("ComposerService aidl remote (surfaceflinger) died [%p]", who.unsafe_get());
mComposerService.composerServiceDied();
}
public:
explicit DeathObserver(ComposerServiceAIDL& mgr) : mComposerService(mgr) {}
};
// 注册死亡通知
mDeathObserver = new DeathObserver(*const_cast<ComposerServiceAIDL*>(this));
IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
return true;
}
connectLocked 获取到名为 SurfaceFlingerAIDL 的 binder 服务代理端 sp<gui::ISurfaceComposer> mComposerService,这个和上一节的分析相吻合。
接着通过这个代理端对象远程调用 createConnection 函数,获取到 sp<ISurfaceComposerClient> conn 匿名 Binder 服务。
找到 SurfaceFlingerAIDL 服务端 createConnection 函数的实现:
// /frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
const sp<Client> client = sp<Client>::make(mFlinger);
if (client->initCheck() == NO_ERROR) {
*outClient = client;
return binder::Status::ok();
} else {
*outClient = nullptr;
return binderStatusFromStatusT(BAD_VALUE);
}
}
new 一个 Client 然后通过参数返回
那这个 Client 又是啥呢?找到 Client 的实现:
// /frameworks/native/services/surfaceflinger/Client.h
class Client : public gui::BnSurfaceComposerClient {
public:
explicit Client(const sp<SurfaceFlinger>& flinger);
~Client() = default;
status_t initCheck() const;
private:
// ISurfaceComposerClient interface
binder::Status createSurface(const std::string& name, int32_t flags, const sp<IBinder>& parent,
const gui::LayerMetadata& metadata,
gui::CreateSurfaceResult* outResult) override;
binder::Status clearLayerFrameStats(const sp<IBinder>& handle) override;
binder::Status getLayerFrameStats(const sp<IBinder>& handle,
gui::FrameStats* outStats) override;
binder::Status mirrorSurface(const sp<IBinder>& mirrorFromHandle,
gui::CreateSurfaceResult* outResult) override;
binder::Status mirrorDisplay(int64_t displayId, gui::CreateSurfaceResult* outResult) override;
// constant
sp<SurfaceFlinger> mFlinger;
// thread-safe
mutable Mutex mLock;
};
Client 是一个 binder 服务端类,内部持有一个 SurfaceFlinger 的指针,指针的值通过构造函数传入。
该匿名 Binder 服务相关类的关系如图所示:
可以看出,Client 实际就是一个匿名 Binder 服务。
总结
- SurfaceFlinger 进程中提供了 SurfaceFlinger Binder 服务,SurfaceFlingerAIDL Binder 服务和一个名为 Client 的匿名 Binder 服务
整个 binder 通信通道的建立过程:
- App 向 ServiceManager 查询 SurfaceFlingerAIDL 服务,获取到服务的代理端对象
- 接着远程调用 SurfaceFlingerAIDL 服务的 createConnection 函数,获取到 Client 匿名服务的代理端对象
- App 想要调用 SurfaceFlinger 相关的功能,可以远程调用 Client 服务,Client 服务中具体的功能再委托给 SurfaceFlinger 来实现。