How to create a basic Linux Kernel Module.
A LKM is like a .so library, and can run kernel-land.
Writting your own kernel module will help you to understand how the system works and make you think about mallocing in the kernel twice before running the code.
Code#
Here is the bare minimum you have to code to get a working LKM:
 1#include <linux/module.h>
 2#include <linux/kernel.h>
 3
 4// Specify module licence, GPL to not taint the kernel
 5MODULE_LICENSE("GPL");
 6
 7// Called on module load
 8int init_module(void) {
 9  printk(KERN_INFO "MODULE loaded!\n");
10  return 0;
11}
12
13// Called on module unload
14void cleanup_module(void) {
15  printk(KERN_INFO "MODULE unloaded!\n");
16}
Compile#
The Makefile I use for my modules:
 1obj-m += my_module.o
 2
 3all:
 4    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
 5
 6install:
 7    sudo insmod ./my_module.ko
 8
 9uninstall:
10    sudo rmmod my_module
11
12clean:
13    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Then just run make. A new my_module.ko should be here, this is your kernel module.
Install#
1sudo insmod ./my_module.ko
2# or
3make install
In dmesg you should have a new line containing MODULE loaded!. Your module is loaded in the kernel.
Uninstall#
1sudo rmmod my_module
2# or
3make uninstall
In dmesg you should have a new line containing MODULE unloaded!. Your module is deleted form the kernel.
MISC#
- dmesg -Cwill clear the dmesg buffer
- watch 'dmesg | grep MODULE'will append the new messages of the module so you don’t have to re-run the command
Afterwords#
Starting to create a kernel module is pretty easy, you just have to be careful with the functions you call and how you code them. There are a lot of specific functions for the kernel only, and you must check them out before using them.
In the future I will discuss more about the internals of Linux and why using a kernel module is insanely powerfull and at the same time a pain to code.
