On Thu, Jun 08, 2023 at 08:45:53AM -0700, Linus Torvalds wrote: > So for convenient automatic pointer freeing, you want an interface > much more akin to > > struct whatever *ptr __automatic_kfree = kmalloc(...); > > which is much more legible, doesn't have any type mis-use issues, and > is also just trivially dealt with by a > > static inline void automatic_kfree_wrapper(void *pp) > { void *p = *(void **)pp; if (p) kfree(p); } > #define __automatic_kfree \ > __attribute__((__cleanup__(automatic_kfree_wrapper))) > #define no_free_ptr(p) \ > ({ __auto_type __ptr = (p); (p) = NULL; __ptr; }) > > which I just tested generates the sane code even for the "set the ptr > to NULL and return success" case. > > The above allows you to trivially do things like > > struct whatever *p __automatic_kfree = kmalloc(..); > > if (!do_something(p)) > return -ENOENT; > > return no_free_ptr(p); I am a little worried about how (any version so far of) this API could go wrong, e.g. if someone uses this and does "return p" instead of "return no_free_ptr(p)", it'll return a freed pointer. I was hoping we could do something like this to the end of automatic_kfree_wrapper(): *(void **)pp = NULL; i.e. if no_free_ptr() goes missing, "return p" will return NULL, which is much easier to track down that dealing with later use-after-free bugs, etc. Unfortunately, the __cleanup ordering is _after_ the compiler stores the return value... static inline void cleanup_info(struct info **p) { free(*p); *p = NULL; /* this is effectively ignored */ } struct info *do_something(int f) { struct info *var __attribute__((__cleanup__(cleanup_info))) = malloc(1024); process(var); return var; /* oops, forgot to disable cleanup */ } compile down to: do_something: pushq %rbx movl $1024, %edi call malloc movq %rax, %rbx movq %rax, %rdi call process movq %rbx, %rdi call free movq %rbx, %rax ; uses saved copy of malloc return popq %rbx ret The point being, if we can proactively make this hard to shoot ourselves in the foot, that would be nice. :) -- Kees Cook