├── README.md ├── App.config ├── HwidGetCurrentEx ├── Properties │ └── AssemblyInfo.cs ├── GUID_DEVINTERFACE.cs ├── StructHWID.cs ├── MinWinDef.cs ├── HwidGetCurrentEx.csproj ├── CPUID.cs ├── ComHelper.cs ├── BitUtil.cs ├── SMBIOS.cs └── Native.cs ├── Properties ├── AssemblyInfo.cs └── app.manifest ├── VRSAVaultSignPKCS ├── VRSA.cs ├── DynamicDllLoader.cs └── DLLFromMemory.cs ├── HwidGetCurrentEx.sln ├── .gitattributes ├── gatherosstate.csproj ├── .gitignore └── Program.cs /README.md: -------------------------------------------------------------------------------- 1 | hwIdGetCURRENTeX -------------------------------------------------------------------------------- /App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /HwidGetCurrentEx/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using System.Runtime.CompilerServices; 5 | using System.Runtime.InteropServices; 6 | using System.Runtime.Versioning; 7 | using System.Security; 8 | using System.Security.Permissions; 9 | 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyConfiguration("")] 12 | [assembly: AssemblyCopyright("Copyright © 2022")] 13 | [assembly: AssemblyDescription("")] 14 | [assembly: AssemblyFileVersion("1.0.0.0")] 15 | [assembly: AssemblyProduct("HwidGetCurrentEx")] 16 | [assembly: AssemblyTitle("HwidGetCurrentEx")] 17 | [assembly: AssemblyTrademark("")] 18 | [assembly: AssemblyVersion("1.0.0.0")] 19 | [assembly: ComVisible(false)] 20 | [assembly: Guid("053495d7-7335-4890-b187-925f8f150bc2")] 21 | [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] 22 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 控制。更改这些特性值可修改 与程序集关联的信息。 5 | [assembly: AssemblyTitle("gatherosstate")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("gatherosstate")] 10 | [assembly: AssemblyCopyright("Copyright © 2022")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | // 将 ComVisible 设置为 false 会使此程序集中的类型 15 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 16 | //请将此类型的 ComVisible 特性设置为 true。 17 | [assembly: ComVisible(false)] 18 | 19 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 20 | [assembly: Guid("728adad5-ad62-469b-8270-d47e34a11cb8")] 21 | 22 | // 程序集的版本信息由下列四个值组成: 23 | // 24 | // 主版本 25 | // 次版本 26 | // 生成号 27 | // 修订号 28 | // 29 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 30 | //通过使用 "*",如下所示: 31 | // [assembly: AssemblyVersion("1.0.*")] 32 | [assembly: AssemblyVersion("1.0.0.0")] 33 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /HwidGetCurrentEx/GUID_DEVINTERFACE.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.GUID_DEVINTERFACE 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System; 7 | 8 | namespace HwidGetCurrentEx 9 | { 10 | public class GUID_DEVINTERFACE 11 | { 12 | public static Guid GUID_DEVCLASS_HDC = new Guid("4d36e96a-e325-11ce-bfc1-08002be10318"); 13 | public static Guid GUID_DEVCLASS_DISPLAY = new Guid("4d36e968-e325-11ce-bfc1-08002be10318"); 14 | public static Guid GUID_DEVCLASS_SCSIADAPTER = new Guid("4d36e97b-e325-11ce-bfc1-08002be10318"); 15 | public static Guid GUID_DEVCLASS_PCMCIA = new Guid("4d36e977-e325-11ce-bfc1-08002be10318"); 16 | public static Guid GUID_DEVCLASS_MEDIA = new Guid("4d36e96c-e325-11ce-bfc1-08002be10318"); 17 | public static Guid GUID_NDIS_LAN_CLASS = new Guid("ad498944-762f-11d0-8dcb-00c04fc3358c"); 18 | public static Guid GUID_BTHPORT_DEVICE_INTERFACE = new Guid("0850302A-B344-4fda-9BE9-90576B8D46F0"); 19 | public static Guid GUID_DEVINTERFACE_CDROM = new Guid("4D36E965-E325-11CE-BFC1-08002BE10318"); 20 | public static Guid GUID_DEVINTERFACE_DISK = new Guid("53f56307-b6bf-11d0-94f2-00a0c91efb8b"); 21 | public static Guid GUID_6994ad04_93ef_11d0_a3cc_00a0c9223196 = new Guid("6994ad04-93ef-11d0-a3cc-00a0c9223196"); 22 | } 23 | } -------------------------------------------------------------------------------- /VRSAVaultSignPKCS/VRSA.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: VRSAVaultSignPKCS.VRSA 3 | // Assembly: VRSAVaultSignPKCS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 835E1F41-447B-4B59-919B-3F453537ACCB 5 | // Assembly location: D:\downloads\Programs\VRSAVaultSignPKCS-cleaned.dll 6 | 7 | using System; 8 | using System.Runtime.InteropServices; 9 | 10 | namespace VRSAVaultSignPKCS 11 | { 12 | public class VRSA 13 | { 14 | public static byte[] SignPKCS(byte[] HashArray) 15 | { 16 | byte[] DST = new byte[256]; 17 | uint outSize = 256; 18 | DLLFromMemory dllFromMemory = new DLLFromMemory(PeArray.rawData); 19 | byte[] numArray; 20 | if (((VRSA.VRSAVaultSignPKCS86) Marshal.GetDelegateForFunctionPointer(new IntPtr(dllFromMemory.pCode.ToInt32() + 313463), typeof (VRSA.VRSAVaultSignPKCS86)))(IntPtr.Zero, IntPtr.Zero, HashArray, HashArray.Length, DST, ref outSize) == 0) 21 | { 22 | dllFromMemory.Close(); 23 | numArray = DST; 24 | } 25 | else 26 | { 27 | dllFromMemory.Close(); 28 | numArray = (byte[]) null; 29 | } 30 | return numArray; 31 | } 32 | 33 | [UnmanagedFunctionPointer(CallingConvention.ThisCall, CharSet = CharSet.Unicode)] 34 | private delegate int VRSAVaultSignPKCS86( 35 | IntPtr pVbnRsaVault_ModExpPriv_clear, 36 | IntPtr handle, 37 | byte[] dwbyte, 38 | int dwsize, 39 | byte[] DST, 40 | ref uint outSize); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /HwidGetCurrentEx/StructHWID.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.StructHWID 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | namespace HwidGetCurrentEx 7 | { 8 | public class StructHWID 9 | { 10 | public int cbsize; 11 | public short BiosHwidCount; 12 | public short MemoryHwidCount; 13 | public short CpuHwidCount; 14 | public short NdisHwidCount; 15 | public short HWProfileCount; 16 | public short GuidHwidCount; 17 | public short PcmciaHwidCount; 18 | public short BthPortHwidCount; 19 | public short ScsiAdapterHwidCount; 20 | public short DisplayHwidCount; 21 | public short DiskHwidCount; 22 | public short HdcHwidCount; 23 | public short WwanHwidCount; 24 | public short CdromHwidCount; 25 | public byte[] BiosHwidBlock; 26 | public byte[] MemoryHwidBlock; 27 | public byte[] CpuHwidBlock; 28 | public byte[] NdisHwidBlock; 29 | public byte[] HWProfileBlock; 30 | public byte[] GuidHwidBlock; 31 | public byte[] PcmciaHwidBlock; 32 | public byte[] BthPortHwidBlock; 33 | public byte[] ScsiAdapterHwidBlock; 34 | public byte[] DisplayHwidBlock; 35 | public byte[] DiskHwidBlock; 36 | public byte[] HdcHwidBlock; 37 | public byte[] WwanHwidBlock; 38 | public byte[] CdromHwidBlock; 39 | } 40 | } -------------------------------------------------------------------------------- /HwidGetCurrentEx/MinWinDef.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.MinWinDef 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System; 7 | 8 | namespace HwidGetCurrentEx 9 | { 10 | public static class MinWinDef 11 | { 12 | internal static Func MAKEWORD = (Func)((a, b) => (object)(ushort)((uint)(byte)((ulong)a & (ulong)byte.MaxValue) | (uint)(byte)((ulong)b & (ulong)byte.MaxValue) << 8)); 13 | internal static Func MAKELONG = (Func)((a, b) => (object)(ulong)((int)(ushort)((ulong)a & (ulong)byte.MaxValue) | (int)(byte)((ulong)b & (ulong)byte.MaxValue) << 8)); 14 | internal static Func LOWORD = (Func)(l => (object)(ushort)((ulong)l & (ulong)ushort.MaxValue)); 15 | internal static Func HIWORD = (Func)(l => (object)(ushort)((ulong)l >> 16 & (ulong)ushort.MaxValue)); 16 | internal static Func LOBYTE = (Func)(w => (object)(byte)((ulong)w & (ulong)byte.MaxValue)); 17 | internal static Func HIBYTE = (Func)(w => (object)(byte)((ulong)w >> 8 & (ulong)byte.MaxValue)); 18 | internal static Func GET_WHEEL_DELTA_WPARAM = (Func)(wParam => (object)(short)MinWinDef.HIWORD(wParam)); 19 | internal static Func GET_KEYSTATE_WPARAM = (Func)(wParam => MinWinDef.LOWORD(wParam)); 20 | internal static Func GET_NCHITTEST_WPARAM = (Func)(wParam => (object)(short)MinWinDef.LOWORD(wParam)); 21 | internal static Func GET_XBUTTON_WPARAM = (Func)(wParam => MinWinDef.HIWORD(wParam)); 22 | } 23 | } -------------------------------------------------------------------------------- /HwidGetCurrentEx.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32228.430 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gatherosstate", "D:\downloads\Compressed\gatherosstate-9c686af7167fa393a1c4652b7c1acc5a651d00bb\gatherosstate\gatherosstate\gatherosstate.csproj", "{728ADAD5-AD62-469B-8270-D47E34A11CB8}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|Mixed Platforms = Debug|Mixed Platforms 12 | Debug|x86 = Debug|x86 13 | Release|Any CPU = Release|Any CPU 14 | Release|Mixed Platforms = Release|Mixed Platforms 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 21 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Debug|Mixed Platforms.Build.0 = Debug|x86 22 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Debug|x86.ActiveCfg = Debug|x86 23 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Debug|x86.Build.0 = Debug|x86 24 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Release|Mixed Platforms.ActiveCfg = Release|x86 27 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Release|Mixed Platforms.Build.0 = Release|x86 28 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Release|x86.ActiveCfg = Release|x86 29 | {728ADAD5-AD62-469B-8270-D47E34A11CB8}.Release|x86.Build.0 = Release|x86 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {1BF57D8A-5097-49CF-B670-BA58C9861021} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /HwidGetCurrentEx/HwidGetCurrentEx.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | x86 7 | {5A2E9F2F-3E73-44AF-82E1-4639698564E3} 8 | Library 9 | HwidGetCurrentEx 10 | HwidGetCurrentEx 11 | v4.7.2 12 | 512 13 | 14 | 15 | x86 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | true 24 | 25 | 26 | x86 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /Properties/app.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 50 | 58 | 59 | 73 | -------------------------------------------------------------------------------- /gatherosstate.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {728ADAD5-AD62-469B-8270-D47E34A11CB8} 8 | Exe 9 | gatherosstate 10 | gatherosstate 11 | v4.7.2 12 | 512 13 | true 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | true 37 | bin\x86\Debug\ 38 | DEBUG;TRACE 39 | full 40 | x86 41 | 7.3 42 | prompt 43 | true 44 | true 45 | 46 | 47 | bin\x86\Release\ 48 | TRACE 49 | true 50 | pdbonly 51 | x86 52 | 7.3 53 | prompt 54 | true 55 | 56 | 57 | LocalIntranet 58 | 59 | 60 | false 61 | 62 | 63 | Properties\app.manifest 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /HwidGetCurrentEx/CPUID.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.CPUID 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System; 7 | using System.Runtime.InteropServices; 8 | 9 | namespace HwidGetCurrentEx 10 | { 11 | public static class CPUID 12 | { 13 | private static readonly byte[] x86CodeBytes = new byte[30] 14 | { 15 | (byte) 85, 16 | (byte) 139, 17 | (byte) 236, 18 | (byte) 83, 19 | (byte) 87, 20 | (byte) 139, 21 | (byte) 69, 22 | (byte) 8, 23 | (byte) 15, 24 | (byte) 162, 25 | (byte) 139, 26 | (byte) 125, 27 | (byte) 12, 28 | (byte) 137, 29 | (byte) 7, 30 | (byte) 137, 31 | (byte) 95, 32 | (byte) 4, 33 | (byte) 137, 34 | (byte) 79, 35 | (byte) 8, 36 | (byte) 137, 37 | (byte) 87, 38 | (byte) 12, 39 | (byte) 95, 40 | (byte) 91, 41 | (byte) 139, 42 | (byte) 229, 43 | (byte) 93, 44 | (byte) 195 45 | }; 46 | 47 | private static readonly byte[] x64CodeBytes = new byte[26] 48 | { 49 | (byte) 83, 50 | (byte) 73, 51 | (byte) 137, 52 | (byte) 208, 53 | (byte) 137, 54 | (byte) 200, 55 | (byte) 15, 56 | (byte) 162, 57 | (byte) 65, 58 | (byte) 137, 59 | (byte) 64, 60 | (byte) 0, 61 | (byte) 65, 62 | (byte) 137, 63 | (byte) 88, 64 | (byte) 4, 65 | (byte) 65, 66 | (byte) 137, 67 | (byte) 72, 68 | (byte) 8, 69 | (byte) 65, 70 | (byte) 137, 71 | (byte) 80, 72 | (byte) 12, 73 | (byte) 91, 74 | (byte) 195 75 | }; 76 | 77 | public static byte[] Invoke(int level) 78 | { 79 | IntPtr num = IntPtr.Zero; 80 | try 81 | { 82 | byte[] source = IntPtr.Size != 4 ? CPUID.x64CodeBytes : CPUID.x86CodeBytes; 83 | num = CPUID.VirtualAlloc(IntPtr.Zero, new UIntPtr((uint)source.Length), CPUID.AllocationType.COMMIT | CPUID.AllocationType.RESERVE, CPUID.MemoryProtection.EXECUTE_READWRITE); 84 | Marshal.Copy(source, 0, num, source.Length); 85 | CPUID.CpuIDDelegate forFunctionPointer = (CPUID.CpuIDDelegate)Marshal.GetDelegateForFunctionPointer(num, typeof(CPUID.CpuIDDelegate)); 86 | GCHandle gcHandle = new GCHandle(); 87 | byte[] buffer = new byte[16]; 88 | try 89 | { 90 | gcHandle = GCHandle.Alloc((object)buffer, GCHandleType.Pinned); 91 | forFunctionPointer(level, buffer); 92 | } 93 | finally 94 | { 95 | if (gcHandle != new GCHandle()) 96 | gcHandle.Free(); 97 | } 98 | return buffer; 99 | } 100 | finally 101 | { 102 | if (num != IntPtr.Zero) 103 | { 104 | CPUID.VirtualFree(num, 0U, 32768U); 105 | IntPtr zero = IntPtr.Zero; 106 | } 107 | } 108 | } 109 | 110 | [DllImport("kernel32.dll", SetLastError = true)] 111 | private static extern IntPtr VirtualAlloc( 112 | IntPtr lpAddress, 113 | UIntPtr dwSize, 114 | CPUID.AllocationType flAllocationType, 115 | CPUID.MemoryProtection flProtect); 116 | 117 | [DllImport("kernel32")] 118 | private static extern bool VirtualFree(IntPtr lpAddress, uint dwSize, uint dwFreeType); 119 | 120 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] 121 | private delegate void CpuIDDelegate(int level, byte[] buffer); 122 | 123 | [Flags] 124 | private enum AllocationType : uint 125 | { 126 | COMMIT = 4096, // 0x00001000 127 | RESERVE = 8192, // 0x00002000 128 | RESET = 524288, // 0x00080000 129 | LARGE_PAGES = 536870912, // 0x20000000 130 | PHYSICAL = 4194304, // 0x00400000 131 | TOP_DOWN = 1048576, // 0x00100000 132 | WRITE_WATCH = 2097152, // 0x00200000 133 | } 134 | 135 | [Flags] 136 | private enum MemoryProtection : uint 137 | { 138 | EXECUTE = 16, // 0x00000010 139 | EXECUTE_READ = 32, // 0x00000020 140 | EXECUTE_READWRITE = 64, // 0x00000040 141 | EXECUTE_WRITECOPY = 128, // 0x00000080 142 | NOACCESS = 1, 143 | READONLY = 2, 144 | READWRITE = 4, 145 | WRITECOPY = 8, 146 | GUARD_Modifierflag = 256, // 0x00000100 147 | NOCACHE_Modifierflag = 512, // 0x00000200 148 | WRITECOMBINE_Modifierflag = 1024, // 0x00000400 149 | } 150 | } 151 | } -------------------------------------------------------------------------------- /HwidGetCurrentEx/ComHelper.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.ComHelper 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System; 7 | using System.Runtime.CompilerServices; 8 | using System.Runtime.InteropServices; 9 | 10 | namespace HwidGetCurrentEx 11 | { 12 | public static class ComHelper 13 | { 14 | public struct MyGuid 15 | { 16 | public int Data1; 17 | public short Data2; 18 | public short Data3; 19 | public byte[] Data4; 20 | 21 | public MyGuid(Guid g) 22 | { 23 | byte[] byteArray = g.ToByteArray(); 24 | this.Data1 = BitConverter.ToInt32(byteArray, 0); 25 | this.Data2 = BitConverter.ToInt16(byteArray, 4); 26 | this.Data3 = BitConverter.ToInt16(byteArray, 6); 27 | this.Data4 = new byte[8]; 28 | Buffer.BlockCopy((Array)byteArray, 8, (Array)this.Data4, 0, 8); 29 | } 30 | 31 | public Guid ToGuid() => new Guid(this.Data1, this.Data2, this.Data3, this.Data4); 32 | } 33 | 34 | [ComVisible(false)] 35 | [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 36 | [Guid("eb89a21b-1f9c-4093-9a4d-05d4002543f6")] 37 | [ComImport] 38 | public interface IUnknown 39 | { 40 | int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid); 41 | 42 | [MethodImpl(MethodImplOptions.PreserveSig)] 43 | int AddRef(IntPtr pUnk); 44 | 45 | [MethodImpl(MethodImplOptions.PreserveSig)] 46 | int Release(IntPtr pUnk); 47 | } 48 | 49 | [ClassInterface(ClassInterfaceType.None)] 50 | [Guid("eb89a21b-1f9c-4093-9a4d-05d4002543f6")] 51 | public class MyUnknown : ComHelper.IUnknown 52 | { 53 | public int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid) => Marshal.QueryInterface(pUnk, ref riid, out pVoid); 54 | 55 | public int AddRef(IntPtr pUnk) => Marshal.AddRef(pUnk); 56 | 57 | public int Release(IntPtr pUnk) => Marshal.Release(pUnk); 58 | } 59 | 60 | [ComVisible(false)] 61 | [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 62 | [Guid("dca42645-c410-4859-ab3c-9e9c563c57bb")] 63 | [ComImport] 64 | public interface ISppNamedParamsReadWrite 65 | { 66 | int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid); 67 | } 68 | 69 | [ClassInterface(ClassInterfaceType.None)] 70 | [Guid("dca42645-c410-4859-ab3c-9e9c563c57bb")] 71 | public class MySppNamedParamsReadWrite : ComHelper.ISppNamedParamsReadWrite 72 | { 73 | public int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid) => Marshal.QueryInterface(pUnk, ref riid, out pVoid); 74 | } 75 | 76 | [ComVisible(false)] 77 | [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 78 | [Guid("22F58556-C467-43CD-98FF-7DBCADB2F661")] 79 | [ComImport] 80 | public interface ISppNamedParamsReadOnly 81 | { 82 | int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid); 83 | } 84 | 85 | [ClassInterface(ClassInterfaceType.None)] 86 | [Guid("22F58556-C467-43CD-98FF-7DBCADB2F661")] 87 | public class MySppNamedParamsReadOnly : ComHelper.ISppNamedParamsReadOnly 88 | { 89 | public int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid) => Marshal.QueryInterface(pUnk, ref riid, out pVoid); 90 | } 91 | 92 | [ComVisible(false)] 93 | [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 94 | [Guid("96B97320-ED0E-4D9F-B390-6C17EAF67277")] 95 | [ComImport] 96 | public interface ISppParamsReadWrite 97 | { 98 | int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid); 99 | } 100 | 101 | [ClassInterface(ClassInterfaceType.None)] 102 | [Guid("96B97320-ED0E-4D9F-B390-6C17EAF67277")] 103 | public class MySppParamsReadWrite : ComHelper.ISppParamsReadWrite 104 | { 105 | public int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid) => Marshal.QueryInterface(pUnk, ref riid, out pVoid); 106 | } 107 | 108 | [ComVisible(false)] 109 | [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 110 | [Guid("BE73DD34-4DAD-4AC5-BBE0-7930F45CED73")] 111 | [ComImport] 112 | public interface ISppParamsReadOnly 113 | { 114 | int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid); 115 | } 116 | 117 | [ClassInterface(ClassInterfaceType.None)] 118 | [Guid("BE73DD34-4DAD-4AC5-BBE0-7930F45CED73")] 119 | public class MySppParamsReadOnly : ComHelper.ISppParamsReadOnly 120 | { 121 | public int QueryInterface(IntPtr pUnk, ref Guid riid, out IntPtr pVoid) => Marshal.QueryInterface(pUnk, ref riid, out pVoid); 122 | } 123 | } 124 | } -------------------------------------------------------------------------------- /HwidGetCurrentEx/BitUtil.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.BitUtil 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Runtime.CompilerServices; 10 | using System.Text; 11 | 12 | namespace HwidGetCurrentEx 13 | { 14 | internal static class BitUtil 15 | { 16 | public static string ReadNullTerminatedAnsiString(byte[] buffer, int offset) 17 | { 18 | StringBuilder stringBuilder = new StringBuilder(); 19 | for (char ch = (char)buffer[offset]; ch > char.MinValue; ch = (char)buffer[offset]) 20 | { 21 | stringBuilder.Append(ch); 22 | ++offset; 23 | } 24 | return stringBuilder.ToString(); 25 | } 26 | 27 | public static byte[] StrToByteArray(string str) 28 | { 29 | Dictionary dictionary = new Dictionary(); 30 | for (int index = 0; index <= (int)byte.MaxValue; ++index) 31 | dictionary.Add(index.ToString("X2"), (byte)index); 32 | List byteList = new List(); 33 | for (int startIndex = 0; startIndex < str.Length; startIndex += 2) 34 | byteList.Add(dictionary[str.Substring(startIndex, 2)]); 35 | return byteList.ToArray(); 36 | } 37 | 38 | public static ulong array2ulong(byte[] bytes, int start, int length) 39 | { 40 | bytes = ((IEnumerable)bytes).Skip(start).Take(length).ToArray(); 41 | ulong num1 = 0; 42 | foreach (byte num2 in bytes) 43 | num1 = num1 * 256UL + (ulong)num2; 44 | return num1; 45 | } 46 | 47 | public static T[] Concats(this T[] array1, params T[] array2) => BitUtil.ConcatArray(array1, array2); 48 | 49 | public static T[] ConcatArray(params T[][] arrays) 50 | { 51 | int index1; 52 | int length; 53 | for (length = index1 = 0; index1 < arrays.Length; ++index1) 54 | length += arrays[index1].Length; 55 | T[] objArray = new T[length]; 56 | int index2; 57 | for (int index3 = index2 = 0; index2 < arrays.Length; ++index2) 58 | { 59 | arrays[index2].CopyTo((Array)objArray, index3); 60 | index3 += arrays[index2].Length; 61 | } 62 | return objArray; 63 | } 64 | 65 | public static byte LOBYTE(int a) => (byte)((uint)(short)a & (uint)byte.MaxValue); 66 | 67 | public static short MAKEWORD(byte a, byte b) => (short)((int)(byte)((uint)a & (uint)byte.MaxValue) | (int)(byte)((uint)b & (uint)byte.MaxValue) << 8); 68 | 69 | public static byte LOBYTE(short a) => (byte)((uint)a & (uint)byte.MaxValue); 70 | 71 | public static byte HIBYTE(short a) => (byte)((uint)a >> 8); 72 | 73 | public static int MAKELONG(short a, short b) => (int)a & (int)ushort.MaxValue | ((int)b & (int)ushort.MaxValue) << 16; 74 | 75 | public static short HIWORD(int a) => (short)(a >> 16); 76 | 77 | public static short LOWORD(int a) => (short)(a & (int)ushort.MaxValue); 78 | 79 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 80 | public static uint RotateLeft(uint value, int offset) => value << offset | value >> 32 - offset; 81 | 82 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 83 | public static ulong RotateLeft64(ulong value, int offset) => value << offset | value >> 64 - offset; 84 | 85 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 86 | public static uint RotateRight(uint value, int offset) => value >> offset | value << 32 - offset; 87 | 88 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 89 | public static ulong RotateRight64(ulong value, int offset) => value >> offset | value << 64 - offset; 90 | 91 | public static int HIDWORD(long intValue) => Convert.ToInt32(intValue >> 32); 92 | 93 | public static int LODWORD(long intValue) => Convert.ToInt32(intValue << 32 >> 32); 94 | 95 | public static short PAIR(sbyte high, sbyte low) => (short)((int)high << 8 | (int)(byte)low); 96 | 97 | public static int PAIR(short high, int low) => (int)high << 16 | (int)(ushort)low; 98 | 99 | public static long PAIR(int high, long low) => (long)high << 32 | (long)(uint)low; 100 | 101 | public static ushort PAIR(byte high, ushort low) => (ushort)((uint)high << 8 | (uint)(byte)low); 102 | 103 | public static uint PAIR(ushort high, uint low) => (uint)high << 16 | (uint)(ushort)low; 104 | 105 | public static ulong PAIR(uint high, ulong low) => (ulong)high << 32 | (ulong)(uint)low; 106 | 107 | public static int adc(uint first, uint second, ref uint carry) 108 | { 109 | uint carry1 = 0; 110 | if (carry == 0U) 111 | { 112 | uint num = first + second; 113 | carry = num >= first || num >= second ? 0U : 1U; 114 | return (int)num; 115 | } 116 | uint num1 = (uint)BitUtil.adc(first, second, ref carry1); 117 | if (carry > 0U) 118 | { 119 | ++num1; 120 | carry1 |= num1 == 0U ? 1U : 0U; 121 | } 122 | carry = carry1; 123 | return (int)num1; 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /HwidGetCurrentEx/SMBIOS.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.SMBIOS 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System.Runtime.InteropServices; 7 | 8 | namespace HwidGetCurrentEx 9 | { 10 | public class SMBIOS 11 | { 12 | public enum SMBIOSTableType : sbyte 13 | { 14 | BIOSInformation = 0, 15 | SystemInformation = 1, 16 | BaseBoardInformation = 2, 17 | EnclosureInformation = 3, 18 | ProcessorInformation = 4, 19 | MemoryControllerInformation = 5, 20 | MemoryModuleInformation = 6, 21 | CacheInformation = 7, 22 | PortConnectorInformation = 8, 23 | SystemSlotsInformation = 9, 24 | OnBoardDevicesInformation = 10, // 0x0A 25 | const_11 = 11, // 0x0B 26 | SystemConfigurationOptions = 12, // 0x0C 27 | BIOSLanguageInformation = 13, // 0x0D 28 | GroupAssociations = 14, // 0x0E 29 | SystemEventLog = 15, // 0x0F 30 | PhysicalMemoryArray = 16, // 0x10 31 | MemoryDevice = 17, // 0x11 32 | MemoryErrorInformation = 18, // 0x12 33 | MemoryArrayMappedAddress = 19, // 0x13 34 | MemoryDeviceMappedAddress = 20, // 0x14 35 | EndofTable = 127, // 0x7F 36 | } 37 | 38 | public struct SMBIOSTableHeader 39 | { 40 | public SMBIOS.SMBIOSTableType type; 41 | public byte length; 42 | public ushort Handle; 43 | } 44 | 45 | public struct SMBIOSTableSystemInfo 46 | { 47 | public SMBIOS.SMBIOSTableHeader header; 48 | public byte manufacturer; 49 | public byte productName; 50 | public byte version; 51 | public byte serialNumber; 52 | 53 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] 54 | public byte[] UUID; 55 | } 56 | 57 | public struct SMBIOSTableBaseBoardInfo 58 | { 59 | public SMBIOS.SMBIOSTableHeader header; 60 | } 61 | 62 | public struct SMBIOSTableEnclosureInfo 63 | { 64 | public SMBIOS.SMBIOSTableHeader header; 65 | } 66 | 67 | public struct SMBIOSTableProcessorInfo 68 | { 69 | public SMBIOS.SMBIOSTableHeader header; 70 | } 71 | 72 | public struct SMBIOSTableCacheInfo 73 | { 74 | public SMBIOS.SMBIOSTableHeader header; 75 | } 76 | 77 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 78 | public struct UnkownInfo 79 | { 80 | public SMBIOS.SMBIOSTableHeader header; 81 | } 82 | 83 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 84 | public struct SHAInfo 85 | { 86 | public SMBIOS.SMBIOSTableHeader header; 87 | public int size; 88 | public byte cache; 89 | } 90 | 91 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 92 | public struct PhysicalMemoryArray 93 | { 94 | public SMBIOS.SMBIOSTableHeader header; 95 | public uint EmptyPageNumber; 96 | public uint TotalPageNumber; 97 | } 98 | 99 | public struct BIOSInformation 100 | { 101 | public SMBIOS.SMBIOSTableHeader header; 102 | public byte vendor; 103 | public byte version; 104 | public ushort startingSegment; 105 | public byte releaseDate; 106 | public byte biosRomSize; 107 | public ulong characteristics; 108 | 109 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] 110 | public byte[] extensionBytes; 111 | } 112 | 113 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 114 | public struct MemCtrlInfo 115 | { 116 | public SMBIOS.SMBIOSTableHeader header; 117 | } 118 | 119 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 120 | public struct MemModuleInfo 121 | { 122 | public SMBIOS.SMBIOSTableHeader header; 123 | public byte SocketDesignation; 124 | public byte BankConnections; 125 | public byte CurrentSpeed; 126 | } 127 | 128 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 129 | public struct OemString 130 | { 131 | public SMBIOS.SMBIOSTableHeader header; 132 | } 133 | 134 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 135 | public struct MemoryArrayMappedAddress 136 | { 137 | public SMBIOS.SMBIOSTableHeader header; 138 | public uint Starting; 139 | public uint Ending; 140 | public ushort Handle; 141 | public byte PartitionWidth; 142 | } 143 | 144 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 145 | public struct BuiltinPointDevice 146 | { 147 | public SMBIOS.SMBIOSTableHeader header; 148 | } 149 | 150 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 151 | public struct PortableBattery 152 | { 153 | public SMBIOS.SMBIOSTableHeader header; 154 | } 155 | 156 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 157 | public struct MemoryDevice 158 | { 159 | public SMBIOS.SMBIOSTableHeader header; 160 | public ushort PhysicalArrayHandle; 161 | public ushort ErrorInformationHandle; 162 | public ushort TotalWidth; 163 | public ushort DataWidth; 164 | public ushort Size; 165 | } 166 | 167 | public struct RawSMBIOSData 168 | { 169 | public byte Used20CallingMethod; 170 | public byte SMBIOSMajorVersion; 171 | public byte SMBIOSMinorVersion; 172 | public byte DmiRevision; 173 | public uint Length; 174 | } 175 | } 176 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /HwidGetCurrentEx/Native.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: HwidGetCurrentEx.Native 3 | // Assembly: HwidGetCurrentEx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 200C1AD7-2186-49E5-9EB2-5AB7013ECA80 Assembly location: D:\downloads\Programs\HwidGetCurrentEx.dll 5 | 6 | using System; 7 | using System.Runtime.InteropServices; 8 | 9 | namespace HwidGetCurrentEx 10 | { 11 | public static class Native 12 | { 13 | public const int ERROR_INVALID_HANDLE_VALUE = -1; 14 | public const uint GENERIC_READ = 2147483648; 15 | public const uint GENERIC_WRITE = 1073741824; 16 | public const uint FILE_SHARE_READ = 1; 17 | public const uint FILE_SHARE_WRITE = 2; 18 | public const uint OPEN_EXISTING = 3; 19 | public const uint IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = 5636096; 20 | public const uint IOCTL_STORAGE_QUERY_PROPERTY = 2954240; 21 | public const uint IOCTL_BTH_GET_LOCAL_INFO = 4259840; 22 | public const uint IOCTL_NDIS_QUERY_GLOBAL_STATS = 1507330; 23 | public const uint PERMANENT_ADDRESS = 16843009; 24 | public const uint RSMB = 1381190978; 25 | 26 | [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] 27 | public static extern bool SetupDiGetDriverInfoDetail( 28 | IntPtr DeviceInfoSet, 29 | ref Native.SP_DEVINFO_DATA DeviceInfoData, 30 | ref Native.SP_DRVINFO_DATA DriverInfoData, 31 | ref Native.SP_DRVINFO_DETAIL_DATA DriverInfoDetailData, 32 | int DriverInfoDetailDataSize, 33 | ref int RequiredSize); 34 | 35 | [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] 36 | public static extern bool SetupDiEnumDriverInfo( 37 | IntPtr DeviceInfoSet, 38 | ref Native.SP_DEVINFO_DATA DeviceInfoData, 39 | int DriverType, 40 | int MemberIndex, 41 | ref Native.SP_DRVINFO_DATA DriverInfoData); 42 | 43 | [DllImport("setupapi.dll", CharSet = CharSet.Auto)] 44 | public static extern IntPtr SetupDiGetClassDevs( 45 | ref Guid ClassGuid, 46 | [MarshalAs(UnmanagedType.LPTStr)] string Enumerator, 47 | IntPtr hwndParent, 48 | uint Flags); 49 | 50 | [DllImport("setupapi.dll", CharSet = CharSet.Auto)] 51 | public static extern IntPtr SetupDiGetClassDevs( 52 | ref Guid ClassGuid, 53 | IntPtr Enumerator, 54 | IntPtr hwndParent, 55 | int Flags); 56 | 57 | [DllImport("setupapi.dll", CharSet = CharSet.Auto)] 58 | public static extern IntPtr SetupDiGetClassDevs( 59 | IntPtr ClassGuid, 60 | [MarshalAs(UnmanagedType.LPTStr)] string Enumerator, 61 | IntPtr hwndParent, 62 | int Flags); 63 | 64 | [DllImport("setupapi.dll", SetLastError = true)] 65 | public static extern IntPtr SetupDiGetClassDevsW( 66 | [In] ref Guid ClassGuid, 67 | [MarshalAs(UnmanagedType.LPWStr)] string Enumerator, 68 | IntPtr parent, 69 | int flags); 70 | 71 | [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)] 72 | public static extern bool SetupDiEnumDeviceInterfaces( 73 | IntPtr hDevInfo, 74 | IntPtr devInfo, 75 | ref Guid interfaceClassGuid, 76 | uint memberIndex, 77 | ref Native.SP_DEVICE_INTERFACE_DATA deviceInterfaceData); 78 | 79 | [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)] 80 | public static extern bool SetupDiGetDeviceInterfaceDetailW( 81 | IntPtr hDevInfo, 82 | ref Native.SP_DEVICE_INTERFACE_DATA deviceInterfaceData, 83 | ref Native.SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, 84 | uint deviceInterfaceDetailDataSize, 85 | out uint requiredSize, 86 | ref Native.SP_DEVINFO_DATA deviceInfoData); 87 | 88 | [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] 89 | public static extern bool SetupDiGetDeviceInterfaceDetailW( 90 | IntPtr hDevInfo, 91 | ref Native.SP_DEVICE_INTERFACE_DATA deviceInterfaceData, 92 | IntPtr deviceInterfaceDetailData, 93 | uint deviceInterfaceDetailDataSize, 94 | out uint requiredSize, 95 | IntPtr deviceInfoData); 96 | 97 | [DllImport("setupapi.dll", SetLastError = true)] 98 | public static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet); 99 | 100 | [DllImport("setupapi.dll", SetLastError = true)] 101 | public static extern bool SetupDiEnumDeviceInfo( 102 | IntPtr DeviceInfoSet, 103 | uint MemberIndex, 104 | ref Native.SP_DEVINFO_DATA DeviceInfoData); 105 | 106 | [DllImport("setupapi.dll")] 107 | public static extern int CM_Get_Parent(ref IntPtr pdnDevInst, IntPtr dnDevInst, int ulFlags); 108 | 109 | [DllImport("kernel32.dll")] 110 | public static extern uint GetLastError(); 111 | 112 | [DllImport("cfgmgr32.dll", CharSet = CharSet.Auto)] 113 | public static extern int CM_Get_DevNode_Registry_PropertyW( 114 | IntPtr dnDevInst, 115 | int ulProperty, 116 | ref int pulRegDataType, 117 | IntPtr Buffer, 118 | ref int pulLength, 119 | int ulFlags); 120 | 121 | [DllImport("cfgmgr32.dll", EntryPoint = "CM_Get_DevNode_Registry_PropertyA", CharSet = CharSet.Ansi, SetLastError = true)] 122 | public static extern int CM_Get_DevNode_Registry_Property( 123 | IntPtr dnDevInst, 124 | int ulProperty, 125 | ref int pulRegDataType, 126 | ref IntPtr Buffer, 127 | ref int pulLength, 128 | int ulFlags); 129 | 130 | [DllImport("cfgmgr32.dll", SetLastError = true)] 131 | public static extern int CM_Get_DevNode_Status( 132 | ref int status, 133 | ref int probNum, 134 | IntPtr devInst, 135 | int flags); 136 | 137 | [DllImport("setupapi.dll", SetLastError = true)] 138 | public static extern int CM_Get_Device_ID( 139 | IntPtr pdnDevInst, 140 | ref IntPtr buffer, 141 | int bufferLen, 142 | int flags); 143 | 144 | [DllImport("setupapi.dll", SetLastError = true)] 145 | public static extern int CM_Get_Device_IDW( 146 | IntPtr pdnDevInst, 147 | IntPtr Buffer, 148 | uint bufferLen, 149 | uint flags); 150 | 151 | [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)] 152 | public static extern bool SetupDiGetDeviceRegistryProperty( 153 | IntPtr deviceInfoSet, 154 | ref Native.SP_DEVINFO_DATA deviceInfoData, 155 | uint property, 156 | int propertyRegDataType, 157 | IntPtr propertyBuffer, 158 | uint propertyBufferSize, 159 | ref int requiredSize); 160 | 161 | [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)] 162 | public static extern bool SetupDiGetDeviceRegistryPropertyW( 163 | IntPtr deviceInfoSet, 164 | ref Native.SP_DEVINFO_DATA deviceInfoData, 165 | int property, 166 | int propertyRegDataType, 167 | byte[] propertyBuffer, 168 | int propertyBufferSize, 169 | out int requiredSize); 170 | 171 | [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)] 172 | public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count); 173 | 174 | [DllImport("kernel32.dll", SetLastError = true)] 175 | public static extern IntPtr CreateFile( 176 | string lpFileName, 177 | uint dwDesiredAccess, 178 | uint dwShareMode, 179 | uint lpSecurityAttributes, 180 | uint dwCreationDisposition, 181 | uint dwFlagsAndAttributes, 182 | uint hTemplateFile); 183 | 184 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] 185 | public static extern IntPtr CreateFileW( 186 | string filename, 187 | uint dwDesiredAccess, 188 | uint dwShareMode, 189 | uint lpSecurityAttributes, 190 | uint dwCreationDisposition, 191 | uint dwFlagsAndAttributes, 192 | uint hTemplateFile); 193 | 194 | [DllImport("kernel32.dll", SetLastError = true)] 195 | public static extern bool CloseHandle(IntPtr hObject); 196 | 197 | [DllImport("hid.dll")] 198 | public static extern bool HidD_GetAttributes( 199 | IntPtr HidDeviceObject, 200 | ref Native.HidD_Attributes Attributes); 201 | 202 | [DllImport("kernel32.dll", SetLastError = true)] 203 | public static extern bool DeviceIoControl( 204 | IntPtr hDevice, 205 | uint dwIoControlCode, 206 | IntPtr lpInBuffer, 207 | int nInBufferSize, 208 | IntPtr lpOutBuffer, 209 | int nOutBufferSize, 210 | out uint lpBytesReturned, 211 | IntPtr lpOverlapped); 212 | 213 | [DllImport("kernel32.dll", SetLastError = true)] 214 | public static extern bool DeviceIoControl( 215 | IntPtr hDevice, 216 | uint dwIoControlCode, 217 | ref uint lpInBuffer, 218 | int nInBufferSize, 219 | IntPtr lpOutBuffer, 220 | int nOutBufferSize, 221 | out uint lpBytesReturned, 222 | IntPtr lpOverlapped); 223 | 224 | [DllImport("advapi32.dll", SetLastError = true)] 225 | public static extern bool GetCurrentHwProfile(IntPtr fProfile); 226 | 227 | [DllImport("kernel32")] 228 | public static extern bool GlobalMemoryStatusEx(ref Native.MEMORYSTATUSEX stat); 229 | 230 | [DllImport("kernel32.dll")] 231 | public static extern uint GetSystemFirmwareTable( 232 | uint FirmwareTableProviderSignature, 233 | uint FirmwareTableID, 234 | IntPtr pFirmwareTableBuffer, 235 | uint BufferSize); 236 | 237 | [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] 238 | public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName); 239 | 240 | [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] 241 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 242 | 243 | [DllImport("wwapi.dll", CharSet = CharSet.Ansi, SetLastError = true)] 244 | public static extern int WwanOpenHandle( 245 | int dwClientVersion, 246 | IntPtr pReserved, 247 | out int pdwNegotiatedVersion, 248 | out IntPtr phClientHandle); 249 | 250 | [DllImport("wwapi.dll", CharSet = CharSet.Ansi, SetLastError = true)] 251 | public static extern int WwanCloseHandle(IntPtr hClientHandle, IntPtr pReserved); 252 | 253 | [DllImport("wwapi.dll", CharSet = CharSet.Ansi, SetLastError = true)] 254 | public static extern int WwanEnumerateInterfaces( 255 | IntPtr hClientHandle, 256 | int pdwReserved, 257 | out Native.WWAN_INTERFACE_INFO_LIST ppInterfaceList); 258 | 259 | [DllImport("wwapi.dll", CharSet = CharSet.Ansi, SetLastError = true)] 260 | public static extern int WwanFreeMemory(IntPtr pMem); 261 | 262 | [DllImport("wwapi.dll", CharSet = CharSet.Ansi, SetLastError = true)] 263 | public static extern int WwanSetInterface( 264 | IntPtr hClientHandle, 265 | Guid pInterfaceGuid, 266 | int OpCode, 267 | int dwDataSize, 268 | IntPtr pData, 269 | IntPtr pReserved1, 270 | IntPtr pReserved2, 271 | IntPtr pReserved3); 272 | 273 | [DllImport("wwapi.dll", CharSet = CharSet.Ansi, SetLastError = true)] 274 | public static extern int WlanQueryInterface( 275 | IntPtr hClientHandle, 276 | Guid pInterfaceGuid, 277 | int OpCode, 278 | IntPtr pReserved, 279 | out int pdwDataSize, 280 | out IntPtr ppData, 281 | out int pWlanOpcodeValueType); 282 | 283 | [DllImport("rpcrt4.dll", SetLastError = true)] 284 | public static extern int UuidCreateSequential(out Guid guid); 285 | 286 | public enum DI_FUNCTION 287 | { 288 | DIF_SELECTDEVICE = 1, 289 | DIF_INSTALLDEVICE = 2, 290 | DIF_ASSIGNRESOURCES = 3, 291 | DIF_PROPERTIES = 4, 292 | DIF_REMOVE = 5, 293 | DIF_FIRSTTIMESETUP = 6, 294 | DIF_FOUNDDEVICE = 7, 295 | DIF_SELECTCLASSDRIVERS = 8, 296 | DIF_VALIDATECLASSDRIVERS = 9, 297 | DIF_INSTALLCLASSDRIVERS = 10, // 0x0000000A 298 | DIF_CALCDISKSPACE = 11, // 0x0000000B 299 | DIF_DESTROYPRIVATEDATA = 12, // 0x0000000C 300 | DIF_VALIDATEDRIVER = 13, // 0x0000000D 301 | DIF_MOVEDEVICE = 14, // 0x0000000E 302 | DIF_DETECT = 15, // 0x0000000F 303 | DIF_INSTALLWIZARD = 16, // 0x00000010 304 | DIF_DESTROYWIZARDDATA = 17, // 0x00000011 305 | DIF_PROPERTYCHANGE = 18, // 0x00000012 306 | DIF_ENABLECLASS = 19, // 0x00000013 307 | DIF_DETECTVERIFY = 20, // 0x00000014 308 | DIF_INSTALLDEVICEFILES = 21, // 0x00000015 309 | DIF_UNREMOVE = 22, // 0x00000016 310 | DIF_SELECTBESTCOMPATDRV = 23, // 0x00000017 311 | DIF_ALLOW_INSTALL = 24, // 0x00000018 312 | DIF_REGISTERDEVICE = 25, // 0x00000019 313 | DIF_NEWDEVICEWIZARD_PRESELECT = 26, // 0x0000001A 314 | DIF_NEWDEVICEWIZARD_SELECT = 27, // 0x0000001B 315 | DIF_NEWDEVICEWIZARD_PREANALYZE = 28, // 0x0000001C 316 | DIF_NEWDEVICEWIZARD_POSTANALYZE = 29, // 0x0000001D 317 | DIF_NEWDEVICEWIZARD_FINISHINSTALL = 30, // 0x0000001E 318 | DIF_UNUSED1 = 31, // 0x0000001F 319 | DIF_INSTALLINTERFACES = 32, // 0x00000020 320 | DIF_DETECTCANCEL = 33, // 0x00000021 321 | DIF_REGISTER_COINSTALLERS = 34, // 0x00000022 322 | DIF_ADDPROPERTYPAGE_ADVANCED = 35, // 0x00000023 323 | DIF_ADDPROPERTYPAGE_BASIC = 36, // 0x00000024 324 | DIF_RESERVED1 = 37, // 0x00000025 325 | DIF_TROUBLESHOOTER = 38, // 0x00000026 326 | DIF_POWERMESSAGEWAKE = 39, // 0x00000027 327 | DIF_ADDREMOTEPROPERTYPAGE_ADVANCED = 40, // 0x00000028 328 | DIF_UPDATEDRIVER_UI = 41, // 0x00000029 329 | DIF_RESERVED2 = 48, // 0x00000030 330 | } 331 | 332 | public struct MEMORYSTATUSEX 333 | { 334 | public uint dwLength; 335 | public uint dwMemoryLoad; 336 | public ulong ullTotalPhys; 337 | public ulong ullAvailPhys; 338 | public ulong ullTotalPageFile; 339 | public ulong ullAvailPageFile; 340 | public ulong ullTotalVirtual; 341 | public ulong ullAvailVirtual; 342 | public ulong ullAvailExtendedVirtual; 343 | } 344 | 345 | [StructLayout(LayoutKind.Sequential)] 346 | public class HWProfile 347 | { 348 | public int dwDockInfo; 349 | 350 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 39)] 351 | public string szHwProfileGuid; 352 | 353 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] 354 | public string szHwProfileName; 355 | } 356 | 357 | [StructLayout(LayoutKind.Sequential)] 358 | public class DISK_EXTENT 359 | { 360 | public uint DiskNumber; 361 | public long StartingOffset; 362 | public long ExtentLength; 363 | } 364 | 365 | [StructLayout(LayoutKind.Sequential)] 366 | public class VOLUME_DISK_EXTENTS 367 | { 368 | public uint NumberOfDiskExtents; 369 | public Native.DISK_EXTENT Extents; 370 | } 371 | 372 | public struct DEVICE_SEEK_PENALTY_DESCRIPTOR 373 | { 374 | public readonly uint Version; 375 | public readonly uint Size; 376 | 377 | [MarshalAs(UnmanagedType.U1)] 378 | public readonly bool IncursSeekPenalty; 379 | } 380 | 381 | public struct STORAGE_DESCRIPTOR_HEADER 382 | { 383 | public uint Version; 384 | public uint Size; 385 | } 386 | 387 | public struct STORAGE_DEVICE_DESCRIPTOR 388 | { 389 | public uint Version; 390 | public uint Size; 391 | public byte DeviceType; 392 | public byte DeviceTypeModifier; 393 | public byte RemovableMedia; 394 | public byte CommandQueueing; 395 | public uint VendorIdOffset; 396 | public uint ProductIdOffset; 397 | public uint ProductRevisionOffset; 398 | public uint SerialNumberOffset; 399 | public byte BusType; 400 | public uint RawPropertiesLength; 401 | 402 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] 403 | public byte[] RawDeviceProperties; 404 | } 405 | 406 | public enum WWAN_INTERFACE_STATE 407 | { 408 | WwanInterfaceStateNotReady, 409 | WwanInterfaceStateDeviceLocked, 410 | WwanInterfaceStateUserAccountNotActivated, 411 | WwanInterfaceStateRegistered, 412 | WwanInterfaceStateRegistering, 413 | WwanInterfaceStateDeregistered, 414 | WwanInterfaceStateAttached, 415 | WwanInterfaceStateAttaching, 416 | WwanInterfaceStateDetaching, 417 | WwanInterfaceStateActivated, 418 | WwanInterfaceStateActivating, 419 | WwanInterfaceStateDeactivating, 420 | } 421 | 422 | public struct WWAN_INTERFACE_STATUS 423 | { 424 | private bool fInitialized; 425 | private Native.WWAN_INTERFACE_STATE InterfaceState; 426 | } 427 | 428 | public struct WWAN_INTERFACE_INFO 429 | { 430 | public Guid InterfaceGuid; 431 | 432 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] 433 | public byte[] strInterfaceDescription; 434 | 435 | public Native.WWAN_INTERFACE_STATUS InterfaceStatus; 436 | public int dwReserved1; 437 | public Guid guidReserved; 438 | public Guid ParentInterfaceGuid; 439 | public int dwReserved2; 440 | public int dwIndex; 441 | public int dwReserved3; 442 | public int dwReserved4; 443 | } 444 | 445 | public struct WWAN_INTERFACE_INFO_LIST 446 | { 447 | public int dwNumberOfItems; 448 | public Native.WWAN_INTERFACE_INFO[] InterfaceInfo; 449 | } 450 | 451 | [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Unicode)] 452 | public struct SP_DRVINFO_DATA 453 | { 454 | public int cbSize; 455 | public uint DriverType; 456 | public UIntPtr Reserved; 457 | 458 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] 459 | public string Description; 460 | 461 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] 462 | public string MfgName; 463 | 464 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] 465 | public string ProviderName; 466 | 467 | public System.Runtime.InteropServices.ComTypes.FILETIME DriverDate; 468 | public ulong DriverVersion; 469 | } 470 | 471 | public struct STORAGE_PROPERTY_QUERY 472 | { 473 | public int PropertyId; 474 | public int QueryType; 475 | 476 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] 477 | public byte[] AdditionalParameters; 478 | } 479 | 480 | public struct HidD_Attributes 481 | { 482 | public int Size; 483 | public ushort VendorID; 484 | public ushort ProductID; 485 | public ushort VersionNumber; 486 | } 487 | 488 | [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Unicode)] 489 | public struct SP_DRVINFO_DETAIL_DATA 490 | { 491 | public int cbSize; 492 | public System.Runtime.InteropServices.ComTypes.FILETIME InfDate; 493 | public int CompatIDsOffset; 494 | public int CompatIDsLength; 495 | public IntPtr Reserved; 496 | 497 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] 498 | public string SectionName; 499 | 500 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] 501 | public string InfFileName; 502 | 503 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] 504 | public string DrvDescription; 505 | 506 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] 507 | public string HardwareID; 508 | } 509 | 510 | [Flags] 511 | public enum DiGetClassFlags : uint 512 | { 513 | DIGCF_DEFAULT = 1, 514 | DIGCF_PRESENT = 2, 515 | DIGCF_ALLCLASSES = 4, 516 | SPDRP_UNUSED2 = DIGCF_ALLCLASSES | DIGCF_PRESENT, // 0x00000006 517 | DIGCF_PROFILE = 8, 518 | DIGCF_DEVICEINTERFACE = 16, // 0x00000010 519 | } 520 | 521 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] 522 | public struct SP_DEVICE_INTERFACE_DATA 523 | { 524 | public uint cbSize; 525 | public Guid InterfaceClassGuid; 526 | public uint Flags; 527 | public IntPtr Reserved; 528 | } 529 | 530 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] 531 | public struct SP_DEVINFO_DATA 532 | { 533 | public uint cbSize; 534 | public Guid ClassGuid; 535 | public uint DevInst; 536 | public IntPtr Reserved; 537 | } 538 | 539 | [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] 540 | public struct NativeDeviceInterfaceDetailData 541 | { 542 | public int size; 543 | public char devicePath; 544 | } 545 | 546 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] 547 | public struct SP_DEVICE_INTERFACE_DETAIL_DATA 548 | { 549 | public int cbSize; 550 | 551 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)] 552 | public string DevicePath; 553 | } 554 | } 555 | } -------------------------------------------------------------------------------- /VRSAVaultSignPKCS/DynamicDllLoader.cs: -------------------------------------------------------------------------------- 1 | // Decompiled with JetBrains decompiler 2 | // Type: VRSAVaultSignPKCS.DynamicDllLoader 3 | // Assembly: VRSAVaultSignPKCS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null 4 | // MVID: 835E1F41-447B-4B59-919B-3F453537ACCB 5 | // Assembly location: D:\downloads\Programs\VRSAVaultSignPKCS-cleaned.dll 6 | 7 | using System; 8 | using System.Runtime.InteropServices; 9 | 10 | namespace VRSAVaultSignPKCS 11 | { 12 | public class DynamicDllLoader 13 | { 14 | public IntPtr pCode = IntPtr.Zero; 15 | private static readonly int[][][] ProtectionFlags = new int[2][][]; 16 | private DynamicDllLoader.MEMORYMODULE module; 17 | 18 | internal unsafe bool LoadLibrary(byte[] data) 19 | { 20 | DynamicDllLoader.IMAGE_DOS_HEADER dosHeader = DynamicDllLoader.PointerHelpers.ToStruct(data); 21 | DynamicDllLoader.IMAGE_NT_HEADERS oldHeaders = DynamicDllLoader.PointerHelpers.ToStruct(data, (uint) dosHeader.e_lfanew); 22 | IntPtr lpStartAddr = (IntPtr) (long) DynamicDllLoader.Win32Imports.VirtualAlloc(oldHeaders.OptionalHeader.ImageBase, oldHeaders.OptionalHeader.SizeOfImage, DynamicDllLoader.Win32Constants.MEM_RESERVE, DynamicDllLoader.Win32Constants.PAGE_READWRITE); 23 | if (lpStartAddr.ToInt32() == 0) 24 | lpStartAddr = (IntPtr) (long) DynamicDllLoader.Win32Imports.VirtualAlloc((uint) (int) lpStartAddr, oldHeaders.OptionalHeader.SizeOfImage, DynamicDllLoader.Win32Constants.MEM_RESERVE, DynamicDllLoader.Win32Constants.PAGE_READWRITE); 25 | this.module = new DynamicDllLoader.MEMORYMODULE() 26 | { 27 | codeBase = lpStartAddr, 28 | numModules = 0, 29 | modules = new IntPtr(0), 30 | initialized = 0 31 | }; 32 | int num1 = (int) DynamicDllLoader.Win32Imports.VirtualAlloc((uint) (int) lpStartAddr, oldHeaders.OptionalHeader.SizeOfImage, DynamicDllLoader.Win32Constants.MEM_COMMIT, DynamicDllLoader.Win32Constants.PAGE_READWRITE); 33 | IntPtr num2 = (IntPtr) (long) DynamicDllLoader.Win32Imports.VirtualAlloc((uint) (int) lpStartAddr, oldHeaders.OptionalHeader.SizeOfHeaders, DynamicDllLoader.Win32Constants.MEM_COMMIT, DynamicDllLoader.Win32Constants.PAGE_READWRITE); 34 | Marshal.Copy(data, 0, num2, (int) ((long) dosHeader.e_lfanew + (long) oldHeaders.OptionalHeader.SizeOfHeaders)); 35 | this.module.headers = DynamicDllLoader.PointerHelpers.ToStruct(num2, (uint) dosHeader.e_lfanew); 36 | this.module.headers.OptionalHeader.ImageBase = (uint) (int) lpStartAddr; 37 | this.CopySections(data, oldHeaders, num2, dosHeader); 38 | uint delta = (uint) (int) (lpStartAddr - (int) oldHeaders.OptionalHeader.ImageBase); 39 | if (delta > 0U) 40 | this.PerformBaseRelocation(delta); 41 | this.BuildImportTable(); 42 | this.FinalizeSections(num2, dosHeader, oldHeaders); 43 | bool flag1; 44 | bool flag2; 45 | try 46 | { 47 | flag1 = ((DynamicDllLoader.fnDllEntry) Marshal.GetDelegateForFunctionPointer(new IntPtr(this.module.codeBase.ToInt32() + (int) this.module.headers.OptionalHeader.AddressOfEntryPoint), typeof (DynamicDllLoader.fnDllEntry)))(lpStartAddr.ToInt32(), 1U, (void*) null); 48 | this.pCode = this.module.codeBase; 49 | } 50 | catch 51 | { 52 | flag2 = false; 53 | goto label_8; 54 | } 55 | flag2 = flag1; 56 | label_8: 57 | return flag2; 58 | } 59 | 60 | public int GetModuleCount() 61 | { 62 | int moduleCount = 0; 63 | IntPtr codeBase = this.module.codeBase; 64 | DynamicDllLoader.IMAGE_DATA_DIRECTORY imageDataDirectory = this.module.headers.OptionalHeader.DataDirectory[1]; 65 | if (imageDataDirectory.Size > 0U) 66 | { 67 | for (DynamicDllLoader.IMAGE_IMPORT_DESCRIPTOR importDescriptor = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, imageDataDirectory.VirtualAddress); importDescriptor.Name > 0U && DynamicDllLoader.Win32Imports.LoadLibrary(Marshal.PtrToStringAnsi(codeBase + (int) importDescriptor.Name)) != -1; importDescriptor = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, (uint) ((ulong) imageDataDirectory.VirtualAddress + (ulong) (Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_IMPORT_DESCRIPTOR)) * moduleCount)))) 68 | ++moduleCount; 69 | } 70 | return moduleCount; 71 | } 72 | 73 | public unsafe int BuildImportTable() 74 | { 75 | this.module.modules = Marshal.AllocHGlobal(this.GetModuleCount() * 4); 76 | int num1 = 0; 77 | int num2 = 1; 78 | IntPtr codeBase = this.module.codeBase; 79 | DynamicDllLoader.IMAGE_DATA_DIRECTORY imageDataDirectory = this.module.headers.OptionalHeader.DataDirectory[1]; 80 | if (imageDataDirectory.Size > 0U) 81 | { 82 | for (DynamicDllLoader.IMAGE_IMPORT_DESCRIPTOR importDescriptor = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, imageDataDirectory.VirtualAddress); importDescriptor.Name > 0U; importDescriptor = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, imageDataDirectory.VirtualAddress + (uint) (Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_IMPORT_DESCRIPTOR)) * num1))) 83 | { 84 | int num3 = DynamicDllLoader.Win32Imports.LoadLibrary(Marshal.PtrToStringAnsi(codeBase + (int) importDescriptor.Name)); 85 | if (num3 != -1) 86 | { 87 | uint* numPtr1; 88 | uint* numPtr2; 89 | if (importDescriptor.CharacteristicsOrOriginalFirstThunk > 0U) 90 | { 91 | numPtr1 = (uint*) (void*) (codeBase + (int) importDescriptor.CharacteristicsOrOriginalFirstThunk); 92 | numPtr2 = (uint*) (void*) (codeBase + (int) importDescriptor.FirstThunk); 93 | } 94 | else 95 | { 96 | numPtr1 = (uint*) (void*) (codeBase + (int) importDescriptor.FirstThunk); 97 | numPtr2 = (uint*) (void*) (codeBase + (int) importDescriptor.FirstThunk); 98 | } 99 | while (*numPtr1 > 0U) 100 | { 101 | if ((*numPtr1 & 2147483648U) > 0U) 102 | { 103 | *numPtr2 = (uint) (int) DynamicDllLoader.Win32Imports.GetProcAddress(new IntPtr(num3), new IntPtr((long) (*numPtr1 & (uint) ushort.MaxValue))); 104 | } 105 | else 106 | { 107 | string stringAnsi = Marshal.PtrToStringAnsi(codeBase + (int) *numPtr1 + 2); 108 | *numPtr2 = DynamicDllLoader.Win32Imports.GetProcAddress(new IntPtr(num3), stringAnsi); 109 | } 110 | if (*numPtr2 != 0U) 111 | { 112 | ++numPtr1; 113 | ++numPtr2; 114 | } 115 | else 116 | { 117 | num2 = 0; 118 | break; 119 | } 120 | } 121 | ++num1; 122 | } 123 | else 124 | { 125 | num2 = 0; 126 | break; 127 | } 128 | } 129 | } 130 | return num2; 131 | } 132 | 133 | public void FinalizeSections( 134 | IntPtr headers, 135 | DynamicDllLoader.IMAGE_DOS_HEADER dosHeader, 136 | DynamicDllLoader.IMAGE_NT_HEADERS oldHeaders) 137 | { 138 | DynamicDllLoader.ProtectionFlags[0] = new int[2][]; 139 | DynamicDllLoader.ProtectionFlags[1] = new int[2][]; 140 | DynamicDllLoader.ProtectionFlags[0][0] = new int[2]; 141 | DynamicDllLoader.ProtectionFlags[0][1] = new int[2]; 142 | DynamicDllLoader.ProtectionFlags[1][0] = new int[2]; 143 | DynamicDllLoader.ProtectionFlags[1][1] = new int[2]; 144 | DynamicDllLoader.ProtectionFlags[0][0][0] = 1; 145 | DynamicDllLoader.ProtectionFlags[0][0][1] = 8; 146 | DynamicDllLoader.ProtectionFlags[0][1][0] = 2; 147 | DynamicDllLoader.ProtectionFlags[0][1][1] = 4; 148 | DynamicDllLoader.ProtectionFlags[1][0][0] = 16; 149 | DynamicDllLoader.ProtectionFlags[1][0][1] = 128; 150 | DynamicDllLoader.ProtectionFlags[1][1][0] = 32; 151 | DynamicDllLoader.ProtectionFlags[1][1][1] = 64; 152 | DynamicDllLoader.IMAGE_SECTION_HEADER imageSectionHeader = DynamicDllLoader.PointerHelpers.ToStruct(headers, (uint) (24 + dosHeader.e_lfanew) + (uint) oldHeaders.FileHeader.SizeOfOptionalHeader); 153 | for (int index1 = 0; index1 < (int) this.module.headers.FileHeader.NumberOfSections; ++index1) 154 | { 155 | int index2 = ((int) imageSectionHeader.Characteristics & 536870912) != 0 ? 1 : 0; 156 | int index3 = ((int) imageSectionHeader.Characteristics & 1073741824) != 0 ? 1 : 0; 157 | int index4 = ((int) imageSectionHeader.Characteristics & int.MinValue) != 0 ? 1 : 0; 158 | if ((imageSectionHeader.Characteristics & 33554432U) > 0U) 159 | { 160 | DynamicDllLoader.Win32Imports.VirtualFree(new IntPtr((long) imageSectionHeader.PhysicalAddress), (UIntPtr) imageSectionHeader.SizeOfRawData, 16384U); 161 | } 162 | else 163 | { 164 | uint flNewProtect = (uint) DynamicDllLoader.ProtectionFlags[index2][index3][index4]; 165 | if ((imageSectionHeader.Characteristics & 67108864U) > 0U) 166 | flNewProtect |= 512U; 167 | int num = (int) imageSectionHeader.SizeOfRawData; 168 | if (num == 0) 169 | { 170 | if ((imageSectionHeader.Characteristics & 64U) > 0U) 171 | num = (int) this.module.headers.OptionalHeader.SizeOfInitializedData; 172 | else if ((imageSectionHeader.Characteristics & 128U) > 0U) 173 | num = (int) this.module.headers.OptionalHeader.SizeOfUninitializedData; 174 | } 175 | if (num <= 0 || !DynamicDllLoader.Win32Imports.VirtualProtect(new IntPtr((long)imageSectionHeader.PhysicalAddress), imageSectionHeader.SizeOfRawData, flNewProtect, out uint _)) 176 | { } 177 | imageSectionHeader = DynamicDllLoader.PointerHelpers.ToStruct(headers, (uint) (24 + dosHeader.e_lfanew + (int) oldHeaders.FileHeader.SizeOfOptionalHeader + Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_SECTION_HEADER)) * (index1 + 1))); 178 | } 179 | } 180 | } 181 | 182 | public unsafe void PerformBaseRelocation(uint delta) 183 | { 184 | IntPtr codeBase = this.module.codeBase; 185 | int num1 = Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_BASE_RELOCATION)); 186 | DynamicDllLoader.IMAGE_DATA_DIRECTORY imageDataDirectory = this.module.headers.OptionalHeader.DataDirectory[5]; 187 | int num2 = 0; 188 | if (imageDataDirectory.Size <= 0U) 189 | return; 190 | for (DynamicDllLoader.IMAGE_BASE_RELOCATION imageBaseRelocation = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, imageDataDirectory.VirtualAddress); imageBaseRelocation.VirtualAddress > 0U; imageBaseRelocation = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, (uint) ((ulong) imageDataDirectory.VirtualAddress + (ulong) num2))) 191 | { 192 | IntPtr num3 = (IntPtr) (codeBase.ToInt32() + (int) imageBaseRelocation.VirtualAddress); 193 | ushort* numPtr1 = (ushort*) (codeBase.ToInt32() + (int) imageDataDirectory.VirtualAddress + num1); 194 | uint num4 = 0; 195 | while ((long) num4 < ((long) imageBaseRelocation.SizeOfBlock - (long) Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_BASE_RELOCATION))) / 2L) 196 | { 197 | int num5 = (int) *numPtr1 >> 12; 198 | int num6 = (int) *numPtr1 & 4095; 199 | switch (num5) 200 | { 201 | case 3: 202 | uint* numPtr2 = (uint*) (void*) (num3 + num6); 203 | int num7 = (int) *numPtr2 + (int) delta; 204 | *numPtr2 = (uint) num7; 205 | break; 206 | } 207 | ++num4; 208 | ++numPtr1; 209 | } 210 | num2 += (int) imageBaseRelocation.SizeOfBlock; 211 | } 212 | } 213 | 214 | public unsafe uint GetProcAddress(string name) 215 | { 216 | IntPtr codeBase = this.module.codeBase; 217 | int num1 = -1; 218 | DynamicDllLoader.IMAGE_DATA_DIRECTORY imageDataDirectory = this.module.headers.OptionalHeader.DataDirectory[0]; 219 | uint procAddress; 220 | if (imageDataDirectory.Size == 0U) 221 | { 222 | procAddress = 0U; 223 | } 224 | else 225 | { 226 | DynamicDllLoader.IMAGE_EXPORT_DIRECTORY imageExportDirectory = DynamicDllLoader.PointerHelpers.ToStruct(codeBase, imageDataDirectory.VirtualAddress); 227 | uint* numPtr1 = (uint*) (void*) new IntPtr((long) codeBase.ToInt32() + (long) imageExportDirectory.AddressOfNames); 228 | ushort* numPtr2 = (ushort*) (void*) new IntPtr((long) codeBase.ToInt32() + (long) imageExportDirectory.AddressOfNameOrdinals); 229 | uint num2 = 0; 230 | while (num2 < imageExportDirectory.NumberOfNames) 231 | { 232 | if (!(Marshal.PtrToStringAnsi(codeBase + (int) *numPtr1) == name)) 233 | { 234 | ++num2; 235 | ++numPtr1; 236 | ++numPtr2; 237 | } 238 | else 239 | { 240 | num1 = (int) *numPtr2; 241 | break; 242 | } 243 | } 244 | uint* numPtr3 = (uint*) ((ulong) codeBase.ToInt32() + ((ulong) imageExportDirectory.AddressOfFunctions + (ulong) (num1 * 4))); 245 | procAddress = (uint) ((ulong) codeBase.ToInt32() + (ulong) *numPtr3); 246 | } 247 | return procAddress; 248 | } 249 | 250 | public void CopySections( 251 | byte[] data, 252 | DynamicDllLoader.IMAGE_NT_HEADERS oldHeaders, 253 | IntPtr headers, 254 | DynamicDllLoader.IMAGE_DOS_HEADER dosHeader) 255 | { 256 | IntPtr codeBase = this.module.codeBase; 257 | DynamicDllLoader.IMAGE_SECTION_HEADER imageSectionHeader = DynamicDllLoader.PointerHelpers.ToStruct(headers, (uint) (24 + dosHeader.e_lfanew) + (uint) oldHeaders.FileHeader.SizeOfOptionalHeader); 258 | IntPtr num; 259 | for (int index = 0; index < (int) this.module.headers.FileHeader.NumberOfSections; ++index) 260 | { 261 | if (imageSectionHeader.SizeOfRawData == 0U) 262 | { 263 | uint sectionAlignment = oldHeaders.OptionalHeader.SectionAlignment; 264 | if (sectionAlignment > 0U) 265 | { 266 | num = new IntPtr((long) DynamicDllLoader.Win32Imports.VirtualAlloc((uint) (int) (codeBase + (int) imageSectionHeader.VirtualAddress), sectionAlignment, DynamicDllLoader.Win32Constants.MEM_COMMIT, DynamicDllLoader.Win32Constants.PAGE_READWRITE)); 267 | imageSectionHeader.PhysicalAddress = (uint) (int) num; 268 | Marshal.WriteInt32(new IntPtr(headers.ToInt32() + (32 + dosHeader.e_lfanew + (int) oldHeaders.FileHeader.SizeOfOptionalHeader) + Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_SECTION_HEADER)) * index), (int) num); 269 | Marshal.Copy(new byte[(int) sectionAlignment + 1], 0, num, (int) sectionAlignment); 270 | } 271 | imageSectionHeader = DynamicDllLoader.PointerHelpers.ToStruct(headers, (uint) (24 + dosHeader.e_lfanew + (int) oldHeaders.FileHeader.SizeOfOptionalHeader + Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_SECTION_HEADER)) * (index + 1))); 272 | } 273 | else 274 | { 275 | num = new IntPtr((long) DynamicDllLoader.Win32Imports.VirtualAlloc((uint) (int) (codeBase + (int) imageSectionHeader.VirtualAddress), imageSectionHeader.SizeOfRawData, DynamicDllLoader.Win32Constants.MEM_COMMIT, DynamicDllLoader.Win32Constants.PAGE_READWRITE)); 276 | Marshal.Copy(data, (int) imageSectionHeader.PointerToRawData, num, (int) imageSectionHeader.SizeOfRawData); 277 | imageSectionHeader.PhysicalAddress = (uint) (int) num; 278 | Marshal.WriteInt32(new IntPtr(headers.ToInt32() + (32 + dosHeader.e_lfanew + (int) oldHeaders.FileHeader.SizeOfOptionalHeader) + Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_SECTION_HEADER)) * index), (int) num); 279 | imageSectionHeader = DynamicDllLoader.PointerHelpers.ToStruct(headers, (uint) (24 + dosHeader.e_lfanew + (int) oldHeaders.FileHeader.SizeOfOptionalHeader + Marshal.SizeOf(typeof (DynamicDllLoader.IMAGE_SECTION_HEADER)) * (index + 1))); 280 | } 281 | } 282 | } 283 | 284 | public struct IMAGE_EXPORT_DIRECTORY 285 | { 286 | public uint Characteristics; 287 | public uint TimeDateStamp; 288 | public ushort MajorVersion; 289 | public ushort MinorVersion; 290 | public uint Name; 291 | public uint Base; 292 | public uint NumberOfFunctions; 293 | public uint NumberOfNames; 294 | public uint AddressOfFunctions; 295 | public uint AddressOfNames; 296 | public uint AddressOfNameOrdinals; 297 | } 298 | 299 | public struct IMAGE_IMPORT_BY_NAME 300 | { 301 | public short Hint; 302 | public byte Name; 303 | } 304 | 305 | public struct MEMORYMODULE 306 | { 307 | public DynamicDllLoader.IMAGE_NT_HEADERS headers; 308 | public IntPtr codeBase; 309 | public IntPtr modules; 310 | public int numModules; 311 | public int initialized; 312 | } 313 | 314 | public struct IMAGE_BASE_RELOCATION 315 | { 316 | public uint VirtualAddress; 317 | public uint SizeOfBlock; 318 | } 319 | 320 | public struct IMAGE_IMPORT_DESCRIPTOR 321 | { 322 | public uint CharacteristicsOrOriginalFirstThunk; 323 | public uint TimeDateStamp; 324 | public uint ForwarderChain; 325 | public uint Name; 326 | public uint FirstThunk; 327 | } 328 | 329 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 330 | public struct IMAGE_SECTION_HEADER 331 | { 332 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] 333 | public byte[] Name; 334 | public uint PhysicalAddress; 335 | public uint VirtualAddress; 336 | public uint SizeOfRawData; 337 | public uint PointerToRawData; 338 | public uint PointerToRelocations; 339 | public uint PointerToLinenumbers; 340 | public short NumberOfRelocations; 341 | public short NumberOfLinenumbers; 342 | public uint Characteristics; 343 | } 344 | 345 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 346 | public struct IMAGE_DOS_HEADER 347 | { 348 | public ushort e_magic; 349 | public ushort e_cblp; 350 | public ushort e_cp; 351 | public ushort e_crlc; 352 | public ushort e_cparhdr; 353 | public ushort e_minalloc; 354 | public ushort e_maxalloc; 355 | public ushort e_ss; 356 | public ushort e_sp; 357 | public ushort e_csum; 358 | public ushort e_ip; 359 | public ushort e_cs; 360 | public ushort e_lfarlc; 361 | public ushort e_ovno; 362 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] 363 | public ushort[] e_res1; 364 | public ushort e_oemid; 365 | public ushort e_oeminfo; 366 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] 367 | public ushort[] e_res2; 368 | public int e_lfanew; 369 | } 370 | 371 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 372 | public struct IMAGE_DATA_DIRECTORY 373 | { 374 | public uint VirtualAddress; 375 | public uint Size; 376 | } 377 | 378 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 379 | public struct IMAGE_OPTIONAL_HEADER32 380 | { 381 | public ushort Magic; 382 | public byte MajorLinkerVersion; 383 | public byte MinorLinkerVersion; 384 | public uint SizeOfCode; 385 | public uint SizeOfInitializedData; 386 | public uint SizeOfUninitializedData; 387 | public uint AddressOfEntryPoint; 388 | public uint BaseOfCode; 389 | public uint BaseOfData; 390 | public uint ImageBase; 391 | public uint SectionAlignment; 392 | public uint FileAlignment; 393 | public ushort MajorOperatingSystemVersion; 394 | public ushort MinorOperatingSystemVersion; 395 | public ushort MajorImageVersion; 396 | public ushort MinorImageVersion; 397 | public ushort MajorSubsystemVersion; 398 | public ushort MinorSubsystemVersion; 399 | public uint Win32VersionValue; 400 | public uint SizeOfImage; 401 | public uint SizeOfHeaders; 402 | public uint CheckSum; 403 | public ushort Subsystem; 404 | public ushort DllCharacteristics; 405 | public uint SizeOfStackReserve; 406 | public uint SizeOfStackCommit; 407 | public uint SizeOfHeapReserve; 408 | public uint SizeOfHeapCommit; 409 | public uint LoaderFlags; 410 | public uint NumberOfRvaAndSizes; 411 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] 412 | public DynamicDllLoader.IMAGE_DATA_DIRECTORY[] DataDirectory; 413 | } 414 | 415 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 416 | public struct IMAGE_FILE_HEADER 417 | { 418 | public ushort Machine; 419 | public ushort NumberOfSections; 420 | public uint TimeDateStamp; 421 | public uint PointerToSymbolTable; 422 | public uint NumberOfSymbols; 423 | public ushort SizeOfOptionalHeader; 424 | public ushort Characteristics; 425 | } 426 | 427 | public struct IMAGE_NT_HEADERS 428 | { 429 | public uint Signature; 430 | public DynamicDllLoader.IMAGE_FILE_HEADER FileHeader; 431 | public DynamicDllLoader.IMAGE_OPTIONAL_HEADER32 OptionalHeader; 432 | } 433 | 434 | internal class Win32Constants 435 | { 436 | public static uint MEM_COMMIT = 4096; 437 | public static uint PAGE_EXECUTE_READWRITE = 64; 438 | public static uint PAGE_READWRITE = 4; 439 | public static uint MEM_RELEASE = 32768; 440 | public static uint MEM_RESERVE = 8192; 441 | } 442 | 443 | internal static class Win32Imports 444 | { 445 | [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] 446 | public static extern uint GetProcAddress(IntPtr hModule, string procName); 447 | 448 | [DllImport("kernel32")] 449 | public static extern int LoadLibrary(string lpFileName); 450 | 451 | [DllImport("kernel32")] 452 | public static extern uint GetLastError(); 453 | 454 | [DllImport("kernel32.dll")] 455 | public static extern IntPtr GetProcAddress(IntPtr module, IntPtr ordinal); 456 | 457 | [DllImport("kernel32")] 458 | public static extern uint VirtualAlloc( 459 | uint lpStartAddr, 460 | uint size, 461 | uint flAllocationType, 462 | uint flProtect); 463 | 464 | [DllImport("kernel32.dll", SetLastError = true)] 465 | internal static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize, uint dwFreeType); 466 | 467 | [DllImport("kernel32.dll", SetLastError = true)] 468 | internal static extern bool VirtualProtect( 469 | IntPtr lpAddress, 470 | uint dwSize, 471 | uint flNewProtect, 472 | out uint lpflOldProtect); 473 | } 474 | 475 | internal static class PointerHelpers 476 | { 477 | public static unsafe T ToStruct(byte[] data) where T : struct 478 | { 479 | fixed (byte* numPtr = &data[0]) 480 | return (T) Marshal.PtrToStructure(new IntPtr((void*) numPtr), typeof (T)); 481 | } 482 | 483 | public static unsafe T ToStruct(byte[] data, uint from) where T : struct 484 | { 485 | fixed (byte* numPtr = &data[(int) from]) 486 | return (T) Marshal.PtrToStructure(new IntPtr((void*) numPtr), typeof (T)); 487 | } 488 | 489 | public static T ToStruct(IntPtr ptr, uint from) where T : struct => (T) Marshal.PtrToStructure(ptr + (int) from, typeof (T)); 490 | } 491 | 492 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 493 | private unsafe delegate bool fnDllEntry(int instance, uint reason, void* reserved); 494 | } 495 | } 496 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Win32; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using System.Runtime.InteropServices; 7 | using System.Text; 8 | using System.Xml; 9 | 10 | namespace gatherosstate 11 | { 12 | internal class Program 13 | { 14 | #region struct 15 | 16 | public enum ALG_ID : uint 17 | { 18 | CALG_MD5 = 0x8003, 19 | CALG_RSA = 0x800C 20 | } 21 | 22 | public enum HashParameters 23 | { 24 | HP_ALGID = 0x0001, 25 | HP_HASHVAL = 0x2, 26 | HP_HASHSIZE = 0x0004 27 | } 28 | 29 | [StructLayout(LayoutKind.Sequential)] 30 | public struct RTL_OSVERSIONINFOEX 31 | { 32 | public uint dwOSVersionInfoSize; 33 | public uint dwMajorVersion; 34 | public uint dwMinorVersion; 35 | public uint dwBuildNumber; 36 | public uint dwPlatformId; 37 | 38 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] 39 | public string szCSDVersion; 40 | } 41 | 42 | [StructLayout(LayoutKind.Sequential)] 43 | public struct FILE_TIME 44 | { 45 | public uint dwLowDateTime; 46 | public uint dwHighDateTime; 47 | } 48 | 49 | [StructLayout(LayoutKind.Sequential)] 50 | public struct SYSTEMTIME 51 | { 52 | public Int16 wYear; 53 | public Int16 wMonth; 54 | public Int16 wDayOfWeek; 55 | public Int16 wDay; 56 | public Int16 wHour; 57 | public Int16 wMinute; 58 | public Int16 wSecond; 59 | public Int16 wMilliseconds; 60 | } 61 | 62 | #endregion struct 63 | 64 | #region pinvoke 65 | 66 | [DllImport("Ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] 67 | private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX osversion); 68 | 69 | [DllImport("slc.dll", EntryPoint = "SLGetWindowsInformationDWORD", CharSet = CharSet.Auto)] 70 | private static extern int SLGetWindowsInformationDWORD(string pwszValueName, ref int pdwValue); 71 | 72 | [DllImport("kernel32.dll")] 73 | private static extern void GetSystemTime(ref SYSTEMTIME lpSystemTime); 74 | 75 | [DllImport("kernel32.dll")] 76 | private static extern void GetSystemTimeAsFileTime(ref FILE_TIME lpSystemTimeAsFileTime); 77 | 78 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 79 | private static extern bool FileTimeToSystemTime(ref FILE_TIME lpFileTime, out SYSTEMTIME lpSystemTime); 80 | 81 | [DllImport("AdvApi32.dll", SetLastError = true, ExactSpelling = true)] 82 | [return: MarshalAs(UnmanagedType.Bool)] 83 | public static extern bool CryptAcquireContextW(out IntPtr providerContext, [MarshalAs(UnmanagedType.LPWStr)] string container, [MarshalAs(UnmanagedType.LPWStr)] string provider, int providerType, uint flags); 84 | 85 | [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 86 | public static extern bool CryptCreateHash(IntPtr hProv, uint algId, IntPtr hKey, uint dwFlags, ref IntPtr phHash); 87 | 88 | [DllImport("advapi32.dll", SetLastError = true)] 89 | public static extern bool CryptDestroyHash(IntPtr hHash); 90 | 91 | [DllImport("advapi32.dll", SetLastError = true)] 92 | public static extern bool CryptDestroyKey(IntPtr phKey); 93 | 94 | [DllImport("advapi32.dll", SetLastError = true)] 95 | public static extern bool CryptHashData(IntPtr hHash, byte[] pbData, uint dataLen, uint flags); 96 | 97 | [DllImport("Advapi32.dll", EntryPoint = "CryptReleaseContext", CharSet = CharSet.Unicode, SetLastError = true)] 98 | public static extern bool CryptReleaseContext(IntPtr hProv, Int32 dwFlags); 99 | 100 | [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 101 | public static extern bool CryptGetHashParam(IntPtr hHash, uint dwParam, Byte[] pbData, ref uint pdwDataLen, uint dwFlags); 102 | 103 | [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)] 104 | public static extern IntPtr memset(byte[] dest, int c, int count); 105 | 106 | #endregion pinvoke 107 | 108 | #region define 109 | 110 | private static bool KMS38 = false; 111 | 112 | private static Dictionary> UpdateProductKey = new Dictionary>() 113 | { 114 | {"43TBQ-NH92J-XKTM7-KT3KK-P39PB", new Tuple(125, 17763, "EnterpriseS","Microsoft.Windows.125.X21-83233_8wekyb3d8bbwe")}, 115 | {"NK96Y-D9CD8-W44CQ-R8YTK-DYJWX", new Tuple(125, 14393, "EnterpriseS","Microsoft.Windows.125.X21-05035_8wekyb3d8bbwe")}, 116 | {"FWN7H-PF93Q-4GGP8-M8RF3-MDWWW", new Tuple(125, 10240, "EnterpriseS","Microsoft.Windows.125.X19-99617_8wekyb3d8bbwe")}, 117 | {"QPM6N-7J2WJ-P88HH-P3YRH-YY74H", new Tuple(191, 19044, "IoTEnterpriseS","Microsoft.Windows.191.X21-99682_8wekyb3d8bbwe")}, 118 | {"M33WV-NHY3C-R7FPM-BQGPT-239PG", new Tuple(126, 17763, "EnterpriseSN","Microsoft.Windows.126.X21-83264_8wekyb3d8bbwe")}, 119 | {"2DBW3-N2PJG-MVHW3-G7TDK-9HKR4", new Tuple(126, 14393, "EnterpriseSN","Microsoft.Windows.126.X21-04922_8wekyb3d8bbwe")}, 120 | {"8V8WN-3GXBH-2TCMG-XHRX3-9766K", new Tuple(126, 10240, "EnterpriseSN","Microsoft.Windows.126.X19-98770_8wekyb3d8bbwe")}, 121 | {"XQQYW-NFFMW-XJPBH-K8732-CKFFD", new Tuple(188, 19044, "IoTEnterprise","Microsoft.Windows.188.X21-99378_8wekyb3d8bbwe")}, 122 | {"YTMG3-N6DKC-DKB77-7M9GH-8HVX7", new Tuple(101, 0, "Core","Microsoft.Windows.101.X19-98868_8wekyb3d8bbwe")}, 123 | {"N2434-X9D7W-8PF6X-8DV9T-8TYMD", new Tuple(99, 0, "CoreCountrySpecific","Microsoft.Windows.99.X19-99652_8wekyb3d8bbwe")}, 124 | {"4CPRK-NM3K3-X6XXQ-RXX86-WXCHW", new Tuple(98, 0, "CoreN","Microsoft.Windows.98.X19-98877_8wekyb3d8bbwe")}, 125 | {"BT79Q-G7N6G-PGBYW-4YWX6-6F4BT", new Tuple(100, 0, "CoreSingleLanguage","Microsoft.Windows.100.X19-99661_8wekyb3d8bbwe")}, 126 | {"YNMGQ-8RYV3-4PGQ3-C8XTP-7CFBY", new Tuple(121, 0, "Education","Microsoft.Windows.121.X19-98886_8wekyb3d8bbwe")}, 127 | {"84NGF-MHBT6-FXBX8-QWJK7-DRR8H", new Tuple(122, 0, "EducationN","Microsoft.Windows.122.X19-98892_8wekyb3d8bbwe")}, 128 | {"XGVPP-NMH47-7TTHJ-W3FW7-8HV2C", new Tuple(4, 0, "Enterprise","Microsoft.Windows.4.X19-99683_8wekyb3d8bbwe")}, 129 | {"WGGHN-J84D6-QYCPR-T7PJ7-X766F", new Tuple(27, 0, "EnterpriseN","Microsoft.Windows.27.X19-98747_8wekyb3d8bbwe")}, 130 | {"3V6Q6-NQXCX-V8YXR-9QCYV-QPFCT", new Tuple(171, 0, "EnterpriseG","Microsoft.Windows.27.X19-98746_8wekyb3d8bbwe")}, 131 | {"FW7NV-4T673-HF4VX-9X4MM-B4H4T", new Tuple(172, 0, "EnterpriseGN","Microsoft.Windows.172.X21-24709_8wekyb3d8bbwe")}, 132 | {"VK7JG-NPHTM-C97JM-9MPGT-3V66T", new Tuple(48, 0, "Professional","Microsoft.Windows.48.X19-98841_8wekyb3d8bbwe")}, 133 | {"2B87N-8KFHP-DKV6R-Y2C8J-PKCKT", new Tuple(49, 0, "ProfessionalN","Microsoft.Windows.49.X19-98859_8wekyb3d8bbwe")}, 134 | {"8PTT6-RNW4C-6V7J2-C2D3X-MHBPB", new Tuple(164, 0, "ProfessionalEducation","Microsoft.Windows.164.X21-04955_8wekyb3d8bbwe")}, 135 | {"GJTYN-HDMQY-FRR76-HVGC7-QPF8P", new Tuple(165, 0, "ProfessionalEducationN","Microsoft.Windows.165.X21-04956_8wekyb3d8bbwe")}, 136 | {"DXG7C-N36C4-C4HTG-X4T3X-2YV77", new Tuple(161, 0, "ProfessionalWorkstation","Microsoft.Windows.161.X21-43626_8wekyb3d8bbwe")}, 137 | {"WYPNQ-8C467-V2W6J-TX4WX-WT2RQ", new Tuple(162, 0, "ProfessionalWorkstationN","Microsoft.Windows.162.X21-43644_8wekyb3d8bbwe")} 138 | }; 139 | 140 | private static Dictionary> KMSProductKey = new Dictionary>() 141 | { 142 | {"M7XTQ-FN8P6-TTKYV-9D4CC-J462D", new Tuple(125, 17763, "EnterpriseS")}, 143 | {"DCPHK-NFMTC-H88MJ-PFHPY-QJ4BJ", new Tuple(125, 14393, "EnterpriseS")}, 144 | {"WNMTR-4C88C-JK8YV-HQ7T2-76DF9", new Tuple(125, 10240, "EnterpriseS")}, 145 | {"92NFX-8DJQP-P6BBQ-THF9C-7CG2H", new Tuple(126, 17763, "EnterpriseSN")}, 146 | {"QFFDN-GRT3P-VKWWX-X7T3R-8B639", new Tuple(126, 14393, "EnterpriseSN")}, 147 | {"2F77B-TNFGY-69QQF-B8YKP-D69TJ", new Tuple(126, 10240, "EnterpriseSN")}, 148 | {"TX9XD-98N7V-6WMQ6-BX7FG-H8Q99", new Tuple(101, 0, "Core")}, 149 | {"PVMJN-6DFY6-9CCP6-7BKTT-D3WVR", new Tuple(99, 0, "CoreCountrySpecific")}, 150 | {"3KHY7-WNT83-DGQKR-F7HPR-844BM", new Tuple(98, 0, "CoreN")}, 151 | {"7HNRX-D7KGG-3K4RQ-4WPJ4-YTDFH", new Tuple(100, 0, "CoreSingleLanguage")}, 152 | {"NW6C2-QMPVW-D7KKK-3GKT6-VCFB2", new Tuple(121, 0, "Education")}, 153 | {"2WH4N-8QGBV-H22JP-CT43Q-MDWWJ", new Tuple(122, 0, "EducationN")}, 154 | {"NPPR9-FWDCX-D2C8J-H872K-2YT43", new Tuple(4, 0, "Enterprise")}, 155 | {"DPH2V-TTNVB-4X9Q3-TJR4H-KHJW4", new Tuple(27, 0, "EnterpriseN")}, 156 | {"YYVX9-NTFWV-6MDM3-9PT4T-4M68B", new Tuple(171, 0, "EnterpriseG")}, 157 | {"44RPN-FTY23-9VTTB-MP9BX-T84FV", new Tuple(172, 0, "EnterpriseGN")}, 158 | {"W269N-WFGWX-YVC9B-4J6C9-T83GX", new Tuple(48, 0, "Professional")}, 159 | {"MH37W-N47XK-V7XM9-C7227-GCQG9", new Tuple(49, 0, "ProfessionalN")}, 160 | {"6TP4R-GNPTD-KYYHQ-7B7DP-J447Y", new Tuple(164, 0, "ProfessionalEducation")}, 161 | {"YVWGF-BXNMC-HTQYQ-CPQ99-66QFC", new Tuple(165, 0, "ProfessionalEducationN")}, 162 | {"NRG8B-VKK3Q-CXVCJ-9G2XF-6Q84J", new Tuple(161, 0, "ProfessionalWorkstation")}, 163 | {"9FNHH-K3HBT-3W4TD-6383H-6XYWF", new Tuple(162, 0, "ProfessionalWorkstationN")}, 164 | {"VDYBN-27WPP-V4HQT-9VMD4-VMK7H", new Tuple(7, 20348, "ServerStandard")}, 165 | {"N69G4-B89J2-4G8F4-WWYCC-J464C", new Tuple(7, 17763, "ServerStandard")}, 166 | {"WC2BQ-8NRM3-FDDYY-2BFGV-KHKQY", new Tuple(7, 0, "ServerStandard")}, 167 | {"67KN8-4FYJW-2487Q-MQ2J7-4C4RG", new Tuple(13, 20348, "ServerStandardCore")}, 168 | {"N2KJX-J94YW-TQVFB-DG9YT-724CC", new Tuple(13, 17763, "ServerStandardCore")}, 169 | {"PTXN8-JFHJM-4WC78-MPCBR-9W4KR", new Tuple(13, 0, "ServerStandardCore")}, 170 | {"WX4NM-KYWYW-QJJR4-XV3QB-6VM33", new Tuple(8, 20348, "ServerDatacenter")}, 171 | {"WMDGN-G9PQG-XVVXX-R3X43-63DFG", new Tuple(8, 17763, "ServerDatacenter")}, 172 | {"CB7KF-BWN84-R7R2Y-793K2-8XDDG", new Tuple(8, 0, "ServerDatacenter")}, 173 | {"QFND9-D3Y9C-J3KKY-6RPVP-2DPYV", new Tuple(12, 20348, "ServerDatacenterCore")}, 174 | {"6NMRW-2C8FM-D24W7-TQWMY-CWH2D", new Tuple(12, 17763, "ServerDatacenterCore")}, 175 | {"2HXDN-KRXHB-GPYC7-YCKFJ-7FVDG", new Tuple(12, 0, "ServerDatacenterCore")}, 176 | {"6N379-GGTMK-23C6M-XVVTC-CKFRQ", new Tuple(52, 20348, "ServerSolution")}, 177 | {"WVDHN-86M7X-466P6-VHXV7-YY726", new Tuple(52, 17763, "ServerSolution")}, 178 | {"FDNH6-VW9RW-BXPJ7-4XTYG-239TB", new Tuple(52, 0, "ServerSolution")}, 179 | {"TM8T6-9NJWV-PC26Y-RFYXH-YY723", new Tuple(53, 0, "ServerSolutionCore")} 180 | }; 181 | 182 | private static Dictionary SkuList = new Dictionary() 183 | { 184 | {"1", "Ultimate"}, 185 | {"2", "HomeBasic"}, 186 | {"3", "HomePremium"}, 187 | {"4", "Enterprise"}, 188 | {"5", "HomeBasicN"}, 189 | {"6", "Business"}, 190 | {"7", "ServerStandard"}, 191 | {"8", "ServerDatacenter"}, 192 | {"9", "ServerSBSStandard"}, 193 | {"10", "ServerEnterprise"}, 194 | {"11", "Starter"}, 195 | {"12", "ServerDatacenterCore"}, 196 | {"13", "ServerStandardCore"}, 197 | {"14", "ServerEnterpriseCore"}, 198 | {"15", "ServerEnterpriseIA64"}, 199 | {"16", "BusinessN"}, 200 | {"17", "ServerWeb"}, 201 | {"18", "ServerComputeCluster"}, 202 | {"19", "ServerHomeStandard"}, 203 | {"20", "ServerStorageExpress"}, 204 | {"21", "ServerStorageStandard"}, 205 | {"22", "ServerStorageWorkgroup"}, 206 | {"23", "ServerStorageEnterprise"}, 207 | {"24", "ServerWinSB"}, 208 | {"25", "ServerSBSPremium"}, 209 | {"26", "HomePremiumN"}, 210 | {"27", "EnterpriseN"}, 211 | {"28", "UltimateN"}, 212 | {"29", "ServerWebCore"}, 213 | {"30", "ServerMediumBusinessManagement"}, 214 | {"31", "ServerMediumBusinessSecurity"}, 215 | {"32", "ServerMediumBusinessMessaging"}, 216 | {"33", "ServerWinFoundation"}, 217 | {"34", "ServerHomePremium"}, 218 | {"35", "ServerWinSBV"}, 219 | {"36", "ServerStandardV"}, 220 | {"37", "ServerDatacenterV"}, 221 | {"38", "ServerEnterpriseV"}, 222 | {"39", "ServerDatacenterVCore"}, 223 | {"40", "ServerStandardVCore"}, 224 | {"41", "ServerEnterpriseVCore"}, 225 | {"42", "ServerHyperCore"}, 226 | {"43", "ServerStorageExpressCore"}, 227 | {"44", "ServerStorageStandardCore"}, 228 | {"45", "ServerStorageWorkgroupCore"}, 229 | {"46", "ServerStorageEnterpriseCore"}, 230 | {"47", "StarterN"}, 231 | {"48", "Professional"}, 232 | {"49", "ProfessionalN"}, 233 | {"50", "ServerSolution"}, 234 | {"51", "ServerForSBSolutions"}, 235 | {"52", "ServerSolutionsPremium"}, 236 | {"53", "ServerSolutionsPremiumCore"}, 237 | {"54", "ServerSolutionEM"}, 238 | {"55", "ServerForSBSolutionsEM"}, 239 | {"56", "ServerEmbeddedSolution"}, 240 | {"57", "ServerEmbeddedSolutionCore"}, 241 | {"58", "ProfessionalEmbedded"}, 242 | {"59", "ServerEssentialManagement"}, 243 | {"60", "ServerEssentialAdditional"}, 244 | {"61", "ServerEssentialManagementSvc"}, 245 | {"62", "ServerEssentialAdditionalSvc"}, 246 | {"63", "ServerSBSPremiumCore"}, 247 | {"64", "ServerHPC"}, 248 | {"65", "Embedded"}, 249 | {"66", "StarterE"}, 250 | {"67", "HomeBasicE"}, 251 | {"68", "HomePremiumE"}, 252 | {"69", "ProfessionalE"}, 253 | {"70", "EnterpriseE"}, 254 | {"71", "UltimateE"}, 255 | {"72", "EnterpriseEval"}, 256 | {"74", "Prerelease"}, 257 | {"76", "ServerMultiPointStandard"}, 258 | {"77", "ServerMultiPointPremium"}, 259 | {"79", "ServerStandardEval"}, 260 | {"80", "ServerDatacenterEval"}, 261 | {"84", "EnterpriseNEval"}, 262 | {"85", "EmbeddedAutomotive"}, 263 | {"86", "EmbeddedIndustryA"}, 264 | {"87", "ThinPC"}, 265 | {"88", "EmbeddedA"}, 266 | {"89", "EmbeddedIndustry"}, 267 | {"90", "EmbeddedE"}, 268 | {"91", "EmbeddedIndustryE"}, 269 | {"92", "EmbeddedIndustryAE"}, 270 | {"93", "ProfessionalPlus"}, 271 | {"95", "ServerStorageWorkgroupEval"}, 272 | {"96", "ServerStorageStandardEval"}, 273 | {"97", "CoreARM"}, 274 | {"98", "CoreN"}, 275 | {"99", "CoreCountrySpecific"}, 276 | {"100", "CoreSingleLanguage"}, 277 | {"101", "Core"}, 278 | {"103", "ProfessionalWMC"}, 279 | {"105", "EmbeddedIndustryEval"}, 280 | {"106", "EmbeddedIndustryEEval"}, 281 | {"107", "EmbeddedEval"}, 282 | {"108", "EmbeddedEEval"}, 283 | {"109", "ServerNano"}, 284 | {"110", "ServerCloudStorage"}, 285 | {"111", "CoreConnected"}, 286 | {"112", "ProfessionalStudent"}, 287 | {"113", "CoreConnectedN"}, 288 | {"114", "ProfessionalStudentN"}, 289 | {"115", "CoreConnectedSingleLanguage"}, 290 | {"116", "CoreConnectedCountrySpecific"}, 291 | {"117", "ConnectedCar"}, 292 | {"118", "IndustryHandheld"}, 293 | {"119", "PPIPro"}, 294 | {"120", "ServerARM64"}, 295 | {"121", "Education"}, 296 | {"122", "EducationN"}, 297 | {"123", "IoTUAP"}, 298 | {"124", "ServerCloudHostInfrastructure"}, 299 | {"125", "EnterpriseS"}, 300 | {"126", "EnterpriseSN"}, 301 | {"127", "ProfessionalS"}, 302 | {"128", "ProfessionalSN"}, 303 | {"129", "EnterpriseSEval"}, 304 | {"130", "EnterpriseSNEval"}, 305 | {"131", "IoTUAPCommercial"}, 306 | {"133", "MobileEnterprise"}, 307 | {"135", "Holographic"}, 308 | {"136", "HolographicBusiness"}, 309 | {"138", "ProfessionalSingleLanguage"}, 310 | {"139", "ProfessionalCountrySpecific"}, 311 | {"140", "EnterpriseSubscription"}, 312 | {"141", "EnterpriseSubscriptionN"}, 313 | {"143", "ServerDatacenterNano"}, 314 | {"144", "ServerStandardNano"}, 315 | {"145", "ServerDatacenterACor"}, 316 | {"146", "ServerStandardACor"}, 317 | {"147", "ServerDatacenterWSCor"}, 318 | {"148", "ServerStandardWSCor"}, 319 | {"149", "UtilityVM"}, 320 | {"159", "ServerDatacenterEvalCor"}, 321 | {"160", "ServerStandardEvalCor"}, 322 | {"161", "ProfessionalWorkstation"}, 323 | {"162", "ProfessionalWorkstationN"}, 324 | {"164", "ProfessionalEducation"}, 325 | {"165", "ProfessionalEducationN"}, 326 | {"168", "ServerAzureCor"}, 327 | {"169", "ServerAzureNano"}, 328 | {"171", "EnterpriseG"}, 329 | {"172", "EnterpriseGN"}, 330 | {"175", "ServerRdsh"}, 331 | {"178", "Cloud"}, 332 | {"179", "CloudN"}, 333 | {"180", "HubOS"}, 334 | {"182", "OneCoreUpdateOS"}, 335 | {"183", "CloudE"}, 336 | {"184", "Andromeda"}, 337 | {"185", "IoTOS"}, 338 | {"186", "CloudEN"}, 339 | {"187", "IoTEdgeOS"}, 340 | {"188", "IoTEnterprise"}, 341 | {"189", "Lite"}, 342 | {"191", "IoTEnterpriseS"}, 343 | {"202", "CloudEditionN"}, 344 | {"203", "CloudEdition"}, 345 | {"406", "ServerAzureStackHCICor"}, 346 | {"407", "ServerTurbine"}, 347 | {"408", "ServerTurbineCor"} 348 | }; 349 | 350 | #endregion define 351 | 352 | private static void Main(string[] args) 353 | { 354 | string VersionString = GetOsVersion(); 355 | if (NativeOsVersion().ToString().Contains("10.0") == false && NativeOsVersion().ToString().Contains("11") == false) 356 | { 357 | return; 358 | } 359 | 360 | byte[] DST = HwidGetCurrentEx.HWID.HwidGetCurrentEx(); 361 | string Base64String1 = HwidGetCurrentEx.HWID.HwidCreateBlock(DST, DST[0]); 362 | string SessionId = VersionString + ";" + "Hwid=" + Base64String1 + ";"; 363 | 364 | int EditionID = 0; 365 | int szRes = SLGetWindowsInformationDWORD("Kernel-ProductInfo", ref EditionID); 366 | if (szRes != 0) 367 | { 368 | RegistryKey regkey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, (Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32)).OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", true); 369 | if (regkey != null) 370 | { 371 | string EditionName = regkey.GetValue("EditionID").ToString(); 372 | EditionID = int.Parse(SkuList.Where((x) => x.Value.ToString() == EditionName).Select((y) => y.Key.ToString()).ToList()[0]); 373 | } 374 | } 375 | 376 | if (KMS38) 377 | { 378 | string ProductKeys = KMSProductKey.Where((x) => x.Value.Item1 == EditionID && NativeOsVersion().Build >= x.Value.Item2).Select((y) => y.Key).ToList()[0]; 379 | if (string.IsNullOrEmpty(ProductKeys)) return; 380 | SessionId = SessionId + "GVLKExp=" + FileTime2SystemTime() + ";DownlevelGenuineState=1;"; 381 | } 382 | else 383 | { 384 | string ProductKeys = UpdateProductKey.Where((x) => x.Value.Item1 == EditionID && NativeOsVersion().Build >= x.Value.Item2).Select((y) => y.Key).ToList()[0]; 385 | if (string.IsNullOrEmpty(ProductKeys)) return; 386 | string pfn = UpdateProductKey[ProductKeys].Item4; 387 | SessionId = SessionId + "Pfn=" + pfn + ";DownlevelGenuineState=1;"; 388 | } 389 | 390 | byte[] bytesessionid = System.Text.Encoding.Unicode.GetBytes(SessionId); 391 | bytesessionid = bytesessionid.Concat(new byte[] { 0, 0 }).ToArray(); 392 | string base64string2 = Convert.ToBase64String(bytesessionid); 393 | SessionId = "SessionId=" + base64string2 + ";" + UtcTimeToIso8601(); 394 | //SessionId = "SessionId=TwBTAE0AYQBqAG8AcgBWAGUAcgBzAGkAbwBuAD0AMQAwADsATwBTAE0AaQBuAG8AcgBWAGUAcgBzAGkAbwBuAD0AMAA7AE8AUwBQAGwAYQB0AGYAbwByAG0ASQBkAD0AMgA7AFAAUAA9ADAAOwBIAHcAaQBkAD0AYgBRAEEAQQBBAEIATQBBAFEAZwBBAEEAQQBBAEEAQQBBAFEAQQBDAEEAQQBJAEEAQQB3AEEARQBBAEEAQQBBAEIAZwBBAEIAQQBBAEUAQQBhAEwANwA4AEcAWQBJAFoAZwBqAEsAbwArAEoAbwBZAGQAaQB1AFEATgBnADcAVABHAE4AYQB3AFcAaABlAE4ARABvADUAZgA4AGEAUQBPADMAaQA1AGMAVQBKAHAAYwBwAEcARABXADgAUgBEAHYARABBAEEAQwBBAEEARQBCAEEAQQBJAEYAQQBBAE0AQgBBAEEAUQBDAEEAQQBZAEIAQQBBAGcASABBAEEAawBEAEEAQQBvAEIAQQBBAHcASABBAEEAQQBBAEEAQQBBAEEAQQBBAD0APQA7AFAAZgBuAD0ATQBpAGMAcgBvAHMAbwBmAHQALgBXAGkAbgBkAG8AdwBzAC4ANAA4AC4AWAAxADkALQA5ADgAOAA0ADEAXwA4AHcAZQBrAHkAYgAzAGQAOABiAGIAdwBlADsARABvAHcAbgBsAGUAdgBlAGwARwBlAG4AdQBpAG4AZQBTAHQAYQB0AGUAPQAxADsAAAA=;TimeStampClient=2022-05-05T00:00:00Z"; 395 | byte[] hashArray = ComputeHashEx(SessionId); 396 | Debug.Print(hashArray.Length.ToString() + Environment.NewLine + BitConverter.ToString(hashArray).Replace("-", " ")); 397 | byte[] Dst = VRSAVaultSignPKCS.VRSA.SignPKCS(hashArray); 398 | if (Dst != null) 399 | { 400 | string base64string3 = System.Convert.ToBase64String(Dst); 401 | SaveData(SessionId, base64string3, System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\DigitalLicense.xml"); 402 | //SaveData(SessionId, base64string3, Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Microsoft\\Windows\\ClipSVC\\GenuineTicket\\DigitalLicense.xml"); 403 | } 404 | } 405 | 406 | #region function 407 | 408 | private static void SaveData(string SessionId, string Base64String3, string szPath) 409 | { 410 | if (string.IsNullOrEmpty(Base64String3) || string.IsNullOrEmpty(SessionId)) 411 | { 412 | return; 413 | } 414 | string pubkey = "BgIAAACkAABSU0ExAAgAAAEAAQARq+V11k+dvHMCaLWVCaSbeQNlOdWTLkkl0hdMh5V3YhLU2R4h0Jd+7k7qfZ4aIo4ussduwGgmyDRikj5L2R77GG2ciHk4i8siK8qg7frOU0KT5rEks3qVj38C3dS1wS6D67shBFrxPlOEP8+JlelgP7Gxmwdao7NF4LXZ3+KdbJ//9jkmN8iAOP0N2XzW0/cJp9P1q6hE7eeqc/3Qn3zMr0q1Dx7vstN98oV17hNYCwumOxxS1rH+3n7ap2JKRSelo8Jvi214jZLBL+hOtYaGpxs7zIL3ofpoaYy5g7pc/DaTvyfpJho5634jK7dXVFMpzJZMn9w0F/3rkquk0Amm"; 415 | using (XmlTextWriter writer = new XmlTextWriter(szPath, System.Text.Encoding.UTF8)) 416 | { 417 | writer.WriteStartDocument(); 418 | writer.Formatting = Formatting.Indented; 419 | writer.Indentation = 4; 420 | writer.WriteStartElement("genuineAuthorization", "http://www.microsoft.com/DRM/SL/GenuineAuthorization/1.0"); 421 | writer.WriteStartElement("version"); 422 | writer.WriteString("1.0"); 423 | writer.WriteEndElement(); 424 | writer.WriteStartElement("genuineProperties"); 425 | writer.WriteAttributeString("origin", "sppclient"); 426 | writer.WriteStartElement("properties"); 427 | writer.WriteString("SessionId=" + SessionId); 428 | writer.WriteEndElement(); 429 | writer.WriteStartElement("signatures"); 430 | writer.WriteStartElement("signature"); 431 | writer.WriteAttributeString("name", "downlevelGTkey"); 432 | writer.WriteAttributeString("method", "rsa-sha256"); 433 | writer.WriteAttributeString("key", pubkey); 434 | writer.WriteString(Base64String3); 435 | writer.WriteEndElement(); 436 | writer.WriteEndElement(); 437 | writer.WriteEndElement(); 438 | writer.WriteEndElement(); 439 | writer.WriteEndDocument(); 440 | } 441 | } 442 | 443 | private static string GetOsVersion() 444 | { 445 | RTL_OSVERSIONINFOEX osVersionInfo = new RTL_OSVERSIONINFOEX(); 446 | osVersionInfo.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osVersionInfo); 447 | int status = RtlGetVersion(out osVersionInfo); 448 | if (status != 0) 449 | { 450 | return ""; 451 | } 452 | return "OSMajorVersion=" + osVersionInfo.dwMajorVersion + ";OSMinorVersion=" + osVersionInfo.dwMinorVersion + ";OSPlatformId=" + osVersionInfo.dwPlatformId + ";PP=0"; 453 | } 454 | 455 | private static Version NativeOsVersion() 456 | { 457 | RTL_OSVERSIONINFOEX osVersionInfo = new RTL_OSVERSIONINFOEX(); 458 | osVersionInfo.dwOSVersionInfoSize = (uint)Marshal.SizeOf(typeof(RTL_OSVERSIONINFOEX)); 459 | int status = RtlGetVersion(out osVersionInfo); 460 | if (status != 0) 461 | { 462 | return Environment.OSVersion.Version; 463 | } 464 | return new Version((int)osVersionInfo.dwMajorVersion, (int)osVersionInfo.dwMinorVersion, (int)osVersionInfo.dwBuildNumber); 465 | } 466 | 467 | private static string FileTime2SystemTime() 468 | { 469 | FILE_TIME SystemTimeAsFileTime = new FILE_TIME(); 470 | GetSystemTimeAsFileTime(ref SystemTimeAsFileTime); 471 | SYSTEMTIME SysTime = new SYSTEMTIME(); 472 | FILE_TIME filetime = new FILE_TIME(); 473 | filetime.dwLowDateTime = SystemTimeAsFileTime.dwLowDateTime; 474 | if (FileTimeToSystemTime(ref filetime, out SysTime)) 475 | { 476 | var timestampclient = SysTime.wYear.ToString("0000") + "-" + SysTime.wMonth.ToString("00") + "-" + SysTime.wDay.ToString("00") + "T" + SysTime.wHour.ToString("00") + ":" + SysTime.wMinute.ToString("00") + ":" + SysTime.wSecond.ToString("00") + "Z"; 477 | return timestampclient.Replace(timestampclient.Substring(0, 10), "2038-01-19"); 478 | } 479 | return ""; 480 | } 481 | 482 | private static string UtcTimeToIso8601() 483 | { 484 | string timestampclient = ""; 485 | SYSTEMTIME SysTime = new SYSTEMTIME(); 486 | GetSystemTime(ref SysTime); 487 | //timestampclient = SysTime.wYear.ToString("0000") + "-" + SysTime.wMonth.ToString("00") + "-" + SysTime.wDay.ToString("00") + "T" + SysTime.wHour.ToString("00") + ":" + SysTime.wMinute.ToString("00") + ":" + SysTime.wSecond.ToString("00") + "Z"; 488 | timestampclient = SysTime.wYear.ToString("0000") + "-" + SysTime.wMonth.ToString("00") + "-" + SysTime.wDay.ToString("00") + "T" + "00:00:00Z"; 489 | if (string.IsNullOrEmpty(timestampclient)) 490 | { 491 | return string.Empty; 492 | } 493 | return "TimeStampClient=" + timestampclient; 494 | } 495 | 496 | private static byte[] ComputeHashEx(string szSessionId) 497 | { 498 | IntPtr phProv = IntPtr.Zero; 499 | if (CryptAcquireContextW(out phProv, null, "Microsoft Enhanced RSA and AES Cryptographic Provider", 0x18, 0xF0000020)) 500 | { 501 | byte[] pbDatas = new byte[4]; 502 | byte[] pNewData = ComputeHash(phProv, szSessionId, pbDatas); 503 | pbDatas = new byte[pNewData[0]]; 504 | byte[] pbNewData = ComputeHash(phProv, szSessionId, pbDatas); 505 | return pbNewData; 506 | } 507 | return null; 508 | } 509 | 510 | private static byte[] ComputeHash(IntPtr phProv, string SessionId, byte[] pbDatas) 511 | { 512 | byte[] ReturnBytes = null; 513 | IntPtr hHash = new IntPtr(); 514 | byte[] pbData = new byte[4]; 515 | if (CryptCreateHash(phProv, (uint)ALG_ID.CALG_RSA, IntPtr.Zero, 0, ref hHash)) 516 | { 517 | uint pdwDataLen = 4; 518 | if (CryptGetHashParam(hHash, 4, pbData, ref pdwDataLen, 0)) 519 | { 520 | if (!(pbDatas.Length == 4)) 521 | { 522 | byte[] pbBuffer = Encoding.ASCII.GetBytes(SessionId); 523 | if (CryptHashData(hHash, pbBuffer, (uint)pbBuffer.Length, 0)) 524 | { 525 | pdwDataLen = (uint)pbDatas.Length; 526 | if (CryptGetHashParam(hHash, (uint)HashParameters.HP_HASHVAL, pbDatas, ref pdwDataLen, 0)) 527 | { 528 | ReturnBytes = pbDatas; 529 | } 530 | } 531 | } 532 | else 533 | { 534 | ReturnBytes = pbData; 535 | } 536 | } 537 | } 538 | CryptDestroyHash(hHash); 539 | return ReturnBytes; 540 | } 541 | 542 | #endregion function 543 | } 544 | } -------------------------------------------------------------------------------- /VRSAVaultSignPKCS/DLLFromMemory.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * DLLFromMemory.Net 3 | * 4 | * Load a native DLL from memory without the need to allow unsafe code 5 | * 6 | * Copyright (C) 2018 - 2019 by Bernhard Schelling 7 | * 8 | * Based on Memory Module.net 0.2 9 | * Copyright (C) 2012 - 2018 by Andreas Kanzler (andi_kanzler(at)gmx.de) 10 | * https://github.com/Scavanger/MemoryModule.net 11 | * 12 | * Based on Memory DLL loading code Version 0.0.4 13 | * Copyright (C) 2004 - 2015 by Joachim Bauch (mail(at)joachim-bauch.de) 14 | * https://github.com/fancycode/MemoryModule 15 | * 16 | * 17 | * The contents of this file are subject to the Mozilla Public License Version 18 | * 2.0 (the "License"); you may not use this file except in compliance with 19 | * the License. You may obtain a copy of the License at 20 | * http://www.mozilla.org/MPL/ 21 | * 22 | * Software distributed under the License is distributed on an "AS IS" basis, 23 | * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 24 | * for the specific language governing rights and limitations under the 25 | * License. 26 | * 27 | * The Original Code is MemoryModule.c 28 | * 29 | * The Initial Developer of the Original Code is Joachim Bauch. 30 | * 31 | * Portions created by Joachim Bauch are Copyright (C) 2004 - 2015 32 | * Joachim Bauch. All Rights Reserved. 33 | * 34 | * Portions created by Andreas Kanzler are Copyright (C) 2012 - 2018 35 | * Andreas Kanzler. All Rights Reserved. 36 | * 37 | * Portions created by Bernhard Schelling are Copyright (C) 2018 - 2019 38 | * Bernhard Schelling. All Rights Reserved. 39 | * 40 | */ 41 | 42 | using System; 43 | using System.Runtime.InteropServices; 44 | 45 | public class DLLFromMemory : IDisposable 46 | { 47 | public class DllException : Exception 48 | { 49 | public DllException() : base() { } 50 | public DllException(string message) : base(message) { } 51 | public DllException(string message, Exception innerException) : base(message, innerException) { } 52 | } 53 | 54 | public bool Disposed { get; private set; } 55 | public bool IsDll { get; private set; } 56 | 57 | public IntPtr pCode = IntPtr.Zero; 58 | IntPtr pNTHeaders = IntPtr.Zero; 59 | IntPtr[] ImportModules; 60 | bool _initialized = false; 61 | DllEntryDelegate _dllEntry = null; 62 | ExeEntryDelegate _exeEntry = null; 63 | bool _isRelocated = false; 64 | 65 | [UnmanagedFunctionPointer(CallingConvention.Winapi)] 66 | delegate bool DllEntryDelegate(IntPtr hinstDLL, DllReason fdwReason, IntPtr lpReserved); 67 | 68 | [UnmanagedFunctionPointer(CallingConvention.Winapi)] 69 | delegate int ExeEntryDelegate(); 70 | 71 | [UnmanagedFunctionPointer(CallingConvention.Winapi)] 72 | delegate void ImageTlsDelegate(IntPtr dllHandle, DllReason reason, IntPtr reserved); 73 | 74 | /// 75 | /// Loads a unmanged (native) DLL in the memory. 76 | /// 77 | /// Dll as a byte array 78 | public DLLFromMemory(byte[] data) 79 | { 80 | Disposed = false; 81 | if (data == null) throw new ArgumentNullException("data"); 82 | MemoryLoadLibrary(data); 83 | } 84 | 85 | ~DLLFromMemory() 86 | { 87 | Dispose(); 88 | } 89 | 90 | /// 91 | /// Returns a delegate for a function inside the DLL. 92 | /// 93 | /// The type of the delegate. 94 | /// The name of the function to be searched. 95 | /// A delegate instance of type TDelegate 96 | public TDelegate GetDelegateFromFuncName(string funcName) where TDelegate : class 97 | { 98 | if (!typeof(Delegate).IsAssignableFrom(typeof(TDelegate))) throw new ArgumentException(typeof(TDelegate).Name + " is not a delegate"); 99 | TDelegate res = Marshal.GetDelegateForFunctionPointer((IntPtr)GetPtrFromFuncName(funcName), typeof(TDelegate)) as TDelegate; 100 | if (res == null) throw new DllException("Unable to get managed delegate"); 101 | return res; 102 | } 103 | 104 | /// 105 | /// Returns a delegate for a function inside the DLL. 106 | /// 107 | /// The Name of the function to be searched. 108 | /// The type of the delegate to be returned. 109 | /// A delegate instance that can be cast to the appropriate delegate type. 110 | public Delegate GetDelegateFromFuncName(string funcName, Type delegateType) 111 | { 112 | if (delegateType == null) throw new ArgumentNullException("delegateType"); 113 | if (!typeof(Delegate).IsAssignableFrom(delegateType)) throw new ArgumentException(delegateType.Name + " is not a delegate"); 114 | Delegate res = Marshal.GetDelegateForFunctionPointer(GetPtrFromFuncName(funcName), delegateType); 115 | if (res == null) throw new DllException("Unable to get managed delegate"); 116 | return res; 117 | } 118 | 119 | IntPtr GetPtrFromFuncName(string funcName) 120 | { 121 | if (Disposed) throw new ObjectDisposedException("DLLFromMemory"); 122 | if (string.IsNullOrEmpty(funcName)) throw new ArgumentException("funcName"); 123 | if (!IsDll) throw new InvalidOperationException("Loaded Module is not a DLL"); 124 | if (!_initialized) throw new InvalidOperationException("Dll is not initialized"); 125 | 126 | IntPtr pDirectory = PtrAdd(pNTHeaders, Of.IMAGE_NT_HEADERS_OptionalHeader + (Is64BitProcess ? Of64.IMAGE_OPTIONAL_HEADER_ExportTable : Of32.IMAGE_OPTIONAL_HEADER_ExportTable)); 127 | IMAGE_DATA_DIRECTORY Directory = PtrRead(pDirectory); 128 | if (Directory.Size == 0) throw new DllException("Dll has no export table"); 129 | 130 | IntPtr pExports = PtrAdd(pCode, Directory.VirtualAddress); 131 | IMAGE_EXPORT_DIRECTORY Exports = PtrRead(pExports); 132 | if (Exports.NumberOfFunctions == 0 || Exports.NumberOfNames == 0) throw new DllException("Dll exports no functions"); 133 | 134 | IntPtr pNameRef = PtrAdd(pCode, Exports.AddressOfNames); 135 | IntPtr pOrdinal = PtrAdd(pCode, Exports.AddressOfNameOrdinals); 136 | for (int i = 0; i < Exports.NumberOfNames; i++, pNameRef = PtrAdd(pNameRef, sizeof(uint)), pOrdinal = PtrAdd(pOrdinal, sizeof(ushort))) 137 | { 138 | uint NameRef = PtrRead(pNameRef); 139 | ushort Ordinal = PtrRead(pOrdinal); 140 | string curFuncName = Marshal.PtrToStringAnsi(PtrAdd(pCode, NameRef)); 141 | if (curFuncName == funcName) 142 | { 143 | if (Ordinal > Exports.NumberOfFunctions) throw new DllException("Invalid function ordinal"); 144 | IntPtr pAddressOfFunction = PtrAdd(pCode, (Exports.AddressOfFunctions + (uint)(Ordinal * 4))); 145 | return PtrAdd(pCode, PtrRead(pAddressOfFunction)); 146 | } 147 | } 148 | 149 | throw new DllException("Dll exports no function named " + funcName); 150 | } 151 | 152 | /// 153 | /// Call entry point of executable. 154 | /// 155 | /// Exitcode of executable 156 | public int MemoryCallEntryPoint() 157 | { 158 | if (Disposed) throw new ObjectDisposedException("DLLFromMemory"); 159 | if (IsDll || _exeEntry == null || !_isRelocated) throw new DllException("Unable to call entry point. Is loaded module a dll?"); 160 | return _exeEntry(); 161 | } 162 | 163 | void MemoryLoadLibrary(byte[] data) 164 | { 165 | if (data.Length < Marshal.SizeOf(typeof(IMAGE_DOS_HEADER))) throw new DllException("Not a valid executable file"); 166 | IMAGE_DOS_HEADER DosHeader = BytesReadStructAt(data, 0); 167 | if (DosHeader.e_magic != Win.IMAGE_DOS_SIGNATURE) throw new BadImageFormatException("Not a valid executable file"); 168 | 169 | if (data.Length < DosHeader.e_lfanew + Marshal.SizeOf(typeof(IMAGE_NT_HEADERS))) throw new DllException("Not a valid executable file"); 170 | IMAGE_NT_HEADERS OrgNTHeaders = BytesReadStructAt(data, DosHeader.e_lfanew); 171 | 172 | if (OrgNTHeaders.Signature != Win.IMAGE_NT_SIGNATURE) throw new BadImageFormatException("Not a valid PE file"); 173 | if (OrgNTHeaders.FileHeader.Machine != GetMachineType()) throw new BadImageFormatException("Machine type doesn't fit (i386 vs. AMD64)"); 174 | if ((OrgNTHeaders.OptionalHeader.SectionAlignment & 1) > 0) throw new BadImageFormatException("Wrong section alignment"); //Only support multiple of 2 175 | if (OrgNTHeaders.OptionalHeader.AddressOfEntryPoint == 0) throw new DllException("Module has no entry point"); 176 | 177 | SYSTEM_INFO systemInfo; 178 | Win.GetNativeSystemInfo(out systemInfo); 179 | uint lastSectionEnd = 0; 180 | int ofSection = Win.IMAGE_FIRST_SECTION(DosHeader.e_lfanew, OrgNTHeaders.FileHeader.SizeOfOptionalHeader); 181 | for (int i = 0; i != OrgNTHeaders.FileHeader.NumberOfSections; i++, ofSection += Sz.IMAGE_SECTION_HEADER) 182 | { 183 | IMAGE_SECTION_HEADER Section = BytesReadStructAt(data, ofSection); 184 | uint endOfSection = Section.VirtualAddress + (Section.SizeOfRawData > 0 ? Section.SizeOfRawData : OrgNTHeaders.OptionalHeader.SectionAlignment); 185 | if (endOfSection > lastSectionEnd) lastSectionEnd = endOfSection; 186 | } 187 | 188 | uint alignedImageSize = AlignValueUp(OrgNTHeaders.OptionalHeader.SizeOfImage, systemInfo.dwPageSize); 189 | uint alignedLastSection = AlignValueUp(lastSectionEnd, systemInfo.dwPageSize); 190 | if (alignedImageSize != alignedLastSection) throw new BadImageFormatException("Wrong section alignment"); 191 | 192 | IntPtr oldHeader_OptionalHeader_ImageBase; 193 | if (Is64BitProcess) oldHeader_OptionalHeader_ImageBase = (IntPtr)unchecked((long)(OrgNTHeaders.OptionalHeader.ImageBaseLong)); 194 | else oldHeader_OptionalHeader_ImageBase = (IntPtr)unchecked((int)(OrgNTHeaders.OptionalHeader.ImageBaseLong >> 32)); 195 | 196 | // reserve memory for image of library 197 | pCode = Win.VirtualAlloc(oldHeader_OptionalHeader_ImageBase, (UIntPtr)OrgNTHeaders.OptionalHeader.SizeOfImage, AllocationType.RESERVE | AllocationType.COMMIT, MemoryProtection.READWRITE); 198 | //pCode = IntPtr.Zero; //test relocation with this 199 | 200 | // try to allocate memory at arbitrary position 201 | if (pCode == IntPtr.Zero) pCode = Win.VirtualAlloc(IntPtr.Zero, (UIntPtr)OrgNTHeaders.OptionalHeader.SizeOfImage, AllocationType.RESERVE | AllocationType.COMMIT, MemoryProtection.READWRITE); 202 | 203 | if (pCode == IntPtr.Zero) throw new DllException("Out of Memory"); 204 | 205 | if (Is64BitProcess && PtrSpanBoundary(pCode, alignedImageSize, 32)) 206 | { 207 | // Memory block may not span 4 GB (32 bit) boundaries. 208 | System.Collections.Generic.List BlockedMemory = new System.Collections.Generic.List(); 209 | while (PtrSpanBoundary(pCode, alignedImageSize, 32)) 210 | { 211 | BlockedMemory.Add(pCode); 212 | pCode = Win.VirtualAlloc(IntPtr.Zero, (UIntPtr)alignedImageSize, AllocationType.RESERVE | AllocationType.COMMIT, MemoryProtection.READWRITE); 213 | if (pCode == IntPtr.Zero) break; 214 | } 215 | foreach (IntPtr ptr in BlockedMemory) Win.VirtualFree(ptr, IntPtr.Zero, AllocationType.RELEASE); 216 | if (pCode == IntPtr.Zero) throw new DllException("Out of Memory"); 217 | } 218 | 219 | // commit memory for headers 220 | IntPtr headers = Win.VirtualAlloc(pCode, (UIntPtr)OrgNTHeaders.OptionalHeader.SizeOfHeaders, AllocationType.COMMIT, MemoryProtection.READWRITE); 221 | if (headers == IntPtr.Zero) throw new DllException("Out of Memory"); 222 | 223 | // copy PE header to code 224 | Marshal.Copy(data, 0, headers, (int)(OrgNTHeaders.OptionalHeader.SizeOfHeaders)); 225 | pNTHeaders = PtrAdd(headers, DosHeader.e_lfanew); 226 | 227 | IntPtr locationDelta = PtrSub(pCode, oldHeader_OptionalHeader_ImageBase); 228 | if (locationDelta != IntPtr.Zero) 229 | { 230 | // update relocated position 231 | Marshal.OffsetOf(typeof(IMAGE_NT_HEADERS), "OptionalHeader"); 232 | Marshal.OffsetOf(typeof(IMAGE_OPTIONAL_HEADER), "ImageBaseLong"); 233 | IntPtr pImageBase = PtrAdd(pNTHeaders, Of.IMAGE_NT_HEADERS_OptionalHeader + (Is64BitProcess ? Of64.IMAGE_OPTIONAL_HEADER_ImageBase : Of32.IMAGE_OPTIONAL_HEADER_ImageBase)); 234 | PtrWrite(pImageBase, pCode); 235 | } 236 | 237 | // copy sections from DLL file block to new memory location 238 | CopySections(ref OrgNTHeaders, pCode, pNTHeaders, data); 239 | 240 | // adjust base address of imported data 241 | _isRelocated = (locationDelta != IntPtr.Zero ? PerformBaseRelocation(ref OrgNTHeaders, pCode, locationDelta) : true); 242 | 243 | // load required dlls and adjust function table of imports 244 | ImportModules = BuildImportTable(ref OrgNTHeaders, pCode); 245 | 246 | // mark memory pages depending on section headers and release 247 | // sections that are marked as "discardable" 248 | FinalizeSections(ref OrgNTHeaders, pCode, pNTHeaders, systemInfo.dwPageSize); 249 | 250 | // TLS callbacks are executed BEFORE the main loading 251 | ExecuteTLS(ref OrgNTHeaders, pCode, pNTHeaders); 252 | 253 | // get entry point of loaded library 254 | IsDll = ((OrgNTHeaders.FileHeader.Characteristics & Win.IMAGE_FILE_DLL) != 0); 255 | if (OrgNTHeaders.OptionalHeader.AddressOfEntryPoint != 0) 256 | { 257 | if (IsDll) 258 | { 259 | // notify library about attaching to process 260 | IntPtr dllEntryPtr = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.AddressOfEntryPoint); 261 | _dllEntry = (DllEntryDelegate)Marshal.GetDelegateForFunctionPointer(dllEntryPtr, typeof(DllEntryDelegate)); 262 | 263 | _initialized = (_dllEntry != null && _dllEntry(pCode, DllReason.DLL_PROCESS_ATTACH, IntPtr.Zero)); 264 | if (!_initialized) throw new DllException("Can't attach DLL to process"); 265 | } 266 | else 267 | { 268 | IntPtr exeEntryPtr = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.AddressOfEntryPoint); 269 | _exeEntry = (ExeEntryDelegate)Marshal.GetDelegateForFunctionPointer(exeEntryPtr, typeof(ExeEntryDelegate)); 270 | } 271 | } 272 | } 273 | 274 | static void CopySections(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode, IntPtr pNTHeaders, byte[] data) 275 | { 276 | IntPtr pSection = Win.IMAGE_FIRST_SECTION(pNTHeaders, OrgNTHeaders.FileHeader.SizeOfOptionalHeader); 277 | for (int i = 0; i < OrgNTHeaders.FileHeader.NumberOfSections; i++, pSection = PtrAdd(pSection, Sz.IMAGE_SECTION_HEADER)) 278 | { 279 | IMAGE_SECTION_HEADER Section = PtrRead(pSection); 280 | if (Section.SizeOfRawData == 0) 281 | { 282 | // section doesn't contain data in the dll itself, but may define uninitialized data 283 | uint size = OrgNTHeaders.OptionalHeader.SectionAlignment; 284 | if (size > 0) 285 | { 286 | IntPtr dest = Win.VirtualAlloc(PtrAdd(pCode, Section.VirtualAddress), (UIntPtr)size, AllocationType.COMMIT, MemoryProtection.READWRITE); 287 | if (dest == IntPtr.Zero) throw new DllException("Unable to allocate memory"); 288 | 289 | // Always use position from file to support alignments smaller than page size (allocation above will align to page size). 290 | dest = PtrAdd(pCode, Section.VirtualAddress); 291 | 292 | // NOTE: On 64bit systems we truncate to 32bit here but expand again later when "PhysicalAddress" is used. 293 | PtrWrite(PtrAdd(pSection, Of.IMAGE_SECTION_HEADER_PhysicalAddress), unchecked((uint)(ulong)(long)dest)); 294 | 295 | Win.MemSet(dest, 0, (UIntPtr)size); 296 | } 297 | 298 | // section is empty 299 | continue; 300 | } 301 | else 302 | { 303 | // commit memory block and copy data from dll 304 | IntPtr dest = Win.VirtualAlloc(PtrAdd(pCode, Section.VirtualAddress), (UIntPtr)Section.SizeOfRawData, AllocationType.COMMIT, MemoryProtection.READWRITE); 305 | if (dest == IntPtr.Zero) throw new DllException("Out of memory"); 306 | 307 | // Always use position from file to support alignments smaller than page size (allocation above will align to page size). 308 | dest = PtrAdd(pCode, Section.VirtualAddress); 309 | Marshal.Copy(data, checked((int)Section.PointerToRawData), dest, checked((int)Section.SizeOfRawData)); 310 | 311 | // NOTE: On 64bit systems we truncate to 32bit here but expand again later when "PhysicalAddress" is used. 312 | PtrWrite(PtrAdd(pSection, Of.IMAGE_SECTION_HEADER_PhysicalAddress), unchecked((uint)(ulong)(long)dest)); 313 | } 314 | } 315 | } 316 | 317 | static bool PerformBaseRelocation(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode, IntPtr delta) 318 | { 319 | if (OrgNTHeaders.OptionalHeader.BaseRelocationTable.Size == 0) return (delta == IntPtr.Zero); 320 | 321 | for (IntPtr pRelocation = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.BaseRelocationTable.VirtualAddress); ;) 322 | { 323 | IMAGE_BASE_RELOCATION Relocation = PtrRead(pRelocation); 324 | if (Relocation.VirtualAdress == 0) break; 325 | 326 | IntPtr pDest = PtrAdd(pCode, Relocation.VirtualAdress); 327 | IntPtr pRelInfo = PtrAdd(pRelocation, Sz.IMAGE_BASE_RELOCATION); 328 | uint RelCount = ((Relocation.SizeOfBlock - Sz.IMAGE_BASE_RELOCATION) / 2); 329 | for (uint i = 0; i != RelCount; i++, pRelInfo = PtrAdd(pRelInfo, sizeof(ushort))) 330 | { 331 | ushort relInfo = (ushort)Marshal.PtrToStructure(pRelInfo, typeof(ushort)); 332 | BasedRelocationType type = (BasedRelocationType)(relInfo >> 12); // the upper 4 bits define the type of relocation 333 | int offset = (relInfo & 0xfff); // the lower 12 bits define the offset 334 | IntPtr pPatchAddr = PtrAdd(pDest, offset); 335 | 336 | switch (type) 337 | { 338 | case BasedRelocationType.IMAGE_REL_BASED_ABSOLUTE: 339 | // skip relocation 340 | break; 341 | case BasedRelocationType.IMAGE_REL_BASED_HIGHLOW: 342 | // change complete 32 bit address 343 | int patchAddrHL = (int)Marshal.PtrToStructure(pPatchAddr, typeof(int)); 344 | patchAddrHL += (int)delta; 345 | Marshal.StructureToPtr(patchAddrHL, pPatchAddr, false); 346 | break; 347 | case BasedRelocationType.IMAGE_REL_BASED_DIR64: 348 | long patchAddr64 = (long)Marshal.PtrToStructure(pPatchAddr, typeof(long)); 349 | patchAddr64 += (long)delta; 350 | Marshal.StructureToPtr(patchAddr64, pPatchAddr, false); 351 | break; 352 | } 353 | } 354 | 355 | // advance to next relocation block 356 | pRelocation = PtrAdd(pRelocation, Relocation.SizeOfBlock); 357 | } 358 | return true; 359 | } 360 | 361 | static IntPtr[] BuildImportTable(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode) 362 | { 363 | System.Collections.Generic.List ImportModules = new System.Collections.Generic.List(); 364 | uint NumEntries = OrgNTHeaders.OptionalHeader.ImportTable.Size / Sz.IMAGE_IMPORT_DESCRIPTOR; 365 | IntPtr pImportDesc = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.ImportTable.VirtualAddress); 366 | for (uint i = 0; i != NumEntries; i++, pImportDesc = PtrAdd(pImportDesc, Sz.IMAGE_IMPORT_DESCRIPTOR)) 367 | { 368 | IMAGE_IMPORT_DESCRIPTOR ImportDesc = PtrRead(pImportDesc); 369 | if (ImportDesc.Name == 0) break; 370 | 371 | IntPtr handle = Win.LoadLibrary(PtrAdd(pCode, ImportDesc.Name)); 372 | if (PtrIsInvalidHandle(handle)) 373 | { 374 | foreach (IntPtr m in ImportModules) Win.FreeLibrary(m); 375 | ImportModules.Clear(); 376 | throw new DllException("Can't load libary " + Marshal.PtrToStringAnsi(PtrAdd(pCode, ImportDesc.Name))); 377 | } 378 | ImportModules.Add(handle); 379 | 380 | IntPtr pThunkRef, pFuncRef; 381 | if (ImportDesc.OriginalFirstThunk > 0) 382 | { 383 | pThunkRef = PtrAdd(pCode, ImportDesc.OriginalFirstThunk); 384 | pFuncRef = PtrAdd(pCode, ImportDesc.FirstThunk); 385 | } 386 | else 387 | { 388 | // no hint table 389 | pThunkRef = PtrAdd(pCode, ImportDesc.FirstThunk); 390 | pFuncRef = PtrAdd(pCode, ImportDesc.FirstThunk); 391 | } 392 | for (int SzRef = IntPtr.Size; ; pThunkRef = PtrAdd(pThunkRef, SzRef), pFuncRef = PtrAdd(pFuncRef, SzRef)) 393 | { 394 | IntPtr ReadThunkRef = PtrRead(pThunkRef), WriteFuncRef; 395 | if (ReadThunkRef == IntPtr.Zero) break; 396 | if (Win.IMAGE_SNAP_BY_ORDINAL(ReadThunkRef)) 397 | { 398 | WriteFuncRef = Win.GetProcAddress(handle, Win.IMAGE_ORDINAL(ReadThunkRef)); 399 | } 400 | else 401 | { 402 | WriteFuncRef = Win.GetProcAddress(handle, PtrAdd(PtrAdd(pCode, ReadThunkRef), Of.IMAGE_IMPORT_BY_NAME_Name)); 403 | } 404 | if (WriteFuncRef == IntPtr.Zero) throw new DllException("Can't get adress for imported function"); 405 | PtrWrite(pFuncRef, WriteFuncRef); 406 | } 407 | } 408 | return (ImportModules.Count > 0 ? ImportModules.ToArray() : null); 409 | } 410 | 411 | static void FinalizeSections(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode, IntPtr pNTHeaders, uint PageSize) 412 | { 413 | UIntPtr imageOffset = (Is64BitProcess ? (UIntPtr)(unchecked((ulong)pCode.ToInt64()) & 0xffffffff00000000) : UIntPtr.Zero); 414 | IntPtr pSection = Win.IMAGE_FIRST_SECTION(pNTHeaders, OrgNTHeaders.FileHeader.SizeOfOptionalHeader); 415 | IMAGE_SECTION_HEADER Section = PtrRead(pSection); 416 | SectionFinalizeData sectionData = new SectionFinalizeData(); 417 | sectionData.Address = PtrBitOr(PtrAdd((IntPtr)0, Section.PhysicalAddress), imageOffset); 418 | sectionData.AlignedAddress = PtrAlignDown(sectionData.Address, (UIntPtr)PageSize); 419 | sectionData.Size = GetRealSectionSize(ref Section, ref OrgNTHeaders); 420 | sectionData.Characteristics = Section.Characteristics; 421 | sectionData.Last = false; 422 | pSection = PtrAdd(pSection, Sz.IMAGE_SECTION_HEADER); 423 | 424 | // loop through all sections and change access flags 425 | for (int i = 1; i < OrgNTHeaders.FileHeader.NumberOfSections; i++, pSection = PtrAdd(pSection, Sz.IMAGE_SECTION_HEADER)) 426 | { 427 | Section = PtrRead(pSection); 428 | IntPtr sectionAddress = PtrBitOr(PtrAdd((IntPtr)0, Section.PhysicalAddress), imageOffset); 429 | IntPtr alignedAddress = PtrAlignDown(sectionAddress, (UIntPtr)PageSize); 430 | IntPtr sectionSize = GetRealSectionSize(ref Section, ref OrgNTHeaders); 431 | 432 | // Combine access flags of all sections that share a page 433 | // TODO(fancycode): We currently share flags of a trailing large section with the page of a first small section. This should be optimized. 434 | IntPtr a = PtrAdd(sectionData.Address, sectionData.Size); 435 | ulong b = unchecked((ulong)a.ToInt64()), c = unchecked((ulong)alignedAddress); 436 | 437 | if (sectionData.AlignedAddress == alignedAddress || unchecked((ulong)PtrAdd(sectionData.Address, sectionData.Size).ToInt64()) > unchecked((ulong)alignedAddress)) 438 | { 439 | // Section shares page with previous 440 | if ((Section.Characteristics & Win.IMAGE_SCN_MEM_DISCARDABLE) == 0 || (sectionData.Characteristics & Win.IMAGE_SCN_MEM_DISCARDABLE) == 0) 441 | { 442 | sectionData.Characteristics = (sectionData.Characteristics | Section.Characteristics) & ~Win.IMAGE_SCN_MEM_DISCARDABLE; 443 | } 444 | else 445 | { 446 | sectionData.Characteristics |= Section.Characteristics; 447 | } 448 | sectionData.Size = PtrSub(PtrAdd(sectionAddress, sectionSize), sectionData.Address); 449 | continue; 450 | } 451 | 452 | FinalizeSection(sectionData, PageSize, OrgNTHeaders.OptionalHeader.SectionAlignment); 453 | 454 | sectionData.Address = sectionAddress; 455 | sectionData.AlignedAddress = alignedAddress; 456 | sectionData.Size = sectionSize; 457 | sectionData.Characteristics = Section.Characteristics; 458 | } 459 | sectionData.Last = true; 460 | FinalizeSection(sectionData, PageSize, OrgNTHeaders.OptionalHeader.SectionAlignment); 461 | } 462 | 463 | static void FinalizeSection(SectionFinalizeData SectionData, uint PageSize, uint SectionAlignment) 464 | { 465 | if (SectionData.Size == IntPtr.Zero) 466 | return; 467 | 468 | if ((SectionData.Characteristics & Win.IMAGE_SCN_MEM_DISCARDABLE) > 0) 469 | { 470 | // section is not needed any more and can safely be freed 471 | if (SectionData.Address == SectionData.AlignedAddress && 472 | (SectionData.Last || 473 | SectionAlignment == PageSize || 474 | (unchecked((ulong)SectionData.Size.ToInt64()) % PageSize) == 0) 475 | ) 476 | { 477 | // Only allowed to decommit whole pages 478 | Win.VirtualFree(SectionData.Address, SectionData.Size, AllocationType.DECOMMIT); 479 | } 480 | return; 481 | } 482 | 483 | // determine protection flags based on characteristics 484 | int readable = (SectionData.Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_READ) != 0 ? 1 : 0; 485 | int writeable = (SectionData.Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_WRITE) != 0 ? 1 : 0; 486 | int executable = (SectionData.Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_EXECUTE) != 0 ? 1 : 0; 487 | uint protect = (uint)ProtectionFlags[executable, readable, writeable]; 488 | if ((SectionData.Characteristics & Win.IMAGE_SCN_MEM_NOT_CACHED) > 0) protect |= Win.PAGE_NOCACHE; 489 | 490 | // change memory access flags 491 | uint oldProtect; 492 | if (!Win.VirtualProtect(SectionData.Address, SectionData.Size, protect, out oldProtect)) 493 | throw new DllException("Error protecting memory page"); 494 | } 495 | 496 | static void ExecuteTLS(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode, IntPtr pNTHeaders) 497 | { 498 | if (OrgNTHeaders.OptionalHeader.TLSTable.VirtualAddress == 0) return; 499 | IMAGE_TLS_DIRECTORY tlsDir = PtrRead(PtrAdd(pCode, OrgNTHeaders.OptionalHeader.TLSTable.VirtualAddress)); 500 | IntPtr pCallBack = tlsDir.AddressOfCallBacks; 501 | if (pCallBack != IntPtr.Zero) 502 | { 503 | for (IntPtr Callback; (Callback = PtrRead(pCallBack)) != IntPtr.Zero; pCallBack = PtrAdd(pCallBack, IntPtr.Size)) 504 | { 505 | ImageTlsDelegate tls = (ImageTlsDelegate)Marshal.GetDelegateForFunctionPointer(Callback, typeof(ImageTlsDelegate)); 506 | tls(pCode, DllReason.DLL_PROCESS_ATTACH, IntPtr.Zero); 507 | } 508 | } 509 | } 510 | 511 | /// 512 | /// Check if the process runs in 64bit mode or in 32bit mode 513 | /// 514 | /// True if process is 64bit, false if it is 32bit 515 | public static bool Is64BitProcess { get { return IntPtr.Size == 8; } } 516 | 517 | static uint GetMachineType() { return (IntPtr.Size == 8 ? Win.IMAGE_FILE_MACHINE_AMD64 : Win.IMAGE_FILE_MACHINE_I386); } 518 | 519 | static uint AlignValueUp(uint value, uint alignment) { return (value + alignment - 1) & ~(alignment - 1); } 520 | 521 | static IntPtr GetRealSectionSize(ref IMAGE_SECTION_HEADER Section, ref IMAGE_NT_HEADERS NTHeaders) 522 | { 523 | uint size = Section.SizeOfRawData; 524 | if (size == 0) 525 | { 526 | if ((Section.Characteristics & Win.IMAGE_SCN_CNT_INITIALIZED_DATA) > 0) 527 | { 528 | size = NTHeaders.OptionalHeader.SizeOfInitializedData; 529 | } 530 | else if ((Section.Characteristics & Win.IMAGE_SCN_CNT_UNINITIALIZED_DATA) > 0) 531 | { 532 | size = NTHeaders.OptionalHeader.SizeOfUninitializedData; 533 | } 534 | } 535 | return (IntPtr.Size == 8 ? (IntPtr)unchecked((long)size) : (IntPtr)unchecked((int)size)); 536 | } 537 | 538 | public void Close() { ((IDisposable)this).Dispose(); } 539 | 540 | void IDisposable.Dispose() 541 | { 542 | Dispose(); 543 | GC.SuppressFinalize(this); 544 | } 545 | 546 | public void Dispose() 547 | { 548 | if (_initialized) 549 | { 550 | if (_dllEntry != null) _dllEntry.Invoke(pCode, DllReason.DLL_PROCESS_DETACH, IntPtr.Zero); 551 | _initialized = false; 552 | } 553 | 554 | if (ImportModules != null) 555 | { 556 | foreach (IntPtr m in ImportModules) if (!PtrIsInvalidHandle(m)) Win.FreeLibrary(m); 557 | ImportModules = null; 558 | } 559 | 560 | if (pCode != IntPtr.Zero) 561 | { 562 | Win.VirtualFree(pCode, IntPtr.Zero, AllocationType.RELEASE); 563 | pCode = IntPtr.Zero; 564 | pNTHeaders = IntPtr.Zero; 565 | } 566 | 567 | Disposed = true; 568 | } 569 | 570 | // Protection flags for memory pages (Executable, Readable, Writeable) 571 | static readonly PageProtection[,,] ProtectionFlags = new PageProtection[2, 2, 2] 572 | { 573 | { 574 | // not executable 575 | { PageProtection.NOACCESS, PageProtection.WRITECOPY }, 576 | { PageProtection.READONLY, PageProtection.READWRITE } 577 | }, 578 | { 579 | // executable 580 | { PageProtection.EXECUTE, PageProtection.EXECUTE_WRITECOPY }, 581 | { PageProtection.EXECUTE_READ, PageProtection.EXECUTE_READWRITE } 582 | } 583 | }; 584 | 585 | struct SectionFinalizeData 586 | { 587 | internal IntPtr Address; 588 | internal IntPtr AlignedAddress; 589 | internal IntPtr Size; 590 | internal uint Characteristics; 591 | internal bool Last; 592 | } 593 | 594 | class Of 595 | { 596 | internal const int IMAGE_NT_HEADERS_OptionalHeader = 24; 597 | internal const int IMAGE_SECTION_HEADER_PhysicalAddress = 8; 598 | internal const int IMAGE_IMPORT_BY_NAME_Name = 2; 599 | } 600 | 601 | class Of32 602 | { 603 | internal const int IMAGE_OPTIONAL_HEADER_ImageBase = 28; 604 | internal const int IMAGE_OPTIONAL_HEADER_ExportTable = 96; 605 | } 606 | 607 | class Of64 608 | { 609 | internal const int IMAGE_OPTIONAL_HEADER_ImageBase = 24; 610 | internal const int IMAGE_OPTIONAL_HEADER_ExportTable = 112; 611 | } 612 | 613 | class Sz 614 | { 615 | internal const int IMAGE_SECTION_HEADER = 40; 616 | internal const int IMAGE_BASE_RELOCATION = 8; 617 | internal const int IMAGE_IMPORT_DESCRIPTOR = 20; 618 | } 619 | 620 | [StructLayout(LayoutKind.Sequential)] 621 | struct IMAGE_DOS_HEADER 622 | { 623 | public ushort e_magic; // Magic number 624 | public ushort e_cblp; // Bytes on last page of file 625 | public ushort e_cp; // Pages in file 626 | public ushort e_crlc; // Relocations 627 | public ushort e_cparhdr; // Size of header in paragraphs 628 | public ushort e_minalloc; // Minimum extra paragraphs needed 629 | public ushort e_maxalloc; // Maximum extra paragraphs needed 630 | public ushort e_ss; // Initial (relative) SS value 631 | public ushort e_sp; // Initial SP value 632 | public ushort e_csum; // Checksum 633 | public ushort e_ip; // Initial IP value 634 | public ushort e_cs; // Initial (relative) CS value 635 | public ushort e_lfarlc; // File address of relocation table 636 | public ushort e_ovno; // Overlay number 637 | public ushort e_res1a, e_res1b, e_res1c, e_res1d; // Reserved words 638 | public ushort e_oemid; // OEM identifier (for e_oeminfo) 639 | public ushort e_oeminfo; // OEM information; e_oemid specific 640 | public ushort e_res2a, e_res2b, e_res2c, e_res2d, e_res2e, e_res2f, e_res2g, e_res2h, e_res2i, e_res2j; // Reserved words 641 | public int e_lfanew; // File address of new exe header 642 | } 643 | 644 | [StructLayout(LayoutKind.Sequential)] 645 | struct IMAGE_NT_HEADERS 646 | { 647 | public uint Signature; 648 | public IMAGE_FILE_HEADER FileHeader; 649 | public IMAGE_OPTIONAL_HEADER OptionalHeader; 650 | } 651 | 652 | [StructLayout(LayoutKind.Sequential)] 653 | struct IMAGE_FILE_HEADER 654 | { 655 | public ushort Machine; 656 | public ushort NumberOfSections; 657 | public uint TimeDateStamp; 658 | public uint PointerToSymbolTable; 659 | public uint NumberOfSymbols; 660 | public ushort SizeOfOptionalHeader; 661 | public ushort Characteristics; 662 | } 663 | 664 | [StructLayout(LayoutKind.Sequential)] 665 | struct IMAGE_OPTIONAL_HEADER 666 | { 667 | public MagicType Magic; 668 | public byte MajorLinkerVersion; 669 | public byte MinorLinkerVersion; 670 | public uint SizeOfCode; 671 | public uint SizeOfInitializedData; 672 | public uint SizeOfUninitializedData; 673 | public uint AddressOfEntryPoint; 674 | public uint BaseOfCode; 675 | public ulong ImageBaseLong; 676 | public uint SectionAlignment; 677 | public uint FileAlignment; 678 | public ushort MajorOperatingSystemVersion; 679 | public ushort MinorOperatingSystemVersion; 680 | public ushort MajorImageVersion; 681 | public ushort MinorImageVersion; 682 | public ushort MajorSubsystemVersion; 683 | public ushort MinorSubsystemVersion; 684 | public uint Win32VersionValue; 685 | public uint SizeOfImage; 686 | public uint SizeOfHeaders; 687 | public uint CheckSum; 688 | public SubSystemType Subsystem; 689 | public DllCharacteristicsType DllCharacteristics; 690 | public IntPtr SizeOfStackReserve; 691 | public IntPtr SizeOfStackCommit; 692 | public IntPtr SizeOfHeapReserve; 693 | public IntPtr SizeOfHeapCommit; 694 | public uint LoaderFlags; 695 | public uint NumberOfRvaAndSizes; 696 | public IMAGE_DATA_DIRECTORY ExportTable; 697 | public IMAGE_DATA_DIRECTORY ImportTable; 698 | public IMAGE_DATA_DIRECTORY ResourceTable; 699 | public IMAGE_DATA_DIRECTORY ExceptionTable; 700 | public IMAGE_DATA_DIRECTORY CertificateTable; 701 | public IMAGE_DATA_DIRECTORY BaseRelocationTable; 702 | public IMAGE_DATA_DIRECTORY Debug; 703 | public IMAGE_DATA_DIRECTORY Architecture; 704 | public IMAGE_DATA_DIRECTORY GlobalPtr; 705 | public IMAGE_DATA_DIRECTORY TLSTable; 706 | public IMAGE_DATA_DIRECTORY LoadConfigTable; 707 | public IMAGE_DATA_DIRECTORY BoundImport; 708 | public IMAGE_DATA_DIRECTORY IAT; 709 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor; 710 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader; 711 | public IMAGE_DATA_DIRECTORY Reserved; 712 | } 713 | 714 | [StructLayout(LayoutKind.Sequential)] 715 | struct IMAGE_DATA_DIRECTORY 716 | { 717 | public uint VirtualAddress; 718 | public uint Size; 719 | } 720 | 721 | [StructLayout(LayoutKind.Sequential)] 722 | struct IMAGE_SECTION_HEADER 723 | { 724 | public ulong Name; //8 byte string 725 | public uint PhysicalAddress; 726 | public uint VirtualAddress; 727 | public uint SizeOfRawData; 728 | public uint PointerToRawData; 729 | public uint PointerToRelocations; 730 | public uint PointerToLinenumbers; 731 | public ushort NumberOfRelocations; 732 | public ushort NumberOfLinenumbers; 733 | public uint Characteristics; 734 | } 735 | 736 | [StructLayout(LayoutKind.Sequential)] 737 | struct IMAGE_BASE_RELOCATION 738 | { 739 | public uint VirtualAdress; 740 | public uint SizeOfBlock; 741 | } 742 | 743 | [StructLayout(LayoutKind.Sequential)] 744 | struct IMAGE_IMPORT_DESCRIPTOR 745 | { 746 | public uint OriginalFirstThunk; 747 | public uint TimeDateStamp; 748 | public uint ForwarderChain; 749 | public uint Name; 750 | public uint FirstThunk; 751 | } 752 | 753 | [StructLayout(LayoutKind.Sequential)] 754 | struct IMAGE_EXPORT_DIRECTORY 755 | { 756 | public uint Characteristics; 757 | public uint TimeDateStamp; 758 | public ushort MajorVersion; 759 | public ushort MinorVersion; 760 | public uint Name; 761 | public uint Base; 762 | public uint NumberOfFunctions; 763 | public uint NumberOfNames; 764 | public uint AddressOfFunctions; // RVA from base of image 765 | public uint AddressOfNames; // RVA from base of image 766 | public uint AddressOfNameOrdinals; // RVA from base of image 767 | } 768 | 769 | [StructLayout(LayoutKind.Sequential)] 770 | struct SYSTEM_INFO 771 | { 772 | public ushort wProcessorArchitecture; 773 | public ushort wReserved; 774 | public uint dwPageSize; 775 | public IntPtr lpMinimumApplicationAddress; 776 | public IntPtr lpMaximumApplicationAddress; 777 | public IntPtr dwActiveProcessorMask; 778 | public uint dwNumberOfProcessors; 779 | public uint dwProcessorType; 780 | public uint dwAllocationGranularity; 781 | public ushort wProcessorLevel; 782 | public ushort wProcessorRevision; 783 | }; 784 | 785 | [StructLayout(LayoutKind.Sequential)] 786 | struct IMAGE_TLS_DIRECTORY 787 | { 788 | public IntPtr StartAddressOfRawData; 789 | public IntPtr EndAddressOfRawData; 790 | public IntPtr AddressOfIndex; 791 | public IntPtr AddressOfCallBacks; 792 | public IntPtr SizeOfZeroFill; 793 | public uint Characteristics; 794 | } 795 | 796 | enum MagicType : ushort 797 | { 798 | IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b, 799 | IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b 800 | } 801 | 802 | enum SubSystemType : ushort 803 | { 804 | IMAGE_SUBSYSTEM_UNKNOWN = 0, 805 | IMAGE_SUBSYSTEM_NATIVE = 1, 806 | IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, 807 | IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, 808 | IMAGE_SUBSYSTEM_POSIX_CUI = 7, 809 | IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, 810 | IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, 811 | IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, 812 | IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, 813 | IMAGE_SUBSYSTEM_EFI_ROM = 13, 814 | IMAGE_SUBSYSTEM_XBOX = 14 815 | } 816 | 817 | enum DllCharacteristicsType : ushort 818 | { 819 | RES_0 = 0x0001, 820 | RES_1 = 0x0002, 821 | RES_2 = 0x0004, 822 | RES_3 = 0x0008, 823 | IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040, 824 | IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080, 825 | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100, 826 | IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200, 827 | IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400, 828 | IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800, 829 | RES_4 = 0x1000, 830 | IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000, 831 | IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000 832 | } 833 | 834 | enum BasedRelocationType 835 | { 836 | IMAGE_REL_BASED_ABSOLUTE = 0, 837 | IMAGE_REL_BASED_HIGH = 1, 838 | IMAGE_REL_BASED_LOW = 2, 839 | IMAGE_REL_BASED_HIGHLOW = 3, 840 | IMAGE_REL_BASED_HIGHADJ = 4, 841 | IMAGE_REL_BASED_MIPS_JMPADDR = 5, 842 | IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, 843 | IMAGE_REL_BASED_IA64_IMM64 = 9, 844 | IMAGE_REL_BASED_DIR64 = 10 845 | } 846 | 847 | enum AllocationType : uint 848 | { 849 | COMMIT = 0x1000, 850 | RESERVE = 0x2000, 851 | RESET = 0x80000, 852 | LARGE_PAGES = 0x20000000, 853 | PHYSICAL = 0x400000, 854 | TOP_DOWN = 0x100000, 855 | WRITE_WATCH = 0x200000, 856 | DECOMMIT = 0x4000, 857 | RELEASE = 0x8000 858 | } 859 | 860 | enum MemoryProtection : uint 861 | { 862 | EXECUTE = 0x10, 863 | EXECUTE_READ = 0x20, 864 | EXECUTE_READWRITE = 0x40, 865 | EXECUTE_WRITECOPY = 0x80, 866 | NOACCESS = 0x01, 867 | READONLY = 0x02, 868 | READWRITE = 0x04, 869 | WRITECOPY = 0x08, 870 | GUARD_Modifierflag = 0x100, 871 | NOCACHE_Modifierflag = 0x200, 872 | WRITECOMBINE_Modifierflag = 0x400 873 | } 874 | 875 | enum PageProtection 876 | { 877 | NOACCESS = 0x01, 878 | READONLY = 0x02, 879 | READWRITE = 0x04, 880 | WRITECOPY = 0x08, 881 | EXECUTE = 0x10, 882 | EXECUTE_READ = 0x20, 883 | EXECUTE_READWRITE = 0x40, 884 | EXECUTE_WRITECOPY = 0x80, 885 | GUARD = 0x100, 886 | NOCACHE = 0x200, 887 | WRITECOMBINE = 0x400, 888 | } 889 | 890 | enum ImageSectionFlags : uint 891 | { 892 | IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000, // Section contains extended relocations. 893 | IMAGE_SCN_MEM_DISCARDABLE = 0x02000000, // Section can be discarded. 894 | IMAGE_SCN_MEM_NOT_CACHED = 0x04000000, // Section is not cachable. 895 | IMAGE_SCN_MEM_NOT_PAGED = 0x08000000, // Section is not pageable. 896 | IMAGE_SCN_MEM_SHARED = 0x10000000, // Section is shareable. 897 | IMAGE_SCN_MEM_EXECUTE = 0x20000000, // Section is executable. 898 | IMAGE_SCN_MEM_READ = 0x40000000, // Section is readable. 899 | IMAGE_SCN_MEM_WRITE = 0x80000000 // Section is writeable. 900 | } 901 | 902 | enum DllReason : uint 903 | { 904 | DLL_PROCESS_ATTACH = 1, 905 | DLL_THREAD_ATTACH = 2, 906 | DLL_THREAD_DETACH = 3, 907 | DLL_PROCESS_DETACH = 0 908 | } 909 | 910 | class Win 911 | { 912 | public const ushort IMAGE_DOS_SIGNATURE = 0x5A4D; 913 | public const uint IMAGE_NT_SIGNATURE = 0x00004550; 914 | public const uint IMAGE_FILE_MACHINE_I386 = 0x014c; 915 | public const uint IMAGE_FILE_MACHINE_AMD64 = 0x8664; 916 | public const uint PAGE_NOCACHE = 0x200; 917 | public const uint IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040; 918 | public const uint IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080; 919 | public const uint IMAGE_SCN_MEM_DISCARDABLE = 0x02000000; 920 | public const uint IMAGE_SCN_MEM_NOT_CACHED = 0x04000000; 921 | public const uint IMAGE_FILE_DLL = 0x2000; 922 | 923 | [DllImport("kernel32.dll", SetLastError = true)] 924 | public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect); 925 | 926 | [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] 927 | public static extern IntPtr MemSet(IntPtr dest, int c, UIntPtr count); 928 | 929 | [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] 930 | public static extern IntPtr LoadLibrary(IntPtr lpFileName); 931 | 932 | [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 933 | public static extern IntPtr GetProcAddress(IntPtr hModule, IntPtr procName); 934 | 935 | [DllImport("kernel32.dll", SetLastError = true)] 936 | public static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, AllocationType dwFreeType); 937 | 938 | [DllImport("kernel32.dll", SetLastError = true)] 939 | public static extern bool VirtualProtect(IntPtr lpAddress, IntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 940 | 941 | [DllImport("kernel32.dll", SetLastError = true)] 942 | public static extern bool FreeLibrary(IntPtr hModule); 943 | 944 | [DllImport("kernel32.dll", SetLastError = true)] 945 | public static extern void GetNativeSystemInfo(out SYSTEM_INFO lpSystemInfo); 946 | 947 | // Equivalent to the IMAGE_FIRST_SECTION macro 948 | public static IntPtr IMAGE_FIRST_SECTION(IntPtr pNTHeader, ushort ntheader_FileHeader_SizeOfOptionalHeader) 949 | { 950 | return PtrAdd(pNTHeader, Of.IMAGE_NT_HEADERS_OptionalHeader + (int)ntheader_FileHeader_SizeOfOptionalHeader); 951 | } 952 | 953 | // Equivalent to the IMAGE_FIRST_SECTION macro 954 | public static int IMAGE_FIRST_SECTION(int lfanew, ushort ntheader_FileHeader_SizeOfOptionalHeader) 955 | { 956 | return lfanew + Of.IMAGE_NT_HEADERS_OptionalHeader + ntheader_FileHeader_SizeOfOptionalHeader; 957 | } 958 | 959 | // Equivalent to the IMAGE_ORDINAL32/64 macros 960 | public static IntPtr IMAGE_ORDINAL(IntPtr ordinal) 961 | { 962 | return (IntPtr)(int)(unchecked((ulong)ordinal.ToInt64()) & 0xffff); 963 | } 964 | 965 | // Equivalent to the IMAGE_SNAP_BY_ORDINAL32/64 macro 966 | public static bool IMAGE_SNAP_BY_ORDINAL(IntPtr ordinal) 967 | { 968 | return (IntPtr.Size == 8 ? (ordinal.ToInt64() < 0) : (ordinal.ToInt32() < 0)); 969 | } 970 | } 971 | 972 | static T PtrRead(IntPtr ptr) { return (T)Marshal.PtrToStructure(ptr, typeof(T)); } 973 | static void PtrWrite(IntPtr ptr, T val) { Marshal.StructureToPtr(val, ptr, false); } 974 | static IntPtr PtrAdd(IntPtr p, int v) { return (IntPtr)(p.ToInt64() + v); } 975 | static IntPtr PtrAdd(IntPtr p, uint v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() + unchecked((long)v)) : (IntPtr)(p.ToInt32() + unchecked((int)v))); } 976 | static IntPtr PtrAdd(IntPtr p, IntPtr v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() + v.ToInt64()) : (IntPtr)(p.ToInt32() + v.ToInt32())); } 977 | static IntPtr PtrAdd(IntPtr p, UIntPtr v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() + unchecked((long)v.ToUInt64())) : (IntPtr)(p.ToInt32() + unchecked((int)v.ToUInt32()))); } 978 | static IntPtr PtrSub(IntPtr p, IntPtr v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() - v.ToInt64()) : (IntPtr)(p.ToInt32() - v.ToInt32())); } 979 | static IntPtr PtrBitOr(IntPtr p, UIntPtr v) { return (IntPtr.Size == 8 ? (IntPtr)unchecked((long)(unchecked((ulong)p.ToInt64()) | v.ToUInt64())) : (IntPtr)unchecked((int)(unchecked((uint)p.ToInt32()) | v.ToUInt32()))); } 980 | static IntPtr PtrAlignDown(IntPtr p, UIntPtr align) { return (IntPtr)unchecked((long)(unchecked((ulong)p.ToInt64()) & ~(align.ToUInt64() - 1))); } 981 | static bool PtrIsInvalidHandle(IntPtr h) { return (h == IntPtr.Zero || h == (IntPtr.Size == 8 ? (IntPtr)(long)-1 : (IntPtr)(int)-1)); } 982 | static bool PtrSpanBoundary(IntPtr p, uint Size, int BoundaryBits) { return ((unchecked((ulong)p.ToInt64()) >> BoundaryBits) < ((unchecked((ulong)(p.ToInt64())) + Size) >> BoundaryBits)); } 983 | 984 | static T BytesReadStructAt(byte[] buf, int offset) 985 | { 986 | int size = Marshal.SizeOf(typeof(T)); 987 | IntPtr ptr = Marshal.AllocHGlobal(size); 988 | Marshal.Copy(buf, offset, ptr, size); 989 | T res = (T)Marshal.PtrToStructure(ptr, typeof(T)); 990 | Marshal.FreeHGlobal(ptr); 991 | return res; 992 | } 993 | } --------------------------------------------------------------------------------