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