Wednesday 4 July 2018

Linux Kernel Module Helloworld Program


I was following the awesome tutorial The Linux Kernel Module Programming Guide until I compiled it and couldn't get it work. So I will just list the steps I did.

Step 1: coding

/*  
 *  hello-1.c - The simplest kernel module.
 */
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */

int init_module(void)
{
 printk(KERN_INFO "Hello world 1.\n");

 /* 
  * A non 0 return means init_module failed; module can't be loaded. 
  */
 return 0;
}

void cleanup_module(void)
{
 printk(KERN_INFO "Goodbye world 1.\n");
}

Step 2: Makefile

obj-m += hello-1.o

all:
 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean


Step 3: compile
$ make
make -C /lib/modules/3.19.0-25-generic/build M=/home/boris/workspace/TheLinuxKernelModuleProgrammingGuide/hello-1 modules
make[1]: Entering directory `/usr/src/linux-headers-3.19.0-25-generic'
  Building modules, stage 2.
  MODPOST 1 modules
make[1]: Leaving directory `/usr/src/linux-headers-3.19.0-25-generic'

Step 4: Insert the module
sudo insmod ./hello-1.ko

Step 5: 
$ cat /proc/modules
hello_1 16384 0 - Live 0x00000000 (POE)    <====== here it is!
cp210x 24576 0 - Live 0x00000000
usbserial 40960 1 cp210x, Live 0x00000000
ctr 16384 1 - Live 0x00000000
ccm 20480 1 - Live 0x00000000
rfcomm 61440 0 - Live 0x00000000
...
...


Step 6: 
$ dmesg
...
...
[ 8741.483837] hello_1: module license 'unspecified' taints kernel.
[ 8741.483841] Disabling lock debugging due to kernel taint
[ 8741.483881] hello_1: module verification failed: signature and/or  required key missing - tainting kernel
[ 8741.484112] Hello world 1.


Step 7:
$ cat /var/log/syslog | grep hello
Jul  4 21:07:34 boris-XYZ kernel: [ 8741.483837] hello_1: module license 'unspecified' taints kernel.
Jul  4 21:07:34 boris-XYZ kernel: [ 8741.483881] hello_1: module verification failed: signature and/or  required key missing - tainting kernel

Step 8:
$ sudo rmmod hello-1
$ dmesg
...
...
[ 8741.483837] hello_1: module license 'unspecified' taints kernel.
[ 8741.483841] Disabling lock debugging due to kernel taint
[ 8741.483881] hello_1: module verification failed: signature and/or  required key missing - tainting kernel
[ 8741.484112] Hello world 1.
[ 9291.123571] Goodbye world 1.


ref:
https://www.tldp.org/LDP/lkmpg/2.6/html/x121.html
https://blog.csdn.net/fantasy_wxe/article/details/12379647
https://blog.csdn.net/zhangyifei216/article/details/49703435

No comments:

Post a Comment