├── .gitignore ├── CSharp-Inline-Assembly.csproj ├── CSharp-Inline-Assembly.sln ├── Program.cs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | 28 | # Visual Studio 2015/2017 cache/options directory 29 | .vs/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # Visual Studio 2017 auto generated files 34 | Generated\ Files/ 35 | 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | 44 | # Build Results of an ATL Project 45 | [Dd]ebugPS/ 46 | [Rr]eleasePS/ 47 | dlldata.c 48 | 49 | # Benchmark Results 50 | BenchmarkDotNet.Artifacts/ 51 | 52 | # .NET Core 53 | project.lock.json 54 | project.fragment.lock.json 55 | artifacts/ 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_h.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *_wpftmp.csproj 81 | *.log 82 | *.vspscc 83 | *.vssscc 84 | .builds 85 | *.pidb 86 | *.svclog 87 | *.scc 88 | 89 | # Chutzpah Test files 90 | _Chutzpah* 91 | 92 | # Visual C++ cache files 93 | ipch/ 94 | *.aps 95 | *.ncb 96 | *.opendb 97 | *.opensdf 98 | *.sdf 99 | *.cachefile 100 | *.VC.db 101 | *.VC.VC.opendb 102 | 103 | # Visual Studio profiler 104 | *.psess 105 | *.vsp 106 | *.vspx 107 | *.sap 108 | 109 | # Visual Studio Trace Files 110 | *.e2e 111 | 112 | # TFS 2012 Local Workspace 113 | $tf/ 114 | 115 | # Guidance Automation Toolkit 116 | *.gpState 117 | 118 | # ReSharper is a .NET coding add-in 119 | _ReSharper*/ 120 | *.[Rr]e[Ss]harper 121 | *.DotSettings.user 122 | 123 | # JustCode is a .NET coding add-in 124 | .JustCode 125 | 126 | # TeamCity is a build add-in 127 | _TeamCity* 128 | 129 | # DotCover is a Code Coverage Tool 130 | *.dotCover 131 | 132 | # AxoCover is a Code Coverage Tool 133 | .axoCover/* 134 | !.axoCover/settings.json 135 | 136 | # Visual Studio code coverage results 137 | *.coverage 138 | *.coveragexml 139 | 140 | # NCrunch 141 | _NCrunch_* 142 | .*crunch*.local.xml 143 | nCrunchTemp_* 144 | 145 | # MightyMoose 146 | *.mm.* 147 | AutoTest.Net/ 148 | 149 | # Web workbench (sass) 150 | .sass-cache/ 151 | 152 | # Installshield output folder 153 | [Ee]xpress/ 154 | 155 | # DocProject is a documentation generator add-in 156 | DocProject/buildhelp/ 157 | DocProject/Help/*.HxT 158 | DocProject/Help/*.HxC 159 | DocProject/Help/*.hhc 160 | DocProject/Help/*.hhk 161 | DocProject/Help/*.hhp 162 | DocProject/Help/Html2 163 | DocProject/Help/html 164 | 165 | # Click-Once directory 166 | publish/ 167 | 168 | # Publish Web Output 169 | *.[Pp]ublish.xml 170 | *.azurePubxml 171 | # Note: Comment the next line if you want to checkin your web deploy settings, 172 | # but database connection strings (with potential passwords) will be unencrypted 173 | *.pubxml 174 | *.publishproj 175 | 176 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 177 | # checkin your Azure Web App publish settings, but sensitive information contained 178 | # in these scripts will be unencrypted 179 | PublishScripts/ 180 | 181 | # NuGet Packages 182 | *.nupkg 183 | # The packages folder can be ignored because of Package Restore 184 | **/[Pp]ackages/* 185 | # except build/, which is used as an MSBuild target. 186 | !**/[Pp]ackages/build/ 187 | # Uncomment if necessary however generally it will be regenerated when needed 188 | #!**/[Pp]ackages/repositories.config 189 | # NuGet v3's project.json files produces more ignorable files 190 | *.nuget.props 191 | *.nuget.targets 192 | 193 | # Microsoft Azure Build Output 194 | csx/ 195 | *.build.csdef 196 | 197 | # Microsoft Azure Emulator 198 | ecf/ 199 | rcf/ 200 | 201 | # Windows Store app package directories and files 202 | AppPackages/ 203 | BundleArtifacts/ 204 | Package.StoreAssociation.xml 205 | _pkginfo.txt 206 | *.appx 207 | 208 | # Visual Studio cache files 209 | # files ending in .cache can be ignored 210 | *.[Cc]ache 211 | # but keep track of directories ending in .cache 212 | !*.[Cc]ache/ 213 | 214 | # Others 215 | ClientBin/ 216 | ~$* 217 | *~ 218 | *.dbmdl 219 | *.dbproj.schemaview 220 | *.jfm 221 | *.pfx 222 | *.publishsettings 223 | orleans.codegen.cs 224 | 225 | # Including strong name files can present a security risk 226 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 227 | #*.snk 228 | 229 | # Since there are multiple workflows, uncomment next line to ignore bower_components 230 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 231 | #bower_components/ 232 | 233 | # RIA/Silverlight projects 234 | Generated_Code/ 235 | 236 | # Backup & report files from converting an old project file 237 | # to a newer Visual Studio version. Backup files are not needed, 238 | # because we have git ;-) 239 | _UpgradeReport_Files/ 240 | Backup*/ 241 | UpgradeLog*.XML 242 | UpgradeLog*.htm 243 | ServiceFabricBackup/ 244 | *.rptproj.bak 245 | 246 | # SQL Server files 247 | *.mdf 248 | *.ldf 249 | *.ndf 250 | 251 | # Business Intelligence projects 252 | *.rdl.data 253 | *.bim.layout 254 | *.bim_*.settings 255 | *.rptproj.rsuser 256 | 257 | # Microsoft Fakes 258 | FakesAssemblies/ 259 | 260 | # GhostDoc plugin setting file 261 | *.GhostDoc.xml 262 | 263 | # Node.js Tools for Visual Studio 264 | .ntvs_analysis.dat 265 | node_modules/ 266 | 267 | # Visual Studio 6 build log 268 | *.plg 269 | 270 | # Visual Studio 6 workspace options file 271 | *.opt 272 | 273 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 274 | *.vbw 275 | 276 | # Visual Studio LightSwitch build output 277 | **/*.HTMLClient/GeneratedArtifacts 278 | **/*.DesktopClient/GeneratedArtifacts 279 | **/*.DesktopClient/ModelManifest.xml 280 | **/*.Server/GeneratedArtifacts 281 | **/*.Server/ModelManifest.xml 282 | _Pvt_Extensions 283 | 284 | # Paket dependency manager 285 | .paket/paket.exe 286 | paket-files/ 287 | 288 | # FAKE - F# Make 289 | .fake/ 290 | 291 | # JetBrains Rider 292 | .idea/ 293 | *.sln.iml 294 | 295 | # CodeRush personal settings 296 | .cr/personal 297 | 298 | # Python Tools for Visual Studio (PTVS) 299 | __pycache__/ 300 | *.pyc 301 | 302 | # Cake - Uncomment if you are using it 303 | # tools/** 304 | # !tools/packages.config 305 | 306 | # Tabs Studio 307 | *.tss 308 | 309 | # Telerik's JustMock configuration file 310 | *.jmconfig 311 | 312 | # BizTalk build output 313 | *.btp.cs 314 | *.btm.cs 315 | *.odx.cs 316 | *.xsd.cs 317 | 318 | # OpenCover UI analysis results 319 | OpenCover/ 320 | 321 | # Azure Stream Analytics local run output 322 | ASALocalRun/ 323 | 324 | # MSBuild Binary and Structured Log 325 | *.binlog 326 | 327 | # NVidia Nsight GPU debugger configuration file 328 | *.nvuser 329 | 330 | # MFractors (Xamarin productivity tool) working folder 331 | .mfractor/ 332 | 333 | # Local History for Visual Studio 334 | .localhistory/ 335 | -------------------------------------------------------------------------------- /CSharp-Inline-Assembly.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net461 6 | esozbek.CSharp-Inline-Assembly 7 | CSharp-Inline-Assembly 8 | x86 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /CSharp-Inline-Assembly.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28010.2036 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharp-Inline-Assembly", "CSharp-Inline-Assembly.csproj", "{4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|x86 = Debug|x86 12 | Release|Any CPU = Release|Any CPU 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Debug|x86.ActiveCfg = Debug|Any CPU 19 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Debug|x86.Build.0 = Debug|Any CPU 20 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Release|x86.ActiveCfg = Release|Any CPU 23 | {4C70ECA3-E7F9-4A27-8D49-00D01DA5B847}.Release|x86.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {9E1B4EE0-8CFA-4D86-80C5-F0CBC46AAD01} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using Binarysharp.Assemblers.Fasm; 2 | using System; 3 | using System.CodeDom; 4 | using System.ComponentModel; 5 | using System.Diagnostics; 6 | using System.Reflection; 7 | using System.Runtime.InteropServices; 8 | using System.Security; 9 | using Process.NET; 10 | using Process.NET.Memory; 11 | using Process.NET.Native.Types; 12 | using Process = System.Diagnostics.Process; 13 | 14 | namespace CSharp_Inline_Assembly 15 | { 16 | /// 17 | /// This program demonstrates how to use inline x86 assembly from C# 18 | /// 19 | class Program 20 | { 21 | private static IProcess _currentProcess; 22 | 23 | static void Main(string[] args) 24 | { 25 | _currentProcess = new ProcessSharp(System.Diagnostics.Process.GetCurrentProcess(), MemoryType.Local); 26 | 27 | Example1(); 28 | Example2(); 29 | Example3(); 30 | Example4(); 31 | Example5(); 32 | 33 | //Wait for any key to exit 34 | Console.ReadKey(true); 35 | } 36 | 37 | // Example 1: Function Returning Constant Value 38 | [SuppressUnmanagedCodeSecurity] // disable security checks for better performance 39 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] // cdecl - let caller (.NET CLR) clean the stack 40 | private delegate int AssemblyConstantValueFunction(); 41 | private static void Example1() 42 | { 43 | const int valueToReturn = 1; 44 | 45 | FasmNet fasmNet = new FasmNet(); 46 | fasmNet.AddLine("use32"); //Tell FASM.Net to use x86 (32bit) mode 47 | fasmNet.AddLine("mov eax, {0}", valueToReturn); // copy "1" to eax 48 | fasmNet.AddLine("ret"); // in cdecl calling convention, return value is stored in eax; so this will return 1 49 | 50 | byte[] assembledCode = fasmNet.Assemble(); 51 | 52 | var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate( 53 | name: "Example1", // only used for debugging; not really needed 54 | size: assembledCode.Length, 55 | protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */ 56 | ); 57 | allocatedCodeMemory.Write(0, assembledCode); 58 | 59 | var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer(allocatedCodeMemory.BaseAddress); 60 | var returnValue = myAssemblyFunction(); 61 | 62 | // Warning: Potential memory leak! 63 | // Do not forget to dispose the allocated code memory after usage. 64 | allocatedCodeMemory.Dispose(); 65 | 66 | Console.WriteLine($"Example1 return value: {returnValue}, expected: {valueToReturn}"); // Prints 1 67 | } 68 | 69 | // Example 2: Function Reading Registers 70 | [SuppressUnmanagedCodeSecurity] // disable security checks for better performance 71 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] // cdecl - let caller (.NET CLR) clean the stack 72 | private delegate IntPtr AssemblyReadRegistersFunction(); 73 | private static void Example2() 74 | { 75 | FasmNet fasmNet = new FasmNet(); 76 | fasmNet.AddLine("use32"); //Tell FASM.Net to use x86 (32bit) mode 77 | fasmNet.AddLine("mov eax, [ebp+4]"); // Set return value to ebp+4 (return address) 78 | fasmNet.AddLine("ret"); // in cdecl calling convention, return value is stored in eax; so this will return the return address 79 | 80 | byte[] assembledCode = fasmNet.Assemble(); 81 | 82 | var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate( 83 | name: "Example2", // only used for debugging; not really needed 84 | size: assembledCode.Length, 85 | protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */ 86 | ); 87 | allocatedCodeMemory.Write(0, assembledCode); 88 | 89 | var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer(allocatedCodeMemory.BaseAddress); 90 | var returnValue = myAssemblyFunction(); 91 | 92 | // Warning: Potential memory leak! 93 | // Do not forget to dispose the allocated code memory after usage. 94 | allocatedCodeMemory.Dispose(); 95 | 96 | Console.WriteLine($"Example2 return value: 0x{returnValue.ToInt32():X}"); // Prints this methods JIT'ed address 97 | } 98 | 99 | // Example 3: Add Function With Parameters 100 | [SuppressUnmanagedCodeSecurity] // disable security checks for better performance 101 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] // cdecl - let caller (.NET CLR) clean the stack 102 | private delegate int AssemblyAddFunction(int x, int y); 103 | private static void Example3() 104 | { 105 | FasmNet fasmNet = new FasmNet(); 106 | fasmNet.AddLine("use32"); //Tell FASM.Net to use x86 (32bit) mode 107 | fasmNet.AddLine("push ebp"); // init stack frame 108 | fasmNet.AddLine("mov eax, [ebp+8]"); // set eax to second param (remember, in cdecl calling convention, params are pushed right-to-left) 109 | fasmNet.AddLine("mov edx, [ebp+12]"); // set edx to first param 110 | fasmNet.AddLine("add eax, edx"); //add edx (first param) to eax (second param) 111 | fasmNet.AddLine("pop ebp"); // leave stack frame 112 | fasmNet.AddLine("ret"); // in cdecl calling convention, return value is stored in eax; so this will return both params added up 113 | 114 | byte[] assembledCode = fasmNet.Assemble(); 115 | 116 | var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate( 117 | name: "Example3", // only used for debugging; not really needed 118 | size: assembledCode.Length, 119 | protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */ 120 | ); 121 | allocatedCodeMemory.Write(0, assembledCode); 122 | 123 | var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer(allocatedCodeMemory.BaseAddress); 124 | var returnValue = myAssemblyFunction(10, -15); 125 | 126 | // Warning: Potential memory leak! 127 | // Do not forget to dispose the allocated code memory after usage. 128 | allocatedCodeMemory.Dispose(); 129 | 130 | Console.WriteLine($"Example3 return value: {returnValue}, expected: -5"); // Prints -5 131 | } 132 | 133 | // Example 4: Add Function With Parameters (Without Fasm.NET) 134 | private static void Example4() 135 | { 136 | //You can use any x86 assembler 137 | //For this example I have used https://defuse.ca/online-x86-assembler.htm 138 | 139 | // Without FASM.Net I strongly suggest you to comment each instruction (e.g. "0 push ebp") 140 | byte[] assembledCode = 141 | { 142 | 0x55, // 0 push ebp ; init stack frame 143 | 0x8B, 0x45, 0x08, // 1 mov eax, [ebp+8] ; set eax to second param (remember, in cdecl calling convention, params are pushed right-to-left) 144 | 0x8B, 0x55, 0x0C, // 4 mov edx, [ebp+12] ; set edx to first param 145 | 0x01, 0xD0, // 7 add eax, edx ; add edx (first param) to eax (second param) 146 | 0x5D, // 9 pop ebp ; leave stack frame 147 | 0xC3 // A ret ; in cdecl calling convention, return value is stored in eax; so this will return both params added up 148 | }; 149 | 150 | var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate( 151 | name: "Example4", // only used for debugging; not really needed 152 | size: assembledCode.Length, 153 | protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */ 154 | ); 155 | allocatedCodeMemory.Write(0, assembledCode); 156 | 157 | var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer(allocatedCodeMemory.BaseAddress); 158 | var returnValue = myAssemblyFunction(10, -15); 159 | 160 | // Warning: Potential memory leak! 161 | // Do not forget to dispose the allocated code memory after usage. 162 | allocatedCodeMemory.Dispose(); 163 | 164 | Console.WriteLine($"Example3 (no Fasm.NET) return value: {returnValue}, expected: -5"); // Prints -5 165 | } 166 | 167 | //Example 5: Add Function With Parameters (Without any dependencies) 168 | [DllImport("kernel32.dll")] 169 | private static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 170 | private static void Example5() 171 | { 172 | var process = System.Diagnostics.Process.GetCurrentProcess(); 173 | 174 | //You can use any x86 assembler 175 | //For this example I have used https://defuse.ca/online-x86-assembler.htm 176 | 177 | // Without FASM.Net I strongly suggest you to comment each instruction (e.g. "0 push ebp") 178 | byte[] assembledCode = 179 | { 180 | 0x55, // 0 push ebp ; init stack frame 181 | 0x8B, 0x45, 0x08, // 1 mov eax, [ebp+8] ; set eax to second param (remember, in cdecl calling convention, params are pushed right-to-left) 182 | 0x8B, 0x55, 0x0C, // 4 mov edx, [ebp+12] ; set edx to first param 183 | 0x01, 0xD0, // 7 add eax, edx ; add edx (first param) to eax (second param) 184 | 0x5D, // 9 pop ebp ; leave stack frame 185 | 0xC3 // A ret ; in cdecl calling convention, return value is stored in eax; so this will return both params added up 186 | }; 187 | 188 | int returnValue; 189 | unsafe 190 | { 191 | fixed (byte* ptr = assembledCode) 192 | { 193 | var memoryAddress = (IntPtr) ptr; 194 | 195 | // Mark memory as EXECUTE_READWRITE to prevent DEP exceptions 196 | if (!VirtualProtectEx(process.Handle, memoryAddress, 197 | (UIntPtr) assembledCode.Length, 0x40 /* EXECUTE_READWRITE */, out uint _)) 198 | { 199 | throw new Win32Exception(); 200 | } 201 | 202 | var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer(memoryAddress); 203 | returnValue = myAssemblyFunction(10, -15); 204 | } 205 | } 206 | 207 | // Note: We do not have to dispose memory ourself; the CLR will handle this. 208 | Console.WriteLine($"Example3 (no dependencies) return value: {returnValue}, expected: -5"); // Prints -5 209 | } 210 | } 211 | } 212 | 213 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Inline Assembly in C# 2 | Inline Assembly Demonstration in C# using Fasm.NET and Process.NET 3 | 4 | Visit [my blog](https://esozbek.me/inline-assembly-in-csharp-and-dotnet/) for more. 5 | --------------------------------------------------------------------------------