private int GetModuleCount(IntPtr codeBase, IMAGE_DATA_DIRECTORY directory) { int result = 0; if (directory.Size > 0) { IMAGE_IMPORT_DESCRIPTOR importDesc = codeBase.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(directory.VirtualAddress); while (importDesc.Name > 0) { string moduleName = Marshal.PtrToStringAnsi(codeBase.Add(importDesc.Name)); if (Native.LoadLibrary(moduleName) == IntPtr.Zero) break; result++; importDesc = codeBase.ToStruct<IMAGE_IMPORT_DESCRIPTOR>((uint)(directory.VirtualAddress + (Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * result))); } } return result; }
private void BuildImportTable64(MEMORYMODULE64 module64) { int moduleCount = 0; IntPtr codeBase = module64.codeBase; IMAGE_DATA_DIRECTORY directory = module64.headers.OptionalHeader.ImportTable; if (directory.Size > 0) { //Log.Console("ImportTable.Size: "+ directory.Size); ulong* nameRef, funcRef; IMAGE_IMPORT_DESCRIPTOR importDesc = codeBase.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(directory.VirtualAddress); while (importDesc.Name > 0) { string moduleName = Marshal.PtrToStringAnsi(codeBase.Add(importDesc.Name)); //Log.Console("Import Module: " + moduleName); IntPtr handle = Native.LoadLibrary(moduleName); if (handle == IntPtr.Zero) break; if (importDesc.CharacteristicsOrOriginalFirstThunk > 0) { nameRef = (ulong*)codeBase.Add(importDesc.CharacteristicsOrOriginalFirstThunk); funcRef = (ulong*)codeBase.Add(importDesc.FirstThunk); } else { nameRef = (ulong*)codeBase.Add(importDesc.FirstThunk); funcRef = (ulong*)codeBase.Add(importDesc.FirstThunk); } for (; *nameRef > 0; nameRef++, funcRef++) { //Log.Console("Import: " + nameRef->ToString("X16") + ", 0x" + funcRef->ToString("x16")); if ((*nameRef & 0x8000000000000000) != 0) { *funcRef = (ulong)Native.GetProcAddress(handle, new IntPtr((long)*nameRef & 0xffff)); } else { string functionName = Marshal.PtrToStringAnsi(codeBase.Add((long)(*nameRef) + 2)); *funcRef = (ulong)Native.GetProcAddress(handle, functionName); //Log.Console("Import Function: " + functionName + " -> 0x" + funcRef->ToString("x16")); } //Log.Console("Import nameRef: 0x" + nameRef->ToString("X16")); //Log.Console("Import funcRef: 0x" + funcRef->ToString("X16")); if (*funcRef == 0) { break; } } moduleCount++; importDesc = codeBase.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(directory.VirtualAddress + (uint)(Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * moduleCount)); } } }