October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Coccinelle Tutorial: Write and Run SmPL Semantic Patches

Coccinelle uses SmPL rules and the spatch engine to match, report, or transform C code across files. Learn the basics, directory workflow, and Linux kernel modes.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Coccinelle applies structured rules to C code so you can find or transform patterns across files without relying on a blind text replacement. You write those rules in SmPL (Semantic Patch Language) and run them with spatch. A reliable workflow is to match a small example, inspect the result, then expand to a directory or codebase.

What Coccinelle and SmPL do

Coccinelle is a program-matching and source-transformation tool for C. An SmPL file describes the code pattern to find and, optionally, an edit to make or a report to produce. The Linux kernel documents it for tree-wide changes and for detecting problematic programming patterns. The project describes its goal as documenting and automating “the kinds of collateral evolutions that occur in device driver code.” See the Coccinelle project and the Linux kernel Coccinelle documentation.

As an Amazon Associate I earn from qualifying purchases.

SmPL resembles a patch, but it can express more than fixed lines of text. Metavariables match categories of code, ellipses skip irrelevant sequences while retaining structural context, dependencies can gate rules, optional scripting can add logic, and isomorphisms can recognize equivalent coding forms. That combination is useful when the same change must follow semantic context across many C files.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install Coccinelle and check spatch

The official download page lists Coccinelle 1.3.3, released September 2, 2026, and offers native packages, Flatpak, Homebrew, and OPAM routes. Use the package manager that fits your system, then verify the command is available before running a rule on a large tree. Refer to the official download page for current platform options.

  • Homebrew: brew install coccinelle
  • OPAM: opam update, then opam install coccinelle
  • Check the installed executable with spatch --help or the version option supported by your installation.

Write a first semantic patch

Create a file named rename.cocci containing this minimal rule:

@@
- foo()
+ bar()

This rule matches calls to foo() and replaces them with bar(). Lines prefixed with - describe what is removed; lines prefixed with + describe what is added. Ordinary code is context. The grammar reference’s example demonstrates that the rule targets the call rather than unrelated text such as a string literal. See the SmPL grammar reference.

Run it on one file first

Use the official invocation form with your patch and a test C file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
spatch -cocci_file rename.cocci test.c

For explicit output control, the Debian spatch manual documents --sp-file to select the semantic patch and -o to write output to a file. For example:

spatch --sp-file rename.cocci -o test.out.c test.c

Review the resulting diff against the original before widening the scope. The manual also documents --debug, which is useful when a metavariable binds in an unexpected way. Consult the Debian spatch manual for the command’s options.

Make matches general without making them careless

Use metavariables for varying code

A fixed rule only matches the spelling and structure it describes. Metavariables let a rule match concrete identifiers, expressions, types, positions, and other declared categories. Declarations constrain what can bind, so add the narrowest useful category and context rather than loosening a rule until it behaves like a text search. Dependencies and virtual rules can make a later rule conditional on an earlier match.

Use the ellipsis as a structural wildcard

The ... operator can stand for a sequence of instructions or arguments that is not important to the pattern. It does not mean “match arbitrary text anywhere”: the code around it still supplies structural context. By default, matching follows a shortest-path rule; when constraints can refine the skipped region or rule out an unwanted intervening pattern. The grammar reference describes the syntax.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Account for equivalent coding styles

Isomorphisms allow Coccinelle to treat certain equivalent forms, such as different styles of null check, as the same pattern. This can prevent duplicate rules for stylistic variants, but it is not a substitute for reviewing which forms your rule should cover. The project’s documentation explains SmPL and its matching facilities.

Apply a rule to a directory

Once a rule behaves correctly on a fixture, run it over a directory. The official examples show:

spatch -cocci_file rename.cocci -dir src

Directory processing can produce many candidate edits. Keep the first run small, inspect every generated hunk, and only then point the command at a broader tree. Separate report-only rules from edit-producing rules while learning; use --debug if a binding surprises you, and tighten types or surrounding context when a pattern is too broad.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use Coccinelle in the Linux kernel

The kernel provides the coccicheck target for running semantic patches. Its documented modes include report for findings, patch for generated edits, and context and org for alternative output forms. Begin with a report so you can see what the rule matches before asking it to prepare a patch.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
make coccicheck MODE=report COCCI=path/to/rule.cocci

After validating the reported sites, run the patch mode and review the resulting changes before applying or committing them:

Best Value
make coccicheck MODE=patch COCCI=path/to/rule.cocci

Check the kernel’s Coccinelle documentation for the target’s current usage and mode details. Its examples include API evolution such as changing usb_submit_urb arguments, replacing obsolete check_region usage, converting expressions to DIV_ROUND_UP, and finding suspicious unsigned comparisons. These are useful models for rules that combine context and metavariables rather than simple token substitution.

When to choose Coccinelle over other approaches

Approach Best fit Main limitation
Textual search and replace Small, uniform edits where the exact text is distinctive and surrounding code does not matter. Can miss formatting variants or change text in the wrong context.
AST or refactoring framework Changes that need a richer language model or tooling built around a particular parser and transformation workflow. Setup and framework choices may be more than a one-off edit needs.
Coccinelle Context-sensitive C matches and consistent transformations across a large codebase, including kernel-style collateral API changes. Rules need careful structural constraints and review; a broad semantic patch can still match code that requires human judgment.

For a one-off replacement with no meaningful code context, a simple search-and-replace may be quicker. When correctness depends on the relationship between code elements or the change spans a large C tree, SmPL offers a way to state that relationship and inspect the resulting edits.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.