Kernel drivers

I thought I would try and play with kernel drivers some. I found this site, and it was very helpful for getting started. I tried this out on a x86_64 box running Fedora 6. I created dirt simple module following the tutorial. I had one c file named “hello.c” with the following contents:

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

MODULE_LICENSE(”GPL”);

static int hello_init(void) {
printk(”<1> Hello world!\n”);
return 0;
}

static void hello_exit(void) {
printk(”<1> Bye, cruel world\n”);
}

module_init(hello_init);
module_exit(hello_exit);

The “Makefile” contained one line:

obj-m := hello.o 

I then used the following compile command:

 make -C /usr/src/kernels/2.6.20-1.2962.fc6-i586 M=`pwd` modules

Up to this point everything was working pretty much as the tutorial described. The problem came when I tried to load the module:

/sbin/insmod hello.ko

Resulting in the following error:

insmod: error inserting ‘hello.ko’: -1 Invalid module format

Upon further investigation I found my running kernel and my build kernel wern’t quite the same /proc/version reads  2.6.20-1.2944.fc6 which is different. I don’t know why Fedora didn’t install 2.6.20-1.2944.fc6 when I installed kernel-devel. You can also see this error in using dmesg. So how do you trick insmod to load the module anyway? You can’t, but you can trick modprobe. The problem with modprobe is it needs to know where your module is so you must add a line to /lib/modules/2.6.20-1.2944.fc6/modules.dep

/path_to_module_dir/hello.ko:

Now modprobe will work with the following command:

 /sbin/modprobe hello –force-vermagic

And you can unload it with:

 /sbin/rmmod hello

Now if you run dmesg it should show our entry and exit print statements.

Leave a Reply