EXPORT_SYMBOL解析 (一)

2014-11-23 23:30:19 · 作者: · 浏览: 18

一般我们编写C程序时,要调用某个文件中的函数,需要在本文件中包含声明有被调用函数的头文件,然后编译连接后,方能找到调用函数。对于模块依赖的情况,不能简单的使用上面的方法,内核提供了一个机制,就是EXPORT_SYMBOL标签内定义的函数或者符号对全部内核代码公开,不用修改内核代码就可以在您的内核模块中直接调用,即使用EXPORT_SYMBOL可以将一个函数以符号的方式导出给其他模块使用。您还可以手工修改内核源代码来导出另外的函数,用于重新编译并加载新内核后的测试。


[cpp]
include/module.h:

struct kernel_symbol
{
unsigned long value;
const char *name;
};
/* For every exported symbol, place a struct in the __ksymtab section */
#define __EXPORT_SYMBOL(sym, sec) \
__CRC_SYMBOL(sym, sec) \
static const char __kstrtab_##sym[] \
__attribute__((section("__ksymtab_strings"))) \
= MODULE_SYMBOL_PREFIX #sym; \
static const struct kernel_symbol __ksymtab_##sym \
__attribute_used__ \
__attribute__((section("__ksymtab" sec), unused)) \
= { (unsigned long)&sym, __kstrtab_##sym }

#define EXPORT_SYMBOL(sym) \
__EXPORT_SYMBOL(sym, "")

#define EXPORT_SYMBOL_GPL(sym) \
__EXPORT_SYMBOL(sym, "_gpl")

#endif

include/module.h:

struct kernel_symbol
{
unsigned long value;
const char *name;
};
/* For every exported symbol, place a struct in the __ksymtab section */
#define __EXPORT_SYMBOL(sym, sec) \
__CRC_SYMBOL(sym, sec) \
static const char __kstrtab_##sym[] \
__attribute__((section("__ksymtab_strings"))) \
= MODULE_SYMBOL_PREFIX #sym; \
static const struct kernel_symbol __ksymtab_##sym \
__attribute_used__ \
__attribute__((section("__ksymtab" sec), unused)) \
= { (unsigned long)&sym, __kstrtab_##sym }

#define EXPORT_SYMBOL(sym) \
__EXPORT_SYMBOL(sym, "")

#define EXPORT_SYMBOL_GPL(sym) \
__EXPORT_SYMBOL(sym, "_gpl")

#endif
下面是这种方法是演示:

\vc29uYmFp/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" />


第一个模块文件如下:

[lingyun@localhost export_symbol]$ ls
mod1 mod2
[lingyun@localhost export_symbol]$ cd mod1/
[lingyun@localhost mod1]$ ls
Makefile mod_a.c
[lingyun@localhost mod1]$ vim mod_a.c
mod_a.c

[cpp]
/*********************************************************************************
* Copyright: (C) 2013 fulinux
* All rights reserved.
*
* Filename: mod_a.c
* Description: This file
*
* Version: 1.0.0(07/12/2013~)
* Author: fulinux
* ChangeLog: 1, Release initial version on "07/12/2013 10:06:50 AM"
*
********************************************************************************/


#include
#include
#include


static int func1(void)
{
printk("In Func: %s...\n",__func__);
return 0;
}
EXPORT_SYMBOL(func1);


static int __init hello_init(void)
{
printk("Module 1, Init!\n");
return 0;
}


static void __exit hello_exit(void)
{
printk("Module 1, Exit!\n");
}


module_init(hello_init);
module_exit(hello_exit);


MODULE_LICENSE("GPL");

/*********************************************************************************
* Co