本文不是描述怎樣編寫dll程序,也不是說明dll在windows系統的意義。我們的目的是確認dll加載到進程空間的一些模糊的概念。
本文只能說是我結合文檔和一些實驗得出的一點猜測性質的結論,有些結論并沒有官方Microsoft明確的說明,不保證完全正確,歡迎大家交流,共同學習。
一、程序加載dll的兩種情況:
比如對于user32.dll,我們在程序中包含了頭文件<windows.h>:
1.如果沒有調用任何user32.dll的函數,那么user32.dll就不會自動加載,可以通過LoadLibrary來手動加載。比如如下代碼:
#include "stdafx.h"
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])


{
//HINSTANCE hInstance1 = LoadLibrary("user32.dll");
HMODULE hModule1 = GetModuleHandle("user32.dll");
if (!hModule1)

{
printf("Not auto load user32.dll!\n");
}
else

{
printf("OK,auto load user32.dll!\n");
}
//MessageBox(0,"System will auto load user32.dll because of the MessageBox function","tim",0);
getchar();
return 0;
}
運行結果告訴我們user32.dll沒有被加載,而且exe程序的輸入表中也沒有user32.dll:

2.如果我們在程序中調用了dll中的函數,比如MessageBox,那么編譯器會自動將user32.dll中的MessageBoxA(W)寫到輸入表中,這樣user32.dll就會在進程啟動時自動加載到地址空間。代碼就是上面的,只是把MessageBox一句的注釋去掉。其運行結果和輸入表如下:
總結一下:dll模塊可能因為exe的輸入函數而自動加載,也可以在運行后手動加載。
二、從MSDN文檔來研究操作dll的API
1、LoadLibrary
The LoadLibrary function maps the specified executable module into the address space of the calling process.
For additional load options, use the LoadLibraryEx function.
HMODULE LoadLibrary( LPCTSTR lpFileName );
這個函數的作用是把可執行模塊(exe,dll)映射到調用進程的內存空間,同時增加該dll模塊的引用計數(引用計數話題后面再討論)。如果是重復調用LoadLibrary,則就是增加dll模塊的引用計數,并返回模塊句柄。
請特別注意下面這段話:Module handles are not global or inheritable. A call to LoadLibrary by one process does not produce a handle that another process can use — for example, in calling GetProcAddress. The other process must make its own call to LoadLibrary for the module before calling GetProcAddress.
利用LoadLibrary得到的模塊句柄不是全局的,也不是可繼承的。這只在本進程中有效!如果其他進程希望利用模塊句柄來得到函數地址,必須自己調用LoadLibrary來獲取句柄!
2、GetModuleHandle
The GetModuleHandle function retrieves a module handle for the specified module if the file has been mapped into the address space of the calling process.
To avoid the race conditions described in the Remarks section, use the GetModuleHandleEx function.
HMODULE GetModuleHandle( LPCTSTR lpModuleName );
利用這個函數可以得到指定模塊的句柄。注意條件:模塊文件已經被映射到了進程的地址空間!
If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
如果參數為NULL,那么本函數就返回調用進程的句柄。也就是本exe程序的基地址,默認情況下,是400000h。
請注意下面這段話:The returned handle is not global or inheritable. It cannot be duplicated or used by another process.
返回的句柄不是全局的或可繼承的,不能復制和跨進程使用!
If lpModuleName does not include a path and there is more than one loaded module with the same base name and extension, you cannot predict which module handle will be returned. To work around this problem, you could specify a path, use side-by-side assemblies, or use GetModuleHandleEx to specify a memory location rather than a DLL name.
The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. Therefore, use care when passing the handle to the FreeLibrary function, because doing so can cause a DLL module to be unmapped prematurely.
本函數返回模塊句柄,但是不增加引用計數!
This function must be used carefully in a multithreaded application. There is no guarantee that the module handle remains valid between the time this function returns the handle and the time it is used. For example, a thread retrieves a module handle, but before it uses the handle, a second thread frees the module. If the system loads another module, it could reuse the module handle that was recently freed. Therefore, first thread would have a handle to a module different than the one intended.
在多線程環境下要小心使用得到的句柄,因為本模塊在別的線程中釋放了,而有重新加載了別的模塊,并且恰恰復用了這個句柄值。這導致利用這個句柄值訪問的不是期望的模塊。
3、FreeLibrary
The FreeLibrary function decrements the reference count of the loaded dynamic-link library (DLL). When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid.
BOOL FreeLibrary( HMODULE hModule );
本函數減少加載的dll的引用計數。當引用計數被減到0時,這個模塊就會被從進程地址空間卸載,并且句柄不再有效。
請注意下面這段話:
Each process maintains a reference count for each loaded library module. This reference count is incremented each time LoadLibrary is called and is decremented each time FreeLibrary is called. A DLL module loaded at process initialization due to load-time dynamic linking has a reference count of one. This count is incremented if the same module is loaded by a call to LoadLibrary.
每一個進程管理自己的每一個模塊的引用計數。引用計數在每次調用LoadLibrary時遞增,在調用FreeLibrary時遞減。
Before unmapping a library module, the system enables the DLL to detach from the process by calling the DLL's DllMain function, if it has one, with the DLL_PROCESS_DETACH value. Doing so gives the DLL an opportunity to clean up resources allocated on behalf of the current process. After the entry-point function returns, the library module is removed from the address space of the current process.
It is not safe to call FreeLibrary from DllMain. For more information, see the Remarks section in DllMain.
Calling FreeLibrary does not affect other processes using the same library module.
調用FreeLibrary不會影響使用相同庫模塊的其他進程。
總結:
通過上面三個函數的說明,我們發現可以得到以下一些明確的概念:
1、模塊的句柄HModule不是全局的,也不是可繼承的。也就是說,只是保證對一個進程唯一的!不能在進程間復制和跨進程使用。
這也就是說,在不同的進程中,對同一個模塊(dll等),得到的HMODULE不一定相同。系統并不保證這個值全局唯一。
2、模塊的加載和卸載是由引用計數來判斷的。LoadLibrary會遞增引用計數,FreeLibrary會遞減引用計數。當引用計數減少到0時,才會卸載該模塊在進程空間的映射。(下文還有一個特殊情況要討論)
3、模塊的引用計數是進程自己管理的!所以一個進程中引用計數的變化不會影響其他的進程。
請記住模塊的引用計數是進程自己管理的。你在一個進程中調用無限次的FreeLibrary也不會影響別的進程正常使用這個庫模塊。
4、如果只是要查看某個模塊是否被映射,而得到其模塊句柄時,請調用GetModuleHandle。本函數不會主動加載,也不會變更模塊的引用計數。
對應疑惑:
1、我們經常發現,在很多不同的程序中,得到某個指定dll的HMODULE好像都是相同的,所以容易誤以為這個值是全局唯一。但是MSDN告訴我們這是不可靠的,這個判斷是錯誤的。
之所以很多情況下相同時,其實是涉及到PE加載和重定位的問題。對PE的映射,windows盡量將模塊映射到PE指定的地址,來省卻重定位的工作。大部分情況下,那些dll的地址是不沖突的,所以就映射成功,所以不同的程序得到的HMODULE值相同。但是這并不代表任何時候都條件滿足,比如由于程序很大,用到了很多庫,那么就可能導致其默認地址被占用,必須映射到別的地方,那么他的HMODULE就不同。
而且,對應“HMODULE值系統全局唯一”的觀點,很容易就可以得出一個反例:對VS編譯的exe程序,如果沒有指定基地址選項,那么所有不同的進程調用GetModuleHandle(NULL)得到的都是400000h,很明顯,對不同的模塊,卻有相同的值,所以可見該值不是全局的。
2、模塊的引用計數是進程自己管理的。也就是你無論怎么調用LoadLibrary和FreeLibrary,都只會影響本進程的引用計數。不要誤認為是系統維護的。
三、關于引用計數遞減到0會導致模塊卸載映射的問題
上文提到模塊的引用計數遞減到0時,就會將模塊從進程的地址空間卸載,有一個特殊情況。這里就來討論這個特殊情況。
第一部分我們說明了dll加載的兩種情況,在這里正是派上用場的地方!
我們先看第一種情況,代碼如下:


1
#include "stdafx.h"
2
#include <Windows.h>
3
int _tmain(int argc, _TCHAR* argv[])
4

{
5
HMODULE hModule1 = GetModuleHandle("user32.dll");
6
if (!hModule1)
7
{
8
printf("Not auto load user32.dll!\n");
9
}
10
else
11
{
12
printf("OK,auto load user32.dll!\n");
13
}
14
15
HINSTANCE hInstance1 = LoadLibrary("user32.dll");
16
hModule1 = GetModuleHandle("user32.dll");
17
if (hModule1)
18
{
19
printf("Have load user32.dll!\n");
20
}
21
else
22
{
23
printf("Not load user32.dll!\n");
24
}
25
26
int count=0;
27
while(hModule1)
28
{
29
FreeLibrary(hModule1);
30
hModule1 = GetModuleHandle("user32.dll");
31
++count;
32
}
33
34
printf("After call FreeLibrary %d time(s).User32.dll has been Freed!\n",count);
35
36
//MessageBox(0,"System will auto load user32.dll because of the MessageBox function","tim",0);
37
getchar();
38
return 0;
39
}下面是輸出:
我們發現起初進程地址空間中沒有user32.dll。然后通過調用LoadLibrary,user32.dll被成功的加載。然后通過調用FreeLibrary,我們也將user32.dll卸載了。這符合我們在第二部分的討論。
不過一個有趣的現象是:我們在程序中明明只調用LoadLibrary一次,但是要調用4次FreeLibrary,才能釋放該模塊!這實在是有意思。。。
我們再來研究第二種情況,代碼很簡單,就是把上面的代碼36行的MessageBox一句的注釋去掉。這是的運行結果就有意思了:

之所以沒有后面的,是因為程序就永遠的陷入了while循環,永無出頭之日了!也就是無論你怎么調用FreeLibrary,都無法將該模塊從地址空間卸載!
結論:對于由輸入表導入的模塊,不管他是否采用引用計數機制,都無法希望利用FreeLibrary遞減引用計數而卸載!
正因為這個特殊情況,也就是我專門寫本文第一部分的原因。希望這樣的編排不影響你的思考。
www.shnenglu.com/Tim