Skip to content

n1haldev/Basic-Kernel-Modules

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 

Repository files navigation

Creating a basic Kernel Module

Creating a Kernel Module needs 4 things:

  1. Some basic understanding of Kernel space and user space.
  2. Another tab open of linus-torvalds github repo of a header which you want to use and test macros.
  3. Linux headers installed from your package manager.
  4. And lastly some love :)

Steps to follow:

1. Installing Linux Kernel Headers:

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)

2. Creating a Makefile:

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 += .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

Now we can compile kernel code using the command: make

3. Time to write some Code:

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.

4. Compile the code!

Compile the C Code that you have typed by running the command: make

5. Wow so many new files!

New files will be created after compiling like this:

image

The one you are looking for is <your C file name without .c extension>.ko

6. Loading the Kernel Module:

To load the Kernel Module, run the command: sudo insmod .ko

7. dmesg is key!

Nothing happened? Well run the command: dmesg
There it is!

image

Releases

No releases published

Packages

No packages published