Controling DLL loading

Submitted by:Pitter Alderson

Date added:28 March, 2011


When you are writing dynamic link libraries and need to control the loading and unloading of a DLL, or if you want to initialize your DLL when it is loaded, you can have a function called DllMain do your initialization. Windows calls the DllMain function of a DLL in four instances:

1) When a process attaches the DLL
2) When a thread attaches the DLL
3) When a process detaches the DLL
4) When a thread detaches the DLL

Each DLL has an enty point. This entry point is implemented as a callback function. It is called by system when a set of event occurs. Function has default name DllMain. A DLL that doesn't want to be loaded by a certain caller can simply return False in its DllMain() function once it detects who's calling.

In Delphi, DLLProc is used to specify a procedure that is invoked every time a DLL's entry point is called. A procedure assigned to DLLProc takes one Integer parameter (Reason).

The GetModuleFileName() API function returns the name of the caller module if you pass 0 as its first argument. Such a parameter is the handle of the module whose name you want to know.

When the Reason parameter is DLL_PROCESS_ATTACH, setting ExitCode to a nonzero value causes the entry point to return false.

Here's a sample code, we are allowing only MyCallingApp.exe to load the library (note: the DLL in this example has NO code except the DLLMain procedure):

Tags: dynamic link libraries , dll loading

Code Snippet:

library OnlyMyDLL;

SysUtils, Windows;

procedure DllMain(reason: integer) ;
buf : array[0..MAX_PATH] of char;
loader : string;
case reason of
GetModuleFileName(0, buf, SizeOf(buf)) ;
loader := buf;
if Pos('MyCallingApp.exe', loader) > 0 then
ExitCode := -1
//DLL unloading...
end; (*DllMain*)

DllProc := @DllMain;

//more DLL code here...