Skip to content

Instantly share code, notes, and snippets.

@iximeow
Last active September 7, 2017 10:28
Show Gist options
  • Select an option

  • Save iximeow/02f77c8f6a8dc1dcead3442a7314932f to your computer and use it in GitHub Desktop.

Select an option

Save iximeow/02f77c8f6a8dc1dcead3442a7314932f to your computer and use it in GitHub Desktop.
i challenge you to explain why this: 1: prints "What was null???" 2: throws an NRE 3: DOES NOT THROW IF YOU REMOVE ANY LINE IN mangler()
using System.Runtime.InteropServices;
using System.Reflection;
using System;
public class lol {
internal delegate void lolwut();
static Delegate d;
static MethodInfo info;
static unsafe byte* rawptr;
public static void Main(System.String[] args) {
info = typeof(lol).GetMethod("mangler");
d = Delegate.CreateDelegate(typeof(lolwut), info);
unsafe {
rawptr = (byte*)Marshal.GetFunctionPointerForDelegate(d).ToPointer();
*rawptr = 0x00;
}
try {
mangler();
} catch (NullReferenceException nre) {
Console.WriteLine("What was null???");
}
}
public static void mangler() {
// note we don't even use the falue here! remove this, NRE stops
Marshal.GetFunctionPointerForDelegate(d);
// removing this stops the NRE
d = Delegate.CreateDelegate(typeof(lolwut), info);
// changing this to String.Format("{0}", "") stops the NRE. return value is unused!
String.Format("{0:s}", "");
unsafe {
// remove this, NRE stops!
Marshal.GetDelegateForFunctionPointer<lolwut>((IntPtr)rawptr)();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment