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