]> <tm>JVM</tm> Tool Interface The JVM Tool Interface () is a programming interface used by development and monitoring tools. It provides both a way to inspect the state and to control the execution of applications running in the Java virtual machine (VM).

is intended to provide a VM interface for the full breadth of tools that need access to VM state, including but not limited to: profiling, debugging, monitoring, thread analysis, and coverage analysis tools.

may not be available in all implementations of the Java virtual machine.

is a two-way interface. A client of , hereafter called an agent, can be notified of interesting occurrences through events. can query and control the application through many functions, either in response to events or independent of them.

Agents run in the same process with and communicate directly with the virtual machine executing the application being examined. This communication is through a native interface (). The native in-process interface allows maximal control with minimal intrusion on the part of a tool. Typically, agents are relatively compact. They can be controlled by a separate process which implements the bulk of a tool's function without interfering with the target application's normal execution. Tools can be written directly to or indirectly through higher level interfaces. The Java Platform Debugger Architecture includes , but also contains higher-level, out-of-process debugger interfaces. The higher-level interfaces are more appropriate than for many tools. For more information on the Java Platform Debugger Architecture, see the Java Platform Debugger Architecture website. Agents can be written in any native language that supports C language calling conventions and C or C++ definitions.

The function, event, data type, and constant definitions needed for using are defined in the include file jvmti.h. To use these definitions add the J2SE include directory to your include path and add #include <jvmti.h> to your source code. An agent is deployed in a platform specific manner but is typically the platform equivalent of a dynamic library. On the Windows operating system, for example, an agent library is a "Dynamic Linked Library" (DLL). On the Solaris Operating Environment, an agent library is a shared object (.so file).

An agent may be started at VM startup by specifying the agent library name using a command line option. Some implementations may support a mechanism to start agents in the live phase. The details of how this is initiated are implementation specific. A native JVMTI Agent may be statically linked with the VM. The manner in which the library and VM image are combined is implementation-dependent. An agent L whose image has been combined with the VM is defined as statically linked if and only if the agent exports a function called Agent_OnLoad_L.

If a statically linked agent L exports a function called Agent_OnLoad_L and a function called Agent_OnLoad, the Agent_OnLoad function will be ignored. If an agent L is statically linked, an Agent_OnLoad_L function will be invoked with the same arguments and expected return value as specified for the Agent_OnLoad function. An agent L that is statically linked will prohibit an agent of the same name from being loaded dynamically.

The VM will invoke the Agent_OnUnload_L function of the agent, if such a function is exported, at the same point during startup as it would have called the dynamic entry point Agent_OnUnLoad. If a statically linked agent L exports a function called Agent_OnUnLoad_L and a function called Agent_OnUnLoad, the Agent_OnUnLoad function will be ignored.

If an agent L is statically linked, an Agent_OnAttach_L function will be invoked with the same arguments and expected return value as specified for the Agent_OnAttach function. If a statically linked agent L exports a function called Agent_OnAttach_L and a function called Agent_OnAttach, the Agent_OnAttach function will be ignored. The term "command-line option" is used below to mean options supplied in the JavaVMInitArgs argument to the JNI_CreateJavaVM function of the JNI Invocation API.

One of the two following command-line options is used on VM startup to properly load and run agents. These arguments identify the library containing the agent as well as an options string to be passed in at startup.

-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 Windows or libfoo.so from the LD_LIBRARY_PATH under the Solaris operating environment. If the agent library is statically linked into the executable then no actual loading takes place.

-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. If the agent library is statically linked into the executable then no actual loading takes place.

For a dynamic shared library agent, the start-up routine Agent_OnLoad in the library will be invoked. If the agent library is statically linked into the executable then the system will attempt to invoke the Agent_OnLoad_<agent-lib-name> entry point where <agent-lib-name> is the basename of the agent. In the above example -agentpath:c:\myLibs\foo.dll=opt1,opt2, the system will attempt to find and call the Agent_OnLoad_foo start-up routine.

Libraries loaded with -agentlib: or -agentpath: will be searched for JNI native method implementations to facilitate the use of Java programming language code in tools, as is needed for bytecode instrumentation.

The agent libraries will be searched after all other libraries have been searched (agents wishing to override or intercept the native method implementations of non-agent methods can use the NativeMethodBind event).

These switches do the above and nothing more - they do not change the state of the VM or . No command line options are needed to enable or aspects of , this is handled programmatically by the use of capabilities. The VM starts each agent by invoking a start-up function. If the agent is started in the OnLoad phase the function Agent_OnLoad or Agent_OnLoad_L for statically linked agents will be invoked. If the agent is started in the live phase the function Agent_OnAttach or Agent_OnAttach_L for statically linked agents will be invoked. Exactly one call to a start-up function is made per agent. If an agent is started during the OnLoad phase then its agent library must export a start-up function with the following prototype: JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) Or for a statically linked agent named 'L': JNIEXPORT jint JNICALL Agent_OnLoad_L(JavaVM *vm, char *options, void *reserved) The VM will start the agent by calling this function. It will be called early enough in VM initialization that:

  • system properties may be set before they have been used in the start-up of the VM
  • the full set of capabilities is still available (note that capabilities that configure the VM may only be available at this time--see the Capability function section)
  • no bytecodes have executed
  • no classes have been loaded
  • no objects have been created

The VM will call the Agent_OnLoad or Agent_OnLoad_<agent-lib-name> function with <options> as the second argument - that is, using the command-line option examples, "opt1,opt2" will be passed to the char *options argument of Agent_OnLoad. The options argument is encoded as a modified UTF-8 string. If =<options> is not specified, a zero length string is passed to options. The lifespan of the options string is the Agent_OnLoad or Agent_OnLoad_<agent-lib-name> call. If needed beyond this time the string or parts of the string must be copied. The period between when Agent_OnLoad is called and when it returns is called the OnLoad phase. Since the VM is not initialized during the OnLoad phase, the set of allowed operations inside Agent_OnLoad is restricted (see the function descriptions for the functionality available at this time). The agent can safely process the options and set event callbacks with . Once the VM initialization event is received (that is, the VMInit callback is invoked), the agent can complete its initialization. Early startup is required so that agents can set the desired capabilities, many of which must be set before the VM is initialized. In JVMDI, the -Xdebug command-line option provided very coarse-grain control of capabilities. JVMPI implementations use various tricks to provide a single "JVMPI on" switch. No reasonable command-line option could provide the fine-grain of control required to balance needed capabilities vs performance impact. Early startup is also needed so that agents can control the execution environment - modifying the file system and system properties to install their functionality.

The return value from Agent_OnLoad or Agent_OnLoad_<agent-lib-name> is used to indicate an error. Any value other than zero indicates an error and causes termination of the VM. A VM may support a mechanism that allows agents to be started in the VM during the live phase. The details of how this is supported, are implementation specific. For example, a tool may use some platform specific mechanism, or implementation specific API, to attach to the running VM, and request it start a given agent.

If an agent is started during the live phase then its agent library must export a start-up function with the following prototype: JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char *options, void *reserved) Or for a statically linked agent named 'L': JNIEXPORT jint JNICALL Agent_OnAttach_L(JavaVM* vm, char *options, void *reserved)

The VM will start the agent by calling this function. It will be called in the context of a thread that is attached to the VM. The first argument <vm> is the Java VM. The <options> argument is the startup options provided to the agent. <options> is encoded as a modified UTF-8 string. If startup options were not provided, a zero length string is passed to options. The lifespan of the options string is the Agent_OnAttach or Agent_OnAttach_<agent-lib-name> call. If needed beyond this time the string or parts of the string must be copied.

Note that some capabilities may not be available in the live phase.

The Agent_OnAttach or Agent_OnAttach_<agent-lib-name > function initializes the agent and returns a value to the VM to indicate if an error occurred. Any value other than zero indicates an error. An error does not cause the VM to terminate. Instead the VM ignores the error, or takes some implementation specific action -- for example it might print an error to standard error, or record the error in a system log. The library may optionally export a shutdown function with the following prototype: JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) Or for a statically linked agent named 'L': JNIEXPORT void JNICALL Agent_OnUnload_L(JavaVM *vm) This function will be called by the VM when the library is about to be unloaded. The library will be unloaded (unless it is statically linked into the executable) and this function will be called if some platform specific mechanism causes the unload (an unload mechanism is not specified in this document) or the library is (in effect) unloaded by the termination of the VM whether through normal termination or VM failure, including start-up failure. Uncontrolled shutdown is, of couse, an exception to this rule. Note the distinction between this function and the VM Death event: for the VM Death event to be sent, the VM must have run at least to the point of initialization and a valid environment must exist which has set a callback for VMDeath and enabled the event. None of these are required for Agent_OnUnload or Agent_OnUnload_<agent-lib-name> and this function is also called if the library is unloaded for other reasons. In the case that a VM Death event is sent, it will be sent before this function is called (assuming this function is called due to VM termination). This function can be used to clean-up resources allocated by the agent. Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a JAVA_TOOL_OPTIONS variable is provided so that agents may be launched in these cases.

Platforms which support environment variables or other named strings, may support the JAVA_TOOL_OPTIONS variable. This variable will be broken into options at white-space boundaries. White-space characters include space, tab, carriage-return, new-line, vertical-tab, and form-feed. Sequences of white-space characters are considered equivalent to a single white-space character. No white-space is included in the options unless quoted. Quoting is as follows:

  • All characters enclosed between a pair of single quote marks (''), except a single quote, are quoted.
  • Double quote characters have no special meaning inside a pair of single quote marks.
  • All characters enclosed between a pair of double quote marks (""), except a double quote, are quoted.
  • Single quote characters have no special meaning inside a pair of double quote marks.
  • A quoted part can start or end anywhere in the variable.
  • White-space characters have no special meaning when quoted -- they are included in the option like any other character and do not mark white-space boundaries.
  • The pair of quote marks is not included in the option.
JNI_CreateJavaVM (in the JNI Invocation API) will prepend these options to the options supplied in its JavaVMInitArgs argument. Platforms may disable this feature in cases where security is a concern; for example, the Reference Implementation disables this feature on Unix systems when the effective user or group ID differs from the real ID. This feature is intended to support the initialization of tools -- specifically including the launching of native or Java programming language agents. Multiple tools may wish to use this feature, so the variable should not be overwritten, instead, options should be appended to the variable. Note that since the variable is processed at the time of the JNI Invocation API create VM call, options processed by a launcher (e.g., VM selection options) will not be handled.
The specification supports the use of multiple simultaneous agents. Each agent has its own environment. That is, the state is separate for each agent - changes to one environment do not affect the others. The state of a environment includes:
  • the event callbacks
  • the set of events which are enabled
  • the capabilities
  • the memory allocation/deallocation hooks
Although their state is separate, agents inspect and modify the shared state of the VM, they also share the native environment in which they execute. As such, an agent can perturb the results of other agents or cause them to fail. It is the responsibility of the agent writer to specify the level of compatibility with other agents. implementations are not capable of preventing destructive interactions between agents. Techniques to reduce the likelihood of these occurrences are beyond the scope of this document.

An agent creates a environment by passing a version as the interface ID to the JNI Invocation API function GetEnv. See Accessing Functions for more details on the creation and use of environments. Typically, environments are created by calling GetEnv from Agent_OnLoad. This interface does not include some events that one might expect in an interface with profiling support. Some examples include object allocation events and full speed method enter and exit events. The interface instead provides support for bytecode instrumentation, the ability to alter the Java virtual machine bytecode instructions which comprise the target program. Typically, these alterations are to add "events" to the code of a method - for example, to add, at the beginning of a method, a call to MyProfiler.methodEntered(). Since the changes are purely additive, they do not modify application state or behavior. Because the inserted agent code is standard bytecodes, the VM can run at full speed, optimizing not only the target program but also the instrumentation. If the instrumentation does not involve switching from bytecode execution, no expensive state transitions are needed. The result is high performance events. This approach also provides complete control to the agent: instrumentation can be restricted to "interesting" portions of the code (e.g., the end user's code) and can be conditional. Instrumentation can run entirely in Java programming language code or can call into the native agent. Instrumentation can simply maintain counters or can statistically sample events.

Instrumentation can be inserted in one of three ways:

  • Static Instrumentation: The class file is instrumented before it is loaded into the VM - for example, by creating a duplicate directory of *.class files which have been modified to add the instrumentation. This method is extremely awkward and, in general, an agent cannot know the origin of the class files which will be loaded.
  • Load-Time Instrumentation: When a class file is loaded by the VM, the raw bytes of the class file are sent for instrumentation to the agent. The event, triggered by the class load, provides this functionality. This mechanism provides efficient and complete access to one-time instrumentation.
  • Dynamic Instrumentation: A class which is already loaded (and possibly even running) is modified. This optional feature is provided by the event, triggered by calling the function. Classes can be modified multiple times and can be returned to their original state. The mechanism allows instrumentation which changes during the course of execution.

The class modification functionality provided in this interface is intended to provide a mechanism for instrumentation (the event and the function) and, during development, for fix-and-continue debugging (the function).

Care must be taken to avoid perturbing dependencies, especially when instrumenting core classes. For example, an approach to getting notification of every object allocation is to instrument the constructor on Object. Assuming that the constructor is initially empty, the constructor could be changed to: public Object() { MyProfiler.allocationTracker(this); } However, if this change was made using the event then this might impact a typical VM as follows: the first created object will call the constructor causing a class load of MyProfiler; which will then cause object creation, and since MyProfiler isn't loaded yet, infinite recursion; resulting in a stack overflow. A refinement of this would be to delay invoking the tracking method until a safe time. For example, trackAllocations could be set in the handler for the VMInit event. static boolean trackAllocations = false; public Object() { if (trackAllocations) { MyProfiler.allocationTracker(this); } }

The allows native methods to be instrumented by the use of wrapper methods. uses modified UTF-8 to encode character strings. This is the same encoding used by JNI. Modified UTF-8 differs from standard UTF-8 in the representation of supplementary characters and of the null character. See the Modified UTF-8 Strings section of the JNI specification for details. Since this interface provides access to the state of applications running in the Java virtual machine; terminology refers to the Java platform and not the native platform (unless stated otherwise). For example:

  • "thread" means Java programming language thread.
  • "stack frame" means Java virtual machine stack frame.
  • "class" means Java programming language class.
  • "heap" means Java virtual machine heap.
  • "monitor" means Java programming language object monitor.

Sun, Sun Microsystems, the Sun logo, Java, and JVM are trademarks or registered trademarks of Oracle and/or its affiliates, in the U.S. and other countries. Native code accesses features by calling functions. Access to functions is by use of an interface pointer in the same manner as Java Native Interface (JNI) functions are accessed. The interface pointer is called the environment pointer.

An environment pointer is a pointer to an environment and has the type jvmtiEnv*. An environment has information about its connection. The first value in the environment is a pointer to the function table. The function table is an array of pointers to functions. Every function pointer is at a predefined offset inside the array.

When used from the C language: double indirection is used to access the functions; the environment pointer provides context and is the first parameter of each function call; for example: jvmtiEnv *jvmti; ... jvmtiError err = (*jvmti)->GetLoadedClasses(jvmti, &class_count, &classes);

When used from the C++ language: functions are accessed as member functions of jvmtiEnv; the environment pointer is not passed to the function call; for example: jvmtiEnv *jvmti; ... jvmtiError err = jvmti->GetLoadedClasses(&class_count, &classes); Unless otherwise stated, all examples and declarations in this specification use the C language.

A environment can be obtained through the JNI Invocation API GetEnv function: jvmtiEnv *jvmti; ... (*jvm)->GetEnv(jvm, &jvmti, JVMTI_VERSION_1_0); Each call to GetEnv creates a new connection and thus a new environment. The version argument of GetEnv must be a version. The returned environment may have a different version than the requested version but the returned environment must be compatible. GetEnv will return JNI_EVERSION if a compatible version is not available, if is not supported or is not supported in the current VM configuration. Other interfaces may be added for creating environments in specific contexts. Each environment has its own state (for example, desired events, event handling functions, and capabilities). An environment is released with . Thus, unlike JNI which has one environment per thread, environments work across threads and are created dynamically. functions always return an error code via the function return value. Some functions can return additional values through pointers provided by the calling function. In some cases, functions allocate memory that your program must explicitly deallocate. This is indicated in the individual function descriptions. Empty lists, arrays, sequences, etc are returned as NULL.

In the event that the function encounters an error (any return value other than JVMTI_ERROR_NONE) the values of memory referenced by argument pointers is undefined, but no memory will have been allocated and no global references will have been allocated. If the error occurs because of invalid input, no action will have occurred. functions identify objects with JNI references ( and ) and their derivatives ( and ). References passed to functions can be either global or local, but they must be strong references. All references returned by functions are local references--these local references are created during the call. Local references are a resource that must be managed (see the JNI Documentation). When threads return from native code all local references are freed. Note that some threads, including typical agent threads, will never return from native code. A thread is ensured the ability to create sixteen local references without the need for any explicit management. For threads executing a limited number of calls before returning from native code (for example, threads processing events), it may be determined that no explicit management is needed. However, long running agent threads will need explicit local reference management--usually with the JNI functions PushLocalFrame and PopLocalFrame. Conversely, to preserve references beyond the return from native code, they must be converted to global references. These rules do not apply to and as they are not s. Unless the function explicitly states that the agent must bring a thread or the VM to a particular state (for example, suspended), the implementation is responsible for bringing the VM to a safe and consistent state for performing the function. functions never throw exceptions; error conditions are communicated via the function return value. Any existing exception state is preserved across a call to a function. See the Java Exceptions section of the JNI specification for information on handling exceptions. These functions provide for the allocation and deallocation of memory used by functionality and can be used to provide working memory for agents. Memory managed by is not compatible with other memory allocation libraries and mechanisms. Allocate Allocate an area of memory through the allocator. The allocated memory should be freed with . jvmdi The number of bytes to allocate. jlong is used for compatibility with JVMDI. On return, a pointer to the beginning of the allocated memory. If size is zero, NULL is returned. Memory request cannot be honored. is less than zero. Deallocate Deallocate mem using the allocator. This function should be used to deallocate any memory allocated and returned by a function (including memory allocated with ). All allocated memory must be deallocated or the memory cannot be reclaimed. jvmdi the call is ignored A pointer to the beginning of the allocated memory. Please ignore "On return, the elements are set." keep it from generating "On return, the elements are set" Get Thread State Get the state of a thread. The state of the thread is represented by the answers to the hierarchical set of questions below:

  • Alive?
    • Not alive.
      • Why not alive?
        • New.
        • Terminated (JVMTI_THREAD_STATE_TERMINATED)
    • Alive (JVMTI_THREAD_STATE_ALIVE)
      • Suspended?
        • Suspended (JVMTI_THREAD_STATE_SUSPENDED)
        • Not suspended
      • Interrupted?
        • Interrupted (JVMTI_THREAD_STATE_INTERRUPTED)
        • Not interrupted.
      • In native?
        • In native code (JVMTI_THREAD_STATE_IN_NATIVE)
        • In Java programming language code
      • What alive state?
        • Runnable (JVMTI_THREAD_STATE_RUNNABLE)
        • Blocked (JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER)
        • Waiting (JVMTI_THREAD_STATE_WAITING)
          • Timed wait?
            • Indefinite (JVMTI_THREAD_STATE_WAITING_INDEFINITELY
            • Timed (JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT)
          • Why waiting?
            • Object.wait (JVMTI_THREAD_STATE_IN_OBJECT_WAIT)
            • LockSupport.park (JVMTI_THREAD_STATE_PARKED)
            • Sleeping (JVMTI_THREAD_STATE_SLEEPING)

The answers are represented by the following bit vector. Thread is alive. Zero if thread is new (not started) or terminated. Thread has completed execution. Thread is runnable. Thread is waiting to enter a synchronization block/method or, after an Object.wait(), waiting to re-enter a synchronization block/method. Thread is waiting. Thread is waiting without a timeout. For example, Object.wait(). Thread is waiting with a maximum time to wait specified. For example, Object.wait(long). Thread is sleeping -- Thread.sleep(long). Thread is waiting on an object monitor -- Object.wait. Thread is parked, for example: LockSupport.park, LockSupport.parkUtil and LockSupport.parkNanos. Thread suspended. java.lang.Thread.suspend() or a suspend function (such as ) has been called on the thread. If this bit is set, the other bits refer to the thread state before suspension. Thread has been interrupted. Thread is in native code--that is, a native method is running which has not called back into the VM or Java programming language code.

This flag is not set when running VM compiled Java programming language code nor is it set when running VM code or VM support code. Native VM interface functions, such as JNI and functions, may be implemented as VM code. Defined by VM vendor. Defined by VM vendor. Defined by VM vendor. The following definitions are used to convert thread state to java.lang.Thread.State style states. Mask the state with this before comparison java.lang.Thread.State.NEW java.lang.Thread.State.TERMINATED java.lang.Thread.State.RUNNABLE java.lang.Thread.State.BLOCKED java.lang.Thread.State.WAITING java.lang.Thread.State.TIMED_WAITING Rules

There can be no more than one answer to a question, although there can be no answer (because the answer is unknown, does not apply, or none of the answers is correct). An answer is set only when the enclosing answers match. That is, no more than one of

  • JVMTI_THREAD_STATE_RUNNABLE
  • JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER
  • JVMTI_THREAD_STATE_WAITING
can be set (a J2SE compliant implementation will always set one of these if JVMTI_THREAD_STATE_ALIVE is set). And if any of these are set, the enclosing answer JVMTI_THREAD_STATE_ALIVE is set. No more than one of
  • JVMTI_THREAD_STATE_WAITING_INDEFINITELY
  • JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT
can be set (a J2SE compliant implementation will always set one of these if JVMTI_THREAD_STATE_WAITING is set). And if either is set, the enclosing answers JVMTI_THREAD_STATE_ALIVE and JVMTI_THREAD_STATE_WAITING are set. No more than one of
  • JVMTI_THREAD_STATE_IN_OBJECT_WAIT
  • JVMTI_THREAD_STATE_PARKED
  • JVMTI_THREAD_STATE_SLEEPING
can be set. And if any of these is set, the enclosing answers JVMTI_THREAD_STATE_ALIVE and JVMTI_THREAD_STATE_WAITING are set. Also, if JVMTI_THREAD_STATE_SLEEPING is set, then JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT is set. If a state A is implemented using the mechanism of state B then it is state A which is returned by this function. For example, if Thread.sleep(long) is implemented using Object.wait(long) then it is still JVMTI_THREAD_STATE_SLEEPING which is returned. More than one of
  • JVMTI_THREAD_STATE_SUSPENDED
  • JVMTI_THREAD_STATE_INTERRUPTED
  • JVMTI_THREAD_STATE_IN_NATIVE
can be set, but if any is set, JVMTI_THREAD_STATE_ALIVE is set.

And finally, JVMTI_THREAD_STATE_TERMINATED cannot be set unless JVMTI_THREAD_STATE_ALIVE is not set.

The thread state representation is designed for extension in future versions of the specification; thread state values should be used accordingly, that is they should not be used as ordinals. Most queries can be made by testing a single bit, if use in a switch statement is desired, the state bits should be masked with the interesting bits. All bits not defined above are reserved for future use. A VM, compliant to the current specification, must set reserved bits to zero. An agent should ignore reserved bits -- they should not be assumed to be zero and thus should not be included in comparisons.

Examples

Note that the values below exclude reserved and vendor bits.

The state of a thread blocked at a synchronized-statement would be: JVMTI_THREAD_STATE_ALIVE + JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER The state of a thread which hasn't started yet would be: 0 The state of a thread at a Object.wait(3000) would be: JVMTI_THREAD_STATE_ALIVE + JVMTI_THREAD_STATE_WAITING + JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT + JVMTI_THREAD_STATE_MONITOR_WAITING The state of a thread suspended while runnable would be: JVMTI_THREAD_STATE_ALIVE + JVMTI_THREAD_STATE_RUNNABLE + JVMTI_THREAD_STATE_SUSPENDED

Testing the State

In most cases, the thread state can be determined by testing the one bit corresponding to that question. For example, the code to test if a thread is sleeping: jint state; jvmtiError err; err = (*jvmti)->GetThreadState(jvmti, thread, &state); if (err == JVMTI_ERROR_NONE) { if (state & JVMTI_THREAD_STATE_SLEEPING) { ...

For waiting (that is, in Object.wait, parked, or sleeping) it would be: if (state & JVMTI_THREAD_STATE_WAITING) { ... For some states, more than one bit will need to be tested as is the case when testing if a thread has not yet been started: if ((state & (JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_TERMINATED)) == 0) { ... To distinguish timed from untimed Object.wait: if (state & JVMTI_THREAD_STATE_IN_OBJECT_WAIT) { if (state & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) { printf("in Object.wait(long timeout)\n"); } else { printf("in Object.wait()\n"); } }

Relationship to java.lang.Thread.State

The thread state represented by java.lang.Thread.State returned from java.lang.Thread.getState() is a subset of the information returned from this function. The corresponding java.lang.Thread.State can be determined by using the provided conversion masks. For example, this returns the name of the java.lang.Thread.State thread state: err = (*jvmti)->GetThreadState(jvmti, thread, &state); abortOnError(err); switch (state & JVMTI_JAVA_LANG_THREAD_STATE_MASK) { case JVMTI_JAVA_LANG_THREAD_STATE_NEW: return "NEW"; case JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED: return "TERMINATED"; case JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE: return "RUNNABLE"; case JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED: return "BLOCKED"; case JVMTI_JAVA_LANG_THREAD_STATE_WAITING: return "WAITING"; case JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING: return "TIMED_WAITING"; } new The thread to query. On return, points to state flags, as defined by the Thread State Flags. Get Current Thread Get the current thread. The current thread is the Java programming language thread which has called the function.

Note that most functions that take a thread as an argument will accept NULL to mean the current thread. new On return, points to the current thread. Get All Threads Get all live threads. The threads are Java programming language threads; that is, threads that are attached to the VM. A thread is live if java.lang.Thread.isAlive() would return true, that is, the thread has been started and has not yet died. The universe of threads is determined by the context of the environment, which typically is all threads attached to the VM. Note that this includes agent threads (see ). jvmdi On return, points to the number of running threads. On return, points to an array of references, one for each running thread. Suspend Thread Suspend the specified thread. If the calling thread is specified, this function will not return until some other thread calls . If the thread is currently suspended, this function does nothing and returns an error. jvmdi The thread to suspend. Thread already suspended. Suspend All Threads There has been no explicit call for this function, and it will thus be removed if there is no interest. Suspend all live threads except:

  • already suspended threads
  • those listed in
  • certain system (non application) threads, as determined by the VM implementation
The threads are Java programming language threads; native threads which are not attached to the VM are not Java programming language threads. A thread is live if java.lang.Thread.isAlive() would return true, that is, the thread has been started and has not yet died. The universe of threads is determined by the context of the environment, which, typically, is all threads attached to the VM, except critical VM internal threads and agent threads (see ).

If the calling thread is specified, all other threads are suspended first then the caller thread is suspended - this function will not return until some other thread calls .

The list of actually suspended threads is returned in . Suspension is as defined in . can be used to resume the suspended threads. new The number of threads in the list of threads not to be suspended. not an error if except_count == 0 The list of threads not to be suspended. On return, points to the number of threads suspended by this call. On return, points to an array of references, one for each thread suspended. A thread in was invalid. Both was NULL and was non-zero. Suspend Thread List Suspend the threads specified in the array. Threads may be resumed with or . If the calling thread is specified in the array, this function will not return until some other thread resumes it. Errors encountered in the suspension of a thread are returned in the array, not in the return value of this function. Threads that are currently suspended do not change state. jvmdi The number of threads to suspend. The list of threads to suspend. jvmtiError An agent supplied array of elements. On return, filled with the error code for the suspend of the corresponding thread. The error code will be if the thread was suspended by this call. Possible error codes are those specified for . Resume Thread Resume a suspended thread. Any threads currently suspended through a suspend function (eg. ) or java.lang.Thread.suspend() will resume execution; all other threads are unaffected. jvmdi The thread to resume. Thread was not suspended. The state of the thread has been modified, and is now inconsistent. Resume Thread List Resume the threads specified in the array. Any thread suspended through a suspend function (eg. ) or java.lang.Thread.suspend() will resume execution. jvmdi The number of threads to resume. The threads to resume. jvmtiError An agent supplied array of elements. On return, filled with the error code for the resume of the corresponding thread. The error code will be if the thread was suspended by this call. Possible error codes are those specified for . Stop Thread Send the specified asynchronous exception to the specified thread (similar to java.lang.Thread.stop). Normally, this function is used to kill the specified thread with an instance of the exception ThreadDeath. jvmdi The thread to stop. The asynchronous exception object. Interrupt Thread Interrupt the specified thread (similar to java.lang.Thread.interrupt). jvmdi The thread to interrupt. Get Thread Info The thread name, encoded as a modified UTF-8 string. The thread priority. See the thread priority constants: . Is this a daemon thread? The thread group to which this thread belongs. NULL if the thread has died. The context class loader associated with this thread. Get thread information. The fields of the structure are filled in with details of the specified thread. jvmdi The thread to query. jvmtiThreadInfo On return, filled with information describing the specified thread.

For JDK 1.1 implementations that don't recognize context class loaders, the context_class_loader field will be NULL. Get Owned Monitor Info Get information about the monitors owned by the specified thread. jvmdiClone The thread to query. The number of monitors returned. The array of owned monitors. Get Owned Monitor Stack Depth Info The owned monitor. The stack depth. Corresponds to the stack depth used in the Stack Frame functions. That is, zero is the current frame, one is the frame which called the current frame. And it is negative one if the implementation cannot determine the stack depth (e.g., for monitors acquired by JNI MonitorEnter). Get information about the monitors owned by the specified thread and the depth of the stack frame which locked them. new The thread to query. The number of monitors returned. jvmtiMonitorStackDepthInfo The array of owned monitor depth information. Get Current Contended Monitor Get the object, if any, whose monitor the specified thread is waiting to enter or waiting to regain through java.lang.Object.wait. jvmdi The thread to query. On return, filled with the current contended monitor, or NULL if there is none. Agent Start Function Agent supplied callback function. This function is the entry point for an agent thread started with . jvmtiEnv The environment. JNIEnv The JNI environment. The arg parameter passed to . Run Agent Thread Starts the execution of an agent thread. with the specified native function. The parameter is forwarded on to the start function (specified with ) as its single argument. This function allows the creation of agent threads for handling communication with another process or for handling events without the need to load a special subclass of java.lang.Thread or implementer of java.lang.Runnable. Instead, the created thread can run entirely in native code. However, the created thread does require a newly created instance of java.lang.Thread (referenced by the argument thread) to which it will be associated. The thread object can be created with JNI calls.

The following common thread priorities are provided for your convenience: Minimum possible thread priority Normal thread priority Maximum possible thread priority

The new thread is started as a daemon thread with the specified . If enabled, a event will be sent.

Since the thread has been started, the thread will be live when this function returns, unless the thread has died immediately.

The thread group of the thread is ignored -- specifically, the thread is not added to the thread group and the thread is not seen on queries of the thread group at either the Java programming language or levels.

The thread is not visible to Java programming language queries but is included in queries (for example, and ).

Upon execution of proc, the new thread will be attached to the VM--see the JNI documentation on Attaching to the VM. jvmdiClone The thread to run. jvmtiStartFunction The start function. NULL is passed to the start function The argument to the start function. The priority of the started thread. Any thread priority allowed by java.lang.Thread.setPriority can be used including those in . is less than or greater than Set Thread Local Storage The VM stores a pointer value associated with each environment-thread pair. This pointer value is called thread-local storage. This value is NULL unless set with this function. Agents can allocate memory in which they store thread specific information. By setting thread-local storage it can then be accessed with .

This function is called by the agent to set the value of the thread-local storage. supplies to the agent a pointer-size thread-local storage that can be used to record per-thread information. jvmpi Store to this thread. value is set to NULL The value to be entered into the thread-local storage. Get Thread Local Storage Called by the agent to get the value of the thread-local storage. jvmpi Retrieve from this thread. Pointer through which the value of the thread local storage is returned. If thread-local storage has not been set with the returned pointer is NULL. Get Top Thread Groups Return all top-level (parentless) thread groups in the VM. jvmdi On return, points to the number of top-level thread groups. On return, refers to a pointer to the top-level thread group array. Get Thread Group Info The parent thread group. The thread group's name, encoded as a modified UTF-8 string. The maximum priority for this thread group. Is this a daemon thread group? Get information about the thread group. The fields of the structure are filled in with details of the specified thread group. jvmdi The thread group to query. jvmtiThreadGroupInfo On return, filled with information describing the specified thread group. Get Thread Group Children Get the live threads and active subgroups in this thread group. jvmdi The group to query. On return, points to the number of live threads in this thread group. On return, points to an array of the live threads in this thread group. On return, points to the number of active child thread groups On return, points to an array of the active child thread groups. These functions provide information about the stack of a thread. Stack frames are referenced by depth. The frame at depth zero is the current frame.

Stack frames are as described in , That is, they correspond to method invocations (including native methods) but do not correspond to platform native or VM internal frames.

A implementation may use method invocations to launch a thread and the corresponding frames may be included in the stack as presented by these functions -- that is, there may be frames shown deeper than main() and run(). However this presentation must be consistent across all functionality which uses stack frames or stack depth. Information about a stack frame is returned in this structure. The method executing in this frame. The index of the instruction executing in this frame. -1 if the frame is executing a native method. Information about a set of stack frames is returned in this structure. On return, the thread traced. On return, the thread state. See . jvmtiFrameInfo On return, this agent allocated buffer is filled with stack frame information. On return, the number of records filled into frame_buffer. This will be min(max_frame_count, stackDepth). Get Stack Trace Get information about the stack of a thread. If is less than the depth of the stack, the topmost frames are returned, otherwise the entire stack is returned. The topmost frames, those most recently invoked, are at the beginning of the returned buffer.

The following example causes up to five of the topmost frames to be returned and (if there are any frames) the currently executing method name to be printed. jvmtiFrameInfo frames[5]; jint count; jvmtiError err; err = (*jvmti)->GetStackTrace(jvmti, aThread, 0, 5, frames, &count); if (err == JVMTI_ERROR_NONE && count >= 1) { char *methodName; err = (*jvmti)->GetMethodName(jvmti, frames[0].method, &methodName, NULL, NULL); if (err == JVMTI_ERROR_NONE) { printf("Executing method: %s", methodName); } } check example code.

The need not be suspended to call this function.

The function can be used to map locations to line numbers. Note that this mapping can be done lazily. jvmpi Fetch the stack trace of this thread. Begin retrieving frames at this depth. If non-negative, count from the current frame, the first frame retrieved is at depth start_depth. For example, if zero, start from the current frame; if one, start from the caller of the current frame; if two, start from the caller of the caller of the current frame; and so on. If negative, count from below the oldest frame, the first frame retrieved is at depth stackDepth + start_depth, where stackDepth is the count of frames on the stack. For example, if negative one, only the oldest frame is retrieved; if negative two, start from the frame called by the oldest frame. The maximum number of records to retrieve. jvmtiFrameInfo On return, this agent allocated buffer is filled with stack frame information. On return, points to the number of records filled in. For non-negative start_depth, this will be min(max_frame_count, stackDepth - start_depth). For negative start_depth, this will be min(max_frame_count, -start_depth). is positive and greater than or equal to stackDepth. Or is negative and less than -stackDepth. Get All Stack Traces Get information about the stacks of all live threads (including agent threads). If is less than the depth of a stack, the topmost frames are returned for that thread, otherwise the entire stack is returned. The topmost frames, those most recently invoked, are at the beginning of the returned buffer.

All stacks are collected simultaneously, that is, no changes will occur to the thread state or stacks between the sampling of one thread and the next. The threads need not be suspended. jvmtiStackInfo *stack_info; jint thread_count; int ti; jvmtiError err; err = (*jvmti)->GetAllStackTraces(jvmti, MAX_FRAMES, &stack_info, &thread_count); if (err != JVMTI_ERROR_NONE) { ... } for (ti = 0; ti < thread_count; ++ti) { jvmtiStackInfo *infop = &stack_info[ti]; jthread thread = infop->thread; jint state = infop->state; jvmtiFrameInfo *frames = infop->frame_buffer; int fi; myThreadAndStatePrinter(thread, state); for (fi = 0; fi < infop->frame_count; fi++) { myFramePrinter(frames[fi].method, frames[fi].location); } } /* this one Deallocate call frees all data allocated by GetAllStackTraces */ err = (*jvmti)->Deallocate(jvmti, stack_info); check example code. new The maximum number of records to retrieve per thread. jvmtiStackInfo On return, this buffer is filled with stack information for each thread. The number of records is determined by .

Note that this buffer is allocated to include the buffers pointed to by . These buffers must not be separately deallocated. The number of threads traced. Get Thread List Stack Traces Get information about the stacks of the supplied threads. If is less than the depth of a stack, the topmost frames are returned for that thread, otherwise the entire stack is returned. The topmost frames, those most recently invoked, are at the beginning of the returned buffer.

All stacks are collected simultaneously, that is, no changes will occur to the thread state or stacks between the sampling one thread and the next. The threads need not be suspended.

If a thread has not yet started or terminates before the stack information is collected, a zero length stack ( will be zero) will be returned and the thread can be checked.

See the example for the similar function . new The number of threads to trace. The list of threads to trace. The maximum number of records to retrieve per thread. jvmtiStackInfo On return, this buffer is filled with stack information for each thread. The number of records is determined by .

Note that this buffer is allocated to include the buffers pointed to by . These buffers must not be separately deallocated. An element in is not a thread object. Get Stack Trace--Asynchronous Get information about the entire stack of a thread (or a sub-section of it). This is the asynchronous version of and is reentrant and safe to call from asynchronous signal handlers. The stack trace is returned only for the calling thread.

The function can be used to map locations to line numbers. Note that this mapping can be done lazily. jvmpi If false, must be false. Return the stack showing model of the stack; otherwise, show the internal representation of the stack with inlined and optimized methods missing. If the virtual machine is using the Java Virtual Machine Specification stack model internally, this flag is ignored. The maximum number of records to retrieve. Retrieve this many unless the stack depth is less than max_count. jvmtiFrameInfo this information is not returned The agent passes in a buffer large enough to hold max_count records of . This buffer must be pre-allocated by the agent. On return, points to the number of records filled in.. The thread being used to call this function is not attached to the virtual machine. Calls must be made from attached threads. Get Frame Count Get the number of frames currently in the specified thread's call stack.

If this function is called for a thread actively executing bytecodes (for example, not the current thread and not suspended), the information returned is transient. jvmdi The thread to query. On return, points to the number of frames in the call stack. Pop Frame Pop the current frame of thread's stack. Popping a frame takes you to the previous frame. When the thread is resumed, the execution state of the thread is reset to the state immediately before the called method was invoked. That is (using terminology):

  • the current frame is discarded as the previous frame becomes the current one
  • the operand stack is restored--the argument values are added back and if the invoke was not invokestatic, objectref is added back as well
  • the Java virtual machine PC is restored to the opcode of the invoke instruction
Note however, that any changes to the arguments, which occurred in the called method, remain; when execution continues, the first instruction to execute will be the invoke.

Between calling PopFrame and resuming the thread the state of the stack is undefined. To pop frames beyond the first, these three steps must be repeated:

  • suspend the thread via an event (step, breakpoint, ...)
  • call PopFrame
  • resume the thread

A lock acquired by calling the called method (if it is a synchronized method) and locks acquired by entering synchronized blocks within the called method are released. Note: this does not apply to native locks or java.util.concurrent.locks locks.

Finally blocks are not executed.

Changes to global state are not addressed and thus remain changed.

The specified thread must be suspended (which implies it cannot be the current thread).

Both the called method and calling method must be non-native Java programming language methods.

No events are generated by this function. jvmdi The thread whose current frame is to be popped. Called or calling method is a native method. The implementation is unable to pop this frame. Thread was not suspended. There are less than two stack frames on the call stack. Get Frame Location

For a Java programming language frame, return the location of the instruction currently executing. jvmdiClone The thread of the frame to query. The depth of the frame to query. On return, points to the method for the current location. On return, points to the index of the currently executing instruction. Is set to -1 if the frame is executing a native method. Notify Frame Pop When the frame that is currently at is popped from the stack, generate a event. See the event for details. Only frames corresponding to non-native Java programming language methods can receive notification.

The specified thread must either be the current thread or the thread must be suspended. jvmdi The thread of the frame for which the frame pop event will be generated. The depth of the frame for which the frame pop event will be generated. The frame at depth is executing a native method. Thread was not suspended and was not the current thread. These functions allow an agent to force a method to return at any point during its execution. The method which will return early is referred to as the called method. The called method is the current method (as defined by ) for the specified thread at the time the function is called.

The specified thread must be suspended or must be the current thread. The return occurs when execution of Java programming language code is resumed on this thread. Between calling one of these functions and resumption of thread execution, the state of the stack is undefined.

No further instructions are executed in the called method. Specifically, finally blocks are not executed. Note: this can cause inconsistent states in the application.

A lock acquired by calling the called method (if it is a synchronized method) and locks acquired by entering synchronized blocks within the called method are released. Note: this does not apply to native locks or java.util.concurrent.locks locks.

Events, such as , are generated as they would be in a normal return.

The called method must be a non-native Java programming language method. Forcing return on a thread with only one frame on the stack causes the thread to exit when resumed. Force Early Return - Object This function can be used to return from a method whose result type is Object or a subclass of Object. new The thread whose current frame is to return early. The return value for the called frame. An object or NULL. Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame. The result type of the called method is not Object or a subclass of Object. The supplied is not compatible with the result type of the called method. Thread was not the current thread and was not suspended. There are no more frames on the call stack. Force Early Return - Int This function can be used to return from a method whose result type is int, short, char, byte, or boolean. new The thread whose current frame is to return early. The return value for the called frame. Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame. The result type of the called method is not int, short, char, byte, or boolean. Thread was not the current thread and was not suspended. There are no frames on the call stack. Force Early Return - Long This function can be used to return from a method whose result type is long. new The thread whose current frame is to return early. The return value for the called frame. Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame. The result type of the called method is not long. Thread was not the current thread and was not suspended. There are no frames on the call stack. Force Early Return - Float This function can be used to return from a method whose result type is float. new The thread whose current frame is to return early. The return value for the called frame. Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame. The result type of the called method is not float. Thread was not the current thread and was not suspended. There are no frames on the call stack. Force Early Return - Double This function can be used to return from a method whose result type is double. new The thread whose current frame is to return early. The return value for the called frame. Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame. The result type of the called method is not double. Thread was not the current thread and was not suspended. There are no frames on the call stack. Force Early Return - Void This function can be used to return from a method with no result type. That is, the called method must be declared void. new The thread whose current frame is to return early. Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame. The called method has a result type. Thread was not the current thread and was not suspended. There are no frames on the call stack. These functions are used to analyze the heap. Functionality includes the ability to view the objects in the heap and to tag these objects. A tag is a value associated with an object. Tags are explicitly set by the agent using the function or by callback functions such as .

Tags are local to the environment; that is, the tags of one environment are not visible in another.

Tags are jlong values which can be used simply to mark an object or to store a pointer to more detailed information. Objects which have not been tagged have a tag of zero. Setting a tag to zero makes the object untagged. Heap functions which iterate through the heap and recursively follow object references use agent supplied callback functions to deliver the information.

These heap callback functions must adhere to the following restrictions -- These callbacks must not use JNI functions. These callbacks must not use functions except callback safe functions which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

An implementation may invoke a callback on an internal thread or the thread which called the iteration function. Heap callbacks are single threaded -- no more than one callback will be invoked at a time.

The Heap Filter Flags can be used to prevent reporting based on the tag status of an object or its class. If no flags are set (the jint is zero), objects will not be filtered out. Filter out tagged objects. Objects which are tagged are not included. Filter out untagged objects. Objects which are not tagged are not included. Filter out objects with tagged classes. Objects whose class is tagged are not included. Filter out objects with untagged classes. Objects whose class is not tagged are not included.

The Heap Visit Control Flags are returned by the heap callbacks and can be used to abort the iteration. For the Heap Reference Callback, it can also be used to prune the graph of traversed references (JVMTI_VISIT_OBJECTS is not set). If we are visiting an object and if this callback was initiated by , traverse the references of this object. Otherwise ignored. Abort the iteration. Ignore all other bits.

The Heap Reference Enumeration is provided by the Heap Reference Callback and Primitive Field Callback to describe the kind of reference being reported. Reference from an object to its class. Reference from an object to the value of one of its instance fields. Reference from an array to one of its elements. Reference from a class to its class loader. Reference from a class to its signers array. Reference from a class to its protection domain. Reference from a class to one of its interfaces. Note: interfaces are defined via a constant pool reference, so the referenced interfaces may also be reported with a JVMTI_HEAP_REFERENCE_CONSTANT_POOL reference kind. Reference from a class to the value of one of its static fields. Reference from a class to a resolved entry in the constant pool. Reference from a class to its superclass. A callback is bot sent if the superclass is java.lang.Object. Note: loaded classes define superclasses via a constant pool reference, so the referenced superclass may also be reported with a JVMTI_HEAP_REFERENCE_CONSTANT_POOL reference kind. Heap root reference: JNI global reference. Heap root reference: System class. Heap root reference: monitor. Heap root reference: local variable on the stack. Heap root reference: JNI local reference. Heap root reference: Thread. Heap root reference: other heap root reference.

Definitions for the single character type descriptors of primitive types. 'Z' - Java programming language boolean - JNI jboolean 'B' - Java programming language byte - JNI jbyte 'C' - Java programming language char - JNI jchar 'S' - Java programming language short - JNI jshort 'I' - Java programming language int - JNI jint 'J' - Java programming language long - JNI jlong 'F' - Java programming language float - JNI jfloat 'D' - Java programming language double - JNI jdouble Reference information returned for and references. For , the referrer object is not a class or an inteface. In this case, index is the index of the field in the class of the referrer object. This class is referred to below as C.

For , the referrer object is a class (referred to below as C) or an interface (referred to below as I). In this case, index is the index of the field in that class or interface.

If the referrer object is not an interface, then the field indices are determined as follows:

  • make a list of all the fields in C and its superclasses, starting with all the fields in java.lang.Object and ending with all the fields in C.
  • Within this list, put the fields for a given class in the order returned by .
  • Assign the fields in this list indices n, n+1, ..., in order, where n is the count of the fields in all the interfaces implemented by C. Note that C implements all interfaces directly implemented by its superclasses; as well as all superinterfaces of these interfaces.
If the referrer object is an interface, then the field indices are determined as follows:
  • make a list of the fields directly declared in I.
  • Within this list, put the fields in the order returned by .
  • Assign the fields in this list indices n, n+1, ..., in order, where n is the count of the fields in all the superinterfaces of I.
All fields are included in this computation, regardless of field modifier (static, public, private, etc).

For example, given the following classes and interfaces: interface I0 { int p = 0; } interface I1 extends I0 { int x = 1; } interface I2 extends I0 { int y = 2; } class C1 implements I1 { public static int a = 3; private int b = 4; } class C2 extends C1 implements I2 { static int q = 5; final int r = 6; } Assume that called on C1 returns the fields of C1 in the order: a, b; and that the fields of C2 are returned in the order: q, r. An instance of class C1 will have the following field indices:

a 2 The count of the fields in the interfaces implemented by C1 is two (n=2): p of I0 and x of I1.
b 3 the subsequent index.
The class C1 will have the same field indices.

An instance of class C2 will have the following field indices:

a 3 The count of the fields in the interfaces implemented by C2 is three (n=3): p of I0, x of I1 and y of I2 (an interface of C2). Note that the field p of I0 is only included once.
b 4 the subsequent index to "a".
q 5 the subsequent index to "b".
r 6 the subsequent index to "q".
The class C2 will have the same field indices. Note that a field may have a different index depending on the object that is viewing it -- for example field "a" above. Note also: not all field indices may be visible from the callbacks, but all indices are shown for illustrative purposes.

The interface I1 will have the following field indices:

x 1 The count of the fields in the superinterfaces of I1 is one (n=1): p of I0.
Reference information returned for references. The array index. Reference information returned for references. The index into the constant pool of the class. See the description in . Reference information returned for references. The tag of the thread corresponding to this stack, zero if not tagged. The unique thread ID of the thread corresponding to this stack. The depth of the frame. The method executing in this frame. The currently executing location in this frame. The slot number of the local variable. Reference information returned for references. The tag of the thread corresponding to this stack, zero if not tagged. The unique thread ID of the thread corresponding to this stack. The depth of the frame. The method executing in this frame. Reference information returned for other references. reserved for future use. reserved for future use. reserved for future use. reserved for future use. reserved for future use. reserved for future use. reserved for future use. reserved for future use. The information returned about referrers. Represented as a union of the various kinds of reference information. jvmtiHeapReferenceInfoField The referrer information for and references. jvmtiHeapReferenceInfoArray The referrer information for For references. jvmtiHeapReferenceInfoConstantPool The referrer information for For references. jvmtiHeapReferenceInfoStackLocal The referrer information for For references. jvmtiHeapReferenceInfoJniLocal The referrer information for For references. jvmtiHeapReferenceInfoReserved reserved for future use. jvmtiHeapIterationCallback The callback to be called to describe an object in the heap. Used by the function, ignored by the function. jvmtiHeapReferenceCallback The callback to be called to describe an object reference. Used by the function, ignored by the function. jvmtiPrimitiveFieldCallback The callback to be called to describe a primitive field. jvmtiArrayPrimitiveValueCallback The callback to be called to describe an array of primitive values. jvmtiStringPrimitiveValueCallback The callback to be called to describe a String value. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. jvmtiReservedCallback Reserved for future use.. The heap dumping functionality (below) uses a callback for each object. While it would seem that a buffered approach would provide better throughput, tests do not show this to be the case--possibly due to locality of memory reference or array access overhead. Still under investigation as to if java.lang.ref references are reported as a different type of reference. Should or can an indication of the cost or relative cost of these operations be included? Heap Iteration Callback Agent supplied callback function. Describes (but does not pass in) an object in the heap.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions. The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). Size of the object (in bytes). See . The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. If this object is an array, the length of the array. Otherwise negative one (-1). The user supplied data that was passed into the iteration function. Heap Reference Callback Agent supplied callback function. Describes a reference from an object or the VM (the referrer) to another object (the referree) or a heap root to a referree.

This function should return a bit vector of the desired visit control flags. This will determine if the objects referenced by the referree should be visited or if the entire iteration should be aborted.

See the heap callback function restrictions. jvmtiHeapReferenceKind The kind of reference. jvmtiHeapReferenceInfo Details about the reference. Set when the reference_kind is , , , , , or . Otherwise NULL. The tag of the class of referree object (zero if the class is not tagged). If the referree object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). The tag of the class of the referrer object (zero if the class is not tagged or the referree is a heap root). If the referrer object represents a runtime class, the referrer_class_tag is the tag associated with the java.lang.Class (zero if java.lang.Class is not tagged). Size of the referree object (in bytes). See . Points to the referree object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. Points to the tag of the referrer object, or points to the zero if the referrer object is not tagged. NULL if the referrer in not an object (that is, this callback is reporting a heap root). To set the tag value to be associated with the referrer object the agent sets the jlong pointed to by the parameter. If this callback is reporting a reference from an object to itself, referrer_tag_ptr == tag_ptr. If this object is an array, the length of the array. Otherwise negative one (-1). The user supplied data that was passed into the iteration function. Primitive Field Callback Agent supplied callback function which describes a primitive field of an object (the object). A primitive field is a field whose type is a primitive type. This callback will describe a static field if the object is a class, and otherwise will describe an instance field.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions. jvmtiHeapReferenceKind The kind of field -- instance or static ( or ). jvmtiHeapReferenceInfo Which field (the field index). The tag of the class of the object (zero if the class is not tagged). If the object represents a runtime class, the object_class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). Points to the tag of the object, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The value of the field. jvmtiPrimitiveType The type of the field. The user supplied data that was passed into the iteration function. Array Primitive Value Callback Agent supplied callback function. Describes the values in an array of a primitive type.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions. The tag of the class of the array object (zero if the class is not tagged). Size of the array (in bytes). See . Points to the tag of the array object, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The length of the primitive array. jvmtiPrimitiveType The type of the elements of the array. The elements of the array in a packed array of element_count items of element_type size each. The user supplied data that was passed into the iteration function. String Primitive Value Callback Agent supplied callback function. Describes the value of a java.lang.String.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions. The tag of the class of the String class (zero if the class is not tagged). Is this needed? Size of the string (in bytes). See . Points to the tag of the String object, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The value of the String, encoded as a Unicode string. The length of the string. The length is equal to the number of 16-bit Unicode characters in the string. The user supplied data that was passed into the iteration function. reserved for future use Callback Placeholder -- reserved for future use. Follow References This function initiates a traversal over the objects that are directly and indirectly reachable from the specified object or, if initial_object is not specified, all objects reachable from the heap roots. The heap root are the set of system classes, JNI globals, references from thread stacks, and other objects used as roots for the purposes of garbage collection.

This function operates by traversing the reference graph. Let A, B, ... represent objects. When a reference from A to B is traversed, when a reference from a heap root to B is traversed, or when B is specified as the , then B is said to be visited. A reference from A to B is not traversed until A is visited. References are reported in the same order that the references are traversed. Object references are reported by invoking the agent supplied callback function . In a reference from A to B, A is known as the referrer and B as the referree. The callback is invoked exactly once for each reference from a referrer; this is true even if there are reference cycles or multiple paths to the referrer. There may be more than one reference between a referrer and a referree, each reference is reported. These references may be distinguished by examining the reference_kind and reference_info parameters of the callback.

This function reports a Java programming language view of object references, not a virtual machine implementation view. The following object references are reported when they are non-null:

  • Instance objects report references to each non-primitive instance fields (including inherited fields).
  • Instance objects report a reference to the object type (class).
  • Classes report a reference to the superclass and directly implemented/extended interfaces.
  • Classes report a reference to the class loader, protection domain, signers, and resolved entries in the constant pool.
  • Classes report a reference to each directly declared non-primitive static field.
  • Arrays report a reference to the array type (class) and each array element.
  • Primitive arrays report a reference to the array type.

This function can also be used to examine primitive (non-object) values. The primitive value of an array or String is reported after the object has been visited; it is reported by invoking the agent supplied callback function or . A primitive field is reported after the object with that field is visited; it is reported by invoking the agent supplied callback function .

Whether a callback is provided or is NULL only determines whether the callback will be invoked, it does not influence which objects are visited nor does it influence whether other callbacks will be invoked. However, the visit control flags returned by do determine if the objects referenced by the current object as visited. The heap filter flags and provided as parameters to this function do not control which objects are visited but they do control which objects and primitive values are reported by the callbacks. For example, if the only callback that was set is and klass is set to the array of bytes class, then only arrays of byte will be reported. The table below summarizes this:

Controls objects visited Controls objects reported Controls primitives reported
the Heap Visit Control Flags returned by Yes Yes, since visits are controlled Yes, since visits are controlled
in set No Yes No
No Yes Yes
No Yes Yes

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled. new This bit vector of heap filter flags. restricts the objects for which the callback function is called. This applies to both the object and primitive callbacks. callbacks are not limited to instances of a particular class Callbacks are only reported when the object is an instance of this class. Objects which are instances of a subclass of klass are not reported. If klass is an interface, no objects are reported. This applies to both the object and primitive callbacks. references are followed from the heap roots The object to follow jvmtiHeapCallbacks Structure defining the set of callback functions. NULL is passed as the user supplied data User supplied data to be passed to the callback. is not a valid class. is not a valid object. Iterate Through Heap Initiate an iteration over all objects in the heap. This includes both reachable and unreachable objects. Objects are visited in no particular order.

Heap objects are reported by invoking the agent supplied callback function . References between objects are not reported. If only reachable objects are desired, or if object reference information is needed, use .

This function can also be used to examine primitive (non-object) values. The primitive value of an array or String is reported after the object has been visited; it is reported by invoking the agent supplied callback function or . A primitive field is reported after the object with that field is visited; it is reported by invoking the agent supplied callback function .

Unless the iteration is aborted by the Heap Visit Control Flags returned by a callback, all objects in the heap are visited. Whether a callback is provided or is NULL only determines whether the callback will be invoked, it does not influence which objects are visited nor does it influence whether other callbacks will be invoked. The heap filter flags and provided as parameters to this function do not control which objects are visited but they do control which objects and primitive values are reported by the callbacks. For example, if the only callback that was set is and klass is set to the array of bytes class, then only arrays of byte will be reported. The table below summarizes this (contrast this with ):

Controls objects visited Controls objects reported Controls primitives reported
the Heap Visit Control Flags returned by No
(unless they abort the iteration)
No
(unless they abort the iteration)
No
(unless they abort the iteration)
in set No Yes No
No Yes Yes
No Yes Yes

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled. new This bit vector of heap filter flags. restricts the objects for which the callback function is called. This applies to both the object and primitive callbacks. callbacks are not limited to instances of a particular class Callbacks are only reported when the object is an instance of this class. Objects which are instances of a subclass of klass are not reported. If klass is an interface, no objects are reported. This applies to both the object and primitive callbacks. jvmtiHeapCallbacks Structure defining the set callback functions. NULL is passed as the user supplied data User supplied data to be passed to the callback. is not a valid class. Get Tag Retrieve the tag associated with an object. The tag is a long value typically used to store a unique identifier or pointer to object information. The tag is set with . Objects for which no tags have been set return a tag value of zero. new The object whose tag is to be retrieved. On return, the referenced long is set to the value of the tag. Set Tag Set the tag associated with an object. The tag is a long value typically used to store a unique identifier or pointer to object information. The tag is visible with . new The object whose tag is to be set. The new value of the tag. Get Objects With Tags Return objects in the heap with the specified tags. The format is parallel arrays of objects and tags. new Number of tags to scan for. Scan for objects with these tags. Zero is not permitted in this array. Return the number of objects with any of the tags in . this information is not returned Returns the array of objects with any of the tags in . this information is not returned For each object in , return the tag at the corresponding index. Zero is present in . Force Garbage Collection Force the VM to perform a garbage collection. The garbage collection is as complete as possible. This function does not cause finalizers to be run. This function does not return until the garbage collection is finished.

Although garbage collection is as complete as possible there is no guarantee that all events will have been sent by the time that this function returns. In particular, an object may be prevented from being freed because it is awaiting finalization. new These functions and data types were introduced in the original version 1.0 and have been superseded by more powerful and flexible versions which:

  • Allow access to primitive values (the value of Strings, arrays, and primitive fields)
  • Allow the tag of the referrer to be set, thus enabling more efficient localized reference graph building
  • Provide more extensive filtering abilities
  • Are extensible, allowing their abilities to grow in future versions of

Please use the current Heap functions.

Tagged objects only. Untagged objects only. Either tagged or untagged objects. JNI global reference. System class. Monitor. Stack local. JNI local reference. Thread. Other. Reference from an object to its class. Reference from an object to the value of one of its instance fields. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the index of the the instance field. The index is based on the order of all the object's fields. This includes all fields of the directly declared static and instance fields in the class, and includes all fields (both public and private) fields declared in superclasses and superinterfaces. The index is thus calculated by summing the index of the field in the directly declared class (see ), with the total number of fields (both public and private) declared in all superclasses and superinterfaces. The index starts at zero. Reference from an array to one of its elements. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the array index. Reference from a class to its class loader. Reference from a class to its signers array. Reference from a class to its protection domain. Reference from a class to one of its interfaces. Reference from a class to the value of one of its static fields. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the index of the the static field. The index is based on the order of all the object's fields. This includes all fields of the directly declared static and instance fields in the class, and includes all fields (both public and private) fields declared in superclasses and superinterfaces. The index is thus calculated by summing the index of the field in the directly declared class (see ), with the total number of fields (both public and private) declared in all superclasses and superinterfaces. The index starts at zero. Note: this definition differs from that in the 1.0 Specification. No known implementations used the 1.0 definition. Reference from a class to a resolved entry in the constant pool. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the index into constant pool table of the class, starting at 1. See . Continue the iteration. If this is a reference iteration, follow the references of this object. Continue the iteration. If this is a reference iteration, ignore the references of this object. Abort the iteration. jvmtiIterationControl Heap Object Callback Agent supplied callback function. Describes (but does not pass in) an object in the heap.

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions. The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). Size of the object (in bytes). See . The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The user supplied data that was passed into the iteration function. jvmtiIterationControl Heap Root Object Callback Agent supplied callback function. Describes (but does not pass in) an object that is a root for the purposes of garbage collection.

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, JVMTI_ITERATION_IGNORE to continue iteration without pursuing references from referree object or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions. jvmtiHeapRootKind The kind of heap root. The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). Size of the object (in bytes). See . The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The user supplied data that was passed into the iteration function. jvmtiIterationControl Stack Reference Object Callback Agent supplied callback function. Describes (but does not pass in) an object on the stack that is a root for the purposes of garbage collection.

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, JVMTI_ITERATION_IGNORE to continue iteration without pursuing references from referree object or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions. jvmtiHeapRootKind The kind of root (either JVMTI_HEAP_ROOT_STACK_LOCAL or JVMTI_HEAP_ROOT_JNI_LOCAL). The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). Size of the object (in bytes). See . The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The tag of the thread corresponding to this stack, zero if not tagged. The depth of the frame. The method executing in this frame. The slot number. The user supplied data that was passed into the iteration function. jvmtiIterationControl Object Reference Callback Agent supplied callback function. Describes a reference from an object (the referrer) to another object (the referree).

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, JVMTI_ITERATION_IGNORE to continue iteration without pursuing references from referree object or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions. jvmtiObjectReferenceKind The type of reference. The tag of the class of referree object (zero if the class is not tagged). If the referree object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged). Size of the referree object (in bytes). See . The referree object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter. The tag of the referrer object, or zero if the referrer object is not tagged. For references of type JVMTI_REFERENCE_FIELD or JVMTI_REFERENCE_STATIC_FIELD the index of the field in the referrer object. The index is based on the order of all the object's fields - see JVMTI_REFERENCE_FIELD or JVMTI_REFERENCE_STATIC_FIELD for further description.

For references of type JVMTI_REFERENCE_ARRAY_ELEMENT the array index - see JVMTI_REFERENCE_ARRAY_ELEMENT for further description.

For references of type JVMTI_REFERENCE_CONSTANT_POOL the index into the constant pool of the class - see JVMTI_REFERENCE_CONSTANT_POOL for further description.

For references of other kinds the referrer_index is -1. The user supplied data that was passed into the iteration function. Iterate Over Objects Reachable From Object This function iterates over all objects that are directly and indirectly reachable from the specified object. For each object A (known as the referrer) with a reference to object B the specified callback function is called to describe the object reference. The callback is called exactly once for each reference from a referrer; this is true even if there are reference cycles or multiple paths to the referrer. There may be more than one reference between a referrer and a referree, These may be distinguished by the and . The callback for an object will always occur after the callback for its referrer.

See for the object references which are reported.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled. new The object jvmtiObjectReferenceCallback The callback to be called to describe each object reference. NULL is passed as the user supplied data User supplied data to be passed to the callback. Iterate Over Reachable Objects This function iterates over the root objects and all objects that are directly and indirectly reachable from the root objects. The root objects comprise the set of system classes, JNI globals, references from thread stacks, and other objects used as roots for the purposes of garbage collection.

For each root the or callback is called. An object can be a root object for more than one reason and in that case the appropriate callback is called for each reason.

For each object reference the callback function is called to describe the object reference. The callback is called exactly once for each reference from a referrer; this is true even if there are reference cycles or multiple paths to the referrer. There may be more than one reference between a referrer and a referree, These may be distinguished by the and . The callback for an object will always occur after the callback for its referrer.

See for the object references which are reported.

Roots are always reported to the profiler before any object references are reported. In other words, the callback will not be called until the appropriate callback has been called for all roots. If the callback is specified as NULL then this function returns after reporting the root objects to the profiler.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled. new jvmtiHeapRootCallback do not report heap roots The callback function to be called for each heap root of type JVMTI_HEAP_ROOT_JNI_GLOBAL, JVMTI_HEAP_ROOT_SYSTEM_CLASS, JVMTI_HEAP_ROOT_MONITOR, JVMTI_HEAP_ROOT_THREAD, or JVMTI_HEAP_ROOT_OTHER. jvmtiStackReferenceCallback do not report stack references The callback function to be called for each heap root of JVMTI_HEAP_ROOT_STACK_LOCAL or JVMTI_HEAP_ROOT_JNI_LOCAL. jvmtiObjectReferenceCallback do not follow references from the root objects The callback function to be called for each object reference. NULL is passed as the user supplied data User supplied data to be passed to the callback. Iterate Over Heap Iterate over all objects in the heap. This includes both reachable and unreachable objects.

The parameter indicates the objects for which the callback function is called. If this parameter is JVMTI_HEAP_OBJECT_TAGGED then the callback will only be called for every object that is tagged. If the parameter is JVMTI_HEAP_OBJECT_UNTAGGED then the callback will only be for objects that are not tagged. If the parameter is JVMTI_HEAP_OBJECT_EITHER then the callback will be called for every object in the heap, irrespective of whether it is tagged or not.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled. new jvmtiHeapObjectFilter Indicates the objects for which the callback function is called. jvmtiHeapObjectCallback The iterator function to be called for each object matching the . NULL is passed as the user supplied data User supplied data to be passed to the callback. Iterate Over Instances Of Class Iterate over all objects in the heap that are instances of the specified class. This includes direct instances of the specified class and instances of all subclasses of the specified class. This includes both reachable and unreachable objects.

The parameter indicates the objects for which the callback function is called. If this parameter is JVMTI_HEAP_OBJECT_TAGGED then the callback will only be called for every object that is tagged. If the parameter is JVMTI_HEAP_OBJECT_UNTAGGED then the callback will only be called for objects that are not tagged. If the parameter is JVMTI_HEAP_OBJECT_EITHER then the callback will be called for every object in the heap, irrespective of whether it is tagged or not.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled. new Iterate over objects of this class only. jvmtiHeapObjectFilter Indicates the objects for which the callback function is called. jvmtiHeapObjectCallback The iterator function to be called for each instance matching the . NULL is passed as the user supplied data User supplied data to be passed to the callback. These functions are used to retrieve or set the value of a local variable. The variable is identified by the depth of the frame containing its value and the variable's slot number within that frame. The mapping of variables to slot numbers can be obtained with the function . Get Local Variable - Object This function can be used to retrieve the value of a local variable whose type is Object or a subclass of Object. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. On return, points to the variable's value. Invalid slot. The variable type is not Object or a subclass of Object. Not a visible frame Get Local Instance This function can be used to retrieve the value of the local object variable at slot 0 (the "this" object) from non-static frames. This function can retrieve the "this" object from native method frames, whereas GetLocalObject() would return JVMTI_ERROR_OPAQUE_FRAME in those cases. new The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. On return, points to the variable's value. If the specified frame is a static method frame. Get Local Variable - Int This function can be used to retrieve the value of a local variable whose type is int, short, char, byte, or boolean. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. On return, points to the variable's value. Invalid slot. The variable type is not int, short, char, byte, or boolean. Not a visible frame Get Local Variable - Long This function can be used to retrieve the value of a local variable whose type is long. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. On return, points to the variable's value. Invalid slot. The variable type is not long. Not a visible frame Get Local Variable - Float This function can be used to retrieve the value of a local variable whose type is float. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. On return, points to the variable's value. Invalid slot. The variable type is not float. Not a visible frame Get Local Variable - Double This function can be used to retrieve the value of a local variable whose type is long. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. On return, points to the variable's value. Invalid slot. The variable type is not double. Not a visible frame Set Local Variable - Object This function can be used to set the value of a local variable whose type is Object or a subclass of Object. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. The new value for the variable. Invalid slot. The variable type is not Object or a subclass of Object. The supplied is not compatible with the variable type. Not a visible frame Set Local Variable - Int This function can be used to set the value of a local variable whose type is int, short, char, byte, or boolean. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. The new value for the variable. Invalid slot. The variable type is not int, short, char, byte, or boolean. Not a visible frame Set Local Variable - Long This function can be used to set the value of a local variable whose type is long. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. The new value for the variable. Invalid slot. The variable type is not long. Not a visible frame Set Local Variable - Float This function can be used to set the value of a local variable whose type is float. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. The new value for the variable. Invalid slot. The variable type is not float. Not a visible frame Set Local Variable - Double This function can be used to set the value of a local variable whose type is double. jvmdi The thread of the frame containing the variable's value. The depth of the frame containing the variable's value. The variable's slot number. The new value for the variable. Invalid slot. The variable type is not double. Not a visible frame Set Breakpoint Set a breakpoint at the instruction indicated by method and location. An instruction can only have one breakpoint.

Whenever the designated instruction is about to be executed, a event is generated. jvmdi The class in which to set the breakpoint The method in which to set the breakpoint the index of the instruction at which to set the breakpoint The designated bytecode already has a breakpoint. Clear Breakpoint Clear the breakpoint at the bytecode indicated by method and location. jvmdi The class in which to clear the breakpoint The method in which to clear the breakpoint the index of the instruction at which to clear the breakpoint There's no breakpoint at the designated bytecode. Set Field Access Watch Generate a event when the field specified by klass and field is about to be accessed. An event will be generated for each access of the field until it is canceled with . Field accesses from Java programming language code or from JNI code are watched, fields modified by other means are not watched. Note that users should be aware that their own field accesses will trigger the watch. A field can only have one field access watch set. Modification of a field is not considered an access--use to monitor modifications. jvmdi The class containing the field to watch The field to watch The designated field is already being watched for accesses. Clear Field Access Watch Cancel a field access watch previously set by , on the field specified by klass and field. jvmdi The class containing the field to watch The field to watch The designated field is not being watched for accesses. Set Field Modification Watch Generate a event when the field specified by klass and field is about to be modified. An event will be generated for each modification of the field until it is canceled with . Field modifications from Java programming language code or from JNI code are watched, fields modified by other means are not watched. Note that users should be aware that their own field modifications will trigger the watch. A field can only have one field modification watch set. jvmdi The class containing the field to watch The field to watch The designated field is already being watched for modifications. Clear Field Modification Watch Cancel a field modification watch previously set by , on the field specified by klass and field. jvmdi The class containing the field to watch The field to watch The designated field is not being watched for modifications. Get Loaded Classes Return an array of all classes loaded in the virtual machine. The number of classes in the array is returned via class_count_ptr, and the array itself via classes_ptr.

Array classes of all types (including arrays of primitive types) are included in the returned list. Primitive classes (for example, java.lang.Integer.TYPE) are not included in this list. jvmdi On return, points to the number of classes. On return, points to an array of references, one for each class. Get Classloader Classes Returns an array of those classes for which this class loader has been recorded as an initiating loader. Each class in the returned array was created by this class loader, either by defining it directly or by delegation to another class loader. See .

For JDK version 1.1 implementations that don't recognize the distinction between initiating and defining class loaders, this function should return all classes loaded in the virtual machine. The number of classes in the array is returned via class_count_ptr, and the array itself via classes_ptr. jvmdi the classes initiated by the bootstrap loader will be returned An initiating class loader. On return, points to the number of classes. On return, points to an array of references, one for each class. Get Class Signature For the class indicated by klass, return the JNI type signature and the generic signature of the class. For example, java.util.List is "Ljava/util/List;" and int[] is "[I" The returned name for primitive classes is the type signature character of the corresponding primitive type. For example, java.lang.Integer.TYPE is "I". jvmdiClone The class to query. the signature is not returned On return, points to the JNI type signature of the class, encoded as a modified UTF-8 string. the generic signature is not returned On return, points to the generic signature of the class, encoded as a modified UTF-8 string. If there is no generic signature attribute for the class, then, on return, points to NULL. Get Class Status Get the status of the class. Zero or more of the following bits can be set. Class bytecodes have been verified Class preparation is complete Class initialization is complete. Static initializer has been run. Error during initialization makes class unusable Class is an array. If set, all other bits are zero. Class is a primitive class (for example, java.lang.Integer.TYPE). If set, all other bits are zero. jvmdi The class to query. On return, points to the current state of this class as one or more of the class status flags. Get Source File Name For the class indicated by klass, return the source file name via source_name_ptr. The returned string is a file name only and never contains a directory name.

For primitive classes (for example, java.lang.Integer.TYPE) and for arrays this function returns . jvmdi The class to query. On return, points to the class's source file name, encoded as a modified UTF-8 string. Class information does not include a source file name. This includes cases where the class is an array class or primitive class. Get Class Modifiers For the class indicated by klass, return the access flags via modifiers_ptr. Access flags are defined in .

If the class is an array class, then its public, private, and protected modifiers are the same as those of its component type. For arrays of primitives, this component type is represented by one of the primitive classes (for example, java.lang.Integer.TYPE).

If the class is a primitive class, its public modifier is always true, and its protected and private modifiers are always false.

If the class is an array class or a primitive class then its final modifier is always true and its interface modifier is always false. The values of its other modifiers are not determined by this specification. jvmdi The class to query. On return, points to the current access flags of this class. Get Class Methods For the class indicated by klass, return a count of methods via method_count_ptr and a list of method IDs via methods_ptr. The method list contains constructors and static initializers as well as true methods. Only directly declared methods are returned (not inherited methods). An empty method list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE). jvmdi The class to query. On return, points to the number of methods declared in this class. On return, points to the method ID array. is not prepared. Get Class Fields For the class indicated by klass, return a count of fields via field_count_ptr and a list of field IDs via fields_ptr. Only directly declared fields are returned (not inherited fields). Fields are returned in the order they occur in the class file. An empty field list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE). Use JNI to determine the length of an array. jvmdi The class to query. On return, points to the number of fields declared in this class. On return, points to the field ID array. is not prepared. Get Implemented Interfaces Return the direct super-interfaces of this class. For a class, this function returns the interfaces declared in its implements clause. For an interface, this function returns the interfaces declared in its extends clause. An empty interface list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE). jvmdi The class to query. On return, points to the number of interfaces. On return, points to the interface array. is not prepared. Get Class Version Numbers For the class indicated by klass, return the minor and major version numbers, as defined in . new The class to query. On return, points to the value of the minor_version item of the Class File Format. Note: to be consistent with the Class File Format, the minor version number is the first parameter. On return, points to the value of the major_version item of the Class File Format. The class is a primitive or array class. Get Constant Pool For the class indicated by klass, return the raw bytes of the constant pool in the format of the constant_pool item of . The format of the constant pool may differ between versions of the Class File Format, so, the minor and major class version numbers should be checked for compatibility.

The returned constant pool might not have the same layout or contents as the constant pool in the defining class file. The constant pool returned by GetConstantPool() may have more or fewer entries than the defining constant pool. Entries may be in a different order. The constant pool returned by GetConstantPool() will match the constant pool used by GetBytecodes(). That is, the bytecodes returned by GetBytecodes() will have constant pool indices which refer to constant pool entries returned by GetConstantPool(). Note that since and can change the constant pool, the constant pool returned by this function can change accordingly. Thus, the correspondence between GetConstantPool() and GetBytecodes() does not hold if there is an intervening class retransformation or redefinition. The value of a constant pool entry used by a given bytecode will match that of the defining class file (even if the indices don't match). Constant pool entries which are not used directly or indirectly by bytecodes (for example, UTF-8 strings associated with annotations) are not required to exist in the returned constant pool. new The class to query. On return, points to the number of entries in the constant pool table plus one. This corresponds to the constant_pool_count item of the Class File Format. On return, points to the number of bytes in the returned raw constant pool. On return, points to the raw constant pool, that is the bytes defined by the constant_pool item of the Class File Format The class is a primitive or array class. Is Interface Determines whether a class object reference represents an interface. The jboolean result is JNI_TRUE if the "class" is actually an interface, JNI_FALSE otherwise. jvmdi The class to query. On return, points to the boolean result of this function. Is Array Class Determines whether a class object reference represents an array. The jboolean result is JNI_TRUE if the class is an array, JNI_FALSE otherwise. jvmdi The class to query. On return, points to the boolean result of this function. Is Modifiable Class Determines whether a class is modifiable. If a class is modifiable ( returns JNI_TRUE) the class can be redefined with (assuming the agent possesses the capability) or retransformed with (assuming the agent possesses the capability). If a class is not modifiable ( returns JNI_FALSE) the class can be neither redefined nor retransformed.

Primitive classes (for example, java.lang.Integer.TYPE) and array classes are never modifiable.

new If possessed then all classes (except primitive and array classes) are modifiable. No effect on the result of the function. But must additionally be possessed to modify the class with . No effect on the result of the function. But must additionally be possessed to modify the class with . The class to query. On return, points to the boolean result of this function. Get Class Loader For the class indicated by klass, return via classloader_ptr a reference to the class loader for the class. jvmdi The class to query. On return, points to the class loader that loaded this class. If the class was not created by a class loader or if the class loader is the bootstrap class loader, points to NULL. Get Source Debug Extension For the class indicated by klass, return the debug extension via source_debug_extension_ptr. The returned string contains exactly the debug extension information present in the class file of klass. jvmdi The class to query. On return, points to the class's debug extension, encoded as a modified UTF-8 string. Class information does not include a debug extension. Retransform Classes This function facilitates the bytecode instrumentation of already loaded classes. To replace the class definition without reference to the existing bytecodes, as one might do when recompiling from source for fix-and-continue debugging, function should be used instead.

When classes are initially loaded or when they are redefined, the initial class file bytes can be transformed with the event. This function reruns the transformation process (whether or not a transformation has previously occurred). This retransformation follows these steps:

  • starting from the initial class file bytes
  • for each retransformation incapable agent which received a ClassFileLoadHook event during the previous load or redefine, the bytes it returned (via the new_class_data parameter) are reused as the output of the transformation; note that this is equivalent to reapplying the previous transformation, unaltered. except that the ClassFileLoadHook event is not sent to these agents
  • for each retransformation capable agent, the ClassFileLoadHook event is sent, allowing a new transformation to be applied
  • the transformed class file bytes are installed as the new definition of the class
See the event for more details.

The initial class file bytes represent the bytes passed to ClassLoader.defineClass or RedefineClasses (before any transformations were applied), however they may not exactly match them. The constant pool may differ in ways described in . Constant pool indices in the bytecodes of methods will correspond. Some attributes may not be present. Where order is not meaningful, for example the order of methods, order may not be preserved.

Retransformation can cause new versions of methods to be installed. Old method versions may become obsolete The new method version will be used on new invokes. If a method has active stack frames, those active frames continue to run the bytecodes of the original method version.

This function does not cause any initialization except that which would occur under the customary JVM semantics. In other words, retransforming a class does not cause its initializers to be run. The values of static fields will remain as they were prior to the call.

Threads need not be suspended.

All breakpoints in the class are cleared.

All attributes are updated.

Instances of the retransformed class are not affected -- fields retain their previous values. Tags on the instances are also unaffected.

In response to this call, no events other than the event will be sent.

The retransformation may change method bodies, the constant pool and attributes. The retransformation must not add, remove or rename fields or methods, change the signatures of methods, change modifiers, or change inheritance. These restrictions may be lifted in future versions. See the error return description below for information on error codes returned if an unsupported retransformation is attempted. The class file bytes are not verified or installed until they have passed through the chain of events, thus the returned error code reflects the result of the transformations. If any error code is returned other than JVMTI_ERROR_NONE, none of the classes to be retransformed will have a new definition installed. When this function returns (with the error code of JVMTI_ERROR_NONE) all of the classes to be retransformed will have their new definitions installed. new The number of classes to be retransformed. The array of classes to be retransformed. One of the cannot be modified. See . One of the is not a valid class. A retransformed class file has a version number not supported by this VM. A retransformed class file is malformed (The VM would return a ClassFormatError). The retransformed class file definitions would lead to a circular definition (the VM would return a ClassCircularityError). The retransformed class file bytes fail verification. The class name defined in a retransformed class file is different from the name in the old class object. A retransformed class file would require adding a method. A retransformed class file changes a field. A direct superclass is different for a retransformed class file, or the set of directly implemented interfaces is different. A retransformed class file does not declare a method declared in the old class version. A retransformed class file has different class modifiers. A method in the retransformed class file has different modifiers than its counterpart in the old class version. Redefine Classes Class object for this class Number of bytes defining class (below) Bytes defining class (in ) All classes given are redefined according to the definitions supplied. This function is used to replace the definition of a class with a new definition, as might be needed in fix-and-continue debugging. Where the existing class file bytes are to be transformed, for example in bytecode instrumentation, should be used.

Redefinition can cause new versions of methods to be installed. Old method versions may become obsolete The new method version will be used on new invokes. If a method has active stack frames, those active frames continue to run the bytecodes of the original method version. If resetting of stack frames is desired, use to pop frames with obsolete method versions.

This function does not cause any initialization except that which would occur under the customary JVM semantics. In other words, redefining a class does not cause its initializers to be run. The values of static fields will remain as they were prior to the call.

Threads need not be suspended.

All breakpoints in the class are cleared.

All attributes are updated.

Instances of the redefined class are not affected -- fields retain their previous values. Tags on the instances are also unaffected.

In response to this call, the event Class File Load Hook will be sent (if enabled), but no other events will be sent.

The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, change modifiers, or change inheritance. These restrictions may be lifted in future versions. See the error return description below for information on error codes returned if an unsupported redefinition is attempted. The class file bytes are not verified or installed until they have passed through the chain of events, thus the returned error code reflects the result of the transformations applied to the bytes passed into . If any error code is returned other than JVMTI_ERROR_NONE, none of the classes to be redefined will have a new definition installed. When this function returns (with the error code of JVMTI_ERROR_NONE) all of the classes to be redefined will have their new definitions installed. jvmdi The number of classes specified in class_definitions jvmtiClassDefinition The array of new class definitions One of class_bytes is NULL. An element of class_definitions cannot be modified. See . An element of class_definitions is not a valid class. A new class file has a version number not supported by this VM. A new class file is malformed (The VM would return a ClassFormatError). The new class file definitions would lead to a circular definition (the VM would return a ClassCircularityError). The class bytes fail verification. The class name defined in a new class file is different from the name in the old class object. A new class file would require adding a method. A new class version changes a field. A direct superclass is different for a new class version, or the set of directly implemented interfaces is different. A new class version does not declare a method declared in the old class version. A new class version has different modifiers. A method in the new class version has different modifiers than its counterpart in the old class version. Get Object Size For the object indicated by object, return via size_ptr the size of the object. This size is an implementation-specific approximation of the amount of storage consumed by this object. It may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM. new The object to query. On return, points to the object's size in bytes. Get Object Hash Code For the object indicated by object, return via hash_code_ptr a hash code. This hash code could be used to maintain a hash table of object references, however, on some implementations this can cause significant performance impacts--in most cases tags will be a more efficient means of associating information with objects. This function guarantees the same hash code value for a particular object throughout its life jvmdi The object to query. On return, points to the object's hash code. Get Object Monitor Usage The thread owning this monitor, or NULL if unused The number of times the owning thread has entered the monitor The number of threads waiting to own this monitor The waiter_count waiting threads The number of threads waiting to be notified by this monitor The notify_waiter_count threads waiting to be notified Get information about the object's monitor. The fields of the structure are filled in with information about usage of the monitor. Decide and then clarify suspend requirements. jvmdi The object to query. jvmtiMonitorUsage On return, filled with monitor information for the specified object. Get Object Monitors Return the list of object monitors.

Note: details about each monitor can be examined with . new On return, pointer to the number of monitors returned in monitors_ptr. On return, pointer to the monitor list. Get Field Name (and Signature) For the field indicated by and , return the field name via and field signature via .

Field signatures are defined in the JNI Specification and are referred to as field descriptors in . jvmdiClone The class of the field to query. The field to query. the name is not returned On return, points to the field name, encoded as a modified UTF-8 string. the signature is not returned On return, points to the field signature, encoded as a modified UTF-8 string. the generic signature is not returned On return, points to the generic signature of the field, encoded as a modified UTF-8 string. If there is no generic signature attribute for the field, then, on return, points to NULL. Get Field Declaring Class For the field indicated by klass and field return the class that defined it via declaring_class_ptr. The declaring class will either be klass, a superclass, or an implemented interface. jvmdi The class to query. The field to query. On return, points to the declaring class Get Field Modifiers For the field indicated by klass and field return the access flags via modifiers_ptr. Access flags are defined in . jvmdi The class to query. The field to query. On return, points to the access flags. Is Field Synthetic For the field indicated by klass and field, return a value indicating whether the field is synthetic via is_synthetic_ptr. Synthetic fields are generated by the compiler but not present in the original source code. jvmdi The class of the field to query. The field to query. On return, points to the boolean result of this function. These functions provide information about a method (represented as a ) and set how methods are processed. The functions and can cause new versions of methods to be installed. An original version of a method is considered equivalent to the new version if:

  • their bytecodes are the same except for indices into the constant pool and
  • the referenced constants are equal.
An original method version which is not equivalent to the new method version is called obsolete and is assigned a new method ID; the original method ID now refers to the new method version. A method ID can be tested for obsolescence with .
Get Method Name (and Signature) For the method indicated by method, return the method name via name_ptr and method signature via signature_ptr.

Method signatures are defined in the JNI Specification and are referred to as method descriptors in . Note this is different than method signatures as defined in the Java Language Specification. jvmdiClone The method to query. the name is not returned On return, points to the method name, encoded as a modified UTF-8 string. the signature is not returned On return, points to the method signature, encoded as a modified UTF-8 string. the generic signature is not returned On return, points to the generic signature of the method, encoded as a modified UTF-8 string. If there is no generic signature attribute for the method, then, on return, points to NULL. Get Method Declaring Class For the method indicated by method, return the class that defined it via declaring_class_ptr. jvmdi The class to query. The method to query. On return, points to the declaring class Get Method Modifiers For the method indicated by method, return the access flags via modifiers_ptr. Access flags are defined in . jvmdi The class to query. The method to query. On return, points to the access flags. Get Max Locals For the method indicated by method, return the number of local variable slots used by the method, including the local variables used to pass parameters to the method on its invocation.

See max_locals in . jvmdi The class to query. The method to query. On return, points to the maximum number of local slots Get Arguments Size For the method indicated by method, return via max_ptr the number of local variable slots used by the method's arguments. Note that two-word arguments use two slots. jvmdi The class to query. The method to query. On return, points to the number of argument slots Get Line Number Table the where the line begins the line number For the method indicated by method, return a table of source line number entries. The size of the table is returned via entry_count_ptr and the table itself is returned via table_ptr. jvmdi The class to query. The method to query. On return, points to the number of entries in the table jvmtiLineNumberEntry On return, points to the line number table pointer. Class information does not include line numbers. Get Method Location For the method indicated by method, return the beginning and ending addresses through start_location_ptr and end_location_ptr. In a conventional byte code indexing scheme, start_location_ptr will always point to zero and end_location_ptr will always point to the byte code count minus one. jvmdi The class to query. The method to query. On return, points to the first location, or -1 if location information is not available. If the information is available and returns then this will always be zero. On return, points to the last location, or -1 if location information is not available. Class information does not include method sizes. Get Local Variable Table The code array index where the local variable is first valid (that is, where it must have a value). The length of the valid section for this local variable. The last code array index where the local variable is valid is start_location + length. The local variable name, encoded as a modified UTF-8 string. The local variable's type signature, encoded as a modified UTF-8 string. The signature format is the same as that defined in . The local variable's generic signature, encoded as a modified UTF-8 string. The value of this field will be NULL for any local variable which does not have a generic type. The local variable's slot. See Local Variables. Return local variable information. jvmdiClone The method to query. On return, points to the number of entries in the table jvmtiLocalVariableEntry On return, points to an array of local variable table entries. Class information does not include local variable information. Get Bytecodes For the method indicated by method, return the byte codes that implement the method. The number of bytecodes is returned via bytecode_count_ptr. The byte codes themselves are returned via bytecodes_ptr. jvmdi The class to query. The method to query. On return, points to the length of the byte code array On return, points to the pointer to the byte code array Is Method Native For the method indicated by method, return a value indicating whether the method is native via is_native_ptr jvmdi The class to query. The method to query. On return, points to the boolean result of this function. Is Method Synthetic For the method indicated by method, return a value indicating whether the method is synthetic via is_synthetic_ptr. Synthetic methods are generated by the compiler but not present in the original source code. jvmdi The class to query. The method to query. On return, points to the boolean result of this function. Is Method Obsolete Determine if a method ID refers to an obsolete method version. jvmdi The class to query. The method ID to query. On return, points to the boolean result of this function. Set Native Method Prefix This function modifies the failure handling of native method resolution by allowing retry with a prefix applied to the name. When used with the ClassFileLoadHook event, it enables native methods to be instrumented.

Since native methods cannot be directly instrumented (they have no bytecodes), they must be wrapped with a non-native method which can be instrumented. For example, if we had: native boolean foo(int x);

We could transform the class file (with the ClassFileLoadHook event) so that this becomes: boolean foo(int x) { ... record entry to foo ... return wrapped_foo(x); } native boolean wrapped_foo(int x);

Where foo becomes a wrapper for the actual native method with the appended prefix "wrapped_". Note that "wrapped_" would be a poor choice of prefix since it might conceivably form the name of an existing method thus something like "$$$MyAgentWrapped$$$_" would be better but would make these examples less readable.

The wrapper will allow data to be collected on the native method call, but now the problem becomes linking up the wrapped method with the native implementation. That is, the method wrapped_foo needs to be resolved to the native implementation of foo, which might be: Java_somePackage_someClass_foo(JNIEnv* env, jint x)

This function allows the prefix to be specified and the proper resolution to occur. Specifically, when the standard resolution fails, the resolution is retried taking the prefix into consideration. There are two ways that resolution occurs, explicit resolution with the JNI function RegisterNatives and the normal automatic resolution. For RegisterNatives, the VM will attempt this association: method(foo) -> nativeImplementation(foo)

When this fails, the resolution will be retried with the specified prefix prepended to the method name, yielding the correct resolution: method(wrapped_foo) -> nativeImplementation(foo)

For automatic resolution, the VM will attempt: method(wrapped_foo) -> nativeImplementation(wrapped_foo)

When this fails, the resolution will be retried with the specified prefix deleted from the implementation name, yielding the correct resolution: method(wrapped_foo) -> nativeImplementation(foo)

Note that since the prefix is only used when standard resolution fails, native methods can be wrapped selectively.

Since each environment is independent and can do its own transformation of the bytecodes, more than one layer of wrappers may be applied. Thus each environment needs its own prefix. Since transformations are applied in order, the prefixes, if applied, will be applied in the same order. The order of transformation application is described in the event. Thus if three environments applied wrappers, foo might become $env3_$env2_$env1_foo. But if, say, the second environment did not apply a wrapper to foo it would be just $env3_$env1_foo. To be able to efficiently determine the sequence of prefixes, an intermediate prefix is only applied if its non-native wrapper exists. Thus, in the last example, even though $env1_foo is not a native method, the $env1_ prefix is applied since $env1_foo exists.

Since the prefixes are used at resolution time and since resolution may be arbitrarily delayed, a native method prefix must remain set as long as there are corresponding prefixed native methods. new any existing prefix in this environment is cancelled The prefix to apply, encoded as a modified UTF-8 string. Set Native Method Prefixes For a normal agent, will provide all needed native method prefixing. For a meta-agent that performs multiple independent class file transformations (for example as a proxy for another layer of agents) this function allows each transformation to have its own prefix. The prefixes are applied in the order supplied and are processed in the same manor as described for the application of prefixes from multiple environments in .

Any previous prefixes are replaced. Thus, calling this function with a of 0 disables prefixing in this environment.

and this function are the two ways to set the prefixes. Calling SetNativeMethodPrefix with a prefix is the same as calling this function with of 1. Calling SetNativeMethodPrefix with NULL is the same as calling this function with of 0. new The number of prefixes to apply. The prefixes to apply for this environment, each encoded as a modified UTF-8 string. Create Raw Monitor Create a raw monitor. jvmdi A name to identify the monitor, encoded as a modified UTF-8 string. On return, points to the created monitor. Destroy Raw Monitor Destroy the raw monitor. If the monitor being destroyed has been entered by this thread, it will be exited before it is destroyed. If the monitor being destroyed has been entered by another thread, an error will be returned and the monitor will not be destroyed. jvmdi The monitor Not monitor owner Raw Monitor Enter Gain exclusive ownership of a raw monitor. The same thread may enter a monitor more then once. The thread must exit the monitor the same number of times as it is entered. If a monitor is entered during OnLoad (before attached threads exist) and has not exited when attached threads come into existence, the enter is considered to have occurred on the main thread. jvmdi The monitor Raw Monitor Exit Release exclusive ownership of a raw monitor. jvmdi The monitor Not monitor owner Raw Monitor Wait Wait for notification of the raw monitor.

Causes the current thread to wait until either another thread calls or for the specified raw monitor, or the specified timeout has elapsed. jvmdi The monitor The timeout, in milliseconds. If the timeout is zero, then real time is not taken into consideration and the thread simply waits until notified. Not monitor owner Wait was interrupted, try again Raw Monitor Notify Notify a single thread waiting on the raw monitor. jvmdi The monitor Not monitor owner Raw Monitor Notify All Notify all threads waiting on the raw monitor. jvmdi The monitor Not monitor owner Get Raw Monitor Use The fields of the structure are filled in with information about usage of the raw monitor. new the raw monitor to query. jvmtiMonitorUsage On return, filled with monitor information for the specified raw monitor. Get Raw Monitors Return the list of raw monitors.

Note: details about each monitor can be examined with . new On return, pointer to the number of monitors returned in monitors_ptr. On return, pointer to the monitor list. Provides the ability to intercept and resend Java Native Interface (JNI) function calls by manipulating the JNI function table. See JNI Functions in the Java Native Interface Specification.

The following example illustrates intercepting the NewGlobalRef JNI call in order to count reference creation. JNIEnv original_jni_Functions; JNIEnv redirected_jni_Functions; int my_global_ref_count = 0; jobject MyNewGlobalRef(JNIEnv *jni_env, jobject lobj) { ++my_global_ref_count; return originalJNIFunctions->NewGlobalRef(env, lobj); } void myInit() { jvmtiError err; err = (*jvmti_env)->GetJNIFunctionTable(jvmti_env, &original_jni_Functions); if (err != JVMTI_ERROR_NONE) { die(); } err = (*jvmti_env)->GetJNIFunctionTable(jvmti_env, &redirected_jni_Functions); if (err != JVMTI_ERROR_NONE) { die(); } redirectedJNIFunctions->NewGlobalRef = MyNewGlobalRef; err = (*jvmti_env)->SetJNIFunctionTable(jvmti_env, redirected_jni_Functions); if (err != JVMTI_ERROR_NONE) { die(); } } Sometime after myInit is called the user's JNI code is executed which makes the call to create a new global reference. Instead of going to the normal JNI implementation the call goes to myNewGlobalRef. Note that a copy of the original function table is kept so that the normal JNI function can be called after the data is collected. Note also that any JNI functions which are not overwritten will behave normally. check that the example compiles and executes. Set JNI Function Table Set the JNI function table in all current and future JNI environments. As a result, all future JNI calls are directed to the specified functions. Use to get the function table to pass to this function. For this function to take effect the the updated table entries must be used by the JNI clients. Since the table is defined const some compilers may optimize away the access to the table, thus preventing this function from taking effect. The table is copied--changes to the local copy of the table have no effect. This function affects only the function table, all other aspects of the environment are unaffected. See the examples above. new jniNativeInterface Points to the new JNI function table. Get JNI Function Table Get the JNI function table. The JNI function table is copied into allocated memory. If has been called, the modified (not the original) function table is returned. Only the function table is copied, no other aspects of the environment are copied. See the examples above. new jniNativeInterface On return, *function_table points a newly allocated copy of the JNI function table. Set Event Callbacks Set the functions to be called for each event. The callbacks are specified by supplying a replacement function table. The function table is copied--changes to the local copy of the table have no effect. This is an atomic action, all callbacks are set at once. No events are sent before this function is called. When an entry is NULL or when the event is beyond no event is sent. Details on events are described later in this document. An event must be enabled and have a callback in order to be sent--the order in which this function and are called does not affect the result. new jvmtiEventCallbacks remove the existing callbacks The new event callbacks. sizeof(jvmtiEventCallbacks)--for version compatibility. Set Event Notification Mode Control the generation of events. If is JVMTI_ENABLE, the event will be enabled If is JVMTI_DISABLE, the event will be disabled If thread is NULL, the event is enabled or disabled globally; otherwise, it is enabled or disabled for a particular thread. An event is generated for a particular thread if it is enabled either at the thread or global levels.

See below for information on specific events.

The following events cannot be controlled at the thread level through this function.

Initially, no events are enabled at either the thread level or the global level.

Any needed capabilities (see Event Enabling Capabilities below) must be possessed before calling this function.

Details on events are described below. jvmdiClone jvmtiEventMode JVMTI_ENABLE or JVMTI_DISABLE jvmtiEvent the event to control event is controlled at the global level The thread to control for future expansion is non-NULL and is not a valid thread. is non-NULL and is not live (has not been started or is now dead). thread level control was attempted on events which do not permit thread level control. The Required Event Enabling Capability is not possessed. Generate Events Generate events to represent the current state of the VM. For example, if is JVMTI_EVENT_COMPILED_METHOD_LOAD, a event will be sent for each currently compiled method. Methods that were loaded and now have been unloaded are not sent. The history of what events have previously been sent does not effect what events are sent by this function--for example, all currently compiled methods will be sent each time this function is called.

This function is useful when events may have been missed due to the agent attaching after program execution begins; this function generates the missed events.

Attempts to execute Java programming language code or JNI functions may be paused until this function returns - so neither should be called from the thread sending the event. This function returns only after the missed events have been sent, processed and have returned. The event may be sent on a different thread than the thread on which the event occurred. The callback for the event must be set with and the event must be enabled with or the events will not occur. If the VM no longer has the information to generate some or all of the requested events, the events are simply not sent - no error is returned.

Only the following events are supported:

new jvmtiEvent The type of event to generate. Must be one of these:
  • JVMTI_EVENT_COMPILED_METHOD_LOAD
  • JVMTI_EVENT_DYNAMIC_CODE_GENERATED
is JVMTI_EVENT_COMPILED_METHOD_LOAD and is false. is other than JVMTI_EVENT_COMPILED_METHOD_LOAD or JVMTI_EVENT_DYNAMIC_CODE_GENERATED.
These functions allow a implementation to provide functions and events beyond those defined in this specification.

Both extension functions and extension events have parameters each of which has a 'type' and 'kind' chosen from the following tables: Java programming language primitive type - byte. JNI type jbyte. Java programming language primitive type - char. JNI type jchar. Java programming language primitive type - short. JNI type jshort. Java programming language primitive type - int. JNI type . Java programming language primitive type - long. JNI type . Java programming language primitive type - float. JNI type . Java programming language primitive type - double. JNI type . Java programming language primitive type - boolean. JNI type . Java programming language object type - java.lang.Object. JNI type . Returned values are JNI local references and must be managed. Java programming language object type - java.lang.Thread. type . Returned values are JNI local references and must be managed. Java programming language object type - java.lang.Class. JNI type . Returned values are JNI local references and must be managed. Union of all Java programming language primitive and object types - JNI type . Returned values which represent object types are JNI local references and must be managed. Java programming language field identifier - JNI type . Java programming language method identifier - JNI type . C programming language type - char. C programming language type - void. JNI environment - JNIEnv. Should be used with the correct to make it a pointer type. Ingoing argument - foo. Ingoing pointer argument - const foo*. Ingoing array argument - const foo*. Outgoing allocated array argument - foo**. Free with Deallocate. Outgoing allocated array of allocated arrays argument - foo***. Free with Deallocate. Outgoing argument - foo*. Outgoing array argument (pre-allocated by agent) - foo*. Do not Deallocate. The parameter name, encoded as a modified UTF-8 string jvmtiParamKind The kind of the parameter - type modifiers jvmtiParamTypes The base type of the parameter - modified by kind Is a NULL argument permitted? Applies only to pointer and object types. jvmtiError Extension Function This is the implementation-specific extension function. jvmtiEnv The environment is the only fixed parameter for extension functions. The extension function-specific parameters Get Extension Functions jvmtiExtensionFunction The actual function to call The identifier for the extension function, encoded as a modified UTF-8 string. Uses package name conventions. For example, com.sun.hotspot.bar A one sentence description of the function, encoded as a modified UTF-8 string. The number of parameters excluding jvmtiEnv *jvmti_env jvmtiParamInfo Array of parameters (jvmtiEnv *jvmti_env excluded) The number of possible error returns (excluding universal errors) jvmtiError Array of possible errors Returns the set of extension functions. new On return, points to the number of extension functions jvmtiExtensionFunctionInfo Returns an array of extension function info, one per function Get Extension Events The identifying index of the event The identifier for the extension event, encoded as a modified UTF-8 string. Uses package name conventions. For example, com.sun.hotspot.bar A one sentence description of the event, encoded as a modified UTF-8 string. The number of parameters excluding jvmtiEnv *jvmti_env jvmtiParamInfo Array of parameters (jvmtiEnv *jvmti_env excluded) Returns the set of extension events. new On return, points to the number of extension events jvmtiExtensionEventInfo Returns an array of extension event info, one per event Extension Event This is the implementation-specific event. The event handler is set with .

Event handlers for extension events must be declared varargs to match this definition. Failure to do so could result in calling convention mismatch and undefined behavior on some platforms.

For example, if the jvmtiParamInfo returned by indicates that there is a jint parameter, the event handler should be declared: void JNICALL myHandler(jvmtiEnv* jvmti_env, jint myInt, ...) Note the terminal "..." which indicates varargs. jvmtiEnv The environment is the only fixed parameter for extension events. The extension event-specific parameters Set Extension Event Callback Sets the callback function for an extension event and enables the event. Or, if the callback is NULL, disables the event. Note that unlike standard events, setting the callback and enabling the event are a single operation. new Identifies which callback to set. This index is the field of . jvmtiExtensionEvent disable the event If callback is non-NULL, set callback to be the event callback function and enable the event. is not an returned by The capabilities functions allow you to change the functionality available to --that is, which functions can be called, what events can be generated, and what functionality these events and functions can provide.

The "Capabilities" section of each function and event describe which capabilities, if any, they are associated with. "Required Functionality" means it is available for use and no capabilities must be added to use it. "Optional Functionality" means the agent must possess the capability before it can be used. To possess a capability, the agent must add the capability. "Optional Features" describe capabilities which, if added, extend the feature set.

The potentially available capabilities of each implementation are different. Depending on the implementation, a capability:

  • may never be added
  • may be added in either the OnLoad or live phase in any environment
  • may be added only during the OnLoad phase
  • may be possessed by only one environment at a time
  • may be possessed by only one environment at a time, and only during the OnLoad phase
  • and so on ...
Frequently, the addition of a capability may incur a cost in execution speed, start up time, and/or memory footprint. Note that the overhead of using a capability is completely different than the overhead of possessing a capability. Take single stepping as an example. When single stepping is on (that is, when the event is enabled and thus actively sending events) the overhead of sending and processing an event on each instruction is huge in any implementation. However, the overhead of possessing the capability may be small or large, depending on the implementation. Also, when and if a capability is potentially available depends on the implementation. Some examples:
  • One VM might perform all execution by compiling bytecodes into native code and be unable to generate single step instructions. In this implementation the capability can not be added.
  • Another VM may be able to switch execution to a single stepping interpreter at any time. In this implementation, having the capability has no overhead and could be added at any time.
  • Yet another VM might be able to choose a bytecode compiling or single stepping capable interpreted execution engine at start up, but be unable to switch between them. In this implementation the capability would need to be added during the OnLoad phase (before bytecode execution begins) and would have a large impact on execution speed even if single stepping was never used.
  • Still another VM might be able to add an "is single stepping on" check into compiled bytecodes or a generated interpreter. Again in this implementation the capability would need to be added during the OnLoad phase but the overhead (a test and branch on each instruction) would be considerably less.

Each environment has its own set of capabilities. Initially, that set is empty. Any desired capability must be added. If possible, capabilities should be added during the OnLoad phase. For most virtual machines certain capabilities require special set up for the virtual machine and this set up must happen during the OnLoad phase, before the virtual machine begins execution. Once a capability is added, it can only be removed if explicitly relinquished by the environment.

The agent can, determine what capabilities this VM can potentially provide, add the capabilities to be used, release capabilities which are no longer needed, and examine the currently available capabilities. For example, a freshly started agent (in the OnLoad function) wants to enable all possible capabilities. Note that, in general, this is not advisable as the agent may suffer a performance penalty for functionality it is not using. The code might look like this in C: jvmtiCapabilities capa; jvmtiError err; err = (*jvmti)->GetPotentialCapabilities(jvmti, &capa); if (err == JVMTI_ERROR_NONE) { err = (*jvmti)->AddCapabilities(jvmti, &capa); For example, if an agent wants to check if it can get the bytecodes of a method (that is, it wants to check if it previously added this capability and has not relinquished it), the code might look like this in C: jvmtiCapabilities capa; jvmtiError err; err = (*jvmti)->GetCapabilities(jvmti, &capa); if (err == JVMTI_ERROR_NONE) { if (capa.can_get_bytecodes) { ... } } The functions in this category use this capabilities structure which contains boolean flags corresponding to each capability: Can set and get tags, as described in the Heap category. Can set watchpoints on field modification - Can set watchpoints on field access - Can get bytecodes of a method Can test if a field or method is synthetic - and Can get information about ownership of monitors - Can Can Can pop frames off the stack - Can redefine classes with . Can send stop or interrupt to threads Can get the source file name of a class Can get the line number table of a method Can get the source debug extension of a class Can set and get local variables Can return methods in the order they occur in the class file Can get single step events Can get exception thrown and exception catch events Can set and thus get events Can set and thus get events Can suspend and resume threads Can modify (retransform or redefine) any non-primitive non-array class. See . Can get current thread CPU time Can get thread CPU time Can generate method entry events on entering a method Can generate method exit events on leaving a method Can generate ClassFileLoadHook events for every loaded class. Can generate events when a method is compiled or unloaded Can generate events on monitor activity Can generate events on VM allocation of an object Can generate events when a native method is bound to its implementation Can generate events when garbage collection begins or ends Can generate events when the garbage collector frees an object Can return early from a method, as described in the Force Early Return category. Can get information about owned monitors with stack depth - Can get the constant pool of a class - Can set prefix to be applied when native method cannot be resolved - and Can retransform classes with . In addition to the restrictions imposed by the specific implementation on this capability (see the Capability section), this capability must be set before the event is enabled for the first time in this environment. An environment that possesses this capability at the time that ClassFileLoadHook is enabled for the first time is said to be retransformation capable. An environment that does not possess this capability at the time that ClassFileLoadHook is enabled for the first time is said to be retransformation incapable. can be called on any class ( must also be set) Can generate events when the VM is unable to allocate memory from the Java platform heap. See . Can generate events when the VM is unable to create a thread. See . Get Potential Capabilities Returns via the features that can potentially be possessed by this environment at this time. The returned capabilities differ from the complete set of capabilities implemented by the VM in two cases: another environment possesses capabilities that can only be possessed by one environment, or the current phase is live, and certain capabilities can only be added during the OnLoad phase. The function may be used to set any or all or these capabilities. Currently possessed capabilities are included.

Typically this function is used in the OnLoad function. Some virtual machines may allow a limited set of capabilities to be added in the live phase. In this case, the set of potentially available capabilities will likely differ from the OnLoad phase set.

See the Capability Examples. new jvmtiCapabilities On return, points to the capabilities that may be added. Estimate Cost Of Capabilities There is strong opposition to this function. The concern is that it would be difficult or impossible to provide meaningful numbers, as the amount of impact is conditional on many factors that a single number could not represent. There is doubt that conditional implementations would be used or are even a good idea. The thought is that release documentation for the implementation would be the best means of exposing this information. Unless new arguments are presented, I intend to remove this function in the next revision.

Return via the and an estimate of the impact of adding the capabilities pointed to by . The returned estimates are in percentage of additional overhead, thus a time impact of 100 mean the application might run at half the speed. The estimates are very rough approximations and are not guaranteed. Note also, that the estimates are of the impact of having the capability available--when and if it is used the impact may be much greater. Estimates can be for a single capability or for a set of capabilities. Note that the costs are not necessarily additive, adding support for one capability might make another available for free or conversely having two capabilities at once may have multiplicative impact. Estimates are relative to the current set of capabilities - that is, how much more impact given the currently possessed capabilities.

Typically this function is used in the OnLoad function, some virtual machines may allow a limited set of capabilities to be added in the live phase. In this case, the set of potentially available capabilities will likely differ from the OnLoad phase set.

See the Capability Examples. new jvmtiCapabilities points to the capabilities to evaluate. On return, points to the estimated percentage increase in run time if this capability was added. On return, points to the estimated percentage increase in memory space used if this capability was added. The desired capabilities are not even potentially available. Add Capabilities Set new capabilities by adding the capabilities whose values are set to one (1) in *. All previous capabilities are retained. Typically this function is used in the OnLoad function. Some virtual machines may allow a limited set of capabilities to be added in the live phase.

See the Capability Examples. new jvmtiCapabilities Points to the capabilities to add. The desired capabilities are not even potentially available. Relinquish Capabilities Relinquish the capabilities whose values are set to one (1) in *. Some implementations may allow only one environment to have a capability (see the capability introduction). This function releases capabilities so that they may be used by other agents. All other capabilities are retained. The capability will no longer be present in . Attempting to relinquish a capability that the agent does not possess is not an error. It is possible for the agent to be actively using capabilities which are being relinquished. For example, a thread is currently suspended and can_suspend is being relinquished or an event is currently enabled and can_generate_whatever is being relinquished. There are three possible ways we could spec this:

  • relinquish automatically releases them
  • relinquish checks and returns some error code if held
  • it is the agent's responsibility and it is not checked
One of these should be chosen. new jvmtiCapabilities Points to the capabilities to relinquish. Get Capabilities Returns via the optional features which this environment currently possesses. Each possessed capability is indicated by a one (1) in the corresponding field of the capabilities structure. An environment does not possess a capability unless it has been successfully added with . An environment only loses possession of a capability if it has been relinquished with . Thus, this function returns the net result of the AddCapabilities and RelinquishCapabilities calls which have been made.

See the Capability Examples. jvmdiClone jvmtiCapabilities On return, points to the capabilities. These functions provide timing information. The resolution at which the time is updated is not specified. They provides nanosecond precision, but not necessarily nanosecond accuracy. Details about the timers, such as their maximum values, can be accessed with the timer information functions. The information function for each timer returns this data structure. The maximum value the timer can reach. After this value is reached the timer wraps back to zero. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. If true, the timer can be externally adjusted and as a result skip forward. If false, the timer value will never increase faster than real time. If true, the timer can be externally adjusted and as a result skip backward. If false, the timer value will be monotonically increasing. jvmtiTimerKind The kind of timer. On a platform that does not distinguish between user and system time, JVMTI_TIMER_TOTAL_CPU is returned. Reserved for future use. Reserved for future use. Where the timer kind is -- CPU time that a thread is in user mode. CPU time that a thread is in user or system mode. Elapsed time. Get Current Thread CPU Timer Information Get information about the timer. The fields of the structure are filled in with details about the timer. This information is specific to the platform and the implementation of and thus does not vary by thread nor does it vary during a particular invocation of the VM.

Note that the implementations of and may differ, and thus the values returned by GetCurrentThreadCpuTimerInfo and may differ -- see for more information. new Can get current thread CPU time. jvmtiTimerInfo On return, filled with information describing the time returned by . Get Current Thread CPU Time Return the CPU time utilized by the current thread.

Note that the function provides CPU time for any thread, including the current thread. GetCurrentThreadCpuTime exists to support platforms which cannot supply CPU time for threads other than the current thread or which have more accurate information for the current thread (see vs ). On many platforms this call will be equivalent to: GetThreadCpuTime(env, NULL, nanos_ptr) new Can get current thread CPU time.

If this capability is enabled after threads have started, the implementation may choose any time up to and including the time that the capability is enabled as the point where CPU time collection starts.

This capability must be potentially available on any platform where can_get_thread_cpu_time is potentially available. On return, points to the CPU time used by this thread in nanoseconds. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. Get Thread CPU Timer Information Get information about the timer. The fields of the structure are filled in with details about the timer. This information is specific to the platform and the implementation of and thus does not vary by thread nor does it vary during a particular invocation of the VM.

Note that the implementations of and may differ, and thus the values returned by and GetThreadCpuTimerInfo may differ -- see for more information. new Can get thread CPU time. jvmtiTimerInfo On return, filled with information describing the time returned by . Get Thread CPU Time Return the CPU time utilized by the specified thread.

Get information about this timer with . new Can get thread CPU time.

If this capability is enabled after threads have started, the implementation may choose any time up to and including the time that the capability is enabled as the point where CPU time collection starts. The thread to query. On return, points to the CPU time used by the specified thread in nanoseconds. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. Get Timer Information Get information about the timer. The fields of the structure are filled in with details about the timer. This information will not change during a particular invocation of the VM. new jvmtiTimerInfo On return, filled with information describing the time returned by . Get Time Return the current value of the system timer, in nanoseconds.

The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This function provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.

Get information about this timer with . new On return, points to the time in nanoseconds. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. Get Available Processors Returns the number of processors available to the Java virtual machine.

This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property. new On return, points to the maximum number of processors available to the virtual machine; never smaller than one. These functions allow the agent to add to the locations that a class loader searches for a class. This is useful for installing instrumentation under the correct class loader. Add To Bootstrap Class Loader Search This function can be used to cause instrumentation classes to be defined by the bootstrap class loader. See . After the bootstrap class loader unsuccessfully searches for a class, the specified platform-dependent search path will be searched as well. Only one segment may be specified in the . This function may be called multiple times to add multiple segments, the segments will be searched in the order that this function was called.

In the OnLoad phase the function may be used to specify any platform-dependent search path segment to be searched after the bootstrap class loader unsuccessfully searches for a class. The segment is typically a directory or JAR file.

In the live phase the may be used to specify any platform-dependent path to a JAR file. The agent should take care that the JAR file does not contain any classes or resources other than those to be defined by the bootstrap class loader for the purposes of instrumentation.

specifies that a subsequent attempt to resolve a symbolic reference that the Java virtual machine has previously unsuccessfully attempted to resolve always fails with the same error that was thrown as a result of the initial resolution attempt. Consequently, if the JAR file contains an entry that corresponds to a class for which the Java virtual machine has unsuccessfully attempted to resolve a reference, then subsequent attempts to resolve that reference will fail with the same error as the initial attempt. new The platform-dependent search path segment, encoded as a modified UTF-8 string. is an invalid path. In the live phase, anything other than an existing JAR file is an invalid path. Add To System Class Loader Search This function can be used to cause instrumentation classes to be defined by the system class loader. See . After the class loader unsuccessfully searches for a class, the specified platform-dependent search path will be searched as well. Only one segment may be specified in the . This function may be called multiple times to add multiple segments, the segments will be searched in the order that this function was called.

In the OnLoad phase the function may be used to specify any platform-dependent search path segment to be searched after the system class loader unsuccessfully searches for a class. The segment is typically a directory or JAR file.

In the live phase the is a platform-dependent path to a JAR file to be searched after the system class loader unsuccessfully searches for a class. The agent should take care that the JAR file does not contain any classes or resources other than those to be defined by the system class loader for the purposes of instrumentation.

In the live phase the system class loader supports adding a JAR file to be searched if the system class loader implements a method name appendToClassPathForInstrumentation which takes a single parameter of type java.lang.String. The method is not required to have public access.

specifies that a subsequent attempt to resolve a symbolic reference that the Java virtual machine has previously unsuccessfully attempted to resolve always fails with the same error that was thrown as a result of the initial resolution attempt. Consequently, if the JAR file contains an entry that corresponds to a class for which the Java virtual machine has unsuccessfully attempted to resolve a reference, then subsequent attempts to resolve that reference will fail with the same error as the initial attempt. new The platform-dependent search path segment, encoded as a modified UTF-8 string. is an invalid path. In the live phase, anything other than an existing JAR file is an invalid path. Operation not supported by the system class loader. These functions get and set system properties. Get System Properties The list of VM system property keys which may be used with is returned. It is strongly recommended that virtual machines provide the following property keys:

  • java.vm.vendor
  • java.vm.version
  • java.vm.name
  • java.vm.info
  • java.library.path
  • java.class.path
Provides access to system properties defined by and used by the VM. Properties set on the command-line are included. This allows getting and setting of these properties before the VM even begins executing bytecodes. Since this is a VM view of system properties, the set of available properties will usually be different than that in java.lang.System.getProperties. JNI method invocation may be used to access java.lang.System.getProperties.

The set of properties may grow during execution. new On return, points to the number of property keys returned. On return, points to an array of property keys, encoded as modified UTF-8 strings. Get System Property Return a VM system property value given the property key.

The function returns the set of property keys which may be used. The properties which can be retrieved may grow during execution.

Since this is a VM view of system properties, the values of properties may differ from that returned by java.lang.System.getProperty(String). A typical VM might copy the values of the VM system properties into the Properties held by java.lang.System during the initialization of that class. Thereafter any changes to the VM system properties (with ) or the java.lang.System system properties (with java.lang.System.setProperty(String,String)) would cause the values to diverge. JNI method invocation may be used to access java.lang.System.getProperty(String). new The key of the property to retrieve, encoded as a modified UTF-8 string. On return, points to the property value, encoded as a modified UTF-8 string. This property is not available. Use to find available properties. Set System Property Set a VM system property value.

The function returns the set of property keys, some of these may be settable. See . new The key of the property, encoded as a modified UTF-8 string. do not set the value, but return if the property is not writeable The property value to set, encoded as a modified UTF-8 string. This property is not available or is not writeable. Get Phase Return the current phase of VM execution. The phases proceed in sequence: OnLoad phase: while in the Agent_OnLoad or, for statically linked agents, the Agent_OnLoad_<agent-lib-name> function. Primordial phase: between return from Agent_OnLoad or Agent_OnLoad_<agent-lib-name> and the VMStart event. Start phase: when the VMStart event is sent and until the VMInit event is sent. Live phase: when the VMInit event is sent and until the event returns. Dead phase: after the event returns or after start-up failure. In the case of start-up failure the VM will proceed directly to the dead phase skipping intermediate phases and neither a VMInit nor VMDeath event will be sent.

Most functions operate only in the live phase. The following functions operate in either the OnLoad or live phases: The following functions operate in only the OnLoad phase: The following functions operate in the start or live phases: The following functions operate in any phase: JNI functions (except the Invocation API) must only be used in the start or live phases.

Most events are sent only in the live phase. The following events operate in others phases: new jvmtiPhase On return, points to the phase. Dispose Environment Shutdown a connection created with JNI GetEnv (see Environments). Dispose of any resources held by the environment. What resources are reclaimed? What is undone? Breakpoints,watchpoints removed? Threads suspended by this environment are not resumed by this call, this must be done explicitly by the agent. Memory allocated by this environment via calls to functions is not released, this can be done explicitly by the agent by calling . Raw monitors created by this environment are not destroyed, this can be done explicitly by the agent by calling . The state of threads waiting on raw monitors created by this environment are not affected.

Any native method prefixes for this environment will be unset; the agent must remove any prefixed native methods before dispose is called.

Any capabilities held by this environment are relinquished.

Events enabled by this environment will no longer be sent, however event handlers currently running will continue to run. Caution must be exercised in the design of event handlers whose environment may be disposed and thus become invalid during their execution.

This environment may not be used after this call. This call returns to the caller. new Set Environment Local Storage The VM stores a pointer value associated with each environment. This pointer value is called environment-local storage. This value is NULL unless set with this function. Agents can allocate memory in which they store environment specific information. By setting environment-local storage it can then be accessed with .

Called by the agent to set the value of the environment-local storage. supplies to the agent a pointer-size environment-local storage that can be used to record per-environment information. new value is set to NULL The value to be entered into the environment-local storage. Get Environment Local Storage Called by the agent to get the value of the environment-local storage. new Pointer through which the value of the environment local storage is returned. If environment-local storage has not been set with returned pointer is NULL. Get Version Number Return the version via version_ptr. The return value is the version identifier. The version identifier includes major, minor and micro version as well as the interface type. Value of JVMTI_VERSION_MASK_INTERFACE_TYPE for JNI. Value of JVMTI_VERSION_MASK_INTERFACE_TYPE for . Mask to extract interface type. The value of the version returned by this function masked with JVMTI_VERSION_MASK_INTERFACE_TYPE is always JVMTI_VERSION_INTERFACE_JVMTI since this is a function. Mask to extract major version number. Mask to extract minor version number. Mask to extract micro version number. Shift to extract major version number. Shift to extract minor version number. Shift to extract micro version number. jvmdi On return, points to the version. Get Error Name Return the symbolic name for an error code.

For example GetErrorName(env, JVMTI_ERROR_NONE, &err_name) would return in err_name the string "JVMTI_ERROR_NONE". new jvmtiError The error code. On return, points to the error name. The name is encoded as a modified UTF-8 string, but is restricted to the ASCII subset. Set Verbose Flag Verbose output other than the below. Verbose garbage collector output, like that specified with -verbose:gc. Verbose class loading output, like that specified with -verbose:class. Verbose JNI output, like that specified with -verbose:jni. Control verbose output. This is the output which typically is sent to stderr. new jvmtiVerboseFlag Which verbose flag to set. New value of the flag. Get JLocation Format Although the greatest functionality is achieved with location information referencing the virtual machine bytecode index, the definition of jlocation has intentionally been left unconstrained to allow VM implementations that do not have this information.

This function describes the representation of jlocation used in this VM. If the returned format is , jlocations can be used as in indices into the array returned by . jlocation values represent virtual machine bytecode indices--that is, offsets into the virtual machine code for a method. jlocation values represent native machine program counter values. jlocation values have some other representation. new jvmtiJlocationFormat On return, points to the format identifier for jlocation values. Every function returns a jvmtiError error code.

It is the responsibility of the agent to call functions with valid parameters and in the proper context (calling thread is attached, phase is correct, etc.). Detecting some error conditions may be difficult, inefficient, or impossible for an implementation. The errors listed in Function Specific Required Errors must be detected by the implementation. All other errors represent the recommended response to the error condition. The following errors may be returned by any function No error has occurred. This is the error code that is returned on successful completion of the function. Pointer is unexpectedly NULL. The function attempted to allocate memory and no more memory was available for allocation. The desired functionality has not been enabled in this virtual machine. The thread being used to call this function is not attached to the virtual machine. Calls must be made from attached threads. See AttachCurrentThread in the JNI invocation API. The environment provided is no longer connected or is not an environment. The desired functionality is not available in the current phase. Always returned if the virtual machine has completed running. An unexpected internal error has occurred. The following errors are returned by some functions and must be returned by the implementation when the condition occurs. Invalid priority. Thread was not suspended. Thread already suspended. This operation requires the thread to be alive--that is, it must be started and not yet have died. The class has been loaded but not yet prepared. There are no Java programming language or JNI stack frames at the specified depth. Information about the frame is not available (e.g. for native frames). Item already set. Desired element (e.g. field or breakpoint) not found This thread doesn't own the raw monitor. The call has been interrupted before completion. The class cannot be modified. The functionality is not available in this virtual machine. The requested information is not available. The specified event type ID is not recognized. The requested information is not available for native method. The class loader does not support this operation. The following errors are returned by some functions. They are returned in the event of invalid parameters passed by the agent or usage in an invalid context. An implementation is not required to detect these errors. The passed thread is not a valid thread. Invalid field. Invalid method. Invalid location. Invalid object. Invalid class. The variable is not an appropriate type for the function used. Invalid slot. The capability being used is false in this environment. Thread group invalid. Invalid raw monitor. Illegal argument. The state of the thread has been modified, and is now inconsistent. A new class file has a version number not supported by this VM. A new class file is malformed (the VM would return a ClassFormatError). The new class file definitions would lead to a circular definition (the VM would return a ClassCircularityError). A new class file would require adding a method. A new class version changes a field. The class bytes fail verification. A direct superclass is different for the new class version, or the set of directly implemented interfaces is different. A new class version does not declare a method declared in the old class version. The class name defined in the new class file is different from the name in the old class object. A new class version has different modifiers. A method in the new class version has different modifiers than its counterpart in the old class version. Agents can be informed of many events that occur in application programs.

To handle events, designate a set of callback functions with . For each event the corresponding callback function will be called. Arguments to the callback function provide additional information about the event.

The callback function is usually called from within an application thread. The implementation does not queue events in any way. This means that event callback functions must be written carefully. Here are some general guidelines. See the individual event descriptions for further suggestions.

  • Any exception thrown during the execution of an event callback can overwrite any current pending exception in the current application thread. Care must be taken to preserve a pending exception when an event callback makes a JNI call that might generate an exception.
  • Event callback functions must be re-entrant. The implementation does not queue events. If an agent needs to process events one at a time, it can use a raw monitor inside the event callback functions to serialize event processing.
  • Event callback functions that execute JNI's FindClass function to load classes need to note that FindClass locates the class loader associated with the current native method. For the purposes of class loading, an event callback that includes a JNI environment as a parameter to the callback will treated as if it is a native call, where the native method is in the class of the event thread's current frame.

Some events identify objects with JNI references. All references in events are JNI local references and will become invalid after the event callback returns. Unless stated otherwise, memory referenced by pointers sent in event callbacks may not be referenced after the event callback returns.

Except where stated otherwise, events are delivered on the thread that caused the event. Events are sent at the time they occur. The specification for each event includes the set of phases in which it can be sent; if an event triggering activity occurs during another phase, no event is sent.

A thread that generates an event does not change its execution status (for example, the event does not cause the thread to be suspended). If an agent wishes the event to result in suspension, then the agent is responsible for explicitly suspending the thread with .

If an event is enabled in multiple environments, the event will be sent to each agent in the order that the environments were created. All events are initially disabled. In order to receive any event:

  • If the event requires a capability, that capability must be added with .
  • A callback for the event must be set with .
  • The event must be enabled with .
In many situations it is possible for multiple events to occur at the same location in one thread. When this happens, all the events are reported through the event callbacks in the order specified in this section.

If the current location is at the entry point of a method, the event is reported before any other event at the current location in the same thread.

If an exception catch has been detected at the current location, either because it is the beginning of a catch clause or a native method that cleared a pending exception has returned, the exceptionCatch event is reported before any other event at the current location in the same thread.

If a singleStep event or breakpoint event is triggered at the current location, the event is defined to occur immediately before the code at the current location is executed. These events are reported before any events which are triggered by the execution of code at the current location in the same thread (specifically: exception, fieldAccess, and fieldModification). If both a step and breakpoint event are triggered for the same thread and location, the step event is reported before the breakpoint event.

If the current location is the exit point of a method (that is, the last location before returning to the caller), the event and the event (if requested) are reported after all other events at the current location in the same thread. There is no specified ordering of these two events with respect to each other.

Co-located events can be triggered during the processing of some other event by the agent at the same location in the same thread. If such an event, of type y, is triggered during the processing of an event of type x, and if x precedes y in the ordering specified above, the co-located event y is reported for the current thread and location. If x does not precede y, y is not reported for the current thread and location. For example, if a breakpoint is set at the current location during the processing of , that breakpoint will be reported before the thread moves off the current location.

The following events are never considered to be co-located with other events.

The event callback structure below is used to specify the handler function for events. It is set with the function. Single step events allow the agent to trace thread execution at the finest granularity allowed by the VM. A single step event is generated whenever a thread reaches a new location. Typically, single step events represent the completion of one VM instruction as defined in . However, some implementations may define locations differently. In any case the method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available.

No single step events are generated from within native methods. jvmdi JNIEnv The JNI environment of the event (current) thread Thread about to execution a new instruction Class of the method about to execute a new instruction Method about to execute a new instruction Location of the new instruction Breakpoint events are generated whenever a thread reaches a location designated as a breakpoint with . The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available. jvmdi JNIEnv The JNI environment of the event (current) thread. Thread that hit the breakpoint Class of the method that hit the breakpoint Method that hit the breakpoint location of the breakpoint Field access events are generated whenever a thread accesses a field that was designated as a watchpoint with . The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available. jvmdi JNIEnv The JNI environment of the event (current) thread Thread accessing the field Class of the method where the access is occurring Method where the access is occurring Location where the access is occurring Class of the field being accessed Object with the field being accessed if the field is an instance field; NULL otherwise Field being accessed Field modification events are generated whenever a thread modifies a field that was designated as a watchpoint with . The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available. jvmdi JNIEnv The JNI environment of the event (current) thread Thread modifying the field Class of the method where the modification is occurring Method where the modification is occurring Location where the modification is occurring Class of the field being modified Object with the field being modified if the field is an instance field; NULL otherwise Field being modified Signature type of the new value The new value Frame pop events are generated upon exit from a single method in a single frame as specified in a call to . This is true whether termination is caused by executing its return instruction or by throwing an exception to its caller (see ). However, frame pops caused by the function are not reported.

The location reported by identifies the executable location in the returning method, immediately prior to the return. jvmdi JNIEnv The JNI environment of the event (current) thread Thread that is popping the frame Class of the method being popped Method being popped True if frame was popped by a thrown exception. False if method exited through its return instruction. Method entry events are generated upon entry of Java programming language methods (including native methods).

The location reported by identifies the initial executable location in the method.

Enabling method entry or exit events will significantly degrade performance on many platforms and is thus not advised for performance critical usage (such as profiling). Bytecode instrumentation should be used in these cases. jvmdi JNIEnv The JNI environment of the event (current) thread Thread entering the method Class of the method being entered Method being entered Method exit events are generated upon exit from Java programming language methods (including native methods). This is true whether termination is caused by executing its return instruction or by throwing an exception to its caller (see ).

The method field uniquely identifies the method being entered or exited. The frame field provides access to the stack frame for the method.

The location reported by identifies the executable location in the returning method immediately prior to the return.

Enabling method entry or exit events will significantly degrade performance on many platforms and is thus not advised for performance critical usage (such as profiling). Bytecode instrumentation should be used in these cases. jvmdi JNIEnv The JNI environment of the event (current) thread Thread exiting the method Class of the method being exited Method being exited True if frame was popped by a thrown exception. False if method exited through its return instruction. The return value of the method being exited. Undefined and should not be used if is true. A Native Method Bind event is sent when a VM binds a Java programming language native method to the address of a function that implements the native method. This will occur when the native method is called for the first time and also occurs when the JNI function RegisterNatives is called. This event allows the bind to be redirected to an agent-specified proxy function. This event is not sent when the native method is unbound. Typically, this proxy function will need to be specific to a particular method or, to handle the general case, automatically generated assembly code, since after instrumentation code is executed the function at the original binding address will usually be invoked. The original binding can be restored or the redirection changed by use of the JNI function RegisterNatives. Some events may be sent during the primordial phase, JNI and most of cannot be used at this time but the method and address can be saved for use later. new JNIEnv The JNI environment of the event (current) thread Will be NULL if sent during the primordial phase. Thread requesting the bind Class of the method being bound Native method being bound The address the VM is about to bind to--that is, the address of the implementation of the native method if the referenced address is changed (that is, if *new_address_ptr is set), the binding will instead be made to the supplied address. Exception events are generated whenever an exception is first detected in a Java programming language method. Where "exception" means any java.lang.Throwable. The exception may have been thrown by a Java programming language or native method, but in the case of native methods, the event is not generated until the exception is first seen by a Java programming language method. If an exception is set and cleared in a native method (and thus is never visible to Java programming language code), no exception event is generated.

The method and location parameters uniquely identify the current location (where the exception was detected) and allow the mapping to source file and line number when that information is available. The exception field identifies the thrown exception object. The catch_method and catch_location identify the location of the catch clause, if any, that handles the thrown exception. If there is no such catch clause, each field is set to 0. There is no guarantee that the thread will ever reach this catch clause. If there are native methods on the call stack between the throw location and the catch clause, the exception may be reset by one of those native methods. Similarly, exceptions that are reported as uncaught (catch_klass et al. set to 0) may in fact be caught by native code. Agents can check for these occurrences by monitoring events. Note that finally clauses are implemented as catch and re-throw. Therefore they will be reported in the catch location. jvmdi JNIEnv The JNI environment of the event (current) thread Thread generating the exception Class generating the exception Method generating the exception Location where exception occurred The exception being thrown Class that will catch the exception, or NULL if no known catch Method that will catch the exception, or NULL if no known catch location which will catch the exception or zero if no known catch Exception catch events are generated whenever a thrown exception is caught. Where "exception" means any java.lang.Throwable. If the exception is caught in a Java programming language method, the event is generated when the catch clause is reached. If the exception is caught in a native method, the event is generated as soon as control is returned to a Java programming language method. Exception catch events are generated for any exception for which a throw was detected in a Java programming language method. Note that finally clauses are implemented as catch and re-throw. Therefore they will generate exception catch events.

The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available. For exceptions caught in a Java programming language method, the exception object identifies the exception object. Exceptions caught in native methods are not necessarily available by the time the exception catch is reported, so the exception field is set to NULL. jvmdi JNIEnv The JNI environment of the event (current) thread Thread catching the exception Class catching the exception Method catching the exception Location where exception is being caught Exception being caught Thread start events are generated by a new thread before its initial method executes.

A thread may be listed in the array returned by before its thread start event is generated. It is possible for other events to be generated on a thread before its thread start event.

The event is sent on the newly started . jvmdi JNIEnv The JNI environment of the event (current) thread. Thread starting Thread end events are generated by a terminating thread after its initial method has finished execution.

A thread may be listed in the array returned by after its thread end event is generated. No events are generated on a thread after its thread end event.

The event is sent on the dying . jvmdi JNIEnv The JNI environment of the event (current) thread. Thread ending A class load event is generated when a class is first loaded. The order of class load events generated by a particular thread are guaranteed to match the order of class loading within that thread. Array class creation does not generate a class load event. The creation of a primitive class (for example, java.lang.Integer.TYPE) does not generate a class load event.

This event is sent at an early stage in loading the class. As a result the class should be used carefully. Note, for example, that methods and fields are not yet loaded, so queries for methods, fields, subclasses, and so on will not give correct results. See "Loading of Classes and Interfaces" in the Java Language Specification. For most purposes the event will be more useful. jvmdi JNIEnv The JNI environment of the event (current) thread Thread loading the class Class being loaded A class unload event is generated when the class is about to be unloaded. Class unload events take place during garbage collection and must be handled extremely carefully. The garbage collector holds many locks and has suspended all other threads, so the event handler cannot depend on the ability to acquire any locks. The class unload event handler should do as little as possible, perhaps by queuing information to be processed later. In particular, the jclass should be used only in the JNI function isSameObject or in the following functions:

jvmdi JNIEnv The JNI environment of the event (current) thread Thread generating the class unload Class being unloaded
A class prepare event is generated when class preparation is complete. At this point, class fields, methods, and implemented interfaces are available, and no code from the class has been executed. Since array classes never have fields or methods, class prepare events are not generated for them. Class prepare events are not generated for primitive classes (for example, java.lang.Integer.TYPE). jvmdi JNIEnv The JNI environment of the event (current) thread Thread generating the class prepare Class being prepared This event is sent when the VM obtains class file data, but before it constructs the in-memory representation for that class. This event is also sent when the class is being modified by the function or the function, called in any environment. The agent can instrument the existing class file data sent by the VM to include profiling/debugging hooks. See the description of bytecode instrumentation for usage information.

This event may be sent before the VM is initialized (the primordial phase). During this time no VM resources should be created. Some classes might not be compatible with the function (eg. ROMized classes) and this event will not be generated for these classes.

The agent must allocate the space for the modified class file data buffer using the memory allocation function because the VM is responsible for freeing the new class file data buffer using . Note that is permitted during the primordial phase.

If the agent wishes to modify the class file, it must set new_class_data to point to the newly instrumented class file data buffer and set new_class_data_len to the length of that buffer before returning from this call. If no modification is desired, the agent simply does not set new_class_data. If multiple agents have enabled this event the results are chained. That is, if new_class_data has been set, it becomes the class_data for the next agent.

The order that this event is sent to each environment differs from other events. This event is sent to environments in the following order:

  • retransformation incapable environments, in the order in which they were created
  • retransformation capable environments, in the order in which they were created
When triggered by , this event is sent only to retransformation capable environments.
jvmpi JNIEnv The JNI environment of the event (current) thread. Will be NULL if sent during the primordial phase. The class being redefined or retransformed. NULL if sent by class load. The class loader loading the class. NULL if the bootstrap class loader. Name of class being loaded as a VM internal qualified name (for example, "java/util/List"), encoded as a modified UTF-8 string. Note: if the class is defined with a NULL name or without a name specified, name will be NULL. The ProtectionDomain of the class. Length of current class file data buffer. Pointer to the current class file data buffer. Pointer to the length of the new class file data buffer. Pointer to the pointer to the instrumented class file data buffer.
The VM initialization event signals the start of the VM. At this time JNI is live but the VM is not yet fully initialized. Once this event is generated, the agent is free to call any JNI function. This event signals the beginning of the start phase, functions permitted in the start phase may be called.

In the case of VM start-up failure, this event will not be sent. jvmdi JNIEnv The JNI environment of the event (current) thread. The VM initialization event signals the completion of VM initialization. Once this event is generated, the agent is free to call any JNI or function. The VM initialization event can be preceded by or can be concurrent with other events, but the preceding events should be handled carefully, if at all, because the VM has not completed its initialization. The thread start event for the main application thread is guaranteed not to occur until after the handler for the VM initialization event returns.

In the case of VM start-up failure, this event will not be sent. jvmdi JNIEnv The JNI environment of the event (current) thread. The initial thread The VM death event notifies the agent of the termination of the VM. No events will occur after the VMDeath event.

In the case of VM start-up failure, this event will not be sent. Note that Agent_OnUnload will still be called in these cases. jvmdi JNIEnv The JNI environment of the event (current) thread Sent when a method is compiled and loaded into memory by the VM. If it is unloaded, the event is sent. If it is moved, the event is sent, followed by a new CompiledMethodLoad event. Note that a single method may have multiple compiled forms, and that this event will be sent for each form. Note also that several methods may be inlined into a single address range, and that this event will be sent for each method.

These events can be sent after their initial occurrence with . jvmpi Starting native address of code corresponding to a location Corresponding location. See for the meaning of location. Class of the method being compiled and loaded Method being compiled and loaded Size of compiled code Address where compiled method code is loaded Number of entries in the address map. Zero if mapping information cannot be supplied. jvmtiAddrLocationMap Map from native addresses to location. The native address range of each entry is from to start_address-1 of the next entry. NULL if mapping information cannot be supplied. VM-specific compilation information. The referenced compile information is managed by the VM and must not depend on the agent for collection. A VM implementation defines the content and lifetime of the information. Sent when a compiled method is unloaded from memory. This event might not be sent on the thread which performed the unload. This event may be sent sometime after the unload occurs, but will be sent before the memory is reused by a newly generated compiled method. This event may be sent after the class is unloaded. jvmpi Class of the compiled method being unloaded. Compiled method being unloaded. For identification of the compiled method only -- the class may be unloaded and therefore the method should not be used as an argument to further JNI or functions. Address where compiled method code was loaded. For identification of the compiled method only -- the space may have been reclaimed. Sent when a component of the virtual machine is generated dynamically. This does not correspond to Java programming language code that is compiled--see . This is for native code--for example, an interpreter that is generated differently depending on command-line options.

Note that this event has no controlling capability. If a VM cannot generate these events, it simply does not send any.

These events can be sent after their initial occurrence with . jvmpi Name of the code, encoded as a modified UTF-8 string. Intended for display to an end-user. The name might not be unique. Native address of the code Length in bytes of the code Sent by the VM to request the agent to dump its data. This is just a hint and the agent need not react to this event. This is useful for processing command-line signals from users. For example, in the Java 2 SDK a CTRL-Break on Win32 and a CTRL-\ on Solaris causes the VM to send this event to the agent. jvmpi Sent when a thread is attempting to enter a Java programming language monitor already acquired by another thread. jvmpi JNIEnv The JNI environment of the event (current) thread JNI local reference to the thread attempting to enter the monitor JNI local reference to the monitor Sent when a thread enters a Java programming language monitor after waiting for it to be released by another thread. jvmpi JNIEnv The JNI environment of the event (current) thread JNI local reference to the thread entering the monitor JNI local reference to the monitor Sent when a thread is about to wait on an object. jvmpi JNIEnv The JNI environment of the event (current) thread JNI local reference to the thread about to wait JNI local reference to the monitor The number of milliseconds the thread will wait Sent when a thread finishes waiting on an object. jvmpi JNIEnv The JNI environment of the event (current) thread JNI local reference to the thread that was finished waiting JNI local reference to the monitor. True if the monitor timed out Sent when a VM resource needed by a running application has been exhausted. Except as required by the optional capabilities, the set of resources which report exhaustion is implementation dependent.

The following bit flags define the properties of the resource exhaustion: After this event returns, the VM will throw a java.lang.OutOfMemoryError. The VM was unable to allocate memory from the Java platform heap. The heap is the runtime data area from which memory for all class instances and arrays are allocated. The VM was unable to create a thread. new Can generate events when the VM is unable to allocate memory from the heap. Can generate events when the VM is unable to create a thread. JNIEnv The JNI environment of the event (current) thread Flags defining the properties of the of resource exhaustion as specified by the Resource Exhaustion Flags. Reserved. Description of the resource exhaustion, encoded as a modified UTF-8 string. Sent when a method causes the virtual machine to allocate an Object visible to Java programming language code and the allocation is not detectable by other intrumentation mechanisms. Generally object allocation should be detected by instrumenting the bytecodes of allocating methods. Object allocation generated in native code by JNI function calls should be detected using JNI function interception. Some methods might not have associated bytecodes and are not native methods, they instead are executed directly by the VM. These methods should send this event. Virtual machines which are incapable of bytecode instrumentation for some or all of their methods can send this event.

Typical examples where this event might be sent:

  • Reflection -- for example, java.lang.Class.newInstance()
  • Methods not represented by bytecodes -- for example, VM intrinsics and J2ME preloaded classes
Cases where this event would not be generated:
  • Allocation due to bytecodes -- for example, the new and newarray VM instructions
  • Allocation due to JNI function calls -- for example, AllocObject
  • Allocations during VM initialization
  • VM internal objects
new JNIEnv The JNI environment of the event (current) thread Thread allocating the object. JNI local reference to the object that was allocated JNI local reference to the class of the object Size of the object (in bytes). See .
An Object Free event is sent when the garbage collector frees an object. Events are only sent for tagged objects--see heap functions.

The event handler must not use JNI functions and must not use functions except those which specifically allow such use (see the raw monitor, memory management, and environment local storage functions). new The freed object's tag A Garbage Collection Start event is sent when a garbage collection pause begins. Only stop-the-world collections are reported--that is, collections during which all threads cease to modify the state of the Java virtual machine. This means that some collectors will never generate these events. This event is sent while the VM is still stopped, thus the event handler must not use JNI functions and must not use functions except those which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

This event is always sent as a matched pair with (assuming both events are enabled) and no garbage collection events will occur between them. new A Garbage Collection Finish event is sent when a garbage collection pause ends. This event is sent while the VM is still stopped, thus the event handler must not use JNI functions and must not use functions except those which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

Some agents may need to do post garbage collection operations that require the use of the disallowed or JNI functions. For these cases an agent thread can be created which waits on a raw monitor, and the handler for the Garbage Collection Finish event simply notifies the raw monitor

This event is always sent as a matched pair with (assuming both events are enabled). The most important use of this event is to provide timing information, and thus additional information is not required. However, information about the collection which is "free" should be included - what that information is needs to be determined. new Send verbose messages as strings. This format is extremely fragile, as it can change with each platform, collector and version. Alternatives include:

  • building off Java programming language M and M APIs
  • XML
  • key/value pairs
  • removing it
Though this seemed trivial to implement. In the RI it appears this will be quite complex.
new jvmtiVerboseFlag Which verbose output is being sent. Message text, encoded as a modified UTF-8 string.
extends the data types defined by JNI. Holds a Java programming language boolean. Unsigned 8 bits. Holds a Java programming language char. Unsigned 16 bits. Holds a Java programming language int. Signed 32 bits. Holds a Java programming language long. Signed 64 bits. Holds a Java programming language float. 32 bits. Holds a Java programming language double. 64 bits. Holds a Java programming language object. Holds a Java programming language class. Is a union of all primitive types and jobject. Thus, holds any Java programming language value. Identifies a Java programming language field. jfieldIDs returned by functions and events may be safely stored. Identifies a Java programming language method, initializer, or constructor. jmethodIDs returned by functions and events may be safely stored. However, if the class is unloaded, they become invalid and must not be used. Pointer to the JNI function table. Pointer to this (JNIEnv *) is a JNI environment. The environment pointer. See the Function Section. jvmtiEnv points to the function table pointer. typedef jobject jthread; Subtype of that holds a thread. typedef jobject jthreadGroup; Subtype of that holds a thread group. typedef jlong jlocation; A 64 bit value, representing a monotonically increasing executable position within a method. -1 indicates a native method. See for the format on a given VM. struct _jrawMonitorID; typedef struct _jrawMonitorID *jrawMonitorID; A raw monitor. Holds an error return code. See the Error section for possible values. typedef enum { JVMTI_ERROR_NONE = 0, JVMTI_ERROR_INVALID_THREAD = 10, ... } jvmtiError; An identifier for an event type. See the Event section for possible values. It is guaranteed that future versions of this specification will never assign zero as an event type identifier. typedef enum { JVMTI_EVENT_SINGLE_STEP = 1, JVMTI_EVENT_BREAKPOINT = 2, ... } jvmtiEvent; The callbacks used for events. typedef struct { jvmtiEventVMInit VMInit; jvmtiEventVMDeath VMDeath; ... } jvmtiEventCallbacks; See event callbacks for the complete structure.

Where, for example, the VM initialization callback is defined: typedef void (JNICALL *jvmtiEventVMInit) (jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread); See the individual events for the callback function definition. typedef struct JNINativeInterface_ jniNativeInterface; Typedef for the JNI function table JNINativeInterface defined in the JNI Specification. The JNI reference implementation defines this with an underscore. JVMDI requires that the agent suspend threads before calling certain sensitive functions. JVMPI requires garbage collection to be disabled before calling certain sensitive functions. It was suggested that rather than have this requirement, that VM place itself in a suitable state before performing an operation. This makes considerable sense since each VM knows its requirements and can most easily arrange a safe state.

The ability to externally suspend/resume threads will, of course, remain. The ability to enable/disable garbage collection will not.

This issue is resolved--suspend will not be required. The spec has been updated to reflect this. There are a variety of approaches to sampling call stacks. The biggest bifurcation is between VM controlled and agent controlled.

This issue is resolved--agent controlled sampling will be the approach. JVMDI represents threads as jthread. JVMPI primarily uses JNIEnv* to represent threads.

The Expert Group has chosen jthread as the representation for threads in . JNIEnv* is sent by events since it is needed to JNI functions. JNIEnv, per the JNI spec, are not supposed to be used outside their thread. The JNI spec allows an implementation to depend on jclass/jmethodID pairs, rather than simply a jmethodID, to reference a method. JVMDI, for consistency, choose the same representation. JVMPI, however, specifies that a jmethodID alone maps to a method. Both of the Sun J2SE virtual machines (Classic and HotSpot) store pointers in jmethodIDs, and as a result, a jmethodID is sufficient. In fact, any JVM implementation that supports JVMPI must have such a representation. will use jmethodID as a unique representation of a method (no jclass is used). There should be efficiency gains, particularly in functionality like stack dumping, to this representation.

Note that fields were not used in JVMPI and that the access profile of fields differs from methods--for implementation efficiency reasons, a jclass/jfieldID pair will still be needed for field reference. Functions return local references. In JVMDI, a frame ID is used to represent a frame. Problem with this is that a VM must track when a frame becomes invalid, a far better approach, and the one used in , is to reference frames by depth. Currently, having a required capabilities means that the functionality is optional. Capabilities are useful even for required functionality since they can inform the VM is needed set-up. Thus, there should be a set of capabilities that a conformant implementation must provide (if requested during Agent_OnLoad). A hint of the percentage of objects that will be tagged would help the VM pick a good implementation. How difficult or easy would be to extend the monitor_info category to include

  - current number of monitors 
  - enumeration of monitors 
  - enumeration of threads waiting on a given monitor 
    
The reason for my question is the fact that current get_monitor_info support requires the agent to specify a given thread to get the info which is probably OK in the profiling/debugging space, while in the monitoring space the agent could be watching the monitor list and then decide which thread to ask for the info. You might ask why is this important for monitoring .... I think it can aid in the detection/prediction of application contention caused by hot-locks. The specification is an evolving document with major, minor, and micro version numbers. A released version of the specification is uniquely identified by its major and minor version. The functions, events, and capabilities in this specification indicate a "Since" value which is the major and minor version in which it was introduced. The version of the specification implemented by the VM can be retrieved at runtime with the function. Converted to XML document. Elided heap dump functions (for now) since what was there was wrong. Added detail throughout. Changed JVMTI_THREAD_STATUS_RUNNING to JVMTI_THREAD_STATUS_RUNNABLE. Added AsyncGetStackTrace. Added jframeID return to GetStackTrace. Elided GetCurrentFrame and GetCallingFrame functions (for now) since what was there since they are redundant with GetStackTrace. Elided ClearAllBreakpoints since it has always been redundant. Added GetSystemProperties. Changed the thread local storage functions to use jthread. Added GetJLocationFormat. Added events and introductory text. Cross reference type and constant definitions. Added DTD. Added capabilities function section. Assign capabilities to each function and event. Add JNI interception functions. Auto generate SetEventNotificationMode capabilities. Add event. Add event. Add const to declarations. Change method exit and frame pop to send on exception. Add ForceGarbageCollection. Redo Xrun section; clarify GetStackTrace and add example; Fix width problems; use "agent" consistently. Remove previous start-up intro. Add Environments section. Add . Numerous minor updates. Add heap profiling functions added: get/set annotation, iterate live objects/heap. Add heap profiling functions place holder added: heap roots. Heap profiling event added: object free. Heap profiling event redesigned: vm object allocation. Heap profiling event placeholders added: garbage collection start/finish. Native method bind event added. Revamp suspend/resume functions. Add origin information with jvmdi tag. Misc fixes. Add semantics to types. Add local reference section. Autogenerate parameter descriptions from types. Document that RunAgentThread sends threadStart. Remove redundant local ref and dealloc warning. Convert GetRawMonitorName to allocated buffer. Add GenerateEvents. Make raw monitors a type and rename to "jrawMonitorID". Include origin information. Clean-up JVMDI issue references. Remove Deallocate warnings which are now automatically generated. Fix representation issues for jthread. Make capabilities buffered out to 64 bits - and do it automatically. Make constants which are enumeration into enum types. Parameters now of enum type. Clean-up and index type section. Replace remaining datadef entities with callback. Correct GenerateEvents description. More internal semantics work. Replace previous GetSystemProperties with two functions which use allocated information instead fixed. Add SetSystemProperty. More internal semantics work. Add varargs to end of SetEventNotificationMode. Finish fixing spec to reflect that alloc sizes are jlong. Allow NULL as RunAgentThread arg. Fixed names to standardized naming convention Removed AsyncGetStackTrace. Since we are using jthread, removed GetThread. Change GetFieldName to allow NULLs like GetMethodName. Rewrite the introductory text, adding sections on start-up, environments and bytecode instrumentation. Change the command line arguments per EG discussions. Add an introduction to the capabilities section. Add the extension mechanism category and functions. Mark for deletion, but clarified anyhow, SuspendAllThreads. Rename IterateOverLiveObjects to IterateOverReachableObjects and change the text accordingly. Clarify IterateOverHeap. Clarify CompiledMethodLoad. Discuss prerequisite state for Calling Functions. Clarify SetAllocationHooks. Added issues ("To be resolved:") through-out. And so on... Remove struct from the call to GetOwnedMonitorInfo. Automatically generate most error documentation, remove (rather broken) hand written error doc. Better describe capability use (empty initial set). Add min value to jint params. Remove the capability can_access_thread_local_storage. Rename error JVMTI_ERROR_NOT_IMPLEMENTED to JVMTI_ERROR_MUST_POSSESS_CAPABILITY; same for *NOT_IMPLEMENTED. Description fixes. Rename GetClassSignature to GetClassName. Rename IterateOverClassObjects to IterateOverInstancesOfClass. Remove GetMaxStack (operand stack isn't used in ). Description fixes: define launch-time, remove native frame pop from PopFrame, and assorted clarifications. Fix minor editing problem. Add phase information. Remap (compact) event numbers. More phase information - allow "any". Elide raw monitor queries and events. Minor description fixes. Add GetPhase. Use "phase" through document. Elide GetRawMonitorName. Elide GetObjectMonitors. Fixes from link, XML, and spell checking. Auto-generate the callback structure. One character XML fix. Change function parameter names to be consistent with event parameters (fooBarBaz becomes foo_bar_baz). Fix broken link. Fix thread markers. Change constants so they are under 128 to workaround compiler problems. Overhaul capabilities. Separate GetStackTrace into GetStackTrace and GetStackFrames. Use depth instead of jframeID to reference frames. Remove the now irrelevant GetCurrentFrame, GetCallerFrame and GetStackFrames. Remove frame arg from events. Remove GetObjectWithAnnotation since tests show bufferred approach more efficient. Add missing annotation_count to GetObjectsWithAnnotations Remove confusing parenthetical statement in GetObjectsWithAnnotations Replace jclass/jmethodID representation of method with simply jmethodID; Pass JvmtiEnv* as first arg of every event; remove JNIEnv* where inappropriate. Replace can_access_frames with can_access_local_variables; remove from purely stack access. Use can_get_synthetic_attribute; fix description. Clarify that zero length arrays must be deallocated. Clarify RelinquishCapabilities. Generalize JVMTI_ERROR_VM_DEAD to JVMTI_ERROR_WRONG_PHASE. Remove lingering indirect references to OBSOLETE_METHOD_ID. Allow DestroyRawMonitor during OnLoad. Added not monitor owner error return to DestroyRawMonitor. Clarify semantics of raw monitors. Change flags on GetThreadStatus. GetClassLoader return NULL for the bootstrap class loader. Add GetClassName issue. Define local variable signature. Disallow zero in annotations array of GetObjectsWithAnnotations. Remove over specification in GetObjectsWithAnnotations. Elide SetAllocationHooks. Elide SuspendAllThreads. Define the data type jvmtiEventCallbacks. Zero length allocations return NULL. Keep SetAllocationHooks in JVMDI, but remove from . Add JVMTI_THREAD_STATUS_FLAG_INTERRUPTED. Better wording, per review. First Alpha. Make jmethodID and jfieldID unique, jclass not used. Fix minor XSLT errors. Undo making jfieldID unique (jmethodID still is). Changes per June 11th Expert Group meeting -- Overhaul Heap functionality: single callback, remove GetHeapRoots, add reachable iterators, and rename "annotation" to "tag". NULL thread parameter on most functions is current thread. Add timers. Remove ForceExit. Add GetEnvironmentLocalStorage. Add verbose flag and event. Add AddToBootstrapClassLoaderSearch. Update ClassFileLoadHook. Clean up issues sections. Rename GetClassName back to GetClassSignature and fix description. Add generic signature to GetClassSignature, GetFieldSignature, GetMethodSignature, and GetLocalVariableTable. Elide EstimateCostOfCapabilities. Clarify that the system property functions operate on the VM view of system properties. Clarify Agent_OnLoad. Remove "const" from JNIEnv* in events. Add metadata accessors. Add start_depth to GetStackTrace. Move system properties to a new category. Add GetObjectSize. Remove "X" from command line flags. XML, HTML, and spell check corrections. Fix JVMTI_HEAP_ROOT_THREAD to be 6. Make each synopsis match the function name. Fix unclear wording. SetThreadLocalStorage and SetEnvironmentLocalStorage should allow value to be set to NULL. NotifyFramePop, GetFrameLocationm and all the local variable operations needed to have their wording about frames fixed. Grammar and clarity need to be fixed throughout. Capitalization and puntuation need to be consistent. Need micro version number and masks for accessing major, minor, and micro. The error code lists should indicate which must be returned by an implementation. The command line properties should be visible in the properties functions. Disallow popping from the current thread. Allow implementations to return opaque frame error when they cannot pop. The NativeMethodBind event should be sent during any phase. The DynamicCodeGenerated event should be sent during any phase. The following functions should be allowed to operate before VMInit: Set/GetEnvironmentLocalStorage GetMethodDeclaringClass GetClassSignature GetClassModifiers IsInterface IsArrayClass GetMethodName GetMethodModifiers GetMaxLocals GetArgumentsSize GetLineNumberTable GetMethodLocation IsMethodNative IsMethodSynthetic. Other changes (to XSL): Argument description should show asterisk after not before pointers. NotifyFramePop, GetFrameLocationm and all the local variable operations should hsve the NO_MORE_FRAMES error added. Not alive threads should have a different error return than invalid thread. VerboseOutput event was missing message parameter. Minor fix-ups. Technical Publications Department corrections. Allow thread and environment local storage to be set to NULL. Use new Agent_OnLoad rather than overloaded JVM_OnLoad. Add JNICALL to callbacks (XSL). Document JNICALL requirement for both events and callbacks (XSL). Restrict RedefineClasses to methods and attributes. Elide the VerboseOutput event. VMObjectAlloc: restrict when event is sent and remove method parameter. Finish loose ends from Tech Pubs edit. Change ClassFileLoadHook event to send the class instead of a boolean of redefine. XML fixes. Minor text clarifications and corrections. Remove GetExceptionHandlerTable and GetThrownExceptions from . Clarify that stack frames are JVM Spec frames. Split can_get_source_info into can_get_source_file_name, can_get_line_numbers, and can_get_source_debug_extension. PopFrame cannot have a native calling method. Removed incorrect statement in GetClassloaderClasses (see ). XML and text fixes. Move stack frame description into Stack Frame category. Allow NULL (means bootstrap loader) for GetClassloaderClasses. Add new heap reference kinds for references from classes. Add timer information struct and query functions. Add AvailableProcessors. Rename GetOtherThreadCpuTime to GetThreadCpuTime. Explicitly add JVMTI_ERROR_INVALID_THREAD and JVMTI_ERROR_THREAD_NOT_ALIVE to SetEventNotification mode. Add initial thread to the VM_INIT event. Remove platform assumptions from AddToBootstrapClassLoaderSearch. Grammar and clarity changes per review. More grammar and clarity changes per review. Add Agent_OnUnload. Change return type of Agent_OnUnload to void. Rename JVMTI_REFERENCE_ARRAY to JVMTI_REFERENCE_ARRAY_ELEMENT. Steal java.lang.Runtime.availableProcessors() wording for AvailableProcessors(). Guarantee that zero will never be an event ID. Remove some issues which are no longer issues. Per review, rename and more completely document the timer information functions. Non-spec visible change to XML controlled implementation: SetThreadLocalStorage must run in VM mode. Add GetErrorName. Add varargs warning to jvmtiExtensionEvent. Remove "const" on the jvmtiEnv* of jvmtiExtensionEvent. Remove unused can_get_exception_info capability. Pass jvmtiEnv* and JNIEnv* to the jvmtiStartFunction. Fix jvmtiExtensionFunctionInfo.func declared type. Extension function returns error code. Use new version numbering. Remove the ClassUnload event. Heap reference iterator callbacks return an enum that allows outgoing object references to be ignored. Allow JNIEnv as a param type to extension events/functions. Fix a typo. Remove all metadata functions: GetClassMetadata, GetFieldMetadata, and GetMethodMetadata. Mark the functions Allocate. Deallocate, RawMonitor*, SetEnvironmentLocalStorage, and GetEnvironmentLocalStorage as safe for use in heap callbacks and GC events. Add pass through opaque user data pointer to heap iterate functions and callbacks. In the CompiledMethodUnload event, send the code address. Add GarbageCollectionOccurred event. Add constant pool reference kind. Mark the functions CreateRawMonitor and DestroyRawMonitor as safe for use in heap callbacks and GC events. Clarify: VMDeath, GetCurrentThreadCpuTimerInfo, GetThreadCpuTimerInfo, IterateOverReachableObjects, IterateOverObjectsReachableFromObject, GetTime and JVMTI_ERROR_NULL_POINTER. Add missing errors to: GenerateEvents and AddToBootstrapClassLoaderSearch. Fix description of ClassFileLoadHook name parameter. In heap callbacks and GC/ObjectFree events, specify that only explicitly allowed functions can be called. Allow GetCurrentThreadCpuTimerInfo, GetCurrentThreadCpuTime, GetTimerInfo, and GetTime during callback. Allow calling SetTag/GetTag during the onload phase. SetEventNotificationMode, add: error attempted inappropriate thread level control. Remove jvmtiExceptionHandlerEntry. Fix handling of native methods on the stack -- location_ptr param of GetFrameLocation, remove JVMTI_ERROR_OPAQUE_FRAME from GetFrameLocation, jvmtiFrameInfo.location, and jlocation. Remove typo (from JVMPI) implying that the MonitorWaited event is sent on sleep. Clarifications and typos. Allow NULL user_data in heap iterators. Add GetThreadState, deprecate GetThreadStatus. INVALID_SLOT and TYPE_MISMATCH errors should be optional. Remove MonitorContendedExit. Added JNIEnv parameter to VMObjectAlloc. Clarified definition of class_tag and referrer_index parameters to heap callbacks. Document JAVA_TOOL_OPTIONS. Divide start phase into primordial and start. Add VMStart event Change phase associations of functions and events. Elide deprecated GetThreadStatus. Bump minor version, subtract 100 from micro version Document that timer nanosecond values are unsigned. Clarify text having to do with native methods. Fix typos. Remove elided deprecated GetThreadStatus. Require NotifyFramePop to act on suspended threads. Add capabilities (can_redefine_any_class and can_generate_all_class_hook_events) and an error () which allow some classes to be unmodifiable. Add JVMTI_ERROR_MUST_POSSESS_CAPABILITY to SetEventNotificationMode. Clarified CompiledMethodUnload so that it is clear the event may be posted after the class has been unloaded. Change the size parameter of VMObjectAlloc to jlong to match GetObjectSize. Added guideline for the use of the JNI FindClass function in event callback functions. Add GetAllStackTraces and GetThreadListStackTraces. ClassLoad and ClassPrepare events can be posted during start phase. Add JVMTI_ERROR_NATIVE_METHOD to GetLineNumberTable, GetLocalVariableTable, GetMaxLocals, GetArgumentsSize, GetMethodLocation, GetBytecodes. Return the timer kind in the timer information structure. Spec clarifications: JVMTI_THREAD_STATE_IN_NATIVE might not include JNI or . ForceGarbageCollection does not run finalizers. The context of the specification is the Java platform. Warn about early instrumentation. Refinements to the above clarifications and Clarify that an error returned by Agent_OnLoad terminates the VM. Array class creation does not generate a class load event. Align thread state hierarchy more closely with java.lang.Thread.State. Clarify the documentation of thread state. Remove GarbageCollectionOccurred event -- can be done by agent. Define "command-line option". Describe the intended use of bytecode instrumentation. Fix description of extension event first parameter. Clarification and typos. Remove DataDumpRequest event. Clarify RawMonitorWait with zero timeout. Clarify thread state after RunAgentThread. Clean-up: fix bad/old links, etc. Clarifications including: All character strings are modified UTF-8. Agent thread visibiity. Meaning of obsolete method version. Thread invoking heap callbacks, Bump major.minor version numbers to "1.0". Clarify interaction between ForceGarbageCollection and ObjectFree. Restrict AddToBootstrapClassLoaderSearch and SetSystemProperty to the OnLoad phase only. Fix typo in SetTag. Fix trademarks. Add missing parameter in example GetThreadState usage. Copyright updates. Add missing function table layout. Add missing description of C++ member function format of functions. Clarify that name in CFLH can be NULL. Released as part of J2SE 5.0. Bump major.minor version numbers to "1.1". Add ForceEarlyReturn* functions. Add GetOwnedMonitorStackDepthInfo function. Add GetCurrentThread function. Add "since" version marker. Add AddToSystemClassLoaderSearch. Allow AddToBootstrapClassLoaderSearch be used in live phase. Fix historic rubbish in the descriptions of the heap_object_callback parameter of IterateOverHeap and IterateOverInstancesOfClass functions; disallow NULL for this parameter. Clarify, correct and make consistent: wording about current thread, opaque frames and insufficient number of frames in PopFrame. Consistently use "current frame" rather than "topmost". Clarify the JVMTI_ERROR_TYPE_MISMATCH errors in GetLocal* and SetLocal* by making them compatible with those in ForceEarlyReturn*. Many other clarifications and wording clean ups. Add GetConstantPool. Switch references to the first edition of the VM Spec, to the seconds edition. Clarify minor/major version order in GetConstantPool. Add SetNativeMethodPrefix and SetNativeMethodPrefixes. Reassign GetOwnedMonitorStackDepthInfo to position 153. Break out Class Loader Search in its own documentation category. Deal with overly long lines in XML source. Allow agents be started in the live phase. Added paragraph about deploying agents. Add specification description to SetNativeMethodPrefix(es). Better define the conditions on GetConstantPool. Break out the GetClassVersionNumber function from GetConstantPool. Clean-up the references to the VM Spec. Allow SetNativeMethodPrefix(es) in any phase. Add clarifications about the impact of redefinition on GetConstantPool. Various clarifications to SetNativeMethodPrefix(es). Add missing performance warning to the method entry event. Remove internal JVMDI support. Add . Revamp the bytecode instrumentation documentation. Change to no longer require the can_redefine_classes capability. Clarifications for retransformation. Clarifications for retransformation, per review. Lock "retransformation (in)capable" at class load enable time. Add new heap functionity which supports reporting primitive values, allows setting the referrer tag, and has more powerful filtering: FollowReferences, IterateThroughHeap, and their associated callbacks, structs, enums, and constants. Clarification. FollowReferences, IterateThroughHeap: Put callbacks in a struct; Add missing error codes; reduce bits in the visit control flags. More on new heap functionity: spec clean-up per review. More on new heap functionity: Rename old heap section to Heap (1.0). Fix typos. Make referrer info structure a union. In new heap functions: Add missing superclass reference kind. Use a single scheme for computing field indexes. Remove outdated references to struct based referrer info. Don't callback during FollowReferences on frivolous java.lang.Object superclass. In string primitive callback, length now Unicode length. In array and string primitive callbacks, value now "const". Note possible compiler impacts on setting JNI function table. GetClassVersionNumbers() and GetConstantPool() should return error on array or primitive class. Grammar fixes. Add IsModifiableClass query. Add referrer_class_tag parameter to jvmtiHeapReferenceCallback. Doc fixes: update can_redefine_any_class to include retransform. Clarify that exception events cover all Throwables. In GetStackTrace, no test is done for start_depth too big if start_depth is zero, Clarify fields reported in Primitive Field Callback -- static vs instance. Repair confusing names of heap types, including callback names. Require consistent usage of stack depth in the face of thread launch methods. Note incompatibility of memory management with other systems. Fix typos and missing renames. Clarify that jmethodIDs and jfieldIDs can be saved. Clarify that Iterate Over Instances Of Class includes subclasses. Better phrasing. Match the referrer_index for static fields in Object Reference Callback with the Reference Implementation (and all other known implementations); that is, make it match the definition for instance fields. In GetThreadListStackTraces, add JVMTI_ERROR_INVALID_THREAD to cover an invalid thread in the list; and specify that not started threads return empty stacks. Typo. Typo. Remove restrictions on AddToBootstrapClassLoaderSearch and AddToSystemClassLoaderSearch. Changed spec to return -1 for monitor stack depth for the implementation which can not determine stack depth. Corrections for readability and accuracy courtesy of Alan Pratt of IBM. List the object relationships reported in FollowReferences. Clarify the object relationships reported in FollowReferences. Clarify DisposeEnvironment; add warning. Fix typos in SetLocalXXX "retrieve" => "set". Clarify that native method prefixes must remain set while used. Clarify that exactly one Agent_OnXXX is called per agent. Clarify that library loading is independent from start-up. Remove ambiguous reference to Agent_OnLoad in the Agent_OnUnload spec. Clarify the interaction between functions and exceptions. Clarify and give examples of field indices. Remove confusing "That is" sentence from MonitorWait and MonitorWaited events. Update links to point to Java 6. Add ResourceExhaustedEvent. Fixed the "HTTP" and "Missing Anchor" errors reported by the LinkCheck tool. Added support for statically linked agents.