Thursday 19 September 2013

LInux: A 'Hello World' linux kernel module

Well, in linux, a kernel module is a piece of kernel object code which can extend the functionality of a running kernel, on demand! Isn't it awesome, being able to get inside a running kernel! Here is a module which is over-simplistic and does nothing, well what else can you expect from 'hello world'.

#include <linux/module.h>

int init(void) {
  printk("Hello world!\n");
  return 0;
}

void exit(void) {
  printk("Goodbye world!\n");
}

MODULE_LICENSE("GPL");
module_init(init);
module_exit(exit);



Compiling a kernel module can be cumbersome. Here is a Makefile to compile the module.

ifneq ($(KERNELRELEASE),)
obj-m := hello_world.o 

else
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default: 
 $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules 
 rm -r -f .tmp_versions *.mod.c .*.cmd *.o *.symvers 

endif


This process can create a spectrum of files (I try to remove most of the useless ones'). The linux kernel module object code is in hello_world.ko.
Install the module with the command...

$ sudo insmod hello_world.ko

Look at the list of all modules currently in the kernel with the command...

$ lsmod

Remove the module with the command...

$ sudo rmmod hello_world

You can have a look at the kernel output, which also contains the output of printk()

$ dmesg | tail -2
[435766.953016] Hello world!
[435766.953017] Goodbye world!

2 comments: