├── .gitignore ├── TestDLL ├── .gitignore ├── main.cpp ├── TestDLL.sln └── TestDLL.vcxproj ├── README.md ├── Sample.sln ├── Sample.csproj ├── Sample.cs ├── LICENSE.txt └── DLLFromMemory.cs /.gitignore: -------------------------------------------------------------------------------- 1 | Debug/ 2 | Release/ 3 | obj/ 4 | .vs/ 5 | *.suo 6 | *.user 7 | -------------------------------------------------------------------------------- /TestDLL/.gitignore: -------------------------------------------------------------------------------- 1 | Debug/ 2 | Release/ 3 | .vs/ 4 | *.sdf 5 | *.opensdf 6 | *.user 7 | *.suo 8 | *.aps 9 | *.ipch 10 | -------------------------------------------------------------------------------- /TestDLL/main.cpp: -------------------------------------------------------------------------------- 1 | extern "C" __declspec(dllexport) int __cdecl Add(int a, int b) 2 | { 3 | return a + b; 4 | } 5 | 6 | extern "C" __declspec(dllexport) void __cdecl CallCallback(void (__cdecl callback)(int number), int number) 7 | { 8 | callback(number); 9 | } 10 | 11 | extern "C" long __stdcall DllMain(void* hDllHandle, long dwReason, void* lpreserved) 12 | { 13 | return 1; 14 | } 15 | -------------------------------------------------------------------------------- /TestDLL/TestDLL.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}") = "TestDLL", "TestDLL.vcxproj", "{FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Debug|x64 = Debug|x64 12 | Release|Win32 = Release|Win32 13 | Release|x64 = Release|x64 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|Win32.ActiveCfg = Debug|Win32 17 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|Win32.Build.0 = Debug|Win32 18 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|x64.ActiveCfg = Debug|x64 19 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|x64.Build.0 = Debug|x64 20 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release|Win32.ActiveCfg = Release|Win32 21 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release|Win32.Build.0 = Release|Win32 22 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release|x64.ActiveCfg = Release|x64 23 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release|x64.Build.0 = Release|x64 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DLLFromMemory.Net 2 | A C# library to load a native DLL from memory without the need to allow unsafe code. 3 | 4 | By default C# can load external libraries only via files on the filesystem. 5 | A common workaround for this problem is to write the DLL into a temporary file first and import it from there. 6 | This library can be used to load a DLL completely from memory - without storing on the disk first. 7 | 8 | It supports both 32bit and 64bit processes/DLLs, as well as AnyCPU builds. 9 | For AnyCPU, both 32bit and 64bit DLLs must be available in memory (see [Sample](Sample.cs)) 10 | 11 | ## Example 12 | ```C# 13 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int AddDelegate(int a, int b); 14 | 15 | static void RunAdd(byte[] dllBytes) 16 | { 17 | DLLFromMemory dll = new DLLFromMemory(dllBytes); 18 | 19 | AddDelegate addFunc = dll.GetDelegateFromFuncName("Add"); 20 | Console.WriteLine("Calling add(1, 2): " + addFunc(1, 2) + "\n"); 21 | 22 | dll.Close(); 23 | } 24 | ``` 25 | 26 | ## Contributions 27 | DLLFromMemory.Net is based on Memory Module.net 0.2 28 | Copyright (C) 2012 - 2018 by Andreas Kanzler 29 | https://github.com/Scavanger/MemoryModule.net 30 | 31 | Memory Module.net is based on Memory DLL loading code Version 0.0.4 32 | Copyright (C) 2004 - 2015 by Joachim Bauch 33 | https://github.com/fancycode/MemoryModule 34 | 35 | ## License 36 | DLLFromMemory.Net is available under the [MPL 2.0](https://www.mozilla.org/en-US/MPL/2.0/). 37 | -------------------------------------------------------------------------------- /Sample.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}") = "Sample", "Sample.csproj", "{FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|x64 = Debug|x64 12 | Debug|x86 = Debug|x86 13 | Release35|Any CPU = Release35|Any CPU 14 | Release35|x64 = Release35|x64 15 | Release35|x86 = Release35|x86 16 | Release45|Any CPU = Release45|Any CPU 17 | Release45|x64 = Release45|x64 18 | Release45|x86 = Release45|x86 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|x64.ActiveCfg = Debug|x64 24 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|x64.Build.0 = Debug|x64 25 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|x86.ActiveCfg = Debug|x86 26 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Debug|x86.Build.0 = Debug|x86 27 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release35|Any CPU.ActiveCfg = Release35|Any CPU 28 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release35|Any CPU.Build.0 = Release35|Any CPU 29 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release35|x64.ActiveCfg = Release35|x64 30 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release35|x64.Build.0 = Release35|x64 31 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release35|x86.ActiveCfg = Release35|x86 32 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release35|x86.Build.0 = Release35|x86 33 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release45|Any CPU.ActiveCfg = Release45|Any CPU 34 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release45|Any CPU.Build.0 = Release45|Any CPU 35 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release45|x64.ActiveCfg = Release45|x64 36 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release45|x64.Build.0 = Release45|x64 37 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release45|x86.ActiveCfg = Release45|x86 38 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF}.Release45|x86.Build.0 = Release45|x86 39 | EndGlobalSection 40 | GlobalSection(SolutionProperties) = preSolution 41 | HideSolutionNode = FALSE 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | x64 7 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF} 8 | Exe 9 | Sample 10 | Sample 11 | 512 12 | false 13 | false 14 | true 15 | 0 16 | 1.0.0.%2a 17 | false 18 | false 19 | false 20 | 4 21 | false 22 | 23 | 24 | Debug\45_32bit\ 25 | x86 26 | 27 | 28 | Debug\45_64bit\ 29 | x64 30 | 31 | 32 | Debug\45_AnyCPU\ 33 | AnyCPU 34 | false 35 | 36 | 37 | Release\35_32bit\ 38 | x86 39 | 40 | 41 | Release\35_64bit\ 42 | x64 43 | 44 | 45 | Release\35_AnyCPU\ 46 | AnyCPU 47 | false 48 | 49 | 50 | Release\45_32bit\ 51 | x86 52 | 53 | 54 | Release\45_64bit\ 55 | x64 56 | 57 | 58 | Release\45_AnyCPU\ 59 | AnyCPU 60 | false 61 | 62 | 63 | v4.5 64 | true 65 | full 66 | false 67 | $(OutputPath) 68 | DEBUG;TRACE;DOTNET45;TARGET$(PlatformTarget) 69 | true 70 | 71 | 72 | v3.5 73 | v4.5 74 | $(OutputPath) 75 | pdbonly 76 | true 77 | DOTNET35;TARGET$(PlatformTarget) 78 | DOTNET45;TARGET$(PlatformTarget) 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /TestDLL/TestDLL.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | TestDLL 23 | {FFFFFFFF-FFFF-4FFF-FFFF-FFFFFFFFFFFF} 24 | 25 | 26 | 27 | DynamicLibrary 28 | v110_xp 29 | v120_xp 30 | v140 31 | v141 32 | v142 33 | false 34 | MultiByte 35 | true 36 | true 37 | 38 | 39 | 40 | 41 | 42 | 43 | $(Configuration)\64bit\ 44 | $(Configuration)\32bit\ 45 | $(OutDir) 46 | $(OutDir) 47 | $(OutDir) 48 | false 49 | true 50 | false 51 | 52 | 53 | 54 | false 55 | Level3 56 | true 57 | false 58 | false 59 | WIN32;_WINDOWS;%(PreprocessorDefinitions) 60 | _HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) 61 | _DEBUG;%(PreprocessorDefinitions) 62 | NDEBUG;%(PreprocessorDefinitions) 63 | WIN64;_WIN64;%(PreprocessorDefinitions) 64 | 65 | 66 | Disabled 67 | Default 68 | MultiThreadedDebug 69 | 70 | 71 | Full 72 | true 73 | true 74 | MultiThreaded 75 | true 76 | true 77 | true 78 | Speed 79 | true 80 | AnySuitable 81 | false 82 | StreamingSIMDExtensions2 83 | /Gw %(AdditionalOptions) 84 | 85 | 86 | true 87 | true 88 | Console 89 | false 90 | true 91 | DllMain 92 | 93 | 94 | true 95 | true 96 | UseLinkTimeCodeGeneration 97 | true 98 | false 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /Sample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | [assembly: System.Reflection.AssemblyTitle("Sample")] 4 | [assembly: System.Reflection.AssemblyProduct("Sample")] 5 | [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] 6 | [assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")] 7 | [assembly: ComVisible(false)] 8 | 9 | static class Sample 10 | { 11 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int AddDelegate(int a, int b); 12 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void CallbackDelegate(int number); 13 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void CallCallbackDelegate(CallbackDelegate callback, int number); 14 | 15 | static int Main(string[] args) 16 | { 17 | Console.WriteLine("Process is " + (DLLFromMemory.Is64BitProcess ? "64" : "32") + "bit\n"); 18 | 19 | DLLFromMemory dll = new DLLFromMemory(GetSampleDLLBytes()); 20 | 21 | AddDelegate addFunc = dll.GetDelegateFromFuncName("Add"); 22 | Console.WriteLine("Calling add(1, 2): " + addFunc(1, 2) + "\n"); 23 | 24 | CallCallbackDelegate callCallbackFunc = dll.GetDelegateFromFuncName("CallCallback"); 25 | Console.WriteLine("Calling callCallback(TestCallback, 777)..."); 26 | callCallbackFunc(TestCallback, 777); 27 | Console.WriteLine("Done!\n"); 28 | 29 | dll.Close(); 30 | return 0; 31 | } 32 | 33 | static void TestCallback(int number) 34 | { 35 | Console.WriteLine(" In callback with number: " + number); 36 | } 37 | 38 | static byte[] GetSampleDLLBytes() 39 | { 40 | byte[] buf; 41 | System.IO.Compression.DeflateStream ds; 42 | if (DLLFromMemory.Is64BitProcess) 43 | { 44 | buf = new byte[2048]; //decompress the 409 bytes below into this 2048 byte buffer (original dll file size) 45 | ds = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(new byte[409] { 46 | 0xE5, 0x94, 0x33, 0xBC, 0xDE, 0x50, 0x1C, 0x40, 0x4F, 0xF0, 0xAC, 0x6A, 0xEF, 0xBF, 0x9C, 0x6A, 0xB7, 0x4B, 0x6D, 0x5B, 0x4F, 0xC1, 0x7D, 0xFC, 0x14, 0xD4, 0x5C, 0x6A, 0xAE, 0xC5, 0xBE, 0xD6, 47 | 0x9C, 0x6A, 0x77, 0x9F, 0x8A, 0x7D, 0x29, 0xB7, 0xF2, 0x73, 0xED, 0x6E, 0x39, 0xBF, 0x9C, 0x5C, 0xE6, 0x3A, 0x77, 0xEE, 0xAA, 0xC3, 0x18, 0x80, 0x09, 0x7C, 0xF8, 0x00, 0x17, 0xC9, 0x31, 0x81, 48 | 0x5F, 0x73, 0x07, 0xA8, 0xED, 0x79, 0xB9, 0x96, 0xB3, 0x15, 0x0F, 0x7B, 0x5D, 0xD4, 0xE6, 0x3C, 0xEC, 0xB5, 0xA4, 0xAD, 0x3D, 0x90, 0x94, 0x9F, 0x6C, 0xF5, 0xAD, 0xB8, 0x38, 0x56, 0x22, 0x91, 49 | 0x0C, 0xC5, 0x56, 0xE2, 0xAF, 0x49, 0x48, 0x7B, 0x42, 0xA6, 0xCC, 0x5F, 0x2C, 0xF1, 0xA4, 0xAB, 0x06, 0xD5, 0xD4, 0x54, 0xF6, 0x25, 0xC7, 0xEC, 0xD8, 0xFB, 0xC7, 0x75, 0x35, 0x87, 0x0F, 0x14, 50 | 0xF4, 0xC3, 0x35, 0x07, 0x6A, 0xB3, 0xE1, 0x9C, 0x7C, 0x38, 0x2F, 0x1B, 0x2E, 0x6A, 0x77, 0xDA, 0x32, 0xE5, 0xFC, 0x80, 0x05, 0x53, 0xC1, 0xDD, 0xA9, 0xD3, 0xE5, 0xF5, 0xB4, 0x06, 0xF2, 0x3C, 51 | 0xA7, 0xB7, 0x54, 0xE9, 0xD5, 0xA0, 0x93, 0x13, 0x90, 0x2E, 0x40, 0x5A, 0x60, 0xBB, 0x46, 0x3E, 0xAE, 0x43, 0x49, 0xAE, 0x42, 0x31, 0x64, 0x08, 0x60, 0x02, 0x80, 0x41, 0xB3, 0x96, 0xAB, 0x48, 52 | 0x31, 0xF8, 0x36, 0x9D, 0x8B, 0x4E, 0x10, 0x58, 0xC9, 0x1F, 0x20, 0x30, 0x86, 0xFF, 0xC7, 0xA0, 0x50, 0xAD, 0x0F, 0x81, 0xFE, 0xC5, 0xB9, 0x01, 0xE6, 0x37, 0x5D, 0x36, 0x0F, 0xF2, 0x5D, 0x2B, 53 | 0xB4, 0xA0, 0x8B, 0x06, 0x48, 0xBE, 0x5E, 0x29, 0x5F, 0x30, 0x21, 0xFB, 0x44, 0x80, 0x08, 0x73, 0xC0, 0xEC, 0x7A, 0xFD, 0xC1, 0x67, 0xCC, 0xD8, 0x77, 0x75, 0xDF, 0xBD, 0x19, 0x1F, 0x9E, 0x16, 54 | 0xD2, 0x17, 0x35, 0xE0, 0x3A, 0x11, 0x20, 0xB2, 0x14, 0xEF, 0x4C, 0x1D, 0x68, 0x04, 0x8E, 0x4B, 0xDA, 0xD2, 0x2F, 0xCB, 0xAA, 0x81, 0x1E, 0xC0, 0x5B, 0x49, 0x5B, 0xFA, 0xFD, 0xEF, 0x37, 0x0B, 55 | 0x68, 0x80, 0x9E, 0xB7, 0x4D, 0x20, 0x25, 0xB0, 0x5E, 0x80, 0x2E, 0xD0, 0x25, 0xED, 0x6E, 0x81, 0xFD, 0x02, 0xA0, 0xB1, 0x44, 0x05, 0xE1, 0x94, 0x39, 0x73, 0x06, 0xB9, 0xB1, 0x18, 0x13, 0x5D, 56 | 0x97, 0xC9, 0x56, 0x2C, 0x96, 0xD1, 0xB6, 0x9C, 0x4E, 0x80, 0x45, 0x8B, 0xA7, 0x2C, 0x36, 0xFC, 0x77, 0x6B, 0x67, 0x4F, 0xDD, 0x3E, 0xF5, 0xA8, 0xB9, 0xBB, 0x2A, 0x3C, 0x75, 0x72, 0x8F, 0x06, 57 | 0x4C, 0x19, 0x57, 0xEF, 0xAA, 0xB5, 0xF5, 0x73, 0x37, 0x2C, 0xF0, 0x93, 0x1D, 0xCA, 0x09, 0x83, 0xFA, 0x74, 0x2B, 0xD3, 0xFC, 0x64, 0x7C, 0xAE, 0x8A, 0x27, 0xFD, 0x0D, 0x03, 0x13, 0x2A, 0xAC, 58 | 0xCF, 0xB7, 0x5D, 0xBF, 0x48, 0xC5, 0x94, 0x15, 0xA8, 0xFA, 0x51, 0x23, 0xEC, 0xF6, 0x62, 0xEE, 0xA0, 0x94, 0x6B, 0x93, 0x43, 0x23, 0xDA, 0x7C, 0x04 59 | }, false), System.IO.Compression.CompressionMode.Decompress, false); 60 | } 61 | else 62 | { 63 | buf = new byte[2048]; //decompress the 417 bytes below into this 2048 byte buffer (original dll file size) 64 | ds = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(new byte[417] { 65 | 0xED, 0xD4, 0x03, 0x8C, 0x1C, 0x01, 0x14, 0x80, 0xE1, 0x7F, 0x70, 0x36, 0x62, 0xF4, 0x5D, 0x52, 0xDB, 0x0A, 0x6A, 0xDB, 0x3A, 0x8D, 0x8E, 0xAB, 0xCC, 0xD6, 0x6E, 0x50, 0x2B, 0xD6, 0xC5, 0x4E, 66 | 0x6A, 0xDB, 0x46, 0x9C, 0x5A, 0xB1, 0x59, 0x1B, 0x83, 0xDA, 0x6D, 0x50, 0x7C, 0x0F, 0x63, 0x63, 0xC4, 0xD4, 0xF5, 0x68, 0x80, 0x0E, 0xBC, 0x7C, 0x09, 0x7B, 0xF0, 0xF5, 0xE6, 0xDB, 0xCE, 0x00, 67 | 0xB9, 0x8D, 0xF6, 0xE5, 0xB2, 0x23, 0xE3, 0x62, 0xC9, 0x1E, 0x65, 0xF8, 0xC5, 0x92, 0xF1, 0x35, 0xB5, 0x49, 0x49, 0xB8, 0xF1, 0x6A, 0xD7, 0x88, 0x8A, 0x65, 0xC4, 0x62, 0xF1, 0xE9, 0x62, 0x3A, 68 | 0xE2, 0xCE, 0x88, 0x49, 0x6D, 0x4C, 0xFA, 0x8F, 0x1A, 0x27, 0xD1, 0xB8, 0xED, 0xB4, 0xCD, 0xC9, 0xC9, 0x6C, 0x8C, 0x6F, 0x58, 0xE4, 0xC5, 0xAD, 0xBC, 0x9C, 0xF5, 0x6B, 0xC2, 0x72, 0xA7, 0xCF, 69 | 0x58, 0x93, 0xEB, 0x0D, 0x87, 0x07, 0xC3, 0x91, 0xDE, 0x70, 0x6C, 0xAD, 0x55, 0xF3, 0x66, 0x39, 0x5F, 0x30, 0x7A, 0x00, 0x0C, 0x57, 0x54, 0xF2, 0xEF, 0x0D, 0x2C, 0x23, 0x70, 0x07, 0xB5, 0x24, 70 | 0x4B, 0xC9, 0x06, 0x15, 0xBF, 0x00, 0xC9, 0x07, 0xDE, 0x94, 0x80, 0x37, 0x96, 0xEF, 0x2F, 0x4B, 0x41, 0x01, 0xDE, 0x0D, 0x69, 0x0F, 0xE8, 0x78, 0x34, 0x7A, 0x2B, 0x90, 0xEF, 0xE5, 0xBB, 0xA1, 71 | 0x3F, 0xE8, 0x2D, 0x30, 0x85, 0x1F, 0x20, 0xD0, 0x9D, 0xDF, 0xA7, 0xED, 0x74, 0x67, 0xF6, 0x74, 0xA0, 0x39, 0x10, 0x5E, 0x0B, 0x3A, 0x1F, 0x10, 0xA8, 0x6C, 0xEB, 0xDA, 0xC6, 0x74, 0x03, 0xF2, 72 | 0x15, 0x40, 0x82, 0xF5, 0x52, 0xF9, 0x40, 0x6F, 0x2F, 0xFF, 0xFB, 0x97, 0xAC, 0xEA, 0xDF, 0x58, 0xD7, 0xFA, 0x37, 0x4E, 0x3F, 0x7E, 0xC1, 0xF7, 0x72, 0x7A, 0xE3, 0xF4, 0x97, 0xE3, 0x1B, 0xA7, 73 | 0x4F, 0x09, 0x66, 0xEC, 0x51, 0x80, 0x63, 0xD9, 0xFC, 0xF7, 0xF7, 0x0A, 0xFF, 0x99, 0x2A, 0x50, 0x0E, 0x34, 0x08, 0x34, 0xA4, 0x7E, 0xB8, 0x2C, 0x1B, 0x28, 0x06, 0x9E, 0x09, 0x3C, 0x4B, 0xFD, 74 | 0xFC, 0xF6, 0xF3, 0x05, 0x14, 0x40, 0x0D, 0xAA, 0x46, 0x20, 0x21, 0x30, 0x5B, 0x82, 0xDF, 0x66, 0x3E, 0x2C, 0x17, 0x58, 0x2D, 0x00, 0x0A, 0xE3, 0x9D, 0xE4, 0xF4, 0xFE, 0xC3, 0x87, 0xB7, 0xB5, 75 | 0x23, 0x11, 0xFA, 0xD8, 0x36, 0xFD, 0x8C, 0x48, 0xE4, 0x4D, 0x99, 0x86, 0x55, 0x0F, 0x30, 0x76, 0x5C, 0xFF, 0x71, 0x37, 0xEE, 0x2F, 0xD9, 0x3A, 0xB7, 0xA0, 0x45, 0xBF, 0x65, 0x1B, 0x9F, 0x1F, 76 | 0x6A, 0x77, 0xF9, 0x49, 0xA5, 0x02, 0xF4, 0xEF, 0x59, 0x6A, 0x3B, 0x33, 0x4B, 0x47, 0xCC, 0x19, 0xED, 0xC6, 0xEB, 0x1C, 0x6B, 0x7A, 0xB2, 0xF4, 0xF5, 0x5E, 0x06, 0xBA, 0xF1, 0xE8, 0x08, 0x27, 77 | 0x1A, 0x77, 0xE7, 0xB4, 0x89, 0x39, 0xD3, 0x4B, 0x83, 0x7D, 0x97, 0x8E, 0x75, 0x22, 0x8E, 0x91, 0x74, 0x4A, 0x3B, 0x75, 0x34, 0x6B, 0xDF, 0xCE, 0x6D, 0x9B, 0xB0, 0x4D, 0x7C, 0x0A, 0xFF, 0xB6, 0x57 78 | }, false), System.IO.Compression.CompressionMode.Decompress, false); 79 | } 80 | ds.Read(buf, 0, buf.Length); 81 | ds.Dispose(); 82 | return buf; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /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 | 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)] struct IMAGE_DOS_HEADER 621 | { 622 | public ushort e_magic; // Magic number 623 | public ushort e_cblp; // Bytes on last page of file 624 | public ushort e_cp; // Pages in file 625 | public ushort e_crlc; // Relocations 626 | public ushort e_cparhdr; // Size of header in paragraphs 627 | public ushort e_minalloc; // Minimum extra paragraphs needed 628 | public ushort e_maxalloc; // Maximum extra paragraphs needed 629 | public ushort e_ss; // Initial (relative) SS value 630 | public ushort e_sp; // Initial SP value 631 | public ushort e_csum; // Checksum 632 | public ushort e_ip; // Initial IP value 633 | public ushort e_cs; // Initial (relative) CS value 634 | public ushort e_lfarlc; // File address of relocation table 635 | public ushort e_ovno; // Overlay number 636 | public ushort e_res1a,e_res1b,e_res1c,e_res1d; // Reserved words 637 | public ushort e_oemid; // OEM identifier (for e_oeminfo) 638 | public ushort e_oeminfo; // OEM information; e_oemid specific 639 | public ushort e_res2a,e_res2b,e_res2c,e_res2d,e_res2e,e_res2f,e_res2g,e_res2h,e_res2i,e_res2j; // Reserved words 640 | public int e_lfanew; // File address of new exe header 641 | } 642 | 643 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_NT_HEADERS 644 | { 645 | public uint Signature; 646 | public IMAGE_FILE_HEADER FileHeader; 647 | public IMAGE_OPTIONAL_HEADER OptionalHeader; 648 | } 649 | 650 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_FILE_HEADER 651 | { 652 | public ushort Machine; 653 | public ushort NumberOfSections; 654 | public uint TimeDateStamp; 655 | public uint PointerToSymbolTable; 656 | public uint NumberOfSymbols; 657 | public ushort SizeOfOptionalHeader; 658 | public ushort Characteristics; 659 | } 660 | 661 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_OPTIONAL_HEADER 662 | { 663 | public MagicType Magic; 664 | public byte MajorLinkerVersion; 665 | public byte MinorLinkerVersion; 666 | public uint SizeOfCode; 667 | public uint SizeOfInitializedData; 668 | public uint SizeOfUninitializedData; 669 | public uint AddressOfEntryPoint; 670 | public uint BaseOfCode; 671 | public ulong ImageBaseLong; 672 | public uint SectionAlignment; 673 | public uint FileAlignment; 674 | public ushort MajorOperatingSystemVersion; 675 | public ushort MinorOperatingSystemVersion; 676 | public ushort MajorImageVersion; 677 | public ushort MinorImageVersion; 678 | public ushort MajorSubsystemVersion; 679 | public ushort MinorSubsystemVersion; 680 | public uint Win32VersionValue; 681 | public uint SizeOfImage; 682 | public uint SizeOfHeaders; 683 | public uint CheckSum; 684 | public SubSystemType Subsystem; 685 | public DllCharacteristicsType DllCharacteristics; 686 | public IntPtr SizeOfStackReserve; 687 | public IntPtr SizeOfStackCommit; 688 | public IntPtr SizeOfHeapReserve; 689 | public IntPtr SizeOfHeapCommit; 690 | public uint LoaderFlags; 691 | public uint NumberOfRvaAndSizes; 692 | public IMAGE_DATA_DIRECTORY ExportTable; 693 | public IMAGE_DATA_DIRECTORY ImportTable; 694 | public IMAGE_DATA_DIRECTORY ResourceTable; 695 | public IMAGE_DATA_DIRECTORY ExceptionTable; 696 | public IMAGE_DATA_DIRECTORY CertificateTable; 697 | public IMAGE_DATA_DIRECTORY BaseRelocationTable; 698 | public IMAGE_DATA_DIRECTORY Debug; 699 | public IMAGE_DATA_DIRECTORY Architecture; 700 | public IMAGE_DATA_DIRECTORY GlobalPtr; 701 | public IMAGE_DATA_DIRECTORY TLSTable; 702 | public IMAGE_DATA_DIRECTORY LoadConfigTable; 703 | public IMAGE_DATA_DIRECTORY BoundImport; 704 | public IMAGE_DATA_DIRECTORY IAT; 705 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor; 706 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader; 707 | public IMAGE_DATA_DIRECTORY Reserved; 708 | } 709 | 710 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_DATA_DIRECTORY 711 | { 712 | public uint VirtualAddress; 713 | public uint Size; 714 | } 715 | 716 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_SECTION_HEADER 717 | { 718 | public ulong Name; //8 byte string 719 | public uint PhysicalAddress; 720 | public uint VirtualAddress; 721 | public uint SizeOfRawData; 722 | public uint PointerToRawData; 723 | public uint PointerToRelocations; 724 | public uint PointerToLinenumbers; 725 | public ushort NumberOfRelocations; 726 | public ushort NumberOfLinenumbers; 727 | public uint Characteristics; 728 | } 729 | 730 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_BASE_RELOCATION 731 | { 732 | public uint VirtualAdress; 733 | public uint SizeOfBlock; 734 | } 735 | 736 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_IMPORT_DESCRIPTOR 737 | { 738 | public uint OriginalFirstThunk; 739 | public uint TimeDateStamp; 740 | public uint ForwarderChain; 741 | public uint Name; 742 | public uint FirstThunk; 743 | } 744 | 745 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_EXPORT_DIRECTORY 746 | { 747 | public uint Characteristics; 748 | public uint TimeDateStamp; 749 | public ushort MajorVersion; 750 | public ushort MinorVersion; 751 | public uint Name; 752 | public uint Base; 753 | public uint NumberOfFunctions; 754 | public uint NumberOfNames; 755 | public uint AddressOfFunctions; // RVA from base of image 756 | public uint AddressOfNames; // RVA from base of image 757 | public uint AddressOfNameOrdinals; // RVA from base of image 758 | } 759 | 760 | [StructLayout(LayoutKind.Sequential)] struct SYSTEM_INFO 761 | { 762 | public ushort wProcessorArchitecture; 763 | public ushort wReserved; 764 | public uint dwPageSize; 765 | public IntPtr lpMinimumApplicationAddress; 766 | public IntPtr lpMaximumApplicationAddress; 767 | public IntPtr dwActiveProcessorMask; 768 | public uint dwNumberOfProcessors; 769 | public uint dwProcessorType; 770 | public uint dwAllocationGranularity; 771 | public ushort wProcessorLevel; 772 | public ushort wProcessorRevision; 773 | }; 774 | 775 | [StructLayout(LayoutKind.Sequential)] struct IMAGE_TLS_DIRECTORY 776 | { 777 | public IntPtr StartAddressOfRawData; 778 | public IntPtr EndAddressOfRawData; 779 | public IntPtr AddressOfIndex; 780 | public IntPtr AddressOfCallBacks; 781 | public IntPtr SizeOfZeroFill; 782 | public uint Characteristics; 783 | } 784 | 785 | enum MagicType : ushort 786 | { 787 | IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b, 788 | IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b 789 | } 790 | 791 | enum SubSystemType : ushort 792 | { 793 | IMAGE_SUBSYSTEM_UNKNOWN = 0, 794 | IMAGE_SUBSYSTEM_NATIVE = 1, 795 | IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, 796 | IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, 797 | IMAGE_SUBSYSTEM_POSIX_CUI = 7, 798 | IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, 799 | IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, 800 | IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, 801 | IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, 802 | IMAGE_SUBSYSTEM_EFI_ROM = 13, 803 | IMAGE_SUBSYSTEM_XBOX = 14 804 | } 805 | 806 | enum DllCharacteristicsType : ushort 807 | { 808 | RES_0 = 0x0001, 809 | RES_1 = 0x0002, 810 | RES_2 = 0x0004, 811 | RES_3 = 0x0008, 812 | IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040, 813 | IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080, 814 | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100, 815 | IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200, 816 | IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400, 817 | IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800, 818 | RES_4 = 0x1000, 819 | IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000, 820 | IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000 821 | } 822 | 823 | enum BasedRelocationType 824 | { 825 | IMAGE_REL_BASED_ABSOLUTE = 0, 826 | IMAGE_REL_BASED_HIGH = 1, 827 | IMAGE_REL_BASED_LOW = 2, 828 | IMAGE_REL_BASED_HIGHLOW = 3, 829 | IMAGE_REL_BASED_HIGHADJ = 4, 830 | IMAGE_REL_BASED_MIPS_JMPADDR = 5, 831 | IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, 832 | IMAGE_REL_BASED_IA64_IMM64 = 9, 833 | IMAGE_REL_BASED_DIR64 = 10 834 | } 835 | 836 | enum AllocationType : uint 837 | { 838 | COMMIT = 0x1000, 839 | RESERVE = 0x2000, 840 | RESET = 0x80000, 841 | LARGE_PAGES = 0x20000000, 842 | PHYSICAL = 0x400000, 843 | TOP_DOWN = 0x100000, 844 | WRITE_WATCH = 0x200000, 845 | DECOMMIT = 0x4000, 846 | RELEASE = 0x8000 847 | } 848 | 849 | enum MemoryProtection : uint 850 | { 851 | EXECUTE = 0x10, 852 | EXECUTE_READ = 0x20, 853 | EXECUTE_READWRITE = 0x40, 854 | EXECUTE_WRITECOPY = 0x80, 855 | NOACCESS = 0x01, 856 | READONLY = 0x02, 857 | READWRITE = 0x04, 858 | WRITECOPY = 0x08, 859 | GUARD_Modifierflag = 0x100, 860 | NOCACHE_Modifierflag = 0x200, 861 | WRITECOMBINE_Modifierflag = 0x400 862 | } 863 | 864 | enum PageProtection 865 | { 866 | NOACCESS = 0x01, 867 | READONLY = 0x02, 868 | READWRITE = 0x04, 869 | WRITECOPY = 0x08, 870 | EXECUTE = 0x10, 871 | EXECUTE_READ = 0x20, 872 | EXECUTE_READWRITE = 0x40, 873 | EXECUTE_WRITECOPY = 0x80, 874 | GUARD = 0x100, 875 | NOCACHE = 0x200, 876 | WRITECOMBINE = 0x400, 877 | } 878 | 879 | enum ImageSectionFlags : uint 880 | { 881 | IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000, // Section contains extended relocations. 882 | IMAGE_SCN_MEM_DISCARDABLE = 0x02000000, // Section can be discarded. 883 | IMAGE_SCN_MEM_NOT_CACHED = 0x04000000, // Section is not cachable. 884 | IMAGE_SCN_MEM_NOT_PAGED = 0x08000000, // Section is not pageable. 885 | IMAGE_SCN_MEM_SHARED = 0x10000000, // Section is shareable. 886 | IMAGE_SCN_MEM_EXECUTE = 0x20000000, // Section is executable. 887 | IMAGE_SCN_MEM_READ = 0x40000000, // Section is readable. 888 | IMAGE_SCN_MEM_WRITE = 0x80000000 // Section is writeable. 889 | } 890 | 891 | enum DllReason : uint 892 | { 893 | DLL_PROCESS_ATTACH = 1, 894 | DLL_THREAD_ATTACH = 2, 895 | DLL_THREAD_DETACH = 3, 896 | DLL_PROCESS_DETACH = 0 897 | } 898 | 899 | class Win 900 | { 901 | public const ushort IMAGE_DOS_SIGNATURE = 0x5A4D; 902 | public const uint IMAGE_NT_SIGNATURE = 0x00004550; 903 | public const uint IMAGE_FILE_MACHINE_I386 = 0x014c; 904 | public const uint IMAGE_FILE_MACHINE_AMD64 = 0x8664; 905 | public const uint PAGE_NOCACHE = 0x200; 906 | public const uint IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040; 907 | public const uint IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080; 908 | public const uint IMAGE_SCN_MEM_DISCARDABLE = 0x02000000; 909 | public const uint IMAGE_SCN_MEM_NOT_CACHED = 0x04000000; 910 | public const uint IMAGE_FILE_DLL = 0x2000; 911 | 912 | [DllImport("kernel32.dll", SetLastError = true)] 913 | public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect); 914 | 915 | [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] 916 | public static extern IntPtr MemSet(IntPtr dest, int c, UIntPtr count); 917 | 918 | [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] 919 | public static extern IntPtr LoadLibrary(IntPtr lpFileName); 920 | 921 | [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 922 | public static extern IntPtr GetProcAddress(IntPtr hModule, IntPtr procName); 923 | 924 | [DllImport("kernel32.dll", SetLastError = true)] 925 | public static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, AllocationType dwFreeType); 926 | 927 | [DllImport("kernel32.dll", SetLastError = true)] 928 | public static extern bool VirtualProtect(IntPtr lpAddress, IntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 929 | 930 | [DllImport("kernel32.dll", SetLastError = true)] 931 | public static extern bool FreeLibrary(IntPtr hModule); 932 | 933 | [DllImport("kernel32.dll", SetLastError = true)] 934 | public static extern void GetNativeSystemInfo(out SYSTEM_INFO lpSystemInfo); 935 | 936 | // Equivalent to the IMAGE_FIRST_SECTION macro 937 | public static IntPtr IMAGE_FIRST_SECTION(IntPtr pNTHeader, ushort ntheader_FileHeader_SizeOfOptionalHeader) 938 | { 939 | return PtrAdd(pNTHeader, Of.IMAGE_NT_HEADERS_OptionalHeader + (int)ntheader_FileHeader_SizeOfOptionalHeader); 940 | } 941 | 942 | // Equivalent to the IMAGE_FIRST_SECTION macro 943 | public static int IMAGE_FIRST_SECTION(int lfanew, ushort ntheader_FileHeader_SizeOfOptionalHeader) 944 | { 945 | return lfanew + Of.IMAGE_NT_HEADERS_OptionalHeader + ntheader_FileHeader_SizeOfOptionalHeader; 946 | } 947 | 948 | // Equivalent to the IMAGE_ORDINAL32/64 macros 949 | public static IntPtr IMAGE_ORDINAL(IntPtr ordinal) 950 | { 951 | return (IntPtr)(int)(unchecked((ulong)ordinal.ToInt64()) & 0xffff); 952 | } 953 | 954 | // Equivalent to the IMAGE_SNAP_BY_ORDINAL32/64 macro 955 | public static bool IMAGE_SNAP_BY_ORDINAL(IntPtr ordinal) 956 | { 957 | return (IntPtr.Size == 8 ? (ordinal.ToInt64() < 0) : (ordinal.ToInt32() < 0)); 958 | } 959 | } 960 | 961 | static T PtrRead(IntPtr ptr) { return (T)Marshal.PtrToStructure(ptr, typeof(T)); } 962 | static void PtrWrite(IntPtr ptr, T val) { Marshal.StructureToPtr(val, ptr, false); } 963 | static IntPtr PtrAdd(IntPtr p, int v) { return (IntPtr)(p.ToInt64() + v); } 964 | static IntPtr PtrAdd(IntPtr p, uint v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() + unchecked((long)v)) : (IntPtr)(p.ToInt32() + unchecked((int)v))); } 965 | static IntPtr PtrAdd(IntPtr p, IntPtr v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() + v.ToInt64()) : (IntPtr)(p.ToInt32() + v.ToInt32())); } 966 | 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()))); } 967 | static IntPtr PtrSub(IntPtr p, IntPtr v) { return (IntPtr.Size == 8 ? (IntPtr)(p.ToInt64() - v.ToInt64()) : (IntPtr)(p.ToInt32() - v.ToInt32())); } 968 | 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()))); } 969 | static IntPtr PtrAlignDown(IntPtr p, UIntPtr align) { return (IntPtr)unchecked((long)(unchecked((ulong)p.ToInt64()) & ~(align.ToUInt64() - 1))); } 970 | static bool PtrIsInvalidHandle(IntPtr h) { return (h == IntPtr.Zero || h == (IntPtr.Size == 8 ? (IntPtr)(long)-1 : (IntPtr)(int)-1)); } 971 | static bool PtrSpanBoundary(IntPtr p, uint Size, int BoundaryBits) { return ((unchecked((ulong)p.ToInt64()) >> BoundaryBits) < ((unchecked((ulong)(p.ToInt64())) + Size) >> BoundaryBits)); } 972 | 973 | static T BytesReadStructAt(byte[] buf, int offset) 974 | { 975 | int size = Marshal.SizeOf(typeof(T)); 976 | IntPtr ptr = Marshal.AllocHGlobal(size); 977 | Marshal.Copy(buf, offset, ptr, size); 978 | T res = (T)Marshal.PtrToStructure(ptr, typeof(T)); 979 | Marshal.FreeHGlobal(ptr); 980 | return res; 981 | } 982 | } 983 | --------------------------------------------------------------------------------