Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

native java bytecode instrumentation

for bytecode instrumentation in java, there is the asm framework and the bcel and javaassist libraries.

However I need to do instrumentation in native code, since some java classes are already loaded by the time the javaagent runs, eg java.lang.Thread, java.lang.Class, etc

is there any library for instrumenting java classes in native code?

Edit: Seems there is a bit of confusion.

What I want is: Create a native java agent, which uses JVMTI apis to change the bytecode of a class while its being loaded, using the OnClassLoad event hook.

like image 988
pdeva Avatar asked Jan 22 '12 11:01

pdeva


2 Answers

I encountered this problem during my doctoral research. The answer that worked best for me was to perform the byte-code modification in a separate JVM using a java library (I used ASM).

I used the JVMTI class load hook to capture the class file and transmit it to the separate JVM using a tcp connection. Once the class had been modified within the separate JVM I returned it to the JVMTI Agent, which copies it into VM memory and returns a pointer to the modified class file to the JVM.

I found that it was too difficult to weave classes within the same JVM as was being profiled as the system class files I wanted to modify (java.lang.Object, for example) had to be loaded before any class files I needed to perform weaving. I hunted for c/c++ bytecode libraries without much success, before settling on the separate JVM approach I finally used.

You can parameterize the JVMTI agent with the hostname/port of the weaver JVM, or you could use some form of discovery, depending on your requirements.

like image 98
Stephen Nelson Avatar answered Oct 21 '22 02:10

Stephen Nelson


The JIT will turn byte code into native code. If you want to produce native code, you need to let the JIT do it or write native code which is called via JNI.

Perhaps what you are trying to achieve can be done simpler another way.

Create a native java agent, which uses JVMTI apis to change the bytecode of a class while its being loaded, using the OnClassLoad event hook.

Though you don't need to do what you want. Why make the solution more complicated (and less likely to work) than it needs to be?

like image 37
Peter Lawrey Avatar answered Oct 21 '22 02:10

Peter Lawrey