Skip to content

eBPF-based security platform

coccinelle: refuse a dereference in the branch that found NULL

Daniel Borkmanna868d1055f13
diff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rst
index 7b127914..3e247112 100644
--- a/Documentation/contribute/code/developer-guide.rst
+++ b/Documentation/contribute/code/developer-guide.rst
@@ -551,6 +551,9 @@ can rewrite what it finds does so with ``-D patch``:
copies.
* - ``test_after_use``
- A pointer tested for NULL after its use.
+ * - ``null_deref``
+ - A pointer dereferenced in the branch of the test that found it
+ NULL.
* - ``alloc_unchecked``
- An allocation used before it is checked.
* - ``use_after_free``
diff --git a/testing/coccinelle/null_deref.cocci b/testing/coccinelle/null_deref.cocci
new file mode 100644
index 00000000..2e7b8a56
--- /dev/null
+++ b/testing/coccinelle/null_deref.cocci
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// A pointer dereferenced in the branch of the test that found it NULL,
+// before anything gave it another value: usually the error message or
+// the cleanup of the failure that the test was there to catch. An
+// operand of sizeof is not evaluated and does not count.
+
+virtual report
+
+@unevaluated@
+expression E;
+identifier fld;
+position p;
+@@
+sizeof(<+... \(E@p->fld\|*E@p\) ...+>)
+
+@r exists@
+expression E, E1;
+identifier fld;
+position p != unevaluated.p;
+@@
+if (\(E == NULL\|!E\)) {
+ ... when != E = E1
+ when != &E
+(
+ E@p->fld
+|
+ *E@p
+)
+ ... when any
+}
+
+@script:python depends on report@
+p << r.p;
+@@
+coccilib.report.print_report(p[0], "dereferenced in the branch that found it NULL")