Linux kernel 模块开发&构建学习

主要是学习下kernel 模块的玩法,代码来自社区

简单kernel 代码

  • hello_world.c
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
 printk(KERN_ALERT "Hello, world\n");
 return 0;
}
static void hello_exit(void)
{
 printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit); 
  • Makefile
ifneq ($(KERNELRELEASE),)
 
# In kbuild context
module-objs := hello_world.o
obj-m := hello_world.o
 
CFLAGS_hello_world.o := -DDEBUG
 
else
# In normal make context
KDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
 
.PHONY: modules
modules:
    $(MAKE) -C $(KDIR) M=$(PWD) modules
 
.PHONY: clean
clean:
    $(MAKE) -C $(KDIR) M=$(PWD) clean
 
endif

构建

因为使用的是mac 系统,构建需要一个linux 虚拟机,我使用了centos的,对于虚拟机的启动基于了utm 工具,具体
创建虚拟机部分可以参考相关文章,或者utm官方文档,同时因为默认的内核没开启共享,所以只能使用scp 工具了
对于创建的虚拟机同时使用默认的网络策略

  • 虚拟机环境准备
    需要安装kernel 开发包以及gcc 编译工具
 
yum install kernel-devel-$(uname -r) gcc -y
  • 拷贝文件

可以使用scp

 

  • 构建
 
cd /opt/kernel
make

 

  • 加载内核模块
insmod ./hello_world.ko

日志

 

查看加载的模块

  • 卸载模块
 
rmmod  hello_world

说明

以上是一个简单的内核模块编译以及加载学习,同时也包含了如何进行构建

参考资料

https://github.com/d0u9/Linux-Device-Driver/tree/master/eg_01_hello_world
https://github.com/martinezjavier/ldd3
https://docs.getutm.app/guest-support/linux/#drivers
https://github.com/PacktPublishing/Linux-Device-Drivers-Development
https://www.cnblogs.com/rongfengliang/p/17362332.html
https://virtio-fs.gitlab.io/
https://www.kernel.org/doc/html/v5.9/driver-api/driver-model/driver.html
https://virtio-fs.gitlab.io/design.html
https://libvirt.org/kbase/virtiofs.html
https://github.com/libfuse/libfuse
https://github.com/oasis-tcs/virtio-spec

posted on 2023-04-28 18:38  荣锋亮  阅读(65)  评论(0编辑  收藏  举报

导航