参考:http://java.sun.com/javase/6/docs/platform/jvmti/jvmti.html
JVM通过JVM TI为外部访问JVM内部状态定义了标准的服务,基本上各种性能剖析工具都是基于JVM TI及其前身JVM DI/JVM PI开发的,包括Visual VM、Eclipse TPTP(Test and Performance Tools Platform)的CPU Profiler和Memory Profiler,JVM TI的前身是JVM PI(JVM Profile Interface)和JVM DI(JVM Debug Interface),其中JVM PI在JDK6中已经被废弃,但仍然有不少剖析工具是基于JVM PI开发的,譬如JProfiler、TPTP都支持JVM PI。
我们称一个JVM TI的客户端程序为Agent,Agent与JVM位于同一个进程内。JVM TI提供了两方面的接口:一方面提供了对JVM内部信息的查询,另一方面提供了一些事件,JVM TI Agent可以向JVM注册一些感兴趣的事件(譬如进入方面或加载了类),并在事件发生时获得JVM的通知。后面我们将大概地了解JVM TI具体会提供哪些功能。
JVM TI接口使用C/C++语言开发,在代码中需要包含#include <jvmti.h>
1.Agent启动:JVM TI Agent有两种启动方式,一种是与JVM一起启动,另一种是在JVM启动之后,通过Attach到该JVM(关于Attach,后续BLOG会详细介绍),然后让该JVM加载Agent
1) 与JVM一起启动
如上在JVM启动参数中指定启动Agent,譬如TPTP的性能剖析Agent就是使用这种方式装载的
大家可能会很奇怪地发现,JVM的调试agent启动方式是如下,其实如下是JVMDI的方式,JDK5开始后开始支持-agentlib:jdwp的方式,详细参见《Connection and Invocation Details 》
与JVM启动的Agent,JVM会回调如下接口对Agent进行初始化(可以理解为Agent的入口函数)
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved)
2) Attach后启动:我们可以在Client JVM上通过Attach API连接到被调试端的JVM上(大部分平台只支持本地进程Attach,Sun Solaris系统下的JVM支持Remote Attach),并在被调试的JVM上加载Agent。这种方式的好处在于我们并不需要在被调试/剖析端上事先指定参数,而是在需要调试/剖析的时候,才去加载调试/剖析Agent。由于需要依赖Attach API,大部分剖析工具需要支持JDK6以下版本的工具大都不支持这种方式(譬如TPTP),Visual VM虽然支持这种方式对JVM进行剖析,可惜的是Visual JVM对于性能剖析部分只支持本地的JVM。(Visual VM远程剖析架构上比较简单,具体讲到Visual VM再说明)
这种方式启动的Agent,JVM会回调如下接口对Agent进行初始化(可以理解为Agent的入口函数)
JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char *options, void *reserved)
在启动之后我们可以通过如下方式获得一个jvmtiEnv指针,而jvmtiEnv代表了与JVM的连接,所有的功能都可以通过jvmtiEnv指针来获得
jvmtiEnv *jvmti; ... (*jvm)->GetEnv(jvm, &jvmti, JVMTI_VERSION_1_0);
2.Agent结束:在JVM退出的时候,会回调Agent的结束接口,我们可以通过该回调来进行一些资源释放的工作
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm);
3.查询接口
我们通过查询接口获取到JVM的内部信息或者做事件注册,JVM TI提供了如下的接口,下面我们预览一下主要的功能,了解JVM为我们提供了些什么
1)辅助功能
2)调试
3)线程
4)堆
5)JNI
6)事件
7)杂项
4.事件
如下是JVM TI支持的一些事件的回调方法格式,通过如上的Event Management系列注册回调方法,而具体回调方法的格式将在此定义,详细可参见JVM TI参考文档的Event Index 部分
5.实现范例讲解(jvm hprof):
Hprof是JVM自带的一个堆/性能剖析工具,具体详细功能说明可以参见Hprof说明文档 。本部分将通过分析Hprof的执行剖析(CPU Sample)部分的源码,来了解我们如何利用JVM TI进行相关的性能剖析的。
Hprof的CPU Sample功能处理原理上是定期地分析线程中的信息,在处理上我们需要的功能是定时触发和分析线程信息。Hprof的代码可以在JAVA_HOME/demo/jvmti/hprof中获取。
1)启动和停止:首先我们要定义的当时就是Agetn的启动和停止回调
(hprof_init.h) JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved); JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm);
在hprof_init.c中定义了这两个回调的函数的实现,其中Agent_OnLoad我们可以理解为入口的函数,我们将从这个地方开始
2)获得jvmtiEnv:如我们前面知道的,jvmtiEnv代表了一个同向JVM内部的连接,在调用任何功能之前,我们首先需要获jvmtiEnv的指针
(hprof_init.c) jvmtiEnv *jvmti = NULL; jint res; jint jvmtiCompileTimeMajorVersion; jint jvmtiCompileTimeMinorVersion; jint jvmtiCompileTimeMicroVersion; res = JVM_FUNC_PTR(gdata->jvm,GetEnv) (gdata->jvm, (void **)&jvmti, JVMTI_VERSION_1); /* 此处把宏JVM_FUNC_PTR展开,变成 *(*((*(env))->GetEnv))(gdata->jvm, (void **)&jvmti, JVMTI_VERSION_1) */
3)设置Capability:对一些Optional的功能,我们要通过设置Capability开启相应的功能,譬如如下部分
(hprof_init.c) jvmtiCapabilities needed_capabilities; jvmtiCapabilities potential_capabilities; …… if (gdata->cpu_timing || gdata->cpu_sampling) { #if 0 /* Not needed until we call JVMTI for CpuTime */ needed_capabilities.can_get_thread_cpu_time = 1; needed_capabilities.can_get_current_thread_cpu_time = 1; #endif needed_capabilities.can_generate_exception_events = 1; } ……
最后进行一个addCapability的操作
(hprof_init.c) void addCapabilities(jvmtiCapabilities *pcapabilities) { jvmtiError error; error = JVMTI_FUNC_PTR(gdata->jvmti,AddCapabilities) (gdata->jvmti, pcapabilities); if (error != JVMTI_ERROR_NONE) { HPROF_ERROR(JNI_FALSE, "Unable to get necessary JVMTI capabilities."); error_exit_process(1); /* Kill entire process, no core dump wanted */ } }
4)注册事件回调和注册时间:接下来我们需要注册回调方法,对于我们的范例,我们需要关注VM初始化事件,在初始化事件中开始Sample线程
static void set_callbacks(jboolean on) { jvmtiEventCallbacks callbacks; (void)memset(&callbacks,0,sizeof(callbacks)); if ( ! on ) { setEventCallbacks(&callbacks); return; } /* JVMTI_EVENT_VM_INIT */ callbacks.VMInit = &cbVMInit; /* JVMTI_EVENT_VM_DEATH */ callbacks.VMDeath = &cbVMDeath; …… } static void setup_event_mode(jboolean onload_set_only, jvmtiEventMode state) { if ( onload_set_only ) { setEventNotificationMode(state, JVMTI_EVENT_VM_INIT, NULL); setEventNotificationMode(state, JVMTI_EVENT_VM_DEATH, NULL); …… }
OK,一切准备就绪,坐等VM初始化事件发生
5)VM初始化时间:VM开始初始化,我们创建Sample线程(我们在上面设置的VM初始化事件回调是cbVMInit)
(hprof_init.c) static void JNICALL cbVMInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) { …… /* Start up cpu sampling thread if we need it */ if ( gdata->cpu_sampling ) { /* Note: this could also get started later (see cpu) */ cpu_sample_init(env); } …… } (hprof_cpu.c) void cpu_sample_init(JNIEnv *env) { gdata->cpu_sampling = JNI_TRUE; /* Create the raw monitors needed */ gdata->cpu_loop_lock = createRawMonitor("HPROF cpu loop lock"); gdata->cpu_sample_lock = createRawMonitor("HPROF cpu sample lock"); rawMonitorEnter(gdata->cpu_loop_lock); { createAgentThread(env, "HPROF cpu sampling thread", &cpu_loop_function); /* Wait for cpu_loop_function() to notify us it has started. */ rawMonitorWait(gdata->cpu_loop_lock, 0); } rawMonitorExit(gdata->cpu_loop_lock); }
6)利用RawMonitor做定时器
(hprof_cpu.c) static void JNICALL cpu_loop_function(jvmtiEnv *jvmti, JNIEnv *env, void *p) { …… /* This is the normal short timed wait before getting a sample */ rawMonitorWait(gdata->cpu_sample_lock, (jlong)gdata->sample_interval); …… /* Sample all the threads and update trace costs */ if ( !gdata->pause_cpu_sampling) { tls_sample_all_threads(env); } …… }
7)分析线程信息
(hprof_tls.c) /* Sample ALL threads and update the trace costs */ void tls_sample_all_threads(JNIEnv *env) { ThreadList list; jthread *threads; SerialNumber *serial_nums; table_lock_enter(gdata->tls_table); { int max_count; int nbytes; int i; /* Get buffers to hold thread list and serial number list */ max_count = table_element_count(gdata->tls_table); nbytes = (int)sizeof(jthread)*max_count; threads = (jthread*)HPROF_MALLOC(nbytes); nbytes = (int)sizeof(SerialNumber)*max_count; serial_nums = (SerialNumber*)HPROF_MALLOC(nbytes); /* Get list of threads and serial numbers */ list.threads = threads; list.infos = NULL; list.serial_nums = serial_nums; list.count = 0; list.env = env; table_walk_items(gdata->tls_table, &get_thread_list, (void*)&list); /* Increment the cost on the traces for these threads */ trace_increment_all_sample_costs(list.count, threads, serial_nums, gdata->max_trace_depth, JNI_FALSE); /* Loop over local refs and free them */ for ( i = 0 ; i < list.count ; i++ ) { if ( threads[i] != NULL ) { deleteLocalReference(env, threads[i]); } } } table_lock_exit(gdata->tls_table); /* Free up allocated space */ HPROF_FREE(threads); HPROF_FREE(serial_nums); }