1. surfaceFlinger initialization and message queue processing mechanism
makefile for surfaceflinger
/frameworks/native/services/surfaceflinger/Android.bp
235 cc_binary {
236 name: "surfaceflinger",
237 defaults: ["libsurfaceflinger_binary"],
238 init_rc: ["surfaceflinger.rc"],
239 srcs: [
240 ":surfaceflinger_binary_sources",
241 // Note: SurfaceFlingerFactory is not in the filegroup so that it
242 // can be easily replaced.
243 "SurfaceFlingerFactory.cpp",
244 ],
245 shared_libs: [
246 "libSurfaceFlingerProp",
247 ],
248
249 logtags: ["EventLog/EventLogTags.logtags"],
250 }
251
The init process can parse "surfaceflinger.rc", start the SurfaceFlinger service process, execute the main method, and start the surfaceflinger process:
/frameworks/native/services/surfaceflinger/main_surfaceflinger.cpp
#include "SurfaceFlingerFactory.h"
int main(int, char**) {
// 管道破裂的信号
signal(SIGPIPE, SIG_IGN);
hardware::configureRpcThreadpool(1 /* maxThreads */,
false /* callerWillJoin */);
startGraphicsAllocatorService();
// 限制 binder 的线程为 4 个
ProcessState::self()->setThreadPoolMaxThreadCount(4);
if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
ALOGW("Couldn't set uclamp.min: %s\n", strerror(errno));
}
。。。
// start the thread pool
sp<ProcessState> ps(ProcessState::self());
// 开启线程池
ps->startThreadPool();
// Reset current thread's policy and priority
if (errorInPriorityModification == 0) {
errorInPriorityModification = sched_setscheduler(0, origPolicy, &origSchedParam);
} else {
ALOGE("Failed to set SurfaceFlinger binder threadpool priority to SCHED_FIFO");
}
// 1. 创建 surfaceflinger 对象
sp<SurfaceFlinger> flinger = surfaceflinger::createSurfaceFlinger();
// Set the minimum policy of surfaceflinger node to be SCHED_FIFO.
// So any thread with policy/priority lower than {SCHED_FIFO, 1}, will run
// at least with SCHED_FIFO policy and priority 1.
if (errorInPriorityModification == 0) {
flinger->setMinSchedulerPolicy(SCHED_FIFO, newPriority);
}
setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);
set_sched_policy(0, SP_FOREGROUND);
// Put most SurfaceFlinger threads in the system-background cpuset
// Keeps us from unnecessarily using big cores
// Do this after the binder thread pool init
if (cpusets_enabled()) set_cpuset_policy(0, SP_SYSTEM);
// 2. 初始化 surfaceflinger
flinger->init();
// 通过 ServiceManager 增加 "surfaceflinger"服务到 manager中,通过getService可以获取到biander服务
sp<IServiceManager> sm(defaultServiceManager());
sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false,
IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
startDisplayService(); // dependency on SF getting registered above
if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
ALOGW("Couldn't set to SCHED_FIFO: %s", strerror(errno));
}
//3. 调用 surfaceflinger 的run 方法,开启消息队列机制
flinger->run();
return 0;
}
The basic operation is as follows:
- Create a SurfaceFlinger object and trigger the execution of SurfaceFlinger::onFirstRef()
- Call SurfaceFlinger::init() to initialize
- Register the service to ServiceManager (named "SurfaceFlinger")
- Call SurfaceFlinger::run()
1). Create surfaceflinger object
surfaceflinger::createSurfaceFlinger()
The SurfaceFlingerFactory header file is called
#include "SurfaceFlingerFactory.h"
/frameworks/native/services/surfaceflinger/SurfaceFlingerFactory.cpp
namespace android::surfaceflinger {
sp<SurfaceFlinger> createSurfaceFlinger() {
static DefaultFactory factory;
// 创建了 SurfaceFlinger 对象,传入的对象是 DefaultFactory
return new SurfaceFlinger(factory);
}
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
// factory 为 DefaultFactory,将其赋值给 mFactory
: mFactory(factory),
mInterceptor(mFactory.createSurfaceInterceptor()),
mTimeStats(std::make_shared<impl::TimeStats>()),
mFrameTracer(mFactory.createFrameTracer()),
mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, getpid())),
// 创建了消息队列 mFactory.createMessageQueue
mEventQueue(mFactory.createMessageQueue()),
// 创建了 CompositionEngine 对象
mCompositionEngine(mFactory.createCompositionEngine()),
mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
mPowerAdvisor(*this) {
ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
mSetInputWindowsListener = new SetInputWindowsListener([&]() { setInputWindowsFinished(); });
}
SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
ALOGI("SurfaceFlinger is starting");
hasSyncFramework = running_without_sync_framework(true);
dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Created a message queue mFactory.createMessageQueue
/frameworks/native/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
DefaultFactory header file
class DefaultFactory : public surfaceflinger::Factory {
public:
virtual ~DefaultFactory();
std::unique_ptr<HWComposer> createHWComposer(const std::string& serviceName) override;
std::unique_ptr<MessageQueue> createMessageQueue() override;
/frameworks/native/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
namespace android::surfaceflinger {
DefaultFactory::~DefaultFactory() = default;
std::unique_ptr<HWComposer> DefaultFactory::createHWComposer(const std::string& serviceName) {
return std::make_unique<android::impl::HWComposer>(serviceName);
}
// 创建独占智能指针 MessageQueue
std::unique_ptr<MessageQueue> DefaultFactory::createMessageQueue() {
return std::make_unique<android::impl::MessageQueue>();
}
Create exclusive smart pointer MessageQueue
The code path is as follows:
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp
2). Initialize surfaceflinger
flinger->init()
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
// Use StartPropertySetThread instead.
void SurfaceFlinger::init() {
// 会打印下列的log
ALOGI( "SurfaceFlinger's main thread ready to run. "
"Initializing graphics H/W...");
Mutex::Autolock _l(mStateLock);
// Get a RenderEngine for the given display / config (can't fail)
// TODO(b/77156734): We need to stop casting and use HAL types when possible.
// Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
// CompositionEngine 去设置渲染引擎 RenderEngine::create
mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
renderengine::RenderEngineCreationArgs::Builder()
.setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
.setImageCacheSize(maxFrameBufferAcquiredBuffers)
.setUseColorManagerment(useColorManagement)
.setEnableProtectedContext(enable_protected_contents(false))
.setPrecacheToneMapperShaderOnly(false)
.setSupportsBackgroundBlur(mSupportsBlur)
.setContextPriority(
useContextPriority
? renderengine::RenderEngine::ContextPriority::REALTIME
: renderengine::RenderEngine::ContextPriority::MEDIUM)
.build()));
// Set SF main policy after initializing RenderEngine which has its own policy.
if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
ALOGW("Failed to set main task profile");
}
mCompositionEngine->setTimeStats(mTimeStats);
// 设置 HwComposer
mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
// HwComposer 设置回调为 surfaceFlinger
mCompositionEngine->getHwComposer().setCallback(this);
ClientCache::getInstance().setRenderEngine(&getRenderEngine());
if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
enableHalVirtualDisplays(true);
}
// Process any initial hotplug and resulting display changes.
processDisplayHotplugEventsLocked();
const auto display = getDefaultDisplayDeviceLocked();
LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
const auto displayId = display->getPhysicalId();
LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
"Internal display is disconnected.");
// initialize our drawing state
mDrawingState = mCurrentState;
// set initial conditions (e.g. unblank default device)
initializeDisplays();
mPowerAdvisor.init();
char primeShaderCache[PROPERTY_VALUE_MAX];
property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
if (atoi(primeShaderCache)) {
if (setSchedFifo(false) != NO_ERROR) {
ALOGW("Can't set SCHED_OTHER for primeCache");
}
mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
if (setSchedFifo(true) != NO_ERROR) {
ALOGW("Can't set SCHED_OTHER for primeCache");
}
}
getRenderEngine().onPrimaryDisplaySizeChanged(display->getSize());
// Inform native graphics APIs whether the present timestamp is supported:
const bool presentFenceReliable =
!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
if (mStartPropertySetThread->Start() != NO_ERROR) {
ALOGE("Run StartPropertySetThread failed!");
}
ALOGV("Done initializing");
}
mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName)
method analysis
/frameworks/native/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
std::unique_ptr<HWComposer> DefaultFactory::createHWComposer(const std::string& serviceName) {
// 创建 HWComposer 对象
return std::make_unique<android::impl::HWComposer>(serviceName);
}
Create an HWComposer object
/frameworks/native/services/surfaceflinger/DisplayHardware/HWComposer.cpp
namespace impl {
HWComposer::HWComposer(std::unique_ptr<Hwc2::Composer> composer)
// mComposer 为:Composer 对象
: mComposer(std::move(composer)),
mMaxVirtualDisplayDimension(static_cast<size_t>(sysprop::max_virtual_display_dimension(0))),
mUpdateDeviceProductInfoOnHotplugReconnect(
sysprop::update_device_product_info_on_hotplug_reconnect(false)) {}
HWComposer::HWComposer(const std::string& composerServiceName)
// 这里创建了 Composer 对象,参数是:composerServiceName
: HWComposer(std::make_unique<Hwc2::impl::Composer>(composerServiceName)) {}
mComposer is: Composer object, the parameter passed in composerServiceName is: "default"
/frameworks/native/services/surfaceflinger/DisplayHardware/ComposerHal.cpp
Composer is equivalent to the interface for obtaining hal layer services
Composer::Composer(const std::string& serviceName) : mWriter(kWriterInitialSize) {
// 获取hal 层服务
mComposer = V2_1::IComposer::getService(serviceName);
if (mComposer == nullptr) {
LOG_ALWAYS_FATAL("failed to get hwcomposer service");
}
if (sp<IComposer> composer_2_4 = IComposer::castFrom(mComposer)) {
composer_2_4->createClient_2_4([&](const auto& tmpError, const auto& tmpClient) {
if (tmpError == V2_4::Error::NONE) {
mClient = tmpClient;
mClient_2_2 = tmpClient;
mClient_2_3 = tmpClient;
mClient_2_4 = tmpClient;
}
});
} else if (sp<V2_3::IComposer> composer_2_3 = V2_3::IComposer::castFrom(mComposer)) {
composer_2_3->createClient_2_3([&](const auto& tmpError, const auto& tmpClient) {
if (tmpError == Error::NONE) {
mClient = tmpClient;
mClient_2_2 = tmpClient;
mClient_2_3 = tmpClient;
}
});
} else {
mComposer->createClient([&](const auto& tmpError, const auto& tmpClient) {
if (tmpError != Error::NONE) {
return;
}
mClient = tmpClient;
3). Call the run method of surfaceflinger to start the message queue mechanism
flinger->run()
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::run() {
// 循环遍历消息
while (true) {
mEventQueue->waitMessage();
}
}
// 发送消息的接口
template <typename F, typename T>
inline std::future<T> SurfaceFlinger::schedule(F&& f) {
auto [task, future] = makeTask(std::move(f));
mEventQueue->postMessage(std::move(task));
return std::move(future);
}
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp
void MessageQueue::init(const sp<SurfaceFlinger>& flinger) {
mFlinger = flinger;
// 创建 Looper 对象
mLooper = new Looper(true);
mHandler = new Handler(*this);
}
-------
// waitMessage 也是个死循环,调用 Looper->pollOnce 方法
void MessageQueue::waitMessage() {
do {
IPCThreadState::self()->flushCommands();
int32_t ret = mLooper->pollOnce(-1);
switch (ret) {
case Looper::POLL_WAKE:
case Looper::POLL_CALLBACK:
continue;
case Looper::POLL_ERROR:
ALOGE("Looper::POLL_ERROR");
continue;
case Looper::POLL_TIMEOUT:
// timeout (should not happen)
continue;
default:
// should not happen
ALOGE("Looper::pollOnce() returned unknown status %d", ret);
continue;
}
} while (true);
}
The header file that calls Looper is as follows:
27 #include <utils/Looper.h>
/system/core/libutils/include/utils/Looper.h
int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
inline int pollOnce(int timeoutMillis) {
return pollOnce(timeoutMillis, nullptr, nullptr, nullptr);
}
/system/core/libutils/Looper.cpp
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
int result = 0;
for (;;) {
while (mResponseIndex < mResponses.size()) {
。。
result = pollInner(timeoutMillis);
}
}
==========
int Looper::pollInner(int timeoutMillis) {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
#endif
。。。。。。。。
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
// 线程阻塞
int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Look at the flow of sending messages:
template <typename F, typename T>
inline std::future<T> SurfaceFlinger::schedule(F&& f) {
// a. 先调用 makeTask 创建task
auto [task, future] = makeTask(std::move(f));
// b. 将task 发到消息队列中
mEventQueue->postMessage(std::move(task));
// 返回future,可以通过 future.get() 获取异步处理回来的结果
return std::move(future);
}
For example, call the following method to set the frame rate asynchronously:
status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
int8_t compatibility, int8_t changeFrameRateStrategy) {
if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
"SurfaceFlinger::setFrameRate")) {
return BAD_VALUE;
}
// schedule 方法
static_cast<void>(schedule([=] {
Mutex::Autolock lock(mStateLock);
if (authenticateSurfaceTextureLocked(surface)) {
sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
if (layer == nullptr) {
ALOGE("Attempt to set frame rate on a layer that no longer exists");
return BAD_VALUE;
}
const auto strategy =
Layer::FrameRate::convertChangeFrameRateStrategy(changeFrameRateStrategy);
if (layer->setFrameRate(
Layer::FrameRate(Fps{frameRate},
Layer::FrameRate::convertCompatibility(compatibility),
strategy))) {
setTransactionFlags(eTraversalNeeded);
}
} else {
ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
return BAD_VALUE;
}
return NO_ERROR;
}));
return NO_ERROR;
}
// a. First call makeTask to create a task
auto [task, future] = makeTask(std::move(f));
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.h
The role of std::packaged_task is to provide a data synchronization mechanism between different threads. It can store a function operation and pass its return value to the corresponding future, and this future can also be safely accessed in another thread. this value
vtemplate <typename F>
// 继承了 MessageHandler
class Task : public MessageHandler {
template <typename G>
friend auto makeTask(G&&);
explicit Task(F&& f) : mTask(std::move(f)) {}
// 执行 handleMessage 消息,则执行 mTask 方法;mTask 就是 f 方法
void handleMessage(const Message&) override { mTask(); }
using T = std::invoke_result_t<F>;
std::packaged_task<T()> mTask;
};
template <typename F>
inline auto makeTask(F&& f) {
sp<Task<F>> task = new Task<F>(std::move(f));
return std::make_pair(task, task->mTask.get_future());
}
So, if the handleMessage method of Task is called, the callback method f is executed
// b. Send the task to the message queue
mEventQueue->postMessage(std::move(task));
Put the task into the message queue, task->mTask can get the corresponding incoming function f
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp
// Task 的父类是 MessageHandler
void MessageQueue::postMessage(sp<MessageHandler>&& handler) {
// 传入 Task 和 Message 对象
mLooper->sendMessage(handler, Message());
}
The Message object is defined in the Looper header file
/system/core/libutils/include/utils/Looper.h
Initialize Message, where what is 0
* A message that can be posted to a Looper.
*/
struct Message {
Message() : what(0) { }
Message(int w) : what(w) { }
/* The message type. (interpretation is left up to the handler) */
int what;
};
/system/core/libutils/Looper.cpp
Vector<MessageEnvelope> mMessageEnvelopes is a dynamic array, save it to the array
void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
sendMessageAtTime(now, handler, message);
}
===============
// 其中 mMessageEnvelopes 是个动态数组
Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
const Message& message) {
#if DEBUG_CALLBACKS
ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
this, uptime, handler.get(), message.what);
#endif
size_t i = 0;
{ // acquire lock
AutoMutex _l(mLock);
size_t messageCount = mMessageEnvelopes.size();
// 如果当前时间 uptime 有延时处理,则遍历所有的消息执行时间,插入到数组中
while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
i += 1;
}
// MessageEnvelope 包装 handler, message
MessageEnvelope messageEnvelope(uptime, handler, message);
// 插入到数组中
mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
// Optimization: If the Looper is currently sending a message, then we can skip
// the call to wake() because the next thing the Looper will do after processing
// messages is to decide when the next wakeup time should be. In fact, it does
// not even matter whether this code is running on the Looper thread.
if (mSendingMessage) {
return;
}
} // release lock
// Wake the poll loop only when we enqueue a new message at the head.
// 如果需要立即执行,则唤醒阻塞的线程
if (i == 0) {
wake();
}
}
wake wakes up a blocked thread
void Looper::wake() {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ wake", this);
#endif
uint64_t inc = 1;
// 写入到 mWakeEventFd 文件描述符,可以执行了
ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
if (nWrite != sizeof(uint64_t)) {
if (errno != EAGAIN) {
LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
mWakeEventFd.get(), nWrite, strerror(errno));
}
}
}
The pollInner method in Looper continues to execute:
int Looper::pollInner(int timeoutMillis) {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
#endif
。。。
for (int i = 0; i < eventCount; i++) {
int fd = eventItems[i].data.fd;
uint32_t epollEvents = eventItems[i].events;
if (fd == mWakeEventFd.get()) {
if (epollEvents & EPOLLIN) {
// 读取对应的文件描述符
awoken();
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
}
v。。。
// Invoke pending message callbacks.
mNextMessageUptime = LLONG_MAX;
while (mMessageEnvelopes.size() != 0) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
// 获取数组中的首个元素
const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
// 判断时间是否满足
if (messageEnvelope.uptime <= now) {
// Remove the envelope from the list.
// We keep a strong reference to the handler until the call to handleMessage
// finishes. Then we drop it so that the handler can be deleted *before*
// we reacquire our lock.
{ // obtain handler
// 获取 handler
sp<MessageHandler> handler = messageEnvelope.handler;
Message message = messageEnvelope.message;
// 移除这个消息 MessageEnvelopes
mMessageEnvelopes.removeAt(0);
mSendingMessage = true;
mLock.unlock();
#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
this, handler.get(), message.what);
#endif
// 调用 handleMessage 方法
handler->handleMessage(message);
} // release handler
Call the handleMessage method
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.h
template <typename F>
class Task : public MessageHandler {
template <typename G>
friend auto makeTask(G&&);
explicit Task(F&& f) : mTask(std::move(f)) {}
// 回调函数的方法
void handleMessage(const Message&) override { mTask(); }
Using the new special type of C++ to abstract and encapsulate, the essence is to send a Message to the main thread and specify its MessageHandler, so in fact, it is still carried out in the main thread of SurfaceFlinger
2. The application communicates with surfaceFlinger
Each application process will create an interface to communicate with the SurfaceFlinger process binder, as follows:
When creating an application, there is the following process:
/frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java
In WMS, each Window corresponds to a WindowState, indicating specific window information
1374 public int addWindow(Session session, IWindow client, int seq,
1375 LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame,
1376 Rect outContentInsets, Rect outStableInsets,
1377 DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel,
1378 InsetsState outInsetsState, InsetsSourceControl[] outActiveControls,
1379 int requestUserId) {
1380 Arrays.fill(outActiveControls, null);
。。。
// 创建了 WindowState 对象
1555 final WindowState win = new WindowState(this, session, client, token, parentWindow,
1556 appOp[0], seq, attrs, viewVisibility, session.mUid, userId,
1557 session.mCanAddInternalSystemWindow);
// 调用 WindowState 对象的 attach 方法
1634 win.attach();
Call the attach method of the WindowState object
/frameworks/base/services/core/java/com/android/server/wm/WindowState.java
273 final Session mSession;
962 void attach() {
963 if (DEBUG) Slog.v(TAG, "Attaching " + this + " token=" + mToken);
964 mSession.windowAddedLocked(mAttrs.packageName);
965 }
windowAddedLocked
/frameworks/base/services/core/java/com/android/server/wm/Session.java
512 void windowAddedLocked(String packageName) {
513 mPackageName = packageName;
514 mRelayoutTag = "relayoutWindow: " + mPackageName;
515 if (mSurfaceSession == null) {
516 if (DEBUG) {
517 Slog.v(TAG_WM, "First window added to " + this + ", creating SurfaceSession");
518 }
// 创建 SurfaceSession 对象
519 mSurfaceSession = new SurfaceSession();
520 ProtoLog.i(WM_SHOW_TRANSACTIONS, " NEW SURFACE SESSION %s", mSurfaceSession);
521 mService.mSessions.add(this);
522 if (mLastReportedAnimatorScale != mService.getCurrentAnimatorScale()) {
523 mService.dispatchNewAnimatorScaleLocked(this);
524 }
525 }
526 mNumWindow++;
527 }
Create a SurfaceSession object
/frameworks/base/core/java/android/view/SurfaceSession.java
30 private long mNativeClient; // SurfaceComposerClient*
31
32 private static native long nativeCreate();
33 private static native void nativeDestroy(long ptr);
34 private static native void nativeKill(long ptr);
35
36 /** Create a new connection with the surface flinger. */
37 @UnsupportedAppUsage
38 public SurfaceSession() {
// native 层去创建
39 mNativeClient = nativeCreate();
40 }
nativeCreate method
/frameworks/base/core/jni/android_view_SurfaceSession.cpp
static const JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "nativeCreate", "()J",
(void*)nativeCreate },
。。。
static jlong nativeCreate(JNIEnv* env, jclass clazz) {
// 创建 SurfaceComposerClient 对象
SurfaceComposerClient* client = new SurfaceComposerClient();
client->incStrong((void*)nativeCreate);
return reinterpret_cast<jlong>(client);
}
Create a SurfaceComposerClient object
/frameworks/native/libs/gui/SurfaceComposerClient.cpp
SurfaceComposerClient::SurfaceComposerClient()
: mStatus(NO_INIT)
{
}
--------
// 由于 SurfaceComposerClient 继承了 RefBase ,所以初始化会调用 onFirstRef 方法
void SurfaceComposerClient::onFirstRef() {
sp<ISurfaceComposer> sf(ComposerService::getComposerService());
if (sf != nullptr && mStatus == NO_INIT) {
sp<ISurfaceComposerClient> conn;
conn = sf->createConnection();
if (conn != nullptr) {
mClient = conn;
mStatus = NO_ERROR;
}
}
}
The value of sf gets the service through ComposerService:
41 class ComposerService : public Singleton<ComposerService>
42 {
43 sp<ISurfaceComposer> mComposerService;
=============
/*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() {
// ComposerService 继承了 Singleton 是单例模式,调用构造函数去:connectLocked
ComposerService& instance = ComposerService::getInstance();
Mutex::Autolock _l(instance.mLock);
if (instance.mComposerService == nullptr) {
ComposerService::getInstance().connectLocked();
assert(instance.mComposerService != nullptr);
ALOGD("ComposerService reconnected");
}
// 返回对象的 mComposerService 成员
return instance.mComposerService;
}
------
void ComposerService::connectLocked() {
const String16 name("SurfaceFlinger");
// ServiceManager 去获取到 "SurfaceFlinger" 服务,赋值给 mComposerService
while (getService(name, &mComposerService) != NO_ERROR) {
usleep(250000);
}
assert(mComposerService != nullptr);
Then call: sf->createConnection, sf is sp<ISurfaceComposer> mComposerService
According to the binder communication principle, BpSurfaceComposer is the client to call the method of the server
/frameworks/native/libs/gui/include/gui/ISurfaceComposer.h
class ISurfaceComposer: public IInterface {
public:
// 宏定义去展开一系列 的函数定义
DECLARE_META_INTERFACE(SurfaceComposer)
// createConnection 方法
* Create a connection with SurfaceFlinger.
*/
virtual sp<ISurfaceComposerClient> createConnection() = 0;
// Out-of-line virtual method definition to trigger vtable emission in this
// translation unit (see clang warning -Wweak-vtables)
BpSurfaceComposer::~BpSurfaceComposer() {}
// 并且,调用了下列的宏定义
IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer");
DECLARE_META_INTERFACE(SurfaceComposer) macro definition to expand a series of function definitions
/frameworks/native/libs/binder/include/binder/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); \
。。。。
#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; \
} \
// asInterface 的方法实现。I##INTERFACE 为:ISurfaceComposer
::android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const ::android::sp<::android::IBinder>& obj) \
{ \
::android::sp<I##INTERFACE> intr; \
if (obj != nullptr) { \
intr = static_cast<I##INTERFACE*>( \
obj->queryLocalInterface( \
I##INTERFACE::descriptor).get()); \
if (intr == nullptr) { \
// 创建 BpSurfaceComposer 对象,并返回
intr = new Bp##INTERFACE(obj); \
} \
} \
return intr; \
} \
std::unique_ptr<I##INTERFACE> I##INTERFACE::default_impl; \
Create a BpSurfaceComposer object and call the createConnection method
/frameworks/native/libs/gui/ISurfaceComposer.cpp
class BpSurfaceComposer : public BpInterface<ISurfaceComposer>
{
public:
explicit BpSurfaceComposer(const sp<IBinder>& impl)
: BpInterface<ISurfaceComposer>(impl)
{
}
virtual ~BpSurfaceComposer();
virtual sp<ISurfaceComposerClient> createConnection()
{
Parcel data, reply;
data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
// binder 通信
remote()->transact(BnSurfaceComposer::CREATE_CONNECTION, data, &reply);
// reply 为对端回复的消息
return interface_cast<ISurfaceComposerClient>(reply.readStrongBinder());
}
remote()->transact(BnSurfaceComposer::CREATE_CONNECTION
BnSurfaceComposer and BpSurfaceComposer are generally in the same file
// ----------------------------------------------------------------------
status_t BnSurfaceComposer::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
// 回调onTransact 方法
case CREATE_CONNECTION: {
CHECK_INTERFACE(ISurfaceComposer, data, reply);
// 调用其子类的 createConnection 方法
sp<IBinder> b = IInterface::asBinder(createConnection());
reply->writeStrongBinder(b);
return NO_ERROR;
}
Let's see who inherits BnSurfaceComposer
/frameworks/native/services/surfaceflinger/SurfaceFlinger.h
class SurfaceFlinger : public BnSurfaceComposer,
public PriorityDumper,
public ClientCache::ErasedRecipient,
private IBinder::DeathRecipient,
private HWC2::ComposerCallback,
private ISchedulerCallback {
SurfaceFlinger inherits BnSurfaceComposer, SurfaceFlinger overrides the onTransact method
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
uint32_t flags) {
status_t credentialCheck = CheckTransactCodeCredentials(code);
if (credentialCheck != OK) {
return credentialCheck;
}
// 再次调用父类的方法 onTransact
status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
CHECK_INTERFACE(ISurfaceComposer, data, reply);
createConnection method
sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
// 这里创建了一个客户端 Client作为中介,传入了this 指针
const sp<Client> client = new Client(this);
return client->initCheck() == NO_ERROR ? client : nullptr;
}
The client object is as follows:
/frameworks/native/services/surfaceflinger/Client.h
class Client : public BnSurfaceComposerClient
{
public:
explicit Client(const sp<SurfaceFlinger>& flinger);
/frameworks/native/services/surfaceflinger/Client.cpp
45 status_t Client::initCheck() const {
46 return NO_ERROR;
47 }
In summary, the timing diagram is as follows:
- Binder RPC architecture of SurfaceFlinger system service
As a typical Binder system service, SurfaceFlinger follows the general principles of Binder service design:
Interface接口:ISurfaceComposer 、ISurfaceComposerClient
Bp client: BpSurfaceComposer, BpSurfaceComposerClient
Bn server: BnSurfaceComposer, BnSurfaceComposerClient
Service implementation: SurfaceFlinger, Client