Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

System.NullReferenceException for IL hooks in specific places #85

Open
Dual-Iron opened this issue Oct 14, 2021 · 0 comments
Open

System.NullReferenceException for IL hooks in specific places #85

Dual-Iron opened this issue Oct 14, 2021 · 0 comments
Labels

Comments

@Dual-Iron
Copy link

Description

In specific cases, a System.NullReferenceException exception will be thrown from an ILHook's generated DMD (and sometimes FastDelegateInvokers.Invoke<...>) when using a custom delegate type for an instance method.

I got this to occur by doing the following:

  1. In an assembly A, IL hook an arbitrary method and call ILCursor.EmitDelegate<CustomDelegate>(someInstanceMethod)
  2. Call DetourModManager.Unload on A
  3. Load a new assembly, B, that shares the same name and version with A
  4. Hook the same method in the same way as A

This is when running Unity v4.6.3/Mono, targeting .NET Framework 3.5. Make sure that CustomDelegate is a delegate from your assembly, not e.g. Action or Func. Also make sure that someInstanceMethod is an instance method.

Example

delegate void A();

string Words = "Hi";

void PrintWords() {
    Console.WriteLine(Words);
}

void Enable() {
    IL.Room.Update += MyILHook;
}

void MyILHook(ILContext il) {
    ILCursor cursor = new(il);
    cursor.EmitDelegate<A>(PrintWords);

    // These also bug out because they compile as instance methods:
    // cursor.EmitDelegate<A>(() => Console.WriteLine(Words));
    // cursor.EmitDelegate<A>(() => Console.WriteLine("Hi"));
}

Before step 2, this runs fine. When Room.Update is called, Hi gets printed to the console.

After step 4, however, whenever Room.Update is called, you'll instead get a nasty exception:

System.NullReferenceException: Object reference not set to an instance of an object
at (wrapper dynamic-method) Room.DMD<Room..Update> (Room) <0x0008c>
etc
@Dual-Iron Dual-Iron added the bug label Oct 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant