As highlighted already in many places, Mustang (java SE 6) has support for Scripting (javax.script API) and includes JavaScript engine in it. There are many ways to use scripting - one very important way is exploratory programming. You can play with new Java APIs without having to write complete Java programs (i.e., avoid "compile" step in the edit/compile/run cycle). You can use jrunscript - command line script shell to explore Java APIs.
Elsewhere I mentioned about attach-on-demand API in Mustang - the facility to load java.lang.instrument (or JVM TI native agents) into running JVM(s). We'll how we can load an agent into running JVM using JavaScript. There is a demo JVM TI agent in $JDK_HOME/demo/jvmti/heapViewer. This agent prints heap histogram whenever SIGQUIT is sent to the process or when the Java process exits. Now, we'll attempt to load this agent "on demand".
// package where attach API lives -
importPackage(Packages.com.sun.tools.attach);
function loadAgentPath(pid, agent, options) {
// attach to the given pid
var vm = VirtualMachine.attach(pid);
// load native library specified by path. optionally, pass options
// to the agent
if (options == undefined) {
vm.loadAgentPath(agent);
} else {
vm.loadAgentPath(agent, options);
}
// detach the VM!
vm.detach();
}
// call the above function using command line arguments to script
loadAgentPath(arguments[0], arguments[1], arguments[2]);
I tried to the above script with jrunscript using the command:
jrunscript attach.js 13525 $JDK_HOME/demo/jvmti/lib/libheapViewer.so
where 13525 is a Java process running on my machine and JDK_HOME is the
directory where Mustang JDK is installed on my machine. I got the following error:
script error in file attach.js : sun.org.mozilla.javascript.internal.WrappedException: Wrapped com.sun.tools.attach.AgentLoadException: Failed to load agent library (attach.js#10) in attach.js at line number 10Why? It seems that heapViewer agent has not been written to support attach-on-demand. i.e., this agent has to be loaded on start-up. It seems that Agent_OnAttach function is missing in heapViewer. So what do we do? well, we can easily add one. The source for heapViewer is in the directory $JDK_HOME/demo/jvmti/heapViewer/src. I looked at heapViewer.c and it does miss Agent_OnAttach function. For experimentation purpose, I just added
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM *vm, char *options, void *reserved) {
printf("attached..\n");
return Agent_OnLoad(vm, options, reserved);
}
in heapViewer.c and recompiled it (I had to copy sample.makefile.txt ad Makefile and do some editing to get correct GNU makefile). After that, I started a
simple Java program and tried the above mentioned jrunscript attach.js ...
command. It worked! This time, the Java process printed "attached..." and whenver
I pressed Ctrl-\ (SIGQUIT) histogram was printed. Also, when the Java process exited, histogram was printed as expected.