Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging A Java Agent

I'm currently developing a Java Agent in order to facilitate the dynamic instrumentation of new and legacy Java Applications.

It occurred to me that, as far as IDE debugging is concerned, Java Agents could be perhaps considered a special case as they are required to be injected into a target JVM process in order to be ran. Which thus naturally gives rise to the question of how one would go about debugging, testing and profiling an Agent-type application.

A cursory search for existing solutions turned up a few command line based options (i.e YourKit, JIP, etc) however many of them are ALSO Java Agents under the hood. Which if utilized would lead to, at least in my view, the rather odd scenario of an Agent debugging/profiling another Agent. I am aware that Agents can be stacked in a hierarchical arrangement, however i'm unsure if Agent Applications can be debugged by stacking Agents in this manor.

like image 203
Giles Thompson Avatar asked Jul 16 '13 11:07

Giles Thompson


1 Answers

As stated in Java How To ... The -javaagent: Option:

An agent is just an interceptor in front of your main method, executed in the same JVM and loaded by the same system classloader, and governed by the same security policy and context.

The name is misleading, since the word agent usually suggests something working remotely and separately from the primary entity. But it turns out the java agent as used in -javaagent: is much simpler than that.

One java application may have any number of agents by using -javaagent: option any number of times. Agents are invoked in the same order as specified in options.

Each agent may also take String-valued args. I guess that's the reason why we have to use this option multiple times for multiple agents. Otherwise, we could've just done something like:

-javaagent agent1.jar:agent2.jar

, which is incorrect.

So, by putting the profiler agent (e.g. YourKit, JIP, etc.) before your own agent will give the debugging control to you.

like image 102
Mohammad Dashti Avatar answered Oct 09 '22 16:10

Mohammad Dashti