├── .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