Android Binder 服务端分析

本文深入剖析Android Binder机制,从startThreadPool和joinRpcThreadpool开始,逐步解析IPCThreadState的joinThreadPool、getAndExecuteCommand及executeCommand等关键函数,揭示Binder驱动如何处理服务间的通信。特别地,详细阐述了服务注册时writeStrongBinder的过程,解释了tr.cookie的含义及其在服务通信中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇文章以这篇为锚点Android Binder 应用程序Binder 启动源码分析_we1less的博客-优快云博客

startThreadPool  joinRpcThreadpool开始进行分析

void joinRpcThreadpool() {
    // TODO(b/32756130) this should be transport-dependent
    joinBinderRpcThreadpool();
}

void joinBinderRpcThreadpool() {
    IPCThreadState::self()->joinThreadPool();
}

joinThreadPool

        路径  frameworks/native/libs/binder/IPCThreadState.cpp

        循环执行getAndExecuteCommand

void                joinThreadPool(bool isMain = true);

void IPCThreadState::joinThreadPool(bool isMain)
{
    ...
    status_t result;
    do {
        processPendingDerefs();
        // now get the next command to be processed, waiting if necessary
        result = getAndExecuteCommand();

        ...
    } while (result != -ECONNREFUSED && result != -EBADF);

    ...
    talkWithDriver(false);
}

getAndExecuteCommand

        路径  frameworks/native/libs/binder/IPCThreadState.cpp

        这个函数的意思就是 循环执行从binder驱动获取接收到的命令再调用executeCommand执行

status_t IPCThreadState::getAndExecuteCommand()
{
    status_t result;
    int32_t cmd;

    result = talkWithDriver();
    if (result >= NO_ERROR) {
        size_t IN = mIn.dataAvail();
        if (IN < sizeof(int32_t)) return result;
        cmd = mIn.readInt32();
        ...
        result = executeCommand(cmd);
       ...
    }
    return result;
}

executeCommand

        路径  frameworks/native/libs/binder/IPCThreadState.cpp

        将tr.cookie强转为BBinder再调用BBindertransact方法

status_t IPCThreadState::executeCommand(int32_t cmd)
{
    BBinder* obj;
    RefBase::weakref_type* refs;
    status_t result = NO_ERROR;

    switch ((uint32_t)cmd) {
    ...
    case BR_TRANSACTION:
        {
            binder_transaction_data tr;
            result = mIn.read(&tr, sizeof(tr));
            ...
            if (tr.target.ptr) {
                if (reinterpret_cast<RefBase::weakref_type*>(
                    error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
                            &reply, tr.flags);
                } else {
                    error = UNKNOWN_TRANSACTION;
                }
            ...
        }
        break;

    ...
    return result;
}

transact

        路径  frameworks/native/libs/binder/Binder.cpp           

        直接调用onTransact方法  在这里可以直接看做调用到了service重写的onTransact方法

status_t BBinder::transact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    data.setDataPosition(0);

    status_t err = NO_ERROR;
    switch (code) {
        case PING_TRANSACTION:
            reply->writeInt32(pingBinder());
            break;
        default:
            err = onTransact(code, data, reply, flags);
            break;
    }

    if (reply != NULL) {
        reply->setDataPosition(0);
    }

    return err;
}

tr.cookie是什么

这里面的tr.cookie猜想肯定是Service继承BBinder对象的类。
那么首先得回到最开始ServiceManager的addService:

addService

        路径  frameworks/native/libs/binder/IServiceManager.cpp        

        主要是调用了ParcelwriteStrongBinder

virtual status_t addService(const String16& name, const sp<IBinder>& service,
            bool allowIsolated)
    {
        Parcel data, reply;
        data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
        data.writeString16(name);
        data.writeStrongBinder(service);
        data.writeInt32(allowIsolated ? 1 : 0);
        status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
        return err == NO_ERROR ? reply.readExceptionCode() : err;
    }

writeStrongBinder

        路径  frameworks/native/libs/binder/Parcel.cpp 

status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
    return flatten_binder(ProcessState::self(), val, this);
}

flatten_binder 

         路径  frameworks/native/libs/binder/Parcel.cpp 

        这里面就存在了obj.cookie

        可见tr.cookie就是当前service的弱引用指针

        IBinder *local = binder->localBinder(); 

status_t flatten_binder(const sp<ProcessState>& /*proc*/,
    const sp<IBinder>& binder, Parcel* out)
{
    flat_binder_object obj;
    ...
    if (binder != NULL) {
        IBinder *local = binder->localBinder();
        if (!local) {
            ...
        } else {
            obj.type = BINDER_TYPE_BINDER;
            obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
            obj.cookie = reinterpret_cast<uintptr_t>(local);
        }
    }...

    return finish_flatten_binder(binder, obj, out);
}

binder->localBinder();  

        路径  frameworks/native/libs/binder/Binder.cpp

BBinder* BBinder::localBinder()
{
    return this;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值