If I want to realize a profiler using byte code instrumentation, should I write a native agent using JVMTI or should I write a java agent using the java.lang.instrument
package?
If I want to use libraries like ASM - which seems to be mandatory if you want to create a serious profiler - I have to use a java agent. Which confuses me, since I thought a native agent can do everything what a java agent can do and more. But to me, it seems easier writing a java agent.
Are there alternatives? Should one use java agent and native agent combined anyway?
Bytecode instrumentation is a process where new function- ality is added to a program by modifying the bytecode of a set of classes before they are loaded by the virtual machine. This paper will look into the details of bytecode instrumen- tation in Java: the tools, APIs and real-life applications.
Defining Java Agents Instrumentation, in the context of software, is a technique used to change an existing application, adding code to it. You can perform instrumentation both manually and automatically. You can also do it both at compiling time and runtime.
Instrumentation is the addition of byte-codes to methods for the purpose of gathering data to be utilized by tools. Since the changes are purely additive, these tools do not modify application state or behavior.
In general, a java agent is just a specially crafted jar file. It utilizes the Instrumentation API that the JVM provides to alter existing byte-code that is loaded in a JVM. For an agent to work, we need to define two methods: premain – will statically load the agent using -javaagent parameter at JVM startup.
Nearly everyone writes a java agent (with ASM or BCEL) as they don't want to have to write a C/C++ bytecode instrumentor from scratch as there are none publicly available.
What you won't be able to do is instrument and profile/monitor the primordial JVM, and accessing native functions requires JNI calls. There are also several JVMTI calls that may be unavailable to you (if memory serves).
I wrote my own instrumentor in C several years ago, and I'm in the process of writing a new one which I hope to open source ( depending on my evil overlords :-) )
How about a half way house, a separate pre-started JVM that your native agent sends bytecode to. In that JVM your easy-peasy to write ASM based instrumentor does the hard work and sends the resulting bytecode back to the native agent over the wire. Yeah it seems a bit over-complicated but it's easier that writing your own BCI library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With