eBPF-based security platform
testing: keep the tree free of known bad patterns with Coccinelle
Daniel Borkmannb733fa117d02
diff --git a/.github/scripts/check-coccinelle.sh b/.github/scripts/check-coccinelle.shnew file mode 100755index 00000000..21671eb2--- /dev/null+++ b/.github/scripts/check-coccinelle.sh@@ -0,0 +1,77 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# .github/scripts/check-coccinelle.sh -- run the semantic patches in+# testing/coccinelle over the C the project writes and fail on any match:+# each one describes a pattern the tree is kept free of, and reports+# file:line: message where it finds the pattern again.+#+# .github/scripts/check-coccinelle.sh [<rule>...]+#+# The rules that can rewrite what they find do so with -D patch:+#+# spatch -D patch --sp-file testing/coccinelle/<rule>.cocci \+# --in-place --include-headers <file>...+#+# Runs from anywhere inside the checkout and needs spatch, Coccinelle+# built with Python, as Debian and Ubuntu ship it.++set -eu++cd "$(git rev-parse --show-toplevel)"+command -v spatch >/dev/null 2>&1 || {+ printf 'check-coccinelle: spatch not found; install coccinelle\n' >&2+ exit 2+}++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT++# The C the project writes, as check-style.sh takes it: not the vendored+# libbpf, not the BTF dumps and not the generated headers.+git ls-files -- '*.c' '*.h' ':(exclude)vendor/' ':(exclude)*vmlinux.h' \+ ':(exclude)*_generated.h' >"$work/files"++if [ $# -eq 0 ]; then+ set -- testing/coccinelle/*.cocci+fi++jobs=${COCCI_JOBS:-$(nproc 2>/dev/null || echo 1)}+bad=0+for rule in "$@"; do+ case $rule in+ *.cocci) ;;+ *) rule=testing/coccinelle/$rule.cocci ;;+ esac+ name=$(basename "$rule" .cocci)+ # Each file on its own, so that one Coccinelle cannot parse costs only+ # that file, and in parallel.+ xargs -P "$jobs" -n 16 spatch -D report --very-quiet --no-includes \+ --include-headers --sp-file "$rule" <"$work/files" \+ >"$work/$name.out" 2>"$work/$name.err" || {+ cat "$work/$name.err" >&2+ printf 'check-coccinelle: %s: spatch failed\n' "$name" >&2+ bad=$((bad + 1))+ continue+ }+ sort -u "$work/$name.out" >"$work/$name.sorted"+ [ -s "$work/$name.sorted" ] || continue+ bad=$((bad + 1))+ while IFS= read -r line; do+ printf '%s: %s\n' "$name" "$line" >&2+ if [ -n "${GITHUB_ACTIONS:-}" ]; then+ f=${line%%:*}+ rest=${line#*:}+ l=${rest%%:*}+ printf '::error file=%s,line=%s::%s: %s\n' "$f" "$l" \+ "$name" "${line#*: }"+ fi+ done <"$work/$name.sorted"+done++if [ "$bad" -gt 0 ]; then+ printf 'check-coccinelle: %d of %d rules matched\n' "$bad" "$#" >&2+ exit 1+fi+printf 'check-coccinelle: %d rules, no match\n' "$#"diff --git a/.github/scripts/check-spdx.sh b/.github/scripts/check-spdx.shindex 8c928ce0..6a829236 100755--- a/.github/scripts/check-spdx.sh+++ b/.github/scripts/check-spdx.sh@@ -80,7 +80,7 @@ check_vendor() {# when it starts with a shebang.kind_of() {case "$1" in- *.c) echo c ;;+ *.c|*.cocci) echo c ;;*.h) echo h ;;*.lua) echo lua ;;*.rst) echo rst ;;diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex e35c63e9..cf71081f 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -64,6 +64,22 @@ jobs:. build/vm-toolchain.env.github/scripts/check-sparse.sh+ coccinelle:+ name: Coccinelle+ runs-on: ubuntu-latest++ steps:+ - name: Check out repository+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1++ - name: Install Coccinelle+ run: sudo apt-get update && sudo apt-get install -y coccinelle++ # Every semantic patch in testing/coccinelle over the C the project+ # writes; a match fails the job and annotates its line.+ - name: Check the tree against the Coccinelle rules+ run: .github/scripts/check-coccinelle.sh+checkpatch:name: Checkpatchruns-on: ubuntu-latestdiff --git a/AGENTS.md b/AGENTS.mdindex 60ca0429..4d8d4c48 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -424,7 +424,11 @@ one usually still compiles and passes tests.`.github/scripts/check-sparse.sh` runs `make sparse`, sparse over theuserspace sources, which fails on a little-endian or big-endian fieldread or written without `le32_to_cpu()`, `cpu_to_le32()` or their kin- from `<shirudo/byteorder.h>`. CI runs all four on every pull request,+ from `<shirudo/byteorder.h>`. `.github/scripts/check-coccinelle.sh`+ runs the semantic patches in `testing/coccinelle/`, each a pattern the+ tree is kept free of, and fails on any match; a pattern worth refusing+ for good gets a rule there, written from scratch, with the tree fixed+ first. CI runs all five on every pull request,and `.github/scripts/build-commits.sh <range>` builds every commit ofa pull request on its own; run them before handing work over.- Shell that a workflow runs lives in `.github/scripts/`, not inline indiff --git a/Documentation/contribute/code/contributing.rst b/Documentation/contribute/code/contributing.rstindex 4b4bf278..3f3d5877 100644--- a/Documentation/contribute/code/contributing.rst+++ b/Documentation/contribute/code/contributing.rst@@ -254,6 +254,11 @@ Before sending``le32_to_cpu()``, ``cpu_to_le32()`` or their kin from``<shirudo/byteorder.h>``. CI runs it as the ``Sparse`` job of the``Lint`` workflow.+- Run ``.github/scripts/check-coccinelle.sh``. It runs every semantic+ patch in :src:`testing/coccinelle/` over the tree and fails on any+ match, such as a secret compared with ``memcmp()``, a descriptor+ opened without close-on-exec or a pointer tested for NULL after its+ use. CI runs it as the ``Coccinelle`` job of the ``Lint`` workflow.- Keep each commit to one logical change that builds and passes on itsown, so the history bisects. CI builds every commit of a pull requeston its own in the ``Build every commit`` workflow.diff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rstindex 119a7637..11d752fc 100644--- a/Documentation/contribute/code/developer-guide.rst+++ b/Documentation/contribute/code/developer-guide.rst@@ -432,6 +432,11 @@ the commit at ``HEAD`` alone without them.between host order and ``__le32`` or ``__be32`` without``cpu_to_le32()``, ``le32_to_cpu()`` or their kin from``<shirudo/byteorder.h>``. Takes no range.+ * - ``check-coccinelle.sh [<rule>...]``+ - Every semantic patch in :src:`testing/coccinelle/`, or the rules+ named, over the C the project writes, failing on any match with+ its file, line, rule and message. Takes no range; see+ `Coccinelle rules`_.* - ``build-commits.sh <range>``- Builds every commit on its own: ``make``, ``makeshirudo-build`` and ``make -C testing test-helpers``. It@@ -466,6 +471,7 @@ Before you send a change:$ .github/scripts/check-style.sh origin/main..HEAD$ .github/scripts/check-spdx.sh$ .github/scripts/check-sparse.sh+ $ .github/scripts/check-coccinelle.sh$ .github/scripts/build-commits.sh origin/main..HEAD2. Run the tests the change touches, and ``make tests`` before you@@ -480,6 +486,108 @@ Before you send a change:4. Verify that every script printed its summary line and exited 0, forexample ``DCO: 3 commits checked`` and ``style: 3 commits checked``.+Coccinelle rules+----------------++Each semantic patch in :src:`testing/coccinelle/` describes a pattern+the tree is kept free of, and ``check-coccinelle.sh`` fails on any+match, in the ``Coccinelle`` job of the ``Lint`` workflow. The rules+cover the C the project writes, as ``check-style.sh`` takes it: not the+vendored libbpf, the BTF dumps or the generated headers. A rule that+can rewrite what it finds does so with ``-D patch``:++.. code-block:: console++ $ spatch -D patch --sp-file testing/coccinelle/zero_init.cocci \+ --in-place --include-headers util/json.c++.. list-table::+ :header-rows: 1+ :widths: 24 76++ * - Rule+ - Refuses+ * - ``array_size``+ - An element count divided out by hand rather than+ ``ARRAY_SIZE()``. Rewrites.+ * - ``zero_init``+ - ``= {0}`` rather than ``= {}``. Rewrites.+ * - ``minmax``+ - A ternary that picks the smaller or larger of two values rather+ than ``min()`` or ``max()``. Rewrites.+ * - ``minmax_t``, ``minmax_cast``+ - ``min_t()`` or ``max_t()`` where ``min()`` or ``max()`` takes+ the values as they are, and a cast inside ``min()`` or+ ``max()``.+ * - ``ifnullfree``+ - A NULL test before a free function that takes NULL. Rewrites.+ * - ``void_cast``+ - A ``(void)`` cast, of a result or a variable. Rewrites.+ * - ``scrub``+ - A ``memset()`` of a local that nothing reads afterwards, which+ the compiler may drop, rather than ``memzero_explicit()``.+ Rewrites.+ * - ``secret_cmp``+ - ``memcmp()`` of a secret or what derives from one rather than+ ``memneq_explicit()``.+ * - ``openssl_ret``+ - A test of the truth of an OpenSSL function that returns 0 or a+ negative value on failure.+ * - ``overflow``+ - A sum or product tested for overflow by hand rather than with+ the helpers of ``<shirudo/overflow.h>``.+ * - ``ctype``+ - A ``char`` passed to a ``<ctype.h>`` function without a cast to+ ``__u8``. Rewrites.+ * - ``memnull``+ - A NULL passed to a memory or string function, and a+ ``memcpy()`` of overlapping buffers.+ * - ``sizeof_ptr``+ - The size of a pointer where the object it points to is meant.+ * - ``literal_len``+ - A length that does not match the string literal it compares or+ copies.+ * - ``test_after_use``+ - A pointer tested for NULL after its use.+ * - ``alloc_unchecked``+ - An allocation used before it is checked.+ * - ``use_after_free``+ - Memory used or freed again after it was freed.+ * - ``uninit``+ - A local read after a ``goto`` jumped over its assignment.+ * - ``alloc_size``+ - An allocation sized for another type than its pointer, and a+ free of memory no allocator returned.+ * - ``double_test``, ``double_init``+ - A term tested twice, an ``if`` whose branches are alike, and a+ member initialized twice.+ * - ``va_end``+ - A ``va_start()`` or ``va_copy()`` without a ``va_end()`` on a+ path out.+ * - ``cloexec``+ - A descriptor or stream opened without close-on-exec.+ * - ``banned``+ - ``rand()``, ``strtok()``, ``usleep()``, ``signal()``,+ ``alloca()``, ``setjmp()``, the time and user database functions+ without ``_r`` and their kin, and ``abort()`` and ``assert()``+ outside :src:`testing/`.+ * - ``no_exec``+ - A function that runs a program, outside the operator helper, the+ command that hands work to it and the tests.+ * - ``anssi_misc``+ - A bitwise operator on a ``bool``, a comma that sequences+ statements, a backward ``goto``, a floating-point loop counter+ and a bare ``NULL`` passed to a variadic function, after the+ ANSSI rules for secure C.+ * - ``cert_misc``+ - A ``char`` array too short for the NUL of the literal it holds, a+ ``char`` that keeps what ``getc()`` returns, and ``getenv()``+ passed on unchecked, after the CERT C rules.++A new pattern worth refusing gets a rule: write it from scratch under+the BSD-2-Clause, with a header that says why the pattern is refused,+fix the tree in the commits before it, and add it to the table.+Next steps----------diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex be3089b2..5214aaa0 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -48,6 +48,10 @@ signed config image.* - ``t0005-gen-sbom``- ``gen-sbom.sh``: the SPDX documents of a target and an operatorpackage, and the archives it refuses to leave out+ * - ``t0006-check-coccinelle``+ - ``check-coccinelle.sh``: a match that fails the check with its+ file, line and rule, the vendored sources left out, a rule named+ alone, the rewrite of ``-D patch``, and the tree itself``build`` (1)~~~~~~~~~~~~~@@ -581,7 +585,7 @@ Coverage by area- ``t0005``, ``t1003``, ``t1004``, ``t1005``, ``t1008``,``t7004``, ``t8003``* - CI scripts- - ``t0001`` to ``t0005``+ - ``t0001`` to ``t0006``* - Parsers- ``t3001``, ``t3011``, ``t5002``, ``t5006``, ``t5008``. Unit:``hex``, ``json``, ``string``. Every fuzz targetdiff --git a/testing/ci-checks/t0006-check-coccinelle.sh b/testing/ci-checks/t0006-check-coccinelle.shnew file mode 100755index 00000000..1b11cf28--- /dev/null+++ b/testing/ci-checks/t0006-check-coccinelle.sh@@ -0,0 +1,60 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t0006 -- .github/scripts/check-coccinelle.sh: a rule that matches fails the+# check with file, line, rule and message, one that does not passes it,+# a rule that can rewrite does with -D patch, on a throwaway repository,+# and the tree itself.++cd "$(dirname "$0")/.."+. ./test-lib.sh+command -v git >/dev/null 2>&1 || test_skip_all "git not installed"+command -v spatch >/dev/null 2>&1 || test_skip_all "spatch not installed"+ROOT=$(cd .. && pwd)+S=$ROOT/.github/scripts/check-coccinelle.sh+W=$(mktemp -d)+trap 'rm -rf "$W"' EXIT++R=$W/repo+mkdir -p "$R/testing/coccinelle" "$R/vendor"+git init -q "$R"+cp "$ROOT/testing/coccinelle/zero_init.cocci" \+ "$ROOT/testing/coccinelle/banned.cocci" "$R/testing/coccinelle/"+printf 'int f(void)\n{\n\tint a[4] = {0};\n\n\treturn a[0];\n}\n' >"$R/bad.c"+printf 'int g(void)\n{\n\tint a[4] = {};\n\n\treturn a[0];\n}\n' >"$R/good.c"+printf 'int h(void)\n{\n\treturn rand();\n}\n' >"$R/vendor/skip.c"++check() {+ (cd "$R" && git add -A && sh "$S" "$@") >"$W/out" 2>"$W/err"+}++test_expect_success 'a match fails the check and names file, line and rule' '+ ! check &&+ grep -q "^zero_init: bad.c:3:" "$W/err" &&+ grep -q "1 of 2 rules matched" "$W/err"+'++test_expect_success 'the vendored sources are not checked' '+ ! grep -q "skip.c" "$W/err"+'++test_expect_success 'a rule is named alone or by path' '+ check banned &&+ grep -q "1 rules, no match" "$W/out" &&+ ! check testing/coccinelle/zero_init.cocci+'++test_expect_success 'a rule rewrites what it finds with -D patch' '+ (cd "$R" && spatch -D patch --very-quiet --in-place \+ --sp-file testing/coccinelle/zero_init.cocci bad.c) &&+ grep -q "= {};" "$R/bad.c" &&+ check+'++test_expect_success 'the tree passes' '+ (cd "$ROOT" && sh "$S") >"$W/out" 2>"$W/err" &&+ grep -q "rules, no match" "$W/out"+'++test_donediff --git a/testing/coccinelle/alloc_size.cocci b/testing/coccinelle/alloc_size.coccinew file mode 100644index 00000000..d2adfcfd--- /dev/null+++ b/testing/coccinelle/alloc_size.cocci@@ -0,0 +1,50 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// An allocation sized for another type than the pointer it is stored+// in, and a free of memory no allocator returned: an address of a+// variable, or an array on the stack.++virtual report++@r@+type T1, T2;+T1 *P;+position p;+identifier alloc = {xmalloc, xcalloc};+expression N;+@@+(+ P = xmalloc@p(sizeof(T2))+|+ P = xcalloc@p(N, sizeof(T2))+)++@script:python depends on report@+p << r.p;+T1 << r.T1;+T2 << r.T2;+@@+norm = lambda t: t.replace("const ", "").replace(" ", "")+if norm(T1) != norm(T2) and norm(T1) not in ("void", "char", "__u8"):+ coccilib.report.print_report(p[0], "allocated with sizeof(%s) for a %s *" % (T2, T1))++@nondyn@+type T;+identifier x;+expression C, S;+identifier fr = {xfree, xstrfree, libc_free};+position p;+@@+(+ T x[C];+ ...+ fr@p(x, ...);+|+ fr@p(&x, ...);+)++@script:python depends on report@+p << nondyn.p;+@@+coccilib.report.print_report(p[0], "a free of memory no allocator returned")diff --git a/testing/coccinelle/alloc_unchecked.cocci b/testing/coccinelle/alloc_unchecked.coccinew file mode 100644index 00000000..4208f24a--- /dev/null+++ b/testing/coccinelle/alloc_unchecked.cocci@@ -0,0 +1,37 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The allocators return NULL on failure; use what they return only+// after testing it.++virtual report++@r exists@+expression E, E1;+identifier fld;+identifier alloc = {xmalloc, xcalloc, xreallocarray, xstrdup, xstrndup,+ xasprintf};+identifier f = {strlen, strcmp, strncmp, strchr, strrchr, strstr, memcpy,+ memmove, memcmp, memset, strscpy, strsprintf};+position p1, p2;+@@+ E = alloc@p1(...);+ ... when != E == NULL+ when != E != NULL+ when != !E+ when != E = E1+(+ E->fld@p2+|+ *E@p2+|+ E[...]@p2+|+ f@p2(..., E, ...)+)++@script:python depends on report@+p2 << r.p2;+E << r.E;+@@+coccilib.report.print_report(p2[0], "%s is used before the allocation is checked" % E)diff --git a/testing/coccinelle/anssi_misc.cocci b/testing/coccinelle/anssi_misc.coccinew file mode 100644index 00000000..09a10524--- /dev/null+++ b/testing/coccinelle/anssi_misc.cocci@@ -0,0 +1,84 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Constructs the tree does without: a bitwise operator on a bool, a+// comma that sequences statements, a goto that jumps backwards, a+// floating-point loop counter, and a variadic call passed a bare NULL,+// which is an int where NULL is 0.++virtual report++@bitbool@+bool A;+expression B;+binary operator op = {&, |, ^};+position p;+@@+(+ A op@p B+|+ B op@p A+)++@script:python depends on report@+p << bitbool.p;+@@+coccilib.report.print_report(p[0], "a bitwise operator on a bool; use && or ||")++@comma@+expression E1, E2;+position p;+@@+ E1 ,@p E2;++@script:python depends on report@+p << comma.p;+@@+coccilib.report.print_report(p[0], "a comma sequencing statements")++@backward exists@+identifier l;+position p;+@@+l:+ ...+ goto@p l;++@script:python depends on report@+p << backward.p;+l << backward.l;+@@+import re+# A path back to the label through a loop is no backward goto; one+# whose label stands above it in the function is.+lines = open(p[0].file).read().split("\n")[:int(p[0].line) - 1]+if any(re.match(r"^%s:\s*$" % re.escape(l), x) for x in lines[::-1]+ [:next((i for i, x in enumerate(lines[::-1]) if x.startswith("}")), len(lines))]):+ coccilib.report.print_report(p[0], "a goto that jumps backwards; write the loop")++@floatloop@+{float, double} X;+expression E1, E2, E3;+statement S;+position p;+@@+ for@p (X = E1; E2; E3) S++@script:python depends on report@+p << floatloop.p;+@@+coccilib.report.print_report(p[0], "a floating-point loop counter")++@varnull@+identifier f = {printf, fprintf, dprintf, pr_err, pr_warn, pr_info,+ pr_debug, pr_audit, pr_hint, strsprintf, xasprintf, execl,+ execlp, execle};+position p;+@@+ f@p(..., NULL, ...)++@script:python depends on report@+p << varnull.p;+f << varnull.f;+@@+coccilib.report.print_report(p[0], "a bare NULL passed to %s(); cast it to the pointer type" % f)diff --git a/testing/coccinelle/array_size.cocci b/testing/coccinelle/array_size.coccinew file mode 100644index 00000000..15fffec0--- /dev/null+++ b/testing/coccinelle/array_size.cocci@@ -0,0 +1,40 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Count an array's elements with ARRAY_SIZE(), which refuses a pointer.++virtual patch+virtual report++@r@+expression E;+position p;+@@+(+ sizeof(E)@p / sizeof(E[...])+|+ sizeof(E)@p / sizeof(*E)+)++@script:python@+p << r.p;+@@+if p[0].current_element == "ARRAY_SIZE":+ cocci.include_match(False)++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "use ARRAY_SIZE()")++@depends on patch@+expression r.E;+position r.p;+@@+(+- sizeof(E)@p / sizeof(E[...])++ ARRAY_SIZE(E)+|+- sizeof(E)@p / sizeof(*E)++ ARRAY_SIZE(E)+)diff --git a/testing/coccinelle/banned.cocci b/testing/coccinelle/banned.coccinew file mode 100644index 00000000..95b5689b--- /dev/null+++ b/testing/coccinelle/banned.cocci@@ -0,0 +1,32 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Functions the tree does without: rand() and its kin are no source of+// secrets (getrandom() is), strtok() and the time and user database+// functions keep hidden state (the _r forms do not), gets(), tmpnam(),+// tempnam() and mktemp() are unsafe by design, vfork(), alloca(),+// setjmp() and longjmp() defeat the compiler's checks, usleep() and+// signal() are obsolete (nanosleep() and sigaction() are not), and+// abort() and assert() belong to the tests, where they fail CI.++virtual report++@r@+identifier f = {rand, srand, random, srandom, rand_r, drand48, lrand48,+ mrand48, strtok, gets, tmpnam, tempnam, mktemp, vfork, alloca,+ setjmp, longjmp, sigsetjmp, siglongjmp, usleep, signal,+ asctime, ctime, gmtime, localtime, getpwnam, getpwuid,+ getgrnam, getgrgid, getlogin, ttyname, bzero, bcopy, index,+ rindex, getwd, abort, assert};+position p;+@@+ f@p(...)++@script:python depends on report@+p << r.p;+f << r.f;+@@+# The tests may use what they exercise, and abort() and assert() fail+# CI there.+if not p[0].file.startswith("testing/"):+ coccilib.report.print_report(p[0], "%s() is not used in the tree" % f)diff --git a/testing/coccinelle/cert_misc.cocci b/testing/coccinelle/cert_misc.coccinew file mode 100644index 00000000..1c4e1af6--- /dev/null+++ b/testing/coccinelle/cert_misc.cocci@@ -0,0 +1,56 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// CERT C: a char array sized as long as the string literal it holds+// has no room for the terminating NUL (STR36-C), a char cannot tell+// EOF from a byte getc() returned (FIO34-C), and getenv() returns NULL+// for an unset variable (EXP34-C).++virtual report++@strbound@+identifier x;+constant C;+constant char[] S;+position p;+@@+ char x@p[C] = S;++@script:python depends on report@+p << strbound.p;+C << strbound.C;+S << strbound.S;+@@+import ast+try:+ n, text = int(C, 0), ast.literal_eval(S)+except Exception:+ n = None+if n is not None and n <= len(text.encode()):+ coccilib.report.print_report(p[0], "no room for the NUL of the string literal; use []")++@getc@+char c;+identifier f = {getc, fgetc, getchar, getc_unlocked, fgetc_unlocked};+position p;+@@+ c =@p f(...)++@script:python depends on report@+p << getc.p;+f << getc.f;+@@+coccilib.report.print_report(p[0], "keep what %s() returns in an int" % f)++@getenv@+identifier f = {strlen, strcmp, strncmp, strchr, strrchr, strstr, strdup,+ xstrdup, strscpy, strtol, parse_u64, atoi};+expression E;+position p;+@@+ f@p(..., getenv(E), ...)++@script:python depends on report@+p << getenv.p;+@@+coccilib.report.print_report(p[0], "getenv() may return NULL")diff --git a/testing/coccinelle/cloexec.cocci b/testing/coccinelle/cloexec.coccinew file mode 100644index 00000000..30491fc8--- /dev/null+++ b/testing/coccinelle/cloexec.cocci@@ -0,0 +1,73 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Open every descriptor close-on-exec, so that none reaches a program+// the operator helper runs.++virtual report++@initialize:python@+@@+closing = set()++@ok@+expression A, B, C, D;+position p;+@@+(+ open@p(A, <+... O_CLOEXEC ...+>, ...)+|+ openat@p(A, B, <+... O_CLOEXEC ...+>, ...)+|+ socket@p(A, <+... SOCK_CLOEXEC ...+>, ...)+|+ memfd_create@p(A, <+... MFD_CLOEXEC ...+>)+|+ pipe2@p(A, <+... O_CLOEXEC ...+>)+|+ accept4@p(A, B, C, <+... SOCK_CLOEXEC ...+>)+|+ dup3@p(A, B, <+... O_CLOEXEC ...+>)+)++@script:python@+p << ok.p;+@@+closing.add((p[0].file, p[0].line, p[0].column))++@r@+identifier f = {open, openat, socket, memfd_create, pipe2, accept4, dup3,+ pipe, accept, dup, dup2, creat, epoll_create, inotify_init,+ signalfd, eventfd, timerfd_create};+position p;+@@+ f@p(...)++@script:python depends on report@+p << r.p;+f << r.f;+@@+# harden_stdio() points a closed standard descriptor at /dev/null for+# good, a program it runs included.+if (p[0].file, p[0].line, p[0].column) not in closing and \+ p[0].current_element != "harden_stdio" and \+ not p[0].file.startswith(("bpf/", "upatches/", "testing/")):+ coccilib.report.print_report(p[0], "%s() without close-on-exec" % f)++@mode@+expression P;+constant char[] M;+position q;+@@+(+ fopen@q(P, M)+|+ freopen@q(P, M, ...)+)++@script:python depends on report@+q << mode.q;+M << mode.M;+@@+if "e" not in M.strip('"') and not q[0].file.startswith("testing/"):+ coccilib.report.print_report(q[0], "open the stream close-on-exec with \"e\" in its mode")diff --git a/testing/coccinelle/ctype.cocci b/testing/coccinelle/ctype.coccinew file mode 100644index 00000000..ec04b32f--- /dev/null+++ b/testing/coccinelle/ctype.cocci@@ -0,0 +1,32 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The <ctype.h> functions take an unsigned char's value or EOF; a char+// above 0x7f is negative where char is signed, which is undefined.++virtual patch+virtual report++@r@+identifier f = {isalnum, isalpha, isascii, isblank, iscntrl, isdigit,+ isgraph, islower, isprint, ispunct, isspace, isupper,+ isxdigit, tolower, toupper};+char C;+position p;+@@+ f@p(C)++@script:python depends on report@+p << r.p;+f << r.f;+@@+coccilib.report.print_report(p[0], "cast the argument of %s() to __u8" % f)++@depends on patch@+identifier r.f;+char r.C;+position r.p;+@@+ f@p(++ (__u8)+ C)diff --git a/testing/coccinelle/double_init.cocci b/testing/coccinelle/double_init.coccinew file mode 100644index 00000000..a21c8dfe--- /dev/null+++ b/testing/coccinelle/double_init.cocci@@ -0,0 +1,21 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A member a designated initializer sets twice keeps only the second+// value; the first was meant for another member.++virtual report++@r@+identifier f, x;+type T;+expression E1, E2;+position p2;+@@+ T x = {..., .f = E1, ..., .f = E2@p2, ...};++@script:python depends on report@+p2 << r.p2;+f << r.f;+@@+coccilib.report.print_report(p2[0], "member %s is initialized twice" % f)diff --git a/testing/coccinelle/double_test.cocci b/testing/coccinelle/double_test.coccinew file mode 100644index 00000000..52044f1a--- /dev/null+++ b/testing/coccinelle/double_test.cocci@@ -0,0 +1,34 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A condition that tests one term twice, or an if whose branches do the+// same, is a copy left in place of what was meant.++virtual report++@r@+expression E;+position p;+@@+(+ E &&@p E+|+ E ||@p E+)++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "the same term tested twice")++@b@+expression E;+statement S;+position p;+@@+ if (E@p) S else S++@script:python depends on report@+p << b.p;+@@+coccilib.report.print_report(p[0], "both branches of the if do the same")diff --git a/testing/coccinelle/ifnullfree.cocci b/testing/coccinelle/ifnullfree.coccinew file mode 100644index 00000000..18fa254d--- /dev/null+++ b/testing/coccinelle/ifnullfree.cocci@@ -0,0 +1,101 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// These free functions take NULL; a test before them only hides the call.++virtual patch+virtual report++@r depends on report@+expression E, S;+position p;+@@+ if@p (E)+(+ xfree(E, S);+|+ xstrfree(E);+|+ libc_free(E);+|+ X509_free(E);+|+ X509_STORE_free(E);+|+ EVP_PKEY_free(E);+|+ EVP_PKEY_CTX_free(E);+|+ EVP_MD_CTX_free(E);+|+ BIO_free(E);+|+ BN_free(E);+|+ OSSL_PARAM_free(E);+|+ CMS_ContentInfo_free(E);+|+ btf__free(E);+|+ bpf_object__close(E);+|+ bpf_link__destroy(E);+|+ curl_slist_free_all(E);+|+ curl_free(E);+|+ curl_easy_cleanup(E);+|+ curl_url_cleanup(E);+)++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "the free function takes NULL; drop the test")++@depends on patch@+expression E, S;+@@+- if (E)+(+ xfree(E, S);+|+ xstrfree(E);+|+ libc_free(E);+|+ X509_free(E);+|+ X509_STORE_free(E);+|+ EVP_PKEY_free(E);+|+ EVP_PKEY_CTX_free(E);+|+ EVP_MD_CTX_free(E);+|+ BIO_free(E);+|+ BN_free(E);+|+ OSSL_PARAM_free(E);+|+ CMS_ContentInfo_free(E);+|+ btf__free(E);+|+ bpf_object__close(E);+|+ bpf_link__destroy(E);+|+ curl_slist_free_all(E);+|+ curl_free(E);+|+ curl_easy_cleanup(E);+|+ curl_url_cleanup(E);+)diff --git a/testing/coccinelle/literal_len.cocci b/testing/coccinelle/literal_len.coccinew file mode 100644index 00000000..1a300bcb--- /dev/null+++ b/testing/coccinelle/literal_len.cocci@@ -0,0 +1,36 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A length that does not match the string literal it bounds compares+// or copies more or less than the literal.++virtual report++@r@+expression E;+constant char[] S;+constant N;+identifier f = {strncmp, strncasecmp, memcmp, memcpy};+position p;+@@+(+ f@p(E, S, N)+|+ f@p(S, E, N)+)++@script:python depends on report@+p << r.p;+S << r.S;+N << r.N;+f << r.f;+@@+import ast+try:+ text = ast.literal_eval(S)+ n = int(N, 0)+except Exception:+ text = None+if text is not None and n != len(text.encode()) and \+ not (f in ("memcmp", "memcpy") and n == len(text.encode()) + 1):+ coccilib.report.print_report(p[0], "%s() of %d bytes against a %d-byte literal" % (f, n, len(text.encode())))diff --git a/testing/coccinelle/memnull.cocci b/testing/coccinelle/memnull.coccinew file mode 100644index 00000000..b6fbe48d--- /dev/null+++ b/testing/coccinelle/memnull.cocci@@ -0,0 +1,29 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The mem*() and str*() functions take no NULL pointer, not even with a+// length of 0, and memcpy() takes no overlap: an empty buffer is copied+// under a test of its length, and an overlapping one with memmove().++virtual report++@r@+identifier f = {memcpy, memmove, memset, memcmp, memchr, strlen, strnlen,+ strcmp, strncmp, strchr, strrchr, strstr, strscpy,+ memzero_explicit, memneq_explicit};+expression list es;+expression E, F, L;+position p;+@@+(+ f@p(..., NULL, ...)+|+ memcpy@p(E, E + F, L)+|+ memcpy@p(E + F, E, L)+)++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "NULL or an overlapping buffer passed to a memory or string function")diff --git a/testing/coccinelle/minmax.cocci b/testing/coccinelle/minmax.coccinew file mode 100644index 00000000..2b36d3f9--- /dev/null+++ b/testing/coccinelle/minmax.cocci@@ -0,0 +1,66 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Take the smaller or larger of two values with min() or max(), which+// evaluate each once and refuse operands of different types; min_t()+// and max_t() name the type when they differ.++virtual patch+virtual report++@r depends on report@+expression A, B;+position p;+@@+(+ A <@p B ? A : B+|+ A <=@p B ? A : B+|+ A >@p B ? B : A+|+ A >=@p B ? B : A+|+ A >@p B ? A : B+|+ A >=@p B ? A : B+|+ A <@p B ? B : A+|+ A <=@p B ? B : A+)++@script:python depends on report@+p << r.p;+@@+if p[0].current_element not in ("min", "max", "__minmax"):+ coccilib.report.print_report(p[0], "use min() or max()")++@depends on patch@+expression A, B;+@@+(+- A < B ? A : B++ min(A, B)+|+- A <= B ? A : B++ min(A, B)+|+- A > B ? B : A++ min(A, B)+|+- A >= B ? B : A++ min(A, B)+|+- A > B ? A : B++ max(A, B)+|+- A >= B ? A : B++ max(A, B)+|+- A < B ? B : A++ max(A, B)+|+- A <= B ? B : A++ max(A, B)+)diff --git a/testing/coccinelle/minmax_cast.cocci b/testing/coccinelle/minmax_cast.coccinew file mode 100644index 00000000..b128aa61--- /dev/null+++ b/testing/coccinelle/minmax_cast.cocci@@ -0,0 +1,27 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A cast inside min() or max() is min_t() spelled by hand: give the+// value its right type, or use min_t() where it cannot have one.++virtual report++@r disable drop_cast@+type T;+expression A, B;+identifier f = {min, max};+position p;+@@+(+ f@p((T)A, B)+|+ f@p(A, (T)B)+)++@script:python depends on report@+p << r.p;+f << r.f;+@@+line = open(p[0].file).read().split("\n")[int(p[0].line) - 1]+if not line.startswith("#define"):+ coccilib.report.print_report(p[0], "a cast inside %s()" % f)diff --git a/testing/coccinelle/minmax_t.cocci b/testing/coccinelle/minmax_t.coccinew file mode 100644index 00000000..d4bce2d1--- /dev/null+++ b/testing/coccinelle/minmax_t.cocci@@ -0,0 +1,29 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// min_t() and max_t() convert both values, which can cut one short; use+// min() and max() wherever they take the two as they are, which they do+// for values of one type and for a non-negative constant.++virtual report++@r@+type T;+T A, B;+constant C;+position p;+identifier f = {min_t, max_t};+@@+(+ f@p(T, A, B)+|+ f@p(T, A, C)+|+ f@p(T, C, A)+)++@script:python depends on report@+p << r.p;+f << r.f;+@@+coccilib.report.print_report(p[0], "%s() converts what %s() takes as it is" % (f, f[:3]))diff --git a/testing/coccinelle/no_exec.cocci b/testing/coccinelle/no_exec.coccinew file mode 100644index 00000000..8044a216--- /dev/null+++ b/testing/coccinelle/no_exec.cocci@@ -0,0 +1,24 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The target runs no other program: only the operator helper in+// tools/shirudo-build, the command that hands work to it and the tests+// fork or execute one.++virtual report++@r@+identifier f = {fork, vfork, clone, clone3, execv, execve, execvp, execvpe,+ execl, execle, execlp, fexecve, execveat, system, popen,+ posix_spawn, posix_spawnp};+position p;+@@+ f@p(...)++@script:python depends on report@+p << r.p;+f << r.f;+@@+if not p[0].file.startswith(("tools/shirudo-build/", "testing/")) and \+ p[0].file != "builtin-build.c":+ coccilib.report.print_report(p[0], "%s() runs a program on the target" % f)diff --git a/testing/coccinelle/openssl_ret.cocci b/testing/coccinelle/openssl_ret.coccinew file mode 100644index 00000000..d7d6d119--- /dev/null+++ b/testing/coccinelle/openssl_ret.cocci@@ -0,0 +1,76 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// These OpenSSL functions return 1 on success, and 0 or a negative+// value on failure: a test of their truth takes an error for success.+// Compare with 1, or with 0 by <= or >.++virtual report++@initialize:python@+@@+compared = set()++@ok@+identifier f = {EVP_PKEY_verify, EVP_PKEY_verify_init, EVP_PKEY_verify_recover,+ EVP_PKEY_sign, EVP_PKEY_sign_init, EVP_PKEY_derive,+ EVP_PKEY_derive_init, EVP_PKEY_derive_set_peer,+ EVP_PKEY_encrypt, EVP_PKEY_encrypt_init, EVP_PKEY_decrypt,+ EVP_PKEY_decrypt_init, EVP_PKEY_encapsulate,+ EVP_PKEY_encapsulate_init, EVP_PKEY_decapsulate,+ EVP_PKEY_decapsulate_init, EVP_PKEY_keygen, EVP_PKEY_keygen_init,+ EVP_PKEY_fromdata, EVP_PKEY_fromdata_init,+ EVP_PKEY_CTX_set_signature_md, EVP_PKEY_CTX_set_rsa_padding,+ EVP_PKEY_CTX_set_rsa_oaep_md, EVP_PKEY_CTX_set_rsa_mgf1_md,+ EVP_PKEY_CTX_set0_rsa_oaep_label, EVP_PKEY_CTX_set_params,+ EVP_DigestVerify, EVP_DigestVerifyInit, EVP_DigestVerifyUpdate,+ EVP_DigestVerifyFinal, EVP_DigestSign, EVP_DigestSignInit,+ EVP_DigestSignUpdate, EVP_DigestSignFinal, X509_verify,+ X509_REQ_verify, X509_CRL_verify, X509_verify_cert, RAND_bytes,+ RAND_priv_bytes, CMS_verify, PKCS7_verify, EVP_PKEY_check,+ EVP_PKEY_public_check};+position p;+@@+(+ f@p(...) == 1+|+ f@p(...) != 1+|+ f@p(...) <= 0+|+ f@p(...) > 0+)++@script:python@+p << ok.p;+@@+compared.add((p[0].file, p[0].line, p[0].column))++@r@+identifier f = {EVP_PKEY_verify, EVP_PKEY_verify_init, EVP_PKEY_verify_recover,+ EVP_PKEY_sign, EVP_PKEY_sign_init, EVP_PKEY_derive,+ EVP_PKEY_derive_init, EVP_PKEY_derive_set_peer,+ EVP_PKEY_encrypt, EVP_PKEY_encrypt_init, EVP_PKEY_decrypt,+ EVP_PKEY_decrypt_init, EVP_PKEY_encapsulate,+ EVP_PKEY_encapsulate_init, EVP_PKEY_decapsulate,+ EVP_PKEY_decapsulate_init, EVP_PKEY_keygen, EVP_PKEY_keygen_init,+ EVP_PKEY_fromdata, EVP_PKEY_fromdata_init,+ EVP_PKEY_CTX_set_signature_md, EVP_PKEY_CTX_set_rsa_padding,+ EVP_PKEY_CTX_set_rsa_oaep_md, EVP_PKEY_CTX_set_rsa_mgf1_md,+ EVP_PKEY_CTX_set0_rsa_oaep_label, EVP_PKEY_CTX_set_params,+ EVP_DigestVerify, EVP_DigestVerifyInit, EVP_DigestVerifyUpdate,+ EVP_DigestVerifyFinal, EVP_DigestSign, EVP_DigestSignInit,+ EVP_DigestSignUpdate, EVP_DigestSignFinal, X509_verify,+ X509_REQ_verify, X509_CRL_verify, X509_verify_cert, RAND_bytes,+ RAND_priv_bytes, CMS_verify, PKCS7_verify, EVP_PKEY_check,+ EVP_PKEY_public_check};+position p;+@@+ f@p(...)++@script:python depends on report@+p << r.p;+f << r.f;+@@+if (p[0].file, p[0].line, p[0].column) not in compared:+ coccilib.report.print_report(p[0], "compare the result of %s() with 1, or by <= 0" % f)diff --git a/testing/coccinelle/overflow.cocci b/testing/coccinelle/overflow.coccinew file mode 100644index 00000000..367256e3--- /dev/null+++ b/testing/coccinelle/overflow.cocci@@ -0,0 +1,40 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Test a sum or a product for overflow with the helpers of+// <shirudo/overflow.h>, not by hand against the limit or after the fact.++virtual report++@r@+expression A, B, C;+identifier M = {SIZE_MAX, UINT64_MAX, UINT32_MAX, UINT16_MAX, UINT8_MAX,+ INT64_MAX, INT32_MAX, INT_MAX, LONG_MAX, SSIZE_MAX, UINT_MAX,+ ULONG_MAX, U64_MAX, U32_MAX, U16_MAX};+binary operator op = {>, >=, <, <=};+position p;+@@+(+ A op@p M - B+|+ M - B op@p A+|+ A op@p M / B+|+ M / B op@p A+|+ A op@p (M - B) / C+|+ A + B <@p A+|+ A + B <@p B+)++@script:python depends on report@+p << r.p;+@@+# BPF code is bounded by the verifier and has no <shirudo/overflow.h>.+f = p[0].file+if not f.startswith(("bpf/", "upatches/")) and \+ p[0].current_element not in ("size_add", "size_mul", "size_sub"):+ coccilib.report.print_report(p[0], "use check_add_overflow(), check_mul_overflow() or the size helpers")diff --git a/testing/coccinelle/scrub.cocci b/testing/coccinelle/scrub.coccinew file mode 100644index 00000000..e3202a31--- /dev/null+++ b/testing/coccinelle/scrub.cocci@@ -0,0 +1,46 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A memset() of a local that nothing reads afterwards is a dead store+// the compiler drops; scrub with memzero_explicit().++virtual patch+virtual report++@r@+identifier x;+expression C, L;+position p;+type T;+@@+(+ T x[C];+|+ T x;+)+ ... when any+(+ memset@p(x, 0, L);+|+ memset@p(&x, 0, L);+)+ ... when != x+ when != &x++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "a memset() nothing reads afterwards may be dropped; use memzero_explicit()")++@depends on patch@+identifier r.x;+expression L;+position r.p;+@@+(+- memset@p(x, 0, L);++ memzero_explicit(x, L);+|+- memset@p(&x, 0, L);++ memzero_explicit(&x, L);+)diff --git a/testing/coccinelle/secret_cmp.cocci b/testing/coccinelle/secret_cmp.coccinew file mode 100644index 00000000..4c9686a5--- /dev/null+++ b/testing/coccinelle/secret_cmp.cocci@@ -0,0 +1,23 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// memcmp() returns at the first difference; compare a secret, or what+// derives from one, with memneq_explicit().++virtual report++@r@+expression A, B, N;+position p;+@@+ memcmp@p(A, B, N)++@script:python depends on report@+p << r.p;+A << r.A;+B << r.B;+@@+import re+secret = re.compile(r"(secret|cred|passw|token|auth|hmac|\bmac\b|_mac\b|sym_key|hmac_key|seed|private|priv_key|shared|\bz\b)", re.I)+if secret.search(A) or secret.search(B):+ coccilib.report.print_report(p[0], "compare a secret with memneq_explicit()")diff --git a/testing/coccinelle/sizeof_ptr.cocci b/testing/coccinelle/sizeof_ptr.coccinew file mode 100644index 00000000..ff42e87e--- /dev/null+++ b/testing/coccinelle/sizeof_ptr.cocci@@ -0,0 +1,30 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// sizeof a pointer where the object it points to was meant: what is+// copied, cleared, compared, scrubbed or allocated is 8 bytes.++virtual report++@r@+type T;+idexpression T *P;+identifier f = {memcpy, memmove, memset, memcmp, memzero_explicit,+ memneq_explicit, xfree, xmalloc, read, write, pread, pwrite,+ strscpy, strsprintf};+position p;+@@+(+ f(..., sizeof@p(P), ...)+|+ f(..., sizeof@p(P) * ..., ...)+|+ xcalloc(..., sizeof@p(P))+|+ sizeof@p(sizeof(...))+)++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "sizeof of a pointer; the object it points to may be meant")diff --git a/testing/coccinelle/test_after_use.cocci b/testing/coccinelle/test_after_use.coccinew file mode 100644index 00000000..06b80391--- /dev/null+++ b/testing/coccinelle/test_after_use.cocci@@ -0,0 +1,153 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A pointer dereferenced, or handed to a function that takes no NULL,+// before the test that it may be NULL: the test comes too late.++virtual report++@initialize:python@+@@+unevaluated = set()++@ufld@+expression E, B;+identifier fld;+position p;+@@+(+ sizeof(<+... E->fld@p ...+>)+|+ E ? <+... E->fld@p ...+> : B+|+ !E || <+... E->fld@p ...+>+|+ E && <+... E->fld@p ...+>+|+ E == NULL || <+... E->fld@p ...+>+|+ E != NULL && <+... E->fld@p ...+>+)++@script:python@+p << ufld.p;+@@+unevaluated.add((p[0].file, p[0].line, p[0].column))++@uptr@+expression E, B;+position p;+@@+(+ sizeof(<+... *E@p ...+>)+|+ E ? <+... *E@p ...+> : B+|+ !E || <+... *E@p ...+>+|+ E && <+... *E@p ...+>+|+ E == NULL || <+... *E@p ...+>+|+ E != NULL && <+... *E@p ...+>+)++@script:python@+p << uptr.p;+@@+unevaluated.add((p[0].file, p[0].line, p[0].column))++@ufn@+expression E, B;+identifier f = {strlen, strnlen, strcmp, strncmp, strchr, strrchr, strstr,+ strcasecmp, strncasecmp, strspn, strcspn, memchr, strscpy};+position p;+@@+(+ E ? <+... f@p(..., E, ...) ...+> : B+|+ !E || <+... f@p(..., E, ...) ...+>+|+ E && <+... f@p(..., E, ...) ...+>+|+ E == NULL || <+... f@p(..., E, ...) ...+>+|+ E != NULL && <+... f@p(..., E, ...) ...+>+)++@script:python@+p << ufn.p;+@@+unevaluated.add((p[0].file, p[0].line, p[0].column))++@r exists@+expression E, E1;+identifier fld;+identifier f = {strlen, strnlen, strcmp, strncmp, strchr, strrchr, strstr,+ strcasecmp, strncasecmp, strspn, strcspn, memchr, strscpy};+position p1, p2;+@@+(+ E->fld@p1+|+ *E@p1+|+ f@p1(..., E, ...)+)+ ... when != E = E1+ when != &E+ when != E+++ when != E--+ when != E += E1+(+ !E@p2+|+ E@p2 == NULL+|+ NULL == E@p2+|+ E@p2 != NULL+)++@script:python depends on report@+p1 << r.p1;+p2 << r.p2;+E << r.E;+@@+import re+# Within one statement, as in a ternary, the order is not the one of+# execution, and a loop tests again what its previous turn used. A test+# after a label is for the paths that come there before the use, a use+# that assigns the pointer is followed by a test of the new value, and+# a use in a block that an if or a loop on the pointer opens, or after+# a test of it in its own block, is guarded by them.+def indent(l):+ return len(l.expandtabs(8)) - len(l.expandtabs(8).lstrip())+lines = open(p1[0].file).read().split("\n")+use, test = int(p1[0].line), int(p2[0].line)+name = re.escape(E)+tested = re.compile(r"(!\s*\(?\s*%s\b|\b%s\s*[!=]=\s*NULL)" % (name, name))+opener = re.compile(r"^\s*(if|while|for|else|do)\b|\{\s*$")+label = any(re.match(r"^[A-Za-z_]\w*:\s*$", l) for l in lines[use:test - 1])+reassigned = re.search(r"(^|[^=!<>])\b%s\s*=[^=]" % name, lines[use - 1]) is not None+guard = False+level = indent(lines[use - 1])+for l in reversed(lines[:use - 1]):+ if not l.strip():+ continue+ if indent(l) >= level:+ if tested.search(l) and indent(l) == level:+ guard = True+ break+ continue+ if not opener.search(l):+ continue+ if re.search(r"\b(if|while|for)\b.*\b%s\b" % name, l):+ guard = True+ break+ level = indent(l)+ if level == 0:+ break+if use < test and not label and not reassigned and not guard and \+ (p1[0].file, p1[0].line, p1[0].column) not in unevaluated:+ coccilib.report.print_report(p2[0], "%s is tested for NULL after its use at line %s" % (E, p1[0].line))diff --git a/testing/coccinelle/uninit.cocci b/testing/coccinelle/uninit.coccinew file mode 100644index 00000000..804936f0--- /dev/null+++ b/testing/coccinelle/uninit.cocci@@ -0,0 +1,44 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A local that a goto jumps over the assignment of, and that is read+// after the label, is read uninitialized on that path, which is+// undefined, and which a compiler reports or not with its version and+// optimizations: initialize it where it is declared.++virtual report++@r disable decl_init exists@+type T;+identifier x, l;+expression E;+position p;+@@+ T x;+ ... when != x+ goto l;+ ...+l:+ ... when != x = E+ when != &x+(+ x = E+|+ &x+|+ sizeof(x)+|+ x@p+)++@script:python depends on report@+p << r.p;+x << r.x;+T << r.T;+@@+import re+# A for loop that assigns x in its header is no read before assignment.+line = open(p[0].file).read().split("\n")[int(p[0].line) - 1]+header = re.search(r"\bfor\s*\(\s*%s\s*=" % re.escape(x), line)+if not header and "[" not in T and not T.startswith(("struct", "union")):+ coccilib.report.print_report(p[0], "%s is read uninitialized when a goto jumps over its assignment" % x)diff --git a/testing/coccinelle/use_after_free.cocci b/testing/coccinelle/use_after_free.coccinew file mode 100644index 00000000..642cf7e2--- /dev/null+++ b/testing/coccinelle/use_after_free.cocci@@ -0,0 +1,38 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Memory is neither read nor freed again once it has been freed.++virtual report++@r exists@+expression E, E1;+identifier fr = {xfree, xstrfree, libc_free, X509_free, EVP_PKEY_free,+ BIO_free, BN_free, CMS_ContentInfo_free, btf__free,+ curl_slist_free_all, curl_free};+identifier fld;+position p1, p2;+@@+ fr@p1(E, ...);+ ... when != E = E1+ when != &E+(+ E->fld@p2+|+ *E@p2+|+ E[...]@p2+|+ fr@p2(E, ...)+|+ memcpy@p2(..., E, ...)+)++@script:python depends on report@+p1 << r.p1;+p2 << r.p2;+E << r.E;+@@+# An element freed in a loop is another one on the next turn.+if "[" not in E:+ coccilib.report.print_report(p2[0], "%s is used after it was freed at line %s" % (E, p1[0].line))diff --git a/testing/coccinelle/va_end.cocci b/testing/coccinelle/va_end.coccinew file mode 100644index 00000000..7bae3d67--- /dev/null+++ b/testing/coccinelle/va_end.cocci@@ -0,0 +1,24 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Every va_start() and va_copy() is matched by a va_end() on each path+// out of the function.++virtual report++@r exists@+expression A, B;+position p;+@@+(+ va_start@p(A, ...);+|+ va_copy@p(A, B);+)+ ... when != va_end(A);+ return ...;++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "no va_end() on a path from here")diff --git a/testing/coccinelle/void_cast.cocci b/testing/coccinelle/void_cast.coccinew file mode 100644index 00000000..71231a9e--- /dev/null+++ b/testing/coccinelle/void_cast.cocci@@ -0,0 +1,33 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// No (void) casts: a __must_check result is checked, a result callers+// may ignore needs none, every build takes -Wno-unused-parameter, and an+// unused variable goes. The type check of min() and max() is the+// exception.++virtual patch+virtual report++@r depends on report@+expression E;+position p;+@@+ (void)@p E++@script:python depends on report@+p << r.p;+@@+if p[0].current_element not in ("min", "max", "__minmax"):+ coccilib.report.print_report(p[0], "drop the (void) cast")++@depends on patch@+expression E;+identifier x;+@@+(+- (void)x;+|+- (void)+ E+)diff --git a/testing/coccinelle/zero_init.cocci b/testing/coccinelle/zero_init.coccinew file mode 100644index 00000000..6cfdec4a--- /dev/null+++ b/testing/coccinelle/zero_init.cocci@@ -0,0 +1,28 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Zero-initialize with = {}, the kernel's form, not = {0}.++virtual patch+virtual report++@r depends on report@+type T;+identifier x;+position p;+@@+ T x@p = {0};++@script:python depends on report@+p << r.p;+@@+coccilib.report.print_report(p[0], "zero-initialize with = {}")++@depends on patch@+type T;+identifier x;+@@+ T x =+- {0}++ {}+ ;