As I mentioned on one my previous questions I am playing with simulating GetProcAddress() in my code. The following code is successful in doing this, however it causes the application to crash on windows 7
void *GetFuncAddr(HMODULE hModule, char *fname)
{
unsigned int count = 1;
IMAGE_DOS_HEADER *DosHeader;
IMAGE_NT_HEADERS *NtHeaders;
IMAGE_OPTIONAL_HEADER *OptionalHeader;
IMAGE_DATA_DIRECTORY *DataDirectory;
IMAGE_EXPORT_DIRECTORY *Exp;
ULONG *addrof;
char *fullfname;
ULONG *faddr;
DosHeader = (IMAGE_DOS_HEADER *)hModule;
if (DosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
return NULL;
}
NtHeaders = (IMAGE_NT_HEADERS *)(((BYTE *)DosHeader) + DosHeader->e_lfanew);
if (NtHeaders->Signature != IMAGE_NT_SIGNATURE)
{
return NULL;
}
OptionalHeader = &NtHeaders->OptionalHeader;
DataDirectory = &OptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
Exp = (IMAGE_EXPORT_DIRECTORY *)((size_t)DosHeader + DataDirectory->VirtualAddress);
addrof = (ULONG *)((BYTE*) hModule + Exp->addrof);
faddr = (ULONG*) ((BYTE*) hModule + Exp->AddressOfFunctions);
for(count = 0; count < Exp->NumberOfNames; count++)
{
fullfname = (char*)((BYTE*) hModule + addrof[count]);
if(strcmp(fullfname, fname) == 0)
{
return (void*)((BYTE*) hModule + faddr[count]);
}
}
return NULL;
}
It doesn't matter what function I tried loading using this the application crashes. The crashes occurs when calling the imported function so my guess is that the pointer returned might be the offending thing here. This occurs on both x86 and x64. Is there any visible reason for this in this code?
I tried setting the function to return FARPROC but I'm getting all confused about how to cast the return on ((BYTE*) hModule + faddr[count]);
Anyway, any ideas? solutions? Any help is appreciated.
Thanks. jess.
EDIT The error returned by some of the API's i am importing is error 18, the parameter is incorrect.