Kernel - 1

25 Oct 2020

Kernel land is full of wonders and treasure and is the land of freedom in its truest form. As I left my home town - peaceful user land to embark on this adventure, I thought keeping a journal to record the various extraodinary phenomenons of the mystical land is a good way to keep my sanity from drifting away…

The Elders’ Scrolls

Many legendary adventurers have explored this sacred land before and provided useful scrolls (maps/directions) for new commers. I found these scrolls to be useful:

It’s been around two weeks since I ventured into the unknown. Here’s my first journal entry…

Journal Entry #1 - Around Two Weeks

Tapping Into The Kernel

To get started with inner workings of the kernel, writing kernel modules is a good idea.

Here’s a template of a kernel module, closely resembling one provided by the Linux Kernel Workbook.

mymodule.c

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

static int __init my_init(void) {
  printk(KERN_INFO "Loading mymodule\n"); //Remember to add \n to make `dmesg` prints messages as expected
  return 0;
}

static void __exit my_exit(void) {
  printk(KERN_INFO "Cleaning up mymodule\n")
}

module_init(my_init);
module_exit(my_exit);

MODULE_DESCRIPTION("Sample Hello World Module");
MODULE_AUTHOR("Rishi Agrawal <rishi.b.agrawal@gmail.com>");
MODULE_LICENSE("GPL");

Makefile

MODULE_FILENAME=mymodule

obj-m +=  $(MODULE_FILENAME).o
KO_FILE=$(MODULE_FILENAME).ko

export KROOT=/lib/modules/$(shell uname -r)/build

modules:
        @$(MAKE) -C $(KROOT) M=$(PWD) modules

clean: 
        @$(MAKE) -C $(KROOT) M=$(PWD) clean
        rm -rf   Module.symvers modules.order

insert: modules
        sudo insmod $(KO_FILE)
        sudo dmesg -c

remove:
        sudo rmmod $(MODULE_FILENAME)
        sudo dmesg -c

What Kernel Functions/Variables are Available in Kernel Module?

I’ve found these are generally available to be used in a kernel module code:

  1. Marked as ‘T’ or ‘D’ in /proc/kallsyms
  2. Defined in kernel code (provided you include appropriate header files)

For example: task_struct is defined in include/linux/sched.h. Therefore, by #include <linux/sched.h>, I can now use it in my kernel module.

Useful Snippets

I have also made a few more interesting encounters but decided to end this entry here because it’s late and I need to rest tomorrow’s journey starts early…