Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify the byte code of a Java method in the runtime?

I am writing a plugin of another large java program .

I want to modify some byte code of some java method of the java program during runtime, so that I can intercept the method calls (namely, inject some hooking code into the method).

Any way can achieve this?

PS:

I've checked the following approaches:

1.change the classloader of the java program. (we CANNOT change it)
2.use java proxy. (We CANNOT use java proxy, because java proxy would create a new proxy object. We DON'T use the proxy object. We need to hook the java program's object, and Use that object)
3. use -javaagent option ( we CANNOT add the commandline option for the java program.)

PS more [Edited again]:
My classes was loaded by ext class loader (I put my jar files in JAVA_HOME\lib\ext folder). The large java program is an applet program loaded by Browser. When the browser start the applet, it also loads my classes.

PS more more [Edited again]:
Although it's running in Applet. I can have full permission. Because I can modify java.policy and java.security file.

Thanks,
Calvin

like image 482
Calvin Kwok Avatar asked Oct 09 '13 09:10

Calvin Kwok


3 Answers

Just use -javaagent opiton, which is used to modify the bytecode at runtime. You can find more about -javaagent from This Link or from This Link

like image 60
Anish Antony Avatar answered Sep 20 '22 02:09

Anish Antony


There are several libraries which you can use. See for example here. Once a class was already loaded/initialized by the VM it will be impossible to manipulate, though.

By the way, in principle you can also just replace the class to be 'hooked' with your own proxy class file. As long as the class' visible interface does not change this may work. (Sub-classes of the class may horribly fail at runtime though.) This replacement can be as easy as changing the classpath so that your class of the same name will be found first, before the original one. Delegating to the original class of the same name may be a little more complex in this case.

like image 44
JimmyB Avatar answered Sep 22 '22 02:09

JimmyB


Yes, you can, but the process would be a bit tricky, as you would operate directly with memory. For this purpose, you'd look at unofficial documentation on sun.misc package and its Unsafe class.

  • Warning 1: the Unsafe class would be removed in JDK 9 according to official sources.
  • Warning 2: the Sun company would not take responsibility for your code to work correctly, as this class should not be used at all, and exists for system usage only.
like image 40
Игорь Комаров Avatar answered Sep 23 '22 02:09

Игорь Комаров