Android Binder 初步分析之一

前言:

在看Android Binder 代码分析 addService() 时,看到 remote()->transact(),网上博客讲最终到了 BpBinder中,即 BpRefBase 中的mRemote 指针 指向了 BpBinder。

那 BpRefBase mRemote 指针究竟如何指向 BpBinder ?本文将进行粗略分析。

Service 注册流程

以 MediaPlayerService 为例分析

frameworks/av/media/mediaserver/main_mediaserver.cpp
  int main(int argc __unused, char **argv __unused)
  {
    sp<ProcessState> proc(ProcessState::self());
    sp<IServiceManager> sm(defaultServiceManager());
    MediaPlayerService::instantiate();
    ResourceManagerService::instantiate();
    
    registerExtensions();
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
  }

frameworks/av/media/libmediaplayerservice/MediaPlayerService.cpp 
  void MediaPlayerService::instantiate() {
    defaultServiceManager()->addService(
            String16("media.player"), new MediaPlayerService());
  }

核心方法 defaultServiceManager()->addService(String16("media.player"), new MediaPlayerService());

addService() 分析

1. addService()
frameworks/native/include/binder/IServiceManager.h
class IServiceManager : public IInterface
{
    // 参数 3 和参数 4 有默认值
    virtual status_t addService(const String16& name, const sp<IBinder>& service,
                                bool allowIsolated = false,
                                int dumpsysFlags = DUMP_FLAG_PRIORITY_DEFAULT) = 0;
}

frameworks/native/libs/binder/IServiceManager.cpp
  virtual status_t addService(const String16& name, const sp<IBinder>& service,
                                bool allowIsolated, int dumpsysPriority) {
	Parcel data, reply;
	data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
	data.writeString16(name);
	data.writeStrongBinder(service);
	data.writeInt32(allowIsolated ? 1 : 0);
	data.writeInt32(dumpsysPriority);
	status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
	return err == NO_ERROR ? reply.readExceptionCode() : err;
  }
  
  // inline  IBinder*        remote()                { return mRemote; }
  // IBinder* const          mRemote; 而 mRemote 实际指向 BpBinder,具体分析如下
2. transact()
frameworks/native/libs/binder/BpBinder.cpp
  status_t BpBinder::transact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
  {
    status_t status = IPCThreadState::self()->transact(
            mHandle, code, data, reply, flags);
  }
 
framewroks/native/libs/binder/IPCThreadState.cpp
  status_t IPCThreadState::transact(int32_t handle,
                                  uint32_t code, const Parcel& data,
                                  Parcel* reply, uint32_t flags)
  {
    err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
    
    if ((flags & TF_ONE_WAY) == 0) {
      if (reply) {
        err = waitForResponse(reply);
      } else {
        Parcel fakeReply;
        err = waitForResponse(&fakeReply);
      }
    }else {
        err = waitForResponse(NULL, NULL);
    }
    return err;
  }
3. defaultServiceManager() 流程,即 mRemote 为何指向 BpBinder 流程分析
frameworks/native/libs/binder/IServiceManager.cpp
  sp<IServiceManager> defaultServiceManager() {
    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
    
    //重要,interface_cast<IServiceManager>(obj)是关键
    gDefaultServiceManager = interface_cast<IServiceManager>(
        ProcessState::self()->getContextObject(NULL));
    return gDefaultServiceManager
  }
  
  sp<ProcessState> ProcessState::self() {
    if (gProcess != NULL) {
        return gProcess;
    }
    gProcess = new ProcessState("/dev/binder");
    return gProcess;
  }
  
  sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/) {
    return getStrongProxyForHandle(0);
  }
  
  //返回值为 BpBinder(handle, trackedUid)
  sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle){
    sp<IBinder> result;
    handle_entry* e = lookupHandleLocked(handle);
    if (e != NULL) {
      IBinder* b = e->binder;
      if (b == NULL || !e->refs->attemptIncWeak(this)) {
        //这里b 指向 BpBinder
        b = BpBinder::create(handle);
        e->binder = b;
        if (b) e->refs = b->getWeakRefs();
        result = b;
      }
    }
    //所以返回的是 BpBinder
    return result;
  }
  BpBinder* BpBinder::create(int32_t handle) {
    return new BpBinder(handle, trackedUid);
  }

frameworks/native/libs/binder/ProcessState.cpp
// 把 handle 保存到 mHandleToObject 矢量数组中
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
{
  const size_t N=mHandleToObject.size();
  if (N <= (size_t)handle) {
      handle_entry e;
      e.binder = NULL;
      e.refs = NULL;
      status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
      if (err < NO_ERROR) return NULL;
  }
  return &mHandleToObject.editItemAt(handle);
}

所以 gDefaultServiceManager = interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));  实际为 gDefaultServiceManager = interface_cast<IServiceManager>(new BpBinder(0,trackedUid)); 

4. interface_cast
frameworks/native/libs/binder/include/binder/IInterface.h
  // 根据上面分析 obj 实际为 BpBinder
  template<typename INTERFACE>
  inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj) {
    return INTERFACE::asInterface(obj);
  }
5. asInterface 接口,通过 IMPLEMENT_META_INTERFACE 实现
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
    const ::android::String16 I##INTERFACE::descriptor(NAME);           \
    const ::android::String16&                                          \
            I##INTERFACE::getInterfaceDescriptor() const {              \
        return I##INTERFACE::descriptor;                                \
    }                                                                   \
    // 根据上面分析 obj 实际为 BpBinder                                    \
    ::android::sp<I##INTERFACE> I##INTERFACE::asInterface(              \
            const ::android::sp<::android::IBinder>& obj)               \
    {                                                                   \
        ::android::sp<I##INTERFACE> intr;                               \
        if (obj != NULL) {                                              \
            intr = static_cast<I##INTERFACE*>(                          \
                obj->queryLocalInterface(                               \
                        I##INTERFACE::descriptor).get());               \
            if (intr == NULL)   {                                       \
  //重要,以INTERFACE 为 ServiceManager为例,此处 new BpServiceManager(obj);\
                intr = new Bp##INTERFACE(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \
    I##INTERFACE::I##INTERFACE() { }                                    \
    I##INTERFACE::~I##INTERFACE() { }                                   \

这里 sp<IServiceManager> IServiceManager::asInterface(
  const ::android::sp<::android::IBinder>& obj) {
    new ServiceManager(obj)
  }
6. IMPLEMENT_META_INTERFACE 具体使用地方
frameworks/native/libs/binder/IServiceManager.cpp
  IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");

7. addService()
frameworks/native/libs/binder/IServiceManager.cpp
  class BpServiceManager : public BpInterface<IServiceManager>{
  public:
    explicit BpServiceManager(const sp<IBinder>& impl)
        : BpInterface<IServiceManager>(impl)
    {}

    virtual status_t addService() {
      status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply)
    }
  }
8. BpInterface 构造方法
frameworks/native/libs/binder/include/binder/IInterface.h
  template<typename INTERFACE>
  inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
    : BpRefBase(remote)
  {}

  template<typename INTERFACE>
  class BpInterface : public INTERFACE, public BpRefBase
  {
  public:
    explicit                    BpInterface(const sp<IBinder>& remote);
  protected:
    virtual IBinder*            onAsBinder();
  };
9. BpInterface继承于 BpRefBase,先构造 BpRefBase
frameworks/native/libs/binder/include/binder/Binder.h
  class BpRefBase : public virtual RefBase {
  public:
    inline  IBinder*        remote()                { return mRemote; }
  private:
    IBinder* const          mRemote;
  }

frameworks/native/libs/binder/Binder.cpp
  BpRefBase::BpRefBase(const sp<IBinder>& o)
    : mRemote(o.get()), mRefs(NULL), mState(0)
  {}

BpInterface和BnInterface

BnInterface 和 BpInterface 都是类模板,根据参数 INTERFACE 的不同进行变化,继承于不同的Ixxx 类,下面以 MediaPlayerService 为例说明

frameworks/native/libs/binder/include/binder/IInterface.h
template<typename INTERFACE>
class BnInterface : public INTERFACE, public BBinder
{
public:
    virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
    virtual const String16&     getInterfaceDescriptor() const;

protected:
    virtual IBinder*            onAsBinder();
};

template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
    explicit                    BpInterface(const sp<IBinder>& remote);

protected:
    virtual IBinder*            onAsBinder();
};

frameworks/av/media/libmedia/IMediaPlayerService.cpp
class BpMediaPlayerService: public BpInterface<IMediaPlayerService>
{
  public:
    explicit BpMediaPlayerService(const sp<IBinder>& impl)
        : BpInterface<IMediaPlayerService>(impl)
    {
    }
}

这里展开即为
class BpInterface : public IMediaPlayerService, public BpRefBase
{
public:
    explicit                    BpInterface(const sp<IBinder>& remote);

protected:
    virtual IBinder*            onAsBinder();
};


frameworks/av/media/libmedia/include/media/IMediaPlayerService.h
class BnMediaPlayerService: public BnInterface<IMediaPlayerService>
{
public:
    virtual status_t    onTransact( uint32_t code,
                                    const Parcel& data,
                                    Parcel* reply,
                                    uint32_t flags = 0);
};

这里展开为
class BnInterface : public IMediaPlayerService, public BBinder
{
public:
    virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
    virtual const String16&     getInterfaceDescriptor() const;

protected:
    virtual IBinder*            onAsBinder();
};

所以 BnMediaPlayerService 继承于 BnInterface,继承于 IMediaPlayerService

BpMediaPlayerService 继承于 BpInterface,继承于 IMediaPlayerService。

下面图片来自 Android Binder框架实现之Binder相关的接口和类_IT先森-CSDN博客_binder类

参考链接

Android Binder框架实现之defaultServiceManager()的实现_IT先森-CSDN博客

Android Binder框架实现之Native层addService详解之请求的发送_IT先森-CSDN博客

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值