Matching usage of bool variables

In this example we write a semantic patch to match the uses of a variable having a user defined type. This tutorial explains how to name rules. We introduce two metavariable types, namely typedef and idexpression. Here we will be studying the following patch:

typedef bool;
idexpression bool id;
* id

You can name a rule by writing the name between the first two “@”‘s of rule definition. Here, we give the rule the name “find_usage”.

The Linux kernel defines a type for boolean variables but Coccinelle is not aware that “bool” is a type. To inform Coccinelle that it is a type, we declare it with typedef, as shown in the semantic patch. These declarations are global to the semantic patch. They should be made only once.

“idexpression” is an expression that has the same form as an identifier. Note that an “idexpression” can’t be used to match a declaration or a function name. It is possible to impose type constraints to expressions with Coccinelle. Here, for instance, we restrict the metavariable to be of type bool.

Finally, the last line indicates that we want to match any reference to a variable that meets the type restriction we just specified.

The sample that we are going to apply our semantic patch to is the following:

struct mystruct {
	bool field1;
	char field2;
int f1() {
	char foo = 0;
	bool bar = true;
	return foo;
int f2() {
	int foo;
	bool bar;
	foo = 0;
	bar = false;
	return foo;

And finally the result is:

--- tuto01.c
+++ /tmp/cocci-output-28697-6c6925-tuto01.c
@@ -13,6 +13,5 @@ int f2() {
 	int foo;
 	bool bar;
 	foo = 0;
-	bar = false;
 	return foo;

Note that declarations and initializations are not matched.
The reason for that is that in Coccinelle, declaration, initialiser and expression are different types.