Static Analysis of Linux Kernel & Drivers Using Clang


Clang is usually quite straightforward to use, but only for simple C/C++ programs that do not have a complex build process. The Linux kernel, however, is a completely different beast with its own custom build system, Kbuild.

This post demonstrates one (rather hackish) way to apply your Clang static analysis programs to the Linux kernel and Linux drivers, even if the modules are outside of the main Linux source tree.


Clang Tutorial Part III: Plugin Example

Introduction to Clang Plugins

As mentioned in Part I of this tutorial, a Clang Plugin is similar to the LibTooling environment, except that it cannot reason about multiple source files (among other differences). In other words, it cannot remember details of more than one source file at a time, so keeping track of information about several source files (with something like global variables) is impossible.

That being said, there are instances when a Clang Plugin is still useful, like a syntax checker or formatting helper. As such, here’s how to build one that does the exact same thing as our LibTooling example from Part II.


Clang Tutorial Part I: Introduction

What is Clang?

I’ve spent the last few months working with Clang, a frontend for the LLVM compiler project. Clang can parse and analyze any source code in the C language family (C, C++, ObjectiveC, etc…) and has a wonderful modular design that makes it easy to use.

If you’re looking to do static analysis on some C code, I highly recommend Clang — it’s vastly superior to other static analysis tools (like CIL … yuck!) and has decent documentation. Also, the Clang mailing list is very active and helpful if you ever find yourself stuck on something.

I personally used Clang to perform static analysis on I/O device drivers in the Linux kernel, including camera drivers and DRM drivers for graphics cards. Kernel code (especially drivers) can be very complex and difficult to analyze, but Clang allows you to handle it with ease. Let’s take a look at what you can do with Clang.