主体

新建文件夹 hello

- hello
  - Makefile
  - hello.c

Makefile 内容如下, 注意 ARCHCROSS_COMPILE 变量,其中 KERNEL_MODULES 是你编译内核项目的根目录

# set current value in your machine
ARCH=arm64
KERNEL_MODULES=../linux-6.14.6
CROSS_COMPILE=/home/cyang/Templates/qemu/aarch64--musl--stable-2024.05-1/bin/aarch64-buildroot-linux-musl-

	export ARCH CROSS_COMPILE

obj-m += hello.o

all:
	${MAKE} -C ${KERNEL_MODULES} M=$(PWD) modules

clean:
	${MAKE} -C ${KERNEL_MODULES} M=$(PWD) clean

hello.c 内容如下

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>

static int __init hello_init(void) {
  printk(KERN_INFO "Hello, World!\\n");
  return 0;
}

static void __exit hello_exit(void) { printk(KERN_INFO "Goodbye, World!\\n"); }

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("MIT");

执行 make 即可编译

image.png

测试一下

你可以通过ssh上传 hello.ko 文件。或者宿主使用 python -m http.server 搭建简易 http 服务,虚拟机通过 wget http://<宿主机ip>:8000/hello.ko 下载。

# use doas replace sudo
doas insmod hello.ko
doas rmmod hello.ko

通过 dmesg 命令查看内核日志。成了,嘿嘿嘿。

image.png

refs