めいくりぷとのブログ

技術的なことをまったりと。

GetModuleHandle Emulate

GetModuleHandle
https://msdn.microsoft.com/ja-jp/library/ms683199(v=vs.85).aspx

HMODULE
WINAPI
GetModuleHandleW(
	_In_ LPCWSTR lpModuleName
	)
{
	PPEB pProcessEnvironmentBlock;
	HMODULE hModule;

	pProcessEnvironmentBlock = this->GetProcessEnvironmentBlock();
	if (!pProcessEnvironmentBlock)
		return NULL;

	if (lpModuleName != NULL)
	{
		PLDR_DATA_TABLE_ENTRY	pLdrTable;
		PPEB_LDR_DATA			pLdrData;
		PLIST_ENTRY				pListEnd, pList;

		pLdrData = pProcessEnvironmentBlock->Ldr;
		if (pLdrData != NULL)
		{
			pListEnd	= pLdrData->InLoadOrderModuleList.Blink;
			pList		= pLdrData->InLoadOrderModuleList.Flink;

			while (pList != pListEnd)
			{
				pLdrTable = reinterpret_cast<PLDR_DATA_TABLE_ENTRY>(pList);

				if (!this->_wcsicmp(pLdrTable->BaseDllName.Buffer, lpModuleName))
				{
					hModule = reinterpret_cast<HMODULE>(pLdrTable->DllBase);
				}

				pList = pLdrTable->InLoadOrderLinks.Flink;
				
			}
		}
	}
	else
	{
		hModule = reinterpret_cast<HMODULE>(pProcessEnvironmentBlock->ImageBaseAddress);
	}

	return hModule;
}