EMN, INRIA, DIKU

Coccinelle - Semantic Patch Examples

This document describes a collection of semantic patches that we have used to find and fix bugs in the Linux kernel. Some of them are Linux specific, while others should be applicable to other software. It should be possible to use these examples as a starting point to solve other, similar, problems.

Making use of available macros

The kernel defines a number of generally useful macros. Some code however either uses the expansion of these macros directly, or defines local macros that do the same thing. To convert this code to use the existing abstractions, we define a semantic patch that has the form of the right-hand side of the macro, with some generalization.

Nonsensical or useless code

Occasionally, one finds code patterns that are just strange or unnecessary. A semantic patch can be used to see whether these patterns occur elsewhere. Some examples are:

Dereferences of NULL pointers

The first of the following semantic patches detects the general case where a pointer is dereferenced and then compared to NULL. Such a comparison is ineffective, because if the value is NULL the kernel has already crashed at the point of the dereference. The remaining semantic patches consider some frequent cases that are possible to fix automatically. Detecting other kinds of NULL pointer dereference problems is possible:

Dereferences of invalid pointers

Linux uses both NULL and values created using ERR_PTR to indicate a failed operation. A value created using ERR_PTR can also contain a negative integer giving some information about the kind of error that has occurred. This value can be extracted using PTR_ERR. Dereferencing a value created using ERR_PTR is invalid, and thus we can define rules similar to the ones for the NULL case.

Resource allocation

Resources that are allocated should be deallocated. Some resources, such as locks or mutexes, are typically acquired and released within a single function. Others, such as memory, are often held beyond the lifetime of the allocating function, but should be freed in an error situation. The semantic patches for finding resource allocation bugs are Linux specific, in that the API functions considered are specific to the Linux kernel. Nevertheless, these rules can easily be adapted to other APIs.

Updating API usage