Interesting Usages in Kernel Code

Interesting usages in kernel code

 

1. #define re-usable struct, function combination using  ##<identifier>##

A set of steps can be common for different entities. Example, when a file_operation structure and related (like open, release, etc) calls, repeatedly used in multiple places in the code, we can define a macro with all the common statements with a unique ##<identifier>## as a distinguishing factor. This will help to have a clean code.

#include <linux/module.h>

#define MOD_GENERIC_FUNCTION(gen_var) \
struct generic_##gen_var##_mod { \
 int k; \
}; \
void init_##gen_var##_mod(void)\
{ \
 struct generic_##gen_var##_mod gv; \
 gv.k = 10;\
 printk ( "%d\n",gv.k);\
}

MOD_GENERIC_FUNCTION(fun1);


int test_init(void)
{
 init_fun1_mod();
 printk(KERN_INFO "Welcome!\n");
 return 0;
}

void test_exit(void)
{
 printk(KERN_INFO "bye!\n");
}

module_init(test_init);
module_exit(test_exit);

MODULE_DESCRIPTION("Test Module");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Soorej");

To get more clarity on this, compile this with the following make flags.

make -C /usr/lib/modules/$(shell uname -r)/build M=$(shell pwd) modules EXTRA_CFLAGS=’-save-temps’

This will generate the intermediate files .i and .s files. The files will be available in

/usr/lib/modules/<kernel-v>/build as <your_module_name>.i

in this file, almost at the end:

# 14 “/root/modules/modname/test.c”
struct generic_fun1_mod { int k; }; void init_fun1_mod(void){ struct generic_fun1_mod gv; gv.k = 10; printk ( “%d\n”,gv.k);};

int test_init(void)
{
init_fun1_mod();
printk(“\001″ “6” “Welcome!\n”);
return 0;
}

void test_exit(void)
{
printk(“\001″ “6” “bye!\n”);
}

Happy coding.. Let me know your opinions and suggestions in comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × 3 =