首页 > 解决方案 > 我无法从内核 5.10.11 构建简单的 hello world 内核模块

问题描述

我在 KALI 中使用内核 5.10.11,我正在尝试学习内核模块编程,但我无法构建模块。我已经尝试了互联网上给出的所有解决方案,但它们对我不起作用,或者我做错了。

这是我的c文件

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

static int helloWorld_init(void)
{
    printk(KERN_DEBUG "Hello World!\n");
    return 0;
}

static void helloWorld_exit(void)
{
    printk(KERN_DEBUG "Removing Module\n");
}

module_init(helloWorld_init);
module_exit(helloWorld_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mukul Mehar");
MODULE_DESCRIPTION("first kernel module");

和Makefile:

obj-m += helloWorld.o
KDIR = /usr/src/linux-headers-5.10.11/ 

all:
    make -C $(KDIR) M=$(shell pwd) modules 

clean:
    make -C $(KDIR) M=$(shell pwd) clean

我收到的输出是:

make -C /usr/src/linux-headers-5.10.11/  M=/home/mukul/Documents/Eudyptula/challenge-1 modules 
make[1]: Entering directory '/usr/src/linux-headers-5.10.11'
make[2]: *** No rule to make target '/home/mukul/Documents/Eudyptula/challenge-1/helloWorld.o', needed by '/home/mukul/Documents/Eudyptula/challenge-1/helloWorld.mod'.  Stop.
make[1]: *** [Makefile:1805: /home/mukul/Documents/Eudyptula/challenge-1] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-5.10.11'
make: *** [Makefile:7: all] Error 2

标签: linux-kerneleudyptula-challenge

解决方案


您是否尝试过Kbuild方法?

在与helloworld.c相同的目录中创建一个名为Kbuild的文件,其内容如下:

obj-m += helloworld.o

从同一目录启动构建:

$ make -C /lib/modules/`uname -r`/build M=`pwd`
make: Entering directory '/usr/src/linux-headers-5.4.0-65-generic'
  CC [M]  .../helloworld.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC [M]  .../helloworld.mod.o
  LD [M]  .../helloworld.ko
make: Leaving directory '/usr/src/linux-headers-5.4.0-65-generic'
$ ls -l helloworld.ko
-rw-rw-r-- 1 xxxx xxxx 4144 janv.  31 14:50 helloworld.ko

然后,使用insmod/rmmod将模块加载/卸载到内核中/从内核中卸载:

$ sudo insmod helloworld.ko
$ dmesg
[16448.154266] Hello World!
$ sudo rmmod helloworld.ko
$ dmesg
[16448.154266] Hello World!
[16497.208337] Removing Module

推荐阅读