Why here is a wonderful program that compiles in safe mode, uses a horribly unsafe buffer overflow treats an array like a buffer, and abuses some quirks of the CLR. This works in x86 C#. A similar exploit can be done for x64 and is left as an exercise for the reader.
public Union(byte bytes)
this.bytes = bytes;
public readonly Byte bytes;
public readonly int ints;
static Union u = new Union(new byte);
static Action a = ()=>Console.WriteLine("Somehow I was called?");
static void Main(string args)
var f = Marshal.GetDelegateForFunctionPointer((IntPtr)u.ints, typeof(Action)) as Action;
The reason this works is that CLR allocates primitive struct type arrays as contiguous blocks. This is why you are allowed to cast a
int to a
uint via using an object first. The CLR however, will NOT allow you to normally cast a
byte to an
int. However, this Union class is COMPLETELY evil, and allows us to trick the CLR into treating the
byte as an
int. Basically we're back to pointer land now.
What's more fun is the CLR inserts a bound check on this access of the
byte and still goes and does an access way out of the bounds of the array at this point. The executable code is located shortly after the accessible variable space. We then read it and then execute the function.
This btw is horribly evil and if you do this in code I hate you.