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