Wednesday, August 28, 2013

I was looking into some classloading issues of websphere application server and encountered with javaagent argument , I found really interesting when i read "The agent class will be loaded by the same classloader which loads the class containing the application main method.", and i started digging more into it.This was a new thing for me. I used the transformer to see a class loaded from which location. I was doing the same from debugger for multiple class was really time consuming. By using transformer i could find out easily a class was loaded by whicih classloader and from which location using ProtectionDomain, etc. Co-incidently I was working on profiling also and found it can be used there as well.
I wrote small program around it and found it is useful. Many people have written already written in this area but did not find on any blog quickly that how to get a count for method execution, so i thought it writing myself. Of-course many tools like Jensor, Jrat, etc, gives lot more facility but i did it just to get method count and not any other reporting.

So ultimately this blog post covers

Javaagent and premain

ClassFileTransformer

Javassist

Javaagent and premain: Introduced in JDK 5, vm argument.. Can augument java bytecode dynamically with the transformer(s) which helps in profiling, bytecode manupulation,. With this dynamic manipulation we can manipulate bytecode during the runtime and which is one of the most useful feature of java. Agent can be added in the JVM argument for your program or server. Agent must implement premain method.

A premain method is the one which gets executed before loading the class and before executing main
method in the class. Javaagent can be added as the JVM argument as follows:

ClassFileTransformer: Agent can add one or more transformer, we have to implement ClassFileTransformer interface. Transformed class which is responsible for transformation of the bytecode. The transformation occurs before the class is defined by the JVM.

jar which we add as a jarpath for javaagent argument, must have Premain-Class attribute in
MANIFEST.MF file. Which is as follows

Javassist: I have used Javassist for byte code instrumentation. We have multiple choices to achive the same. Users can use Javassist, ASM, BCEL from apache, etc.

You can find/download the source code from my github account repository which included dsinstrumentation.jar as well, which can be used directly.
User need to provide
a) -javaagent
b) configuration system property which should have conf folder with the classinstrumentation.properties file
with the class file name in the following format: