├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── assets └── git │ ├── Git-branching-model.pdf │ └── gitflow.png ├── build └── vs │ ├── MemorySharp.sln │ └── nuget.config ├── src └── MemorySharp │ ├── Assembly │ ├── Assembler │ │ ├── Fasm32Assembler.cs │ │ └── IAssembler.cs │ ├── AssemblyFactory.cs │ ├── AssemblyTransaction.cs │ └── CallingConvention │ │ ├── CallingConventionSelector.cs │ │ ├── CdeclCallingConvention.cs │ │ ├── Enumerations.cs │ │ ├── FastcallCallingConvention.cs │ │ ├── ICallingConvention.cs │ │ ├── StdcallCallingConvention.cs │ │ └── ThiscallCallingConvention.cs │ ├── Helpers │ ├── ApplicationFinder.cs │ ├── HandleManipulator.cs │ ├── Randomizer.cs │ ├── SerializationHelper.cs │ └── Singleton.cs │ ├── Internals │ ├── IApplicableElement.cs │ ├── IDisposableState.cs │ ├── IFactory.cs │ ├── IMarshalledValue.cs │ ├── INamedElement.cs │ ├── Manager.cs │ ├── MarshalType.cs │ └── MarshalValue.cs │ ├── Memory │ ├── LocalUnmanagedMemory.cs │ ├── MemoryCore.cs │ ├── MemoryFactory.cs │ ├── MemoryProtection.cs │ ├── RemoteAllocation.cs │ ├── RemotePointer.cs │ └── RemoteRegion.cs │ ├── MemorySharp.cs │ ├── MemorySharp.csproj │ ├── MemorySharp.licenseheader │ ├── Modules │ ├── InjectedModule.cs │ ├── ModuleCore.cs │ ├── ModuleFactory.cs │ ├── RemoteFunction.cs │ └── RemoteModule.cs │ ├── Native │ ├── Enumerations.cs │ ├── ManagedPeb.cs │ ├── ManagedTeb.cs │ ├── NativeMethods.cs │ ├── SafeMemoryHandle.cs │ └── Structures.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── Threading │ ├── Enumerations.cs │ ├── FrozenThread.cs │ ├── RemoteThread.cs │ ├── ThreadCore.cs │ └── ThreadFactory.cs │ ├── Windows │ ├── Keyboard │ │ ├── BaseKeyboard.cs │ │ └── MessageKeyboard.cs │ ├── Mouse │ │ ├── BaseMouse.cs │ │ └── SendInputMouse.cs │ ├── RemoteWindow.cs │ ├── WindowCore.cs │ └── WindowFactory.cs │ └── packages.config └── test └── IntegrationTests ├── Assembly └── AssemblyFactoryTests.cs ├── Helpers ├── ApplicationFinderTests.cs ├── HandleManipulatorTests.cs └── SingletonTests.cs ├── IntegrationTests.csproj ├── Internals ├── MarshalTypeTests.cs └── MarshalValueTests.cs ├── Memory ├── LocalUnmanagedMemoryTests.cs ├── MemoryCoreTests.cs ├── MemoryFactoryTests.cs ├── RemotePointerTests.cs └── RemoteRegionTests.cs ├── MemorySharp.licenseheader ├── MemorySharpTests.cs ├── Modules ├── ModuleCoreTests.cs ├── ModuleFactoryTests.cs └── RemoteModuleTests.cs ├── Properties └── AssemblyInfo.cs ├── README.md ├── Resources.cs ├── Threading ├── RemoteThreadTests.cs ├── ThreadCoreTests.cs └── ThreadFactoryTests.cs └── Windows ├── KeyboardTests.cs ├── RemoteWindowTests.cs ├── WindowCoreTests.cs └── WindowsFactoryTests.cs /.gitignore: -------------------------------------------------------------------------------- 1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 2 | [Bb]in/ 3 | [Oo]bj/ 4 | 5 | # mstest test/results 6 | MemorySharpTests/bin/ 7 | MemorySharpDirtyTests 8 | TestResults 9 | 10 | # Useless extensions 11 | *.zip 12 | *.rar 13 | 14 | ## Ignore Visual Studio temporary files, build results, and 15 | ## files generated by popular Visual Studio add-ons. 16 | 17 | # User-specific files 18 | *.suo 19 | *.user 20 | *.sln.docstates 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | *_i.c 25 | *_p.c 26 | *.ilk 27 | *.meta 28 | *.obj 29 | *.pch 30 | *.pgc 31 | *.pgd 32 | *.rsp 33 | *.sbr 34 | *.tlb 35 | *.tli 36 | *.tlh 37 | *.tmp 38 | *.log 39 | *.vspscc 40 | *.vssscc 41 | .builds 42 | 43 | # Visual C++ cache files 44 | ipch/ 45 | *.aps 46 | *.ncb 47 | *.opensdf 48 | *.sdf 49 | 50 | # Visual Studio profiler 51 | *.psess 52 | *.vsp 53 | *.vspx 54 | 55 | # Guidance Automation Toolkit 56 | *.gpState 57 | 58 | # ReSharper is a .NET coding add-in 59 | _ReSharper* 60 | 61 | # NCrunch 62 | *.ncrunch* 63 | .*crunch*.local.xml 64 | 65 | # Installshield output folder 66 | [Ee]xpress 67 | 68 | # DocProject is a documentation generator add-in 69 | DocProject/buildhelp/ 70 | DocProject/Help/*.HxT 71 | DocProject/Help/*.HxC 72 | DocProject/Help/*.hhc 73 | DocProject/Help/*.hhk 74 | DocProject/Help/*.hhp 75 | DocProject/Help/Html2 76 | DocProject/Help/html 77 | 78 | # Click-Once directory 79 | publish 80 | 81 | # Publish Web Output 82 | *.Publish.xml 83 | 84 | # NuGet Packages Directory 85 | packages 86 | 87 | # Windows Azure Build Output 88 | csx 89 | *.build.csdef 90 | 91 | # Windows Store app package directory 92 | AppPackages/ 93 | 94 | # Others 95 | [Oo]bj 96 | sql 97 | TestResults 98 | [Tt]est[Rr]esult* 99 | *.Cache 100 | ClientBin 101 | [Ss]tyle[Cc]op.* 102 | ~$* 103 | *.dbmdl 104 | Generated_Code #added for RIA/Silverlight projects 105 | 106 | # Backup & report files from converting an old project file to a newer 107 | # Visual Studio version. Backup files are not needed, because we have git ;-) 108 | _UpgradeReport_Files/ 109 | Backup*/ 110 | UpgradeLog*.XML 111 | 112 | # GhostDoc is a documentation generator add-in 113 | *.GhostDoc.xml -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # MemorySharp Library Changelog 2 | 3 | The log of changes made to MemorySharp Library. 4 | 5 | ## V1.2 (21 September 2016) 6 | 7 | Enhancements: 8 | 9 | - Rewrite the read operations for arrays to have much better performance. 10 | - Rewrite the write operations for arrays to have much better performance. 11 | - Heavily improve the performance of write operations when a relative address is provided (the main module of the remote process is now cached). 12 | 13 | Bugfixes: 14 | 15 | - Properly read strings without a \0 delimiter instead of throwing an ArgumentOutOfRangeException. 16 | 17 | ## V1.1.1 (05 September 2016) 18 | 19 | Bugfixes: 20 | 21 | - Threads created using the library are properly returned by the API. 22 | 23 | ## V1.1 (25 March 2014) 24 | 25 | Bugfixes: 26 | 27 | - The method `SendInputMouse.ReleaseLeft()`, properly releases the left click of the mouse. 28 | 29 | ## V1.0 (10 July 2013) 30 | 31 | - Initial Release -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (C) 2012-2013 Jämes Ménétrey (a.k.a. ZenLulz) 4 | 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining 7 | a copy of this software and associated documentation files (the 8 | "Software"), to deal in the Software without restriction, including 9 | without limitation the rights to use, copy, modify, merge, publish, 10 | distribute, sublicense, and/or sell copies of the Software, and to 11 | permit persons to whom the Software is furnished to do so, subject to 12 | the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 20 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 21 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 22 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /assets/git/Git-branching-model.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesMenetrey/MemorySharp/f563acd274962efe3b1836ac1a67c6f42cf47071/assets/git/Git-branching-model.pdf -------------------------------------------------------------------------------- /assets/git/gitflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesMenetrey/MemorySharp/f563acd274962efe3b1836ac1a67c6f42cf47071/assets/git/gitflow.png -------------------------------------------------------------------------------- /build/vs/MemorySharp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.24720.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MemorySharp", "..\..\src\MemorySharp\MemorySharp.csproj", "{78A6F97D-5CA8-4E92-8E17-2545983C9555}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntegrationTests", "..\..\test\IntegrationTests\IntegrationTests.csproj", "{E3EFE942-113F-46AA-9CF4-A51473D9E8B8}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{84C4DD62-B81F-4116-A853-29A21EE74A99}" 11 | ProjectSection(SolutionItems) = preProject 12 | ..\..\.gitignore = ..\..\.gitignore 13 | ..\..\CHANGELOG.md = ..\..\CHANGELOG.md 14 | ..\..\LICENSE = ..\..\LICENSE 15 | ..\..\README.md = ..\..\README.md 16 | EndProjectSection 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8CE5378B-EF17-465D-AB2E-1394ECA7BB7E}" 19 | EndProject 20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{93385C92-5674-4822-9665-7F2541826856}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Debug|Mixed Platforms = Debug|Mixed Platforms 26 | Debug|Win32 = Debug|Win32 27 | Debug|x64 = Debug|x64 28 | Release|Any CPU = Release|Any CPU 29 | Release|Mixed Platforms = Release|Mixed Platforms 30 | Release|Win32 = Release|Win32 31 | Release|x64 = Release|x64 32 | EndGlobalSection 33 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 34 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU 37 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU 38 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|Win32.ActiveCfg = Debug|Any CPU 39 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|x64.ActiveCfg = Debug|x64 40 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Debug|x64.Build.0 = Debug|x64 41 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU 44 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|Mixed Platforms.Build.0 = Release|Any CPU 45 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|Win32.ActiveCfg = Release|Any CPU 46 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|x64.ActiveCfg = Release|x64 47 | {78A6F97D-5CA8-4E92-8E17-2545983C9555}.Release|x64.Build.0 = Release|x64 48 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU 51 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU 52 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Debug|Win32.ActiveCfg = Debug|Any CPU 53 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Debug|x64.ActiveCfg = Debug|Any CPU 54 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Release|Any CPU.Build.0 = Release|Any CPU 56 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU 57 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Release|Mixed Platforms.Build.0 = Release|Any CPU 58 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Release|Win32.ActiveCfg = Release|Any CPU 59 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8}.Release|x64.ActiveCfg = Release|Any CPU 60 | EndGlobalSection 61 | GlobalSection(SolutionProperties) = preSolution 62 | HideSolutionNode = FALSE 63 | EndGlobalSection 64 | GlobalSection(NestedProjects) = preSolution 65 | {78A6F97D-5CA8-4E92-8E17-2545983C9555} = {8CE5378B-EF17-465D-AB2E-1394ECA7BB7E} 66 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8} = {93385C92-5674-4822-9665-7F2541826856} 67 | EndGlobalSection 68 | EndGlobal 69 | -------------------------------------------------------------------------------- /build/vs/nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/Assembler/Fasm32Assembler.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using Binarysharp.Assemblers.Fasm; 10 | using System; 11 | 12 | namespace Binarysharp.MemoryManagement.Assembly.Assembler 13 | { 14 | /// 15 | /// Implement Fasm.NET compiler for 32-bit development. 16 | /// More info: https://github.com/ZenLulz/Fasm.NET 17 | /// 18 | public class Fasm32Assembler : IAssembler 19 | { 20 | /// 21 | /// Assemble the specified assembly code. 22 | /// 23 | /// The assembly code. 24 | /// An array of bytes containing the assembly code. 25 | public byte[] Assemble(string asm) 26 | { 27 | // Assemble and return the code 28 | return Assemble(asm, IntPtr.Zero); 29 | } 30 | 31 | /// 32 | /// Assemble the specified assembly code at a base address. 33 | /// 34 | /// The assembly code. 35 | /// The address where the code is rebased. 36 | /// An array of bytes containing the assembly code. 37 | public byte[] Assemble(string asm, IntPtr baseAddress) 38 | { 39 | // Rebase the code 40 | asm = String.Format("use32\norg 0x{0:X8}\n", baseAddress.ToInt64()) + asm; 41 | // Assemble and return the code 42 | return FasmNet.Assemble(asm); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/Assembler/IAssembler.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | 11 | namespace Binarysharp.MemoryManagement.Assembly.Assembler 12 | { 13 | /// 14 | /// Interface defining an assembler. 15 | /// 16 | public interface IAssembler 17 | { 18 | /// 19 | /// Assemble the specified assembly code. 20 | /// 21 | /// The assembly code. 22 | /// An array of bytes containing the assembly code. 23 | byte[] Assemble(string asm); 24 | /// 25 | /// Assemble the specified assembly code at a base address. 26 | /// 27 | /// The assembly code. 28 | /// The address where the code is rebased. 29 | /// An array of bytes containing the assembly code. 30 | byte[] Assemble(string asm, IntPtr baseAddress); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/AssemblyTransaction.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Text; 11 | using Binarysharp.MemoryManagement.Internals; 12 | 13 | namespace Binarysharp.MemoryManagement.Assembly 14 | { 15 | /// 16 | /// Class representing a transaction where the user can insert mnemonics. 17 | /// The code is then executed when the object is disposed. 18 | /// 19 | public class AssemblyTransaction : IDisposable 20 | { 21 | #region Fields 22 | /// 23 | /// The reference of the object. 24 | /// 25 | protected readonly MemorySharp MemorySharp; 26 | /// 27 | /// The builder contains all the mnemonics inserted by the user. 28 | /// 29 | protected StringBuilder Mnemonics; 30 | /// 31 | /// The exit code of the thread created to execute the assembly code. 32 | /// 33 | protected IntPtr ExitCode; 34 | #endregion 35 | 36 | #region Properties 37 | #region Address 38 | /// 39 | /// The address where to assembly code is assembled. 40 | /// 41 | public IntPtr Address { get; private set; } 42 | #endregion 43 | #region IsAutoExecuted 44 | /// 45 | /// Gets the value indicating whether the assembly code is executed once the object is disposed. 46 | /// 47 | public bool IsAutoExecuted { get; set; } 48 | #endregion 49 | #endregion 50 | 51 | #region Constructors 52 | /// 53 | /// Initializes a new instance of the class. 54 | /// 55 | /// The reference of the object. 56 | /// The address where the assembly code is injected. 57 | /// Indicates whether the assembly code is executed once the object is disposed. 58 | public AssemblyTransaction(MemorySharp memorySharp, IntPtr address, bool autoExecute) 59 | { 60 | // Save the parameters 61 | MemorySharp = memorySharp; 62 | IsAutoExecuted = autoExecute; 63 | Address = address; 64 | // Initialize the string builder 65 | Mnemonics = new StringBuilder(); 66 | } 67 | /// 68 | /// Initializes a new instance of the class. 69 | /// 70 | /// The reference of the object. 71 | /// Indicates whether the assembly code is executed once the object is disposed. 72 | public AssemblyTransaction(MemorySharp memorySharp, bool autoExecute) : this(memorySharp, IntPtr.Zero, autoExecute) 73 | { 74 | } 75 | #endregion 76 | 77 | #region Methods 78 | #region AddLine 79 | /// 80 | /// Adds a mnemonic to the transaction. 81 | /// 82 | /// A composite format string. 83 | /// An object array that contains zero or more objects to format. 84 | public void AddLine(string asm, params object[] args) 85 | { 86 | Mnemonics.AppendLine(String.Format(asm, args)); 87 | } 88 | #endregion 89 | #region Assemble 90 | /// 91 | /// Assemble the assembly code of this transaction. 92 | /// 93 | /// An array of bytes containing the assembly code. 94 | public byte[] Assemble() 95 | { 96 | return MemorySharp.Assembly.Assembler.Assemble(Mnemonics.ToString()); 97 | } 98 | #endregion 99 | #region Clear 100 | /// 101 | /// Removes all mnemonics from the transaction. 102 | /// 103 | public void Clear() 104 | { 105 | Mnemonics.Clear(); 106 | } 107 | #endregion 108 | #region Dispose (implementation of IDisposable) 109 | /// 110 | /// Releases all resources used by the object. 111 | /// 112 | public virtual void Dispose() 113 | { 114 | // If a pointer was specified 115 | if (Address != IntPtr.Zero) 116 | { 117 | // If the assembly code must be executed 118 | if (IsAutoExecuted) 119 | { 120 | ExitCode = MemorySharp.Assembly.InjectAndExecute(Mnemonics.ToString(), Address); 121 | } 122 | // Else the assembly code is just injected 123 | else 124 | { 125 | MemorySharp.Assembly.Inject(Mnemonics.ToString(), Address); 126 | } 127 | } 128 | 129 | // If no pointer was specified and the code assembly code must be executed 130 | if (Address == IntPtr.Zero && IsAutoExecuted) 131 | { 132 | ExitCode = MemorySharp.Assembly.InjectAndExecute(Mnemonics.ToString()); 133 | } 134 | } 135 | #endregion 136 | #region GetExitCode 137 | /// 138 | /// Gets the termination status of the thread. 139 | /// 140 | public T GetExitCode() 141 | { 142 | return MarshalType.PtrToObject(MemorySharp, ExitCode); 143 | } 144 | #endregion 145 | #region InsertLine 146 | /// 147 | /// Inserts a mnemonic to the transaction at a given index. 148 | /// 149 | /// The position in the transaction where insertion begins. 150 | /// A composite format string. 151 | /// An object array that contains zero or more objects to format. 152 | public void InsertLine(int index, string asm, params object[] args) 153 | { 154 | Mnemonics.Insert(index, String.Format(asm, args)); 155 | } 156 | #endregion 157 | #endregion 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/CallingConventionSelector.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Helpers; 11 | 12 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 13 | { 14 | /// 15 | /// Static class providing calling convention instances. 16 | /// 17 | public static class CallingConventionSelector 18 | { 19 | /// 20 | /// Gets a calling convention object according the given type. 21 | /// 22 | /// The type of calling convention to get. 23 | /// The return value is a singleton of a child. 24 | public static ICallingConvention Get(CallingConventions callingConvention) 25 | { 26 | switch (callingConvention) 27 | { 28 | case CallingConventions.Cdecl: 29 | return Singleton.Instance; 30 | case CallingConventions.Stdcall: 31 | return Singleton.Instance; 32 | case CallingConventions.Fastcall: 33 | return Singleton.Instance; 34 | case CallingConventions.Thiscall: 35 | return Singleton.Instance; 36 | default: 37 | throw new ApplicationException("Unsupported calling convention."); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/CdeclCallingConvention.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using System.Text; 12 | 13 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 14 | { 15 | /// 16 | /// Define the C Declaration Calling Convention. 17 | /// 18 | public class CdeclCallingConvention : ICallingConvention 19 | { 20 | /// 21 | /// The name of the calling convention. 22 | /// 23 | public string Name 24 | { 25 | get { return "Cdecl"; } 26 | } 27 | /// 28 | /// Defines which function performs the clean-up task. 29 | /// 30 | public CleanupTypes Cleanup 31 | { 32 | get { return CleanupTypes.Caller; } 33 | } 34 | /// 35 | /// Formats the given parameters to call a function. 36 | /// 37 | /// An array of parameters. 38 | /// The mnemonics to pass the parameters. 39 | public string FormatParameters(IntPtr[] parameters) 40 | { 41 | // Declare a var to store the mnemonics 42 | var ret = new StringBuilder(); 43 | // For each parameters (in reverse order) 44 | foreach (var parameter in parameters.Reverse()) 45 | { 46 | ret.AppendLine("push " + parameter); 47 | } 48 | // Return the mnemonics 49 | return ret.ToString(); 50 | } 51 | /// 52 | /// Formats the call of a given function. 53 | /// 54 | /// The function to call. 55 | /// The mnemonics to call the function. 56 | public string FormatCalling(IntPtr function) 57 | { 58 | return "call " + function; 59 | } 60 | /// 61 | /// Formats the cleaning of a given number of parameters. 62 | /// 63 | /// The number of parameters to clean. 64 | /// The mnemonics to clean a given number of parameters. 65 | public string FormatCleaning(int nbParameters) 66 | { 67 | return "add esp, " + nbParameters * 4; 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/Enumerations.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 10 | { 11 | /// 12 | /// A list of calling conventions. 13 | /// 14 | public enum CallingConventions 15 | { 16 | /// 17 | /// Name : C Declaration Calling Convention 18 | /// Clean-up : Caller 19 | /// Parameters : Passed on the stack in reverse order 20 | /// Ret. value : Returned in the EAX register 21 | /// Notes : Widely used by the compiler GCC 22 | /// 23 | Cdecl, 24 | /// 25 | /// Name : Standard Calling Convention 26 | /// Clean-up : Callee 27 | /// Parameters : Passed on the stack in reverse order 28 | /// Ret. value : Returned in the EAX register 29 | /// Notes : Convention created by Microsoft, used in the Win32 API 30 | /// 31 | Stdcall, 32 | /// 33 | /// Name : Fast Calling Convention (aka __msfastcall) 34 | /// Clean-up : Callee 35 | /// Parameters : The first two parameters are placed in the ECX and EDX registers respectively. 36 | /// Any remaining parameters are placed on the stack in reverse order. 37 | /// Ret. Value : Returned in the EAX register 38 | /// Notes : A variation of the stdcall convention 39 | /// 40 | Fastcall, 41 | /// 42 | /// Name : This Calling Convention 43 | /// Clean-up : Callee 44 | /// Parameters : The 'this' pointer is placed in the ECX register. 45 | /// Parameters are placed on the stack in reverse order. 46 | /// Ret. Value : Returned in the EAX register 47 | /// Notes : Used for object-oriented programming by Microsoft Visual C++ 48 | /// 49 | Thiscall 50 | } 51 | 52 | /// 53 | /// A list of type of clean-up available in calling conventions. 54 | /// 55 | public enum CleanupTypes 56 | { 57 | /// 58 | /// The clean-up task is performed by the called function. 59 | /// 60 | Callee, 61 | /// 62 | /// The clean-up task is performed by the caller function. 63 | /// 64 | Caller 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/FastcallCallingConvention.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Text; 12 | 13 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 14 | { 15 | /// 16 | /// Define the Fast Calling Convention (aka __msfastcall). 17 | /// 18 | public class FastcallCallingConvention : ICallingConvention 19 | { 20 | /// 21 | /// The name of the calling convention. 22 | /// 23 | public string Name 24 | { 25 | get { return "Fastcall"; } 26 | } 27 | /// 28 | /// Defines which function performs the clean-up task. 29 | /// 30 | public CleanupTypes Cleanup 31 | { 32 | get { return CleanupTypes.Callee; } 33 | } 34 | /// 35 | /// Formats the given parameters to call a function. 36 | /// 37 | /// An array of parameters. 38 | /// The mnemonics to pass the parameters. 39 | public string FormatParameters(IntPtr[] parameters) 40 | { 41 | // Declare a var to store the mnemonics 42 | var ret = new StringBuilder(); 43 | var paramList = new List(parameters); 44 | // Store the first parameter in the ECX register 45 | if (paramList.Count > 0) 46 | { 47 | ret.AppendLine("mov ecx, " + paramList[0]); 48 | paramList.RemoveAt(0); 49 | } 50 | // Store the second parameter in the EDX register 51 | if (paramList.Count > 0) 52 | { 53 | ret.AppendLine("mov edx, " + paramList[0]); 54 | paramList.RemoveAt(0); 55 | } 56 | // For each parameters (in reverse order) 57 | paramList.Reverse(); 58 | foreach (var parameter in paramList) 59 | { 60 | ret.AppendLine("push " + parameter); 61 | } 62 | // Return the mnemonics 63 | return ret.ToString(); 64 | } 65 | /// 66 | /// Formats the call of a given function. 67 | /// 68 | /// The function to call. 69 | /// The mnemonics to call the function. 70 | public string FormatCalling(IntPtr function) 71 | { 72 | return "call " + function; 73 | } 74 | /// 75 | /// Formats the cleaning of a given number of parameters. 76 | /// 77 | /// The number of parameters to clean. 78 | /// The mnemonics to clean a given number of parameters. 79 | public string FormatCleaning(int nbParameters) 80 | { 81 | return String.Empty; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/ICallingConvention.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | 11 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 12 | { 13 | /// 14 | /// Interface defining a calling convention. 15 | /// 16 | public interface ICallingConvention 17 | { 18 | /// 19 | /// The name of the calling convention. 20 | /// 21 | string Name { get; } 22 | /// 23 | /// Defines which function performs the clean-up task. 24 | /// 25 | CleanupTypes Cleanup { get; } 26 | /// 27 | /// Formats the given parameters to call a function. 28 | /// 29 | /// An array of parameters. 30 | /// The mnemonics to pass the parameters. 31 | string FormatParameters(IntPtr[] parameters); 32 | /// 33 | /// Formats the call of a given function. 34 | /// 35 | /// The function to call. 36 | /// The mnemonics to call the function. 37 | string FormatCalling(IntPtr function); 38 | /// 39 | /// Formats the cleaning of a given number of parameters. 40 | /// 41 | /// The number of parameters to clean. 42 | /// The mnemonics to clean a given number of parameters. 43 | string FormatCleaning(int nbParameters); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/StdcallCallingConvention.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using System.Text; 12 | 13 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 14 | { 15 | /// 16 | /// Define the Standard Calling Convention. 17 | /// 18 | public class StdcallCallingConvention : ICallingConvention 19 | { 20 | /// 21 | /// The name of the calling convention. 22 | /// 23 | public string Name 24 | { 25 | get { return "Stdcall"; } 26 | } 27 | /// 28 | /// Defines which function performs the clean-up task. 29 | /// 30 | public CleanupTypes Cleanup 31 | { 32 | get { return CleanupTypes.Callee; } 33 | } 34 | /// 35 | /// Formats the given parameters to call a function. 36 | /// 37 | /// An array of parameters. 38 | /// The mnemonics to pass the parameters. 39 | public string FormatParameters(IntPtr[] parameters) 40 | { 41 | // Declare a var to store the mnemonics 42 | var ret = new StringBuilder(); 43 | // For each parameters (in reverse order) 44 | foreach (var parameter in parameters.Reverse()) 45 | { 46 | ret.AppendLine("push " + parameter); 47 | } 48 | // Return the mnemonics 49 | return ret.ToString(); 50 | } 51 | /// 52 | /// Formats the call of a given function. 53 | /// 54 | /// The function to call. 55 | /// The mnemonics to call the function. 56 | public string FormatCalling(IntPtr function) 57 | { 58 | return "call " + function; 59 | } 60 | /// 61 | /// Formats the cleaning of a given number of parameters. 62 | /// 63 | /// The number of parameters to clean. 64 | /// The mnemonics to clean a given number of parameters. 65 | public string FormatCleaning(int nbParameters) 66 | { 67 | return String.Empty; 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/MemorySharp/Assembly/CallingConvention/ThiscallCallingConvention.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Text; 12 | 13 | namespace Binarysharp.MemoryManagement.Assembly.CallingConvention 14 | { 15 | /// 16 | /// Define the 'This' Calling Convention. 17 | /// 18 | public class ThiscallCallingConvention : ICallingConvention 19 | { 20 | /// 21 | /// The name of the calling convention. 22 | /// 23 | public string Name 24 | { 25 | get { return "Stdcall"; } 26 | } 27 | /// 28 | /// Defines which function performs the clean-up task. 29 | /// 30 | public CleanupTypes Cleanup 31 | { 32 | get { return CleanupTypes.Callee; } 33 | } 34 | /// 35 | /// Formats the given parameters to call a function. The 'this' pointer must be passed in first. 36 | /// 37 | /// An array of parameters. 38 | /// The mnemonics to pass the parameters. 39 | public string FormatParameters(IntPtr[] parameters) 40 | { 41 | // Declare a var to store the mnemonics 42 | var ret = new StringBuilder(); 43 | var paramList = new List(parameters); 44 | // Store the 'this' pointer in the ECX register 45 | if (paramList.Count > 0) 46 | { 47 | ret.AppendLine("mov ecx, " + paramList[0]); 48 | paramList.RemoveAt(0); 49 | } 50 | // For each parameters (in reverse order) 51 | paramList.Reverse(); 52 | foreach (var parameter in paramList) 53 | { 54 | ret.AppendLine("push " + parameter); 55 | } 56 | // Return the mnemonics 57 | return ret.ToString(); 58 | } 59 | /// 60 | /// Formats the call of a given function. 61 | /// 62 | /// The function to call. 63 | /// The mnemonics to call the function. 64 | public string FormatCalling(IntPtr function) 65 | { 66 | return "call " + function; 67 | } 68 | /// 69 | /// Formats the cleaning of a given number of parameters. 70 | /// 71 | /// The number of parameters to clean. 72 | /// The mnemonics to clean a given number of parameters. 73 | public string FormatCleaning(int nbParameters) 74 | { 75 | return String.Empty; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/MemorySharp/Helpers/ApplicationFinder.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Diagnostics; 12 | using System.Linq; 13 | using Binarysharp.MemoryManagement.Windows; 14 | 15 | namespace Binarysharp.MemoryManagement.Helpers 16 | { 17 | /// 18 | /// Static helper class providing tools for finding applications. 19 | /// 20 | public static class ApplicationFinder 21 | { 22 | #region Property TopLevelWindows 23 | /// 24 | /// Gets all top-level windows on the screen. 25 | /// 26 | public static IEnumerable TopLevelWindows 27 | { 28 | get { return WindowCore.EnumTopLevelWindows(); } 29 | } 30 | #endregion 31 | 32 | #region Property Windows 33 | /// 34 | /// Gets all the windows on the screen. 35 | /// 36 | public static IEnumerable Windows 37 | { 38 | get { return WindowCore.EnumAllWindows(); } 39 | } 40 | #endregion 41 | 42 | #region FromProcessId 43 | /// 44 | /// Returns a new component, given the identifier of a process. 45 | /// 46 | /// The system-unique identifier of a process resource. 47 | /// A component that is associated with the local process resource identified by the processId parameter. 48 | public static Process FromProcessId(int processId) 49 | { 50 | return Process.GetProcessById(processId); 51 | } 52 | #endregion 53 | 54 | #region FromProcessName 55 | /// 56 | /// Creates an collection of new components and associates them with all the process resources that share the specified process name. 57 | /// 58 | /// The friendly name of the process. 59 | /// A collection of type that represents the process resources running the specified application or file. 60 | public static IEnumerable FromProcessName(string processName) 61 | { 62 | return Process.GetProcessesByName(processName); 63 | } 64 | #endregion 65 | 66 | #region FromWindowClassName 67 | /// 68 | /// Creates a collection of new components and associates them with all the process resources that share the specified class name. 69 | /// 70 | /// The class name string. 71 | /// A collection of type that represents the process resources running the specified application or file. 72 | public static IEnumerable FromWindowClassName(string className) 73 | { 74 | return Windows.Where(window => WindowCore.GetClassName(window) == className).Select(FromWindowHandle); 75 | } 76 | #endregion 77 | 78 | #region FromWindowHandle 79 | /// 80 | /// Retrieves a new component that created the window. 81 | /// 82 | /// A handle to the window. 83 | /// A A component that is associated with the specified window handle. 84 | public static Process FromWindowHandle(IntPtr windowHandle) 85 | { 86 | return FromProcessId(WindowCore.GetWindowProcessId(windowHandle)); 87 | } 88 | #endregion 89 | 90 | #region FromWindowTitle 91 | /// 92 | /// Creates a collection of new components and associates them with all the process resources that share the specified window title. 93 | /// 94 | /// The window title string. 95 | /// A collection of type that represents the process resources running the specified application or file. 96 | public static IEnumerable FromWindowTitle(string windowTitle) 97 | { 98 | return Windows.Where(window => WindowCore.GetWindowText(window) == windowTitle).Select(FromWindowHandle); 99 | } 100 | #endregion 101 | 102 | #region FromWindowTitleContains 103 | /// 104 | /// Creates a collection of new components and associates them with all the process resources that contain the specified window title. 105 | /// 106 | /// A part a window title string. 107 | /// A collection of type that represents the process resources running the specified application or file. 108 | public static IEnumerable FromWindowTitleContains(string windowTitle) 109 | { 110 | return Windows.Where(window => WindowCore.GetWindowText(window).Contains(windowTitle)).Select(FromWindowHandle); 111 | } 112 | #endregion 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/MemorySharp/Helpers/Randomizer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Text; 11 | 12 | namespace Binarysharp.MemoryManagement.Helpers 13 | { 14 | /// 15 | /// Static helper class providing tools for generating random numbers or strings. 16 | /// 17 | public static class Randomizer 18 | { 19 | #region Fields 20 | /// 21 | /// Provides random engine. 22 | /// 23 | private static readonly Random Random = new Random(); 24 | /// 25 | /// Allowed characters in random strings. 26 | /// 27 | private static readonly char[] AllowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray(); 28 | #endregion 29 | 30 | #region GenerateNumber 31 | /// 32 | /// Returns a random number within a specified range. 33 | /// 34 | /// The inclusive lower bound of the random number returned. 35 | /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. 36 | /// A 32-bit signed integer greater than or equal to minValue and less than maxValue. 37 | public static int GenerateNumber(int minValue, int maxValue) 38 | { 39 | return Random.Next(minValue, maxValue); 40 | } 41 | /// 42 | /// Returns a nonnegative random number less than the specified maximum. 43 | /// 44 | /// The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to zero. 45 | /// A 32-bit signed integer greater than or equal to zero, and less than maxValue. 46 | public static int GenerateNumber(int maxValue) 47 | { 48 | return Random.Next(maxValue); 49 | } 50 | /// 51 | /// Returns a nonnegative random number. 52 | /// 53 | /// A 32-bit signed integer greater than or equal to zero and less than . 54 | public static int GenerateNumber() 55 | { 56 | return Random.Next(); 57 | } 58 | #endregion 59 | 60 | #region GenerateString 61 | /// 62 | /// Returns a random string where its size is within a specified range. 63 | /// 64 | /// The inclusive lower bound of the size of the string returned. 65 | /// The exclusive upper bound of the size of the string returned. 66 | /// 67 | public static string GenerateString(int minSize = 40, int maxSize = 40) 68 | { 69 | // Create the string builder with a specific capacity 70 | var builder = new StringBuilder(GenerateNumber(minSize, maxSize)); 71 | 72 | // Fill the string builder 73 | for (var i = 0; i < builder.Capacity; i++) 74 | { 75 | builder.Append(AllowedChars[GenerateNumber(AllowedChars.Length - 1)]); 76 | } 77 | 78 | return builder.ToString(); 79 | } 80 | #endregion 81 | 82 | #region GenerateGuid 83 | /// 84 | /// Initializes a new instance of the structure. 85 | /// 86 | /// A new object. 87 | public static Guid GenerateGuid() 88 | { 89 | return Guid.NewGuid(); 90 | } 91 | #endregion 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/MemorySharp/Helpers/SerializationHelper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.IO; 10 | using System.Text; 11 | using System.Xml.Serialization; 12 | 13 | namespace Binarysharp.MemoryManagement.Helpers 14 | { 15 | /// 16 | /// Static helper class providing tools for serializing/deserializing objects. 17 | /// 18 | public static class SerializationHelper 19 | { 20 | #region ExportToXmlFile 21 | /// 22 | /// Serializes the specified object and writes the XML document to the specified path. 23 | /// 24 | /// The type of the object to serialize. 25 | /// The object to serialize. 26 | /// The path where the file is saved. 27 | /// The encoding to generate. 28 | public static void ExportToXmlFile(T obj, string path, Encoding encoding) 29 | { 30 | // Create the stream to write into the specified file 31 | using (var file = new StreamWriter(path, false, encoding)) 32 | { 33 | // Write the content by calling the method to serialize the object 34 | file.Write(ExportToXmlString(obj)); 35 | } 36 | } 37 | /// 38 | /// Serializes the specified object and writes the XML document to the specified path using encoding. 39 | /// 40 | /// The type of the object to serialize. 41 | /// The object to serialize. 42 | /// The path where the file is saved. 43 | public static void ExportToXmlFile(T obj, string path) 44 | { 45 | ExportToXmlFile(obj, path, Encoding.UTF8); 46 | } 47 | #endregion 48 | 49 | #region ExportToXmlString 50 | /// 51 | /// Serializes the specified object and returns the XML document. 52 | /// 53 | /// The type of the object to serialize. 54 | /// The object to serialize. 55 | /// XML document of the serialized object. 56 | public static string ExportToXmlString(T obj) 57 | { 58 | // Initialize the required objects for serialization 59 | var serializer = new XmlSerializer(typeof(T)); 60 | using (var stringWriter = new StringWriter()) 61 | { 62 | // Serialize the object 63 | serializer.Serialize(stringWriter, obj); 64 | // Return the serialized object 65 | return stringWriter.ToString(); 66 | } 67 | } 68 | #endregion 69 | 70 | #region ImportFromXmlFile 71 | /// 72 | /// Deserializes the specified file into an object. 73 | /// 74 | /// The type of the object to deserialize. 75 | /// The path where the object is read. 76 | /// The character encoding to use. 77 | /// The deserialized object. 78 | public static T ImportFromXmlFile(string path, Encoding encoding) 79 | { 80 | // Create the stream to read the specified file 81 | using (var file = new StreamReader(path, encoding)) 82 | { 83 | // Read the content of the file and call the method to deserialize the object 84 | return ImportFromXmlString(file.ReadToEnd()); 85 | } 86 | } 87 | /// 88 | /// Deserializes the specified file into an object using encoding. 89 | /// 90 | /// The type of the object to deserialize. 91 | /// The path where the object is read. 92 | /// The deserialized object. 93 | public static T ImportFromXmlFile(string path) 94 | { 95 | return ImportFromXmlFile(path, Encoding.UTF8); 96 | } 97 | #endregion 98 | 99 | #region ImportFromXmlString 100 | /// 101 | /// Deserializes the XML document to the specified object. 102 | /// 103 | /// The type of the object to deserialize. 104 | /// The string representing the serialized object. 105 | /// The deserialized object. 106 | public static T ImportFromXmlString(string serializedObj) 107 | { 108 | // Initialize the required objects for deserialization 109 | var serializer = new XmlSerializer(typeof(T)); 110 | using (var stringWriter = new StringReader(serializedObj)) 111 | { 112 | // Return the serialized object 113 | return (T)serializer.Deserialize(stringWriter); 114 | } 115 | } 116 | #endregion 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/MemorySharp/Helpers/Singleton.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | namespace Binarysharp.MemoryManagement.Helpers 10 | { 11 | /// 12 | /// Static helper used to create or get a singleton from another class. 13 | /// 14 | /// The type to create or get a singleton. 15 | public static class Singleton where T : new() 16 | { 17 | /// 18 | /// Gets the singleton of the given type. 19 | /// 20 | public static readonly T Instance = new T(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/MemorySharp/Internals/IApplicableElement.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | namespace Binarysharp.MemoryManagement.Internals 10 | { 11 | /// 12 | /// Defines an element able to be activated in the remote process. 13 | /// 14 | public interface IApplicableElement : IDisposableState 15 | { 16 | /// 17 | /// States if the element is enabled. 18 | /// 19 | bool IsEnabled { get; set; } 20 | /// 21 | /// Disables the element. 22 | /// 23 | void Disable(); 24 | /// 25 | /// Enables the element. 26 | /// 27 | void Enable(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/MemorySharp/Internals/IDisposableState.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | 11 | namespace Binarysharp.MemoryManagement.Internals 12 | { 13 | /// 14 | /// Defines an IDisposable interface with a known state. 15 | /// 16 | public interface IDisposableState : IDisposable 17 | { 18 | /// 19 | /// Gets a value indicating whether the element is disposed. 20 | /// 21 | bool IsDisposed { get; } 22 | /// 23 | /// Gets a value indicating whether the element must be disposed when the Garbage Collector collects the object. 24 | /// 25 | bool MustBeDisposed { get; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/MemorySharp/Internals/IFactory.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | 11 | namespace Binarysharp.MemoryManagement.Internals 12 | { 13 | /// 14 | /// Define a factory for the library. 15 | /// 16 | /// At the moment, the factories are just disposable. 17 | public interface IFactory : IDisposable 18 | { 19 | } 20 | } -------------------------------------------------------------------------------- /src/MemorySharp/Internals/IMarshalledValue.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Memory; 11 | 12 | namespace Binarysharp.MemoryManagement.Internals 13 | { 14 | /// 15 | /// Interface representing a value within the memory of a remote process. 16 | /// 17 | public interface IMarshalledValue : IDisposable 18 | { 19 | /// 20 | /// The memory allocated where the value is fully written if needed. It can be unused. 21 | /// 22 | RemoteAllocation Allocated { get; } 23 | /// 24 | /// The reference of the value. It can be directly the value or a pointer. 25 | /// 26 | IntPtr Reference { get; } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/MemorySharp/Internals/INamedElement.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | namespace Binarysharp.MemoryManagement.Internals 10 | { 11 | /// 12 | /// Defines a element with a name. 13 | /// 14 | public interface INamedElement : IApplicableElement 15 | { 16 | /// 17 | /// The name of the element. 18 | /// 19 | string Name { get; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/MemorySharp/Internals/Manager.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.Collections.Generic; 10 | 11 | namespace Binarysharp.MemoryManagement.Internals 12 | { 13 | /// 14 | /// Class managing objects implementing interface. 15 | /// 16 | public abstract class Manager where T : INamedElement 17 | { 18 | #region Fields 19 | /// 20 | /// The collection of the elements (writable). 21 | /// 22 | protected Dictionary InternalItems = new Dictionary(); 23 | #endregion 24 | 25 | #region Properties 26 | /// 27 | /// The collection of the elements. 28 | /// 29 | public IReadOnlyDictionary Items 30 | { 31 | get { return InternalItems; } 32 | } 33 | #endregion 34 | 35 | #region Methods 36 | #region DisableAll 37 | /// 38 | /// Disables all items in the manager. 39 | /// 40 | public void DisableAll() 41 | { 42 | foreach (var item in InternalItems) 43 | { 44 | item.Value.Disable(); 45 | } 46 | } 47 | #endregion 48 | #region EnableAll 49 | /// 50 | /// Enables all items in the manager. 51 | /// 52 | public void EnableAll() 53 | { 54 | foreach (var item in InternalItems) 55 | { 56 | item.Value.Enable(); 57 | } 58 | } 59 | #endregion 60 | #region Remove 61 | /// 62 | /// Removes an element by its name in the manager. 63 | /// 64 | /// The name of the element to remove. 65 | public void Remove(string name) 66 | { 67 | // Check if the element exists in the dictionary 68 | if (InternalItems.ContainsKey(name)) 69 | { 70 | try 71 | { 72 | // Dispose the element 73 | InternalItems[name].Dispose(); 74 | } 75 | finally 76 | { 77 | // Remove the element from the dictionary 78 | InternalItems.Remove(name); 79 | } 80 | } 81 | } 82 | /// 83 | /// Remove a given element. 84 | /// 85 | /// The element to remove. 86 | public void Remove(T item) 87 | { 88 | Remove(item.Name); 89 | } 90 | #endregion 91 | #region RemoveAll 92 | /// 93 | /// Removes all the elements in the manager. 94 | /// 95 | public void RemoveAll() 96 | { 97 | // For each element 98 | foreach (var item in InternalItems) 99 | { 100 | // Dispose it 101 | item.Value.Dispose(); 102 | } 103 | // Clear the dictionary 104 | InternalItems.Clear(); 105 | } 106 | #endregion 107 | #endregion 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/MemorySharp/Internals/MarshalValue.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Memory; 11 | 12 | namespace Binarysharp.MemoryManagement.Internals 13 | { 14 | /// 15 | /// The factory to create instance of the class. 16 | /// 17 | /// 18 | /// A factory pattern is used because C# 5.0 constructor doesn't support type inference. 19 | /// More info from Eric Lippert here : http://stackoverflow.com/questions/3570167/why-cant-the-c-sharp-constructor-infer-type 20 | /// 21 | public static class MarshalValue 22 | { 23 | /// 24 | /// Marshals a given value into the remote process. 25 | /// 26 | /// The type of the value. It can be a primitive or reference data type. 27 | /// The concerned process. 28 | /// The value to marshal. 29 | /// The return value is an new instance of the class. 30 | public static MarshalledValue Marshal(MemorySharp memorySharp, T value) 31 | { 32 | return new MarshalledValue(memorySharp, value); 33 | } 34 | } 35 | 36 | /// 37 | /// Class marshalling a value into the remote process. 38 | /// 39 | /// The type of the value. It can be a primitive or reference data type. 40 | public class MarshalledValue : IMarshalledValue 41 | { 42 | #region Fields 43 | /// 44 | /// The reference of the object. 45 | /// 46 | protected readonly MemorySharp MemorySharp; 47 | #endregion 48 | 49 | #region Properties 50 | /// 51 | /// The memory allocated where the value is fully written if needed. It can be unused. 52 | /// 53 | public RemoteAllocation Allocated { get; private set; } 54 | /// 55 | /// The reference of the value. It can be directly the value or a pointer. 56 | /// 57 | public IntPtr Reference { get; private set; } 58 | /// 59 | /// The initial value. 60 | /// 61 | public T Value { get; private set; } 62 | #endregion 63 | 64 | #region Constructor/Destructor 65 | /// 66 | /// Initializes a new instance of the class. 67 | /// 68 | /// The reference of the object. 69 | /// The value to marshal. 70 | public MarshalledValue(MemorySharp memorySharp, T value) 71 | { 72 | // Save the parameters 73 | MemorySharp = memorySharp; 74 | Value = value; 75 | // Marshal the value 76 | Marshal(); 77 | } 78 | /// 79 | /// Frees resources and perform other cleanup operations before it is reclaimed by garbage collection. 80 | /// 81 | ~MarshalledValue() 82 | { 83 | Dispose(); 84 | } 85 | #endregion 86 | 87 | #region Methods 88 | #region Dispose (implementation of IDisposable) 89 | /// 90 | /// Releases all resources used by the object. 91 | /// 92 | public void Dispose() 93 | { 94 | // Free the allocated memory 95 | if(Allocated != null) 96 | Allocated.Dispose(); 97 | // Set the pointer to zero 98 | Reference = IntPtr.Zero; 99 | // Avoid the finalizer 100 | GC.SuppressFinalize(this); 101 | } 102 | #endregion 103 | #region Marshal (private) 104 | /// 105 | /// Marshals the value into the remote process. 106 | /// 107 | private void Marshal() 108 | { 109 | // If the type is string, it's a special case 110 | if (typeof(T) == typeof(string)) 111 | { 112 | var text = Value.ToString(); 113 | // Allocate memory in the remote process (string + '\0') 114 | Allocated = MemorySharp.Memory.Allocate(text.Length + 1); 115 | // Write the value 116 | Allocated.WriteString(0, text); 117 | // Get the pointer 118 | Reference = Allocated.BaseAddress; 119 | } 120 | else 121 | { 122 | // For all other types 123 | // Convert the value into a byte array 124 | var byteArray = MarshalType.ObjectToByteArray(Value); 125 | 126 | // If the value can be stored directly in registers 127 | if (MarshalType.CanBeStoredInRegisters) 128 | { 129 | // Convert the byte array into a pointer 130 | Reference = MarshalType.ByteArrayToObject(byteArray); 131 | } 132 | else 133 | { 134 | // It's a bit more complicated, we must allocate some space into 135 | // the remote process to store the value and get its pointer 136 | 137 | // Allocate memory in the remote process 138 | Allocated = MemorySharp.Memory.Allocate(MarshalType.Size); 139 | // Write the value 140 | Allocated.Write(0, Value); 141 | // Get the pointer 142 | Reference = Allocated.BaseAddress; 143 | } 144 | } 145 | } 146 | #endregion 147 | #endregion 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/MemorySharp/Memory/LocalUnmanagedMemory.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Runtime.InteropServices; 11 | 12 | namespace Binarysharp.MemoryManagement.Memory 13 | { 14 | /// 15 | /// Class representing a block of memory allocated in the local process. 16 | /// 17 | public class LocalUnmanagedMemory : IDisposable 18 | { 19 | #region Properties 20 | /// 21 | /// The address where the data is allocated. 22 | /// 23 | public IntPtr Address { get; private set; } 24 | /// 25 | /// The size of the allocated memory. 26 | /// 27 | public int Size { get; private set; } 28 | #endregion 29 | 30 | #region Constructor/Destructor 31 | /// 32 | /// Initializes a new instance of the class, allocating a block of memory in the local process. 33 | /// 34 | /// The size to allocate. 35 | public LocalUnmanagedMemory(int size) 36 | { 37 | // Allocate the memory 38 | Size = size; 39 | Address = Marshal.AllocHGlobal(Size); 40 | } 41 | /// 42 | /// Frees resources and perform other cleanup operations before it is reclaimed by garbage collection. 43 | /// 44 | ~LocalUnmanagedMemory() 45 | { 46 | Dispose(); 47 | } 48 | #endregion 49 | 50 | #region Methods 51 | #region Dispose (implementation of IDisposable) 52 | /// 53 | /// Releases the memory held by the object. 54 | /// 55 | public virtual void Dispose() 56 | { 57 | // Free the allocated memory 58 | Marshal.FreeHGlobal(Address); 59 | // Remove the pointer 60 | Address = IntPtr.Zero; 61 | // Avoid the finalizer 62 | GC.SuppressFinalize(this); 63 | } 64 | #endregion 65 | #region Read 66 | /// 67 | /// Reads data from the unmanaged block of memory. 68 | /// 69 | /// The type of data to return. 70 | /// The return value is the block of memory casted in the specified type. 71 | public T Read() 72 | { 73 | // Marshal data from the block of memory to a new allocated managed object 74 | return (T)Marshal.PtrToStructure(Address, typeof(T)); 75 | } 76 | /// 77 | /// Reads an array of bytes from the unmanaged block of memory. 78 | /// 79 | /// The return value is the block of memory. 80 | public byte[] Read() 81 | { 82 | // Allocate an array to store data 83 | var bytes = new byte[Size]; 84 | // Copy the block of memory to the array 85 | Marshal.Copy(Address, bytes, 0, Size); 86 | // Return the array 87 | return bytes; 88 | } 89 | #endregion 90 | #region ToString (override) 91 | /// 92 | /// Returns a string that represents the current object. 93 | /// 94 | public override string ToString() 95 | { 96 | return string.Format("Size = {0:X}", Size); 97 | } 98 | #endregion 99 | #region Write 100 | /// 101 | /// Writes an array of bytes to the unmanaged block of memory. 102 | /// 103 | /// The array of bytes to write. 104 | /// The start position to copy bytes from. 105 | public void Write(byte[] byteArray, int index = 0) 106 | { 107 | // Copy the array of bytes into the block of memory 108 | Marshal.Copy(byteArray, index, Address, Size); 109 | } 110 | /// 111 | /// Write data to the unmanaged block of memory. 112 | /// 113 | /// The type of data to write. 114 | /// The data to write. 115 | public void Write(T data) 116 | { 117 | // Marshal data from the managed object to the block of memory 118 | Marshal.StructureToPtr(data, Address, false); 119 | } 120 | #endregion 121 | #endregion 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/MemorySharp/Memory/MemoryFactory.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using Binarysharp.MemoryManagement.Internals; 13 | using Binarysharp.MemoryManagement.Native; 14 | 15 | namespace Binarysharp.MemoryManagement.Memory 16 | { 17 | /// 18 | /// Class providing tools for manipulating memory space. 19 | /// 20 | public class MemoryFactory : IFactory 21 | { 22 | #region Fields 23 | /// 24 | /// The reference of the object. 25 | /// 26 | protected readonly MemorySharp MemorySharp; 27 | /// 28 | /// The list containing all allocated memory. 29 | /// 30 | protected readonly List InternalRemoteAllocations; 31 | #endregion 32 | 33 | #region Properties 34 | #region RemoteAllocations 35 | /// 36 | /// A collection containing all allocated memory in the remote process. 37 | /// 38 | public IEnumerable RemoteAllocations 39 | { 40 | get { return InternalRemoteAllocations.AsReadOnly(); } 41 | } 42 | #endregion 43 | #region Regions 44 | /// 45 | /// Gets all blocks of memory allocated in the remote process. 46 | /// 47 | public IEnumerable Regions 48 | { 49 | get 50 | { 51 | #if x64 52 | var adresseTo = new IntPtr(0x7fffffffffffffff); 53 | #else 54 | var adresseTo = new IntPtr(0x7fffffff); 55 | #endif 56 | return MemoryCore.Query(MemorySharp.Handle, IntPtr.Zero, adresseTo).Select(page => new RemoteRegion(MemorySharp, page.BaseAddress)); 57 | } 58 | } 59 | #endregion 60 | #endregion 61 | 62 | #region Constructor/Destructor 63 | /// 64 | /// Initializes a new instance of the class. 65 | /// 66 | /// The reference of the object. 67 | internal MemoryFactory(MemorySharp memorySharp) 68 | { 69 | // Save the parameter 70 | MemorySharp = memorySharp; 71 | // Create a list containing all allocated memory 72 | InternalRemoteAllocations = new List(); 73 | } 74 | /// 75 | /// Frees resources and perform other cleanup operations before it is reclaimed by garbage collection. 76 | /// 77 | ~MemoryFactory() 78 | { 79 | Dispose(); 80 | } 81 | #endregion 82 | 83 | #region Methods 84 | #region Allocate 85 | /// 86 | /// Allocates a region of memory within the virtual address space of the remote process. 87 | /// 88 | /// The size of the memory to allocate. 89 | /// The protection of the memory to allocate. 90 | /// The allocated memory will be released when the finalizer collects the object. 91 | /// A new instance of the class. 92 | public RemoteAllocation Allocate(int size, MemoryProtectionFlags protection = MemoryProtectionFlags.ExecuteReadWrite, bool mustBeDisposed = true) 93 | { 94 | // Allocate a memory space 95 | var memory = new RemoteAllocation(MemorySharp, size, protection, mustBeDisposed); 96 | // Add the memory in the list 97 | InternalRemoteAllocations.Add(memory); 98 | return memory; 99 | } 100 | #endregion 101 | #region Deallocate 102 | /// 103 | /// Deallocates a region of memory previously allocated within the virtual address space of the remote process. 104 | /// 105 | /// The allocated memory to release. 106 | public void Deallocate(RemoteAllocation allocation) 107 | { 108 | // Dispose the element 109 | if(!allocation.IsDisposed) 110 | allocation.Dispose(); 111 | // Remove the element from the allocated memory list 112 | if (InternalRemoteAllocations.Contains(allocation)) 113 | InternalRemoteAllocations.Remove(allocation); 114 | } 115 | #endregion 116 | #region Dispose (implementation of IFactory) 117 | /// 118 | /// Releases all resources used by the object. 119 | /// 120 | public virtual void Dispose() 121 | { 122 | // Release all allocated memories which must be disposed 123 | foreach (var allocatedMemory in InternalRemoteAllocations.Where(m => m.MustBeDisposed).ToArray()) 124 | { 125 | allocatedMemory.Dispose(); 126 | } 127 | // Avoid the finalizer 128 | GC.SuppressFinalize(this); 129 | } 130 | #endregion 131 | #endregion 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/MemorySharp/Memory/MemoryProtection.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Native; 11 | 12 | namespace Binarysharp.MemoryManagement.Memory 13 | { 14 | /// 15 | /// Class providing tools for manipulating memory protection. 16 | /// 17 | public class MemoryProtection : IDisposable 18 | { 19 | #region Fields 20 | /// 21 | /// The reference of the object. 22 | /// 23 | private readonly MemorySharp _memorySharp; 24 | #endregion 25 | 26 | #region Properties 27 | #region BaseAddress 28 | /// 29 | /// The base address of the altered memory. 30 | /// 31 | public IntPtr BaseAddress { get; private set; } 32 | #endregion 33 | #region MustBedisposed 34 | /// 35 | /// States if the object nust be disposed when it is collected. 36 | /// 37 | public bool MustBeDisposed { get; set; } 38 | #endregion 39 | #region NewProtection 40 | /// 41 | /// Defines the new protection applied to the memory. 42 | /// 43 | public MemoryProtectionFlags NewProtection { get; private set; } 44 | #endregion 45 | #region OldProtection 46 | /// 47 | /// References the inital protection of the memory. 48 | /// 49 | public MemoryProtectionFlags OldProtection { get; private set; } 50 | #endregion 51 | #region Size 52 | /// 53 | /// The size of the altered memory. 54 | /// 55 | public int Size { get; private set; } 56 | #endregion 57 | #endregion 58 | 59 | #region Constructor/Destructor 60 | /// 61 | /// Initializes a new instance of the class. 62 | /// 63 | /// The reference of the object. 64 | /// The base address of the memory to change the protection. 65 | /// The size of the memory to change. 66 | /// The new protection to apply. 67 | /// The resource will be automatically disposed when the finalizer collects the object. 68 | public MemoryProtection(MemorySharp memorySharp, IntPtr baseAddress, int size, MemoryProtectionFlags protection = MemoryProtectionFlags.ExecuteReadWrite, 69 | bool mustBeDisposed = true) 70 | { 71 | // Save the parameters 72 | _memorySharp = memorySharp; 73 | BaseAddress = baseAddress; 74 | NewProtection = protection; 75 | Size = size; 76 | MustBeDisposed = mustBeDisposed; 77 | 78 | // Change the memory protection 79 | OldProtection = MemoryCore.ChangeProtection(_memorySharp.Handle, baseAddress, size, protection); 80 | } 81 | /// 82 | /// Frees resources and perform other cleanup operations before it is reclaimed by garbage collection. 83 | /// 84 | ~MemoryProtection() 85 | { 86 | if(MustBeDisposed) 87 | Dispose(); 88 | } 89 | #endregion 90 | 91 | #region Methods 92 | #region Dispose (implementation of IDisposable) 93 | /// 94 | /// Restores the initial protection of the memory. 95 | /// 96 | public virtual void Dispose() 97 | { 98 | // Restore the memory protection 99 | MemoryCore.ChangeProtection(_memorySharp.Handle, BaseAddress, Size, OldProtection); 100 | // Avoid the finalizer 101 | GC.SuppressFinalize(this); 102 | } 103 | #endregion 104 | #region ToString (override) 105 | /// 106 | /// Returns a string that represents the current object. 107 | /// 108 | public override string ToString() 109 | { 110 | return string.Format("BaseAddress = 0x{0:X} NewProtection = {1} OldProtection = {2}", BaseAddress.ToInt64(), 111 | NewProtection, OldProtection); 112 | } 113 | #endregion 114 | #endregion 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/MemorySharp/Memory/RemoteAllocation.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Internals; 11 | using Binarysharp.MemoryManagement.Native; 12 | 13 | namespace Binarysharp.MemoryManagement.Memory 14 | { 15 | /// 16 | /// Class representing an allocated memory in a remote process. 17 | /// 18 | public class RemoteAllocation : RemoteRegion, IDisposableState 19 | { 20 | #region Properties 21 | #region IsDisposed (implementation of IDisposableState) 22 | /// 23 | /// Gets a value indicating whether the element is disposed. 24 | /// 25 | public bool IsDisposed { get; private set; } 26 | #endregion 27 | #region MustBeDisposed (implementation of IDisposableState) 28 | /// 29 | /// Gets a value indicating whether the element must be disposed when the Garbage Collector collects the object. 30 | /// 31 | public bool MustBeDisposed { get; set; } 32 | #endregion 33 | #endregion 34 | 35 | #region Constructor/Destructor 36 | /// 37 | /// Initializes a new instance of the class. 38 | /// 39 | /// The reference of the object. 40 | /// The size of the allocated memory. 41 | /// The protection of the allocated memory. 42 | /// The allocated memory will be released when the finalizer collects the object. 43 | internal RemoteAllocation(MemorySharp memorySharp, int size, MemoryProtectionFlags protection = MemoryProtectionFlags.ExecuteReadWrite, 44 | bool mustBeDisposed = true) 45 | : base(memorySharp, MemoryCore.Allocate(memorySharp.Handle, size, protection)) 46 | { 47 | // Set local vars 48 | MustBeDisposed = mustBeDisposed; 49 | IsDisposed = false; 50 | } 51 | /// 52 | /// Frees resources and perform other cleanup operations before it is reclaimed by garbage collection. 53 | /// 54 | ~RemoteAllocation() 55 | { 56 | if(MustBeDisposed) 57 | Dispose(); 58 | } 59 | #endregion 60 | 61 | #region Methods 62 | #region Dispose (implementation of IDisposableState) 63 | /// 64 | /// Releases all resources used by the object. 65 | /// 66 | /// Don't use the IDisposable pattern because the class is sealed. 67 | public virtual void Dispose() 68 | { 69 | if (!IsDisposed) 70 | { 71 | // Set the flag to true 72 | IsDisposed = true; 73 | // Release the allocated memory 74 | Release(); 75 | // Remove this object from the collection of allocated memory 76 | MemorySharp.Memory.Deallocate(this); 77 | // Remove the pointer 78 | BaseAddress = IntPtr.Zero; 79 | // Avoid the finalizer 80 | GC.SuppressFinalize(this); 81 | } 82 | } 83 | #endregion 84 | #endregion 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/MemorySharp/Memory/RemoteRegion.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Native; 11 | 12 | namespace Binarysharp.MemoryManagement.Memory 13 | { 14 | /// 15 | /// Represents a contiguous block of memory in the remote process. 16 | /// 17 | public class RemoteRegion : RemotePointer, IEquatable 18 | { 19 | #region Properties 20 | #region Information 21 | /// 22 | /// Contains information about the memory. 23 | /// 24 | public MemoryBasicInformation Information 25 | { 26 | get { return MemoryCore.Query(MemorySharp.Handle, BaseAddress); } 27 | } 28 | #endregion 29 | #region IsValid 30 | /// 31 | /// Gets if the is valid. 32 | /// 33 | public override bool IsValid 34 | { 35 | get { return base.IsValid && Information.State != MemoryStateFlags.Free; } 36 | } 37 | #endregion 38 | #endregion 39 | 40 | #region Constructor 41 | /// 42 | /// Initializes a new instance of the class. 43 | /// 44 | /// The reference of the object. 45 | /// The base address of the memory region. 46 | internal RemoteRegion(MemorySharp memorySharp, IntPtr baseAddress) : base(memorySharp, baseAddress) 47 | { 48 | } 49 | #endregion 50 | 51 | #region Methods 52 | #region ChangeProtection 53 | /// 54 | /// Changes the protection of the n next bytes in remote process. 55 | /// 56 | /// The new protection to apply. 57 | /// The resource will be automatically disposed when the finalizer collects the object. 58 | /// A new instance of the class. 59 | public MemoryProtection ChangeProtection(MemoryProtectionFlags protection = MemoryProtectionFlags.ExecuteReadWrite, bool mustBeDisposed = true) 60 | { 61 | return new MemoryProtection(MemorySharp, BaseAddress, Information.RegionSize, protection, mustBeDisposed); 62 | } 63 | #endregion 64 | #region Equals (override) 65 | /// 66 | /// Determines whether the specified object is equal to the current object. 67 | /// 68 | public override bool Equals(object obj) 69 | { 70 | if (ReferenceEquals(null, obj)) return false; 71 | if (ReferenceEquals(this, obj)) return true; 72 | return obj.GetType() == GetType() && Equals((RemoteRegion)obj); 73 | } 74 | /// 75 | /// Returns a value indicating whether this instance is equal to a specified object. 76 | /// 77 | public bool Equals(RemoteRegion other) 78 | { 79 | if (ReferenceEquals(null, other)) return false; 80 | return ReferenceEquals(this, other) || (BaseAddress.Equals(other.BaseAddress) && MemorySharp.Equals(other.MemorySharp) && 81 | Information.RegionSize.Equals(other.Information.RegionSize)); 82 | } 83 | #endregion 84 | #region GetHashCode (override) 85 | /// 86 | /// Serves as a hash function for a particular type. 87 | /// 88 | public override int GetHashCode() 89 | { 90 | return BaseAddress.GetHashCode() ^ MemorySharp.GetHashCode() ^ Information.RegionSize.GetHashCode(); 91 | } 92 | #endregion 93 | #region Operator (override) 94 | public static bool operator ==(RemoteRegion left, RemoteRegion right) 95 | { 96 | return Equals(left, right); 97 | } 98 | 99 | public static bool operator !=(RemoteRegion left, RemoteRegion right) 100 | { 101 | return !Equals(left, right); 102 | } 103 | #endregion 104 | #region Release 105 | /// 106 | /// Releases the memory used by the region. 107 | /// 108 | public void Release() 109 | { 110 | // Release the memory 111 | MemoryCore.Free(MemorySharp.Handle, BaseAddress); 112 | // Remove the pointer 113 | BaseAddress = IntPtr.Zero; 114 | } 115 | #endregion 116 | #region ToString (override) 117 | /// 118 | /// Returns a string that represents the current object. 119 | /// 120 | public override string ToString() 121 | { 122 | return string.Format("BaseAddress = 0x{0:X} Size = 0x{1:X} Protection = {2}", BaseAddress.ToInt64(), 123 | Information.RegionSize, Information.Protect); 124 | } 125 | #endregion 126 | #endregion 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/MemorySharp/MemorySharp.licenseheader: -------------------------------------------------------------------------------- 1 | extensions: designer.cs generated.cs 2 | extensions: .cs .cpp .h 3 | /* 4 | * MemorySharp Library 5 | * http://www.binarysharp.com/ 6 | * 7 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 8 | * This library is released under the MIT License. 9 | * See the file LICENSE for more information. 10 | */ -------------------------------------------------------------------------------- /src/MemorySharp/Modules/InjectedModule.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Diagnostics; 11 | using System.Linq; 12 | using Binarysharp.MemoryManagement.Internals; 13 | 14 | namespace Binarysharp.MemoryManagement.Modules 15 | { 16 | /// 17 | /// Class representing an injected module in a remote process. 18 | /// 19 | public class InjectedModule : RemoteModule, IDisposableState 20 | { 21 | #region Properties 22 | #region IsDisposed (implementation of IDisposableState) 23 | /// 24 | /// Gets a value indicating whether the element is disposed. 25 | /// 26 | public bool IsDisposed { get; private set; } 27 | #endregion 28 | #region MustBeDisposed (implementation of IDisposableState) 29 | /// 30 | /// Gets a value indicating whether the element must be disposed when the Garbage Collector collects the object. 31 | /// 32 | public bool MustBeDisposed { get; set; } 33 | #endregion 34 | #endregion 35 | 36 | #region Constructor/Destructor 37 | /// 38 | /// Initializes a new instance of the class. 39 | /// 40 | /// The reference of the object. 41 | /// The native object corresponding to the injected module. 42 | /// The module will be ejected when the finalizer collects the object. 43 | internal InjectedModule(MemorySharp memorySharp, ProcessModule module, bool mustBeDisposed = true) 44 | : base(memorySharp, module) 45 | { 46 | // Save the parameter 47 | MustBeDisposed = mustBeDisposed; 48 | } 49 | /// 50 | /// Frees resources and perform other cleanup operations before it is reclaimed by garbage collection. 51 | /// 52 | ~InjectedModule() 53 | { 54 | if(MustBeDisposed) 55 | Dispose(); 56 | } 57 | #endregion 58 | 59 | #region Methods 60 | #region Dispose (implementation of IDisposableState) 61 | /// 62 | /// Releases all resources used by the object. 63 | /// 64 | public virtual void Dispose() 65 | { 66 | if (!IsDisposed) 67 | { 68 | // Set the flag to true 69 | IsDisposed = true; 70 | // Eject the module 71 | MemorySharp.Modules.Eject(this); 72 | // Avoid the finalizer 73 | GC.SuppressFinalize(this); 74 | } 75 | } 76 | #endregion 77 | #region InternalInject (internal) 78 | /// 79 | /// Injects the specified module into the address space of the remote process. 80 | /// 81 | /// The reference of the object. 82 | /// The path of the module. This can be either a library module (a .dll file) or an executable module (an .exe file). 83 | /// A new instance of the class. 84 | internal static InjectedModule InternalInject(MemorySharp memorySharp, string path) 85 | { 86 | // Call LoadLibraryA remotely 87 | var thread = memorySharp.Threads.CreateAndJoin(memorySharp["kernel32"]["LoadLibraryA"].BaseAddress, path); 88 | // Get the inject module 89 | if (thread.GetExitCode() != IntPtr.Zero) 90 | return new InjectedModule(memorySharp, memorySharp.Modules.NativeModules.First(m => m.BaseAddress == thread.GetExitCode())); 91 | return null; 92 | } 93 | #endregion 94 | #endregion 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/MemorySharp/Modules/ModuleCore.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.ComponentModel; 11 | using System.Diagnostics; 12 | using System.IO; 13 | using System.Linq; 14 | using Binarysharp.MemoryManagement.Native; 15 | 16 | namespace Binarysharp.MemoryManagement.Modules 17 | { 18 | /// 19 | /// Static core class providing tools for manipulating modules and libraries. 20 | /// 21 | public static class ModuleCore 22 | { 23 | #region GetProcAddress 24 | /// 25 | /// Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL). 26 | /// 27 | /// The module name (not case-sensitive). 28 | /// The function or variable name, or the function's ordinal value. 29 | /// The address of the exported function. 30 | public static IntPtr GetProcAddress(string moduleName, string functionName) 31 | { 32 | // Get the module 33 | var module = Process.GetCurrentProcess().Modules.Cast().FirstOrDefault(m => m.ModuleName.ToLower() == moduleName.ToLower()); 34 | 35 | // Check whether there is a module loaded with this name 36 | if (module == null) 37 | throw new ArgumentException(string.Format("Couldn't get the module {0} because it doesn't exist in the current process.", moduleName)); 38 | 39 | // Get the function address 40 | var ret = NativeMethods.GetProcAddress(module.BaseAddress, functionName); 41 | 42 | // Check whether the function was found 43 | if (ret != IntPtr.Zero) 44 | return ret; 45 | 46 | // Else the function was not found, throws an exception 47 | throw new Win32Exception(string.Format("Couldn't get the function address of {0}.", functionName)); 48 | } 49 | 50 | /// 51 | /// Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL). 52 | /// 53 | /// The object corresponding to the module. 54 | /// The function or variable name, or the function's ordinal value. 55 | /// If the function succeeds, the return value is the address of the exported function. 56 | public static IntPtr GetProcAddress(ProcessModule module, string functionName) 57 | { 58 | return GetProcAddress(module.ModuleName, functionName); 59 | } 60 | #endregion 61 | 62 | #region FreeLibrary 63 | /// 64 | /// Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. 65 | /// 66 | /// The name of the library to free (not case-sensitive). 67 | public static void FreeLibrary(string libraryName) 68 | { 69 | // Get the module 70 | var module = Process.GetCurrentProcess().Modules.Cast().FirstOrDefault(m => m.ModuleName.ToLower() == libraryName.ToLower()); 71 | 72 | // Check whether there is a library loaded with this name 73 | if(module == null) 74 | throw new ArgumentException(string.Format("Couldn't free the library {0} because it doesn't exist in the current process.", libraryName)); 75 | 76 | // Free the library 77 | if(!NativeMethods.FreeLibrary(module.BaseAddress)) 78 | throw new Win32Exception(string.Format("Couldn't free the library {0}.", libraryName)); 79 | } 80 | 81 | /// 82 | /// Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. 83 | /// 84 | /// The object corresponding to the library to free. 85 | public static void FreeLibrary(ProcessModule module) 86 | { 87 | FreeLibrary(module.ModuleName); 88 | } 89 | #endregion 90 | 91 | #region LoadLibrary 92 | /// 93 | /// Loads the specified module into the address space of the calling process. 94 | /// 95 | /// The name of the module. This can be either a library module (a .dll file) or an executable module (an .exe file). 96 | /// A corresponding to the loaded library. 97 | public static ProcessModule LoadLibrary(string libraryPath) 98 | { 99 | // Check whether the file exists 100 | if(!File.Exists(libraryPath)) 101 | throw new FileNotFoundException(string.Format("Couldn't load the library {0} because the file doesn't exist.", libraryPath)); 102 | 103 | // Load the library 104 | if(NativeMethods.LoadLibrary(libraryPath) == IntPtr.Zero) 105 | throw new Win32Exception(string.Format("Couldn't load the library {0}.", libraryPath)); 106 | 107 | // Enumerate the loaded modules and return the one newly added 108 | return Process.GetCurrentProcess().Modules.Cast().First(m => m.FileName == libraryPath); 109 | } 110 | #endregion 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/MemorySharp/Modules/RemoteFunction.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Memory; 11 | 12 | namespace Binarysharp.MemoryManagement.Modules 13 | { 14 | /// 15 | /// Class representing a function in the remote process. 16 | /// 17 | public class RemoteFunction : RemotePointer 18 | { 19 | #region Properties 20 | /// 21 | /// The name of the function. 22 | /// 23 | public string Name { get; private set; } 24 | #endregion 25 | 26 | #region Constructor 27 | public RemoteFunction(MemorySharp memorySharp, IntPtr address, string functionName) : base(memorySharp, address) 28 | { 29 | // Save the parameter 30 | Name = functionName; 31 | } 32 | #endregion 33 | 34 | #region Methods 35 | #region ToString (override) 36 | /// 37 | /// Returns a string that represents the current object. 38 | /// 39 | public override string ToString() 40 | { 41 | return string.Format("BaseAddress = 0x{0:X} Name = {1}", BaseAddress.ToInt64(), Name); 42 | } 43 | #endregion 44 | #endregion 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/MemorySharp/Native/SafeMemoryHandle.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Runtime.ConstrainedExecution; 11 | using System.Security.Permissions; 12 | using Microsoft.Win32.SafeHandles; 13 | 14 | namespace Binarysharp.MemoryManagement.Native 15 | { 16 | /// 17 | /// Represents a Win32 handle safely managed. 18 | /// 19 | [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] 20 | public sealed class SafeMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid 21 | { 22 | /// 23 | /// Parameterless constructor for handles built by the system (like ). 24 | /// 25 | public SafeMemoryHandle() : base(true) { } 26 | 27 | /// 28 | /// Initializes a new instance of the class, specifying the handle to keep in safe. 29 | /// 30 | /// The handle to keep in safe. 31 | public SafeMemoryHandle(IntPtr handle) : base(true) 32 | { 33 | SetHandle(handle); 34 | } 35 | 36 | /// 37 | /// Executes the code required to free the handle. 38 | /// 39 | /// True if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a releaseHandleFailed MDA Managed Debugging Assistant. 40 | [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] 41 | protected override bool ReleaseHandle() 42 | { 43 | // Check whether the handle is set AND whether the handle has been successfully closed 44 | return handle != IntPtr.Zero && NativeMethods.CloseHandle(handle); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/MemorySharp/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.Reflection; 10 | using System.Runtime.InteropServices; 11 | 12 | // General Information about an assembly is controlled through the following 13 | // set of attributes. Change these attribute values to modify the information 14 | // associated with an assembly. 15 | [assembly: AssemblyTitle("MemorySharp")] 16 | [assembly: AssemblyDescription("MemorySharp is a C# based memory editing library targeting Windows applications, offering various functions to extract and inject data and codes into remote processes to allow interoperability.")] 17 | [assembly: AssemblyConfiguration("")] 18 | [assembly: AssemblyCompany("Binarysharp")] 19 | [assembly: AssemblyProduct("MemorySharp")] 20 | [assembly: AssemblyCopyright("Copyright © 2012-2016 ZenLulz")] 21 | [assembly: AssemblyTrademark("")] 22 | [assembly: AssemblyCulture("")] 23 | 24 | // Setting ComVisible to false makes the types in this assembly not visible 25 | // to COM components. If you need to access a type in this assembly from 26 | // COM, set the ComVisible attribute to true on that type. 27 | [assembly: ComVisible(false)] 28 | 29 | // The following GUID is for the ID of the typelib if this project is exposed to COM 30 | [assembly: Guid("1641caf4-3e21-40b4-acb4-1364c4853930")] 31 | 32 | // Version information for an assembly consists of the following four values: 33 | // 34 | // Major Version 35 | // Minor Version 36 | // Build Number 37 | // Revision 38 | // 39 | // You can specify all the values or you can default the Build and Revision Numbers 40 | // by using the '*' as shown below: 41 | // [assembly: AssemblyVersion("1.0.*")] 42 | [assembly: AssemblyVersion("1.2.0.0")] 43 | [assembly: AssemblyFileVersion("1.2.0.0")] 44 | -------------------------------------------------------------------------------- /src/MemorySharp/Threading/Enumerations.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | namespace Binarysharp.MemoryManagement.Threading 10 | { 11 | #region SegmentRegisters 12 | /// 13 | /// List of segment registers. 14 | /// 15 | public enum SegmentRegisters 16 | { 17 | /// 18 | /// The code segment. 19 | /// 20 | Cs, 21 | /// 22 | /// The Data segment. 23 | /// 24 | Ds, 25 | /// 26 | /// The extra data segment. 27 | /// 28 | Es, 29 | /// 30 | /// The points to Thread Information Block (TIB). 31 | /// 32 | Fs, 33 | /// 34 | /// The extra data segment. 35 | /// 36 | Gs, 37 | /// 38 | /// The stack segment. 39 | /// 40 | Ss 41 | } 42 | #endregion 43 | } 44 | -------------------------------------------------------------------------------- /src/MemorySharp/Threading/FrozenThread.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | 11 | namespace Binarysharp.MemoryManagement.Threading 12 | { 13 | /// 14 | /// Class containing a frozen thread. If an instance of this class is disposed, its associated thread is resumed. 15 | /// 16 | public class FrozenThread : IDisposable 17 | { 18 | #region Properties 19 | /// 20 | /// The frozen thread. 21 | /// 22 | public RemoteThread Thread { get; private set; } 23 | #endregion 24 | 25 | #region Constructor 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// 29 | /// The frozen thread. 30 | internal FrozenThread(RemoteThread thread) 31 | { 32 | // Save the parameter 33 | Thread = thread; 34 | } 35 | #endregion 36 | 37 | #region Methods 38 | #region Dispose (implementation of IDisposable) 39 | /// 40 | /// Releases all resources used by the object. 41 | /// 42 | public virtual void Dispose() 43 | { 44 | // Unfreeze the thread 45 | Thread.Resume(); 46 | } 47 | #endregion 48 | #region ToString (override) 49 | /// 50 | /// Returns a string that represents the current object. 51 | /// 52 | public override string ToString() 53 | { 54 | return string.Format("Id = {0}", Thread.Id); 55 | } 56 | #endregion 57 | #endregion 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/MemorySharp/Windows/Keyboard/BaseKeyboard.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | using Binarysharp.MemoryManagement.Native; 14 | 15 | namespace Binarysharp.MemoryManagement.Windows.Keyboard 16 | { 17 | /// 18 | /// Abstract class defining a virtual keyboard. 19 | /// 20 | public abstract class BaseKeyboard 21 | { 22 | #region Fields 23 | /// 24 | /// The reference of the object. 25 | /// 26 | protected readonly RemoteWindow Window; 27 | /// 28 | /// The collection storing the current pressed keys. 29 | /// 30 | protected static readonly List> PressedKeys = new List>(); 31 | #endregion 32 | 33 | #region Constructor 34 | /// 35 | /// Initializes a new instance of a child of the class. 36 | /// 37 | /// The reference of the object. 38 | protected BaseKeyboard(RemoteWindow window) 39 | { 40 | // Save the parameter 41 | Window = window; 42 | } 43 | #endregion 44 | 45 | #region Abstract Methods 46 | /// 47 | /// Presses the specified virtual key to the window. 48 | /// 49 | /// The virtual key to press. 50 | public abstract void Press(Keys key); 51 | /// 52 | /// Writes the specified character to the window. 53 | /// 54 | /// The character to write. 55 | public abstract void Write(char character); 56 | #endregion 57 | 58 | #region Virtual Methods 59 | #region Release 60 | /// 61 | /// Releases the specified virtual key to the window. 62 | /// 63 | /// The virtual key to release. 64 | public virtual void Release(Keys key) 65 | { 66 | // Create the tuple 67 | var tuple = Tuple.Create(Window.Handle, key); 68 | 69 | // If the key is pressed with an interval 70 | if (PressedKeys.Contains(tuple)) 71 | PressedKeys.Remove(tuple); 72 | } 73 | #endregion 74 | #endregion 75 | 76 | #region Extended Methods 77 | #region Press 78 | /// 79 | /// Presses the specified virtual key to the window at a specified interval. 80 | /// 81 | /// The virtual key to press. 82 | /// The interval between the key activations. 83 | public void Press(Keys key, TimeSpan interval) 84 | { 85 | // Create the tuple 86 | var tuple = Tuple.Create(Window.Handle, key); 87 | 88 | // If the key is already pressed 89 | if (PressedKeys.Contains(tuple)) 90 | return; 91 | 92 | // Add the key to the collection 93 | PressedKeys.Add(tuple); 94 | // Start a new task to press the key at the specified interval 95 | Task.Run(async () => 96 | { 97 | // While the key must be pressed 98 | while (PressedKeys.Contains(tuple)) 99 | { 100 | // Press the key 101 | Press(key); 102 | // Wait the interval 103 | await Task.Delay(interval); 104 | } 105 | }); 106 | } 107 | #endregion 108 | #region PressRelease 109 | /// 110 | /// Presses and releaes the specified virtual key to the window. 111 | /// 112 | /// The virtual key to press and release. 113 | public void PressRelease(Keys key) 114 | { 115 | Press(key); 116 | Thread.Sleep(10); 117 | Release(key); 118 | } 119 | #endregion 120 | #region Write 121 | /// 122 | /// Writes the text representation of the specified array of objects to the window using the specified format information. 123 | /// 124 | /// A composite format string. 125 | /// An array of objects to write using format. 126 | public void Write(string text, params object[] args) 127 | { 128 | foreach (var character in string.Format(text, args)) 129 | { 130 | Write(character); 131 | } 132 | } 133 | #endregion 134 | #endregion 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/MemorySharp/Windows/Keyboard/MessageKeyboard.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Native; 11 | 12 | namespace Binarysharp.MemoryManagement.Windows.Keyboard 13 | { 14 | /// 15 | /// Class defining a virtual keyboard using the API Message. 16 | /// 17 | public class MessageKeyboard : BaseKeyboard 18 | { 19 | #region Constructor 20 | public MessageKeyboard(RemoteWindow window) : base(window) 21 | { 22 | } 23 | #endregion 24 | 25 | #region Overridden Methods 26 | #region Press 27 | /// 28 | /// Presses the specified virtual key to the window. 29 | /// 30 | /// The virtual key to press. 31 | public override void Press(Keys key) 32 | { 33 | Window.PostMessage(WindowsMessages.KeyDown, new UIntPtr((uint)key), MakeKeyParameter(key, false)); 34 | } 35 | #endregion 36 | #region Release 37 | /// 38 | /// Releases the specified virtual key to the window. 39 | /// 40 | /// The virtual key to release. 41 | public override void Release(Keys key) 42 | { 43 | // Call the base function 44 | base.Release(key); 45 | Window.PostMessage(WindowsMessages.KeyUp, new UIntPtr((uint)key), MakeKeyParameter(key, true)); 46 | } 47 | #endregion 48 | #region Write 49 | /// 50 | /// Writes the specified character to the window. 51 | /// 52 | /// The character to write. 53 | public override void Write(char character) 54 | { 55 | Window.PostMessage(WindowsMessages.Char, new UIntPtr(character), UIntPtr.Zero); 56 | } 57 | #endregion 58 | #endregion 59 | 60 | #region MakeKeyParameter (private) 61 | /// 62 | /// Makes the lParam for a key depending on several settings. 63 | /// 64 | /// 65 | /// [16-23 bits] The virtual key. 66 | /// 67 | /// 68 | /// [31 bit] The transition state. 69 | /// The value is always 0 for a message. 70 | /// The value is always 1 for a message. 71 | /// 72 | /// 73 | /// [30 bit] The previous key state. 74 | /// The value is 1 if the key is down before the message is sent, or it is zero if the key is up. 75 | /// The value is always 1 for a message. 76 | /// 77 | /// 78 | /// [0-15 bits] The repeat count for the current message. 79 | /// The value is the number of times the keystroke is autorepeated as a result of the user holding down the key. 80 | /// If the keystroke is held long enough, multiple messages are sent. However, the repeat count is not cumulative. 81 | /// The repeat count is always 1 for a message. 82 | /// 83 | /// 84 | /// [29 bit] The context code. 85 | /// The value is always 0 for a message. 86 | /// The value is always 0 for a message. 87 | /// 88 | /// [24 bit] Indicates whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on 89 | /// an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0. 90 | /// 91 | /// The return value is the lParam when posting or sending a message regarding key press. 92 | /// 93 | /// KeyDown resources: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646280%28v=vs.85%29.aspx 94 | /// KeyUp resources: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646281%28v=vs.85%29.aspx 95 | /// 96 | private UIntPtr MakeKeyParameter(Keys key, bool keyUp, bool fRepeat, uint cRepeat, bool altDown, bool fExtended) 97 | { 98 | // Create the result and assign it with the repeat count 99 | var result = cRepeat; 100 | // Add the scan code with a left shift operation 101 | result |= WindowCore.MapVirtualKey(key, TranslationTypes.VirtualKeyToScanCode) << 16; 102 | // Does we need to set the extended flag ? 103 | if (fExtended) 104 | result |= 0x1000000; 105 | // Does we need to set the alt flag ? 106 | if (altDown) 107 | result |= 0x20000000; 108 | // Does we need to set the repeat flag ? 109 | if (fRepeat) 110 | result |= 0x40000000; 111 | // Does we need to set the keyUp flag ? 112 | if (keyUp) 113 | result |= 0x80000000; 114 | 115 | return new UIntPtr(result); 116 | } 117 | /// 118 | /// Makes the lParam for a key depending on several settings. 119 | /// 120 | /// The virtual key. 121 | /// 122 | /// The transition state. 123 | /// The value is always 0 for a message. 124 | /// The value is always 1 for a message. 125 | /// 126 | /// The return value is the lParam when posting or sending a message regarding key press. 127 | private UIntPtr MakeKeyParameter(Keys key, bool keyUp) 128 | { 129 | return MakeKeyParameter(key, keyUp, keyUp, 1, false, false); 130 | } 131 | #endregion 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/MemorySharp/Windows/Mouse/BaseMouse.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.Threading; 10 | 11 | namespace Binarysharp.MemoryManagement.Windows.Mouse 12 | { 13 | /// 14 | /// Abstract class defining a virtual mouse. 15 | /// 16 | public abstract class BaseMouse 17 | { 18 | #region Fields 19 | /// 20 | /// The reference of the object. 21 | /// 22 | protected readonly RemoteWindow Window; 23 | #endregion 24 | 25 | #region Constructor 26 | /// 27 | /// Initializes a new instance of a child of the class. 28 | /// 29 | /// The reference of the object. 30 | protected BaseMouse(RemoteWindow window) 31 | { 32 | // Save the parameter 33 | Window = window; 34 | } 35 | #endregion 36 | 37 | #region Abstract Methods 38 | /// 39 | /// Moves the cursor at the specified coordinate. 40 | /// 41 | /// The x-coordinate. 42 | /// The y-coordinate. 43 | protected abstract void MoveToAbsolute(int x, int y); 44 | /// 45 | /// Presses the left button of the mouse at the current cursor position. 46 | /// 47 | public abstract void PressLeft(); 48 | /// 49 | /// Presses the middle button of the mouse at the current cursor position. 50 | /// 51 | public abstract void PressMiddle(); 52 | /// 53 | /// Presses the right button of the mouse at the current cursor position. 54 | /// 55 | public abstract void PressRight(); 56 | /// 57 | /// Releases the left button of the mouse at the current cursor position. 58 | /// 59 | public abstract void ReleaseLeft(); 60 | /// 61 | /// Releases the middle button of the mouse at the current cursor position. 62 | /// 63 | public abstract void ReleaseMiddle(); 64 | /// 65 | /// Releases the right button of the mouse at the current cursor position. 66 | /// 67 | public abstract void ReleaseRight(); 68 | /// 69 | /// Scrolls horizontally using the wheel of the mouse at the current cursor position. 70 | /// 71 | /// The amount of wheel movement. 72 | public abstract void ScrollHorizontally(int delta = 120); 73 | /// 74 | /// Scrolls vertically using the wheel of the mouse at the current cursor position. 75 | /// 76 | /// The amount of wheel movement. 77 | public abstract void ScrollVertically(int delta = 120); 78 | #endregion 79 | 80 | #region Extended Methods 81 | #region ClickLeft 82 | /// 83 | /// Clicks the left button of the mouse at the current cursor position. 84 | /// 85 | public void ClickLeft() 86 | { 87 | PressLeft(); 88 | ReleaseLeft(); 89 | } 90 | #endregion 91 | #region ClickMiddle 92 | /// 93 | /// Clicks the middle button of the mouse at the current cursor position. 94 | /// 95 | public void ClickMiddle() 96 | { 97 | PressMiddle(); 98 | ReleaseMiddle(); 99 | } 100 | #endregion 101 | #region ClickRight 102 | /// 103 | /// Clicks the right button of the mouse at the current cursor position. 104 | /// 105 | public void ClickRight() 106 | { 107 | PressRight(); 108 | ReleaseRight(); 109 | } 110 | #endregion 111 | #region DoubleClickLeft 112 | /// 113 | /// Double clicks the left button of the mouse at the current cursor position. 114 | /// 115 | public void DoubleClickLeft() 116 | { 117 | ClickLeft(); 118 | Thread.Sleep(10); 119 | ClickLeft(); 120 | } 121 | #endregion 122 | #region MoveTo 123 | /// 124 | /// Moves the cursor at the specified coordinate from the position of the window. 125 | /// 126 | /// The x-coordinate. 127 | /// The y-coordinate. 128 | public void MoveTo(int x, int y) 129 | { 130 | MoveToAbsolute(Window.X + x, Window.Y + y); 131 | } 132 | #endregion 133 | #endregion 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/MemorySharp/Windows/Mouse/SendInputMouse.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using Binarysharp.MemoryManagement.Native; 10 | 11 | namespace Binarysharp.MemoryManagement.Windows.Mouse 12 | { 13 | /// 14 | /// Class defining a virtual mouse using the API SendInput. 15 | /// 16 | public class SendInputMouse : BaseMouse 17 | { 18 | #region Constructor 19 | /// 20 | /// Initializes a new instance of a child of the class. 21 | /// 22 | /// The reference of the object. 23 | public SendInputMouse(RemoteWindow window) : base(window) 24 | { 25 | } 26 | #endregion 27 | 28 | #region Overridden methods 29 | #region MoveToAbsolute 30 | /// 31 | /// Moves the cursor at the specified coordinate. 32 | /// 33 | /// The x-coordinate. 34 | /// The y-coordinate. 35 | protected override void MoveToAbsolute(int x, int y) 36 | { 37 | var input = CreateInput(); 38 | input.Mouse.DeltaX = CalculateAbsoluteCoordinateX(x); 39 | input.Mouse.DeltaY = CalculateAbsoluteCoordinateY(y); 40 | input.Mouse.Flags = MouseFlags.Move | MouseFlags.Absolute; 41 | input.Mouse.MouseData = 0; 42 | WindowCore.SendInput(input); 43 | } 44 | #endregion 45 | #region PressLeft 46 | /// 47 | /// Presses the left button of the mouse at the current cursor position. 48 | /// 49 | public override void PressLeft() 50 | { 51 | var input = CreateInput(); 52 | input.Mouse.Flags = MouseFlags.LeftDown; 53 | WindowCore.SendInput(input); 54 | } 55 | #endregion 56 | #region PressMiddle 57 | /// 58 | /// Presses the middle button of the mouse at the current cursor position. 59 | /// 60 | public override void PressMiddle() 61 | { 62 | var input = CreateInput(); 63 | input.Mouse.Flags = MouseFlags.MiddleDown; 64 | WindowCore.SendInput(input); 65 | } 66 | #endregion 67 | #region PressRight 68 | /// 69 | /// Presses the right button of the mouse at the current cursor position. 70 | /// 71 | public override void PressRight() 72 | { 73 | var input = CreateInput(); 74 | input.Mouse.Flags = MouseFlags.RightDown; 75 | WindowCore.SendInput(input); 76 | } 77 | #endregion 78 | #region ReleaseLeft 79 | /// 80 | /// Releases the left button of the mouse at the current cursor position. 81 | /// 82 | public override void ReleaseLeft() 83 | { 84 | var input = CreateInput(); 85 | input.Mouse.Flags = MouseFlags.LeftUp; 86 | WindowCore.SendInput(input); 87 | } 88 | #endregion 89 | #region ReleaseMiddle 90 | /// 91 | /// Releases the middle button of the mouse at the current cursor position. 92 | /// 93 | public override void ReleaseMiddle() 94 | { 95 | var input = CreateInput(); 96 | input.Mouse.Flags = MouseFlags.MiddleUp; 97 | WindowCore.SendInput(input); 98 | } 99 | 100 | #endregion 101 | #region ReleaseRight 102 | /// 103 | /// Releases the right button of the mouse at the current cursor position. 104 | /// 105 | public override void ReleaseRight() 106 | { 107 | var input = CreateInput(); 108 | input.Mouse.Flags = MouseFlags.RightUp; 109 | WindowCore.SendInput(input); 110 | } 111 | #endregion 112 | #region ScrollHorizontally 113 | /// 114 | /// Scrolls horizontally using the wheel of the mouse at the current cursor position. 115 | /// 116 | /// The amount of wheel movement. 117 | public override void ScrollHorizontally(int delta = 120) 118 | { 119 | var input = CreateInput(); 120 | input.Mouse.Flags = MouseFlags.HWheel; 121 | input.Mouse.MouseData = delta; 122 | WindowCore.SendInput(input); 123 | } 124 | #endregion 125 | #region ScrollVertically 126 | /// 127 | /// Scrolls vertically using the wheel of the mouse at the current cursor position. 128 | /// 129 | /// The amount of wheel movement. 130 | public override void ScrollVertically(int delta = 120) 131 | { 132 | var input = CreateInput(); 133 | input.Mouse.Flags = MouseFlags.Wheel; 134 | input.Mouse.MouseData = delta; 135 | WindowCore.SendInput(input); 136 | } 137 | #endregion 138 | #endregion 139 | 140 | #region CalculateAbsoluteCoordinateX 141 | /// 142 | /// Calculates the x-coordinate with the system metric. 143 | /// 144 | private int CalculateAbsoluteCoordinateX(int x) 145 | { 146 | return (x * 65536) / NativeMethods.GetSystemMetrics(SystemMetrics.CxScreen); 147 | } 148 | #endregion 149 | #region CalculateAbsoluteCoordinateY 150 | /// 151 | /// Calculates the y-coordinate with the system metric. 152 | /// 153 | private int CalculateAbsoluteCoordinateY(int y) 154 | { 155 | return (y * 65536) / NativeMethods.GetSystemMetrics(SystemMetrics.CyScreen); 156 | } 157 | #endregion 158 | #region CreateInput 159 | /// 160 | /// Create an structure for mouse event. 161 | /// 162 | private Input CreateInput() 163 | { 164 | return new Input(InputTypes.Mouse); 165 | } 166 | #endregion 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/MemorySharp/Windows/WindowFactory.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using Binarysharp.MemoryManagement.Internals; 13 | 14 | namespace Binarysharp.MemoryManagement.Windows 15 | { 16 | /// 17 | /// Class providing tools for manipulating windows. 18 | /// 19 | public class WindowFactory : IFactory 20 | { 21 | #region Fields 22 | /// 23 | /// The reference of the object. 24 | /// 25 | private readonly MemorySharp _memorySharp; 26 | #endregion 27 | 28 | #region Properties 29 | #region ChildWindows 30 | /// 31 | /// Gets all the child windows that belong to the application. 32 | /// 33 | public IEnumerable ChildWindows 34 | { 35 | get { return ChildWindowHandles.Select(handle => new RemoteWindow(_memorySharp, handle)); } 36 | } 37 | #endregion 38 | #region ChildWindowHandles (internal) 39 | /// 40 | /// Gets all the child window handles that belong to the application. 41 | /// 42 | internal IEnumerable ChildWindowHandles 43 | { 44 | get { return WindowCore.EnumChildWindows(_memorySharp.Native.MainWindowHandle); } 45 | } 46 | #endregion 47 | #region MainWindow 48 | /// 49 | /// Gets the main window of the application. 50 | /// 51 | public RemoteWindow MainWindow 52 | { 53 | get { return new RemoteWindow(_memorySharp, MainWindowHandle); } 54 | } 55 | #endregion 56 | #region MainWindowHandle (internal) 57 | /// 58 | /// Gets the main window handle of the application. 59 | /// 60 | public IntPtr MainWindowHandle 61 | { 62 | get { return _memorySharp.Native.MainWindowHandle; } 63 | } 64 | #endregion 65 | #region This 66 | /// 67 | /// Gets all the windows that have the same specified title. 68 | /// 69 | /// The window title string. 70 | /// A collection of . 71 | public IEnumerable this[string windowTitle] 72 | { 73 | get { return GetWindowsByTitle(windowTitle); } 74 | } 75 | #endregion 76 | #region Windows 77 | /// 78 | /// Gets all the windows that belong to the application. 79 | /// 80 | public IEnumerable RemoteWindows 81 | { 82 | get { return WindowHandles.Select(handle => new RemoteWindow(_memorySharp, handle)); } 83 | } 84 | #endregion 85 | #region WindowHandles (internal) 86 | /// 87 | /// Gets all the window handles that belong to the application. 88 | /// 89 | internal IEnumerable WindowHandles 90 | { 91 | get 92 | { 93 | return new List(ChildWindowHandles) {MainWindowHandle}; 94 | } 95 | } 96 | #endregion 97 | #endregion 98 | 99 | #region Constructor 100 | /// 101 | /// Initializes a new instance of the class. 102 | /// 103 | /// The reference of the object. 104 | internal WindowFactory(MemorySharp memorySharp) 105 | { 106 | // Save the parameter 107 | _memorySharp = memorySharp; 108 | } 109 | #endregion 110 | 111 | #region Methods 112 | #region Dispose (implementation of IFactory) 113 | /// 114 | /// Releases all resources used by the object. 115 | /// 116 | public void Dispose() 117 | { 118 | // Nothing to dispose... yet 119 | } 120 | #endregion 121 | #region GetWindowsByClassName 122 | /// 123 | /// Gets all the windows that have the specified class name. 124 | /// 125 | /// The class name string. 126 | /// A collection of . 127 | public IEnumerable GetWindowsByClassName(string className) 128 | { 129 | return WindowHandles 130 | .Where(handle => WindowCore.GetClassName(handle) == className) 131 | .Select(handle => new RemoteWindow(_memorySharp, handle)); 132 | } 133 | #endregion 134 | #region GetWindowsByTitle 135 | /// 136 | /// Gets all the windows that have the same specified title. 137 | /// 138 | /// The window title string. 139 | /// A collection of . 140 | public IEnumerable GetWindowsByTitle(string windowTitle) 141 | { 142 | return WindowHandles 143 | .Where(handle => WindowCore.GetWindowText(handle) == windowTitle) 144 | .Select(handle => new RemoteWindow(_memorySharp, handle)); 145 | } 146 | #endregion 147 | #region GetWindowsByTitleContains 148 | /// 149 | /// Gets all the windows that contain the specified title. 150 | /// 151 | /// A part a window title string. 152 | /// A collection of . 153 | public IEnumerable GetWindowsByTitleContains(string windowTitle) 154 | { 155 | return WindowHandles 156 | .Where(handle => WindowCore.GetWindowText(handle).Contains(windowTitle)) 157 | .Select(handle => new RemoteWindow(_memorySharp, handle)); 158 | } 159 | #endregion 160 | #endregion 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/MemorySharp/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /test/IntegrationTests/Assembly/AssemblyFactoryTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using Binarysharp.MemoryManagement.Assembly; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace MemorySharpTests.Assembly 13 | { 14 | [TestClass] 15 | public class AssemblyFactoryTests 16 | { 17 | /// 18 | /// Injects some mnemonics. 19 | /// 20 | [TestMethod] 21 | public void Inject() 22 | { 23 | // Arrange 24 | var sharp = Resources.MemorySharp; 25 | 26 | // Act 27 | using (var memory = sharp.Memory.Allocate(1)) 28 | { 29 | sharp.Assembly.Inject( 30 | new[] 31 | { 32 | "push 0", 33 | "add esp, 4", 34 | "retn" 35 | }, 36 | memory.BaseAddress); 37 | 38 | // Assert 39 | CollectionAssert.AreEqual(new byte[] { 0x6A, 00, 0x83, 0xC4, 04, 0xC3 }, sharp.Read(memory.BaseAddress, 6, false)); 40 | } 41 | 42 | Resources.EndTests(sharp); 43 | } 44 | 45 | /// 46 | /// Injects some mnemonics using a transaction. 47 | /// 48 | [TestMethod] 49 | public void TransactionInject() 50 | { 51 | // Arrange 52 | var sharp = Resources.MemorySharp; 53 | 54 | // Act 55 | using (var memory = sharp.Memory.Allocate(1)) 56 | { 57 | using (var t = sharp.Assembly.BeginTransaction(memory.BaseAddress, false)) 58 | { 59 | t.AddLine("push 0"); 60 | t.AddLine("add esp, 4"); 61 | t.AddLine("retn"); 62 | } 63 | // Assert 64 | CollectionAssert.AreEqual(new byte[] { 0x6A, 00, 0x83, 0xC4, 04, 0xC3 }, sharp.Read(memory.BaseAddress, 6, false)); 65 | 66 | } 67 | 68 | Resources.EndTests(sharp); 69 | } 70 | 71 | /// 72 | /// Injects and executes some mnemonics. 73 | /// 74 | [TestMethod] 75 | public void InjectAndExecute() 76 | { 77 | // Arrange 78 | var sharp = Resources.MemorySharp; 79 | var asm = new[] 80 | { 81 | "use32", 82 | "mov eax, 66", 83 | "retn" 84 | }; 85 | 86 | // Act 87 | var ret = sharp.Assembly.InjectAndExecute(asm); 88 | 89 | // Assert 90 | Assert.AreEqual(66, ret, "The return value is incorrect."); 91 | Resources.EndTests(sharp); 92 | } 93 | 94 | /// 95 | /// Injects and executes some mnemonics with a transaction. 96 | /// 97 | [TestMethod] 98 | public void InjectAndExecuteWithTransaction() 99 | { 100 | // Arrange 101 | var sharp = Resources.MemorySharp; 102 | AssemblyTransaction t; 103 | 104 | // Act 105 | using (t = sharp.Assembly.BeginTransaction()) 106 | { 107 | t.AddLine("use32"); 108 | t.AddLine("mov eax, 66"); 109 | t.AddLine("retn"); 110 | } 111 | 112 | // Assert 113 | Assert.AreEqual(66, t.GetExitCode(), "The return value is incorrect."); 114 | Resources.EndTests(sharp); 115 | } 116 | 117 | /// 118 | /// Writes some mnemonics and execute them. 119 | /// 120 | [TestMethod] 121 | public void Execute() 122 | { 123 | // Arrange 124 | var sharp = Resources.MemorySharp; 125 | 126 | // Act 127 | using (var memory = sharp.Memory.Allocate(1)) 128 | { 129 | using (var t = sharp.Assembly.BeginTransaction(memory.BaseAddress)) 130 | { 131 | t.AddLine("use32"); 132 | t.AddLine("mov eax, 66"); 133 | t.AddLine("retn"); 134 | } 135 | 136 | var ret = memory.Execute(); 137 | 138 | // Assert 139 | Assert.AreEqual(66, ret, "The return value is incorrect."); 140 | } 141 | 142 | Resources.EndTests(sharp); 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /test/IntegrationTests/Helpers/ApplicationFinderTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.Linq; 10 | using Binarysharp.MemoryManagement.Helpers; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace MemorySharpTests.Helpers 14 | { 15 | [TestClass] 16 | public class ApplicationFinderTests 17 | { 18 | /// 19 | /// Enumerates all top-level windows and search the test process. 20 | /// 21 | [TestMethod] 22 | public void TopLevelWindows() 23 | { 24 | // Arrange 25 | var process = Resources.ProcessTest; 26 | 27 | // Act 28 | var ret = ApplicationFinder.TopLevelWindows.FirstOrDefault(windowHandle => windowHandle == process.MainWindowHandle); 29 | 30 | // Assert 31 | Assert.AreNotEqual(null, ret, "Couldn't find the main window of the test process."); 32 | } 33 | 34 | /// 35 | /// Enumerates all windows and search the test process. 36 | /// 37 | [TestMethod] 38 | public void Windows() 39 | { 40 | // Arrange 41 | var process = Resources.ProcessTest; 42 | 43 | // Act 44 | var ret = ApplicationFinder.Windows.FirstOrDefault(windowHandle => windowHandle == process.MainWindowHandle); 45 | 46 | // Assert 47 | Assert.AreNotEqual(null, ret, "Couldn't find the main window of the test process."); 48 | } 49 | 50 | /// 51 | /// Finds the application by process id. 52 | /// 53 | [TestMethod] 54 | public void FromProcessId() 55 | { 56 | // Arrange 57 | var process = Resources.ProcessTest; 58 | 59 | // Act 60 | var ret = ApplicationFinder.FromProcessId(process.Id); 61 | 62 | // Assert 63 | Assert.AreEqual(process.Id, ret.Id, "Both processes are not equal."); 64 | } 65 | 66 | /// 67 | /// Finds the application by process name. 68 | /// 69 | [TestMethod] 70 | public void FromProcessName() 71 | { 72 | // Arrange 73 | var process = Resources.ProcessTest; 74 | 75 | // Act 76 | var ret = ApplicationFinder.FromProcessName(process.ProcessName).First(); 77 | 78 | // Assert 79 | Assert.AreEqual(process.Id, ret.Id, "Both processes are not equal."); 80 | } 81 | 82 | /// 83 | /// Finds the application by class name. 84 | /// 85 | [TestMethod] 86 | public void FromWindowClassName() 87 | { 88 | // Arrange 89 | var process = Resources.ProcessTest; 90 | 91 | // Act 92 | var ret = ApplicationFinder.FromWindowClassName("Notepad++").First(); 93 | 94 | // Assert 95 | Assert.AreEqual(process.Id, ret.Id, "Both processes are not equal."); 96 | } 97 | 98 | /// 99 | /// Finds the application from the window handle. 100 | /// 101 | [TestMethod] 102 | public void FromWindowHandle() 103 | { 104 | // Arrange 105 | var process = Resources.ProcessTest; 106 | 107 | // Act 108 | var ret = ApplicationFinder.FromWindowHandle(process.MainWindowHandle); 109 | 110 | // Assert 111 | Assert.AreEqual(process.Id, ret.Id, "Both processes are not equal."); 112 | } 113 | 114 | /// 115 | /// Finds the application from the title. 116 | /// 117 | [TestMethod] 118 | public void FromWindowTitle() 119 | { 120 | // Arrange 121 | Resources.Restart(); 122 | var process = Resources.ProcessTest; 123 | 124 | // Act 125 | var ret = ApplicationFinder.FromWindowTitle("new 1 - Notepad++").First(); 126 | 127 | // Assert 128 | Assert.AreEqual(process.Id, ret.Id, "Both processes are not equal."); 129 | } 130 | 131 | /// 132 | /// Finds the application from a part of the title. 133 | /// 134 | [TestMethod] 135 | public void FromWindowTitleContains() 136 | { 137 | // Arrange 138 | var process = Resources.ProcessTest; 139 | 140 | // Act 141 | var ret = ApplicationFinder.FromWindowTitleContains("Notepad++").First(); 142 | 143 | // Assert 144 | Assert.AreEqual(process.Id, ret.Id, "Both processes are not equal."); 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /test/IntegrationTests/Helpers/HandleManipulatorTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using Binarysharp.MemoryManagement.Helpers; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace MemorySharpTests.Helpers 13 | { 14 | [TestClass] 15 | public class HandleManipulatorTests 16 | { 17 | /// 18 | /// Converts a handle to a managed process. 19 | /// 20 | [TestMethod] 21 | public void HandleToProcess() 22 | { 23 | // Arrange 24 | var processHandle = Resources.MemorySharp.Handle; 25 | 26 | // Act 27 | var ret = HandleManipulator.HandleToProcess(processHandle); 28 | 29 | // Assert 30 | Assert.AreEqual(Resources.ProcessTest.Id, ret.Id, "The both process id are not equal."); 31 | } 32 | 33 | /// 34 | /// Converts a handle to a process id. 35 | /// 36 | [TestMethod] 37 | public void HandleToProcessId() 38 | { 39 | // Arrange 40 | var processHandle = Resources.MemorySharp.Handle; 41 | 42 | // Act 43 | var ret = HandleManipulator.HandleToProcessId(processHandle); 44 | 45 | // Assert 46 | Assert.AreEqual(Resources.ProcessTest.Id, ret, "The both process id are not equal."); 47 | } 48 | 49 | /// 50 | /// Converts a handle to a managed thread. 51 | /// 52 | [TestMethod] 53 | public void HandleToThread() 54 | { 55 | // Arrange 56 | var threadHandle = Resources.MemorySharp.Threads.MainThread; 57 | 58 | // Act 59 | var ret = HandleManipulator.HandleToThread(threadHandle.Handle); 60 | 61 | // Assert 62 | Assert.AreEqual(threadHandle.Id, ret.Id, "The both thread id are equal."); 63 | } 64 | 65 | /// 66 | /// Converts a handle to a thread id. 67 | /// 68 | [TestMethod] 69 | public void HandleToThreadId() 70 | { 71 | // Arrange 72 | var threadHandle = Resources.MemorySharp.Threads.MainThread; 73 | 74 | // Act 75 | var ret = HandleManipulator.HandleToThreadId(threadHandle.Handle); 76 | 77 | // Assert 78 | Assert.AreEqual(threadHandle.Id, ret, "The both thread id are equal."); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /test/IntegrationTests/Helpers/SingletonTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Helpers; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace MemorySharpTests.Helpers 14 | { 15 | [TestClass] 16 | public class SingletonTests 17 | { 18 | /// 19 | /// Tests the singleton pattern implementation. 20 | /// 21 | [TestMethod] 22 | public void ReallySingleton() 23 | { 24 | Assert.AreSame(Singleton.Instance, Singleton.Instance); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /test/IntegrationTests/IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {E3EFE942-113F-46AA-9CF4-A51473D9E8B8} 7 | Library 8 | Properties 9 | MemorySharpTests 10 | MemorySharpTests 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 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 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | {78a6f97d-5ca8-4e92-8e17-2545983c9555} 81 | MemorySharp 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | False 92 | 93 | 94 | False 95 | 96 | 97 | False 98 | 99 | 100 | False 101 | 102 | 103 | 104 | 105 | 106 | 107 | 114 | -------------------------------------------------------------------------------- /test/IntegrationTests/Internals/MarshalTypeTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Internals; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace MemorySharpTests.Internals 14 | { 15 | [TestClass] 16 | public class MarshalTypeTests 17 | { 18 | /// 19 | /// Mashals a double object into an array of bytes. 20 | /// 21 | [TestMethod] 22 | public void ToByteArrayDoubleType() 23 | { 24 | // Arrange 25 | const double originalValue = 3.141592; 26 | var valueInBytes = BitConverter.GetBytes(originalValue); 27 | 28 | // Act 29 | var ret = MarshalType.ObjectToByteArray(originalValue); 30 | 31 | // Assert 32 | CollectionAssert.AreEqual(valueInBytes, ret, "Both variables aren't equal."); 33 | } 34 | 35 | /// 36 | /// Marshals a Point structure in and out a block of unmanaged memory. 37 | /// 38 | [TestMethod] 39 | public void ToManagedObjectPointStruct() 40 | { 41 | // Arrange 42 | var customStruct = Resources.CustomStruct; 43 | 44 | // Act 45 | var byteArray = MarshalType.ObjectToByteArray(customStruct); 46 | var customStruct2 = MarshalType.ByteArrayToObject(byteArray); 47 | 48 | // Assert 49 | Assert.AreEqual(customStruct, customStruct2, "Both structures are not equal."); 50 | } 51 | 52 | /// 53 | /// Converts a pointer to a long type. 54 | /// 55 | [TestMethod] 56 | public void PtrToObjectLong() 57 | { 58 | // Arrange 59 | var ptr = new IntPtr(32); 60 | 61 | // Act 62 | var value = MarshalType.PtrToObject(Resources.MemorySharp, ptr); 63 | 64 | // Assert 65 | Assert.AreEqual(32, value); 66 | } 67 | 68 | /// 69 | /// Converts a pointer to a structure. 70 | /// 71 | [TestMethod] 72 | public void PtrToObjectString() 73 | { 74 | // Arrange 75 | var point = Resources.CustomStruct; 76 | var sharp = Resources.MemorySharp; 77 | 78 | // Act 79 | using (var memory = sharp.Memory.Allocate(MarshalType.Size)) 80 | { 81 | memory.Write(point); 82 | var ret = MarshalType.PtrToObject(sharp, memory.BaseAddress); 83 | 84 | // Assert 85 | Assert.AreEqual(point, ret); 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /test/IntegrationTests/Internals/MarshalValueTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using Binarysharp.MemoryManagement.Internals; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace MemorySharpTests.Internals 13 | { 14 | [TestClass] 15 | public class MarshalValueTests 16 | { 17 | /// 18 | /// Marshals an integer. 19 | /// 20 | [TestMethod] 21 | public void MarshalInteger() 22 | { 23 | // Arrange 24 | var sharp = Resources.MemorySharp; 25 | const int value = 1024; 26 | 27 | // Act 28 | using (var pointer = MarshalValue.Marshal(sharp, value)) 29 | { 30 | // Assert 31 | Assert.AreEqual(value, pointer.Reference.ToInt32()); 32 | } 33 | 34 | Resources.EndTests(sharp); 35 | } 36 | 37 | /// 38 | /// Marshals a float. 39 | /// 40 | [TestMethod] 41 | public void MarshalFloat() 42 | { 43 | // Arrange 44 | var sharp = Resources.MemorySharp; 45 | const float value = 1024f; 46 | 47 | // Act 48 | using (var pointer = MarshalValue.Marshal(sharp, value)) 49 | { 50 | // Assert 51 | Assert.AreEqual(0x44800000, pointer.Reference.ToInt32()); 52 | } 53 | 54 | Resources.EndTests(sharp); 55 | } 56 | 57 | /// 58 | /// Marshals a boolean. 59 | /// 60 | [TestMethod] 61 | public void MarshalBoolean() 62 | { 63 | // Arrange 64 | var sharp = Resources.MemorySharp; 65 | const bool value = true; 66 | 67 | // Act 68 | using (var pointer = MarshalValue.Marshal(sharp, value)) 69 | { 70 | // Assert 71 | Assert.AreEqual(0x1, pointer.Reference.ToInt32()); 72 | } 73 | 74 | Resources.EndTests(sharp); 75 | } 76 | 77 | /// 78 | /// Marshals a char. 79 | /// 80 | [TestMethod] 81 | public void MarshalChar() 82 | { 83 | // Arrange 84 | var sharp = Resources.MemorySharp; 85 | const char value = 'A'; 86 | 87 | // Act 88 | using (var pointer = MarshalValue.Marshal(sharp, value)) 89 | { 90 | // Assert 91 | Assert.AreEqual(0x41, pointer.Reference.ToInt32()); 92 | } 93 | 94 | Resources.EndTests(sharp); 95 | } 96 | 97 | /// 98 | /// Marshals a byte. 99 | /// 100 | [TestMethod] 101 | public void MarshalByte() 102 | { 103 | // Arrange 104 | var sharp = Resources.MemorySharp; 105 | const byte value = 0x90; 106 | 107 | // Act 108 | using (var pointer = MarshalValue.Marshal(sharp, value)) 109 | { 110 | // Assert 111 | Assert.AreEqual(value, pointer.Reference.ToInt32()); 112 | } 113 | 114 | Resources.EndTests(sharp); 115 | } 116 | 117 | /// 118 | /// Marshals a custom structure. 119 | /// 120 | [TestMethod] 121 | public void Marshal_CustomStruct() 122 | { 123 | // Arrange 124 | var sharp = Resources.MemorySharp; 125 | var value = Resources.CustomStruct; 126 | 127 | // Act 128 | using (var pointer = MarshalValue.Marshal(sharp, value)) 129 | { 130 | 131 | // Assert 132 | Assert.AreEqual(Resources.CustomStruct.X, pointer.Allocated.Read(0)); 133 | Assert.AreEqual(Resources.CustomStruct.Y, pointer.Allocated.Read(4)); 134 | Assert.AreEqual(Resources.CustomStruct.Z, pointer.Allocated.Read(8)); 135 | } 136 | 137 | Resources.EndTests(sharp); 138 | } 139 | 140 | /// 141 | /// Marshals a string. 142 | /// 143 | [TestMethod] 144 | public void MarshalString() 145 | { 146 | // Arrange 147 | var sharp = Resources.MemorySharp; 148 | const string path = "If you read that, you're *really* like unit tests."; 149 | 150 | // Act 151 | using (var pointer = MarshalValue.Marshal(sharp, path)) 152 | { 153 | // Assert 154 | Assert.AreEqual(path, pointer.Allocated.ReadString(0)); 155 | } 156 | 157 | Resources.EndTests(sharp); 158 | } 159 | 160 | /// 161 | /// Marshals a short. 162 | /// 163 | [TestMethod] 164 | public void MarshalShort() 165 | { 166 | // Arrange 167 | var sharp = Resources.MemorySharp; 168 | const short value = 1024; 169 | 170 | // Act 171 | using (var pointer = MarshalValue.Marshal(sharp, value)) 172 | { 173 | // Assert 174 | Assert.AreEqual(value, pointer.Reference.ToInt32()); 175 | } 176 | 177 | Resources.EndTests(sharp); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /test/IntegrationTests/Memory/LocalUnmanagedMemoryTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement.Internals; 11 | using Binarysharp.MemoryManagement.Memory; 12 | using Microsoft.VisualStudio.TestTools.UnitTesting; 13 | 14 | namespace MemorySharpTests.Memory 15 | { 16 | [TestClass] 17 | public class LocalUnmanagedMemoryTests 18 | { 19 | /// 20 | /// Writes and reads a double value from unmanaged memory. 21 | /// 22 | [TestMethod] 23 | public void WriteAndReadDouble() 24 | { 25 | // Arrange 26 | const double originalValue = 3.141592; 27 | LocalUnmanagedMemory local; 28 | double ret; 29 | 30 | // Act 31 | using (local = new LocalUnmanagedMemory(MarshalType.Size)) 32 | { 33 | local.Write(originalValue); 34 | ret = local.Read(); 35 | } 36 | 37 | // Assert 38 | Assert.AreEqual(originalValue, ret, "Both values aren't equal."); 39 | Assert.AreEqual(IntPtr.Zero, local.Address); 40 | } 41 | 42 | /// 43 | /// Writes and reads a CustomStruct structure from unmanaged memory. 44 | /// 45 | [TestMethod] 46 | public void WriteAndReadCustomStruct() 47 | { 48 | // Arrange 49 | var customStruct = Resources.CustomStruct; 50 | LocalUnmanagedMemory local; 51 | Point ret; 52 | 53 | // Act 54 | using (local = new LocalUnmanagedMemory(MarshalType.Size)) 55 | { 56 | local.Write(customStruct); 57 | ret = local.Read(); 58 | } 59 | 60 | // Assert 61 | Assert.AreEqual(customStruct, ret, "Both structures aren't equal."); 62 | Assert.AreEqual(IntPtr.Zero, local.Address); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /test/IntegrationTests/Memory/MemoryCoreTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.ComponentModel; 11 | using System.Linq; 12 | using Binarysharp.MemoryManagement.Memory; 13 | using Binarysharp.MemoryManagement.Native; 14 | using Microsoft.VisualStudio.TestTools.UnitTesting; 15 | 16 | namespace MemorySharpTests.Memory 17 | { 18 | [TestClass] 19 | public class MemoryCoreTests 20 | { 21 | /// 22 | /// Allocates and free a memory page. 23 | /// 24 | [TestMethod] 25 | public void AllocateFree() 26 | { 27 | // Arrange 28 | var handle = MemoryCore.OpenProcess(ProcessAccessFlags.AllAccess, Resources.ProcessTest.Id); 29 | 30 | // Act 31 | try 32 | { 33 | var address = MemoryCore.Allocate(handle, 1); 34 | MemoryCore.Free(handle, address); 35 | } 36 | catch (Win32Exception ex) 37 | { 38 | Assert.Fail(ex.Message); 39 | } 40 | 41 | } 42 | 43 | /// 44 | /// Change the protection, writes and reads the first bytes of the memory. 45 | /// 46 | [TestMethod] 47 | public void VirtualProtectExWriteReadBytes() 48 | { 49 | // Arrange 50 | var handle = MemoryCore.OpenProcess(ProcessAccessFlags.AllAccess, Resources.ProcessTest.Id); 51 | var expected = new byte[] { 0x90, 0x90, 0x90, 0x90, 0x90 }; 52 | var memory = new IntPtr(0x00400000); 53 | 54 | // Act 55 | try 56 | { 57 | MemoryCore.ChangeProtection(handle, memory, 5, MemoryProtectionFlags.ExecuteReadWrite); 58 | MemoryCore.WriteBytes(handle, memory, expected); 59 | var actual = MemoryCore.ReadBytes(handle, memory, 5); 60 | 61 | // Assert 62 | CollectionAssert.AreEqual(expected, actual, "The collections are not equal."); 63 | } 64 | catch (Win32Exception ex) 65 | { 66 | Assert.Fail(ex.Message); 67 | } 68 | } 69 | 70 | /// 71 | /// List all memory regions. 72 | /// 73 | [TestMethod] 74 | public void VirtualQueryEx_AnyProcess_ListAllMemoryPages() 75 | { 76 | // Arrange 77 | var handle = Resources.MemorySharp.Handle; 78 | var starting = new IntPtr(0); 79 | var ending = new IntPtr(0x07fffffff); 80 | 81 | // Act 82 | var regions = MemoryCore.Query(handle, starting, ending); 83 | 84 | // Assert 85 | Assert.AreNotEqual(0, regions.Count(), "Memory pages cannot be gathered."); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /test/IntegrationTests/Memory/MemoryFactoryTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using Binarysharp.MemoryManagement.Memory; 12 | using Binarysharp.MemoryManagement.Native; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | 15 | namespace MemorySharpTests.Memory 16 | { 17 | [TestClass] 18 | public class MemoryFactoryTests 19 | { 20 | /// 21 | /// Gets all memory regions. 22 | /// 23 | [TestMethod] 24 | public void Regions_GetAllMemoryRegions() 25 | { 26 | // Arrange 27 | var sharp = Resources.MemorySharp; 28 | 29 | // Act 30 | var ret = sharp.Memory.Regions.ToArray(); 31 | 32 | // Assert 33 | Assert.IsTrue(ret.Any(), "The array of memory regions is empty."); 34 | Resources.EndTests(sharp); 35 | } 36 | 37 | /// 38 | /// Allocates 1MB of memory in the remote process. 39 | /// 40 | [TestMethod] 41 | public void Allocate_Allocate1MBMemoryRegion() 42 | { 43 | // Arrange 44 | var sharp = Resources.MemorySharp; 45 | const int size = 1024*1024; 46 | 47 | // Act 48 | var allocated = sharp.Memory.Allocate(size); 49 | // Fill the cave 50 | try 51 | { 52 | for (var i = 0; i < allocated.Information.RegionSize; i++) 53 | { 54 | allocated.Write(i, (byte)1); 55 | } 56 | } 57 | catch (Exception) 58 | { 59 | Assert.Fail("Cannot write into the memory."); 60 | } 61 | 62 | // Assert 63 | Assert.IsTrue(size - 4096 < allocated.Information.RegionSize && allocated.Information.RegionSize < size + 4096, "The allocated memory is wrong."); // 4096 = size of a page 64 | Assert.AreEqual(MemoryStateFlags.Commit, allocated.Information.State, "The state of the memory is incorrect."); 65 | Assert.AreEqual(MemoryProtectionFlags.ExecuteReadWrite, allocated.Information.Protect, "The protection of the memory is incorrect."); 66 | allocated.Dispose(); 67 | Resources.EndTests(sharp); 68 | } 69 | 70 | /// 71 | /// Allocates a chunk of memory using the keyword 'using'. 72 | /// 73 | [TestMethod] 74 | public void Allocate_WithUsingStatement() 75 | { 76 | // Arrange 77 | var sharp = Resources.MemorySharp; 78 | RemoteAllocation remoteAllocation; 79 | 80 | // Act 81 | using (remoteAllocation = sharp.Memory.Allocate(1)) 82 | { 83 | Assert.IsTrue(remoteAllocation.IsValid, "The chunk of memory couldn't be allocated."); 84 | Assert.AreEqual(4096, remoteAllocation.Information.RegionSize, "The chunk of memory doesn't have the default size of a page."); 85 | } 86 | 87 | // Assert 88 | Assert.IsFalse(remoteAllocation.IsValid, "The pointer is still valid."); 89 | Resources.EndTests(sharp); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /test/IntegrationTests/Memory/RemotePointerTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using Binarysharp.MemoryManagement; 11 | using Binarysharp.MemoryManagement.Native; 12 | using Microsoft.VisualStudio.TestTools.UnitTesting; 13 | 14 | namespace MemorySharpTests.Memory 15 | { 16 | [TestClass] 17 | public class RemotePointerTests 18 | { 19 | /// 20 | /// Checks the implementation of IEquatable. 21 | /// 22 | [TestMethod] 23 | public void Equality() 24 | { 25 | // Arrange 26 | var notepad = Resources.MemorySharp; 27 | var own = new MemorySharp(Resources.ProcessSelf); 28 | 29 | // Act 30 | var ptr1 = notepad[IntPtr.Zero]; 31 | var ptr2 = notepad[IntPtr.Zero]; 32 | var ptr3 = own[IntPtr.Zero]; 33 | 34 | // Assert 35 | Assert.AreEqual(ptr1, ptr2, "IEquatable is not properly implemented."); 36 | Assert.AreNotEqual(ptr2, ptr3, "IEquatable is not properly implemented."); 37 | } 38 | 39 | /// 40 | /// Changes the protection of a chunk of memory. 41 | /// 42 | [TestMethod] 43 | public void ChangeProtection() 44 | { 45 | // Arrange 46 | var sharp = Resources.MemorySharp; 47 | 48 | // Act 49 | // Allocate a chunk of memory for testing purpose 50 | using (var memory = sharp.Memory.Allocate(1)) 51 | { 52 | // Check we can write inside 53 | try 54 | { 55 | memory.Write(1); 56 | } 57 | catch (Exception) 58 | { 59 | Assert.Fail("Unable to write inside the chunk of memory (issue with memory allocation ?)."); 60 | } 61 | // Change the protection to read only 62 | using (var change = memory.ChangeProtection(MemoryProtectionFlags.ReadOnly)) 63 | { 64 | // Check we CANNOT write inside 65 | try 66 | { 67 | memory.Write(1); 68 | Assert.Fail("The memory mustn't be writable here."); 69 | } 70 | // ReSharper disable EmptyGeneralCatchClause 71 | catch 72 | // ReSharper restore EmptyGeneralCatchClause 73 | { 74 | // All is right 75 | } 76 | // Some asserts 77 | Assert.AreEqual(MemoryProtectionFlags.ExecuteReadWrite, change.OldProtection, "The old memory protection is wrong."); 78 | Assert.AreEqual(MemoryProtectionFlags.ReadOnly, change.NewProtection, "The new memory protection is wrong."); 79 | } 80 | // Check we can write inside 81 | try 82 | { 83 | memory.Write(1); 84 | } 85 | catch (Exception) 86 | { 87 | Assert.Fail("Unable to write inside the chunk of memory (issue with memory allocation ?)."); 88 | } 89 | } 90 | 91 | Resources.EndTests(sharp); 92 | } 93 | 94 | /// 95 | /// Executes some asm code. 96 | /// 97 | [TestMethod] 98 | public void Execute() 99 | { 100 | Resources.Restart(); 101 | // Arrange 102 | var sharp = Resources.MemorySharp; 103 | 104 | // Act 105 | // Allocate a chunk of memory for testing purpose 106 | using (var memory = sharp.Memory.Allocate(1)) 107 | { 108 | // Write some asm inside ! 109 | // MOV EAX, 0x66 110 | // RETN 111 | memory.Write(new byte[] { 0xB8, 0x66, 0x00, 0x00, 0x00, 0xC3 }); 112 | 113 | // Execute the asm code 114 | var ret = memory.Execute(); 115 | 116 | // Assert 117 | Assert.AreEqual(0x66, ret, "The return value is wrong."); 118 | } 119 | 120 | Resources.EndTests(sharp); 121 | } 122 | 123 | /// 124 | /// Executes asynchronously some asm code. 125 | /// 126 | [TestMethod] 127 | public void ExecuteAsync() 128 | { 129 | Resources.Restart(); 130 | // Arrange 131 | var sharp = Resources.MemorySharp; 132 | 133 | // Act 134 | // Allocate a chunk of memory for testing purpose 135 | using (var memory = sharp.Memory.Allocate(1)) 136 | { 137 | // Write some asm inside ! 138 | // MOV EAX, 0x66 139 | // RETN 140 | memory.Write(new byte[] { 0xB8, 0x66, 0x00, 0x00, 0x00, 0xC3 }); 141 | 142 | // Execute the asm code 143 | var ret = memory.ExecuteAsync(); 144 | 145 | // Assert 146 | Assert.AreEqual(0x66, ret.Result, "The return value is wrong."); 147 | } 148 | 149 | Resources.EndTests(sharp); 150 | } 151 | 152 | /// 153 | /// Writes and reads an integer. 154 | /// 155 | [TestMethod] 156 | public void WriteAndReadInteger() 157 | { 158 | // Arrange 159 | var sharp = Resources.MemorySharp; 160 | 161 | // Act 162 | // Allocate a chunk of memory for testing purpose 163 | using (var memory = sharp.Memory.Allocate(1)) 164 | { 165 | memory.Write(66); 166 | 167 | // Assert 168 | Assert.AreEqual(66, memory.Read(), "Error when the memory was writen/read."); 169 | } 170 | 171 | Resources.EndTests(sharp); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /test/IntegrationTests/Memory/RemoteRegionTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.Threading; 10 | using Binarysharp.MemoryManagement.Native; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace MemorySharpTests.Memory 14 | { 15 | [TestClass] 16 | public class RemoteRegionTests 17 | { 18 | /// 19 | /// Changes the protection of the main module and restores it. 20 | /// 21 | [TestMethod] 22 | public void ChangeProtection() 23 | { 24 | // Arrange 25 | var sharp = Resources.MemorySharp; 26 | 27 | // Act - Assert 28 | Resources.EndTests(sharp); 29 | Assert.AreEqual(MemoryProtectionFlags.ReadOnly, sharp.Modules.MainModule.Information.Protect, "The main module is not in readonly."); 30 | using (sharp.Modules.MainModule.ChangeProtection(MemoryProtectionFlags.ExecuteRead)) 31 | { 32 | Assert.AreEqual(MemoryProtectionFlags.ExecuteRead, sharp.Modules.MainModule.Information.Protect, "The main module protection couldn't be changed."); 33 | } 34 | Assert.AreEqual(MemoryProtectionFlags.ReadOnly, sharp.Modules.MainModule.Information.Protect, "The main module is not in readonly (2)."); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/IntegrationTests/MemorySharp.licenseheader: -------------------------------------------------------------------------------- 1 | extensions: designer.cs generated.cs 2 | extensions: .cs .cpp .h 3 | /* 4 | * MemorySharp Library 5 | * http://www.binarysharp.com/ 6 | * 7 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 8 | * This library is released under the MIT License. 9 | * See the file LICENSE for more information. 10 | */ -------------------------------------------------------------------------------- /test/IntegrationTests/Modules/ModuleCoreTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.ComponentModel; 10 | using System.Diagnostics; 11 | using System.Linq; 12 | using Binarysharp.MemoryManagement.Modules; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | 15 | namespace MemorySharpTests.Modules 16 | { 17 | [TestClass] 18 | public class ModuleCoreTests 19 | { 20 | /// 21 | /// Loads and frees a library. 22 | /// 23 | [TestMethod] 24 | public void LoadFreeLibrary() 25 | { 26 | // Arrange 27 | var dllPath = Resources.LibraryTest; 28 | 29 | // Act 30 | var module = ModuleCore.LoadLibrary(dllPath); 31 | 32 | // Assert 33 | Assert.AreEqual(module.FileName, dllPath, "The module cannot be loaded correctly."); 34 | Assert.IsTrue(Resources.ProcessSelf.Modules.Cast().Any(m => m.FileName == dllPath), "The module cannot be found."); 35 | 36 | // Act 2 37 | ModuleCore.FreeLibrary(module); 38 | 39 | // Assert 2 40 | Assert.IsFalse(Resources.ProcessSelf.Modules.Cast().Any(m => m.FileName == dllPath), "The module cannot be freed."); 41 | } 42 | 43 | /// 44 | /// Gets the pointer of MessageBoxW function from Win32 API. 45 | /// 46 | [TestMethod] 47 | public void GetProcAddressMessageBoxW() 48 | { 49 | // Arrange 50 | const string moduleName = "User32.dll"; 51 | const string functionName = "MessageBoxW"; 52 | 53 | // Act 54 | try 55 | { 56 | ModuleCore.GetProcAddress(moduleName, functionName); 57 | } 58 | // Assert 59 | catch (Win32Exception ex) 60 | { 61 | Assert.Fail(ex.Message); 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /test/IntegrationTests/Modules/ModuleFactoryTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Diagnostics; 11 | using System.Linq; 12 | using System.Threading; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | 15 | namespace MemorySharpTests.Modules 16 | { 17 | [TestClass] 18 | public class ModuleFactoryTests 19 | { 20 | /// 21 | /// Gets all modules and check the difference with the native API. 22 | /// 23 | [TestMethod] 24 | public void Modules() 25 | { 26 | // Arrange 27 | var sharp = Resources.MemorySharp; 28 | 29 | // Act 30 | var modules = sharp.Modules.RemoteModules.ToArray(); 31 | 32 | // Assert 33 | Assert.AreEqual(Resources.ProcessTest.Modules.Count, modules.Length, "The number of modules doesn't match."); 34 | } 35 | 36 | /// 37 | /// Verifies the MainModule property. 38 | /// 39 | [TestMethod] 40 | public void MainModule() 41 | { 42 | // Arrange 43 | var process = Resources.ProcessTest; 44 | var memorySharp = Resources.MemorySharp; 45 | 46 | // Act 47 | var mainModule = memorySharp.Modules.MainModule; 48 | 49 | // Assert 50 | Assert.AreEqual(process.MainModule.BaseAddress, mainModule.Native.BaseAddress, "Both modules aren't equal."); 51 | } 52 | 53 | /// 54 | /// Injects and ejects a library. 55 | /// 56 | [TestMethod] 57 | public void InjectEjectLibrary() 58 | { 59 | Resources.Restart(); 60 | // Arrange 61 | var sharp = Resources.MemorySharp; 62 | var dllPath = Resources.LibraryTest; 63 | 64 | // Act 65 | using (var lib = sharp.Modules.Inject(dllPath)) 66 | { 67 | // Assert 68 | Assert.AreNotEqual(IntPtr.Zero, lib.BaseAddress, "The library couldn't be loaded properly."); 69 | Assert.IsTrue(sharp.Modules.InjectedModules.Any(m => m == lib), "The collection of injected modules doesn't contain the module."); 70 | Assert.IsTrue(Resources.ProcessTest.Modules.Cast().Any(m => m.FileName.ToLower() == dllPath.ToLower()), "Cannot find the module using native API."); 71 | } 72 | 73 | Resources.EndTests(sharp); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /test/IntegrationTests/Modules/RemoteModuleTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using Binarysharp.MemoryManagement; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace MemorySharpTests.Modules 13 | { 14 | [TestClass] 15 | public class RemoteModuleTests 16 | { 17 | /// 18 | /// Finds the Beep function in a module loaded in the remote process. 19 | /// 20 | [TestMethod] 21 | public void FindFunctionInModuleAlreadyLoaded() 22 | { 23 | // Arrange 24 | var memorysharp = Resources.MemorySharp; 25 | 26 | // Act 27 | var ret = memorysharp.Modules["kernel32.dll"].FindFunction("Beep"); 28 | 29 | // Assert 30 | Assert.IsTrue(ret != null && ret.Name == "Beep"); 31 | } 32 | 33 | /// 34 | /// Finds the Beep function in a module loaded in the remote process and checks the module cache. 35 | /// 36 | [TestMethod] 37 | public void FindFunctionCheckCachedFunctions() 38 | { 39 | // Arrange 40 | var memorysharp = Resources.MemorySharp; 41 | 42 | // Act 43 | var func1 = memorysharp.Modules["kernel32.dll"].FindFunction("Beep"); 44 | var func2 = memorysharp.Modules["kernel32.dll"].FindFunction("Beep"); 45 | 46 | // Assert 47 | Assert.AreSame(func1, func2, "The cache does not work properly."); 48 | } 49 | 50 | /// 51 | /// Finds the a function in a module loaded in the remote process but not in the calling process. 52 | /// 53 | [TestMethod] 54 | public void FindFunctionInModuleNotLoaded() 55 | { 56 | // Arrange 57 | var memorysharp = Resources.MemorySharp; 58 | 59 | // Act 60 | var ret = memorysharp.Modules["SciLexer.dll"].FindFunction("Scintilla_DirectFunction"); 61 | 62 | // Assert 63 | Assert.IsTrue(ret != null && ret.Name == "Scintilla_DirectFunction"); 64 | } 65 | 66 | /// 67 | /// Checks if the implementation of IEquatable interface. 68 | /// 69 | [TestMethod] 70 | public void Equals() 71 | { 72 | // Arrange 73 | var remote = Resources.MemorySharp; 74 | var own = new MemorySharp(Resources.ProcessSelf); 75 | 76 | // Act 77 | var module1 = remote["kernel32"]; 78 | var module2 = remote["kernel32"]; 79 | var module3 = own["kernel32"]; 80 | 81 | // Assert 82 | Assert.AreEqual(module1, module2); 83 | Assert.AreNotEqual(module1, module3); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /test/IntegrationTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.Reflection; 10 | using System.Runtime.CompilerServices; 11 | using System.Runtime.InteropServices; 12 | 13 | // General Information about an assembly is controlled through the following 14 | // set of attributes. Change these attribute values to modify the information 15 | // associated with an assembly. 16 | [assembly: AssemblyTitle("MemorySharpTests")] 17 | [assembly: AssemblyDescription("")] 18 | [assembly: AssemblyConfiguration("")] 19 | [assembly: AssemblyCompany("")] 20 | [assembly: AssemblyProduct("MemorySharpTests")] 21 | [assembly: AssemblyCopyright("Copyright © 2013")] 22 | [assembly: AssemblyTrademark("")] 23 | [assembly: AssemblyCulture("")] 24 | 25 | // Setting ComVisible to false makes the types in this assembly not visible 26 | // to COM components. If you need to access a type in this assembly from 27 | // COM, set the ComVisible attribute to true on that type. 28 | [assembly: ComVisible(false)] 29 | 30 | // The following GUID is for the ID of the typelib if this project is exposed to COM 31 | [assembly: Guid("a5111a24-9394-4795-bb07-30c8e1598cd9")] 32 | 33 | // Version information for an assembly consists of the following four values: 34 | // 35 | // Major Version 36 | // Minor Version 37 | // Build Number 38 | // Revision 39 | // 40 | // You can specify all the values or you can default the Build and Revision Numbers 41 | // by using the '*' as shown below: 42 | // [assembly: AssemblyVersion("1.0.*")] 43 | [assembly: AssemblyVersion("1.0.0.0")] 44 | [assembly: AssemblyFileVersion("1.0.0.0")] 45 | -------------------------------------------------------------------------------- /test/IntegrationTests/README.md: -------------------------------------------------------------------------------- 1 | # MemorySharp # 2 | 3 | ## Unit tests ## 4 | 5 | These unit tests must be launched while the software [Notepad++](http://notepad-plus-plus.org "Notepad++") is running. The latest sucessful test was run with the version **6.3.3**. 6 | 7 | When the unit tests are performing, please do NOT touch your computer, it can fail some ones. 8 | 9 | ## Getting started ## 10 | 11 | 1. Open your favourite tool to perform unit tests (Visual Studio recommended) 12 | 2. Run Notepad++ with no document opened 13 | 3. Launch the unit tests 14 | 4. Do NOT touch your computer until the tests are terminated 15 | 5. Report the errors to the author 16 | 17 | ~ ZenLulz -------------------------------------------------------------------------------- /test/IntegrationTests/Resources.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System.IO; 10 | using System.Runtime.InteropServices; 11 | using System.Threading; 12 | using Binarysharp.MemoryManagement; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | using System; 15 | using System.Diagnostics; 16 | using System.Linq; 17 | 18 | namespace MemorySharpTests 19 | { 20 | internal static class Resources 21 | { 22 | /// 23 | /// Static constructor. 24 | /// 25 | static Resources() 26 | { 27 | if(ProcessTest == null) 28 | throw new Exception("You probably forgot to launch the test process."); 29 | _path = ProcessTest.MainModule.FileName; 30 | } 31 | 32 | /// 33 | /// The path of the test process. 34 | /// 35 | private static readonly string _path; 36 | 37 | /// 38 | /// A new instance of the structure. 39 | /// 40 | internal static Point CustomStruct 41 | { 42 | get { return new Point { X = 4, Y = 5, Z = 6 }; } 43 | } 44 | 45 | /// 46 | /// Provides the path of a test library (dll). 47 | /// 48 | internal static string LibraryTest 49 | { 50 | get 51 | { 52 | return Path.Combine(Environment.SystemDirectory, "apphelp.dll"); 53 | } 54 | } 55 | 56 | /// 57 | /// A new instance of the class. 58 | /// 59 | internal static MemorySharp MemorySharp 60 | { 61 | get 62 | { 63 | return new MemorySharp(ProcessTest); 64 | } 65 | } 66 | 67 | /// 68 | /// The process itself. 69 | /// 70 | internal static Process ProcessSelf 71 | { 72 | get { return Process.GetCurrentProcess(); } 73 | } 74 | 75 | /// 76 | /// The process used for tests. 77 | /// 78 | internal static Process ProcessTest 79 | { 80 | get 81 | { 82 | return Process.GetProcessesByName("notepad++").FirstOrDefault(); 83 | } 84 | } 85 | 86 | /// 87 | /// Performs the ending tests. 88 | /// 89 | internal static void EndTests(MemorySharp memorySharp) 90 | { 91 | Assert.AreEqual(0, memorySharp.Memory.RemoteAllocations.Count()); 92 | Assert.AreEqual(0, memorySharp.Modules.InjectedModules.Count()); 93 | } 94 | 95 | /// 96 | /// Restart the test process. 97 | /// 98 | internal static void Restart() 99 | { 100 | // Kill the process 101 | if (ProcessTest != null) 102 | ProcessTest.Kill(); 103 | // Start it 104 | Process.Start(_path); 105 | Thread.Sleep(2000); 106 | } 107 | } 108 | 109 | /// 110 | /// A sample test structure. 111 | /// 112 | [StructLayout(LayoutKind.Sequential)] 113 | public struct Point : IEquatable 114 | { 115 | public int X; 116 | public int Y; 117 | public int Z; 118 | 119 | #region Equality methods 120 | public override bool Equals(object obj) 121 | { 122 | if (ReferenceEquals(null, obj)) return false; 123 | return obj is Point && Equals((Point)obj); 124 | } 125 | 126 | public bool Equals(Point other) 127 | { 128 | return X == other.X && Y == other.Y && Z == other.Z; 129 | } 130 | 131 | public override int GetHashCode() 132 | { 133 | return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); 134 | } 135 | 136 | public static bool operator ==(Point left, Point right) 137 | { 138 | return left.Equals(right); 139 | } 140 | 141 | public static bool operator !=(Point left, Point right) 142 | { 143 | return !left.Equals(right); 144 | } 145 | #endregion 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /test/IntegrationTests/Threading/RemoteThreadTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using System.Threading; 12 | using Binarysharp.MemoryManagement.Native; 13 | using Binarysharp.MemoryManagement.Threading; 14 | using Microsoft.VisualStudio.TestTools.UnitTesting; 15 | 16 | namespace MemorySharpTests.Threading 17 | { 18 | [TestClass] 19 | public class RemoteThreadTests 20 | { 21 | /// 22 | /// Suspends and resumes the main thread. 23 | /// 24 | [TestMethod] 25 | public void SuspendResumeMainThread() 26 | { 27 | // Arrange 28 | var sharp = Resources.MemorySharp; 29 | var thread = sharp.Threads.MainThread; 30 | 31 | // Act - Assert 32 | thread.Suspend(); 33 | Assert.IsTrue(thread.IsSuspended, "The thread is not suspended."); 34 | thread.Resume(); 35 | Assert.IsFalse(thread.IsSuspended, "The thread is still suspended."); 36 | using (thread.Suspend()) 37 | { 38 | Assert.IsTrue(thread.IsSuspended, "The thread is not suspended (2)."); 39 | } 40 | Assert.IsFalse(thread.IsSuspended, "The thread is still suspended (2)."); 41 | } 42 | 43 | /// 44 | /// Kill a main thread. 45 | /// 46 | [TestMethod] 47 | public void TerminateMainThread() 48 | { 49 | // Arrange 50 | var sharp = Resources.MemorySharp; 51 | var thread = sharp.Threads.MainThread; 52 | 53 | // Act - Assert 54 | Assert.IsTrue(thread.IsAlive); 55 | thread.Terminate(); 56 | Thread.Sleep(1000); 57 | Assert.IsTrue(thread.IsTerminated); 58 | 59 | Resources.Restart(); 60 | } 61 | 62 | /// 63 | /// Gets the context of the main thread. 64 | /// 65 | [TestMethod] 66 | public void GetContextMainThread() 67 | { 68 | // Arrange 69 | var sharp = Resources.MemorySharp; 70 | 71 | // Act 72 | var context = sharp.Threads.MainThread.Context; 73 | 74 | // Assert 75 | Assert.AreNotEqual(0, context.Eip); 76 | } 77 | 78 | /// 79 | /// Gets all segment addresses of the main thread. 80 | /// 81 | [TestMethod] 82 | public void GetRealSegmentAddress_GetAllSegmentsMainThread() 83 | { 84 | // Arrange 85 | var sharp = Resources.MemorySharp; 86 | 87 | // Act 88 | var thread = sharp.Threads.MainThread; 89 | var fs = thread.GetRealSegmentAddress(SegmentRegisters.Fs); 90 | 91 | // Assert. 92 | Assert.AreNotEqual(IntPtr.Zero, fs, "The FS segment is null."); 93 | } 94 | 95 | /// 96 | /// Copies the TlsSlots from a thread to the main one by erasing them (YEAH, it's a bit evil :D). 97 | /// 98 | [TestMethod] 99 | public void TebTlsSlots_CopyTlsFromAnotherThread() 100 | { 101 | // Arrange 102 | var sharp = Resources.MemorySharp; 103 | var t1 = sharp.Threads.MainThread; 104 | var t2 = sharp.Threads.RemoteThreads.Last(); 105 | var values = new[] { new IntPtr(0x1123344), new IntPtr(0x55667788) }; 106 | 107 | // Act 108 | // Write identifiable data 109 | t2.Teb.TlsSlots = values; 110 | // Erase main tls :O 111 | t1.Teb.TlsSlots = t2.Teb.TlsSlots; 112 | 113 | // Assert 114 | Assert.AreEqual(values[0], t1.Teb.TlsSlots[0], "Couldn't read/write TLS."); 115 | Assert.AreEqual(values[1], t1.Teb.TlsSlots[1], "Couldn't read/write TLS (2)."); 116 | 117 | Resources.Restart(); 118 | } 119 | 120 | /// 121 | /// [No Assert] Changes the EIP register. 122 | /// 123 | [TestMethod] 124 | public void SuspendResumeSetContextEip() 125 | { 126 | // Arrange 127 | var sharp = Resources.MemorySharp; 128 | var sharp2 = Resources.MemorySharp; 129 | var thread = sharp.Threads.MainThread; 130 | const uint value = 0x666; 131 | 132 | // Act 133 | using (thread.Suspend()) 134 | { 135 | // Get the original value 136 | var original = thread.Context; 137 | // Set the value 138 | var context = thread.Context; 139 | context.Eip = value; 140 | sharp.Threads.MainThread.Context = context; 141 | 142 | // Assert 143 | Assert.AreEqual(sharp2.Threads.MainThread.Context.Eip, thread.Context.Eip, "The values are not equal."); 144 | 145 | // Set the origial value back 146 | thread.Context = original; 147 | } 148 | } 149 | 150 | /// 151 | /// Waits on the main thread during 3 seconds or until it terminates.. 152 | /// 153 | [TestMethod] 154 | public void Join3SecMainThread() 155 | { 156 | // Arrange 157 | var sharp = Resources.MemorySharp; 158 | 159 | // Act 160 | var ret = sharp.Threads.MainThread.Join(TimeSpan.FromSeconds(3)); 161 | 162 | // Assert 163 | Assert.AreEqual(WaitValues.Timeout, ret); 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /test/IntegrationTests/Threading/ThreadCoreTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.ComponentModel; 11 | using System.Diagnostics; 12 | using System.Linq; 13 | using System.Threading; 14 | using System.Threading.Tasks; 15 | using Binarysharp.MemoryManagement.Helpers; 16 | using Binarysharp.MemoryManagement.Memory; 17 | using Binarysharp.MemoryManagement.Native; 18 | using Binarysharp.MemoryManagement.Threading; 19 | using Microsoft.VisualStudio.TestTools.UnitTesting; 20 | 21 | namespace MemorySharpTests.Threading 22 | { 23 | [TestClass] 24 | public class ThreadCoreTests 25 | { 26 | /// 27 | /// Suspends and restores the main thread. 28 | /// 29 | [TestMethod] 30 | public void SuspendRestore() 31 | { 32 | // Arrange 33 | var threadHandle = ThreadCore.OpenThread(ThreadAccessFlags.SuspendResume, Resources.ProcessTest.Threads[0].Id); 34 | 35 | // Act 36 | try 37 | { 38 | var retSuspend = ThreadCore.SuspendThread(threadHandle); 39 | var retResume = ThreadCore.ResumeThread(threadHandle); 40 | 41 | // Assert 42 | Assert.AreEqual((uint)0, retSuspend); 43 | Assert.AreEqual((uint)1, retResume); 44 | } 45 | catch (Win32Exception ex) 46 | { 47 | Assert.Fail(ex.Message); 48 | } 49 | } 50 | 51 | /// 52 | /// Terminates the main thread. 53 | /// 54 | [TestMethod] 55 | public void Terminate() 56 | { 57 | // Arrange 58 | var handle = ThreadCore.OpenThread(ThreadAccessFlags.Terminate, Resources.ProcessTest.Threads[0].Id); 59 | var threadId = Resources.ProcessTest.Threads[0].Id; 60 | 61 | // Act 62 | try 63 | { 64 | ThreadCore.TerminateThread(handle, 0); 65 | } 66 | // Assert 67 | catch (Win32Exception ex) 68 | { 69 | Assert.Fail(ex.Message); 70 | } 71 | Resources.ProcessTest.Refresh(); 72 | Assert.AreNotEqual(threadId, Resources.ProcessTest.Threads[0].Id, "The main thread was not properly killed."); 73 | Resources.Restart(); 74 | } 75 | 76 | /// 77 | /// Creates an suspended remote thread. 78 | /// 79 | [TestMethod] 80 | public void CreateRemoteThread() 81 | { 82 | // Arrange 83 | var handle = MemoryCore.OpenProcess(ProcessAccessFlags.AllAccess, Resources.ProcessTest.Id); 84 | 85 | // Act 86 | var thread = ThreadCore.CreateRemoteThread(handle, new IntPtr(1), IntPtr.Zero ,ThreadCreationFlags.Suspended); 87 | var threadId = HandleManipulator.HandleToThreadId(thread); 88 | 89 | // Assert 90 | Assert.IsFalse(thread.IsInvalid); 91 | Assert.IsTrue(Resources.ProcessTest.Threads.Cast().Any(t => t.Id == threadId)); 92 | } 93 | 94 | /// 95 | /// Gets main thread context of the process test 96 | /// 97 | [TestMethod] 98 | public void GetSetThreadContextSuspendResume() 99 | { 100 | // Arrange 101 | var handle = ThreadCore.OpenThread(ThreadAccessFlags.AllAccess, Resources.ProcessTest.Threads[0].Id); 102 | 103 | // Act 104 | try 105 | { 106 | ThreadCore.SuspendThread(handle); 107 | 108 | // Get the context 109 | var original = ThreadCore.GetThreadContext(handle); 110 | var modified = original; 111 | 112 | Assert.AreNotEqual(0, modified.Eip); 113 | 114 | // Set a value to eax 115 | modified.Eax = 0x666; 116 | // Set the context 117 | ThreadCore.SetThreadContext(handle, modified); 118 | // Re-get the context to check if it's all right 119 | modified = ThreadCore.GetThreadContext(handle); 120 | 121 | Assert.AreEqual((uint)0x666, modified.Eax); 122 | 123 | // Restore the original context 124 | ThreadCore.SetThreadContext(handle, original); 125 | } 126 | finally 127 | { 128 | ThreadCore.ResumeThread(handle); 129 | } 130 | } 131 | 132 | /// 133 | /// Waits for the end of the main thread. 134 | /// 135 | [TestMethod] 136 | public void WaitForSingleObject() 137 | { 138 | // Arrange 139 | var handle = ThreadCore.OpenThread(ThreadAccessFlags.Synchronize, Resources.ProcessTest.Threads[0].Id); 140 | 141 | // Act 142 | var task = new Task(() => ThreadCore.WaitForSingleObject(handle)); 143 | task.Start(); 144 | Resources.Restart(); 145 | 146 | // Assert 147 | Assert.AreEqual(WaitValues.Signaled, task.Result); 148 | } 149 | 150 | /// 151 | /// Gets the exit code of the main thread. 152 | /// 153 | [TestMethod] 154 | public void GetExitCodeThread() 155 | { 156 | // Arrange 157 | var handle = ThreadCore.OpenThread(ThreadAccessFlags.QueryInformation | ThreadAccessFlags.Terminate, Resources.ProcessTest.Threads[0].Id); 158 | 159 | // Act 160 | var exitCodeBefore = ThreadCore.GetExitCodeThread(handle); 161 | // Exit the application 162 | ThreadCore.TerminateThread(handle, 1337); 163 | // Wait the process is terminating 164 | Thread.Sleep(2000); 165 | // Check the exit code 166 | var exitCodeAfter = ThreadCore.GetExitCodeThread(handle); 167 | 168 | // Assert 169 | Assert.AreEqual(null, exitCodeBefore); 170 | Assert.AreEqual((IntPtr)1337, exitCodeAfter, "The exit code didn't match to the expected value."); 171 | 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /test/IntegrationTests/Threading/ThreadFactoryTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace MemorySharpTests.Threading 14 | { 15 | [TestClass] 16 | public class ThreadFactoryTests 17 | { 18 | /// 19 | /// Creates a remote thread. 20 | /// 21 | [TestMethod] 22 | public void CreateThread() 23 | { 24 | // Arrange 25 | var sharp = Resources.MemorySharp; 26 | 27 | // Act 28 | var thread = sharp.Threads.Create(new IntPtr(1), false); 29 | 30 | // Assert 31 | Assert.IsTrue(sharp.Threads.RemoteThreads.Any(t => t.Id == thread.Id)); 32 | } 33 | 34 | /// 35 | /// Gets the main thread by its id. 36 | /// 37 | [TestMethod] 38 | public void GetThreadById() 39 | { 40 | // Arrange 41 | var sharp = Resources.MemorySharp; 42 | var mainThread = Resources.ProcessTest.Threads[0]; 43 | 44 | // Act 45 | var mainThread2 = sharp.Threads.GetThreadById(mainThread.Id); 46 | 47 | // Assert 48 | Assert.AreEqual(mainThread.Id, mainThread2.Id, "Cannot get the main thread properly."); 49 | } 50 | 51 | /// 52 | /// Retrieves remote threads. 53 | /// 54 | [TestMethod] 55 | public void RemoteThreadsAny() 56 | { 57 | // Arrange 58 | var sharp = Resources.MemorySharp; 59 | 60 | // Act 61 | var ret = sharp.Threads.RemoteThreads.ToArray(); 62 | 63 | // Assert 64 | Assert.IsTrue(ret.Any(), "Cannot gather remote threads."); 65 | Assert.AreEqual(Resources.ProcessTest.Threads.Count, ret.Count(), "The number of thread does not match."); 66 | } 67 | 68 | /// 69 | /// Suspends and resumes all the threads. 70 | /// 71 | [TestMethod] 72 | public void SuspenAllResumeAll() 73 | { 74 | // Arrange 75 | var sharp = Resources.MemorySharp; 76 | 77 | // Act - Assert 78 | sharp.Threads.SuspendAll(); 79 | Assert.IsFalse(sharp.Threads.RemoteThreads.Any(t => !t.IsSuspended), "A thread is not suspended."); 80 | sharp.Threads.ResumeAll(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /test/IntegrationTests/Windows/KeyboardTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using System.Threading; 12 | using Binarysharp.MemoryManagement.Native; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | 15 | namespace MemorySharpTests.Windows 16 | { 17 | [TestClass] 18 | public class KeyboardTests 19 | { 20 | /// 21 | /// Presses and releases the bottom arrow key during 3 seconds in Scintilla. 22 | /// 23 | /// Manual assert. 24 | [TestMethod] 25 | public void ArrowBottom3Sec() 26 | { 27 | // Arrange 28 | var scintilla = Resources.MemorySharp.Windows.GetWindowsByClassName("Scintilla").First(); 29 | 30 | // Act 31 | scintilla.Keyboard.Press(Keys.Down, TimeSpan.FromMilliseconds(20)); 32 | Thread.Sleep(3000); 33 | scintilla.Keyboard.Release(Keys.Down); 34 | 35 | // Assert 36 | Assert.Inconclusive("Manual assert"); 37 | } 38 | 39 | /// 40 | /// Presses and releases the key F1. 41 | /// 42 | /// Manual assert. 43 | [TestMethod] 44 | public void PostKey_MainWindow() 45 | { 46 | // Arrange 47 | var window = Resources.MemorySharp.Windows.MainWindow; 48 | 49 | // Act 50 | window.Keyboard.PressRelease(Keys.F1); 51 | 52 | // Assert 53 | Assert.Inconclusive("Manual assert"); 54 | } 55 | 56 | /// 57 | /// Writes a text in Scintilla. 58 | /// 59 | /// Manual assert. 60 | [TestMethod] 61 | public void WriteText() 62 | { 63 | // Arrange 64 | var scintilla = Resources.MemorySharp.Windows.GetWindowsByClassName("Scintilla").First(); 65 | 66 | // Act 67 | scintilla.Keyboard.Write(""); 68 | 69 | // Assert 70 | Assert.Inconclusive("Manual assert"); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /test/IntegrationTests/Windows/RemoteWindowTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using System.Threading; 12 | using Binarysharp.MemoryManagement.Native; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | 15 | namespace MemorySharpTests.Windows 16 | { 17 | [TestClass] 18 | public class RemoteWindowTests 19 | { 20 | /// 21 | /// Gets the children of the main window and checks if Scintilla is there. 22 | /// 23 | [TestMethod] 24 | public void ChildrenAndClassName() 25 | { 26 | // Arrange 27 | var sharp = Resources.MemorySharp; 28 | 29 | // Act 30 | var window = sharp.Windows.MainWindow.Children.FirstOrDefault(w => w.ClassName == "Scintilla"); 31 | 32 | // Assert 33 | Assert.AreNotEqual(null, window, "Cannot find Scintilla window."); 34 | } 35 | 36 | /// 37 | /// Gets and sets the height and the width. 38 | /// 39 | [TestMethod] 40 | public void GetSetHeightWidthPosition() 41 | { 42 | // Arrange 43 | var window = Resources.MemorySharp.Windows.MainWindow; 44 | const int size = 200; 45 | 46 | // Act 47 | window.Height = size; 48 | window.Width = size; 49 | window.X = size; 50 | window.Y = size; 51 | var height = window.Height; 52 | var width = window.Width; 53 | var x = window.X; 54 | var y = window.Y; 55 | 56 | // Assert 57 | Assert.AreEqual(size, height, "The height cannot be got/set."); 58 | Assert.AreEqual(size, width, "The width cannot be got/set."); 59 | Assert.AreEqual(size, x, "The X-coordinate cannot be got/set."); 60 | Assert.AreEqual(size, y, "The Y-coordinate cannot be got/set."); 61 | } 62 | 63 | /// 64 | /// Activates the window. 65 | /// 66 | [TestMethod] 67 | public void ActivateAndIsActivated() 68 | { 69 | // Arrange 70 | var window = Resources.MemorySharp.Windows.MainWindow; 71 | 72 | // Act 73 | window.Activate(); 74 | Thread.Sleep(1000); 75 | var ret = window.IsActivated; 76 | 77 | // Assert 78 | Assert.AreEqual(true, ret, "The window is not activated."); 79 | } 80 | 81 | /// 82 | /// Gets and sets the state of the window. 83 | /// 84 | [TestMethod] 85 | public void GetSetState() 86 | { 87 | // Arrange 88 | var window = Resources.MemorySharp.Windows.MainWindow; 89 | 90 | // Act 91 | window.State = WindowStates.ShowMinimized; 92 | var ret = window.State; 93 | 94 | // Assert 95 | Assert.AreEqual(WindowStates.ShowMinimized, ret, "The window is not minimized."); 96 | } 97 | 98 | /// 99 | /// Get and sets the title. 100 | /// 101 | [TestMethod] 102 | public void Title() 103 | { 104 | // Arrange 105 | var window = Resources.MemorySharp.Windows.MainWindow; 106 | const string title = "I love cookies"; 107 | 108 | // Act 109 | window.Title = title; 110 | var ret = window.Title; 111 | 112 | // Assert 113 | Assert.AreEqual(title, ret, "The title cannot be got/set."); 114 | Resources.Restart(); 115 | } 116 | 117 | /// 118 | /// Closes the test process. 119 | /// 120 | [TestMethod] 121 | public void Close() 122 | { 123 | // Arrange 124 | var sharp = Resources.MemorySharp; 125 | 126 | // Act 127 | sharp.Windows.MainWindow.Close(); 128 | Thread.Sleep(2000); 129 | 130 | // Assert 131 | Assert.IsTrue(sharp.IsRunning, "The process is not closed."); 132 | Resources.Restart(); 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /test/IntegrationTests/Windows/WindowsFactoryTests.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * MemorySharp Library 3 | * http://www.binarysharp.com/ 4 | * 5 | * Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz). 6 | * This library is released under the MIT License. 7 | * See the file LICENSE for more information. 8 | */ 9 | using System; 10 | using System.Linq; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace MemorySharpTests.Windows 14 | { 15 | [TestClass] 16 | public class WindowsFactoryTests 17 | { 18 | /// 19 | /// Gets the child windows of the test process. 20 | /// 21 | [TestMethod] 22 | public void ChildWindows() 23 | { 24 | // Arrange 25 | var sharp = Resources.MemorySharp; 26 | 27 | // Act 28 | var windows = sharp.Windows.ChildWindows; 29 | 30 | // Assert 31 | Assert.IsTrue(windows.Any(w => w.ClassName == "Scintilla"), "Cannot find Scintilla (or it's not Notepad++)."); 32 | } 33 | 34 | /// 35 | /// Gets the windows of the test process. 36 | /// 37 | [TestMethod] 38 | public void Windows() 39 | { 40 | // Arrange 41 | var sharp = Resources.MemorySharp; 42 | 43 | // Act 44 | var windows = sharp.Windows.RemoteWindows; 45 | 46 | // Assert 47 | Assert.IsTrue(windows.Any(w => w.ClassName == "Scintilla"), "Cannot find Scintilla (or it's not Notepad++)."); 48 | } 49 | 50 | /// 51 | /// Gets windows by their class name. 52 | /// 53 | [TestMethod] 54 | public void GetWindowByClassName() 55 | { 56 | // Arrange 57 | var sharp = Resources.MemorySharp; 58 | 59 | // Act 60 | var windows = sharp.Windows.GetWindowsByClassName("Scintilla"); 61 | 62 | // Assert 63 | Assert.IsTrue(windows.Any(), "Cannot find Scintilla (or it's not Notepad++)."); 64 | } 65 | 66 | /// 67 | /// Gets windows by a part of their title. 68 | /// 69 | [TestMethod] 70 | public void GetWindowByTitleContains() 71 | { 72 | // Arrange 73 | var sharp = Resources.MemorySharp; 74 | 75 | // Act 76 | var windows = sharp.Windows.GetWindowsByTitleContains("Notepad++"); 77 | 78 | // Assert 79 | Assert.IsTrue(windows.Any(), "Cannot find Notepad++ window."); 80 | } 81 | } 82 | } 83 | --------------------------------------------------------------------------------