
Tony Juricic wrote:
Since we are sort of messing with PEF and considering a separate DLL for catching thread exit notifications (it won't work with threads forcefully terminated with TerminateThread Win32 API) perhaps hooking Win32 API calls ExitThread and TerminateThread would be one solution?
I've given this some amount of thought, but to be honest, I don't see any way this could be done reliably and without making some serious compromises: -I think it might be possible for threads to die some other way. I don't think anything makes any guarantee that ExitThread and TerminateThread are the only ways a thread may exit. For example, a thread may be caused to exit by some lower-level API (perhaps a direct access to NTDLL). -Hooking itself is problematic. I don't think that modifying kernel32's in-memory EAT is going to catch all possible ways ExitThread might be called. An alternate proposed strategy is to directly alter the first few bytes of the function the EAT refers to, but this is also not generally correct (a jmp is typically five bytes, but there might be some jmp into the middle of that instr), and also is a system global change on Win9x systems. Besides these problems, modifying in-memory DLL images in any manner is undesirable, as it will trigger COW semantics and cause possibly significant increases in memory usage. -Hooking may interfere with proper operation of debuggers. Hooking is great strategy for a debugger, or for programs designed to act as debuggers, but I think it is far to risky a technique to rely on for normal application programs. The advantage you mention (besides possibly having a valid PTD at dtor-time) is that we can execute dtors for threads killed by TerminateThread. I don't know if this is a good idea. In the general case, there is no particular guarantee about what context the thread will be in when you call TerminateThread. In particular, any and all thread-local data structures may be in an inconsistant state. Executing dtors in this situation would be wrong, and would lead to undesirable and unpredictable actions. Aaron W. LaFramboise