This transcript is unfinished

I'm making explainer videos to put up on youtube. As part of the process, I have to write little scripts for myself. So, I figured "why not just put them up on my website?"

Well, that's what you see here. Enjoy.

Hello World Kernel Module


We've talked about the entry points to the Linux kernel. Whenever an interrupt is triggered, the kernel regains control of the CPU. It's important to remember that a user program can trigger an interrupt with a special instruction; this is what a "system call" is.

To write a Linux driver requires two more things: 1) we need to get our compiled code added into kernel memory, and 2) we need to get the kernel to jump to our code. This video deals with the first job, and the next video will deal with the second.

At this point, it's important to understand what a "shared object" is (called "DLL"s in Windows). I'll do a brief refresher right now.

The whole point of "compiling" code is to translate code written in C into executable machine code (in other words, the raw instruction bits that the CPU will consume). In your code, sometimes you will call library functions (such as printf); the machine code for the library functions must also end up in your final executable. There are two ways to do this:

One method is called static linking. This means looking up the printf machien code and copy-pasting it into your program's executable. There's nothing wrong with this method, but there is a better way.

The other method is called dynamic linking. Instead of creating a final, complete executable, your program will have "unresolved references" in it. The result is a file in a VERY specific format, called an object file. (These are the .o files you get when you compile C code) which is basically a list of unresolved functions along with the machine code from your own program. When the OS loads your program at runtime, it will copy your program's machine code into memory, and then it will satisfy all the references to other functions. This involves tweaking the jump addresses in your machine code.

Well, that's all I'm gonna say about it. There's more to dynamic linking than that, but it's enough for us to start writing kernel code.

Our goal will be to write a kernel module. This is basically the same thing as an object file, except it gets loaded into kernel memory, and its references must be to other kernel functions. We'll use the insmod and rmmod commands to load and unload our module on a running kernel.