I/O Kit & Kernel Extension Tutorial: Part 1 of 1001

Introduction

This is part one of a not known how long series of tutorials for programming the Darwin/OS X I/O Kit Kernel Extensions. New episodes will be available at nice time intervals.

Code will look like this, and should be fixed width.
if (a < b) {
    eat_fish(cod);
}

This will be open for questions and comments, and I absolutely encourage all to not be shy. I do not guarantee any accuracy here, and everything is provided as it is.

We will start with the theory first.

Kernel Extensions

There are different kinds of kernel extensions (kexts) used in Mac OS X, but we will talk about I/O Kit here. As the name implys it is basically for input/output, i.e. device drivers. But also for internal system devices.

Basically, you should not use the kext interface. And that’s it. So why write these tutorials? Because there is also a but… but unless… you have to. If you have programmed in user space, you know that kernel layer is not easily accessible, you also have a wide variety of failguards to protect the system if your software has bugs or behave badly. When programming kext, you are in the kernel level. There are no protection mechanisms at all. Except for the kernel panic, which is very rudimentary and fatal protection. Any single mistake in your software will bring down the system if you are lucky, else it will make it unstable and in worst case in a state it may damage or put the system in a volunerable postition for virus, hacking etc.

So, you are still willing to try? Ok. I/O Kit is object oriented, programmed in a limited C++ subset. So knowledge of OO and C++ is a big bonus. You may not use exceptions, not multiple inheritance, no templates and runtime type information have its own custom implementation. All I/O Kit objects are based on base object OSMetaClass, but basically you will start your driver classes from some of the apple provided device base classes, or IOService.  But fear not if you only have C knowledge or only have a c-source you want to use, it is possible to use c as well. But this tutorial will be using mostly C++.

If you are coming from linux or bsd background, it may take some time to adapt to the dynamic and automatic features of the I/O Kit, but once known you will realize how outdated the driver model in those systems are! Also the object oriented approach may be difficult to grasp at first, but I am sure you will quickly understand.

For more detailed information about I/O Kit, I recommend to read through I/O Kit Fundamentals on http://developer.apple.com/

Next time I will look at matching and Info.plist…