public IProcessFunction FindFunction(string functionName)
{
//Console.WriteLine("Looking for function "+functionName+" in "+ThisModule.FileName);
// Check if the function is already cached
if (CachedFunctions.ContainsKey(functionName))
return CachedFunctions[functionName];
// If the function is not cached
// Check if the local process has this module loaded
var localModule =
Process.GetCurrentProcess()
.Modules.Cast<ProcessModule>()
.FirstOrDefault(m => m.FileName.ToLower() == Path.ToLower());
var isManuallyLoaded = false;
try
{
// If this is not the case, load the module inside the local process
if (localModule == null)
{
isManuallyLoaded = true;
Console.WriteLine("Loading libary to local memory "+ ThisModule.FileName);
localModule = NativeHelper.LoadLibrary(ThisModule.FileName);
}
// Get the offset of the function
var offset = NativeHelper.GetProcAddress(localModule, functionName).ToInt64() -
localModule.BaseAddress.ToInt64();
Console.WriteLine("Function "+functionName+" Address: "+ offset);
var functionAddress = new IntPtr(ThisModule.BaseAddress.ToInt64() + offset);
// Rebase the function with the remote module
var function = new Function(functionAddress, functionName);
lock (CachedFunctions)
{
// Store the function in the cache
CachedFunctions.Add(functionName, function);
}
// Return the function rebased with the remote module
return function;
}
finally
{
// Free the module if it was manually loaded
if (isManuallyLoaded)
NativeHelper.FreeLibrary(localModule);
}
}