逆向分析_DLL基础(3)

DLL基础(3) DllMain处理
(一) 创建dll release项目(sum)
//sum.cpp
#include
#include

extern "C" int __declspec(dllexport)  __stdcall add(int x, int y);

int __stdcall add(int x, int y)
{
	return x + y;
}

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL,
    DWORD     fdwReason,
    LPVOID    lpvReserved
){
    switch (fdwReason) //Dll被调用的原因
    {
    case DLL_PROCESS_ATTACH:
        printf("process attach of dll\n");
        break;
    case DLL_THREAD_ATTACH:
        printf("thread attach of dll\n");
        break;
    case DLL_THREAD_DETACH:
        printf("thread detach of dll\n");
        break;
    case DLL_PROCESS_DETACH:
        printf("process detach of dll\n");
        break;
    }
    return TRUE;
}

(二) 静态加载DLL

创建Win32 Console空项目,添加文件my_dll_main.cpp,把sum.lib sum.dll复制到该项目下

//my_dll_main.cpp
//#define APIENTRY WINAPI
//#define WINAPI __stdcall
/*
BOOL WINAPI DllMain(
  _In_ HINSTANCE hinstDLL,
  _In_ DWORD     fdwReason,
  _In_ LPVOID    lpvReserved
);
*/

#include 
#include 
#include 

#pragma comment(lib,"sum.lib")

typedef int(__stdcall *lpAddFunc)(int,int);  //宏定义函数指针类型

int main(int argc, char *argv[])
{
	HINSTANCE hDll;			//DLL 句柄	
	lpAddFunc addFunc;		//函数指针
	hDll = LoadLibrary("sum.dll");
	if(hDll != NULL)
	{
		//addFunc = (lpAddFunc)GetProcAddress(hDll,"add");
        addFunc = (lpAddFunc)GetProcAddress(hDll, MAKEINTRESOURCE(1));
        //MAKEINTRESOURCE 直接使用导出文件中的序号
		if(addFunc != NULL)
		{
			int result = addFunc(2,3);
			printf("%d\n", result);
			system("pause");
		}
	}
	FreeLibrary(hDll);
	return 0;
}

进程中的每个DLL模块被全局唯一的32字节的HINSTANCE句柄标识,只有在特定的进程内部有效,句柄代表了DLL模块在进程虚拟空间中的起始地址

GetProcAddress(hDll, MAKEINTRESOURCE(1))直接通过.def文件中add函数指定的顺序号访问函数,MAKEINTRESOURCE是一个通过序号获取函数名的宏。

你可能感兴趣的:(Binary)