Can someone explain this code to me?

I looked at this question: How to implement multiplication without using the multiplication operator in .NET and it was actually a lot of fun trying to think of ways to multiply without using *.

But I was left scratching my head with this answer. I have no idea what is going on in this code.

Can someone explain this to me?

using System; using System.Runtime.InteropServices; delegate uint BinaryOp(uint a, uint b); static class Program { [DllImport("kernel32.dll", SetLastError = true)] static extern bool VirtualProtect( IntPtr address, IntPtr size, uint protect, out uint oldProtect); static void Main() { var bytes = IntPtr.Size == sizeof(int) ? //32-bit? It slower BTW new byte[] {0x8B, 0x44, 0x24, 0x04, 0x0F, 0xAF, 0x44, 0x24, 0x08, 0xC3} : new byte[] {0x0F, 0xAF, 0xCA, 0x8B, 0xC1, 0xC3}; var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { uint old; VirtualProtect(handle.AddrOfPinnedObject(), (IntPtr)bytes.Length, 0x40, out old); var action = (BinaryOp)Marshal.GetDelegateForFunctionPointer( handle.AddrOfPinnedObject(), typeof(BinaryOp)); var temp = action(3, 2); //6! } finally { handle.Free(); } } } 

Credit for this code is sent to Mehrdad.

+6
source share
3 answers

Basically, he creates a delegate from his own code for multiplication, and then calls it. Byte arrays are raw instructions that are then pinned into memory, set as executable, and then the delegate itself creates the Marshal.GetDelegateForFunctionPointer .

The conditional statement must use different native code for x86 and x64. I suspect that this will not work when working in Mono on an ARM processor, for example :)

+12
source

This code contains the binary code of the CPU instructions. It finds the address of the binary file and executes it. Pretty awful, with the exception of a negative example or a joke.

+3
source

This is assembly language code for implementing multiplication. The challenge of VirtualProtect is to enable code execution in what would otherwise be an unexecutable data segment.

+1
source

Source: https://habr.com/ru/post/887482/


All Articles