private void BuildImportTable() { IMAGE_DATA_DIRECTORY *directory = &this.headers->OptionalHeader.ImportTable; if (directory->Size > 0) { IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(this.codeBase + directory->VirtualAddress); for (; !NativeDeclarations.IsBadReadPtr(new IntPtr(importDesc), (uint)Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR))) && importDesc->Name > 0; importDesc++) { uint *thunkRef; int * funcRef; string funcName = Marshal.PtrToStringAnsi(new IntPtr(this.codeBase + importDesc->Name)); IntPtr handle = NativeDeclarations.LoadLibrary(funcName); if (handle == IntPtr.Zero) { throw new NativeDllLoadException("Can't load libary " + funcName); } this.modules.Add(handle); if (importDesc->OriginalFirstThunk > 0) { thunkRef = (uint *)(codeBase + importDesc->OriginalFirstThunk); funcRef = (int *)(codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (uint *)(codeBase + importDesc->FirstThunk); funcRef = (int *)(codeBase + importDesc->FirstThunk); } for (; *thunkRef > 0; thunkRef++, funcRef++) { string procName; if (NativeDeclarations.IMAGE_SNAP_BY_ORDINAL32(*thunkRef)) { procName = Marshal.PtrToStringAnsi(new IntPtr(NativeDeclarations.IMAGE_ORDINAL32(*thunkRef))); *funcRef = (int)NativeDeclarations.GetProcAddress(handle, procName); } else { IMAGE_IMPORT_BY_NAME *thunkData = (IMAGE_IMPORT_BY_NAME *)(codeBase + (*thunkRef)); procName = Marshal.PtrToStringAnsi(new IntPtr(thunkData->Name)); *funcRef = (int)NativeDeclarations.GetProcAddress(handle, procName); } if (*funcRef == 0) { throw new NativeDllLoadException("Can't get adress for " + procName); } } } } }