Previous Next Table of Contents

3. Differences between kernel and userland hacking

One of the first things you should learn is that there is no "libc" in the kernel one can use for kernel hacking. There are several reasons for this: it would be a kernel bloat, many libc function implementations are not doable the same way in the kernel, many of the libc functions would be never used. Fortunately, there is a huge set of functions you are used to from userland, which have their kernel counterparts. This includes mainly string and memory operations, like strcpy, strcmp, strlen, ..., memcpy, memset, memcmp, ..., sprintf, vsprintf. The printf function has been replaced by the printk function, so keep this in mind when writing kernel code.

Another thing to keep in mind is you should not use FPU registers in the kernel, unless special care is taken. This means e.g. your kernel C code should not use variables of types "float", "double" or "long double". The FPU is usually owned by a user process and saved only during a context switch (with lazy math only during some context switches), so unless you take care of saving the FPU state, you should not touch it.

You should consider stack usage a very important thing during your kernel programming. Kernel stack is very limited (usually to two pages, but some part of this two page space is used for task_struct and other things). So try to avoid using large arrays as local variables, don't use alloca and try to avoid recursion. If you need some recursion, always make sure the recursion depth is limited, so that even if an interrupt comes and takes a huge portion from the stack, data below the stack does not get corrupted. There are some patches which check the maximum stack usage and tell you if you eat too much. But if you try to be stack friendly, you won't need such tools in your daily hacking.

One nice thing in the kernel is that, unlike in userland, you won't get preempted, unless you allow it (e.g. call some function which sleeps). It would be very difficult to program in the kernel if the above was not true.

Previous Next Table of Contents