46

The subject is pretty vague since I'm not sure what's the correct terminology for what I'm trying to do.

I've downloaded a dll (I don't have the source code), and using a reflection tool, I found a bug in the dll implementation. The bug is easy to fix. So let's say the bug is here:

class A 
{
    void f() { // BUG!!! }
}

Is there any way to implement my own A which would fix the bug and inject it in runtime to replace other A instances?

davidsbro
  • 2,761
  • 4
  • 23
  • 33
Shmoopy
  • 5,334
  • 4
  • 36
  • 72
  • It really depends on what the bug is doing within the class. You could potentially inherit from this class (if it isn't `sealed`) and forcefully hide the method implementation that has the bug. – Simon Whitehead Feb 25 '14 at 12:41
  • 6
    Do you have access to developer of said DLL? If yes, ask him to make changes. Till then you can kidnap his favourite coffee mug. – danish Feb 25 '14 at 12:44
  • Duplicate: http://stackoverflow.com/questions/1518891/fix-bugs-in-net-program-without-access-to-source –  Mar 04 '14 at 10:55

2 Answers2

73

If you are using .NET 4.0. or higher, take a look at the: MethodRental.SwapMethodBody Method

Other way: CLR Injection: Runtime Method Replacer

HABJAN
  • 9,212
  • 3
  • 35
  • 59
  • Never knew about this. Thanks. Is this not a security issue? what if I just replace body of Login method in some DLL? – danish Feb 25 '14 at 12:49
  • 3
    @danish "The method can only be called by the client that created the dynamic module that contains the type whose method's body is being swapped." This implies that there is no privilege escalation, since any changes are only visible inside processes that you control already. – Jacob Krall Feb 25 '14 at 14:54
  • 2
    Can't you remove the check of existence of a license file with this method? – Thomas Feb 26 '14 at 10:09
  • @Thomas Hopefully. :) – flarn2006 Jul 05 '15 at 11:10
7

Easiest way would be to inherit from that class and write your own implementation.

  class ParentClass
            {
                public void SomeMethod() { 
                   //bug here 
                }
            }

            class Child:ParentClass
            {
                new public void SomeMethod() { 
                   // I fixed it 
                }
            }

Here after, use your class.

Child child = new Child();
child.SomeMethod();
danish
  • 5,550
  • 2
  • 25
  • 28
  • 5
    Note that you have to call it as "Child" type, even `UseThatParentClass(ParentClass ins);` -> `UseThatParentClass(new Child());` will call default SomeMethod (that buggy one on ParentClass, not at your Child class) becouse thats the way how "new" keyword works - its nothing like inheritance (virtual/override), its more like "two methods have same name" – Jan 'splite' K. Feb 25 '14 at 15:33