I’m involved in various C++ projects (mostly using MSVC6 up to MSVC10) in which we recently found a few handle leaks (thread handles as given by the CreateThread function). I suspect that there are plenty of other handles being leaked as well and I’d like to integrate a test which verifies that no handles are leaked into our nightly test results.
My idea was to develop a DLL which instruments the relevant kernel32.dll functions (CreateThread, OpenProcess, CreateProcess and a dozen more) as well as the CloseHandle function. The DLL would then, for each handle being acquired, memorize a backtrace. At the end of the process, the DLL would print all backtraces of handles which weren’t closed to some sort of log file, which could then be parsed by the test framework.
This will of course also yield backtraces for all handles which are still reachable (so technically, they didn’t leak – maybe the author intended that the OS reclaims them when the process terminates) but I Guess explicitely closing them doesn’t hurt – especially since we already have some nice RAII wrappers for this stuff, we just don’t use it as much as we should.
Now I’m wondering – this seems like a fairly straightforward approach; maybe somebody here is alware of a library which already does this?
This is definitely possible, but I don’t think there’s a library that does it yet.
The easiest way, I think, would be with Application Verifier. You can get it from Microsoft’s Debugging Tools for Windows. Configure it to track your application’s handles, run your application in a debugger for a bit, and then a list of handles will be dumped when your application exits.
Another way to do it, without Application Debugger, would be to set a breakpoint or pause before your application exits. While the application is paused, use something like Process Explorer to obtain a list of all open handles.
For your purposes, I think the latter would be the better choice. I’m not sure of any automated tools that use the debug output. You can use some functionality of the WDK to retrieve a list of the current process (or another process’s) open handles, but it is a bit complicated.