Runtime DLL Patching

In some languages (e.g Javascript, Ruby and Python) it is possible to change classes and namespaces while running. This is referred to as monkey-patching and can be useful while testing. Most people seem to think that the rest of the time it is a bad idea because of global consequences and missing papertrail.

However, brutal hacking can be advantageous. For example - if a third party library is broken, cannot be fixed or patched statically, and is used by code over which you have no control then it could be a good idea to.

Regardless - Obviously, monkey-patching is clearly impossible in static, compiled languages since the addresses of the functions you call are fixed at compile time leaving you no indirection to use at run-time...


Sort of - unless you want to write non-portable, machine-dependent, operating-system-dependent code. If so, it can at least be done - on 32-bit windows machines.

How to Monkey-Patch a static Dll

Firstly, you probably don't want to do this. Secondly you probably don't want to do this. However, if you really want to do this you can use the following approach.

The memory location of a loaded dll is not known ahead-of-time. So, there must be mechanism to specify where the called functions are. This is done as follows:

This means that when loading a DLL (or executable) you can change the function pointers in the process-specific memory storage so as to change where any external function call in this DLL points to.

Example

When loading a patched.dll which uses the c runtime library msvcrt, you can change all calls to the _write function in msvcrt from patched.dll so that it calls any function you want.

Here is some C# sample code which should work - and has been made to work on 32-bit windows. Though it hasn't been used extensively and should be treated with caution.

PatchedDll

I'd be very interested to know if anyone finds a reason to use this and finds this page at the same time - so shout at me if you do.

I imagine it may also be possible to do this for elf binaries...

See also

winnt.h contains the definitions of the data structures representing a DLL in memory. The word THUNK is sometimes used instead of function pointer here.

Contact

If you'd like to tell anything about this you can find me here.