Watch your scope! The hidden pitfalls of scoped_guard() and other cleanup.h macros
2026-05-27 , Auditorium

Everyone loves "cleaning up" code in the Linux kernel using macros from linux/cleanup.h. It's one of the latest fads. There have been hundreds of "clean up" patches and these macros are used thousands of times in the kernel now. However, these macros have some hidden secrets that can result in hard-to-spot bugs and mysterious compiler warnings! As these gain wider use and acceptance, let's see what the problems are and what we should do about it.


Spoiler alert:

scoped_guard() contains a for loop, so using break and continue keywords in this scope doesn't do what one might think. I've found and reported a number of cases where this mistake made it into the kernel. Even experienced kernel maintainers are missing this and submitting patches with bugs. This makes me wary of using scoped_guard() in general, but I seem to be in the minority.

The other cleanup macros introduce local variables. The clang compiler doesn't like this when you use them in a switch statement. I'll show the compiler warning/error and how to avoid it.

David is a senior Embedded Software Engineer at BayLibre. He learned (almost) everything he knows about embedded systems from hacking on LEGO MINDSTORMS robots. In the Linux kernel world, he is a reviewer for the IIO subsystem (and is maintainer for some LEGO MINDSTORMS EV3 drivers, of course!). In his spare time, he maintains Bleak, a cross-platform Bluetooth Low Energy library for Python and co-maintains Pybricks, a 3rd-party firmware and IDE for LEGO "smart hubs" based on MicroPython.