【安卓源码】SurfaceFlinger 启动及其与应用通信

1. surfaceFlinger 初始化和消息队列处理机制

surfaceflinger 的makefile 文件

/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 

init进程就可以解析 "surfaceflinger.rc" ,启动 SurfaceFlinger 服务进程,执行 main 方法,启动surfaceflinger 进程:

 /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;
}

基本操作如下: 

  1. 创建SurfaceFlinger对象,触发执行 SurfaceFlinger::onFirstRef()
  2. 调用SurfaceFlinger::init()进行初始化
  3. 注册服务到ServiceManager(名字是"SurfaceFlinger")
  4. 调用SurfaceFlinger::run()

1). 创建 surfaceflinger 对象

surfaceflinger::createSurfaceFlinger()

调用的是 SurfaceFlingerFactory 头文件

#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);

创建了消息队列 mFactory.createMessageQueue

/frameworks/native/services/surfaceflinger/SurfaceFlingerDefaultFactory.h

DefaultFactory 头文件 

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>();
}

创建独占智能指针 MessageQueue

代码路径为如下:

/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp

2). 初始化 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)

方法解析

/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);
}

创建 HWComposer 对象

/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 为:Composer 对象,composerServiceName 传入的参数为:"default"

/frameworks/native/services/surfaceflinger/DisplayHardware/ComposerHal.cpp

Composer 相当于获取hal 层服务的接口

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). 调用 surfaceflinger 的run 方法,开启消息队列机制

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);
}

调用 Looper 的头文件为如下:

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);

看下发送消息的流程:

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);
}

比如调用下列的设置帧率的方法,异步调用:

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. 先调用 makeTask 创建task
    auto [task, future] = makeTask(std::move(f));

/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.h

std::packaged_task的作用就是提供一个不同线程之间的数据同步机制,它可以存储一个函数操作,并将其返回值传递给对应的future, 而这个future在另外一个线程中也可以安全的访问到这个值 

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());
}

所以,如果调用Task 的 handleMessage 方法,则执行了回调的方法 f


// b. 将task 发到消息队列中
    mEventQueue->postMessage(std::move(task));

将 task 放入到消息队列中,task->mTask 可以获取到对应传入的函数 f

/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp

// Task 的父类是 MessageHandler
void MessageQueue::postMessage(sp<MessageHandler>&& handler) {

// 传入 Task 和 Message 对象
    mLooper->sendMessage(handler, Message());
}

Message 对象在  Looper 头文件有定义

/system/core/libutils/include/utils/Looper.h

初始化 Message,其中 what 为 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 是个动态数组,将其保存到数组中


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 唤醒阻塞的线程

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));
        }
    }
}

Looper 中的 pollInner 方法,继续往下执行:

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

调用 handleMessage 方法

/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(); }

利用C++的新特型做了抽象与封装,本质还是向主线程发送一个Message并指定其MessageHandler,所以其实还是在 SurfaceFlinger 的主线程中进行

2. 应用与 surfaceFlinger 通信

每个应用进程均会创建一个与 SurfaceFlinger 进程binder 通信的接口,为如下流程:

在创建应用的时候,有如下流程:

/frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

在WMS中,每一个Window都会对应一个WindowState,表示具体窗口信息

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();

调用 WindowState 对象的 attach 方法

/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      }

创建 SurfaceSession 对象

/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 方法

/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);
}

创建 SurfaceComposerClient 对象

/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;
        }
    }
}

sf 的值通过 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);

接着调用:sf->createConnection,sf 为 sp<ISurfaceComposer> mComposerService

根据binder 通信原理,BpSurfaceComposer 为客户端,去调用服务器端的方法

/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)  宏定义去展开一系列 的函数定义

/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;           \

创建 BpSurfaceComposer 对象,调用 createConnection 方法

 /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 和 BpSurfaceComposer 一般情况下均是在同一个文件中

// ----------------------------------------------------------------------

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;
        }

看下谁继承了 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 继承了 BnSurfaceComposer,SurfaceFlinger 重写了 onTransact 方法

/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 方法


sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {

// 这里创建了一个客户端 Client作为中介,传入了this 指针
    const sp<Client> client = new Client(this);
    return client->initCheck() == NO_ERROR ? client : nullptr;
}

client  对象为如下:

/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  }

总结,时序图为如下:

  • SurfaceFlinger系统服务的Binder RPC架构

SurfaceFlinger作为典型的Binder系统服务,遵循Binder服务设计的一般原则:

Interface接口:ISurfaceComposer 、ISurfaceComposerClient

Bp客户端:BpSurfaceComposer、BpSurfaceComposerClient

Bn服务端:BnSurfaceComposer、BnSurfaceComposerClient

服务实现:SurfaceFlinger、Client

猜你喜欢

转载自blog.csdn.net/qq_40587575/article/details/129657882