Scope-based resource management for the kernel (Merged with Linux 6.5)

The C language lacks the resource-management features seen in more contemporary languages. As a result, vulnerabilities involving spilled memory or failure to release a lock are rather prevalent in C applications, including the kernel. However, the kernel project has never been confined to the language features included in the C standard; kernel engineers will gladly adopt compiler extensions if they prove useful. It appears that a relatively basic compiler-supplied feature could result in a considerable shift in some popular kernel code patterns.
The feature in question is the cleaning attribute, which is supported by both GCC and Clang. It enables the declaration of variables using syntax such as:

The feature, specifically, is the cleanup attribute, which is implemented by both GCC and Clang. It allows a variable to be declared using a syntax like:

type my_var __attribute__((__cleanup__(cleanup_func)));
The extra attribute says that, when my_var, a variable of the given type, goes out of scope, a call should be made to:

cleanup_func(&my_var);
This function, it is assumed, will do some sort of final cleanup on that variable before it disappears forever. As an example, one could declare a pointer (in the kernel) this way:

void auto_kfree(void **p) { kfree(*p); }

struct foo *foo_ptr __attribute__((__cleanup__(auto_kfree))) = NULL;
/* ... */
foo_ptr = kmalloc(sizeof(struct foo));


Details found here -
https://lwn.net/Articles/934679/
https://clang.llvm.org/docs/AttributeReference.html#cleanup
https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html

Comments

Popular posts from this blog

Infiniband Application's Memory Buffer Mapped into the RDMA Device's Address Space

PCIe Address Translation Unit (ATU) in Linux

Learning Experience with Linux Foundation