binder驱动之我见

                            Binder驱动之我见

一.介绍接种常见的跨进程通信机制

1.       共享内存(share memory)

2.       socket

3.       命名管道(named pipe)

4.       消息队列(message queue)

5.       binder

(查看这几种之间的特性与联系)

二.binder的特性

三.Binder的设计原理

四.Binder的设计实现

五.Binder的设计总结

sensorservice服务为例来进行简要介绍。

首先介绍其大致流程:

  1. system_init.cppsystem_init函数中首先实例化一个ProcessState
  2. 然后获取服务管理的实例defaultServiceManager
  3. 每个服务进程都会实例化ProcessState类,此类是单例模型的
  4. 调用对外的构造接口ProcessState::self
  5. 如果类实例为NULL,调用ProcessState构造一个类对象
  6. 构造函数中主要调用open_driver()函数打开binder的设备文件,获得设备文件的句柄,调用mmap()函数将设备文件映射到进程的地址空间,实现对此地址空间的操作直接反应到设备文件上
  7. 服务进程的构造函数实例化一个BinderService类,将此服务注册进servicemanager服务管理程序
  8. 当一系列的初始化结束后,调用开始服务的封闭的轮询
  9. 函数ProcessState::self()->startThreadPool();开启进程的线程池
  10. IPCThreadState::self()->joinThreadPool();创建一个新的线程加入线程池开始对设备请求进行轮询

将封闭的循环结构建立起来后,就开始服务的最核心的操作了,开始通过binder驱动与客户端进行交互了。

  1. 首先进入joinThreadPool()函数
  2. 通过轮询抵用函数talkWithDriver与设备文件进行交互
  3. 调用executeCommand()函数执行相关操作

 

下面来分析binder驱动的服务与客户端实现原理

主要涉及的类:

1.       refbase 

功能:引用计数,用于实现垃圾回收

2.       Parcel

功能:定义了binder IPC通信传输数据的格式

3.       IInterface

功能:为一个抽象类,用于服务继承,定义属于自己的属性接口

与之相关联的模版类:BnInterfaceBpInterface用对应服务的接口来实例化

4.       IBinder, BBinderBpBinderBpRefBase

功能:IBinder是模型的基类

      BBinder代表服务的基类

      BpBinder代表客户端的基类

      BpRefBase记录对服务的引用(猜测是用于控制服务的生命周期)

5.       ProcessState

功能:记录服务进程相关的信息

6.       IPCThreadState

功能:一个线程类,用于与设备文件进行信息交互

几种类之间的关系如下:

下面开始分析这几个类:

/*

**此类是所有服务都需要继承的接口基类。服务继承它实现数据自己的属性接口。

**提供了几个公共的接口。

**sp<IBinder>         asBinder();

**sp<const IBinder>   asBinder() const;

**这两个接口最终都是调用虚函数virtual IBinder*  onAsBinder() = 0;

**此函数设置成虚函数,可供派生类来重新实现。

*/

 

class IInterface : public virtual RefBase

{

public:

            IInterface();

            sp<IBinder>         asBinder();

            sp<const IBinder>   asBinder() const;

           

protected:

    virtual                     ~IInterface();

    virtual IBinder*            onAsBinder() = 0;

};

下面来看两个重要的模版类

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

/*

**此模版类用于BINDER C/S模型的服务端的基类。

**此基类公有继承了INTERFACE类和BBinder

**此处用来实例化的INTERFACE类都是服务对应的接口类

*/

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>

inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(

        const String16& _descriptor)

{

    if (_descriptor == INTERFACE::descriptor) return this;

    return NULL;

}

 

/*

**此虚函数的模版类是获取对应接口的描述符

**此函数的实现形式是内联函数

*/

template<typename INTERFACE>

inline const String16& BnInterface<INTERFACE>::getInterfaceDescriptor() const

{

    return INTERFACE::getInterfaceDescriptor();

}

/*

**获取接口的对象

*/

template<typename INTERFACE>

IBinder* BnInterface<INTERFACE>::onAsBinder()

{

    return this;

}

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

/*

**此模版类用于BINDER C/S模型的客户端的基类。

**此基类公有继承了INTERFACE类和BpRefBase

**此处用来实例化的INTERFACE类都是服务对应的接口类

**BpRefBase类用于统筹管理服务被引用的次数,控制服务的生命周期

*/

template<typename INTERFACE>

class BpInterface : public INTERFACE, public BpRefBase

{

public:

                            BpInterface(const sp<IBinder>& remote);

 

protected:

    virtual IBinder*            onAsBinder();

};

 

/*

**此内联接口函数就是调用基类BpRefBase的构造函数

*/

template<typename INTERFACE>

inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)

    : BpRefBase(remote)

{

}

 

/*

**此内联函数返回一个Ibinder类型的类对象指针

*/

template<typename INTERFACE>

inline IBinder* BpInterface<INTERFACE>::onAsBinder()

{

    return remote();

}

 

下面的两个宏是在定义服务接口的时候定义和实现的。是用于C/S模型中的客户端侧的。

所有的服务都要定义此类型的接口

/*

**1.定义描述符变量

**2.定义接口asInterface()

**3.实现虚函数getInterfaceDescriptor()

**4.定义对应的构造函数和析构函数

*/

#define DECLARE_META_INTERFACE(INTERFACE)                               \

    static const android::String16 descriptor;                          \

    static android::sp<I##INTERFACE> asInterface(                       \

            const android::sp<android::IBinder>& obj);                  \

    virtual const android::String16& getInterfaceDescriptor() const;    \

    I##INTERFACE();                                                     \

    virtual ~I##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;                                \

}                

                                                 \

//返回当前接口描述符的对象

//1.首先查询本地接口的对象

//2.如果不是本地接口描述符,则创建对应的远程接口对象

    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) {                                         \

                intr = new Bp##INTERFACE(obj);                          \

            }                                                           \

        }                                                               \

        return intr;                                                    \

    }                                                                   \

    I##INTERFACE::I##INTERFACE() { }                                    \

I##INTERFACE::~I##INTERFACE() { }                                   \

 

template<typename INTERFACE>

inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)

{

    return INTERFACE::asInterface(obj);

}

这个本质上就是一个类型转换

调用它的时候就是返回此Ibinder对象,至于NEW Bpxxx不会走!此流程一定成功

一般情况下都是获取服务之后调用的,所有的服务对应服务管理程序而言都是客户端.但是服务本身继承的是BnInterface类。故返回的是此类型。

//通过interface_cast模版函数进行类型转换:

如果是服务调用服务管理程序,返回的是指向服务的binder对象,故

   if (obj != NULL) {                                              \

            intr = static_cast<I##INTERFACE*>(                          \

                obj->queryLocalInterface(                               \

                        I##INTERFACE::descriptor).get());               \

            直接转换成服务类型的对象返回。

否则则是一般的客户端调用服务的用法,则返回服务代理。

if (intr == NULL) {                                         \

                intr = new Bp##INTERFACE(obj); 

}

Java层与之相对应的是:举例实现:

    static public IActivityManager asInterface(IBinder obj) {

        if (obj == null) {

            return null;

        }

        IActivityManager in =

            (IActivityManager)obj.queryLocalInterface(descriptor);

        if (in != null) {

            return in;

        }

 

        return new ActivityManagerProxy(obj);

    }

综述来说下面的操作取决于存进来的Ibinder派生类继承的模版类是BnInterface还是BpInterface,也即此binder是远程代理对象,还是本地服务对象。

 

现在进入binder模型的几个核心的类

IBinder,BBinder,BpBinder

 

class IBinder : public virtual RefBase

{

public:

                          IBinder();

    virtual const String16& getInterfaceDescriptor() const = 0;

 

    virtual bool            isBinderAlive() const = 0;

    virtual status_t        pingBinder() = 0;

    virtual status_t        dump(int fd, const Vector<String16>& args) = 0;

 

    virtual status_t        transact(   uint32_t code,

                                        const Parcel& data,

                                        Parcel* reply,

                                        uint32_t flags = 0) = 0;

 

    class DeathRecipient : public virtual RefBase

    {

    public:

        virtual void binderDied(const wp<IBinder>& who) = 0;

    };

    virtual status_t        linkToDeath(const sp<DeathRecipient>& recipient,

                                        void* cookie = NULL,

                                        uint32_t flags = 0) = 0;

    virtual status_t        unlinkToDeath(  const wp<DeathRecipient>& recipient,

                                            void* cookie = NULL,

                                            uint32_t flags = 0,

                                            wp<DeathRecipient>* outRecipient = NULL) = 0;

    virtual bool            checkSubclass(const void* subclassID) const;

    typedef void (*object_cleanup_func)(const void* id, void* obj, void* cleanupCookie);

    virtual void            attachObject(   const void* objectID,

                                            void* object,

                                            void* cleanupCookie,

                                            object_cleanup_func func) = 0;

    virtual void*           findObject(const void* objectID) const = 0;

    virtual void            detachObject(const void* objectID) = 0;

    virtual BBinder*        localBinder();

    virtual BpBinder*       remoteBinder();

protected:

    virtual          ~IBinder();

private:

};

此类是一个抽象类,里面有大量的纯虚函数,其中有一下的函数只是一般的虚函数。

//构造函数不能实现能纯虚函数形式

IBinder::IBinder()

    : RefBase()

{

}

 

IBinder::~IBinder()

{

}

 

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

//查询本地接口函数,这样的接口是本地服务端binder需要继承实现的

sp<IInterface>  IBinder::queryLocalInterface(const String16& descriptor)

{

    return NULL;

}

//此接口是本地服务端需要继承实现的

BBinder* IBinder::localBinder()

{

    return NULL;

}

//此接口是远程服务代理端(即客户端)需要继承实现的

BpBinder* IBinder::remoteBinder()

{

    return NULL;

}

//此类目前还不了解其用途,待日后分析

bool IBinder::checkSubclass(const void* /*subclassID*/) const

{

    return false;

}

其他的纯虚函数都得在派生类中完全实现,否则不能实例化

class BBinder : public IBinder

{

public:

    //类的构造函数

                        BBinder();

    //获取接口描述符

virtual const String16& getInterfaceDescriptor() const;

//判断binder是否活着

virtual bool        isBinderAlive() const;

//PING binder 具体作用目前还不清楚

virtual status_t    pingBinder();

//用于输出dump LOG

    virtual status_t    dump(int fd, const Vector<String16>& args);

    //此函数是扩进程传输的核心,用binder设备文件进行交互

virtual status_t    transact(   uint32_t code,

                                    const Parcel& data,

                                    Parcel* reply,

                                    uint32_t flags = 0);

class DeathRecipient : public virtual RefBase

    {

    public:

        virtual void binderDied(const wp<IBinder>& who) = 0;

    };

//将此binder加入到死亡容器中(目前姑且这么理解,对其了解目前还不深入)

//binder死掉的时候,调用DeathRecipient类的binderDied给远程代码对象发送//一个死亡消息通知,如果是本地服务对象对用此接口,则返回无效的操作

//binder死亡的时候会调用死亡容器recipient中的binderDied函数

    virtual status_t    linkToDeath(const sp<DeathRecipient>& recipient,

                                    void* cookie = NULL,

                                    uint32_t flags = 0);

    //卸载掉之前注册的死亡通知,这样当binder死掉的时候不会产生死亡通知

    virtual status_t    unlinkToDeath(  const wp<DeathRecipient>& recipient,

                                        void* cookie = NULL,

                                        uint32_t flags = 0,

                                        wp<DeathRecipient>* outRecipient = NULL);

//此处是管理本服务对应的所有客户端对应的服务代理对象

    virtual void        attachObject(   const void* objectID,

                                        void* object,

                                        void* cleanupCookie,

                                        object_cleanup_func func);

//根据对象ID查询对应的远程服务代理对象

    virtual void*       findObject(const void* objectID) const;

virtual void        detachObject(const void* objectID);

//返回此本地服务的对象指针

    virtual BBinder*    localBinder();

protected:

//类的析构函数

virtual             ~BBinder();

//核心的数据传输函数

    virtual status_t    onTransact( uint32_t code,

                                    const Parcel& data,

                                    Parcel* reply,

                                    uint32_t flags = 0);

private:

//构造函数私有,其实用的就是单例模型

                        BBinder(const BBinder& o);

            BBinder&    operator=(const BBinder& o);

    class Extras;

            Extras*     mExtras;

            void*       mReserved0;

};

 

/*通过此类来管理本地服务对应的所有远程代理服务对象

** class BBinder::Extras

**{

**public:

**    Mutex mLock;

**    BpBinder::ObjectManager mObjects;//此处就是对服务代理的管理

};

*/

下面进入BpBinder

class BpBinder : public IBinder

{

public:

//构造函数

                        BpBinder(int32_t handle);

//获得类对象的进程句柄

inline  int32_t     handle() const { return mHandle; }

//获取接口描述符

virtual const String16&    getInterfaceDescriptor() const;

//判断此时binder是否继续活着

virtual bool        isBinderAlive() const;

//ping binder

virtual status_t    pingBinder();

//输出dump log

virtual status_t    dump(int fd, const Vector<String16>& args);

//核心的数据传输函数

    virtual status_t    transact(   uint32_t code,

                                    const Parcel& data,

                                    Parcel* reply,

                                    uint32_t flags = 0);

    //注册死亡通知接口

    virtual status_t    linkToDeath(const sp<DeathRecipient>& recipient,

                                    void* cookie = NULL,

                                    uint32_t flags = 0);

    //注销死亡通知接口

    virtual status_t    unlinkToDeath(  const wp<DeathRecipient>& recipient,

                                        void* cookie = NULL,

                                        uint32_t flags = 0,

                                        wp<DeathRecipient>* outRecipient = NULL);

  //我目前的理解,所有的服务都是servicemanager的客户端,而这些服务又有自己的//客户端,故客户端和服务都有自己的关联OBJECT的管理。

    virtual void        attachObject(   const void* objectID,

                                        void* object,

                                        void* cleanupCookie,

                                        object_cleanup_func func);

//根据objectID查询OBJECT

virtual void*       findObject(const void* objectID) const;

//取消绑定OBJECT

virtual void        detachObject(const void* objectID);

//返回远程的代理对象指针

virtual BpBinder*   remoteBinder();

//此函数应该是用来设置常量的,但是一直没有找到函数的实现

            status_t    setConstantData(const void* data, size_t size);

            void        sendObituary();

//此类事BBinder端管理远程代理类的类

    class ObjectManager

    {

    public:

                    ObjectManager();

                    ~ObjectManager();

        //对象管理的附加函数

        void        attach( const void* objectID,

                            void* object,

                            void* cleanupCookie,

                            IBinder::object_cleanup_func func);

        //对象管理的查询函数

        void*       find(const void* objectID) const;

        //对象管理的分离函数

        void        detach(const void* objectID);

        //分离所有的对象

        void        kill();

    private:

                    ObjectManager(const ObjectManager&);

        ObjectManager& operator=(const ObjectManager&);

        //一个结构体,将一下三种属相集中管理

        struct entry_t

        {

            void* object;

            void* cleanupCookie;

            IBinder::object_cleanup_func func;

        };

        //结构体entry类型的对象矢量容器

        KeyedVector<const void*, entry_t> mObjects;

    };

protected:

    //析构函数

virtual             ~BpBinder();

//对服务对象进行强引用(目前的理解)

virtual void        onFirstRef();

//取消对服务对象的强引用

virtual void        onLastStrongRef(const void* id);

//尝试对服务对象进行强引用

    virtual bool        onIncStrongAttempted(uint32_t flags, const void* id);

private:

const   int32_t             mHandle;

//此结构体集中管理死亡通知

    struct Obituary {

        wp<DeathRecipient> recipient;

        void* cookie;

        uint32_t flags;

};

        //报告binder对象的死亡消息

            void                reportOneDeath(const Obituary& obit);

            //判断描述符是否被储存起来

            bool                isDescriptorCached() const;

            //互斥锁

    mutable Mutex               mLock;

            volatile int32_t    mAlive;

            volatile int32_t    mObitsSent;

            Vector<Obituary>*   mObituaries;

            ObjectManager       mObjects;

       //此变量是一个常量数据,但是和函数一样,没有找到什么地方对其进行应用了

            Parcel*             mConstantData;

    mutable String16            mDescriptorCache;

};

 

下面进入ProcessState

class ProcessState : public virtual RefBase

{

public:

//静态的成员函数,所有的类对象共享同一个函数,这样做是为了实现单例模型

//类对象调用构造函数的方法,(C++类。如果没有显示可调用的构造函数,会调用一//个默认的构造函数,此构造函数不做任何事情,仅负责对象创建)

static  sp<ProcessState>    self();

//添加一个进程上下文的对象,类似于添加一个服务,(此函数针对服务管理服务)

            void                setContextObject(const sp<IBinder>& object);

            //获取一个上下文对象,就是获取服务对象(此函数针对服务管理程序)

sp<IBinder>         getContextObject(const sp<IBinder>& caller);

//此函数针对一般的服务管理程序,添加服务

            void                setContextObject(const sp<IBinder>& object,

                                                 const String16& name);

            //获取服务,针对一般的服务程序

            sp<IBinder>         getContextObject(const String16& name,

                                                 const sp<IBinder>& caller);

            //开启线程池

            void                startThreadPool();

            //定义了一个指针函数

            typedef bool (*context_check_func)(const String16& name,

                                       const sp<IBinder>& caller,

                                       void* userData);

            //判断是否是服务的管理者

            bool                isContextManager(void) const;

            //成为服务的管理者

            bool                becomeContextManager(

                                    context_check_func checkFunc,

                                    void* userData);

            //获取代理的对象,根据handler,此代理对象与服务是强引用关系

            sp<IBinder>         getStrongProxyForHandle(int32_t handle);

            //获取代理的对象,根据handler,此代理对象与服务是弱引用关系

            wp<IBinder>         getWeakProxyForHandle(int32_t handle);

            //擦出此handler关联的binder对象

            void                expungeHandle(int32_t handle, IBinder* binder);

            //设置进程的命令行参数

            void                setArgs(int argc, const char* const argv[]);

            //获取命令行参数的个数

            int                 getArgC() const;

            //获取命令行参数

            const char* const*  getArgV() const;

            //设置命令行的第一个参数,即程序运行的全路劲名

            void                setArgV0(const char* txt);

            //创建一个新的线程池

            void                spawnPooledThread(bool isMain);

private:

friend class IPCThreadState;//友元类

                            //无参构造函数

                                ProcessState();

                                //析构函数

                                ~ProcessState();

                                //有参构造函数

                                ProcessState(const ProcessState& o);

            //操作符重载

ProcessState&       operator=(const ProcessState& o);

            //结构体统一管理对象的引用

            struct handle_entry {

                IBinder* binder;

                RefBase::weakref_type* refs;

            };

            //查找handler对应的对象,如果没有则创建一个新的对象

            handle_entry*       lookupHandleLocked(int32_t handle);

            //binder设备文件的文件句柄

            int                 mDriverFD;

            //设备文件map进进程的虚拟地址的起始地址

            void*               mVMStart;

    mutable Mutex               mLock;  // protects everything below.

            Vector<handle_entry>mHandleToObject;

            bool                mManagesContexts;

            context_check_func  mBinderContextCheckFunc;

            void*               mBinderContextUserData;

            KeyedVector<String16, sp<IBinder> >

                                mContexts;

            String8             mRootDir;

            bool                mThreadPoolStarted;

    volatile int32_t            mThreadPoolSeq;

};

}; // namespace android

 

Binder模型有两套协议:

一个是command,另一个是reply协议。

enum BinderDriverReturnProtocol {

 BR_ERROR = _IOR_BAD('r', 0, int),

 BR_OK = _IO('r', 1),

 BR_TRANSACTION = _IOR_BAD('r', 2, struct binder_transaction_data),

 BR_REPLY = _IOR_BAD('r', 3, struct binder_transaction_data),

 BR_ACQUIRE_RESULT = _IOR_BAD('r', 4, int),

 BR_DEAD_REPLY = _IO('r', 5),

 BR_TRANSACTION_COMPLETE = _IO('r', 6),

 BR_INCREFS = _IOR_BAD('r', 7, struct binder_ptr_cookie),

 BR_ACQUIRE = _IOR_BAD('r', 8, struct binder_ptr_cookie),

 BR_RELEASE = _IOR_BAD('r', 9, struct binder_ptr_cookie),

 BR_DECREFS = _IOR_BAD('r', 10, struct binder_ptr_cookie),

 BR_ATTEMPT_ACQUIRE = _IOR_BAD('r', 11, struct binder_pri_ptr_cookie),

 BR_NOOP = _IO('r', 12),

 BR_SPAWN_LOOPER = _IO('r', 13),

 BR_FINISHED = _IO('r', 14),

 BR_DEAD_BINDER = _IOR_BAD('r', 15, void *),

 BR_CLEAR_DEATH_NOTIFICATION_DONE = _IOR_BAD('r', 16, void *),

 BR_FAILED_REPLY = _IO('r', 17),

};

 

enum BinderDriverCommandProtocol {

 BC_TRANSACTION = _IOW_BAD('c', 0, struct binder_transaction_data),

 BC_REPLY = _IOW_BAD('c', 1, struct binder_transaction_data),

 BC_ACQUIRE_RESULT = _IOW_BAD('c', 2, int),

 BC_FREE_BUFFER = _IOW_BAD('c', 3, int),

 BC_INCREFS = _IOW_BAD('c', 4, int),

 BC_ACQUIRE = _IOW_BAD('c', 5, int),

 BC_RELEASE = _IOW_BAD('c', 6, int),

 BC_DECREFS = _IOW_BAD('c', 7, int),

 BC_INCREFS_DONE = _IOW_BAD('c', 8, struct binder_ptr_cookie),

 BC_ACQUIRE_DONE = _IOW_BAD('c', 9, struct binder_ptr_cookie),

 BC_ATTEMPT_ACQUIRE = _IOW_BAD('c', 10, struct binder_pri_desc),

 BC_REGISTER_LOOPER = _IO('c', 11),

 BC_ENTER_LOOPER = _IO('c', 12),

 BC_EXIT_LOOPER = _IO('c', 13),

 BC_REQUEST_DEATH_NOTIFICATION = _IOW_BAD('c', 14, struct binder_ptr_cookie),

 BC_CLEAR_DEATH_NOTIFICATION = _IOW_BAD('c', 15, struct binder_ptr_cookie),

 BC_DEAD_BINDER_DONE = _IOW_BAD('c', 16, void *),

};

 

下面进入IPCThreadState类进行浅析

/*

**此类事单例模型

**此类与binder设备驱动进行通信,轮询通信

*/

class IPCThreadState

{

public:

//单例模型,构造函数的对外接口

/*

**1.首先pthread_key_create(&gTLS, threadDestructor) != 0)创建并获取一个线程相关的**key

**2.然后判断IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);区域是否为NULL

**3.如果为NULL,则return new IPCThreadState;

**4.在此类的构造函数中调用pthread_setspecific(gTLS, this);将此类对象存放进线程的私**有数据区域

*/

static  IPCThreadState*     self();

//直接到线程的私有数据区域去驱动类对象的实例

static  IPCThreadState*     selfOrNull();  // self(), but won't instantiate

//获取此线程相关的进程实例对象

                sp<ProcessState>    process();

            //清理最后产生的错误

            status_t            clearLastError();

            //获取进程的PID

            int                 getCallingPid();

            //获取用户的UID

            int                 getCallingUid();

            //设置严格的线程方针模式

            /*

            **常见的strictMode:

// Thread-policy:

           public static final int DETECT_DISK_WRITE = 0x01;  // for ThreadPolicy

           public static final int DETECT_DISK_READ = 0x02;  // for ThreadPolicy

           public static final int DETECT_NETWORK = 0x04;  // for ThreadPolicy

           public static final int DETECT_CUSTOM = 0x08;  // for ThreadPolicy

           // Process-policy://线程方针在此举例列举

static final int DETECT_VM_CURSOR_LEAKS = 0x200;  // for VmPolicy

           public static final int DETECT_VM_CLOSABLE_LEAKS = 0x400;  // for VmPolicy

           public static final int DETECT_VM_ACTIVITY_LEAKS = 0x800;  // for VmPolicy

           private static final int DETECT_VM_INSTANCE_LEAKS = 0x1000; // for VmPolicy

           */

            void                setStrictModePolicy(int32_t policy);

            //获取线程policy mode

            int32_t             getStrictModePolicy() const;

            //设置最后处理binder的状态

            void                setLastTransactionBinderFlags(int32_t flags);

            //获取最后处理的binder的状态

            int32_t             getLastTransactionBinderFlags() const;

            //清理调用的标识,也就是PIDUID

            int64_t             clearCallingIdentity();

            //重新存储PIDUID

            void                restoreCallingIdentity(int64_t token);

            //调用talkWithDriver(false)函数将READwrite存储命令的存储区域清理干净

                        void                flushCommands();

            //将此线程加入进程的线程池,开始与binder设备驱动进行交互

            void                joinThreadPool(bool isMain = true);

                        // Stop the local process.

            void                stopProcess(bool immediate = true);

            //进程数据传输的函数

                        status_t            transact(int32_t handle,

                                         uint32_t code, const Parcel& data,

                                         Parcel* reply, uint32_t flags);

            //增加对务对象进程强引用

            void                incStrongHandle(int32_t handle);

            //取消对服务的强引用

            void                decStrongHandle(int32_t handle);

            //增加对服务对象的弱引用

            void                incWeakHandle(int32_t handle);

            //取消对服务进程进行强引用

            void                decWeakHandle(int32_t handle);

            //尝试对服务进程进行强引用

            status_t            attemptIncStrongHandle(int32_t handle);

            //调用进程相关函数,擦出此handle对应的binder对象

static  void                expungeHandle(int32_t handle, IBinder* binder);

        //申请注册死亡消息通知

            status_t            requestDeathNotification(   int32_t handle,

                                                            BpBinder* proxy);

            //注销死亡消息通知

            status_t            clearDeathNotification( int32_t handle,

                                                        BpBinder* proxy);

    //退出此线程,并清理此线程私有的数据

    static  void                shutdown();

       // Call this to disable switching threads to background scheduling when

    // receiving incoming IPC calls.  This is specifically here for the

    // Android system process, since it expects to have background apps calling

    // in to it but doesn't want to acquire locks in its services while in

// the background.

//disable后台进程的调度

    static  void                disableBackgroundScheduling(bool disable);

   private:

                                //构造函数

                                IPCThreadState();

                                //析构函数

                                ~IPCThreadState();

            //将请求的结果发送回去

            status_t            sendReply(const Parcel& reply, uint32_t flags);

            //等待反馈

            status_t            waitForResponse(Parcel *reply,

                                                status_t *acquireResult=NULL);

            //与驱动进行交互

            status_t            talkWithDriver(bool doReceive=true);

            //通过paracl类,初始化传输数据

            status_t            writeTransactionData(int32_t cmd,

                                                     uint32_t binderFlags,

                                                     int32_t handle,

                                                     uint32_t code,

                                                     const Parcel& data,

                                                     status_t* statusBuffer);

    //根据命令执行相关操作

            status_t            executeCommand(int32_t command);

            //重新获取PIDUID

            void                clearCaller();

    //线程的销毁函数,下命令到binder通知此线程退出

static  void                threadDestructor(void *st);

//通知binder进行相关的存储空间的释放

    static  void                freeBuffer(Parcel* parcel,

                                           const uint8_t* data, size_t dataSize,

                                           const size_t* objects, size_t objectsSize,

                                           void* cookie);

    //标识此线程的类对象

    const   sp<ProcessState>    mProcess;

    const   pid_t               mMyThreadId;

            Vector<BBinder*>    mPendingStrongDerefs;

            Vector<RefBase::weakref_type*> mPendingWeakDerefs;

            Parcel              mIn;

            Parcel              mOut;

            status_t            mLastError;

            pid_t               mCallingPid;

            uid_t               mCallingUid;

            int32_t             mStrictModePolicy;

            int32_t             mLastTransactionBinderFlags;

};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值