Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte code instrumentation - implement native or java agent?

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?

like image 843
Konrad Reiche Avatar asked Sep 06 '11 14:09

Konrad Reiche


People also ask

What is bytecode instrumentation in Java?

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.

How does Java instrumentation work?

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.

What is instrumentation API in Java?

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.

What is the purpose of Javaagent?

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.


1 Answers

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.

like image 145
user931239 Avatar answered Oct 31 '22 02:10

user931239