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