本文不是描述怎樣編寫dll程序,也不是說明dll在windows系統(tǒng)的意義。我們的目的是確認(rèn)dll加載到進(jìn)程空間的一些模糊的概念。
本文只能說是我結(jié)合文檔和一些實(shí)驗(yàn)得出的一點(diǎn)猜測(cè)性質(zhì)的結(jié)論,有些結(jié)論并沒有官方Microsoft明確的說明,不保證完全正確,歡迎大家交流,共同學(xué)習(xí)。
1.如果沒有調(diào)用任何user32.dll的函數(shù),那么user32.dll就不會(huì)自動(dòng)加載,可以通過LoadLibrary來手動(dòng)加載。比如如下代碼:
2.如果我們?cè)诔绦蛑姓{(diào)用了dll中的函數(shù),比如MessageBox,那么編譯器會(huì)自動(dòng)將user32.dll中的MessageBoxA(W)寫到輸入表中,這樣user32.dll就會(huì)在進(jìn)程啟動(dòng)時(shí)自動(dòng)加載到地址空間。代碼就是上面的,只是把MessageBox一句的注釋去掉。其運(yùn)行結(jié)果和輸入表如下:
請(qǐng)?zhí)貏e注意下面這段話: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得到的模塊句柄不是全局的,也不是可繼承的。這只在本進(jìn)程中有效!如果其他進(jìn)程希望利用模塊句柄來得到函數(shù)地址,必須自己調(diào)用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 );
利用這個(gè)函數(shù)可以得到指定模塊的句柄。注意條件:模塊文件已經(jīng)被映射到了進(jìn)程的地址空間!
If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
如果參數(shù)為NULL,那么本函數(shù)就返回調(diào)用進(jìn)程的句柄。也就是本exe程序的基地址,默認(rèn)情況下,是400000h。
請(qǐng)注意下面這段話:The returned handle is not global or inheritable. It cannot be duplicated or used by another process.
返回的句柄不是全局的或可繼承的,不能復(fù)制和跨進(jìn)程使用!
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.
本函數(shù)返回模塊句柄,但是不增加引用計(jì)數(shù)!
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.
在多線程環(huán)境下要小心使用得到的句柄,因?yàn)楸灸K在別的線程中釋放了,而有重新加載了別的模塊,并且恰恰復(fù)用了這個(gè)句柄值。這導(dǎo)致利用這個(gè)句柄值訪問的不是期望的模塊。
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 );
本函數(shù)減少加載的dll的引用計(jì)數(shù)。當(dāng)引用計(jì)數(shù)被減到0時(shí),這個(gè)模塊就會(huì)被從進(jìn)程地址空間卸載,并且句柄不再有效。
請(qǐng)注意下面這段話:
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.
每一個(gè)進(jìn)程管理自己的每一個(gè)模塊的引用計(jì)數(shù)。引用計(jì)數(shù)在每次調(diào)用LoadLibrary時(shí)遞增,在調(diào)用FreeLibrary時(shí)遞減。
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.
調(diào)用FreeLibrary不會(huì)影響使用相同庫(kù)模塊的其他進(jìn)程。
總結(jié):
通過上面三個(gè)函數(shù)的說明,我們發(fā)現(xiàn)可以得到以下一些明確的概念:
1、模塊的句柄HModule不是全局的,也不是可繼承的。也就是說,只是保證對(duì)一個(gè)進(jìn)程唯一的!不能在進(jìn)程間復(fù)制和跨進(jìn)程使用。
這也就是說,在不同的進(jìn)程中,對(duì)同一個(gè)模塊(dll等),得到的HMODULE不一定相同。系統(tǒng)并不保證這個(gè)值全局唯一。
2、模塊的加載和卸載是由引用計(jì)數(shù)來判斷的。LoadLibrary會(huì)遞增引用計(jì)數(shù),F(xiàn)reeLibrary會(huì)遞減引用計(jì)數(shù)。當(dāng)引用計(jì)數(shù)減少到0時(shí),才會(huì)卸載該模塊在進(jìn)程空間的映射。(下文還有一個(gè)特殊情況要討論)
3、模塊的引用計(jì)數(shù)是進(jìn)程自己管理的!所以一個(gè)進(jìn)程中引用計(jì)數(shù)的變化不會(huì)影響其他的進(jìn)程。
請(qǐng)記住模塊的引用計(jì)數(shù)是進(jìn)程自己管理的。你在一個(gè)進(jìn)程中調(diào)用無限次的FreeLibrary也不會(huì)影響別的進(jìn)程正常使用這個(gè)庫(kù)模塊。
4、如果只是要查看某個(gè)模塊是否被映射,而得到其模塊句柄時(shí),請(qǐng)調(diào)用GetModuleHandle。本函數(shù)不會(huì)主動(dòng)加載,也不會(huì)變更模塊的引用計(jì)數(shù)。
對(duì)應(yīng)疑惑:
1、我們經(jīng)常發(fā)現(xiàn),在很多不同的程序中,得到某個(gè)指定dll的HMODULE好像都是相同的,所以容易誤以為這個(gè)值是全局唯一。但是MSDN告訴我們這是不可靠的,這個(gè)判斷是錯(cuò)誤的。
之所以很多情況下相同時(shí),其實(shí)是涉及到PE加載和重定位的問題。對(duì)PE的映射,windows盡量將模塊映射到PE指定的地址,來省卻重定位的工作。大部分情況下,那些dll的地址是不沖突的,所以就映射成功,所以不同的程序得到的HMODULE值相同。但是這并不代表任何時(shí)候都條件滿足,比如由于程序很大,用到了很多庫(kù),那么就可能導(dǎo)致其默認(rèn)地址被占用,必須映射到別的地方,那么他的HMODULE就不同。
而且,對(duì)應(yīng)“HMODULE值系統(tǒng)全局唯一”的觀點(diǎn),很容易就可以得出一個(gè)反例:對(duì)VS編譯的exe程序,如果沒有指定基地址選項(xiàng),那么所有不同的進(jìn)程調(diào)用GetModuleHandle(NULL)得到的都是400000h,很明顯,對(duì)不同的模塊,卻有相同的值,所以可見該值不是全局的。
2、模塊的引用計(jì)數(shù)是進(jìn)程自己管理的。也就是你無論怎么調(diào)用LoadLibrary和FreeLibrary,都只會(huì)影響本進(jìn)程的引用計(jì)數(shù)。不要誤認(rèn)為是系統(tǒng)維護(hù)的。
三、關(guān)于引用計(jì)數(shù)遞減到0會(huì)導(dǎo)致模塊卸載映射的問題
上文提到模塊的引用計(jì)數(shù)遞減到0時(shí),就會(huì)將模塊從進(jìn)程的地址空間卸載,有一個(gè)特殊情況。這里就來討論這個(gè)特殊情況。
第一部分我們說明了dll加載的兩種情況,在這里正是派上用場(chǎng)的地方!
我們先看第一種情況,代碼如下:


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
}下面是輸出:
我們發(fā)現(xiàn)起初進(jìn)程地址空間中沒有user32.dll。然后通過調(diào)用LoadLibrary,user32.dll被成功的加載。然后通過調(diào)用FreeLibrary,我們也將user32.dll卸載了。這符合我們?cè)诘诙糠值挠懻摗?/p>
不過一個(gè)有趣的現(xiàn)象是:我們?cè)诔绦蛑忻髅髦徽{(diào)用LoadLibrary一次,但是要調(diào)用4次FreeLibrary,才能釋放該模塊!這實(shí)在是有意思。。。
我們?cè)賮硌芯康诙N情況,代碼很簡(jiǎn)單,就是把上面的代碼36行的MessageBox一句的注釋去掉。這是的運(yùn)行結(jié)果就有意思了:

之所以沒有后面的,是因?yàn)槌绦蚓陀肋h(yuǎn)的陷入了while循環(huán),永無出頭之日了!也就是無論你怎么調(diào)用FreeLibrary,都無法將該模塊從地址空間卸載!
結(jié)論:對(duì)于由輸入表導(dǎo)入的模塊,不管他是否采用引用計(jì)數(shù)機(jī)制,都無法希望利用FreeLibrary遞減引用計(jì)數(shù)而卸載!
正因?yàn)檫@個(gè)特殊情況,也就是我專門寫本文第一部分的原因。希望這樣的編排不影響你的思考。
www.shnenglu.com/Tim