Simple Patching Tool v1.0 (OpenJDK)

When writing OpenJDK tests in Java, I sometimes need to mock methods or set specific values on static fields in order to execute the paths of my interest. Even though using internal APIs is not ideal from a dependencies point of view, there is sometimes no choice. In example, a test that only uses public APIs may not be reliable enough to trigger a race condition bug; or may not return a constant value which can be compared against an expected one.

A few weeks ago I had to modify java.net.DatagramSocket default constructor to use a fixed port number, instead of getting a random one from the OS. Instrumenting Java bytecode with ASM was a good option back then. However, some modifications require more logic and implementing it with ASM can be harsh.

Ideally, I wanted a tool to inject a static method call with ASM and implement the hook logic in Java. Going back to the DatagramSocket case, injecting a static call to a Java method that returns which fixed port to use in run time.

That’s how I came up with Simple Patching Tool. It allows to instrument Java classes in run time (leveraging on ASM) and inject calls to Java hook methods that you define in the Hooker class.

Any Java class can be hooked, even those loaded by the bootstrap class loader. The hook method can import and use any class, even classes loaded by non-bootstrap class loaders. To combine these two features, there is some cheat behind.

The Hooker class is loaded by the application class loader. Thus, any other class can be imported from there. A proxy class named Bridge is dynamically defined mirroring Hooker methods. Each mirrored method in Bridge is a call to its counterpart in Hooker through reflection. Parameters and return values are transferred back and forth. Bridge can be loaded by the bootstrap class loader because it’s not linked against any non-bootstrap class.

This tool is partially based on the Hotspot test suite classes redefinition agent.

Download here

Thanks to Andrew Dinn for his review.

2019-07-05 update: Simple Patching Tool v2.0 released.
2018-10-02 update: Simple Patching Tool v1.4 released.
2018-10-01 update:
Simple Patching Tool v1.3 released.
2018-03-29 update
Simple Patching Tool v1.2 released.

One Reply to “Simple Patching Tool v1.0 (OpenJDK)”

Leave a Reply

Your email address will not be published.