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