WSL2 编译Linux内核模块
编译内核
简单版本:
cd WSL2-Linux-Kernel
cp Microsoft/config-wsl .config
make -j $(nproc)
详细版本请参考我之前的博客: Windows11 WSL2 Ubuntu编译安装perf工具
安装新的内核镜像
编译完成之后
- 拷贝
WSL2-Linux-Kernel/arch/x86_64/boot/bzImage
到Windows系统中%userprofile%\bzImage
. - 编辑WSL2配置文件:
%userprofile%\.wslconfig
,添加如下内容:
[wsl2]
kernel=C:\\Users\\WIN11_USER\\bzImage
注意上面的WIN11_USER
需要替换为你的Windows用户名.
注意必须使用两个反斜杠\\
. 两行的结尾不要有任何的空格.
- 重启WSL2, 打开PowerShell, 运行:
wsl --shutdown
- 重新打开WSL2.
编译自己的内核模块
在WSL2 的$home
目录下创建一个新的目录study-kernel
.
创建一个Makefile
文件:
obj-m += hello_world.o
all:
make -C ${HOME}/WSL2-Linux-Kernel M=$(shell pwd) modules
clean:
make -C ${HOME}/WSL2-Linux-Kernel M=$(shell pwd) clean
创建一个hello_world.c
文件:
#include<linux/module.h>
#include<linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arong Xu");
MODULE_DESCRIPTION("A simple hello world module");
MODULE_VERSION("0.01");
static int __init hello_mod_init(void) {
printk(KERN_ALERT "Hello world from kernel!! \n");
return 0;
}
static void __exit hello_mod_exit(void) {
printk(KERN_ALERT "Exiting hello world module from kernel !!!\n");
}
module_init(hello_mod_init);
module_exit(hello_mod_exit);
安装内核模块
- 为了观察打印, 首先清空内核日志:
sudo dmesg -C
- 安装编译好的内核模块:
sudo insmod hello_world.ko
- 观察安装过程打印:
[ 1609.505562] Hello world from kernel!!
- 卸载内核模块:
sudo rmmod hello_world
- 观察卸载过程打印:
[ 1642.989547] Exiting hello world module from kernel !!!