Creating a Kernel Module needs 4 things:
- Some basic understanding of Kernel space and user space.
- Another tab open of linus-torvalds github repo of a header which you want to use and test macros.
- Linux headers installed from your package manager.
- And lastly some love :)
To compile the kernel code you are about to write, you will need the linux kernel headers which can be installed using the following command:
sudo apt-get install linux-headers-$(uname -r) (If you are using apt)
sudo dnf install kernel-headers-$(uname -r) (If you are using dnf)
Compiling Kernel Code is not as simple as just running:
gcc my_kernel_module.c
We need to use the build present in the kernel header that you installed!
So to compile kernel code you need to run the command:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
And to remove all the kernel module and accessory stuff built you need to run the command:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
This can be a bit of a headache so we write a Makefile that goes like this:
obj-m += .oall:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Now we can compile kernel code using the command: make
Write some code related to macros and structures already present in some linux headers. Refer to my_module.c in list_processes directory for example.
Compile the C Code that you have typed by running the command: make
New files will be created after compiling like this:
The one you are looking for is <your C file name without .c extension>.ko
To load the Kernel Module, run the command: sudo insmod .ko
Nothing happened?
Well run the command: dmesg
There it is!