Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Binder進程間通信---注冊Service組件---Server處理BC_TRANSACTION

Android Binder進程間通信---注冊Service組件---Server處理BC_TRANSACTION

編輯:關於Android編程

本文參考《Android系統源代碼情景分析》,作者羅升陽

一、測試代碼:

~/Android/external/binder/server

----FregServer.cpp

~/Android/external/binder/common

----IFregService.cpp

----IFregService.h

~/Android/external/binder/client

----FregClient.cpp


Binder庫(libbinder)代碼:

~/Android/frameworks/base/libs/binder

----BpBinder.cpp

----Parcel.cpp

----ProcessState.cpp

----Binder.cpp

----IInterface.cpp

----IPCThreadState.cpp

----IServiceManager.cpp

----Static.cpp

~/Android/frameworks/base/include/binder

----Binder.h

----BpBinder.h

----IInterface.h

----IPCThreadState.h

----IServiceManager.h

----IBinder.h

----Parcel.h

----ProcessState.h


驅動層代碼:

~/Android//kernel/goldfish/drivers/staging/android

----binder.c

----binder.h


二、源碼分析 在上一篇文章中,Android Binder進程間通信---注冊Service組件---Client發送BC_TRANSACTIONhttp://blog.csdn.net/jltxgcy/article/details/26076149, list_add_tail(&t->work.entry, target_list);已經加入到目標進程的todo列表。 wake_up_interruptible(target_wait);喚醒了目標進程。 還記得在Andorid Binder進程間通信---啟動ServiceManager一文中http://blog.csdn.net/jltxgcy/article/details/25797011,最後進程睡眠等待直到有新的未處理項為止,此時有新的處理項,繼續執行binder_thread_read函數。實現如下:

~/Android//kernel/goldfish/drivers/staging/android

----binder.c

static int
binder_thread_read(struct binder_proc *proc, struct binder_thread *thread,
	void  __user *buffer, int size, signed long *consumed, int non_block)
{
	void __user *ptr = buffer + *consumed;
	void __user *end = buffer + size;

	int ret = 0;
	.........

	while (1) {
		uint32_t cmd;
		struct binder_transaction_data tr;
		struct binder_work *w;
		struct binder_transaction *t = NULL;

		if (!list_empty(&thread->todo))
			w = list_first_entry(&thread->todo, struct binder_work, entry);
		else if (!list_empty(&proc->todo) && wait_for_proc_work)
			w = list_first_entry(&proc->todo, struct binder_work, entry);//將要處理的工作項保存在binder_work結構體w中
		else {
			if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */
				goto retry;
			break;
		}

		........

		switch (w->type) {
		case BINDER_WORK_TRANSACTION: {
			t = container_of(w, struct binder_transaction, work);//由於binder_work結構體w的類型為BINDER_WORK_TRANSACTION,即它是一個嵌入在一個binder_transaction結構體中的工作項,因此可以安全地將它轉換為一個binder_transaction結構體t
		} break;
		.........
		}

		if (!t)
			continue;

		BUG_ON(t->buffer == NULL);
		if (t->buffer->target_node) {
			struct binder_node *target_node = t->buffer->target_node;
			tr.target.ptr = target_node->ptr;//Binder實體對象ptr為NULL
			tr.cookie =  target_node->cookie;//Binder實體對象cookie為NULL
			t->saved_priority = task_nice(current);
			if (t->priority < target_node->min_priority &&
			    !(t->flags & TF_ONE_WAY))
				binder_set_nice(t->priority);
			else if (!(t->flags & TF_ONE_WAY) ||
				 t->saved_priority > target_node->min_priority)
				binder_set_nice(target_node->min_priority);
			cmd = BR_TRANSACTION;//cmd設置BR_TRANSACTION
		} else {
			.....
		}
		tr.code = t->code;//ADD_SERVICE_TRANCATION
		tr.flags = t->flags;//TF_ACCEPTS_FDS
		tr.sender_euid = t->sender_euid;

		if (t->from) {
			struct task_struct *sender = t->from->proc->tsk;
			tr.sender_pid = task_tgid_nr_ns(sender, current->nsproxy->pid_ns);
		} else {
			.......
		}

		tr.data_size = t->buffer->data_size;//數據緩沖區大小
		tr.offsets_size = t->buffer->offsets_size;//偏移數組大小
		tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;//內核緩沖區的內核空間地址和用戶空間地址相差一個固定值,並且保存在它的成員變量user_buffer_offset中
		tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));//偏移保存在數據緩沖區的後面

		if (put_user(cmd, (uint32_t __user *)ptr))//將命令返回
			return -EFAULT;
		ptr += sizeof(uint32_t);
		if (copy_to_user(ptr, &tr, sizeof(tr)))//將binder_transaction_data結構體tr返回
			return -EFAULT;
		ptr += sizeof(tr);

		.......

		list_del(&t->work.entry);//刪除該任務項
		t->buffer->allow_user_free = 1;//允許釋放
		if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
			t->to_parent = thread->transaction_stack;
			t->to_thread = thread;
			thread->transaction_stack = t;
		} else {
			t->buffer->transaction = NULL;
			kfree(t);
			........
		}
		break;
	}

done:

	*consumed = ptr - buffer;//cmd和binder_transaction_data結構體tr大小之和
	........
	return 0;
}
if語句首先檢查線程thread自己的todo隊列中是否有個工作項需要處理。如果沒有,第19行的if語句再檢查它所屬進程proc的todo隊列中是否有工作項需要處理。只要其中的一個todo隊列中有工作項需要處理,函數binder_thread_read就將它取出來處理,並且保存在binder_work結構體w中。 由於binder_work結構體w的類型為BINDER_WORK_TRANSACTION,即它是一個嵌入在一個binder_transaction結構體中的工作項,因此可以安全地將它轉換為一個binder_transaction結構體t。 利用binder_transaction結構體t設置binder_transaction_data結構體tr各參數。並將cmd和binder_transaction_data結構體tr返回到binder_ioctl,然後再返回到binder_loop: ~/Android/frameworks/base/cmd/servicemanager ----binder.c
void binder_loop(struct binder_state *bs, binder_handler func)
{
    int res;
    struct binder_write_read bwr;
    unsigned readbuf[32];

    bwr.write_size = 0;
    bwr.write_consumed = 0;
    bwr.write_buffer = 0;
    
    readbuf[0] = BC_ENTER_LOOPER;//首先將BC_ENTER_LOOPER協議寫入緩沖區readbuf中
    binder_write(bs, readbuf, sizeof(unsigned));//調用binder_write將它發送到Binder驅動程序中

    for (;;) {
        bwr.read_size = sizeof(readbuf);
        bwr.read_consumed = 0;
        bwr.read_buffer = (unsigned) readbuf;

        res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);//bwr.write_size為0,bwr.read_size不為0

        if (res < 0) {
            LOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));
            break;
        }

        res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func);//此時readbuf為cmd和binder_transaction_data結構體tr,bwr.read_consumed為cmd和binder_transaction_data結構體tr大小之和
        if (res == 0) {
            LOGE("binder_loop: unexpected reply?!\n");
            break;
        }
        if (res < 0) {
            LOGE("binder_loop: io error %d %s\n", res, strerror(errno));
            break;
        }
    }
}
開始執行binder_parse。實現如下:
int binder_parse(struct binder_state *bs, struct binder_io *bio,
                 uint32_t *ptr, uint32_t size, binder_handler func)
{
    int r = 1;
    uint32_t *end = ptr + (size / 4);

    while (ptr < end) {
        uint32_t cmd = *ptr++;
        .......
        switch(cmd) {//cmd為BR_TRANSACTION
        ......
        case BR_TRANSACTION: {
            struct binder_txn *txn = (void *) ptr;//binder_transaction_data結構體tr取出放到binder_txt結構體中
            ........
            if (func) {//svcmgr_handler函數指針
                unsigned rdata[256/4];
                struct binder_io msg;
                struct binder_io reply;
                int res;

                bio_init(&reply, rdata, sizeof(rdata), 4);
                bio_init_from_txn(&msg, txn);
                res = func(bs, txn, &msg, &reply);//svcmgr_handler函數指針
                binder_send_reply(bs, &reply, txn->data, res);
            }
            ptr += sizeof(*txn) / sizeof(uint32_t);
            break;
        }
        ......
    }

    return r;
}
在介紹binder_parse前,首先看幾個結構體。 ~/Android/frameworks/base/cmd/servicemanager ----binder.h
struct binder_object
{
    uint32_t type;
    uint32_t flags;
    void *pointer;
    void *cookie;
};

struct binder_txn
{
    void *target;
    void *cookie;
    uint32_t code;
    uint32_t flags;

    uint32_t sender_pid;
    uint32_t sender_euid;

    uint32_t data_size;
    uint32_t offs_size;
    void *data;
    void *offs;
};

struct binder_io //具體含義見英文注釋
{
    char *data;            /* pointer to read/write from */
    uint32_t *offs;        /* array of offsets */
    uint32_t data_avail;   /* bytes available in data buffer */
    uint32_t offs_avail;   /* entries available in offsets array */

    char *data0;           /* start of data buffer */
    uint32_t *offs0;       /* start of offsets buffer */
    uint32_t flags;
    uint32_t unused;
};
結構體binder_txn用來描述進程間通信數據,它等同於前面介紹的binder_transaction_data結構體。
結構體binder_io用來解析進程間通信數據的,它的作用類似於Binder庫中的Parcel類。 結構體binder_object用來描述進程間通信數據中的一個Binder對象,它等同於結構體flat_binder_object。 執行binder_parse,首先取出cmd,然後取出binder_transaction_data結構體tr保存在binder_txn結構體txn中。然後調用bio_init函數,實現如下:
~/Android/frameworks/base/cmd/servicemanager ----binder.c
void bio_init(struct binder_io *bio, void *data,
              uint32_t maxdata, uint32_t maxoffs)
{
    uint32_t n = maxoffs * sizeof(uint32_t);//偏移數組所占的大小

    if (n > maxdata) {//偏移數組所占的大小不能大於最大能分配大小
        bio->flags = BIO_F_OVERFLOW;
        bio->data_avail = 0;
        bio->offs_avail = 0;
        return;
    }

    bio->data = bio->data0 = data + n;//偏移數組後面是數據緩沖區
    bio->offs = bio->offs0 = data;//開始是偏移數組
    bio->data_avail = maxdata - n;//數據緩沖區大小
    bio->offs_avail = maxoffs;//偏移數組大小
    bio->flags = 0;
}
bio_init初始化了binder_io結構體reply。返回binder_parse執行bio_init_from_txn函數,實現如下: ~/Android/frameworks/base/cmd/servicemanager ----binder.c
void bio_init_from_txn(struct binder_io *bio, struct binder_txn *txn)
{
    bio->data = bio->data0 = txn->data;
    bio->offs = bio->offs0 = txn->offs;
    bio->data_avail = txn->data_size;
    bio->offs_avail = txn->offs_size / 4;
    bio->flags = BIO_F_SHARED;
}
bio_init_from_txn初始化了binder_io結構體msg。 返回binder_parse執行svcmgr_handler函數,實現如下: ~/Android/frameworks/base/cmd/servicemanager ----service_manager.c
int svcmgr_handler(struct binder_state *bs,
                   struct binder_txn *txn,
                   struct binder_io *msg,
                   struct binder_io *reply)
{
    struct svcinfo *si;
    uint16_t *s;
    unsigned len;
    void *ptr;
    uint32_t strict_policy;

    ......

    if (txn->target != svcmgr_handle)//txn->target為NULL,svcmgr_handle為NULL(void* (0))
        return -1;

    // Equivalent to Parcel::enforceInterface(), reading the RPC
    // header with the strict mode policy mask and the interface name.
    // Note that we ignore the strict_policy and don't propagate it
    // further (since we do no outbound RPCs anyway).
    strict_policy = bio_get_uint32(msg);//strict_policy為STRICT_MODE_PENALTY_GATHER
    s = bio_get_string16(msg, &len);//s為android.os.IServiceManager
    if ((len != (sizeof(svcmgr_id) / 2)) ||
        memcmp(svcmgr_id, s, sizeof(svcmgr_id))) {//比較是否一致,如果不一致,直接返回出錯
        fprintf(stderr,"invalid id %s\n", str8(s));
        return -1;
    }

    switch(txn->code) {//ADD_SERVICE_TRANSACTION,即SVC_MGR_ADD_SERVICE
    ........
    case SVC_MGR_ADD_SERVICE:
        s = bio_get_string16(msg, &len);//s為shy.luo.FregService,len為它的長度
        ptr = bio_get_ref(msg);//返回Binder引用對象的句柄值
        if (do_add_service(bs, s, len, ptr, txn->sender_euid))
            return -1;
        break;
    .......
    bio_put_uint32(reply, 0);
    return 0;
}
其中svcmgr_id[]實現如下: ~/Android/frameworks/base/cmd/servicemanager ----service_manager.c
uint16_t svcmgr_id[] = { 
    'a','n','d','r','o','i','d','.','o','s','.',
    'I','S','e','r','v','i','c','e','M','a','n','a','g','e','r' 
};
程序從binder_io結構體msg從獲取了3個字符串信息,然後調用bio_get_ref函數返回Binder引用對象的句柄值,實現如下: ~/Android/frameworks/base/cmd/servicemanager ----binder.c
void *bio_get_ref(struct binder_io *bio)
{
    struct binder_object *obj;

    obj = _bio_get_obj(bio);
    if (!obj)
        return 0;

    if (obj->type == BINDER_TYPE_HANDLE)
        return obj->pointer;

    return 0;
}
_bio_get_obj實現如下: ~/Android/frameworks/base/cmd/servicemanager ----binder.c
static struct binder_object *_bio_get_obj(struct binder_io *bio)
{
    unsigned n;
    unsigned off = bio->data - bio->data0;//flat_binder_object偏移,由於前面獲取字符串移動了data

        /* TODO: be smarter about this? */
    for (n = 0; n < bio->offs_avail; n++) {//offs_avail等於1
        if (bio->offs[n] == off)
            return bio_get(bio, sizeof(struct binder_object));
    }

    bio->data_avail = 0;
    bio->flags |= BIO_F_OVERFLOW;
    return 0;
}
_bio_get_obj首先計算出flat_binder_object偏移,然後看看偏移是否和bio->offs[0]一致,如果一致,那麼就調用bio_get函數,實現如下。 ~/Android/frameworks/base/cmd/servicemanager ----binder.c
static void *bio_get(struct binder_io *bio, uint32_t size)
{
    size = (size + 3) & (~3);

    if (bio->data_avail < size){
        .......
    }  else {
        void *ptr = bio->data;
        bio->data += size;//數據指針增加
        bio->data_avail -= size;//可用空間減少
        return ptr;//返回了flat_binder_object結構體
    }
}
函數返回了flat_binder_object結構體,最後返回到bio_get_ref函數,轉換成binder_object結構體指針。由於type等於BINDER_TYPE_HANDLE,所以返回Binder引用對象的句柄值。
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved