public DllContext(string filePath, bool runHash = true) { DLLPath = filePath; if (!File.Exists(DLLPath)) { Console.WriteLine($"{DLLPath}: File does not exist"); return; } FileName = Path.GetFileName(filePath); // Compute and store the file hash if (runHash) { using (var cryptoProvider = new SHA1CryptoServiceProvider()) { SHA1Hash = BitConverter.ToString(cryptoProvider.ComputeHash(File.ReadAllBytes(filePath))).Replace("-", ""); } } // Get the module's exports DllExports = UnmanagedUtility.GetExports(DLLPath); if (DllExports.Count == 0) { Console.WriteLine($"{DLLPath}: No exports, possibly an invalid DLL"); return; } // Try to load the library into our process space dllHandle = UnmanagedUtility.LoadLibrary(filePath); if (dllHandle == IntPtr.Zero) { Console.WriteLine($"{DLLPath}: LoadLibrary failed"); return; } // Try to load addresses of all known exports dllAddressMappings = new Dictionary <string, IntPtr>(); foreach (string knownExport in ExportDefinition.KnownExportedFunctions) { if (DllExports.Contains(knownExport)) { dllAddressMappings.Add(knownExport, UnmanagedUtility.GetProcAddress(dllHandle, knownExport)); } else { dllAddressMappings.Add(knownExport, IntPtr.Zero); } } // Set capabilities KeyGenerationCapability = DllExports.Contains("GenerateKeyEx") || DllExports.Contains("GenerateKeyExOpt"); ModeSpecified = DllExports.Contains("GetKeyLength") && DllExports.Contains("GetSeedLength") && DllExports.Contains("GetConfiguredAccessTypes"); // Store additional metadata FileDescription = FileVersionInfo.GetVersionInfo(DLLPath).FileDescription; LoadAdditionalDataFromDllCalls(); }
public void UnloadLibrary() { // WARNING: the instance will no longer be able to access native functions after this is called // This is a workaround if many DLLs have to be enumerated for their metadata -- Windows has a limit on the number of DLLs that can be loaded simultaneously UnmanagedUtility.FreeLibrary(dllHandle); }