Hello :) tl;dr: Compiler-assisted runtime checking of port handling in variables with automatic storage duration. Do we want to go there?
Long version: I recently found a pretty bad resource leak in our crash server and pondered how to find such issues proactively. The main idea is to 1/ clear variables if the right is transferred, and to 2/ check if it is indeed cleared when the variable goes out of scope. 1/ can be idiomatically achieved using variants of mach_port_deallocate that do error checking and clear the variable holding the port name. 2/ can be done in a robust way using the gcc variable attribute 'cleanup' that executes a function when the variable goes out of scope. The follow up patch demonstrates the use of this in the crash servers 'S_crash_dump_task' server function. Using it I already found a bug, my initial attempt of fixing the resource leak in crash was incomplete, and in fact leaking 'ctty_id' when suspending the crashing task. I believe this approach offers strong guarantees: It produces no false negatives (if used correctly...), with acceptable manual work applying it to existing code, and minimal runtime overhead (which can be reduced to zero for NDEBUG builds). Printing meaningful error messages with backtraces will help both fixing bugs and deploying this mechanism. Do we want to do this, or is this too clever for its own good? Cheers, Justus