This code snippet can be useful in case of code caving. It helps to get absolute address of any exported module function inside of external process memory (any directx or kernel functions). BlackMagic class (named wow) is used here to retrieve all process modules and for mem reading. Example:
uint OpenMutexA=FindFuncAdress("kernel32.dll", "OpenMutexA");
Code:
public uint FindFuncAdress(string moduleName, string functionName)
{
uint moduleAdress=0; //get module adress to find function in
foreach (ProcessModule pm in wow.Modules)
if (pm.ModuleName == moduleName)
{
moduleAdress = (uint)pm.BaseAddress;
break;
}
if (moduleAdress != 0)
{
uint ptr=wow.ReadUInt(moduleAdress+0x3c); //skip ms-dos header
ptr = wow.ReadUInt(moduleAdress + ptr + 0x78);//go to export table
int count = wow.ReadInt(moduleAdress + ptr + 0x18);//export function count
uint nameTable = wow.ReadUInt(moduleAdress + ptr + 0x20);//table names adress
int funcIndex = -1;
for (int i = 0; i < count; i++) //iterate throught name table to find all functions
{
uint currentNamePtr = wow.ReadUInt(moduleAdress+ nameTable +(uint) i * 4);
string currentName = wow.ReadASCIIString(moduleAdress + currentNamePtr, 64);
if (currentName == functionName) { funcIndex = i; break; } //found our function
}
if (funcIndex == -1) { throw new Exception(functionName + " not found in module"); return 0; } //no matches
uint ordinalsTable = wow.ReadUInt(moduleAdress + ptr + 0x24) + moduleAdress;//get ordinals array adress and rebase it
int ordinalNumber = wow.ReadShort(ordinalsTable + (uint)funcIndex * 2);
uint relativeTable = wow.ReadUInt(moduleAdress + ptr + 0x1c) + moduleAdress;//get RVA array
uint functionAdress = wow.ReadUInt(relativeTable + (uint)ordinalNumber * 4) + moduleAdress;//get function ptr and rebase it
return functionAdress;
}
else
{
throw new Exception(moduleName+" not found");
return 0;
}
}