Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a Java agent after program start

Is it possible to insert a javaagent after virtual machine start from within the same VM?

Lets say for example we have an agent in a jar myagent.jar with the appropriate meta data set-up and an agentmain method already implemented. Now the users program calls an API call which should result in the insertion of the agent so that it can redefine the classes.

Can it be done and how?

like image 228
Paul Keeble Avatar asked Aug 14 '09 10:08

Paul Keeble


3 Answers

https://web.archive.org/web/20141014195801/http://dhruba.name/2010/02/07/creation-dynamic-loading-and-instrumentation-with-javaagents/ has a great example of how to write an agent as well as how to start one on the fly.

like image 198
Alan Cabrera Avatar answered Nov 11 '22 15:11

Alan Cabrera


Yes, you just have to pass the JVM process ID to the VirtualMachine.attach(String pid) method, and load the agent jar. The VirtualMachine class is available in the JDK_HOME/lib/tools.jar file. Here's an example of how I activate an agent at runtime:

public static void attachGivenAgentToThisVM(String pathToAgentJar) {
  try {                                                                               
    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();                                                   
    String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));                                                   
    VirtualMachine vm = VirtualMachine.attach(pid);                                                                            
    vm.loadAgent(pathToAgentJar, "");
    vm.detach();   
  } catch (Exception e) {
    e.printStackTrace();
  }
}                                                                                                            
like image 38
11101101b Avatar answered Nov 11 '22 14:11

11101101b


You should be able to do it in Java 6, see the package documentation chapter "Starting Agents After VM Startup"

edit: Maybe it was possible in Java 5 already and just the javadocs didn't mention it that explicitly

like image 4
HerdplattenToni Avatar answered Nov 11 '22 16:11

HerdplattenToni