Is it possible to release a resource (a file lock, timer) while a program is stopped in the debugger?
More generically, could I execute code before MSVC stops the program for debugging and after resuming execution?
I would like to accomplish to things: - Automatically release a file lock for editing during debugging. - Automatically reload the file after the process resumes - Prevent timers from triggering which overflow during the debug stop - Subtract the duration spent in debugging from timers
Workaround: If I cannot execute code before the program is stopped by the debugger, then detecting programmatically in the program that the debugger stopped the application would already help a lot.
Edit:
I looked at Windows API functions for debugger integration, but it seems functions such as ContinueDebugEvent
are only for the writer of a debugger and never for the process being debugged.
Edit 2: It seems that hotpatching the DbgBreakPoint function could be a way to intercept when the Debugger wants to break a process.
The main idea behind attaching is that a debugger calls the "DebugActiveProcess" function which ends up with calling the "RtlCreateUserThread" function to create a new remote thread into the target process, with the "DbgUiRemoteBreakin" function as the new thread entry point.
(from http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques.html)
DbgUiRemoteBreakin seems to call DbgBreakPoint to actually stop the process.
Edit 3:
I hotpatched both DbgBreakPoint and DebugBreak to see if these methods get called from the MSVC debugger when I break interactively. Alas, they don't! It seems that the MSVC debugger just inserts int 3
at the break point locations and does not call any process method.
Edit 4: Reading up on Structured Exceptions and their interaction with the DebugBreak trap also results in a deadend: When hitting a break point, the interrupt 3 will first reach the kernel, which passes the Structured Exception to the debugger first (if attached). The debugger handles the interrupt and the application never sees it.