How to write a Kernel module

A very very simple and rudimentary tutorial to know "How to write a kernel module". This is _no_ substitute for reading a good driver book/tutorial. This is just to give a launchpad for a novice to start on kernel programming.

Step 1: vi hello.c


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

static int hello_init(void)
{
        printk(KERN_ALERT "Hello World");
        return 0;
}

static void hello_exit(void)
{
        printk(KERN_ALERT "Goodbye World");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("YOUR NAME");


Step 2: vi Makefile

obj-m := hello-kernel.o
hello-kernel-objs := hello.o

Step 3: make -C /lib/modules/`uname -r`/build M=`pwd`
You should see hello-kernel.ko in your current directory, by now.

Step 4: sudo /sbin/insmod hello-kernel.ko

Step 5: dmesg

You should see "Hello World" here.

Step 6: lsmod | grep hello-kernel

Step 7: modinfo hello-kernel.ko

Step 8: sudo /sbin/rmmod hello-kernel.ko

Step 9: dmesg

You should see "Goodbye World" here.

4 comments:

Anonymous said...

Thanks a lot, this helps very much!

Just one questions: when I do it it says:


hello_kernel: module license 'GPLv2' taints kernel.
Disabling lock debugging due to kernel taint
Hello World


What's so wrong on GPLv2 ???

Sankar said...

Anon: You need add a space between v and L, like: "GPL v2". This will solve the problem. Thanks for letting me know of this. I will fix it in the post.

Appu said...

Hi sankar,
It Looks very Useful.
It is different from Native code in Bionic C libraries rite? can i use this tool to find memory leaks in Libraries? or is there any other method to do this?

Sankar said...

@Appu: I don't get what you mean by libraries. If you are referring to user space libraries like glib, then this method will not help you. It is applicable only for kernel space. For user space you need to use a tool like valgrind.

Leaks from glibc will also be reported by valgrind and I believe bionic should be no different.

However remember to pass --run-libc-freeres to suppress false leaks from glibc