`
ayufox
  • 浏览: 273381 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

[Java性能剖析]JPDA 2)JVM TI

    博客分类:
  • JVM
阅读更多

      参考: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一起启动

-agentlib:<agent-lib-name>=<options>
The name following -agentlib: is the name of the library to load. Lookup of the library, both its full name and location, proceeds in a platform-specific manner. Typically, the <agent-lib-name> is expanded to an operating system specific file name. The <options> will be passed to the agent on start-up. For example, if the option -agentlib:foo=opt1,opt2 is specified, the VM will attempt to load the shared library foo.dll from the system PATH under WindowsTM or libfoo.so from the LD_LIBRARY_PATH under the SolarisTM operating environment.
-agentpath:<path-to-agent>=<options>
The path following -agentpath: is the absolute path from which to load the library. No library name expansion will occur. The <options> will be passed to the agent on start-up. For example, if the option -agentpath:c:\myLibs\foo.dll=opt1,opt2 is specified, the VM will attempt to load the shared library c:/myLibs/foo.dll.

     如上在JVM启动参数中指定启动Agent,譬如TPTP的性能剖析Agent就是使用这种方式装载的

-agentlib:JPIBootLoader=JPIAgent:server=enabled;CGProf;

    大家可能会很奇怪地发现,JVM的调试agent启动方式是如下,其实如下是JVMDI的方式,JDK5开始后开始支持-agentlib:jdwp的方式,详细参见《Connection and Invocation Details

-Xrunjdwp:transport=dt_shmem,address=jdbconn,server=y,suspend=n

    与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)辅助功能

  • Memory Management系列:JVM TI为Agent提供了内存分配和释放的接口,这个功能与JVM内部无关
  • Raw Monitor系列:类似于互排斥量,通过Raw Monitor来保护执行区域,与Memory Management系列一样是一个辅助性的功能

     2)调试

  • Force Early Return系列:这个系列能够控制JVM终止当前正在执行的函数,并返回一个值回去
  • Local Variable系列:通过这个系列可以修改本地变量的值,主要用于调试用途
  • Breakpoint系列:可以通过这个系列设置断点、清除断点,主要用于调试用途
  • Watched Field系列:通过这个系列设置要观察的属性,当属性被访问时触发事件回调(相当于注册事件)

     3)线程

  • Thread系列:这个系列提供了JVM线程相关信息的访问,包括获得所有线程信息、获得当前线程信息、获得线程状态、获得线程栈、挂起线程、停止线程、打断线程(Interrupt)、获得线程Monitor等等
  • Thread Group系列:这个系列提供了JVM线程组相关信息的访问,包括获得线程组及组下的线程信息等等
    Stack Frame系列:这个系列提供了访问JVM线程堆栈信息,一般线程系列联合使用,包括获得所有线程栈、获得指定线程的线程栈、获得栈深度、获得栈位置、POP出栈等
  • Stack Frame系列:这个系列提供了访问JVM线程堆栈信息,一般线程系列联合使用,包括获得所有线程栈、获得指定线程的线程栈、获得栈深度、获得栈位置、POP出栈等

     4)堆

  • Heap/ Heap (1.0)系列:通过这个系列可以访问堆内存中的对象数据,包括遍历、打TAG(后续可以通过TAG查询到所有打了TAG的对象)、GC、遍历某个类的对象等等
  • Class系列:通过这个系列可以对加载类访问和处理,包括获得类信息、获得加载器信息、重新加载类定义等。其中我们可以通过java.lang.instrutment,使用Java语言实现重新加载类定义的功能。
    Object系列:获得对象相关的信息,譬如对象的大小、HashCode和Monitor。
  • Field/Method系列:获取属性相关的信息,相当于C/C++版的java.lang.reflect,除此之外提供了一些额外的信息,譬如可以获取到方法的字节码、Max Locals(即jvm汇编中的 .limit local xx 这个汇编指令中的xx)
  • Class Loader Search系列:通过这个系列可以增加类加载路径,譬如BootstrapClassLoader的搜索路径(默认是jre/lib)、譬如SystemClassLoader的搜索路径(classpath定义)

     5)JNI

  • JNI Function Interception系列:这个系列通过修改JNI Table的方式提供对JNI方法的拦截,可以理解为JNI函数的一个拦截器

     6)事件

  • Event Management系列:通过这个系列的API我们可以向JVM设置回调方法,JVM在事件发生时回调这些方法,譬如进入方法的事件、线程停止的事件等。一般用于调试,虽然也可以通过事件的方式来进行性能剖析(譬如拦截方法的进入和退出事件),但使用直接字节码增强的方式在性能上会更加有效。具体可以处理的事件可以参见后面的事件部分。

     7)杂项

  • Extension Mechanism系列:这个系列允许JVM TI的实现者(JVM)在基准API的基础上提供更丰富的功能,譬如定义新的事件类型等。
  • Capability系列:相当于告诉JVM TI需要允许访问哪些功能,对于JVM TI来说,有些功能(Capability)默认是提供的(Required Functionality),即不需要Agent告诉(调用Capability的接口)JVM TI,而对一些则是默认不提供的(Optional Functionality),在获取该功能之前,Agent必须先告诉(调用Capability的接口)JVM TI。哪些是Required哪些是Optional,可以参阅JVM TI参考文档的jvmtiCapabilities - The Capabilities Structure部分 )
  • Timers系列:可以通过这个系列获得时间相关的信息,譬如线程的CPU时间等
  • System Properties系列:相当于C/C++版的System.getProperty/System.setProperty/System.getProperties
  • General系列:杂项,包括C/C++版的System的env功能、获得版本号、Verbose Flag设置等

     4.事件
     如下是JVM TI支持的一些事件的回调方法格式,通过如上的Event Management系列注册回调方法,而具体回调方法的格式将在此定义,详细可参见JVM TI参考文档的Event Index 部分

  • Breakpoint
  • Class File Load Hook/Class Load/Class Prepare
  • Compiled Method Load/Compiled Method Unload
  • Data Dump Request
  • Dynamic Code Generated
  • Exception/Exception Catch
  • Field Access/Field Modification
  • Frame Pop
  • Garbage Collection Finish/Garbage Collection Start
  • Method Entry/Method Exit
  • Monitor Contended Enter/Monitor Contended Entered/Monitor Wait/Monitor Waited
  • Native Method Bind
  • Object Free
  • Resource Exhausted
  • Single Step
  • Thread End/Thread Start
  • VM Death Event/VM Initialization Event/VM Object Allocation

      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);

}
 

 

3
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics