Trao đổi với tôi

http://www.buidao.com

4/24/10

[Programming] GetProcName


#define MakePtr( cast, ptr, addValue ) (cast)((DWORD)(ptr) + (addValue))

LPVOID GetBaseAddress(DWORD dwAddr)
{
HANDLE hSnap;
LPVOID ret = NULL;
MODULEENTRY32 me32;

hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0);
if (hSnap == NULL) {
goto end;
}

memset(&me32, 0, sizeof(MODULEENTRY32));
me32.dwSize = sizeof(MODULEENTRY32);
if (Module32First(hSnap, &me32)) {
do {
if (((DWORD)me32.modBaseAddr <= dwAddr) &&
(dwAddr < ((DWORD)me32.modBaseAddr +
me32.modBaseSize))) {
ret = me32.modBaseAddr;
goto end;
}

} while (Module32Next(hSnap, &me32));
}

end:
if (hSnap)
CloseHandle(hSnap);

return ret;
}

void GetProcName(FARPROC proc, LPSTR lpBuf, DWORD dwSize)
{
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS ntHeader;
PIMAGE_EXPORT_DIRECTORY pExportDir;
DWORD dwExportRVA;
DWORD i;
WORD offset;
DWORD *ppNames;
DWORD *ppFuncs;
WORD *ppOrdinal;

dosHeader = (PIMAGE_DOS_HEADER)GetBaseAddress((DWORD)proc);
if (!dosHeader)
goto end;

ntHeader = MakePtr(PIMAGE_NT_HEADERS, dosHeader,
dosHeader->e_lfanew);
if (ntHeader->Signature != IMAGE_NT_SIGNATURE)
goto end;

dwExportRVA = ntHeader->OptionalHeader.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
if (!dwExportRVA)
goto end;

pExportDir = MakePtr(PIMAGE_EXPORT_DIRECTORY, dosHeader,
dwExportRVA);

ppNames = MakePtr(DWORD*, dosHeader,
pExportDir->AddressOfNames);
ppFuncs = MakePtr(DWORD*, dosHeader,
pExportDir->AddressOfFunctions);
ppOrdinal = MakePtr(WORD*, dosHeader,
pExportDir->AddressOfNameOrdinals);

if (!ppNames || !ppFuncs || !ppOrdinal ||
!pExportDir->NumberOfFunctions)
goto end;

for (i = 0; i <>NumberOfFunctions; i++) {
offset = ppOrdinal[i];
if (MakePtr(DWORD, dosHeader, ppFuncs[offset]) ==
(DWORD)proc) {
strcpy_s(lpBuf, dwSize,
MakePtr(LPSTR, dosHeader, ppNames[i]));
goto end;
}
}

end:
return;
}



reflink: http://d.hatena.ne.jp/t04ya0/20080902/1220369795