3.18 内核模块加载机制
c代码
/* C file */
/************************************************
* Copyright(C) zhaixue.cc. All rights reserved
*
* Filename: hello.c
* Author: litao.wang
* E-mail: 3284757626@qq.com
* Description:
* Create: 2017-09-21 06:59:57
* Last Modified: 2017-09-21 07:00:08
************************************************/
#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("GPL");
static int hello_init(void)
{
printk("-----------------!\n");
printk("hello world!\n");
printk("-----------------!\n");
return 0;
}
static void __exit hello_exit(void)
{
printk("-----------------!\n");
printk("Goodbye, cruel world!\n");
printk("-----------------!\n");
}
module_init(hello_init);
module_exit(hello_exit);
makefile
.PHONY:all clean
ifneq ($(KERNELRELEASE),)
obj-m := hello.o ##要编译的文件
else
KDIR := /lib/modules/4.4.0-96-generic/build #编译路径
all:
make -C $(KDIR) M=$(PWD) modules
//
clean:
rm -fr .*.cmd *.ko *.o *.mod.o *.mod.c *.symvers *.order .*.ko .tmp_versions
rm -fr .*.cmd
endif
make -C和M=的作用
当make的目标为all时,
-C $(KDIR) 指明跳转到源码目录下读取那里的Makefile;
M=$(PWD) 表明然后返回到当前目录继续读入、执行当前的Makefile.
模块命令
insmod hello.ko
lsmod
rmmod
内核打印
dmesg
echo 7 > /proc/sys/kernel/printk
加载的同时追踪系统调用
strace insmod hello.ko
模块加载实现
由系统调用init_module完成
Kernel/module.c/init_module
- 拷贝到内核:copy_module_from_user
- 地址空间分配:layout_and_allocate
- 符号解析:simplify_symbols
- 重定位:apply_relocations
- 执行:complete_formation