jvmtiExport.cpp revision 12290:8953c0318163
1/*
2 * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "classfile/systemDictionary.hpp"
27#include "code/nmethod.hpp"
28#include "code/pcDesc.hpp"
29#include "code/scopeDesc.hpp"
30#include "interpreter/interpreter.hpp"
31#include "jvmtifiles/jvmtiEnv.hpp"
32#include "logging/log.hpp"
33#include "logging/logStream.hpp"
34#include "memory/resourceArea.hpp"
35#include "oops/objArrayKlass.hpp"
36#include "oops/objArrayOop.hpp"
37#include "oops/oop.inline.hpp"
38#include "prims/jvmtiCodeBlobEvents.hpp"
39#include "prims/jvmtiEventController.hpp"
40#include "prims/jvmtiEventController.inline.hpp"
41#include "prims/jvmtiExport.hpp"
42#include "prims/jvmtiImpl.hpp"
43#include "prims/jvmtiManageCapabilities.hpp"
44#include "prims/jvmtiRawMonitor.hpp"
45#include "prims/jvmtiRedefineClasses.hpp"
46#include "prims/jvmtiTagMap.hpp"
47#include "prims/jvmtiThreadState.inline.hpp"
48#include "runtime/arguments.hpp"
49#include "runtime/handles.hpp"
50#include "runtime/interfaceSupport.hpp"
51#include "runtime/javaCalls.hpp"
52#include "runtime/objectMonitor.hpp"
53#include "runtime/objectMonitor.inline.hpp"
54#include "runtime/os.inline.hpp"
55#include "runtime/thread.inline.hpp"
56#include "runtime/vframe.hpp"
57#include "services/attachListener.hpp"
58#include "services/serviceUtil.hpp"
59#include "utilities/macros.hpp"
60#if INCLUDE_ALL_GCS
61#include "gc/parallel/psMarkSweep.hpp"
62#endif // INCLUDE_ALL_GCS
63
64#ifdef JVMTI_TRACE
65#define EVT_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_SENT) != 0) { SafeResourceMark rm; log_trace(jvmti) out; }
66#define EVT_TRIG_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_TRIGGER) != 0) { SafeResourceMark rm; log_trace(jvmti) out; }
67#else
68#define EVT_TRIG_TRACE(evt,out)
69#define EVT_TRACE(evt,out)
70#endif
71
72///////////////////////////////////////////////////////////////
73//
74// JvmtiEventTransition
75//
76// TO DO --
77//  more handle purging
78
79// Use this for JavaThreads and state is  _thread_in_vm.
80class JvmtiJavaThreadEventTransition : StackObj {
81private:
82  ResourceMark _rm;
83  ThreadToNativeFromVM _transition;
84  HandleMark _hm;
85
86public:
87  JvmtiJavaThreadEventTransition(JavaThread *thread) :
88    _rm(),
89    _transition(thread),
90    _hm(thread)  {};
91};
92
93// For JavaThreads which are not in _thread_in_vm state
94// and other system threads use this.
95class JvmtiThreadEventTransition : StackObj {
96private:
97  ResourceMark _rm;
98  HandleMark _hm;
99  JavaThreadState _saved_state;
100  JavaThread *_jthread;
101
102public:
103  JvmtiThreadEventTransition(Thread *thread) : _rm(), _hm() {
104    if (thread->is_Java_thread()) {
105       _jthread = (JavaThread *)thread;
106       _saved_state = _jthread->thread_state();
107       if (_saved_state == _thread_in_Java) {
108         ThreadStateTransition::transition_from_java(_jthread, _thread_in_native);
109       } else {
110         ThreadStateTransition::transition(_jthread, _saved_state, _thread_in_native);
111       }
112    } else {
113      _jthread = NULL;
114    }
115  }
116
117  ~JvmtiThreadEventTransition() {
118    if (_jthread != NULL)
119      ThreadStateTransition::transition_from_native(_jthread, _saved_state);
120  }
121};
122
123
124///////////////////////////////////////////////////////////////
125//
126// JvmtiEventMark
127//
128
129class JvmtiEventMark : public StackObj {
130private:
131  JavaThread *_thread;
132  JNIEnv* _jni_env;
133  bool _exception_detected;
134  bool _exception_caught;
135#if 0
136  JNIHandleBlock* _hblock;
137#endif
138
139public:
140  JvmtiEventMark(JavaThread *thread) :  _thread(thread),
141                                         _jni_env(thread->jni_environment()) {
142#if 0
143    _hblock = thread->active_handles();
144    _hblock->clear_thoroughly(); // so we can be safe
145#else
146    // we want to use the code above - but that needs the JNIHandle changes - later...
147    // for now, steal JNI push local frame code
148    JvmtiThreadState *state = thread->jvmti_thread_state();
149    // we are before an event.
150    // Save current jvmti thread exception state.
151    if (state != NULL) {
152      _exception_detected = state->is_exception_detected();
153      _exception_caught = state->is_exception_caught();
154    } else {
155      _exception_detected = false;
156      _exception_caught = false;
157    }
158
159    JNIHandleBlock* old_handles = thread->active_handles();
160    JNIHandleBlock* new_handles = JNIHandleBlock::allocate_block(thread);
161    assert(new_handles != NULL, "should not be NULL");
162    new_handles->set_pop_frame_link(old_handles);
163    thread->set_active_handles(new_handles);
164#endif
165    assert(thread == JavaThread::current(), "thread must be current!");
166    thread->frame_anchor()->make_walkable(thread);
167  };
168
169  ~JvmtiEventMark() {
170#if 0
171    _hblock->clear(); // for consistency with future correct behavior
172#else
173    // we want to use the code above - but that needs the JNIHandle changes - later...
174    // for now, steal JNI pop local frame code
175    JNIHandleBlock* old_handles = _thread->active_handles();
176    JNIHandleBlock* new_handles = old_handles->pop_frame_link();
177    assert(new_handles != NULL, "should not be NULL");
178    _thread->set_active_handles(new_handles);
179    // Note that we set the pop_frame_link to NULL explicitly, otherwise
180    // the release_block call will release the blocks.
181    old_handles->set_pop_frame_link(NULL);
182    JNIHandleBlock::release_block(old_handles, _thread); // may block
183#endif
184
185    JvmtiThreadState* state = _thread->jvmti_thread_state();
186    // we are continuing after an event.
187    if (state != NULL) {
188      // Restore the jvmti thread exception state.
189      if (_exception_detected) {
190        state->set_exception_detected();
191      }
192      if (_exception_caught) {
193        state->set_exception_caught();
194      }
195    }
196  }
197
198#if 0
199  jobject to_jobject(oop obj) { return obj == NULL? NULL : _hblock->allocate_handle_fast(obj); }
200#else
201  // we want to use the code above - but that needs the JNIHandle changes - later...
202  // for now, use regular make_local
203  jobject to_jobject(oop obj) { return JNIHandles::make_local(_thread,obj); }
204#endif
205
206  jclass to_jclass(Klass* klass) { return (klass == NULL ? NULL : (jclass)to_jobject(klass->java_mirror())); }
207
208  jmethodID to_jmethodID(methodHandle method) { return method->jmethod_id(); }
209
210  JNIEnv* jni_env() { return _jni_env; }
211};
212
213class JvmtiThreadEventMark : public JvmtiEventMark {
214private:
215  jthread _jt;
216
217public:
218  JvmtiThreadEventMark(JavaThread *thread) :
219    JvmtiEventMark(thread) {
220    _jt = (jthread)(to_jobject(thread->threadObj()));
221  };
222 jthread jni_thread() { return _jt; }
223};
224
225class JvmtiClassEventMark : public JvmtiThreadEventMark {
226private:
227  jclass _jc;
228
229public:
230  JvmtiClassEventMark(JavaThread *thread, Klass* klass) :
231    JvmtiThreadEventMark(thread) {
232    _jc = to_jclass(klass);
233  };
234  jclass jni_class() { return _jc; }
235};
236
237class JvmtiMethodEventMark : public JvmtiThreadEventMark {
238private:
239  jmethodID _mid;
240
241public:
242  JvmtiMethodEventMark(JavaThread *thread, methodHandle method) :
243    JvmtiThreadEventMark(thread),
244    _mid(to_jmethodID(method)) {};
245  jmethodID jni_methodID() { return _mid; }
246};
247
248class JvmtiLocationEventMark : public JvmtiMethodEventMark {
249private:
250  jlocation _loc;
251
252public:
253  JvmtiLocationEventMark(JavaThread *thread, methodHandle method, address location) :
254    JvmtiMethodEventMark(thread, method),
255    _loc(location - method->code_base()) {};
256  jlocation location() { return _loc; }
257};
258
259class JvmtiExceptionEventMark : public JvmtiLocationEventMark {
260private:
261  jobject _exc;
262
263public:
264  JvmtiExceptionEventMark(JavaThread *thread, methodHandle method, address location, Handle exception) :
265    JvmtiLocationEventMark(thread, method, location),
266    _exc(to_jobject(exception())) {};
267  jobject exception() { return _exc; }
268};
269
270class JvmtiClassFileLoadEventMark : public JvmtiThreadEventMark {
271private:
272  const char *_class_name;
273  jobject _jloader;
274  jobject _protection_domain;
275  jclass  _class_being_redefined;
276
277public:
278  JvmtiClassFileLoadEventMark(JavaThread *thread, Symbol* name,
279     Handle class_loader, Handle prot_domain, KlassHandle *class_being_redefined) : JvmtiThreadEventMark(thread) {
280      _class_name = name != NULL? name->as_utf8() : NULL;
281      _jloader = (jobject)to_jobject(class_loader());
282      _protection_domain = (jobject)to_jobject(prot_domain());
283      if (class_being_redefined == NULL) {
284        _class_being_redefined = NULL;
285      } else {
286        _class_being_redefined = (jclass)to_jclass((*class_being_redefined)());
287      }
288  };
289  const char *class_name() {
290    return _class_name;
291  }
292  jobject jloader() {
293    return _jloader;
294  }
295  jobject protection_domain() {
296    return _protection_domain;
297  }
298  jclass class_being_redefined() {
299    return _class_being_redefined;
300  }
301};
302
303//////////////////////////////////////////////////////////////////////////////
304
305int               JvmtiExport::_field_access_count                        = 0;
306int               JvmtiExport::_field_modification_count                  = 0;
307
308bool              JvmtiExport::_can_access_local_variables                = false;
309bool              JvmtiExport::_can_hotswap_or_post_breakpoint            = false;
310bool              JvmtiExport::_can_modify_any_class                      = false;
311bool              JvmtiExport::_can_walk_any_space                        = false;
312
313bool              JvmtiExport::_has_redefined_a_class                     = false;
314bool              JvmtiExport::_all_dependencies_are_recorded             = false;
315
316//
317// field access management
318//
319
320// interpreter generator needs the address of the counter
321address JvmtiExport::get_field_access_count_addr() {
322  // We don't grab a lock because we don't want to
323  // serialize field access between all threads. This means that a
324  // thread on another processor can see the wrong count value and
325  // may either miss making a needed call into post_field_access()
326  // or will make an unneeded call into post_field_access(). We pay
327  // this price to avoid slowing down the VM when we aren't watching
328  // field accesses.
329  // Other access/mutation safe by virtue of being in VM state.
330  return (address)(&_field_access_count);
331}
332
333//
334// field modification management
335//
336
337// interpreter generator needs the address of the counter
338address JvmtiExport::get_field_modification_count_addr() {
339  // We don't grab a lock because we don't
340  // want to serialize field modification between all threads. This
341  // means that a thread on another processor can see the wrong
342  // count value and may either miss making a needed call into
343  // post_field_modification() or will make an unneeded call into
344  // post_field_modification(). We pay this price to avoid slowing
345  // down the VM when we aren't watching field modifications.
346  // Other access/mutation safe by virtue of being in VM state.
347  return (address)(&_field_modification_count);
348}
349
350
351///////////////////////////////////////////////////////////////
352// Functions needed by java.lang.instrument for starting up javaagent.
353///////////////////////////////////////////////////////////////
354
355jint
356JvmtiExport::get_jvmti_interface(JavaVM *jvm, void **penv, jint version) {
357  // The JVMTI_VERSION_INTERFACE_JVMTI part of the version number
358  // has already been validated in JNI GetEnv().
359  int major, minor, micro;
360
361  // micro version doesn't matter here (yet?)
362  decode_version_values(version, &major, &minor, &micro);
363  switch (major) {
364    case 1:
365      switch (minor) {
366        case 0:  // version 1.0.<micro> is recognized
367        case 1:  // version 1.1.<micro> is recognized
368        case 2:  // version 1.2.<micro> is recognized
369          break;
370
371        default:
372          return JNI_EVERSION;  // unsupported minor version number
373      }
374      break;
375    case 9:
376      switch (minor) {
377        case 0:  // version 9.0.<micro> is recognized
378          break;
379        default:
380          return JNI_EVERSION;  // unsupported minor version number
381      }
382      break;
383    default:
384      return JNI_EVERSION;  // unsupported major version number
385  }
386
387  if (JvmtiEnv::get_phase() == JVMTI_PHASE_LIVE) {
388    JavaThread* current_thread = JavaThread::current();
389    // transition code: native to VM
390    ThreadInVMfromNative __tiv(current_thread);
391    VM_ENTRY_BASE(jvmtiEnv*, JvmtiExport::get_jvmti_interface, current_thread)
392    debug_only(VMNativeEntryWrapper __vew;)
393
394    JvmtiEnv *jvmti_env = JvmtiEnv::create_a_jvmti(version);
395    *penv = jvmti_env->jvmti_external();  // actual type is jvmtiEnv* -- not to be confused with JvmtiEnv*
396    return JNI_OK;
397
398  } else if (JvmtiEnv::get_phase() == JVMTI_PHASE_ONLOAD) {
399    // not live, no thread to transition
400    JvmtiEnv *jvmti_env = JvmtiEnv::create_a_jvmti(version);
401    *penv = jvmti_env->jvmti_external();  // actual type is jvmtiEnv* -- not to be confused with JvmtiEnv*
402    return JNI_OK;
403
404  } else {
405    // Called at the wrong time
406    *penv = NULL;
407    return JNI_EDETACHED;
408  }
409}
410
411void
412JvmtiExport::add_default_read_edges(Handle h_module, TRAPS) {
413  if (!Universe::is_module_initialized()) {
414    return; // extra safety
415  }
416  assert(!h_module.is_null(), "module should always be set");
417
418  // Invoke the transformedByAgent method
419  JavaValue result(T_VOID);
420  JavaCalls::call_static(&result,
421                         SystemDictionary::module_Modules_klass(),
422                         vmSymbols::transformedByAgent_name(),
423                         vmSymbols::transformedByAgent_signature(),
424                         h_module,
425                         THREAD);
426
427  if (HAS_PENDING_EXCEPTION) {
428    LogTarget(Trace, jvmti) log;
429    LogStreamCHeap log_stream(log);
430    java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
431    log_stream.cr();
432    CLEAR_PENDING_EXCEPTION;
433    return;
434  }
435}
436
437jvmtiError
438JvmtiExport::add_module_reads(Handle module, Handle to_module, TRAPS) {
439  if (!Universe::is_module_initialized()) {
440    return JVMTI_ERROR_NONE; // extra safety
441  }
442  assert(!module.is_null(), "module should always be set");
443  assert(!to_module.is_null(), "to_module should always be set");
444
445  // Invoke the addReads method
446  JavaValue result(T_VOID);
447  JavaCalls::call_static(&result,
448                         SystemDictionary::module_Modules_klass(),
449                         vmSymbols::addReads_name(),
450                         vmSymbols::addReads_signature(),
451                         module,
452                         to_module,
453                         THREAD);
454
455  if (HAS_PENDING_EXCEPTION) {
456    LogTarget(Trace, jvmti) log;
457    LogStreamCHeap log_stream(log);
458    java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
459    log_stream.cr();
460    CLEAR_PENDING_EXCEPTION;
461    return JVMTI_ERROR_INTERNAL;
462  }
463  return JVMTI_ERROR_NONE;
464}
465
466jvmtiError
467JvmtiExport::add_module_exports(Handle module, Handle pkg_name, Handle to_module, TRAPS) {
468  if (!Universe::is_module_initialized()) {
469    return JVMTI_ERROR_NONE; // extra safety
470  }
471  assert(!module.is_null(), "module should always be set");
472  assert(!to_module.is_null(), "to_module should always be set");
473  assert(!pkg_name.is_null(), "pkg_name should always be set");
474
475  // Invoke the addExports method
476  JavaValue result(T_VOID);
477  JavaCalls::call_static(&result,
478                         SystemDictionary::module_Modules_klass(),
479                         vmSymbols::addExports_name(),
480                         vmSymbols::addExports_signature(),
481                         module,
482                         pkg_name,
483                         to_module,
484                         THREAD);
485
486  if (HAS_PENDING_EXCEPTION) {
487    Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
488    LogTarget(Trace, jvmti) log;
489    LogStreamCHeap log_stream(log);
490    java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
491    log_stream.cr();
492    CLEAR_PENDING_EXCEPTION;
493    if (ex_name == vmSymbols::java_lang_IllegalArgumentException()) {
494      return JVMTI_ERROR_ILLEGAL_ARGUMENT;
495    }
496    return JVMTI_ERROR_INTERNAL;
497  }
498  return JVMTI_ERROR_NONE;
499}
500
501jvmtiError
502JvmtiExport::add_module_opens(Handle module, Handle pkg_name, Handle to_module, TRAPS) {
503  if (!Universe::is_module_initialized()) {
504    return JVMTI_ERROR_NONE; // extra safety
505  }
506  assert(!module.is_null(), "module should always be set");
507  assert(!to_module.is_null(), "to_module should always be set");
508  assert(!pkg_name.is_null(), "pkg_name should always be set");
509
510  // Invoke the addOpens method
511  JavaValue result(T_VOID);
512  JavaCalls::call_static(&result,
513                         SystemDictionary::module_Modules_klass(),
514                         vmSymbols::addOpens_name(),
515                         vmSymbols::addExports_signature(),
516                         module,
517                         pkg_name,
518                         to_module,
519                         THREAD);
520
521  if (HAS_PENDING_EXCEPTION) {
522    Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
523    LogTarget(Trace, jvmti) log;
524    LogStreamCHeap log_stream(log);
525    java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
526    log_stream.cr();
527    CLEAR_PENDING_EXCEPTION;
528    if (ex_name == vmSymbols::java_lang_IllegalArgumentException()) {
529      return JVMTI_ERROR_ILLEGAL_ARGUMENT;
530    }
531    return JVMTI_ERROR_INTERNAL;
532  }
533  return JVMTI_ERROR_NONE;
534}
535
536jvmtiError
537JvmtiExport::add_module_uses(Handle module, Handle service, TRAPS) {
538  if (!Universe::is_module_initialized()) {
539    return JVMTI_ERROR_NONE; // extra safety
540  }
541  assert(!module.is_null(), "module should always be set");
542  assert(!service.is_null(), "service should always be set");
543
544  // Invoke the addUses method
545  JavaValue result(T_VOID);
546  JavaCalls::call_static(&result,
547                         SystemDictionary::module_Modules_klass(),
548                         vmSymbols::addUses_name(),
549                         vmSymbols::addUses_signature(),
550                         module,
551                         service,
552                         THREAD);
553
554  if (HAS_PENDING_EXCEPTION) {
555    LogTarget(Trace, jvmti) log;
556    LogStreamCHeap log_stream(log);
557    java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
558    log_stream.cr();
559    CLEAR_PENDING_EXCEPTION;
560    return JVMTI_ERROR_INTERNAL;
561  }
562  return JVMTI_ERROR_NONE;
563}
564
565jvmtiError
566JvmtiExport::add_module_provides(Handle module, Handle service, Handle impl_class, TRAPS) {
567  if (!Universe::is_module_initialized()) {
568    return JVMTI_ERROR_NONE; // extra safety
569  }
570  assert(!module.is_null(), "module should always be set");
571  assert(!service.is_null(), "service should always be set");
572  assert(!impl_class.is_null(), "impl_class should always be set");
573
574  // Invoke the addProvides method
575  JavaValue result(T_VOID);
576  JavaCalls::call_static(&result,
577                         SystemDictionary::module_Modules_klass(),
578                         vmSymbols::addProvides_name(),
579                         vmSymbols::addProvides_signature(),
580                         module,
581                         service,
582                         impl_class,
583                         THREAD);
584
585  if (HAS_PENDING_EXCEPTION) {
586    LogTarget(Trace, jvmti) log;
587    LogStreamCHeap log_stream(log);
588    java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
589    log_stream.cr();
590    CLEAR_PENDING_EXCEPTION;
591    return JVMTI_ERROR_INTERNAL;
592  }
593  return JVMTI_ERROR_NONE;
594}
595
596void
597JvmtiExport::decode_version_values(jint version, int * major, int * minor,
598                                   int * micro) {
599  *major = (version & JVMTI_VERSION_MASK_MAJOR) >> JVMTI_VERSION_SHIFT_MAJOR;
600  *minor = (version & JVMTI_VERSION_MASK_MINOR) >> JVMTI_VERSION_SHIFT_MINOR;
601  *micro = (version & JVMTI_VERSION_MASK_MICRO) >> JVMTI_VERSION_SHIFT_MICRO;
602}
603
604void JvmtiExport::enter_primordial_phase() {
605  JvmtiEnvBase::set_phase(JVMTI_PHASE_PRIMORDIAL);
606}
607
608void JvmtiExport::enter_early_start_phase() {
609  JvmtiManageCapabilities::recompute_always_capabilities();
610  set_early_vmstart_recorded(true);
611}
612
613void JvmtiExport::enter_start_phase() {
614  JvmtiManageCapabilities::recompute_always_capabilities();
615  JvmtiEnvBase::set_phase(JVMTI_PHASE_START);
616}
617
618void JvmtiExport::enter_onload_phase() {
619  JvmtiEnvBase::set_phase(JVMTI_PHASE_ONLOAD);
620}
621
622void JvmtiExport::enter_live_phase() {
623  JvmtiEnvBase::set_phase(JVMTI_PHASE_LIVE);
624}
625
626//
627// JVMTI events that the VM posts to the debugger and also startup agent
628// and call the agent's premain() for java.lang.instrument.
629//
630
631void JvmtiExport::post_early_vm_start() {
632  EVT_TRIG_TRACE(JVMTI_EVENT_VM_START, ("Trg Early VM start event triggered" ));
633
634  // can now enable some events
635  JvmtiEventController::vm_start();
636
637  JvmtiEnvIterator it;
638  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
639    // Only early vmstart envs post early VMStart event
640    if (env->early_vmstart_env() && env->is_enabled(JVMTI_EVENT_VM_START)) {
641      EVT_TRACE(JVMTI_EVENT_VM_START, ("Evt Early VM start event sent" ));
642      JavaThread *thread  = JavaThread::current();
643      JvmtiThreadEventMark jem(thread);
644      JvmtiJavaThreadEventTransition jet(thread);
645      jvmtiEventVMStart callback = env->callbacks()->VMStart;
646      if (callback != NULL) {
647        (*callback)(env->jvmti_external(), jem.jni_env());
648      }
649    }
650  }
651}
652
653void JvmtiExport::post_vm_start() {
654  EVT_TRIG_TRACE(JVMTI_EVENT_VM_START, ("Trg VM start event triggered" ));
655
656  // can now enable some events
657  JvmtiEventController::vm_start();
658
659  JvmtiEnvIterator it;
660  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
661    // Early vmstart envs do not post normal VMStart event
662    if (!env->early_vmstart_env() && env->is_enabled(JVMTI_EVENT_VM_START)) {
663      EVT_TRACE(JVMTI_EVENT_VM_START, ("Evt VM start event sent" ));
664
665      JavaThread *thread  = JavaThread::current();
666      JvmtiThreadEventMark jem(thread);
667      JvmtiJavaThreadEventTransition jet(thread);
668      jvmtiEventVMStart callback = env->callbacks()->VMStart;
669      if (callback != NULL) {
670        (*callback)(env->jvmti_external(), jem.jni_env());
671      }
672    }
673  }
674}
675
676
677void JvmtiExport::post_vm_initialized() {
678  EVT_TRIG_TRACE(JVMTI_EVENT_VM_INIT, ("Trg VM init event triggered" ));
679
680  // can now enable events
681  JvmtiEventController::vm_init();
682
683  JvmtiEnvIterator it;
684  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
685    if (env->is_enabled(JVMTI_EVENT_VM_INIT)) {
686      EVT_TRACE(JVMTI_EVENT_VM_INIT, ("Evt VM init event sent" ));
687
688      JavaThread *thread  = JavaThread::current();
689      JvmtiThreadEventMark jem(thread);
690      JvmtiJavaThreadEventTransition jet(thread);
691      jvmtiEventVMInit callback = env->callbacks()->VMInit;
692      if (callback != NULL) {
693        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
694      }
695    }
696  }
697}
698
699
700void JvmtiExport::post_vm_death() {
701  EVT_TRIG_TRACE(JVMTI_EVENT_VM_DEATH, ("Trg VM death event triggered" ));
702
703  JvmtiEnvIterator it;
704  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
705    if (env->is_enabled(JVMTI_EVENT_VM_DEATH)) {
706      EVT_TRACE(JVMTI_EVENT_VM_DEATH, ("Evt VM death event sent" ));
707
708      JavaThread *thread  = JavaThread::current();
709      JvmtiEventMark jem(thread);
710      JvmtiJavaThreadEventTransition jet(thread);
711      jvmtiEventVMDeath callback = env->callbacks()->VMDeath;
712      if (callback != NULL) {
713        (*callback)(env->jvmti_external(), jem.jni_env());
714      }
715    }
716  }
717
718  JvmtiEnvBase::set_phase(JVMTI_PHASE_DEAD);
719  JvmtiEventController::vm_death();
720}
721
722char**
723JvmtiExport::get_all_native_method_prefixes(int* count_ptr) {
724  // Have to grab JVMTI thread state lock to be sure environment doesn't
725  // go away while we iterate them.  No locks during VM bring-up.
726  if (Threads::number_of_threads() == 0 || SafepointSynchronize::is_at_safepoint()) {
727    return JvmtiEnvBase::get_all_native_method_prefixes(count_ptr);
728  } else {
729    MutexLocker mu(JvmtiThreadState_lock);
730    return JvmtiEnvBase::get_all_native_method_prefixes(count_ptr);
731  }
732}
733
734class JvmtiClassFileLoadHookPoster : public StackObj {
735 private:
736  Symbol*            _h_name;
737  Handle               _class_loader;
738  Handle               _h_protection_domain;
739  unsigned char **     _data_ptr;
740  unsigned char **     _end_ptr;
741  JavaThread *         _thread;
742  jint                 _curr_len;
743  unsigned char *      _curr_data;
744  JvmtiEnv *           _curr_env;
745  JvmtiCachedClassFileData ** _cached_class_file_ptr;
746  JvmtiThreadState *   _state;
747  KlassHandle *        _h_class_being_redefined;
748  JvmtiClassLoadKind   _load_kind;
749
750 public:
751  inline JvmtiClassFileLoadHookPoster(Symbol* h_name, Handle class_loader,
752                                      Handle h_protection_domain,
753                                      unsigned char **data_ptr, unsigned char **end_ptr,
754                                      JvmtiCachedClassFileData **cache_ptr) {
755    _h_name = h_name;
756    _class_loader = class_loader;
757    _h_protection_domain = h_protection_domain;
758    _data_ptr = data_ptr;
759    _end_ptr = end_ptr;
760    _thread = JavaThread::current();
761    _curr_len = *end_ptr - *data_ptr;
762    _curr_data = *data_ptr;
763    _curr_env = NULL;
764    _cached_class_file_ptr = cache_ptr;
765
766    _state = _thread->jvmti_thread_state();
767    if (_state != NULL) {
768      _h_class_being_redefined = _state->get_class_being_redefined();
769      _load_kind = _state->get_class_load_kind();
770      Klass* klass = (_h_class_being_redefined == NULL) ? NULL : (*_h_class_being_redefined)();
771      if (_load_kind != jvmti_class_load_kind_load && klass != NULL) {
772        ModuleEntry* module_entry = InstanceKlass::cast(klass)->module();
773        assert(module_entry != NULL, "module_entry should always be set");
774        if (module_entry->is_named() &&
775            module_entry->module() != NULL &&
776            !module_entry->has_default_read_edges()) {
777          if (!module_entry->set_has_default_read_edges()) {
778            // We won a potential race.
779            // Add read edges to the unnamed modules of the bootstrap and app class loaders
780            Handle class_module(_thread, JNIHandles::resolve(module_entry->module())); // Obtain j.l.r.Module
781            JvmtiExport::add_default_read_edges(class_module, _thread);
782          }
783        }
784      }
785      // Clear class_being_redefined flag here. The action
786      // from agent handler could generate a new class file load
787      // hook event and if it is not cleared the new event generated
788      // from regular class file load could have this stale redefined
789      // class handle info.
790      _state->clear_class_being_redefined();
791    } else {
792      // redefine and retransform will always set the thread state
793      _h_class_being_redefined = (KlassHandle *) NULL;
794      _load_kind = jvmti_class_load_kind_load;
795    }
796  }
797
798  void post() {
799    post_all_envs();
800    copy_modified_data();
801  }
802
803 private:
804  void post_all_envs() {
805    if (_load_kind != jvmti_class_load_kind_retransform) {
806      // for class load and redefine,
807      // call the non-retransformable agents
808      JvmtiEnvIterator it;
809      for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
810        if (!env->is_retransformable() && env->is_enabled(JVMTI_EVENT_CLASS_FILE_LOAD_HOOK)) {
811          // non-retransformable agents cannot retransform back,
812          // so no need to cache the original class file bytes
813          post_to_env(env, false);
814        }
815      }
816    }
817    JvmtiEnvIterator it;
818    for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
819      // retransformable agents get all events
820      if (env->is_retransformable() && env->is_enabled(JVMTI_EVENT_CLASS_FILE_LOAD_HOOK)) {
821        // retransformable agents need to cache the original class file
822        // bytes if changes are made via the ClassFileLoadHook
823        post_to_env(env, true);
824      }
825    }
826  }
827
828  void post_to_env(JvmtiEnv* env, bool caching_needed) {
829    if (env->phase() == JVMTI_PHASE_PRIMORDIAL && !env->early_class_hook_env()) {
830      return;
831    }
832    unsigned char *new_data = NULL;
833    jint new_len = 0;
834    JvmtiClassFileLoadEventMark jem(_thread, _h_name, _class_loader,
835                                    _h_protection_domain,
836                                    _h_class_being_redefined);
837    JvmtiJavaThreadEventTransition jet(_thread);
838    jvmtiEventClassFileLoadHook callback = env->callbacks()->ClassFileLoadHook;
839    if (callback != NULL) {
840      (*callback)(env->jvmti_external(), jem.jni_env(),
841                  jem.class_being_redefined(),
842                  jem.jloader(), jem.class_name(),
843                  jem.protection_domain(),
844                  _curr_len, _curr_data,
845                  &new_len, &new_data);
846    }
847    if (new_data != NULL) {
848      // this agent has modified class data.
849      if (caching_needed && *_cached_class_file_ptr == NULL) {
850        // data has been changed by the new retransformable agent
851        // and it hasn't already been cached, cache it
852        JvmtiCachedClassFileData *p;
853        p = (JvmtiCachedClassFileData *)os::malloc(
854          offset_of(JvmtiCachedClassFileData, data) + _curr_len, mtInternal);
855        if (p == NULL) {
856          vm_exit_out_of_memory(offset_of(JvmtiCachedClassFileData, data) + _curr_len,
857            OOM_MALLOC_ERROR,
858            "unable to allocate cached copy of original class bytes");
859        }
860        p->length = _curr_len;
861        memcpy(p->data, _curr_data, _curr_len);
862        *_cached_class_file_ptr = p;
863      }
864
865      if (_curr_data != *_data_ptr) {
866        // curr_data is previous agent modified class data.
867        // And this has been changed by the new agent so
868        // we can delete it now.
869        _curr_env->Deallocate(_curr_data);
870      }
871
872      // Class file data has changed by the current agent.
873      _curr_data = new_data;
874      _curr_len = new_len;
875      // Save the current agent env we need this to deallocate the
876      // memory allocated by this agent.
877      _curr_env = env;
878    }
879  }
880
881  void copy_modified_data() {
882    // if one of the agent has modified class file data.
883    // Copy modified class data to new resources array.
884    if (_curr_data != *_data_ptr) {
885      *_data_ptr = NEW_RESOURCE_ARRAY(u1, _curr_len);
886      memcpy(*_data_ptr, _curr_data, _curr_len);
887      *_end_ptr = *_data_ptr + _curr_len;
888      _curr_env->Deallocate(_curr_data);
889    }
890  }
891};
892
893bool JvmtiExport::_should_post_class_file_load_hook = false;
894
895// this entry is for class file load hook on class load, redefine and retransform
896void JvmtiExport::post_class_file_load_hook(Symbol* h_name,
897                                            Handle class_loader,
898                                            Handle h_protection_domain,
899                                            unsigned char **data_ptr,
900                                            unsigned char **end_ptr,
901                                            JvmtiCachedClassFileData **cache_ptr) {
902  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
903    return;
904  }
905
906  JvmtiClassFileLoadHookPoster poster(h_name, class_loader,
907                                      h_protection_domain,
908                                      data_ptr, end_ptr,
909                                      cache_ptr);
910  poster.post();
911}
912
913void JvmtiExport::report_unsupported(bool on) {
914  // If any JVMTI service is turned on, we need to exit before native code
915  // tries to access nonexistant services.
916  if (on) {
917    vm_exit_during_initialization("Java Kernel does not support JVMTI.");
918  }
919}
920
921
922static inline Klass* oop_to_klass(oop obj) {
923  Klass* k = obj->klass();
924
925  // if the object is a java.lang.Class then return the java mirror
926  if (k == SystemDictionary::Class_klass()) {
927    if (!java_lang_Class::is_primitive(obj)) {
928      k = java_lang_Class::as_Klass(obj);
929      assert(k != NULL, "class for non-primitive mirror must exist");
930    }
931  }
932  return k;
933}
934
935class JvmtiVMObjectAllocEventMark : public JvmtiClassEventMark  {
936 private:
937   jobject _jobj;
938   jlong    _size;
939 public:
940   JvmtiVMObjectAllocEventMark(JavaThread *thread, oop obj) : JvmtiClassEventMark(thread, oop_to_klass(obj)) {
941     _jobj = (jobject)to_jobject(obj);
942     _size = obj->size() * wordSize;
943   };
944   jobject jni_jobject() { return _jobj; }
945   jlong size() { return _size; }
946};
947
948class JvmtiCompiledMethodLoadEventMark : public JvmtiMethodEventMark {
949 private:
950  jint _code_size;
951  const void *_code_data;
952  jint _map_length;
953  jvmtiAddrLocationMap *_map;
954  const void *_compile_info;
955 public:
956  JvmtiCompiledMethodLoadEventMark(JavaThread *thread, nmethod *nm, void* compile_info_ptr = NULL)
957          : JvmtiMethodEventMark(thread,methodHandle(thread, nm->method())) {
958    _code_data = nm->insts_begin();
959    _code_size = nm->insts_size();
960    _compile_info = compile_info_ptr; // Set void pointer of compiledMethodLoad Event. Default value is NULL.
961    JvmtiCodeBlobEvents::build_jvmti_addr_location_map(nm, &_map, &_map_length);
962  }
963  ~JvmtiCompiledMethodLoadEventMark() {
964     FREE_C_HEAP_ARRAY(jvmtiAddrLocationMap, _map);
965  }
966
967  jint code_size() { return _code_size; }
968  const void *code_data() { return _code_data; }
969  jint map_length() { return _map_length; }
970  const jvmtiAddrLocationMap* map() { return _map; }
971  const void *compile_info() { return _compile_info; }
972};
973
974
975
976class JvmtiMonitorEventMark : public JvmtiThreadEventMark {
977private:
978  jobject _jobj;
979public:
980  JvmtiMonitorEventMark(JavaThread *thread, oop object)
981          : JvmtiThreadEventMark(thread){
982     _jobj = to_jobject(object);
983  }
984  jobject jni_object() { return _jobj; }
985};
986
987///////////////////////////////////////////////////////////////
988//
989// pending CompiledMethodUnload support
990//
991
992void JvmtiExport::post_compiled_method_unload(
993       jmethodID method, const void *code_begin) {
994  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
995    return;
996  }
997  JavaThread* thread = JavaThread::current();
998  EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
999                 ("[%s] method compile unload event triggered",
1000                  JvmtiTrace::safe_get_thread_name(thread)));
1001
1002  // post the event for each environment that has this event enabled.
1003  JvmtiEnvIterator it;
1004  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1005    if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_UNLOAD)) {
1006      if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1007        continue;
1008      }
1009      EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
1010                ("[%s] class compile method unload event sent jmethodID " PTR_FORMAT,
1011                 JvmtiTrace::safe_get_thread_name(thread), p2i(method)));
1012
1013      ResourceMark rm(thread);
1014
1015      JvmtiEventMark jem(thread);
1016      JvmtiJavaThreadEventTransition jet(thread);
1017      jvmtiEventCompiledMethodUnload callback = env->callbacks()->CompiledMethodUnload;
1018      if (callback != NULL) {
1019        (*callback)(env->jvmti_external(), method, code_begin);
1020      }
1021    }
1022  }
1023}
1024
1025///////////////////////////////////////////////////////////////
1026//
1027// JvmtiExport
1028//
1029
1030void JvmtiExport::post_raw_breakpoint(JavaThread *thread, Method* method, address location) {
1031  HandleMark hm(thread);
1032  methodHandle mh(thread, method);
1033
1034  JvmtiThreadState *state = thread->jvmti_thread_state();
1035  if (state == NULL) {
1036    return;
1037  }
1038  EVT_TRIG_TRACE(JVMTI_EVENT_BREAKPOINT, ("[%s] Trg Breakpoint triggered",
1039                      JvmtiTrace::safe_get_thread_name(thread)));
1040  JvmtiEnvThreadStateIterator it(state);
1041  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1042    ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_BREAKPOINT);
1043    if (!ets->breakpoint_posted() && ets->is_enabled(JVMTI_EVENT_BREAKPOINT)) {
1044      ThreadState old_os_state = thread->osthread()->get_state();
1045      thread->osthread()->set_state(BREAKPOINTED);
1046      EVT_TRACE(JVMTI_EVENT_BREAKPOINT, ("[%s] Evt Breakpoint sent %s.%s @ " INTX_FORMAT,
1047                     JvmtiTrace::safe_get_thread_name(thread),
1048                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1049                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1050                     location - mh()->code_base() ));
1051
1052      JvmtiEnv *env = ets->get_env();
1053      JvmtiLocationEventMark jem(thread, mh, location);
1054      JvmtiJavaThreadEventTransition jet(thread);
1055      jvmtiEventBreakpoint callback = env->callbacks()->Breakpoint;
1056      if (callback != NULL) {
1057        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1058                    jem.jni_methodID(), jem.location());
1059      }
1060
1061      ets->set_breakpoint_posted();
1062      thread->osthread()->set_state(old_os_state);
1063    }
1064  }
1065}
1066
1067//////////////////////////////////////////////////////////////////////////////
1068
1069bool              JvmtiExport::_can_get_source_debug_extension            = false;
1070bool              JvmtiExport::_can_maintain_original_method_order        = false;
1071bool              JvmtiExport::_can_post_interpreter_events               = false;
1072bool              JvmtiExport::_can_post_on_exceptions                    = false;
1073bool              JvmtiExport::_can_post_breakpoint                       = false;
1074bool              JvmtiExport::_can_post_field_access                     = false;
1075bool              JvmtiExport::_can_post_field_modification               = false;
1076bool              JvmtiExport::_can_post_method_entry                     = false;
1077bool              JvmtiExport::_can_post_method_exit                      = false;
1078bool              JvmtiExport::_can_pop_frame                             = false;
1079bool              JvmtiExport::_can_force_early_return                    = false;
1080
1081bool              JvmtiExport::_early_vmstart_recorded                    = false;
1082
1083bool              JvmtiExport::_should_post_single_step                   = false;
1084bool              JvmtiExport::_should_post_field_access                  = false;
1085bool              JvmtiExport::_should_post_field_modification            = false;
1086bool              JvmtiExport::_should_post_class_load                    = false;
1087bool              JvmtiExport::_should_post_class_prepare                 = false;
1088bool              JvmtiExport::_should_post_class_unload                  = false;
1089bool              JvmtiExport::_should_post_thread_life                   = false;
1090bool              JvmtiExport::_should_clean_up_heap_objects              = false;
1091bool              JvmtiExport::_should_post_native_method_bind            = false;
1092bool              JvmtiExport::_should_post_dynamic_code_generated        = false;
1093bool              JvmtiExport::_should_post_data_dump                     = false;
1094bool              JvmtiExport::_should_post_compiled_method_load          = false;
1095bool              JvmtiExport::_should_post_compiled_method_unload        = false;
1096bool              JvmtiExport::_should_post_monitor_contended_enter       = false;
1097bool              JvmtiExport::_should_post_monitor_contended_entered     = false;
1098bool              JvmtiExport::_should_post_monitor_wait                  = false;
1099bool              JvmtiExport::_should_post_monitor_waited                = false;
1100bool              JvmtiExport::_should_post_garbage_collection_start      = false;
1101bool              JvmtiExport::_should_post_garbage_collection_finish     = false;
1102bool              JvmtiExport::_should_post_object_free                   = false;
1103bool              JvmtiExport::_should_post_resource_exhausted            = false;
1104bool              JvmtiExport::_should_post_vm_object_alloc               = false;
1105bool              JvmtiExport::_should_post_on_exceptions                 = false;
1106
1107////////////////////////////////////////////////////////////////////////////////////////////////
1108
1109
1110//
1111// JVMTI single step management
1112//
1113void JvmtiExport::at_single_stepping_point(JavaThread *thread, Method* method, address location) {
1114  assert(JvmtiExport::should_post_single_step(), "must be single stepping");
1115
1116  HandleMark hm(thread);
1117  methodHandle mh(thread, method);
1118
1119  // update information about current location and post a step event
1120  JvmtiThreadState *state = thread->jvmti_thread_state();
1121  if (state == NULL) {
1122    return;
1123  }
1124  EVT_TRIG_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Trg Single Step triggered",
1125                      JvmtiTrace::safe_get_thread_name(thread)));
1126  if (!state->hide_single_stepping()) {
1127    if (state->is_pending_step_for_popframe()) {
1128      state->process_pending_step_for_popframe();
1129    }
1130    if (state->is_pending_step_for_earlyret()) {
1131      state->process_pending_step_for_earlyret();
1132    }
1133    JvmtiExport::post_single_step(thread, mh(), location);
1134  }
1135}
1136
1137
1138void JvmtiExport::expose_single_stepping(JavaThread *thread) {
1139  JvmtiThreadState *state = thread->jvmti_thread_state();
1140  if (state != NULL) {
1141    state->clear_hide_single_stepping();
1142  }
1143}
1144
1145
1146bool JvmtiExport::hide_single_stepping(JavaThread *thread) {
1147  JvmtiThreadState *state = thread->jvmti_thread_state();
1148  if (state != NULL && state->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1149    state->set_hide_single_stepping();
1150    return true;
1151  } else {
1152    return false;
1153  }
1154}
1155
1156void JvmtiExport::post_class_load(JavaThread *thread, Klass* klass) {
1157  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1158    return;
1159  }
1160  HandleMark hm(thread);
1161  KlassHandle kh(thread, klass);
1162
1163  EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Trg Class Load triggered",
1164                      JvmtiTrace::safe_get_thread_name(thread)));
1165  JvmtiThreadState* state = thread->jvmti_thread_state();
1166  if (state == NULL) {
1167    return;
1168  }
1169  JvmtiEnvThreadStateIterator it(state);
1170  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1171    if (ets->is_enabled(JVMTI_EVENT_CLASS_LOAD)) {
1172      JvmtiEnv *env = ets->get_env();
1173      if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1174        continue;
1175      }
1176      EVT_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Evt Class Load sent %s",
1177                                         JvmtiTrace::safe_get_thread_name(thread),
1178                                         kh()==NULL? "NULL" : kh()->external_name() ));
1179      JvmtiClassEventMark jem(thread, kh());
1180      JvmtiJavaThreadEventTransition jet(thread);
1181      jvmtiEventClassLoad callback = env->callbacks()->ClassLoad;
1182      if (callback != NULL) {
1183        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1184      }
1185    }
1186  }
1187}
1188
1189
1190void JvmtiExport::post_class_prepare(JavaThread *thread, Klass* klass) {
1191  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1192    return;
1193  }
1194  HandleMark hm(thread);
1195  KlassHandle kh(thread, klass);
1196
1197  EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Trg Class Prepare triggered",
1198                      JvmtiTrace::safe_get_thread_name(thread)));
1199  JvmtiThreadState* state = thread->jvmti_thread_state();
1200  if (state == NULL) {
1201    return;
1202  }
1203  JvmtiEnvThreadStateIterator it(state);
1204  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1205    if (ets->is_enabled(JVMTI_EVENT_CLASS_PREPARE)) {
1206      JvmtiEnv *env = ets->get_env();
1207      if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1208        continue;
1209      }
1210      EVT_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Evt Class Prepare sent %s",
1211                                            JvmtiTrace::safe_get_thread_name(thread),
1212                                            kh()==NULL? "NULL" : kh()->external_name() ));
1213      JvmtiClassEventMark jem(thread, kh());
1214      JvmtiJavaThreadEventTransition jet(thread);
1215      jvmtiEventClassPrepare callback = env->callbacks()->ClassPrepare;
1216      if (callback != NULL) {
1217        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1218      }
1219    }
1220  }
1221}
1222
1223void JvmtiExport::post_class_unload(Klass* klass) {
1224  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1225    return;
1226  }
1227  Thread *thread = Thread::current();
1228  HandleMark hm(thread);
1229  KlassHandle kh(thread, klass);
1230
1231  EVT_TRIG_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Trg Class Unload triggered" ));
1232  if (JvmtiEventController::is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1233    assert(thread->is_VM_thread(), "wrong thread");
1234
1235    // get JavaThread for whom we are proxy
1236    JavaThread *real_thread =
1237        (JavaThread *)((VMThread *)thread)->vm_operation()->calling_thread();
1238
1239    JvmtiEnvIterator it;
1240    for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1241      if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1242        continue;
1243      }
1244      if (env->is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1245        EVT_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Evt Class Unload sent %s",
1246                  kh()==NULL? "NULL" : kh()->external_name() ));
1247
1248        // do everything manually, since this is a proxy - needs special care
1249        JNIEnv* jni_env = real_thread->jni_environment();
1250        jthread jt = (jthread)JNIHandles::make_local(real_thread, real_thread->threadObj());
1251        jclass jk = (jclass)JNIHandles::make_local(real_thread, kh()->java_mirror());
1252
1253        // Before we call the JVMTI agent, we have to set the state in the
1254        // thread for which we are proxying.
1255        JavaThreadState prev_state = real_thread->thread_state();
1256        assert(((Thread *)real_thread)->is_ConcurrentGC_thread() ||
1257               (real_thread->is_Java_thread() && prev_state == _thread_blocked),
1258               "should be ConcurrentGCThread or JavaThread at safepoint");
1259        real_thread->set_thread_state(_thread_in_native);
1260
1261        jvmtiExtensionEvent callback = env->ext_callbacks()->ClassUnload;
1262        if (callback != NULL) {
1263          (*callback)(env->jvmti_external(), jni_env, jt, jk);
1264        }
1265
1266        assert(real_thread->thread_state() == _thread_in_native,
1267               "JavaThread should be in native");
1268        real_thread->set_thread_state(prev_state);
1269
1270        JNIHandles::destroy_local(jk);
1271        JNIHandles::destroy_local(jt);
1272      }
1273    }
1274  }
1275}
1276
1277
1278void JvmtiExport::post_thread_start(JavaThread *thread) {
1279  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1280    return;
1281  }
1282  assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
1283
1284  EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Trg Thread Start event triggered",
1285                      JvmtiTrace::safe_get_thread_name(thread)));
1286
1287  // do JVMTI thread initialization (if needed)
1288  JvmtiEventController::thread_started(thread);
1289
1290  // Do not post thread start event for hidden java thread.
1291  if (JvmtiEventController::is_enabled(JVMTI_EVENT_THREAD_START) &&
1292      !thread->is_hidden_from_external_view()) {
1293    JvmtiEnvIterator it;
1294    for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1295      if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1296        continue;
1297      }
1298      if (env->is_enabled(JVMTI_EVENT_THREAD_START)) {
1299        EVT_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Evt Thread Start event sent",
1300                     JvmtiTrace::safe_get_thread_name(thread) ));
1301
1302        JvmtiThreadEventMark jem(thread);
1303        JvmtiJavaThreadEventTransition jet(thread);
1304        jvmtiEventThreadStart callback = env->callbacks()->ThreadStart;
1305        if (callback != NULL) {
1306          (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1307        }
1308      }
1309    }
1310  }
1311}
1312
1313
1314void JvmtiExport::post_thread_end(JavaThread *thread) {
1315  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1316    return;
1317  }
1318  EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Trg Thread End event triggered",
1319                      JvmtiTrace::safe_get_thread_name(thread)));
1320
1321  JvmtiThreadState *state = thread->jvmti_thread_state();
1322  if (state == NULL) {
1323    return;
1324  }
1325
1326  // Do not post thread end event for hidden java thread.
1327  if (state->is_enabled(JVMTI_EVENT_THREAD_END) &&
1328      !thread->is_hidden_from_external_view()) {
1329
1330    JvmtiEnvThreadStateIterator it(state);
1331    for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1332      if (ets->is_enabled(JVMTI_EVENT_THREAD_END)) {
1333        JvmtiEnv *env = ets->get_env();
1334        if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1335          continue;
1336        }
1337        EVT_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Evt Thread End event sent",
1338                     JvmtiTrace::safe_get_thread_name(thread) ));
1339
1340        JvmtiThreadEventMark jem(thread);
1341        JvmtiJavaThreadEventTransition jet(thread);
1342        jvmtiEventThreadEnd callback = env->callbacks()->ThreadEnd;
1343        if (callback != NULL) {
1344          (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1345        }
1346      }
1347    }
1348  }
1349}
1350
1351void JvmtiExport::post_object_free(JvmtiEnv* env, jlong tag) {
1352  assert(SafepointSynchronize::is_at_safepoint(), "must be executed at safepoint");
1353  assert(env->is_enabled(JVMTI_EVENT_OBJECT_FREE), "checking");
1354
1355  EVT_TRIG_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Trg Object Free triggered" ));
1356  EVT_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Evt Object Free sent"));
1357
1358  jvmtiEventObjectFree callback = env->callbacks()->ObjectFree;
1359  if (callback != NULL) {
1360    (*callback)(env->jvmti_external(), tag);
1361  }
1362}
1363
1364void JvmtiExport::post_resource_exhausted(jint resource_exhausted_flags, const char* description) {
1365  EVT_TRIG_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Trg resource exhausted event triggered" ));
1366
1367  JvmtiEnvIterator it;
1368  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1369    if (env->is_enabled(JVMTI_EVENT_RESOURCE_EXHAUSTED)) {
1370      EVT_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Evt resource exhausted event sent" ));
1371
1372      JavaThread *thread  = JavaThread::current();
1373      JvmtiThreadEventMark jem(thread);
1374      JvmtiJavaThreadEventTransition jet(thread);
1375      jvmtiEventResourceExhausted callback = env->callbacks()->ResourceExhausted;
1376      if (callback != NULL) {
1377        (*callback)(env->jvmti_external(), jem.jni_env(),
1378                    resource_exhausted_flags, NULL, description);
1379      }
1380    }
1381  }
1382}
1383
1384void JvmtiExport::post_method_entry(JavaThread *thread, Method* method, frame current_frame) {
1385  HandleMark hm(thread);
1386  methodHandle mh(thread, method);
1387
1388  EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Trg Method Entry triggered %s.%s",
1389                     JvmtiTrace::safe_get_thread_name(thread),
1390                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1391                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1392
1393  JvmtiThreadState* state = thread->jvmti_thread_state();
1394  if (state == NULL || !state->is_interp_only_mode()) {
1395    // for any thread that actually wants method entry, interp_only_mode is set
1396    return;
1397  }
1398
1399  state->incr_cur_stack_depth();
1400
1401  if (state->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1402    JvmtiEnvThreadStateIterator it(state);
1403    for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1404      if (ets->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1405        EVT_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Evt Method Entry sent %s.%s",
1406                                             JvmtiTrace::safe_get_thread_name(thread),
1407                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1408                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1409
1410        JvmtiEnv *env = ets->get_env();
1411        JvmtiMethodEventMark jem(thread, mh);
1412        JvmtiJavaThreadEventTransition jet(thread);
1413        jvmtiEventMethodEntry callback = env->callbacks()->MethodEntry;
1414        if (callback != NULL) {
1415          (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_methodID());
1416        }
1417      }
1418    }
1419  }
1420}
1421
1422void JvmtiExport::post_method_exit(JavaThread *thread, Method* method, frame current_frame) {
1423  HandleMark hm(thread);
1424  methodHandle mh(thread, method);
1425
1426  EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Trg Method Exit triggered %s.%s",
1427                     JvmtiTrace::safe_get_thread_name(thread),
1428                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1429                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1430
1431  JvmtiThreadState *state = thread->jvmti_thread_state();
1432  if (state == NULL || !state->is_interp_only_mode()) {
1433    // for any thread that actually wants method exit, interp_only_mode is set
1434    return;
1435  }
1436
1437  // return a flag when a method terminates by throwing an exception
1438  // i.e. if an exception is thrown and it's not caught by the current method
1439  bool exception_exit = state->is_exception_detected() && !state->is_exception_caught();
1440
1441
1442  if (state->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1443    Handle result;
1444    jvalue value;
1445    value.j = 0L;
1446
1447    // if the method hasn't been popped because of an exception then we populate
1448    // the return_value parameter for the callback. At this point we only have
1449    // the address of a "raw result" and we just call into the interpreter to
1450    // convert this into a jvalue.
1451    if (!exception_exit) {
1452      oop oop_result;
1453      BasicType type = current_frame.interpreter_frame_result(&oop_result, &value);
1454      if (type == T_OBJECT || type == T_ARRAY) {
1455        result = Handle(thread, oop_result);
1456      }
1457    }
1458
1459    JvmtiEnvThreadStateIterator it(state);
1460    for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1461      if (ets->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1462        EVT_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Evt Method Exit sent %s.%s",
1463                                            JvmtiTrace::safe_get_thread_name(thread),
1464                                            (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1465                                            (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1466
1467        JvmtiEnv *env = ets->get_env();
1468        JvmtiMethodEventMark jem(thread, mh);
1469        if (result.not_null()) {
1470          value.l = JNIHandles::make_local(thread, result());
1471        }
1472        JvmtiJavaThreadEventTransition jet(thread);
1473        jvmtiEventMethodExit callback = env->callbacks()->MethodExit;
1474        if (callback != NULL) {
1475          (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1476                      jem.jni_methodID(), exception_exit,  value);
1477        }
1478      }
1479    }
1480  }
1481
1482  if (state->is_enabled(JVMTI_EVENT_FRAME_POP)) {
1483    JvmtiEnvThreadStateIterator it(state);
1484    for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1485      int cur_frame_number = state->cur_stack_depth();
1486
1487      if (ets->is_frame_pop(cur_frame_number)) {
1488        // we have a NotifyFramePop entry for this frame.
1489        // now check that this env/thread wants this event
1490        if (ets->is_enabled(JVMTI_EVENT_FRAME_POP)) {
1491          EVT_TRACE(JVMTI_EVENT_FRAME_POP, ("[%s] Evt Frame Pop sent %s.%s",
1492                                            JvmtiTrace::safe_get_thread_name(thread),
1493                                            (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1494                                            (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1495
1496          // we also need to issue a frame pop event for this frame
1497          JvmtiEnv *env = ets->get_env();
1498          JvmtiMethodEventMark jem(thread, mh);
1499          JvmtiJavaThreadEventTransition jet(thread);
1500          jvmtiEventFramePop callback = env->callbacks()->FramePop;
1501          if (callback != NULL) {
1502            (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1503                        jem.jni_methodID(), exception_exit);
1504          }
1505        }
1506        // remove the frame's entry
1507        ets->clear_frame_pop(cur_frame_number);
1508      }
1509    }
1510  }
1511
1512  state->decr_cur_stack_depth();
1513}
1514
1515
1516// Todo: inline this for optimization
1517void JvmtiExport::post_single_step(JavaThread *thread, Method* method, address location) {
1518  HandleMark hm(thread);
1519  methodHandle mh(thread, method);
1520
1521  JvmtiThreadState *state = thread->jvmti_thread_state();
1522  if (state == NULL) {
1523    return;
1524  }
1525  JvmtiEnvThreadStateIterator it(state);
1526  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1527    ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_SINGLE_STEP);
1528    if (!ets->single_stepping_posted() && ets->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1529      EVT_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Evt Single Step sent %s.%s @ " INTX_FORMAT,
1530                    JvmtiTrace::safe_get_thread_name(thread),
1531                    (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1532                    (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1533                    location - mh()->code_base() ));
1534
1535      JvmtiEnv *env = ets->get_env();
1536      JvmtiLocationEventMark jem(thread, mh, location);
1537      JvmtiJavaThreadEventTransition jet(thread);
1538      jvmtiEventSingleStep callback = env->callbacks()->SingleStep;
1539      if (callback != NULL) {
1540        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1541                    jem.jni_methodID(), jem.location());
1542      }
1543
1544      ets->set_single_stepping_posted();
1545    }
1546  }
1547}
1548
1549
1550void JvmtiExport::post_exception_throw(JavaThread *thread, Method* method, address location, oop exception) {
1551  HandleMark hm(thread);
1552  methodHandle mh(thread, method);
1553  Handle exception_handle(thread, exception);
1554
1555  JvmtiThreadState *state = thread->jvmti_thread_state();
1556  if (state == NULL) {
1557    return;
1558  }
1559
1560  EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION, ("[%s] Trg Exception thrown triggered",
1561                      JvmtiTrace::safe_get_thread_name(thread)));
1562  if (!state->is_exception_detected()) {
1563    state->set_exception_detected();
1564    JvmtiEnvThreadStateIterator it(state);
1565    for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1566      if (ets->is_enabled(JVMTI_EVENT_EXCEPTION) && (exception != NULL)) {
1567
1568        EVT_TRACE(JVMTI_EVENT_EXCEPTION,
1569                     ("[%s] Evt Exception thrown sent %s.%s @ " INTX_FORMAT,
1570                      JvmtiTrace::safe_get_thread_name(thread),
1571                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1572                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1573                      location - mh()->code_base() ));
1574
1575        JvmtiEnv *env = ets->get_env();
1576        JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1577
1578        // It's okay to clear these exceptions here because we duplicate
1579        // this lookup in InterpreterRuntime::exception_handler_for_exception.
1580        EXCEPTION_MARK;
1581
1582        bool should_repeat;
1583        vframeStream st(thread);
1584        assert(!st.at_end(), "cannot be at end");
1585        Method* current_method = NULL;
1586        // A GC may occur during the Method::fast_exception_handler_bci_for()
1587        // call below if it needs to load the constraint class. Using a
1588        // methodHandle to keep the 'current_method' from being deallocated
1589        // if GC happens.
1590        methodHandle current_mh = methodHandle(thread, current_method);
1591        int current_bci = -1;
1592        do {
1593          current_method = st.method();
1594          current_mh = methodHandle(thread, current_method);
1595          current_bci = st.bci();
1596          do {
1597            should_repeat = false;
1598            KlassHandle eh_klass(thread, exception_handle()->klass());
1599            current_bci = Method::fast_exception_handler_bci_for(
1600              current_mh, eh_klass, current_bci, THREAD);
1601            if (HAS_PENDING_EXCEPTION) {
1602              exception_handle = Handle(thread, PENDING_EXCEPTION);
1603              CLEAR_PENDING_EXCEPTION;
1604              should_repeat = true;
1605            }
1606          } while (should_repeat && (current_bci != -1));
1607          st.next();
1608        } while ((current_bci < 0) && (!st.at_end()));
1609
1610        jmethodID catch_jmethodID;
1611        if (current_bci < 0) {
1612          catch_jmethodID = 0;
1613          current_bci = 0;
1614        } else {
1615          catch_jmethodID = jem.to_jmethodID(current_mh);
1616        }
1617
1618        JvmtiJavaThreadEventTransition jet(thread);
1619        jvmtiEventException callback = env->callbacks()->Exception;
1620        if (callback != NULL) {
1621          (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1622                      jem.jni_methodID(), jem.location(),
1623                      jem.exception(),
1624                      catch_jmethodID, current_bci);
1625        }
1626      }
1627    }
1628  }
1629
1630  // frames may get popped because of this throw, be safe - invalidate cached depth
1631  state->invalidate_cur_stack_depth();
1632}
1633
1634
1635void JvmtiExport::notice_unwind_due_to_exception(JavaThread *thread, Method* method, address location, oop exception, bool in_handler_frame) {
1636  HandleMark hm(thread);
1637  methodHandle mh(thread, method);
1638  Handle exception_handle(thread, exception);
1639
1640  JvmtiThreadState *state = thread->jvmti_thread_state();
1641  if (state == NULL) {
1642    return;
1643  }
1644  EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1645                    ("[%s] Trg unwind_due_to_exception triggered %s.%s @ %s" INTX_FORMAT " - %s",
1646                     JvmtiTrace::safe_get_thread_name(thread),
1647                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1648                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1649                     location==0? "no location:" : "",
1650                     location==0? 0 : location - mh()->code_base(),
1651                     in_handler_frame? "in handler frame" : "not handler frame" ));
1652
1653  if (state->is_exception_detected()) {
1654
1655    state->invalidate_cur_stack_depth();
1656    if (!in_handler_frame) {
1657      // Not in exception handler.
1658      if(state->is_interp_only_mode()) {
1659        // method exit and frame pop events are posted only in interp mode.
1660        // When these events are enabled code should be in running in interp mode.
1661        JvmtiExport::post_method_exit(thread, method, thread->last_frame());
1662        // The cached cur_stack_depth might have changed from the
1663        // operations of frame pop or method exit. We are not 100% sure
1664        // the cached cur_stack_depth is still valid depth so invalidate
1665        // it.
1666        state->invalidate_cur_stack_depth();
1667      }
1668    } else {
1669      // In exception handler frame. Report exception catch.
1670      assert(location != NULL, "must be a known location");
1671      // Update cur_stack_depth - the frames above the current frame
1672      // have been unwound due to this exception:
1673      assert(!state->is_exception_caught(), "exception must not be caught yet.");
1674      state->set_exception_caught();
1675
1676      JvmtiEnvThreadStateIterator it(state);
1677      for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1678        if (ets->is_enabled(JVMTI_EVENT_EXCEPTION_CATCH) && (exception_handle() != NULL)) {
1679          EVT_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1680                     ("[%s] Evt ExceptionCatch sent %s.%s @ " INTX_FORMAT,
1681                      JvmtiTrace::safe_get_thread_name(thread),
1682                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1683                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1684                      location - mh()->code_base() ));
1685
1686          JvmtiEnv *env = ets->get_env();
1687          JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1688          JvmtiJavaThreadEventTransition jet(thread);
1689          jvmtiEventExceptionCatch callback = env->callbacks()->ExceptionCatch;
1690          if (callback != NULL) {
1691            (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1692                      jem.jni_methodID(), jem.location(),
1693                      jem.exception());
1694          }
1695        }
1696      }
1697    }
1698  }
1699}
1700
1701oop JvmtiExport::jni_GetField_probe(JavaThread *thread, jobject jobj, oop obj,
1702                                    Klass* klass, jfieldID fieldID, bool is_static) {
1703  if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1704    // At least one field access watch is set so we have more work
1705    // to do. This wrapper is used by entry points that allow us
1706    // to create handles in post_field_access_by_jni().
1707    post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1708    // event posting can block so refetch oop if we were passed a jobj
1709    if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1710  }
1711  return obj;
1712}
1713
1714oop JvmtiExport::jni_GetField_probe_nh(JavaThread *thread, jobject jobj, oop obj,
1715                                       Klass* klass, jfieldID fieldID, bool is_static) {
1716  if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1717    // At least one field access watch is set so we have more work
1718    // to do. This wrapper is used by "quick" entry points that don't
1719    // allow us to create handles in post_field_access_by_jni(). We
1720    // override that with a ResetNoHandleMark.
1721    ResetNoHandleMark rnhm;
1722    post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1723    // event posting can block so refetch oop if we were passed a jobj
1724    if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1725  }
1726  return obj;
1727}
1728
1729void JvmtiExport::post_field_access_by_jni(JavaThread *thread, oop obj,
1730                                           Klass* klass, jfieldID fieldID, bool is_static) {
1731  // We must be called with a Java context in order to provide reasonable
1732  // values for the klazz, method, and location fields. The callers of this
1733  // function don't make the call unless there is a Java context.
1734  assert(thread->has_last_Java_frame(), "must be called with a Java context");
1735
1736  ResourceMark rm;
1737  fieldDescriptor fd;
1738  // if get_field_descriptor finds fieldID to be invalid, then we just bail
1739  bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1740  assert(valid_fieldID == true,"post_field_access_by_jni called with invalid fieldID");
1741  if (!valid_fieldID) return;
1742  // field accesses are not watched so bail
1743  if (!fd.is_field_access_watched()) return;
1744
1745  HandleMark hm(thread);
1746  KlassHandle h_klass(thread, klass);
1747  Handle h_obj;
1748  if (!is_static) {
1749    // non-static field accessors have an object, but we need a handle
1750    assert(obj != NULL, "non-static needs an object");
1751    h_obj = Handle(thread, obj);
1752  }
1753  post_field_access(thread,
1754                    thread->last_frame().interpreter_frame_method(),
1755                    thread->last_frame().interpreter_frame_bcp(),
1756                    h_klass, h_obj, fieldID);
1757}
1758
1759void JvmtiExport::post_field_access(JavaThread *thread, Method* method,
1760  address location, KlassHandle field_klass, Handle object, jfieldID field) {
1761
1762  HandleMark hm(thread);
1763  methodHandle mh(thread, method);
1764
1765  JvmtiThreadState *state = thread->jvmti_thread_state();
1766  if (state == NULL) {
1767    return;
1768  }
1769  EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Trg Field Access event triggered",
1770                      JvmtiTrace::safe_get_thread_name(thread)));
1771  JvmtiEnvThreadStateIterator it(state);
1772  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1773    if (ets->is_enabled(JVMTI_EVENT_FIELD_ACCESS)) {
1774      EVT_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Evt Field Access event sent %s.%s @ " INTX_FORMAT,
1775                     JvmtiTrace::safe_get_thread_name(thread),
1776                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1777                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1778                     location - mh()->code_base() ));
1779
1780      JvmtiEnv *env = ets->get_env();
1781      JvmtiLocationEventMark jem(thread, mh, location);
1782      jclass field_jclass = jem.to_jclass(field_klass());
1783      jobject field_jobject = jem.to_jobject(object());
1784      JvmtiJavaThreadEventTransition jet(thread);
1785      jvmtiEventFieldAccess callback = env->callbacks()->FieldAccess;
1786      if (callback != NULL) {
1787        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1788                    jem.jni_methodID(), jem.location(),
1789                    field_jclass, field_jobject, field);
1790      }
1791    }
1792  }
1793}
1794
1795oop JvmtiExport::jni_SetField_probe(JavaThread *thread, jobject jobj, oop obj,
1796                                    Klass* klass, jfieldID fieldID, bool is_static,
1797                                    char sig_type, jvalue *value) {
1798  if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1799    // At least one field modification watch is set so we have more work
1800    // to do. This wrapper is used by entry points that allow us
1801    // to create handles in post_field_modification_by_jni().
1802    post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1803    // event posting can block so refetch oop if we were passed a jobj
1804    if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1805  }
1806  return obj;
1807}
1808
1809oop JvmtiExport::jni_SetField_probe_nh(JavaThread *thread, jobject jobj, oop obj,
1810                                       Klass* klass, jfieldID fieldID, bool is_static,
1811                                       char sig_type, jvalue *value) {
1812  if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1813    // At least one field modification watch is set so we have more work
1814    // to do. This wrapper is used by "quick" entry points that don't
1815    // allow us to create handles in post_field_modification_by_jni(). We
1816    // override that with a ResetNoHandleMark.
1817    ResetNoHandleMark rnhm;
1818    post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1819    // event posting can block so refetch oop if we were passed a jobj
1820    if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1821  }
1822  return obj;
1823}
1824
1825void JvmtiExport::post_field_modification_by_jni(JavaThread *thread, oop obj,
1826                                                 Klass* klass, jfieldID fieldID, bool is_static,
1827                                                 char sig_type, jvalue *value) {
1828  // We must be called with a Java context in order to provide reasonable
1829  // values for the klazz, method, and location fields. The callers of this
1830  // function don't make the call unless there is a Java context.
1831  assert(thread->has_last_Java_frame(), "must be called with Java context");
1832
1833  ResourceMark rm;
1834  fieldDescriptor fd;
1835  // if get_field_descriptor finds fieldID to be invalid, then we just bail
1836  bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1837  assert(valid_fieldID == true,"post_field_modification_by_jni called with invalid fieldID");
1838  if (!valid_fieldID) return;
1839  // field modifications are not watched so bail
1840  if (!fd.is_field_modification_watched()) return;
1841
1842  HandleMark hm(thread);
1843
1844  Handle h_obj;
1845  if (!is_static) {
1846    // non-static field accessors have an object, but we need a handle
1847    assert(obj != NULL, "non-static needs an object");
1848    h_obj = Handle(thread, obj);
1849  }
1850  KlassHandle h_klass(thread, klass);
1851  post_field_modification(thread,
1852                          thread->last_frame().interpreter_frame_method(),
1853                          thread->last_frame().interpreter_frame_bcp(),
1854                          h_klass, h_obj, fieldID, sig_type, value);
1855}
1856
1857void JvmtiExport::post_raw_field_modification(JavaThread *thread, Method* method,
1858  address location, KlassHandle field_klass, Handle object, jfieldID field,
1859  char sig_type, jvalue *value) {
1860
1861  if (sig_type == 'I' || sig_type == 'Z' || sig_type == 'B' || sig_type == 'C' || sig_type == 'S') {
1862    // 'I' instructions are used for byte, char, short and int.
1863    // determine which it really is, and convert
1864    fieldDescriptor fd;
1865    bool found = JvmtiEnv::get_field_descriptor(field_klass(), field, &fd);
1866    // should be found (if not, leave as is)
1867    if (found) {
1868      jint ival = value->i;
1869      // convert value from int to appropriate type
1870      switch (fd.field_type()) {
1871      case T_BOOLEAN:
1872        sig_type = 'Z';
1873        value->i = 0; // clear it
1874        value->z = (jboolean)ival;
1875        break;
1876      case T_BYTE:
1877        sig_type = 'B';
1878        value->i = 0; // clear it
1879        value->b = (jbyte)ival;
1880        break;
1881      case T_CHAR:
1882        sig_type = 'C';
1883        value->i = 0; // clear it
1884        value->c = (jchar)ival;
1885        break;
1886      case T_SHORT:
1887        sig_type = 'S';
1888        value->i = 0; // clear it
1889        value->s = (jshort)ival;
1890        break;
1891      case T_INT:
1892        // nothing to do
1893        break;
1894      default:
1895        // this is an integer instruction, should be one of above
1896        ShouldNotReachHere();
1897        break;
1898      }
1899    }
1900  }
1901
1902  assert(sig_type != '[', "array should have sig_type == 'L'");
1903  bool handle_created = false;
1904
1905  // convert oop to JNI handle.
1906  if (sig_type == 'L') {
1907    handle_created = true;
1908    value->l = (jobject)JNIHandles::make_local(thread, (oop)value->l);
1909  }
1910
1911  post_field_modification(thread, method, location, field_klass, object, field, sig_type, value);
1912
1913  // Destroy the JNI handle allocated above.
1914  if (handle_created) {
1915    JNIHandles::destroy_local(value->l);
1916  }
1917}
1918
1919void JvmtiExport::post_field_modification(JavaThread *thread, Method* method,
1920  address location, KlassHandle field_klass, Handle object, jfieldID field,
1921  char sig_type, jvalue *value_ptr) {
1922
1923  HandleMark hm(thread);
1924  methodHandle mh(thread, method);
1925
1926  JvmtiThreadState *state = thread->jvmti_thread_state();
1927  if (state == NULL) {
1928    return;
1929  }
1930  EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
1931                     ("[%s] Trg Field Modification event triggered",
1932                      JvmtiTrace::safe_get_thread_name(thread)));
1933
1934  JvmtiEnvThreadStateIterator it(state);
1935  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1936    if (ets->is_enabled(JVMTI_EVENT_FIELD_MODIFICATION)) {
1937      EVT_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
1938                   ("[%s] Evt Field Modification event sent %s.%s @ " INTX_FORMAT,
1939                    JvmtiTrace::safe_get_thread_name(thread),
1940                    (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1941                    (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1942                    location - mh()->code_base() ));
1943
1944      JvmtiEnv *env = ets->get_env();
1945      JvmtiLocationEventMark jem(thread, mh, location);
1946      jclass field_jclass = jem.to_jclass(field_klass());
1947      jobject field_jobject = jem.to_jobject(object());
1948      JvmtiJavaThreadEventTransition jet(thread);
1949      jvmtiEventFieldModification callback = env->callbacks()->FieldModification;
1950      if (callback != NULL) {
1951        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1952                    jem.jni_methodID(), jem.location(),
1953                    field_jclass, field_jobject, field, sig_type, *value_ptr);
1954      }
1955    }
1956  }
1957}
1958
1959void JvmtiExport::post_native_method_bind(Method* method, address* function_ptr) {
1960  JavaThread* thread = JavaThread::current();
1961  assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
1962
1963  HandleMark hm(thread);
1964  methodHandle mh(thread, method);
1965
1966  EVT_TRIG_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Trg Native Method Bind event triggered",
1967                      JvmtiTrace::safe_get_thread_name(thread)));
1968
1969  if (JvmtiEventController::is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
1970    JvmtiEnvIterator it;
1971    for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1972      if (env->is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
1973        EVT_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Evt Native Method Bind event sent",
1974                     JvmtiTrace::safe_get_thread_name(thread) ));
1975
1976        JvmtiMethodEventMark jem(thread, mh);
1977        JvmtiJavaThreadEventTransition jet(thread);
1978        JNIEnv* jni_env = (env->phase() == JVMTI_PHASE_PRIMORDIAL) ? NULL : jem.jni_env();
1979        jvmtiEventNativeMethodBind callback = env->callbacks()->NativeMethodBind;
1980        if (callback != NULL) {
1981          (*callback)(env->jvmti_external(), jni_env, jem.jni_thread(),
1982                      jem.jni_methodID(), (void*)(*function_ptr), (void**)function_ptr);
1983        }
1984      }
1985    }
1986  }
1987}
1988
1989// Returns a record containing inlining information for the given nmethod
1990jvmtiCompiledMethodLoadInlineRecord* create_inline_record(nmethod* nm) {
1991  jint numstackframes = 0;
1992  jvmtiCompiledMethodLoadInlineRecord* record = (jvmtiCompiledMethodLoadInlineRecord*)NEW_RESOURCE_OBJ(jvmtiCompiledMethodLoadInlineRecord);
1993  record->header.kind = JVMTI_CMLR_INLINE_INFO;
1994  record->header.next = NULL;
1995  record->header.majorinfoversion = JVMTI_CMLR_MAJOR_VERSION_1;
1996  record->header.minorinfoversion = JVMTI_CMLR_MINOR_VERSION_0;
1997  record->numpcs = 0;
1998  for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
1999   if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2000   record->numpcs++;
2001  }
2002  record->pcinfo = (PCStackInfo*)(NEW_RESOURCE_ARRAY(PCStackInfo, record->numpcs));
2003  int scope = 0;
2004  for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
2005    if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2006    void* pc_address = (void*)p->real_pc(nm);
2007    assert(pc_address != NULL, "pc_address must be non-null");
2008    record->pcinfo[scope].pc = pc_address;
2009    numstackframes=0;
2010    for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2011      numstackframes++;
2012    }
2013    assert(numstackframes != 0, "numstackframes must be nonzero.");
2014    record->pcinfo[scope].methods = (jmethodID *)NEW_RESOURCE_ARRAY(jmethodID, numstackframes);
2015    record->pcinfo[scope].bcis = (jint *)NEW_RESOURCE_ARRAY(jint, numstackframes);
2016    record->pcinfo[scope].numstackframes = numstackframes;
2017    int stackframe = 0;
2018    for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2019      // sd->method() can be NULL for stubs but not for nmethods. To be completely robust, include an assert that we should never see a null sd->method()
2020      assert(sd->method() != NULL, "sd->method() cannot be null.");
2021      record->pcinfo[scope].methods[stackframe] = sd->method()->jmethod_id();
2022      record->pcinfo[scope].bcis[stackframe] = sd->bci();
2023      stackframe++;
2024    }
2025    scope++;
2026  }
2027  return record;
2028}
2029
2030void JvmtiExport::post_compiled_method_load(nmethod *nm) {
2031  if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
2032    return;
2033  }
2034  JavaThread* thread = JavaThread::current();
2035
2036  EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2037                 ("[%s] method compile load event triggered",
2038                 JvmtiTrace::safe_get_thread_name(thread)));
2039
2040  JvmtiEnvIterator it;
2041  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2042    if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
2043      if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
2044        continue;
2045      }
2046      EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2047                ("[%s] class compile method load event sent %s.%s  ",
2048                JvmtiTrace::safe_get_thread_name(thread),
2049                (nm->method() == NULL) ? "NULL" : nm->method()->klass_name()->as_C_string(),
2050                (nm->method() == NULL) ? "NULL" : nm->method()->name()->as_C_string()));
2051      ResourceMark rm(thread);
2052      HandleMark hm(thread);
2053
2054      // Add inlining information
2055      jvmtiCompiledMethodLoadInlineRecord* inlinerecord = create_inline_record(nm);
2056      // Pass inlining information through the void pointer
2057      JvmtiCompiledMethodLoadEventMark jem(thread, nm, inlinerecord);
2058      JvmtiJavaThreadEventTransition jet(thread);
2059      jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
2060      if (callback != NULL) {
2061        (*callback)(env->jvmti_external(), jem.jni_methodID(),
2062                    jem.code_size(), jem.code_data(), jem.map_length(),
2063                    jem.map(), jem.compile_info());
2064      }
2065    }
2066  }
2067}
2068
2069
2070// post a COMPILED_METHOD_LOAD event for a given environment
2071void JvmtiExport::post_compiled_method_load(JvmtiEnv* env, const jmethodID method, const jint length,
2072                                            const void *code_begin, const jint map_length,
2073                                            const jvmtiAddrLocationMap* map)
2074{
2075  if (env->phase() <= JVMTI_PHASE_PRIMORDIAL) {
2076    return;
2077  }
2078  JavaThread* thread = JavaThread::current();
2079  EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2080                 ("[%s] method compile load event triggered (by GenerateEvents)",
2081                 JvmtiTrace::safe_get_thread_name(thread)));
2082  if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
2083
2084    EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2085              ("[%s] class compile method load event sent (by GenerateEvents), jmethodID=" PTR_FORMAT,
2086               JvmtiTrace::safe_get_thread_name(thread), p2i(method)));
2087
2088    JvmtiEventMark jem(thread);
2089    JvmtiJavaThreadEventTransition jet(thread);
2090    jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
2091    if (callback != NULL) {
2092      (*callback)(env->jvmti_external(), method,
2093                  length, code_begin, map_length,
2094                  map, NULL);
2095    }
2096  }
2097}
2098
2099void JvmtiExport::post_dynamic_code_generated_internal(const char *name, const void *code_begin, const void *code_end) {
2100  assert(name != NULL && name[0] != '\0', "sanity check");
2101
2102  JavaThread* thread = JavaThread::current();
2103  // In theory everyone coming thru here is in_vm but we need to be certain
2104  // because a callee will do a vm->native transition
2105  ThreadInVMfromUnknown __tiv;
2106
2107  EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2108                 ("[%s] method dynamic code generated event triggered",
2109                 JvmtiTrace::safe_get_thread_name(thread)));
2110  JvmtiEnvIterator it;
2111  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2112    if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2113      EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2114                ("[%s] dynamic code generated event sent for %s",
2115                JvmtiTrace::safe_get_thread_name(thread), name));
2116      JvmtiEventMark jem(thread);
2117      JvmtiJavaThreadEventTransition jet(thread);
2118      jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2119      jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2120      if (callback != NULL) {
2121        (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2122      }
2123    }
2124  }
2125}
2126
2127void JvmtiExport::post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) {
2128  jvmtiPhase phase = JvmtiEnv::get_phase();
2129  if (phase == JVMTI_PHASE_PRIMORDIAL || phase == JVMTI_PHASE_START) {
2130    post_dynamic_code_generated_internal(name, code_begin, code_end);
2131  } else {
2132    // It may not be safe to post the event from this thread.  Defer all
2133    // postings to the service thread so that it can perform them in a safe
2134    // context and in-order.
2135    MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
2136    JvmtiDeferredEvent event = JvmtiDeferredEvent::dynamic_code_generated_event(
2137        name, code_begin, code_end);
2138    JvmtiDeferredEventQueue::enqueue(event);
2139  }
2140}
2141
2142
2143// post a DYNAMIC_CODE_GENERATED event for a given environment
2144// used by GenerateEvents
2145void JvmtiExport::post_dynamic_code_generated(JvmtiEnv* env, const char *name,
2146                                              const void *code_begin, const void *code_end)
2147{
2148  JavaThread* thread = JavaThread::current();
2149  EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2150                 ("[%s] dynamic code generated event triggered (by GenerateEvents)",
2151                  JvmtiTrace::safe_get_thread_name(thread)));
2152  if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2153    EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2154              ("[%s] dynamic code generated event sent for %s",
2155               JvmtiTrace::safe_get_thread_name(thread), name));
2156    JvmtiEventMark jem(thread);
2157    JvmtiJavaThreadEventTransition jet(thread);
2158    jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2159    jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2160    if (callback != NULL) {
2161      (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2162    }
2163  }
2164}
2165
2166// post a DynamicCodeGenerated event while holding locks in the VM.
2167void JvmtiExport::post_dynamic_code_generated_while_holding_locks(const char* name,
2168                                                                  address code_begin, address code_end)
2169{
2170  // register the stub with the current dynamic code event collector
2171  JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
2172  // state can only be NULL if the current thread is exiting which
2173  // should not happen since we're trying to post an event
2174  guarantee(state != NULL, "attempt to register stub via an exiting thread");
2175  JvmtiDynamicCodeEventCollector* collector = state->get_dynamic_code_event_collector();
2176  guarantee(collector != NULL, "attempt to register stub without event collector");
2177  collector->register_stub(name, code_begin, code_end);
2178}
2179
2180// Collect all the vm internally allocated objects which are visible to java world
2181void JvmtiExport::record_vm_internal_object_allocation(oop obj) {
2182  Thread* thread = Thread::current_or_null();
2183  if (thread != NULL && thread->is_Java_thread())  {
2184    // Can not take safepoint here.
2185    NoSafepointVerifier no_sfpt;
2186    // Can not take safepoint here so can not use state_for to get
2187    // jvmti thread state.
2188    JvmtiThreadState *state = ((JavaThread*)thread)->jvmti_thread_state();
2189    if (state != NULL ) {
2190      // state is non NULL when VMObjectAllocEventCollector is enabled.
2191      JvmtiVMObjectAllocEventCollector *collector;
2192      collector = state->get_vm_object_alloc_event_collector();
2193      if (collector != NULL && collector->is_enabled()) {
2194        // Don't record classes as these will be notified via the ClassLoad
2195        // event.
2196        if (obj->klass() != SystemDictionary::Class_klass()) {
2197          collector->record_allocation(obj);
2198        }
2199      }
2200    }
2201  }
2202}
2203
2204void JvmtiExport::post_garbage_collection_finish() {
2205  Thread *thread = Thread::current(); // this event is posted from VM-Thread.
2206  EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2207                 ("[%s] garbage collection finish event triggered",
2208                  JvmtiTrace::safe_get_thread_name(thread)));
2209  JvmtiEnvIterator it;
2210  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2211    if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH)) {
2212      EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2213                ("[%s] garbage collection finish event sent",
2214                 JvmtiTrace::safe_get_thread_name(thread)));
2215      JvmtiThreadEventTransition jet(thread);
2216      // JNIEnv is NULL here because this event is posted from VM Thread
2217      jvmtiEventGarbageCollectionFinish callback = env->callbacks()->GarbageCollectionFinish;
2218      if (callback != NULL) {
2219        (*callback)(env->jvmti_external());
2220      }
2221    }
2222  }
2223}
2224
2225void JvmtiExport::post_garbage_collection_start() {
2226  Thread* thread = Thread::current(); // this event is posted from vm-thread.
2227  EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2228                 ("[%s] garbage collection start event triggered",
2229                  JvmtiTrace::safe_get_thread_name(thread)));
2230  JvmtiEnvIterator it;
2231  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2232    if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_START)) {
2233      EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2234                ("[%s] garbage collection start event sent",
2235                 JvmtiTrace::safe_get_thread_name(thread)));
2236      JvmtiThreadEventTransition jet(thread);
2237      // JNIEnv is NULL here because this event is posted from VM Thread
2238      jvmtiEventGarbageCollectionStart callback = env->callbacks()->GarbageCollectionStart;
2239      if (callback != NULL) {
2240        (*callback)(env->jvmti_external());
2241      }
2242    }
2243  }
2244}
2245
2246void JvmtiExport::post_data_dump() {
2247  Thread *thread = Thread::current();
2248  EVT_TRIG_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2249                 ("[%s] data dump request event triggered",
2250                  JvmtiTrace::safe_get_thread_name(thread)));
2251  JvmtiEnvIterator it;
2252  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2253    if (env->is_enabled(JVMTI_EVENT_DATA_DUMP_REQUEST)) {
2254      EVT_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2255                ("[%s] data dump request event sent",
2256                 JvmtiTrace::safe_get_thread_name(thread)));
2257     JvmtiThreadEventTransition jet(thread);
2258     // JNIEnv is NULL here because this event is posted from VM Thread
2259     jvmtiEventDataDumpRequest callback = env->callbacks()->DataDumpRequest;
2260     if (callback != NULL) {
2261       (*callback)(env->jvmti_external());
2262     }
2263    }
2264  }
2265}
2266
2267void JvmtiExport::post_monitor_contended_enter(JavaThread *thread, ObjectMonitor *obj_mntr) {
2268  oop object = (oop)obj_mntr->object();
2269  if (!ServiceUtil::visible_oop(object)) {
2270    // Ignore monitor contended enter for vm internal object.
2271    return;
2272  }
2273  JvmtiThreadState *state = thread->jvmti_thread_state();
2274  if (state == NULL) {
2275    return;
2276  }
2277
2278  HandleMark hm(thread);
2279  Handle h(thread, object);
2280
2281  EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2282                     ("[%s] montior contended enter event triggered",
2283                      JvmtiTrace::safe_get_thread_name(thread)));
2284
2285  JvmtiEnvThreadStateIterator it(state);
2286  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2287    if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTER)) {
2288      EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2289                   ("[%s] monitor contended enter event sent",
2290                    JvmtiTrace::safe_get_thread_name(thread)));
2291      JvmtiMonitorEventMark  jem(thread, h());
2292      JvmtiEnv *env = ets->get_env();
2293      JvmtiThreadEventTransition jet(thread);
2294      jvmtiEventMonitorContendedEnter callback = env->callbacks()->MonitorContendedEnter;
2295      if (callback != NULL) {
2296        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2297      }
2298    }
2299  }
2300}
2301
2302void JvmtiExport::post_monitor_contended_entered(JavaThread *thread, ObjectMonitor *obj_mntr) {
2303  oop object = (oop)obj_mntr->object();
2304  if (!ServiceUtil::visible_oop(object)) {
2305    // Ignore monitor contended entered for vm internal object.
2306    return;
2307  }
2308  JvmtiThreadState *state = thread->jvmti_thread_state();
2309  if (state == NULL) {
2310    return;
2311  }
2312
2313  HandleMark hm(thread);
2314  Handle h(thread, object);
2315
2316  EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2317                     ("[%s] montior contended entered event triggered",
2318                      JvmtiTrace::safe_get_thread_name(thread)));
2319
2320  JvmtiEnvThreadStateIterator it(state);
2321  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2322    if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED)) {
2323      EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2324                   ("[%s] monitor contended enter event sent",
2325                    JvmtiTrace::safe_get_thread_name(thread)));
2326      JvmtiMonitorEventMark  jem(thread, h());
2327      JvmtiEnv *env = ets->get_env();
2328      JvmtiThreadEventTransition jet(thread);
2329      jvmtiEventMonitorContendedEntered callback = env->callbacks()->MonitorContendedEntered;
2330      if (callback != NULL) {
2331        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2332      }
2333    }
2334  }
2335}
2336
2337void JvmtiExport::post_monitor_wait(JavaThread *thread, oop object,
2338                                          jlong timeout) {
2339  JvmtiThreadState *state = thread->jvmti_thread_state();
2340  if (state == NULL) {
2341    return;
2342  }
2343
2344  HandleMark hm(thread);
2345  Handle h(thread, object);
2346
2347  EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2348                     ("[%s] montior wait event triggered",
2349                      JvmtiTrace::safe_get_thread_name(thread)));
2350
2351  JvmtiEnvThreadStateIterator it(state);
2352  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2353    if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAIT)) {
2354      EVT_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2355                   ("[%s] monitor wait event sent",
2356                    JvmtiTrace::safe_get_thread_name(thread)));
2357      JvmtiMonitorEventMark  jem(thread, h());
2358      JvmtiEnv *env = ets->get_env();
2359      JvmtiThreadEventTransition jet(thread);
2360      jvmtiEventMonitorWait callback = env->callbacks()->MonitorWait;
2361      if (callback != NULL) {
2362        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2363                    jem.jni_object(), timeout);
2364      }
2365    }
2366  }
2367}
2368
2369void JvmtiExport::post_monitor_waited(JavaThread *thread, ObjectMonitor *obj_mntr, jboolean timed_out) {
2370  oop object = (oop)obj_mntr->object();
2371  if (!ServiceUtil::visible_oop(object)) {
2372    // Ignore monitor waited for vm internal object.
2373    return;
2374  }
2375  JvmtiThreadState *state = thread->jvmti_thread_state();
2376  if (state == NULL) {
2377    return;
2378  }
2379
2380  HandleMark hm(thread);
2381  Handle h(thread, object);
2382
2383  EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2384                     ("[%s] montior waited event triggered",
2385                      JvmtiTrace::safe_get_thread_name(thread)));
2386
2387  JvmtiEnvThreadStateIterator it(state);
2388  for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2389    if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAITED)) {
2390      EVT_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2391                   ("[%s] monitor waited event sent",
2392                    JvmtiTrace::safe_get_thread_name(thread)));
2393      JvmtiMonitorEventMark  jem(thread, h());
2394      JvmtiEnv *env = ets->get_env();
2395      JvmtiThreadEventTransition jet(thread);
2396      jvmtiEventMonitorWaited callback = env->callbacks()->MonitorWaited;
2397      if (callback != NULL) {
2398        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2399                    jem.jni_object(), timed_out);
2400      }
2401    }
2402  }
2403}
2404
2405
2406void JvmtiExport::post_vm_object_alloc(JavaThread *thread,  oop object) {
2407  EVT_TRIG_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Trg vm object alloc triggered",
2408                      JvmtiTrace::safe_get_thread_name(thread)));
2409  if (object == NULL) {
2410    return;
2411  }
2412  HandleMark hm(thread);
2413  Handle h(thread, object);
2414  JvmtiEnvIterator it;
2415  for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2416    if (env->is_enabled(JVMTI_EVENT_VM_OBJECT_ALLOC)) {
2417      EVT_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Evt vmobject alloc sent %s",
2418                                         JvmtiTrace::safe_get_thread_name(thread),
2419                                         object==NULL? "NULL" : object->klass()->external_name()));
2420
2421      JvmtiVMObjectAllocEventMark jem(thread, h());
2422      JvmtiJavaThreadEventTransition jet(thread);
2423      jvmtiEventVMObjectAlloc callback = env->callbacks()->VMObjectAlloc;
2424      if (callback != NULL) {
2425        (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2426                    jem.jni_jobject(), jem.jni_class(), jem.size());
2427      }
2428    }
2429  }
2430}
2431
2432////////////////////////////////////////////////////////////////////////////////////////////////
2433
2434void JvmtiExport::cleanup_thread(JavaThread* thread) {
2435  assert(JavaThread::current() == thread, "thread is not current");
2436  MutexLocker mu(JvmtiThreadState_lock);
2437
2438  if (thread->jvmti_thread_state() != NULL) {
2439    // This has to happen after the thread state is removed, which is
2440    // why it is not in post_thread_end_event like its complement
2441    // Maybe both these functions should be rolled into the posts?
2442    JvmtiEventController::thread_ended(thread);
2443  }
2444}
2445
2446void JvmtiExport::clear_detected_exception(JavaThread* thread) {
2447  assert(JavaThread::current() == thread, "thread is not current");
2448
2449  JvmtiThreadState* state = thread->jvmti_thread_state();
2450  if (state != NULL) {
2451    state->clear_exception_detected();
2452  }
2453}
2454
2455void JvmtiExport::oops_do(OopClosure* f) {
2456  JvmtiCurrentBreakpoints::oops_do(f);
2457  JvmtiVMObjectAllocEventCollector::oops_do_for_all_threads(f);
2458}
2459
2460void JvmtiExport::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f) {
2461  JvmtiTagMap::weak_oops_do(is_alive, f);
2462}
2463
2464void JvmtiExport::gc_epilogue() {
2465  JvmtiCurrentBreakpoints::gc_epilogue();
2466}
2467
2468// Onload raw monitor transition.
2469void JvmtiExport::transition_pending_onload_raw_monitors() {
2470  JvmtiPendingMonitors::transition_raw_monitors();
2471}
2472
2473////////////////////////////////////////////////////////////////////////////////////////////////
2474#if INCLUDE_SERVICES
2475// Attach is disabled if SERVICES is not included
2476
2477// type for the Agent_OnAttach entry point
2478extern "C" {
2479  typedef jint (JNICALL *OnAttachEntry_t)(JavaVM*, char *, void *);
2480}
2481
2482jint JvmtiExport::load_agent_library(AttachOperation* op, outputStream* st) {
2483  // get agent name and options
2484  const char* agent = op->arg(0);
2485  const char* absParam = op->arg(1);
2486  const char* options = op->arg(2);
2487
2488  return load_agent_library(agent, absParam, options, st);
2489}
2490
2491jint JvmtiExport::load_agent_library(const char *agent, const char *absParam,
2492                                     const char *options, outputStream* st) {
2493  char ebuf[1024];
2494  char buffer[JVM_MAXPATHLEN];
2495  void* library = NULL;
2496  jint result = JNI_ERR;
2497  const char *on_attach_symbols[] = AGENT_ONATTACH_SYMBOLS;
2498  size_t num_symbol_entries = ARRAY_SIZE(on_attach_symbols);
2499
2500  // The abs paramter should be "true" or "false"
2501  bool is_absolute_path = (absParam != NULL) && (strcmp(absParam,"true")==0);
2502
2503  // Initially marked as invalid. It will be set to valid if we can find the agent
2504  AgentLibrary *agent_lib = new AgentLibrary(agent, options, is_absolute_path, NULL);
2505
2506  // Check for statically linked in agent. If not found then if the path is
2507  // absolute we attempt to load the library. Otherwise we try to load it
2508  // from the standard dll directory.
2509
2510  if (!os::find_builtin_agent(agent_lib, on_attach_symbols, num_symbol_entries)) {
2511    if (is_absolute_path) {
2512      library = os::dll_load(agent, ebuf, sizeof ebuf);
2513    } else {
2514      // Try to load the agent from the standard dll directory
2515      if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
2516                             agent)) {
2517        library = os::dll_load(buffer, ebuf, sizeof ebuf);
2518      }
2519      if (library == NULL) {
2520        // not found - try local path
2521        char ns[1] = {0};
2522        if (os::dll_build_name(buffer, sizeof(buffer), ns, agent)) {
2523          library = os::dll_load(buffer, ebuf, sizeof ebuf);
2524        }
2525      }
2526    }
2527    if (library != NULL) {
2528      agent_lib->set_os_lib(library);
2529      agent_lib->set_valid();
2530    }
2531  }
2532  // If the library was loaded then we attempt to invoke the Agent_OnAttach
2533  // function
2534  if (agent_lib->valid()) {
2535    // Lookup the Agent_OnAttach function
2536    OnAttachEntry_t on_attach_entry = NULL;
2537    on_attach_entry = CAST_TO_FN_PTR(OnAttachEntry_t,
2538       os::find_agent_function(agent_lib, false, on_attach_symbols, num_symbol_entries));
2539    if (on_attach_entry == NULL) {
2540      // Agent_OnAttach missing - unload library
2541      if (!agent_lib->is_static_lib()) {
2542        os::dll_unload(library);
2543      }
2544      delete agent_lib;
2545    } else {
2546      // Invoke the Agent_OnAttach function
2547      JavaThread* THREAD = JavaThread::current();
2548      {
2549        extern struct JavaVM_ main_vm;
2550        JvmtiThreadEventMark jem(THREAD);
2551        JvmtiJavaThreadEventTransition jet(THREAD);
2552
2553        result = (*on_attach_entry)(&main_vm, (char*)options, NULL);
2554      }
2555
2556      // Agent_OnAttach may have used JNI
2557      if (HAS_PENDING_EXCEPTION) {
2558        CLEAR_PENDING_EXCEPTION;
2559      }
2560
2561      // If OnAttach returns JNI_OK then we add it to the list of
2562      // agent libraries so that we can call Agent_OnUnload later.
2563      if (result == JNI_OK) {
2564        Arguments::add_loaded_agent(agent_lib);
2565      } else {
2566        delete agent_lib;
2567      }
2568
2569      // Agent_OnAttach executed so completion status is JNI_OK
2570      st->print_cr("%d", result);
2571      result = JNI_OK;
2572    }
2573  }
2574  return result;
2575}
2576
2577#endif // INCLUDE_SERVICES
2578////////////////////////////////////////////////////////////////////////////////////////////////
2579
2580// Setup current current thread for event collection.
2581void JvmtiEventCollector::setup_jvmti_thread_state() {
2582  // set this event collector to be the current one.
2583  JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
2584  // state can only be NULL if the current thread is exiting which
2585  // should not happen since we're trying to configure for event collection
2586  guarantee(state != NULL, "exiting thread called setup_jvmti_thread_state");
2587  if (is_vm_object_alloc_event()) {
2588    _prev = state->get_vm_object_alloc_event_collector();
2589    state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)this);
2590  } else if (is_dynamic_code_event()) {
2591    _prev = state->get_dynamic_code_event_collector();
2592    state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)this);
2593  }
2594}
2595
2596// Unset current event collection in this thread and reset it with previous
2597// collector.
2598void JvmtiEventCollector::unset_jvmti_thread_state() {
2599  JvmtiThreadState* state = JavaThread::current()->jvmti_thread_state();
2600  if (state != NULL) {
2601    // restore the previous event collector (if any)
2602    if (is_vm_object_alloc_event()) {
2603      if (state->get_vm_object_alloc_event_collector() == this) {
2604        state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)_prev);
2605      } else {
2606        // this thread's jvmti state was created during the scope of
2607        // the event collector.
2608      }
2609    } else {
2610      if (is_dynamic_code_event()) {
2611        if (state->get_dynamic_code_event_collector() == this) {
2612          state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)_prev);
2613        } else {
2614          // this thread's jvmti state was created during the scope of
2615          // the event collector.
2616        }
2617      }
2618    }
2619  }
2620}
2621
2622// create the dynamic code event collector
2623JvmtiDynamicCodeEventCollector::JvmtiDynamicCodeEventCollector() : _code_blobs(NULL) {
2624  if (JvmtiExport::should_post_dynamic_code_generated()) {
2625    setup_jvmti_thread_state();
2626  }
2627}
2628
2629// iterate over any code blob descriptors collected and post a
2630// DYNAMIC_CODE_GENERATED event to the profiler.
2631JvmtiDynamicCodeEventCollector::~JvmtiDynamicCodeEventCollector() {
2632  assert(!JavaThread::current()->owns_locks(), "all locks must be released to post deferred events");
2633 // iterate over any code blob descriptors that we collected
2634 if (_code_blobs != NULL) {
2635   for (int i=0; i<_code_blobs->length(); i++) {
2636     JvmtiCodeBlobDesc* blob = _code_blobs->at(i);
2637     JvmtiExport::post_dynamic_code_generated(blob->name(), blob->code_begin(), blob->code_end());
2638     FreeHeap(blob);
2639   }
2640   delete _code_blobs;
2641 }
2642 unset_jvmti_thread_state();
2643}
2644
2645// register a stub
2646void JvmtiDynamicCodeEventCollector::register_stub(const char* name, address start, address end) {
2647 if (_code_blobs == NULL) {
2648   _code_blobs = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JvmtiCodeBlobDesc*>(1,true);
2649 }
2650 _code_blobs->append(new JvmtiCodeBlobDesc(name, start, end));
2651}
2652
2653// Setup current thread to record vm allocated objects.
2654JvmtiVMObjectAllocEventCollector::JvmtiVMObjectAllocEventCollector() : _allocated(NULL) {
2655  if (JvmtiExport::should_post_vm_object_alloc()) {
2656    _enable = true;
2657    setup_jvmti_thread_state();
2658  } else {
2659    _enable = false;
2660  }
2661}
2662
2663// Post vm_object_alloc event for vm allocated objects visible to java
2664// world.
2665JvmtiVMObjectAllocEventCollector::~JvmtiVMObjectAllocEventCollector() {
2666  if (_allocated != NULL) {
2667    set_enabled(false);
2668    for (int i = 0; i < _allocated->length(); i++) {
2669      oop obj = _allocated->at(i);
2670      if (ServiceUtil::visible_oop(obj)) {
2671        JvmtiExport::post_vm_object_alloc(JavaThread::current(), obj);
2672      }
2673    }
2674    delete _allocated;
2675  }
2676  unset_jvmti_thread_state();
2677}
2678
2679void JvmtiVMObjectAllocEventCollector::record_allocation(oop obj) {
2680  assert(is_enabled(), "VM object alloc event collector is not enabled");
2681  if (_allocated == NULL) {
2682    _allocated = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(1, true);
2683  }
2684  _allocated->push(obj);
2685}
2686
2687// GC support.
2688void JvmtiVMObjectAllocEventCollector::oops_do(OopClosure* f) {
2689  if (_allocated != NULL) {
2690    for(int i=_allocated->length() - 1; i >= 0; i--) {
2691      if (_allocated->at(i) != NULL) {
2692        f->do_oop(_allocated->adr_at(i));
2693      }
2694    }
2695  }
2696}
2697
2698void JvmtiVMObjectAllocEventCollector::oops_do_for_all_threads(OopClosure* f) {
2699  // no-op if jvmti not enabled
2700  if (!JvmtiEnv::environments_might_exist()) {
2701    return;
2702  }
2703
2704  // Runs at safepoint. So no need to acquire Threads_lock.
2705  for (JavaThread *jthr = Threads::first(); jthr != NULL; jthr = jthr->next()) {
2706    JvmtiThreadState *state = jthr->jvmti_thread_state();
2707    if (state != NULL) {
2708      JvmtiVMObjectAllocEventCollector *collector;
2709      collector = state->get_vm_object_alloc_event_collector();
2710      while (collector != NULL) {
2711        collector->oops_do(f);
2712        collector = (JvmtiVMObjectAllocEventCollector *)collector->get_prev();
2713      }
2714    }
2715  }
2716}
2717
2718
2719// Disable collection of VMObjectAlloc events
2720NoJvmtiVMObjectAllocMark::NoJvmtiVMObjectAllocMark() : _collector(NULL) {
2721  // a no-op if VMObjectAlloc event is not enabled
2722  if (!JvmtiExport::should_post_vm_object_alloc()) {
2723    return;
2724  }
2725  Thread* thread = Thread::current_or_null();
2726  if (thread != NULL && thread->is_Java_thread())  {
2727    JavaThread* current_thread = (JavaThread*)thread;
2728    JvmtiThreadState *state = current_thread->jvmti_thread_state();
2729    if (state != NULL) {
2730      JvmtiVMObjectAllocEventCollector *collector;
2731      collector = state->get_vm_object_alloc_event_collector();
2732      if (collector != NULL && collector->is_enabled()) {
2733        _collector = collector;
2734        _collector->set_enabled(false);
2735      }
2736    }
2737  }
2738}
2739
2740// Re-Enable collection of VMObjectAlloc events (if previously enabled)
2741NoJvmtiVMObjectAllocMark::~NoJvmtiVMObjectAllocMark() {
2742  if (was_enabled()) {
2743    _collector->set_enabled(true);
2744  }
2745};
2746
2747JvmtiGCMarker::JvmtiGCMarker() {
2748  // if there aren't any JVMTI environments then nothing to do
2749  if (!JvmtiEnv::environments_might_exist()) {
2750    return;
2751  }
2752
2753  if (JvmtiExport::should_post_garbage_collection_start()) {
2754    JvmtiExport::post_garbage_collection_start();
2755  }
2756
2757  if (SafepointSynchronize::is_at_safepoint()) {
2758    // Do clean up tasks that need to be done at a safepoint
2759    JvmtiEnvBase::check_for_periodic_clean_up();
2760  }
2761}
2762
2763JvmtiGCMarker::~JvmtiGCMarker() {
2764  // if there aren't any JVMTI environments then nothing to do
2765  if (!JvmtiEnv::environments_might_exist()) {
2766    return;
2767  }
2768
2769  // JVMTI notify gc finish
2770  if (JvmtiExport::should_post_garbage_collection_finish()) {
2771    JvmtiExport::post_garbage_collection_finish();
2772  }
2773}
2774