HAL层代码

之前实现好了linux底层的模拟自设备驱动freg和测试程序后,下面开始学习android下的硬件抽象层,hardware层,也叫HAL层。
主要的文件:

hardware/libhardware/hardware.c
hardware/libhardware/include/hardware/hardware.h

Android的HAL层是Android系统对底层硬件操作屏蔽的一个中间层,就是上层不必关心底层硬件具体是怎么执行的,只需要调用HAL层中给定的统一的接口就行了。那这样的话,就类似linux系统中的一些驱动模型的设计一样,都会有统一的格式。HAL层应该也是一样。

通过上述的两个文件,尤其是头文件,可以观察到主要的是
三个结构体

struct hw_module_t;
struct hw_module_methods_t ;
struct hw_device_t;

两个常量

#define HAL_MODULE_INFO_SYM_AS_STR “HMI”
#define HAL_MODULE_INFO_SYM HMI

一个函数。

int hw_get_module(const char *id, const struct hw_module_t **module);

这个的详细解释,可以参看此篇文章:
http://blog.csdn.net/mr_raptor/article/details/8069588
http://blog.csdn.net/u011913612/article/details/52518186
关于定义HAL_MODULE_INFO_SYM的原因可参考:
http://www.embedu.org/Column/Column733.htm

我们编写一个底层硬件的HAL层代码,都是基于以上三个结构体来封装的。(这里相当于利用结构体的特点来体现的“继承”的概念,继承基本的 hw_module_t 和 hw_device_t 类型,丰富出自己的特有的功能)

  • 封装我们自己定义的xxx_module_t结构体,其中第一个成员必须为 hw_module_t 类型。程序中定义此类型且名称固定为HAL_MODULE_INFO_SYM的全局变量。
  • 封装我们自己定义的xxx_device_t结构体,其中第一个成员必须是hw_device_t类型成员。

具体实现一个HAL层的库,其实就是定义一个 xxx_module_t 类型,名称为 HAL_MODULE_INFO_SYM 的全局变量,上层代码与这个库产生联系的一个关键。然后就是现实自己封装的 xxx_device_t 类型中的其他函数接口。

上层在调用时,
1. 首先调用 hw_get_module() 方法,通过模块ID来找到动态库。
2. 找到后使用load()函数打开这个库,并通过一个固定的符号 HAL_MODULE_INFO_SYM 寻找hw_module_t结构体(load函数中使用的是 HAL_MODULE_INFO_SYM_AS_STR 来匹配查找,所以这两个宏的字符要匹配)。
3. 在 hw_module_t 结构体中有一个hw_module_methods_t 类型成员,这个结构体中会提供一个open方法用来打开模块,在open的参数中会传入一个 hw_device_t 类型的变量,用来保存open方法传出的参数。
4. 将这个指针强转成我们自定义的 xxx_device_t 类型指针(这也就是为什么第一个成员必须是hw_device_t 类型的成员)。在xxx_device_t 结构体中就有我们定义的一系列对底层硬件的操作接口。这样就实现了上层对底层硬件设备的统一访问形式。

上面说了定位库中hw_module_t类型的入口就是 hw_get_module 函数。那如何找到具体是哪个库呢?
这个就是HAL层对库的规范的定义。在hardware.c

int hw_get_module_by_class(const char *class_id, const char *inst,
                           const struct hw_module_t **module)
{
    int i = 0;
    char prop[PATH_MAX] = {0};
    char path[PATH_MAX] = {0};
    char name[PATH_MAX] = {0};
    char prop_name[PATH_MAX] = {0};


    if (inst)
        snprintf(name, PATH_MAX, "%s.%s", class_id, inst);
    else
        strlcpy(name, class_id, PATH_MAX);

    /*
     * Here we rely on the fact that calling dlopen multiple times on
     * the same .so will simply increment a refcount (and not load
     * a new copy of the library).
     * We also assume that dlopen() is thread-safe.
     */

    /* First try a property specific to the class and possibly instance */
    /* 首先尝试特定属性值,找到的话就直接去打开库 */
    snprintf(prop_name, sizeof(prop_name), "ro.hardware.%s", name);
    if (property_get(prop_name, prop, NULL) > 0) {
        if (hw_module_exists(path, sizeof(path), name, prop) == 0) {
            goto found;
        }
    }

    /* Loop through the configuration variants looking for a module */
    /* 如果没有找到就遍历之前定义好的几个属性值,见下面代码 */
    for (i=0 ; i<HAL_VARIANT_KEYS_COUNT; i++) {
        if (property_get(variant_keys[i], prop, NULL) == 0) {
            continue;
        }
        if (hw_module_exists(path, sizeof(path), name, prop) == 0) {
            goto found;
        }
    }

    /* Nothing found, try the default */
    /* 如果都没有找到这写属性值,就使用"default"来补充库名称 */
    if (hw_module_exists(path, sizeof(path), name, "default") == 0) {
        goto found;
    }

    return -ENOENT;

found:
    /* load the module, if this fails, we're doomed, and we should not try
     * to load a different variant. */
    /* 打开库 */
    return load(class_id, path, module);
}

可以看出,上面的所有动作都是为了”合成”一个动态库的名称,主要就是在hw_module_exists中。

/*
 * Check if a HAL with given name and subname exists, if so return 0, otherwise
 * otherwise return negative.  On success path will contain the path to the HAL.
 */
static int hw_module_exists(char *path, size_t path_len, const char *name,
                            const char *subname)
{
    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH2, name, subname);
    if (access(path, R_OK) == 0)
        return 0;

    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH1, name, subname);
    if (access(path, R_OK) == 0)
        return 0;

    return -ENOENT;
}

可以看出,库的存放路径是两个固定的位置(宏定义),动态库名称为
{MODULE_ID}.{variant}.so
其中variant就是上面从属性中获取的值,如果没有找到就是“default”

其中四个属性名称为:

static const char *variant_keys[] = {
    "ro.hardware",  /* This goes first so that it can pick up a different
                       file on the emulator. */
    "ro.product.board",
    "ro.board.platform",
    "ro.arch"
};

两个路径宏定义为(即动态链接库的存放路径固定):

/** Base path of the hal modules */
#if defined(__LP64__)
#define HAL_LIBRARY_PATH1 "/system/lib64/hw"
#define HAL_LIBRARY_PATH2 "/vendor/lib64/hw"
#else
#define HAL_LIBRARY_PATH1 "/system/lib/hw"
#define HAL_LIBRARY_PATH2 "/vendor/lib/hw"
#endif

通过这里也可以看出,动态链接库的名称规范是有这里的匹配规则来规定的。也可以通过修改这部分代码,来自己定义这样的匹配规则。

下来再看一下load接口的实现

static int load(const char *id,
        const char *path,
        const struct hw_module_t **pHmi)
        //此处可以看出要传出的是hw_module_t类型的参数
{
    int status;
    void *handle;
    struct hw_module_t *hmi;

    /*
     * load the symbols resolving undefined symbols before
     * dlopen returns. Since RTLD_GLOBAL is not or'd in with
     * RTLD_NOW the external symbols will not be global
     */
    handle = dlopen(path, RTLD_NOW);
    if (handle == NULL) {
        char const *err_str = dlerror();
        ALOGE("load: module=%s\n%s", path, err_str?err_str:"unknown");
        status = -EINVAL;
        goto done;
    }

    /* Get the address of the struct hal_module_info. */
    const char *sym = HAL_MODULE_INFO_SYM_AS_STR;
    hmi = (struct hw_module_t *)dlsym(handle, sym);
    //查找时是以自定义的xx_module_t类型的名称为HAL_MODULE_INFO_SYM的符号为依据的。
    //所以hmi实际指向了xx_module_t类型变量的地方,但是传出时是以hw_module_t类型传出的,所以就有强转的动作。
    if (hmi == NULL) {
        ALOGE("load: couldn't find symbol %s", sym);
        status = -EINVAL;
        goto done;
    }

    /* Check that the id matches */
    if (strcmp(id, hmi->id) != 0) {
        ALOGE("load: id=%s != hmi->id=%s", id, hmi->id);
        status = -EINVAL;
        goto done;
    }

    hmi->dso = handle;

    /* success */
    status = 0;

    done:
    if (status != 0) {
        hmi = NULL;
        if (handle != NULL) {
            dlclose(handle);
            handle = NULL;
        }
    } else {
        ALOGV("loaded HAL id=%s path=%s hmi=%p handle=%p",
                id, path, *pHmi, handle);
    }

    *pHmi = hmi;     //以hw_module_t 类型返回

    return status;
}

这里HAL层的库和平时使用的动态链接库有些不同,平时使用的动态链接库是在程序编译时指定,在程序运行之初就要通过dlopen、dlsym等库的操作接口加载的,如果找不到程序就会异常退出。而HAL层所编译出的库是通过上层访问时去寻找相应的库,找到后才通过dlopen、dlsym接口去打开库,找到所需的资源。这就像唐攀老师说的“杀鸡取卵”。

再补充一个一个对罗老师书中freg的HAL层代码的测试程序:
hal_freg_test.c

#include <hardware/hardware.h>
#include <hardware/freg.h>

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    struct hw_module_t* module;
    struct hw_device_t* device;
    struct freg_device_t*   dev;
    int     val = -1;
    int     ret = 0;

    if (argc > 2) {
        printf("Usage: %s <num>\r\n", argv[0]);
        return 0;
    }

    if (hw_get_module(FREG_HARDWARE_DEVICE_ID, (struct hw_module_t const **)&module) == 0){
        printf("get_modules success.\r\n");
    } else {
        printf("get_modules failed.\r\n");
        return -1;
    }

    if (module->methods->open(module, FREG_HARDWARE_MODULE_ID, &device) == 0) {
        printf("open modules success.\r\n");
    } else {
        printf("open modules failed.\r\n");
        return -1;
    }

    dev = (struct freg_device_t*)device;

    if (dev->get_val(dev, &val) != 0) {
        printf("get_val err.\r\n");
    } else {
        printf("get val: %d.\r\n", val);
    }

    if (argc == 2) {
        if (dev->set_val(dev, atoi(argv[1])) != 0) {
            printf("set val err.\r\n");
        } else {
            printf("set val ok.\r\n");
        }
    }

    dev->common.close(device);

    return 0;
}

Android.mk

LOCAL_PATH := $(call my-dir)                                                                                                 

include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := hal_freg_test
LOCAL_SHARED_LIBRARIES := libhardware
LOCAL_SRC_FILES := $(call all-subdir-c-files)
include $(BUILD_EXECUTABLE)

运行结果
这里写图片描述
基本是按照套路出牌的。

参考的系列博客:
唐攀博客:http://blog.csdn.net/mr_raptor/article/details/8074549
老罗博客:http://blog.csdn.net/luoshengyang/article/details/6567257
华清远见讲师博文:http://www.embedu.org/Column/Column339.htm

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值