前言

在上一篇博客 【Binder 机制】Native 层 Binder 机制分析 ( binder_loop | svcmgr_handler | binder.c | binder_parse ) 中 , 简单介绍了 在 service_manager.c 中的 main 函数中调用了 binder_loop 方法 , 在 binder_loop 方法中 , 传入了 svcmgr_handler 方法作为回调函数 , svcmgr_handler 中可以接收不同的消息 , 处理不同的业务 ;





一、查找 Binder 服务

参考 【Binder 机制】Native 层 Binder 机制分析 ( binder_loop | svcmgr_handler | binder.c | binder_parse ) 二、binder_loop 方法参数 svcmgr_handler 章节 ;

在 svcmgr_handler 方法中 , 查找 Binder 服务 , 需要执行如下逻辑 : 接收到 SVC_MGR_CHECK_SERVICE 消息 , 查找 Binder 服务 , 主要调用 do_find_service 方法 ;

int svcmgr_handler(struct binder_state *bs,
                   struct binder_transaction_data *txn,
                   struct binder_io *msg,
                   struct binder_io *reply)
{
	// 链表 
    struct svcinfo *si;

	// 根据不同的 txn->code 执行不同的方法 
    switch(txn->code) {
    case SVC_MGR_CHECK_SERVICE:
        s = bio_get_string16(msg, &len);
        if (s == NULL) {
            return -1;
        }
        handle = do_find_service(s, len, txn->sender_euid, txn->sender_pid);
        if (!handle)
            break;
        bio_put_ref(reply, handle);
        return 0;
    }
    return 0;
}

完整代码参考 /frameworks/native/cmds/servicemanager/service_manager.c





二、service_manager.c | do_find_service

do_find_service 方法 , 主要用于查找之前是否有注册过 Service 服务 ;

uint32_t do_find_service(const uint16_t *s, size_t len, uid_t uid, pid_t spid)
{
	// 查找服务 
    struct svcinfo *si = find_svc(s, len);

    if (!si || !si->handle) {
        return 0;
    }

    if (!si->allow_isolated) {
        // If this service doesn't allow access from isolated processes,
        // then check the uid to see if it is isolated.
        uid_t appid = uid % AID_USER;
        if (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END) {
            return 0;
        }
    }

	// 如果没有找到服务 , 返回 0 
    if (!svc_can_find(s, len, spid, uid)) {
        return 0;
    }

	// 如果找到服务 , 直接返回 
    return si->handle;
}

完整代码参考 /frameworks/native/cmds/servicemanager/service_manager.c