Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking thread creation/termination

Is it possible to hook into thread termination on Windows? IOW, I would like to be notified if a thread inside the process (not interested in other processes and their threads) has terminated (either normally or - more important - forcefully).

Alternatively, hooking into thread creation would also do.

Rationale: I have a library that manages some information on per-thread basis (think of it as a process-wide per-thread cache for some information). When a thread is terminated I have to remove all thread-specific information from the cache. [Cache associations are implemented using thread ID which may get reused for future threads.]

There's no problem with "normal" execution order as the library user will detach the current thread from the library which will clear the state. Problems start to appear if somebody kills the thread owning cached resource.

like image 575
gabr Avatar asked Sep 27 '10 08:09

gabr


2 Answers

The best way is to call WaitForSingleObject with the HANDLE of the thread (call OpenThread using the thread id to get the HANDLE).

like image 123
Pablo Yabo Avatar answered Oct 26 '22 18:10

Pablo Yabo


If your program is in a dll, you can set up to handle the DllMain method. This is called when a thread or process starts/ends.

For example,

library MyDLL;

uses
   SysUtils, Windows;

procedure DllMain(reason: integer) ;
var
   dyingThreadId: Cardinal;
begin
   case reason of
     DLL_THREAD_DETACH:
     begin
          dyingThreadId := GetCurrentThreadId();
          // handle thread exit with thread id
     end;
   end;
end; 

begin
   DllProc := @DllMain;
end.

EDIT: The call is made in the context of the exiting thread, so you can call GetCurrentThreadId() to get the thread's id.

like image 31
mdma Avatar answered Oct 26 '22 18:10

mdma